style-map.js 2.7 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475
  1. var _ = require("underscore");
  2. var promises = require("../promises");
  3. var xml = require("../xml");
  4. exports.writeStyleMap = writeStyleMap;
  5. exports.readStyleMap = readStyleMap;
  6. var schema = "http://schemas.zwobble.org/mammoth/style-map";
  7. var styleMapPath = "mammoth/style-map";
  8. var styleMapAbsolutePath = "/" + styleMapPath;
  9. function writeStyleMap(docxFile, styleMap) {
  10. docxFile.write(styleMapPath, styleMap);
  11. return updateRelationships(docxFile).then(function() {
  12. return updateContentTypes(docxFile);
  13. });
  14. }
  15. function updateRelationships(docxFile) {
  16. var path = "word/_rels/document.xml.rels";
  17. var relationshipsUri = "http://schemas.openxmlformats.org/package/2006/relationships";
  18. var relationshipElementName = "{" + relationshipsUri + "}Relationship";
  19. return docxFile.read(path, "utf8")
  20. .then(xml.readString)
  21. .then(function(relationshipsContainer) {
  22. var relationships = relationshipsContainer.children;
  23. addOrUpdateElement(relationships, relationshipElementName, "Id", {
  24. "Id": "rMammothStyleMap",
  25. "Type": schema,
  26. "Target": styleMapAbsolutePath
  27. });
  28. var namespaces = {"": relationshipsUri};
  29. return docxFile.write(path, xml.writeString(relationshipsContainer, namespaces));
  30. });
  31. }
  32. function updateContentTypes(docxFile) {
  33. var path = "[Content_Types].xml";
  34. var contentTypesUri = "http://schemas.openxmlformats.org/package/2006/content-types";
  35. var overrideName = "{" + contentTypesUri + "}Override";
  36. return docxFile.read(path, "utf8")
  37. .then(xml.readString)
  38. .then(function(typesElement) {
  39. var children = typesElement.children;
  40. addOrUpdateElement(children, overrideName, "PartName", {
  41. "PartName": styleMapAbsolutePath,
  42. "ContentType": "text/prs.mammoth.style-map"
  43. });
  44. var namespaces = {"": contentTypesUri};
  45. return docxFile.write(path, xml.writeString(typesElement, namespaces));
  46. });
  47. }
  48. function addOrUpdateElement(elements, name, identifyingAttribute, attributes) {
  49. var existingElement = _.find(elements, function(element) {
  50. return element.name === name &&
  51. element.attributes[identifyingAttribute] === attributes[identifyingAttribute];
  52. });
  53. if (existingElement) {
  54. existingElement.attributes = attributes;
  55. } else {
  56. elements.push(xml.element(name, attributes));
  57. }
  58. }
  59. function readStyleMap(docxFile) {
  60. if (docxFile.exists(styleMapPath)) {
  61. return docxFile.read(styleMapPath, "utf8");
  62. } else {
  63. return promises.resolve(null);
  64. }
  65. }