docx4js
Version:
javascript docx parser
1,358 lines (1,186 loc) • 3.28 MB
JavaScript
require=(function(){function r(e,n,t){function o(i,f){if(!n[i]){if(!e[i]){var c="function"==typeof require&&require;if(!f&&c)return c(i,!0);if(u)return u(i,!0);var a=new Error("Cannot find module '"+i+"'");throw a.code="MODULE_NOT_FOUND",a}var p=n[i]={exports:{}};e[i][0].call(p.exports,function(r){var n=e[i][1][r];return o(n||r)},p,p.exports,r,e,n,t)}return n[i].exports}for(var u="function"==typeof require&&require,i=0;i<t.length;i++)o(t[i]);return o}return r})()({1:[function(require,module,exports){
"use strict";
var _cheerio = require("cheerio");
var _cheerio2 = _interopRequireDefault(_cheerio);
function _interopRequireDefault(obj) { return obj && obj.__esModule ? obj : { default: obj }; }
_cheerio2.default.prototype.props = function () {
var opt = arguments.length > 0 && arguments[0] !== undefined ? arguments[0] : {};
if (this.length == 0) return {};
var $ = this.constructor;
var names = opt.names,
_opt$nameFn = opt.nameFn,
nameFn = _opt$nameFn === undefined ? function (a) {
return names && names[a] || a;
} : _opt$nameFn,
_opt$__filter = opt.__filter,
__filter = _opt$__filter === undefined ? '*' : _opt$__filter,
_opt$tidy = opt.tidy,
tidy = _opt$tidy === undefined ? function (a) {
return a;
} : _opt$tidy;
var propsAttribs = function propsAttribs(attribs) {
return Object.keys(attribs).filter(function (k) {
return !k.startsWith("xmlns");
}).reduce(function (props, attribKey) {
var value = attribs[attribKey];
attribKey = attribKey.split(":").pop();
var parsedValue = opt[attribKey] ? opt[attribKey](value) : value;
if (parsedValue != undefined) {
props[nameFn(attribKey)] = parsedValue;
}
return props;
}, {});
};
var propsChild = function propsChild(node, parentProps, index) {
var tagName = node.name.split(":").pop();
var parsed = opt[tagName] ? opt[tagName](node) : toJS(node);
if (parsed != undefined) {
var key = Array.isArray(parentProps) ? index : nameFn(tagName, node, parentProps);
parentProps[key == "[]" ? tagName : key] = opt["tidy_" + tagName] ? opt["tidy_" + tagName](parsed) : parsed;
}
return parentProps;
};
var toJS = function toJS(node, p) {
var children = node.children,
attribs = node.attribs,
_node$name = node.name,
name = _node$name === undefined ? "" : _node$name,
_node$tagName = node.tagName,
tagName = _node$tagName === undefined ? name.split(":").pop() : _node$tagName;
return children.filter(function (a) {
return a.name && $(a).is(__filter);
}).reduce(function (parentProps, child, i) {
return propsChild(child, parentProps, i);
}, nameFn(tagName, node) === "[]" ? [] : propsAttribs(attribs));
};
var props = toJS(this[0]);
return tidy ? tidy(props) : props;
};
_cheerio2.default.prototype.forwardUntil = function (selector, filter) {
var Empty = this.constructor.root().not(function (a) {
return true;
});
var $ = function $(n) {
return Empty.not(function (a) {
return true;
}).add(n);
};
var until = Empty,
filtered = Empty;
var next = this.get(0);
var parentNext = function parentNext(node) {
return node && node.parent && (node.parent.next || parentNext(node.parent));
};
var getNext = function getNext(node) {
return node && (node.children && node.children[0] || node.next || parentNext(node));
};
while (next && (next = getNext(next))) {
var $n = $(next);
if ($n.is(selector)) {
until = until.add(next);
break;
} else if (filter && $n.is(filter)) {
filtered = filtered.add(next);
}
}
return filter ? filtered : until;
};
_cheerio2.default.prototype.backwardUntil = function (selector, filter) {
var Empty = this.constructor.root().not(function (a) {
return true;
});
var $ = function $(n) {
return Empty.not(function (a) {
return true;
}).add(n);
};
var until = Empty,
filtered = Empty;
var prev = this.get(0);
var parentPrev = function parentPrev(node) {
return node && node.parent && (node.parent.prev || parentPrev(node.parent));
};
var getPrev = function getPrev(node) {
return node && (node.children && node.children[node.children.length - 1] || node.prev || parentPrev(node));
};
while (prev && (prev = getPrev(prev))) {
var $n = $(prev);
if ($n.is(selector)) {
until = until.add(prev);
break;
} else if (filter && $n.is(filter)) {
filtered = filtered.add(next);
}
}
return filter ? filtered : until;
};
},{"cheerio":18}],2:[function(require,module,exports){
(function (__dirname){(function (){
"use strict";
Object.defineProperty(exports, "__esModule", {
value: true
});
var _get = function get(object, property, receiver) { if (object === null) object = Function.prototype; var desc = Object.getOwnPropertyDescriptor(object, property); if (desc === undefined) { var parent = Object.getPrototypeOf(object); if (parent === null) { return undefined; } else { return get(parent, property, receiver); } } else if ("value" in desc) { return desc.value; } else { var getter = desc.get; if (getter === undefined) { return undefined; } return getter.call(receiver); } };
var _extends = Object.assign || function (target) { for (var i = 1; i < arguments.length; i++) { var source = arguments[i]; for (var key in source) { if (Object.prototype.hasOwnProperty.call(source, key)) { target[key] = source[key]; } } } return target; };
var _slicedToArray = function () { function sliceIterator(arr, i) { var _arr = []; var _n = true; var _d = false; var _e = undefined; try { for (var _i = arr[Symbol.iterator](), _s; !(_n = (_s = _i.next()).done); _n = true) { _arr.push(_s.value); if (i && _arr.length === i) break; } } catch (err) { _d = true; _e = err; } finally { try { if (!_n && _i["return"]) _i["return"](); } finally { if (_d) throw _e; } } return _arr; } return function (arr, i) { if (Array.isArray(arr)) { return arr; } else if (Symbol.iterator in Object(arr)) { return sliceIterator(arr, i); } else { throw new TypeError("Invalid attempt to destructure non-iterable instance"); } }; }();
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; }; }();
var _jszip = require("jszip");
var _jszip2 = _interopRequireDefault(_jszip);
var _cheerio = require("cheerio");
var _cheerio2 = _interopRequireDefault(_cheerio);
require("./cheerio-fn");
var _htmlparser = require("htmlparser2");
function _interopRequireDefault(obj) { return obj && obj.__esModule ? obj : { default: obj }; }
function _possibleConstructorReturn(self, call) { if (!self) { throw new ReferenceError("this hasn't been initialised - super() hasn't been called"); } return call && (typeof call === "object" || typeof call === "function") ? call : self; }
function _inherits(subClass, superClass) { if (typeof superClass !== "function" && superClass !== null) { throw new TypeError("Super expression must either be null or a function, not " + typeof superClass); } subClass.prototype = Object.create(superClass && superClass.prototype, { constructor: { value: subClass, enumerable: false, writable: true, configurable: true } }); if (superClass) Object.setPrototypeOf ? Object.setPrototypeOf(subClass, superClass) : subClass.__proto__ = superClass; }
function _classCallCheck(instance, Constructor) { if (!(instance instanceof Constructor)) { throw new TypeError("Cannot call a class as a function"); } }
var normalize = function normalize(path) {
return path.split("/").filter(function (a) {
return a != ".";
}).reduceRight(function (n, a) {
if (a == "..") {
n.r++;
} else if (n.r) {
n.r--;
} else {
n.trimed.unshift(a);
}
return n;
}, { trimed: [], r: 0 }).trimed.join("/");
};
/**
* document parser
*
* @example
* Document.load(file)
* .then(doc=>doc.parse())
*/
var ZipDocument = function () {
function ZipDocument(parts, raw, props) {
_classCallCheck(this, ZipDocument);
this.parts = parts;
this.raw = raw;
this.props = props;
this._shouldReleased = new Map();
}
_createClass(ZipDocument, [{
key: "normalizePath",
value: function normalizePath() {
return normalize.apply(undefined, arguments);
}
}, {
key: "getPart",
value: function getPart(name) {
name = normalize(name);
return this.parts[name];
}
}, {
key: "getDataPart",
value: function getDataPart(name) {
name = normalize(name);
var part = this.parts[name];
var crc32 = part._data.crc32;
var data = part.asUint8Array(); //unsafe call, part._data is changed
data.crc32 = part._data.crc32 = crc32; //so keep crc32 on part._data for future
return data;
}
}, {
key: "getDataPartAsUrl",
value: function getDataPartAsUrl(name) {
var type = arguments.length > 1 && arguments[1] !== undefined ? arguments[1] : "*/*";
name = normalize(name);
var part = this.parts[name];
var crc32 = part._data.crc32;
if (!this._shouldReleased.has(crc32)) {
this._shouldReleased.set(crc32, URL.createObjectURL(new Blob([this.getDataPart(name)], { type: type })));
}
return this._shouldReleased.get(crc32);
}
}, {
key: "getPartCrc32",
value: function getPartCrc32(name) {
name = normalize(name);
var part = this.parts[name];
var crc32 = part._data.crc32;
return crc32;
}
}, {
key: "release",
value: function release() {
var _iteratorNormalCompletion = true;
var _didIteratorError = false;
var _iteratorError = undefined;
try {
for (var _iterator = this._shouldReleased[Symbol.iterator](), _step; !(_iteratorNormalCompletion = (_step = _iterator.next()).done); _iteratorNormalCompletion = true) {
var _step$value = _slicedToArray(_step.value, 2),
url = _step$value[1];
URL.revokeObjectURL(url);
}
} catch (err) {
_didIteratorError = true;
_iteratorError = err;
} finally {
try {
if (!_iteratorNormalCompletion && _iterator.return) {
_iterator.return();
}
} finally {
if (_didIteratorError) {
throw _iteratorError;
}
}
}
}
}, {
key: "getObjectPart",
value: function getObjectPart(name) {
name = normalize(name);
var part = this.parts[name];
if (!part) return null;else if (part.cheerio) return part;else {
var $ = Object.assign(this.parts[name] = this.constructor.parseXml(part.asText()), { part: name });
Object.assign($.root()[0].attribs, { part: name });
$.prototype.part = function () {
return name;
};
return $;
}
}
}, {
key: "$",
value: function $(node) {
var root = function root(a) {
return a.root || a.parent && root(a.parent);
};
return this.getObjectPart(root(node).attribs.part)(node);
}
}, {
key: "parse",
value: function parse(domHandler) {}
}, {
key: "render",
value: function render() {}
}, {
key: "serialize",
value: function serialize() {
var _this = this;
var newDoc = new _jszip2.default();
Object.keys(this.parts).forEach(function (path) {
var part = _this.parts[path];
if (part.cheerio) {
newDoc.file(path, part.xml());
} else {
newDoc.file(path, part._data, part.options);
}
});
return newDoc;
}
}, {
key: "save",
value: function save(file, options) {
file = file || this.props.name || Date.now() + ".docx";
var newDoc = this.serialize();
if (typeof document != "undefined" && window.URL && window.URL.createObjectURL) {
var data = newDoc.generate(_extends({}, options, { type: "blob", mimeType: this.constructor.mime }));
var url = window.URL.createObjectURL(data);
var link = document.createElement("a");
document.body.appendChild(link);
link.download = file;
link.href = url;
link.click();
document.body.removeChild(link);
window.URL.revokeObjectURL(url);
} else {
var _data = newDoc.generate(_extends({}, options, { type: "nodebuffer" }));
return new Promise(function (resolve, reject) {
return require("f" + "s").writeFile(file, _data, function (error) {
error ? reject(error) : resolve(_data);
});
});
}
}
}, {
key: "clone",
value: function clone() {
var _this2 = this;
var zip = new _jszip2.default();
var props = props ? JSON.parse(JSON.stringify(this.props)) : props;
var parts = Object.keys(this.parts).reduce(function (state, k) {
var v = _this2.parts[k];
if (v.cheerio) {
zip.file(v.name, v.xml(), v.options);
state[k] = zip.file(v.name);
} else {
zip.file(v.name, v._data, v.options);
state[k] = zip.file(v.name);
}
return state;
}, {});
return new this.constructor(parts, zip, props);
}
/**
* a helper to load document file
* @param inputFile {File} - a html input file, or nodejs file
* @return {Promise}
*/
}], [{
key: "load",
value: function load(inputFile) {
var DocumentSelf = this;
if (inputFile instanceof ZipDocument) return Promise.resolve(inputFile);
return new Promise(function (resolve, reject) {
function parse(data) {
var props = arguments.length > 1 && arguments[1] !== undefined ? arguments[1] : {};
try {
var raw = new _jszip2.default(data),
parts = {};
raw.filter(function (path, file) {
return parts[path] = file;
});
resolve(new DocumentSelf(parts, raw, props));
} catch (error) {
reject(error);
}
}
if (typeof inputFile == 'string') {
//file name
require('fs').readFile(inputFile, function (error, data) {
if (error) reject(error);else if (data) {
parse(data, { name: inputFile.split(/[\/\\]/).pop().replace(/\.docx$/i, '') });
}
});
} else if (inputFile instanceof Blob) {
var reader = new FileReader();
reader.onload = function (e) {
parse(e.target.result, inputFile.name ? {
name: inputFile.name.replace(/\.docx$/i, ''),
lastModified: inputFile.lastModified,
size: inputFile.size
} : { size: inputFile.size });
};
reader.readAsArrayBuffer(inputFile);
} else {
parse(inputFile);
}
});
}
}, {
key: "create",
value: function create() {
return this.load(__dirname + "/../templates/blank." + this.ext);
}
}, {
key: "parseXml",
value: function parseXml(data) {
try {
var opt = { xmlMode: true, decodeEntities: false };
var handler = new ContentDomHandler(opt);
new _htmlparser.Parser(handler, opt).end(data);
var parsed = _cheerio2.default.load(handler.dom, opt);
if (typeof parsed.cheerio == "undefined") parsed.cheerio = "customized";
return parsed;
} catch (error) {
console.error(error);
return null;
}
}
}]);
return ZipDocument;
}();
ZipDocument.ext = "unknown";
ZipDocument.mime = "application/zip";
exports.default = ZipDocument;
var ContentDomHandler = function (_DomHandler) {
_inherits(ContentDomHandler, _DomHandler);
function ContentDomHandler() {
_classCallCheck(this, ContentDomHandler);
return _possibleConstructorReturn(this, (ContentDomHandler.__proto__ || Object.getPrototypeOf(ContentDomHandler)).apply(this, arguments));
}
_createClass(ContentDomHandler, [{
key: "_addDomElement",
value: function _addDomElement(el) {
if (el.type == "text" && (el.data[0] == '\r' || el.data[0] == '\n')) ; //remove format whitespaces
else return _get(ContentDomHandler.prototype.__proto__ || Object.getPrototypeOf(ContentDomHandler.prototype), "_addDomElement", this).call(this, el);
}
}]);
return ContentDomHandler;
}(_htmlparser.DomHandler);
module.exports = exports['default'];
}).call(this)}).call(this,"/lib")
},{"./cheerio-fn":1,"cheerio":18,"fs":133,"htmlparser2":71,"jszip":85}],3:[function(require,module,exports){
"use strict";
Object.defineProperty(exports, "__esModule", {
value: true
});
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; }; }();
var _document = require("../document");
var _document2 = _interopRequireDefault(_document);
var _part = require("./part");
var _part2 = _interopRequireDefault(_part);
var _color = require("color");
var _color2 = _interopRequireDefault(_color);
function _interopRequireDefault(obj) { return obj && obj.__esModule ? obj : { default: obj }; }
function _classCallCheck(instance, Constructor) { if (!(instance instanceof Constructor)) { throw new TypeError("Cannot call a class as a function"); } }
function _possibleConstructorReturn(self, call) { if (!self) { throw new ReferenceError("this hasn't been initialised - super() hasn't been called"); } return call && (typeof call === "object" || typeof call === "function") ? call : self; }
function _inherits(subClass, superClass) { if (typeof superClass !== "function" && superClass !== null) { throw new TypeError("Super expression must either be null or a function, not " + typeof superClass); } subClass.prototype = Object.create(superClass && superClass.prototype, { constructor: { value: subClass, enumerable: false, writable: true, configurable: true } }); if (superClass) Object.setPrototypeOf ? Object.setPrototypeOf(subClass, superClass) : subClass.__proto__ = superClass; }
var _class = function (_Base) {
_inherits(_class, _Base);
function _class() {
_classCallCheck(this, _class);
var _this = _possibleConstructorReturn(this, (_class.__proto__ || Object.getPrototypeOf(_class)).apply(this, arguments));
_this.main = new _part2.default("", _this);
_this.officeDocument = new _this.constructor.OfficeDocument(_this.main.getRelTarget("officeDocument"), _this);
return _this;
}
_createClass(_class, [{
key: "render",
value: function render() {
var _officeDocument;
return (_officeDocument = this.officeDocument).render.apply(_officeDocument, arguments);
}
}, {
key: "parse",
value: function parse() {
var _officeDocument2;
return (_officeDocument2 = this.officeDocument).parse.apply(_officeDocument2, arguments);
}
}, {
key: "dxa2Px",
value: function dxa2Px(a) {
return this.pt2Px(a / 20.0);
}
}, {
key: "emu2Px",
value: function emu2Px(a) {
return this.pt2Px(a / 12700);
}
}, {
key: "pt2Px",
value: function pt2Px(pt) {
return pt * 96 / 72;
}
}, {
key: "cm2Px",
value: function cm2Px(cm) {
return this.pt2Px(parseInt(cm) * 28.3464567);
}
}, {
key: "asColor",
value: function asColor(v, transform) {
if (!v || v.length == 0 || v == 'auto') return '#000000';
v = v.split(' ')[0];
var rgb = v.charAt(0) == '#' ? v : RGB.test(v) ? '#' + v : v;
if (transform) {
var lumMod = transform.lumMod,
lumOff = transform.lumOff,
tint = transform.tint,
shade = transform.shade;
if (lumMod || lumOff || tint) {
var color = (0, _color2.default)(rgb);
if (tint != undefined) {
color = color.lighten(1 - tint);
}
if (lumMod != undefined) {
color = color.lighten(lumMod);
}
if (lumOff != undefined) {
color = color.darken(lumOff);
}
if (shade != undefined) {
color = color.red(color.red() * (1 + shade)).green(color.green() * (1 + shade)).blue(color.blue() * (1 + shade));
}
return ("" + color.hex()).replace(/^0x/, "#");
}
}
return rgb;
}
}, {
key: "toPx",
value: function toPx(length) {
var value = parseFloat(length),
units = String(length).match(RE_LENGTH_UNIT)[1];
switch (units) {
case 'cm':
return this.cm2Px(value);
case 'mm':
return this.cm2Px(value / 10);
case 'in':
return this.pt2Px(value * 72);
case 'pt':
return this.pt2Px(value);
case 'ft':
return this.pt2Px(value * 864);
default:
return value;
}
}
}, {
key: "vender",
get: function get() {
"Microsoft";
}
}, {
key: "product",
get: function get() {
return 'Office 2010';
}
}, {
key: "contentTypes",
get: function get() {
return this.getObjectPart("[Content_Types].xml")("Types");
}
}]);
return _class;
}(_document2.default);
_class.OfficeDocument = _part2.default;
exports.default = _class;
var RGB = /([a-fA-F0-9]{2}?){3}?/;
var RE_LENGTH_UNIT = /^([a-zA-Z]+)$/;
module.exports = exports['default'];
},{"../document":2,"./part":9,"color":34}],4:[function(require,module,exports){
"use strict";
Object.defineProperty(exports, "__esModule", {
value: true
});
var _document = require("../document");
var _document2 = _interopRequireDefault(_document);
var _officeDocument = require("./officeDocument");
var _officeDocument2 = _interopRequireDefault(_officeDocument);
function _interopRequireDefault(obj) { return obj && obj.__esModule ? obj : { default: obj }; }
function _classCallCheck(instance, Constructor) { if (!(instance instanceof Constructor)) { throw new TypeError("Cannot call a class as a function"); } }
function _possibleConstructorReturn(self, call) { if (!self) { throw new ReferenceError("this hasn't been initialised - super() hasn't been called"); } return call && (typeof call === "object" || typeof call === "function") ? call : self; }
function _inherits(subClass, superClass) { if (typeof superClass !== "function" && superClass !== null) { throw new TypeError("Super expression must either be null or a function, not " + typeof superClass); } subClass.prototype = Object.create(superClass && superClass.prototype, { constructor: { value: subClass, enumerable: false, writable: true, configurable: true } }); if (superClass) Object.setPrototypeOf ? Object.setPrototypeOf(subClass, superClass) : subClass.__proto__ = superClass; }
var _class = function (_Base) {
_inherits(_class, _Base);
function _class() {
_classCallCheck(this, _class);
return _possibleConstructorReturn(this, (_class.__proto__ || Object.getPrototypeOf(_class)).apply(this, arguments));
}
return _class;
}(_document2.default);
_class.ext = "docx";
_class.mime = "application/vnd.openxmlformats-officedocument.wordprocessingml.document";
_class.OfficeDocument = _officeDocument2.default;
exports.default = _class;
module.exports = exports['default'];
},{"../document":3,"./officeDocument":5}],5:[function(require,module,exports){
"use strict";
Object.defineProperty(exports, "__esModule", {
value: true
});
var _extends = Object.assign || function (target) { for (var i = 1; i < arguments.length; i++) { var source = arguments[i]; for (var key in source) { if (Object.prototype.hasOwnProperty.call(source, key)) { target[key] = source[key]; } } } return target; };
var _typeof = typeof Symbol === "function" && typeof Symbol.iterator === "symbol" ? function (obj) { return typeof obj; } : function (obj) { return obj && typeof Symbol === "function" && obj.constructor === Symbol && obj !== Symbol.prototype ? "symbol" : typeof obj; };
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; }; }();
var _get = function get(object, property, receiver) { if (object === null) object = Function.prototype; var desc = Object.getOwnPropertyDescriptor(object, property); if (desc === undefined) { var parent = Object.getPrototypeOf(object); if (parent === null) { return undefined; } else { return get(parent, property, receiver); } } else if ("value" in desc) { return desc.value; } else { var getter = desc.get; if (getter === undefined) { return undefined; } return getter.call(receiver); } };
var _officeDocument = require("../officeDocument");
var _officeDocument2 = _interopRequireDefault(_officeDocument);
var _drawml = require("../drawml");
var _drawml2 = _interopRequireDefault(_drawml);
function _interopRequireDefault(obj) { return obj && obj.__esModule ? obj : { default: obj }; }
function _objectWithoutProperties(obj, keys) { var target = {}; for (var i in obj) { if (keys.indexOf(i) >= 0) continue; if (!Object.prototype.hasOwnProperty.call(obj, i)) continue; target[i] = obj[i]; } return target; }
function _classCallCheck(instance, Constructor) { if (!(instance instanceof Constructor)) { throw new TypeError("Cannot call a class as a function"); } }
function _possibleConstructorReturn(self, call) { if (!self) { throw new ReferenceError("this hasn't been initialised - super() hasn't been called"); } return call && (typeof call === "object" || typeof call === "function") ? call : self; }
function _inherits(subClass, superClass) { if (typeof superClass !== "function" && superClass !== null) { throw new TypeError("Super expression must either be null or a function, not " + typeof superClass); } subClass.prototype = Object.create(superClass && superClass.prototype, { constructor: { value: subClass, enumerable: false, writable: true, configurable: true } }); if (superClass) Object.setPrototypeOf ? Object.setPrototypeOf(subClass, superClass) : subClass.__proto__ = superClass; }
var _class = function (_Base) {
_inherits(_class, _Base);
function _class() {
_classCallCheck(this, _class);
return _possibleConstructorReturn(this, (_class.__proto__ || Object.getPrototypeOf(_class)).apply(this, arguments));
}
_createClass(_class, [{
key: "_init",
value: function _init() {
_get(_class.prototype.__proto__ || Object.getPrototypeOf(_class.prototype), "_init", this).call(this);
this._assignRel("styles,numbering,settings".split(","));
var $ = this.styles;
this.styles.prototype.basest = function (selector) {
var current = this;
while (current.length > 0) {
if (current.is(selector)) {
return $(current);
}
current = $.root().find("w\\:style[w\\:styleId=\"" + current.children("w\\:basedOn").attr("w:val") + "\"]");
}
return this.not(this);
};
}
}, {
key: "render",
value: function render(createElement) {
var identify = arguments.length > 1 && arguments[1] !== undefined ? arguments[1] : this.constructor.identify.bind(this.constructor);
var styles = void 0,
numbering = void 0;
if (this.styles) styles = this.renderNode(this.styles("w\\:styles").get(0), createElement, identify);
if (this.numbering) numbering = this.renderNode(this.numbering("w\\:numbering").get(0), createElement, identify);
return this.renderNode(this.content("w\\:document").get(0), createElement, identify, { styles: styles, numbering: numbering });
}
}, {
key: "parse",
value: function parse(domHandler) {
var identify = arguments.length > 1 && arguments[1] !== undefined ? arguments[1] : this.constructor.identify.bind(this.constructor);
var doc = {};
var createElement = domHandler.createElement.bind(domHandler);
function _identify() {
var model = identify.apply(undefined, arguments);
if (model && (typeof model === "undefined" ? "undefined" : _typeof(model)) == "object") {
domHandler.emit.apply(domHandler, ["*", model].concat(Array.prototype.slice.call(arguments)));
domHandler.emit.apply(domHandler, [model.type, model].concat(Array.prototype.slice.call(arguments)));
if (domHandler["on" + model.type]) domHandler["on" + model.type].apply(domHandler, [model].concat(Array.prototype.slice.call(arguments)));
}
return model;
}
if (this.styles) doc.styles = this.renderNode(this.styles("w\\:styles").get(0), createElement, _identify);
if (this.numbering) doc.numbering = this.renderNode(this.numbering("w\\:numbering").get(0), createElement, _identify);
doc.document = this.renderNode(this.content("w\\:document").get(0), createElement, _identify);
return doc;
}
}]);
return _class;
}(_officeDocument2.default);
_class.identities = {
document: function document(wXml, officeDocument) {
var $ = officeDocument.content;
var current = null;
var children = $("w\\:sectPr").each(function (i, sect) {
var end = $(sect).closest('w\\:body>*');
sect.content = end.prevUntil(current).toArray().reverse();
if (!end.is(sect)) sect.content.push(end.get(0));
current = end;
}).toArray();
return { type: "document", children: children };
},
sectPr: function sectPr(wXml, officeDocument) {
var hf = function hf(type) {
return wXml.children.filter(function (a) {
return a.name == "w:" + type + "Reference";
}).reduce(function (headers, a) {
headers.set(a.attribs["w:type"], officeDocument.getRel(a.attribs["r:id"]));
return headers;
}, new Map());
};
return {
type: "section",
children: wXml.content,
headers: hf("header"),
footers: hf("footer"),
hasTitlePage: !!wXml.children.find(function (a) {
return a.name == "w:titlePg";
})
};
},
p: function p(wXml, officeDocument) {
var $ = officeDocument.content(wXml);
var type = "p";
var identity = { type: type, pr: wXml.children.find(function (_ref) {
var name = _ref.name;
return name == "w:pPr";
}), children: wXml.children.filter(function (_ref2) {
var name = _ref2.name;
return name != "w:pPr";
}) };
var pPr = $.find("w\\:pPr");
if (pPr.length) {
var styleId = pPr.find("w\\:pStyle").attr("w:val");
var numPr = pPr.children("w\\:numPr");
if (!numPr.length && styleId) {
numPr = officeDocument.styles("w\\:style[w\\:styleId=\"" + styleId + "\"]").basest(":has(w\\:numPr)").find("w\\:numPr");
}
if (numPr.length) {
identity.type = "list";
identity.numId = numPr.find("w\\:numId").attr("w:val");
identity.level = parseInt(numPr.find("w\\:ilvl").attr("w:val") || 0);
}
if (styleId && styleId.startsWith("Heading")) {
var outlineLvl = officeDocument.styles("w\\:style[w\\:styleId=\"" + styleId + "\"]").basest(":has(w\\:outlineLvl)").find("w\\:outlineLvl").attr("w:val");
if (outlineLvl) {
identity.type = "heading";
identity.outline = parseInt(outlineLvl) + 1;
}
}
}
return identity;
},
r: function r(wXml) {
return { type: "r", pr: wXml.children.find(function (_ref3) {
var name = _ref3.name;
return name == "w:rPr";
}), children: wXml.children.filter(function (_ref4) {
var name = _ref4.name;
return name != "w:rPr";
}) };
},
fldChar: function fldChar(wXml) {
return wXml.attribs["w:fldCharType"];
},
inline: function inline(wXml, officeDocument) {
var $ = officeDocument.content(wXml);
var props = $.props(_extends({}, (0, _drawml2.default)(officeDocument), {
__filter: "wp\\:extent,wp\\:effectExtent"
}));
return _extends({
type: "drawing.inline"
}, props, {
children: $.find('a\\:graphic>a\\:graphicData').children().toArray()
});
},
anchor: function anchor(wXml, officeDocument) {
var $ = officeDocument.content(wXml);
var graphicData = $.find('>a\\:graphic>a\\:graphicData');
var type = graphicData.attr("uri").split("/").pop();
var children = graphicData.children().toArray();
if (type == "wordprocessingGroup") children = children[0].children.filter(function (a) {
return a.name.split(":")[0] != "wpg";
});
return { type: "drawing.anchor", children: children };
},
pic: function pic(wXml, officeDocument) {
var $ = officeDocument.$(wXml);
var props = $.props(_extends({}, (0, _drawml2.default)(officeDocument), {
tidy: function tidy(_ref5) {
var spPr = _ref5.spPr,
_ref5$nvPicPr = _ref5.nvPicPr,
_ref5$nvPicPr$cNvPr = _ref5$nvPicPr.cNvPr,
cNvPr = _ref5$nvPicPr$cNvPr === undefined ? {} : _ref5$nvPicPr$cNvPr,
_ref5$nvPicPr$cNvSpPr = _ref5$nvPicPr.cNvSpPr,
cNvSpPr = _ref5$nvPicPr$cNvSpPr === undefined ? {} : _ref5$nvPicPr$cNvSpPr,
_ref5$nvPicPr$nvPr = _ref5$nvPicPr.nvPr,
nvPr = _ref5$nvPicPr$nvPr === undefined ? {} : _ref5$nvPicPr$nvPr,
_ref5$style = _ref5.style;
_ref5$style = _ref5$style === undefined ? {} : _ref5$style;
var _ref5$style$lnRef = _ref5$style.lnRef,
lnRef = _ref5$style$lnRef === undefined ? {} : _ref5$style$lnRef,
_ref5$style$fillRef = _ref5$style.fillRef,
fillRef = _ref5$style$fillRef === undefined ? {} : _ref5$style$fillRef,
_ref5$style$effectRef = _ref5$style.effectRef,
effectRef = _ref5$style$effectRef === undefined ? {} : _ref5$style$effectRef,
others = _objectWithoutProperties(_ref5, ["spPr", "nvPicPr", "style"]);
return _extends({}, lnRef, fillRef, effectRef, spPr, cNvPr, cNvSpPr, nvPr, others);
}
}));
return _extends({}, props, { type: "picture" });
},
wsp: function wsp(wXml, officeDocument) {
var content = "wps\\:txbx";
var $ = officeDocument.$(wXml);
var children = $.children(content).toArray();
var same = function same(keys, fx) {
return keys.reduce(function (fs, k) {
return fs[k] = fx, fs;
}, {});
};
var props = $.props(_extends({}, (0, _drawml2.default)(officeDocument), same("r,t,l,b".split(",").map(function (a) {
return a + "Ins";
}), function (v) {
return officeDocument.doc.emu2Px(v);
}), {
__filter: ":not(" + content + ")",
tidy: function tidy(_ref6) {
var _ref6$cNvSpPr = _ref6.cNvSpPr,
cNvSpPr = _ref6$cNvSpPr === undefined ? {} : _ref6$cNvSpPr,
_ref6$spPr = _ref6.spPr,
spPr = _ref6$spPr === undefined ? {} : _ref6$spPr,
_ref6$style = _ref6.style;
_ref6$style = _ref6$style === undefined ? {} : _ref6$style;
var _ref6$style$lnRef = _ref6$style.lnRef,
lnRef = _ref6$style$lnRef === undefined ? {} : _ref6$style$lnRef,
_ref6$style$fillRef = _ref6$style.fillRef,
fillRef = _ref6$style$fillRef === undefined ? {} : _ref6$style$fillRef,
_ref6$style$effectRef = _ref6$style.effectRef,
effectRef = _ref6$style$effectRef === undefined ? {} : _ref6$style$effectRef,
_ref6$style$fontRef = _ref6$style.fontRef,
fontRef = _ref6$style$fontRef === undefined ? {} : _ref6$style$fontRef,
others = _objectWithoutProperties(_ref6, ["cNvSpPr", "spPr", "style"]);
return _extends({}, cNvSpPr, lnRef, fillRef, effectRef, spPr, { textStyle: fontRef }, others);
}
}));
return _extends({}, props, { type: "shape", children: children });
},
Fallback: function Fallback() {
return null;
},
sdt: function sdt(wXml, officeDocument) {
var $ = officeDocument.content(wXml);
var pr = $.find('>w\\:sdtPr');
var content = $.find('>w\\:sdtContent');
var children = content.children().toArray();
var elBinding = pr.find('w\\:dataBinding').get(0);
if (elBinding) {
//properties
var path = elBinding.attribs['w:xpath'],
d = path.split(/[\/\:\[]/),
name = (d.pop(), d.pop());
var value = content.text();
return { type: "property", name: name, value: value, children: children };
} else {
//controls
var prChildren = pr.get(0).children;
var elType = prChildren[prChildren.length - 1];
var _name = elType.name.split(":").pop();
var type = "text,picture,docPartList,docPartObj,comboBox,dropDownList,date,checkbox,repeatingSection,repeatingSectionItem".split(",").find(function (a) {
return a == _name;
});
var model = { children: children };
if (type) {
model.type = "control." + type;
} else {
//container
if (content.find("w\\:p,w\\:tbl,w\\:tr,w\\:tc").length) {
model.type = "block";
} else {
model.type = "inline";
}
}
$ = officeDocument.content;
switch (model.type) {
case "control.dropDownList":
case "control.comboBox":
{
var selected = $(content).text();
model.options = $(elType).find("w\\:listItem").map(function (i, li) {
return {
displayText: li.attribs["w:displayText"],
value: li.attribs["w:value"]
};
}).get();
model.value = (model.options.find(function (a) {
return a.displayText == selected;
}) || {}).value;
break;
}
case "control.checkbox":
{
var ns = elType.name.split(":")[0];
model.checked = $(elType).find(ns + "\\:checked").attr(ns + ":val") == "1";
break;
}
case "control.text":
if (content.find('w\\:r [w\\:val~=Placeholder]').length == 0) model.value = content.text();
break;
case "control.date":
model.value = new Date($(elType).attr("w:fullDate"));
model.format = $(elType).find("w\\:dateFormat").attr("w:val");
model.locale = $(elType).find("w\\:lid").attr("w:val");
break;
}
return model;
}
},
hyperlink: function hyperlink(wXml, officeDocument) {
if (wXml.attribs["r:id"]) {
var url = officeDocument.getRel(wXml.attribs["r:id"]);
return { type: "hyperlink", url: url };
} else if (wXml.attribs["w:anchor"]) {
return { type: "hyperlink", url: "#" + wXml.attribs["w:anchor"] };
}
},
tbl: function tbl(wXml) {
return wXml.children.reduce(function (state, node) {
switch (node.name) {
case "w:tblPr":
state.pr = node;
break;
case "w:tblGrid":
state.cols = node.children;
break;
default:
state.children.push(node);
}
return state;
}, { type: "tbl", children: [], pr: null, cols: [] });
},
tr: function tr(wXml) {
return wXml.children.reduce(function (state, node) {
switch (node.name) {
case "w:trPr":
state.pr = node;
state.isHeader = !!node.children.find(function (a) {
return a.name == "w:tblHeader";
});
break;
default:
state.children.push(node);
}
return state;
}, { type: "tr", children: [], pr: null });
},
tc: function tc(wXml) {
return wXml.children.reduce(function (state, node) {
switch (node.name) {
case "w:tcPr":
state.pr = node;
break;
default:
state.children.push(node);
}
return state;
}, { type: "tc", children: [], pr: null });
},
altChunk: function altChunk(wXml, officeDocument) {
var rId = wXml.attribs['r:id'];
var data = officeDocument.getRel(rId);
var partName = officeDocument.folder + officeDocument.rels("[Id=" + rId + "]").attr("Target");
var contentType = officeDocument.doc.contentTypes("Override[PartName='" + partName + "']").attr("ContentType");
return { type: "chunk", data: data, contentType: contentType };
},
docDefaults: function docDefaults(wXml) {
return { type: "style" };
},
style: function style(wXml) {
return { type: "style", id: wXml.attribs['w:styleId'] };
},
abstractNum: function abstractNum(wXml) {
return { type: "abstractNum", id: wXml.attribs["w:abstractNumId"] };
},
num: function num(wXml) {
return { type: "num", id: wXml.attribs["w:numId"], abstractNum: wXml.children.find(function (a) {
return a.name == "w:abstractNumId";
}).attribs["w:val"] };
},
latentStyles: function latentStyles() {
return null;
},
object: function object(wXml, officeDocument) {
var ole = officeDocument.content(wXml).find("o\\:OLEObject");
var type = ole.attr("ProgID");
var embed = ole.attr("Type") === "Embed";
var rId = ole.attr("r:id");
return { type: "object", embed: embed, prog: type, data: officeDocument.getRelOleObject(rId) };
}
};
exports.default = _class;
module.exports = exports['default'];
},{"../drawml":6,"../officeDocument":7}],6:[function(require,module,exports){
"use strict";
Object.defineProperty(exports, "__esModule", {
value: true
});
var _extends = Object.assign || function (target) { for (var i = 1; i < arguments.length; i++) { var source = arguments[i]; for (var key in source) { if (Object.prototype.hasOwnProperty.call(source, key)) { target[key] = source[key]; } } } return target; };
var _part = require("../part");
var _part2 = _interopRequireDefault(_part);
function _interopRequireDefault(obj) { return obj && obj.__esModule ? obj : { default: obj }; }
function _objectWithoutProperties(obj, keys) { var target = {}; for (var i in obj) { if (keys.indexOf(i) >= 0) continue; if (!Object.prototype.hasOwnProperty.call(obj, i)) continue; target[i] = obj[i]; } return target; }
exports.default = function (od) {
return _extends({
__filter: ":not(a\\:extLst)",
id: function id() {
return undefined;
}
}, same("latin,ea,cs".split(","), function (_ref) {
var _ref$attribs$typeface = _ref.attribs.typeface,
typeface = _ref$attribs$typeface === undefined ? "" : _ref$attribs$typeface;
return od.theme.font(typeface);
}), same("lumMod,lumOff,tint,shade".split(","), function (_ref2) {
var val = _ref2.attribs.val;
return parseInt(val) / 100000;
}), {
tidy_schemeClr: function tidy_schemeClr(_ref3) {
var val = _ref3.val,
effect = _objectWithoutProperties(_ref3, ["val"]);
return od.doc.asColor(od.theme.color(val), effect);
},
tidy_srgbClr: function tidy_srgbClr(_ref4) {
var val = _ref4.val,
effect = _objectWithoutProperties(_ref4, ["val"]);
return od.doc.asColor(val, effect);
},
tidy_prstClr: function tidy_prstClr(_ref5) {
var val = _ref5.val,
effect = _objectWithoutProperties(_ref5, ["val"]);
return od.doc.asColor(val, effect);
},
sysClr: function sysClr(_ref6) {
var val = _ref6.attribs.val;
return val;
},
tidy_solidFill: function tidy_solidFill(_ref7) {
var color = _ref7.color;
return color;
},
rot: function rot(v) {
return parseInt(v) / 60000;
},
blip: function blip(n) {
var _n$attribs = n.attribs,
embed = _n$attribs["r:embed"],
url = _n$attribs["r:link"];
if (url) return { url: url };
var part = od.$(n).part();
return new _part2.default(part, od.doc).getRel(embed);
},
prstGeom: function prstGeom(x) {
return x.attribs.prst;
},
pathLst: function pathLst(_ref8) {
var children = _ref8.children;
var px = function px(x) {
return od.doc.emu2Px(x);
};
return children.filter(function (a) {
return a.name == "a:path";
}).reduce(function (d, path) {
path.children.filter(function (a) {
return a.name;
}).forEach(function (a) {
switch (a.name.split(":").pop()) {
case 'moveTo':
d.push('M ' + px(a.children[0].attribs.x) + ' ' + px(a.children[0].attribs.y));
break;
case 'lnTo':
d.push('L ' + px(a.children[0].attribs.x) + ' ' + px(a.children[0].attribs.y));
break;
break;
case 'cubicBezTo':
d.push('L ' + px(a.children[0].attribs.x) + ' ' + px(a.children[0].attribs.y));
d.push('Q ' + px(a.children[1].attribs.x) + ' ' + px(a.children[1].attribs.y) + ' ' + px(a.children[2].attribs.x) + ' ' + px(a.children[2].attribs.y));
break;
case 'arcTo':
d.push("A");
break;
case 'close':
d.push('Z');
break;
}
});
return d;
}, []).join(" ");
},
tidy_custGeom: function tidy_custGeom(_ref9) {
var pathLst = _ref9.pathLst;
return pathLst;
},
lvl: function lvl(v) {
return parseInt(v);
},
spcPts: function spcPts(_ref10) {
var val = _ref10.attribs.val;
return od.doc.pt2Px(parseInt(val) / 100);
},
tidy_spcAft: function tidy_spcAft(_ref11) {
var a = _ref11.spcPts;
return a;
},
tidy_spcBef: function tidy_spcBef(_ref12) {
var a = _ref12.spcPts;
return a;
},
buFont: function buFont(_ref13) {
var typeface = _ref13.attribs.typeface;
return od.theme.font(typeface);
},
buChar: function buChar(_ref14) {
var char = _ref14.attribs.char;
return char;
},
buSzPts: function buSzPts(_ref15) {
var val = _ref15.attribs.val;
return od.doc.pt2Px(parseInt(val) / 100);
},
buSzPct: function buSzPct(_ref16) {
var val = _ref16.attribs.val;
return parseInt(val) / 1000 / 100;
},
buAutoNum: function buAutoNum(_ref17) {
var attribs = _ref17.attribs;
return _extends({}, attribs);
},
tidy_buClr: function tidy_buClr(_ref18) {
var color = _ref18.color;
return color;
},
indent: function indent(v) {
return od.doc.emu2Px(v);
},
marL: function marL(v) {
return od.doc.emu2Px(v);
},
marR: function marR(v) {
return od.doc.emu2Px(v);
},
marT: function marT(v) {
return od.doc.emu2Px(v);
},
marB: function marB(v) {
return od.doc.emu2Px(v);
},
lIns: function lIns(v) {
return od.doc.emu2Px(v);
},
rIns: function rIns(v) {
return od.doc.emu2Px(v);
},
bIns: function bIns(v) {
return od.doc.emu2Px(v);
},
tIns: function tIns(v) {
return od.doc.emu2Px(v);
},
distL: function distL(v) {
return od.doc.emu2Px(v);
},
distR: function distR(v) {
return od.doc.emu2Px(v);
},
distT: function distT(v) {
return od.doc.emu2Px(v);
},
distB: function distB(v) {
return od.doc.emu2Px(v);
},
ext: function ext(_ref19) {
var _ref19$attribs = _ref19.attribs,
cx = _ref19$attribs.cx,
cy = _ref19$attribs.cy;
return { width: od.doc.emu2Px(cx), height: od.doc.emu2Px(cy) };
},
extent: function extent(_ref20) {
var _ref20$attribs = _ref20.attribs,
cx = _ref20$attribs.cx,
cy = _ref20$attribs.cy;
return { width: od.doc.emu2Px(cx), height: od.doc.emu2Px(cy) };
},
effectExtent: function effectExtent(_ref21) {
var _ref21$attribs = _ref21.attribs,
l = _ref21$attribs.l,
t = _ref21$attribs.t,
r = _ref21$attribs.r,
b = _ref21$attribs.b;
return { left: od.doc.emu2Px(l), right: od.doc.emu2Px(r), top: od.doc.emu2Px(t), bottom: od.doc.emu2Px(b) };
},
off: function off(_ref22) {
var _ref22$attribs = _ref22.attribs,
x = _ref22$attribs.x,
y = _ref22$attribs.y;
return { x: od.doc.emu2Px(x), y: od.doc.emu2Px(y) };
},
tidy_xfrm: function tidy_xfrm(_ref23) {
var _ref23$ext = _ref23.ext,
ext = _ref23$ext === undefined ? {} : _ref23$ext,
_ref23$off = _ref23.off,
off = _ref23$off === undefined ? {} : _ref23$off,
transform = _objectWithoutProperties(_ref23, ["ext", "off"]);
return _extends({}, ext, off, transform);
}
}, same("ln,lnB,lnR,lnL,lnT,lnTlToBr,lnBlToTr".split(",").map(function (a) {
return 'tidy_' + a;
}), function (_ref24) {
var w = _ref24.w,
props = _objectWithoutProperties(_ref24, ["w"]);
return _extends({}, props, { w: w ? od.doc.emu2Px(w) : undefined });
}), same("left,right,top,bottom".split(",").map(function (a) {
return 'tidy_' + a;
}), function (_ref25) {
var ln = _ref25.ln;
return ln;
}), {
tidy_tcTxStyle: function tidy_tcTxStyle(_ref26) {
var color = _ref26.color,
props = _objectWithoutProperties(_ref26, ["color"]);
return _extends({}, props, { solidFill: color });
},
tidy_lnRef: function tidy_lnRef(_ref27) {
var idx = _ref27.idx,
ph = _objectWithoutProperties(_ref27, ["idx"]);
return od.theme.lnRef(idx, ph);
},
tidy_fillRef: function tidy_fillRef(_ref28) {
var idx = _ref28.idx,
ph = _objectWithoutProperties(_ref28, ["idx"]