document-head.js 2.6 KB

1234567891011121314151617181920212223242526272829303132333435363738394041424344454647484950515253545556575859606162636465666768
  1. "use strict";
  2. exports.__esModule = true;
  3. var tslib_1 = require("tslib");
  4. var document_head_1 = require("../factories/document-head");
  5. var get_match_index_1 = require("../utils/get-match-index");
  6. function transformDocumentHead(document, context) {
  7. var _a;
  8. var cstNode = document.cstNode;
  9. var _b = categorizeNodes(cstNode, context), directives = _b.directives, comments = _b.comments, endComments = _b.endComments;
  10. var _c = getPosition(cstNode, directives, context), position = _c.position, endMarkerPoint = _c.endMarkerPoint;
  11. (_a = context.comments).push.apply(_a, tslib_1.__spreadArrays(comments, endComments));
  12. var createDocumentHeadWithTrailingComment = function (trailingComment) {
  13. if (trailingComment) {
  14. context.comments.push(trailingComment);
  15. }
  16. return document_head_1.createDocumentHead(position, directives, endComments, trailingComment);
  17. };
  18. return {
  19. createDocumentHeadWithTrailingComment: createDocumentHeadWithTrailingComment,
  20. documentHeadEndMarkerPoint: endMarkerPoint
  21. };
  22. }
  23. exports.transformDocumentHead = transformDocumentHead;
  24. function categorizeNodes(document, context) {
  25. var directives = [];
  26. var comments = [];
  27. var endComments = [];
  28. var hasDirective = false;
  29. for (var i = document.directives.length - 1; i >= 0; i--) {
  30. var node = context.transformNode(document.directives[i]);
  31. if (node.type === "comment") {
  32. if (hasDirective) {
  33. comments.unshift(node);
  34. }
  35. else {
  36. endComments.unshift(node);
  37. }
  38. }
  39. else {
  40. hasDirective = true;
  41. directives.unshift(node);
  42. }
  43. }
  44. return { directives: directives, comments: comments, endComments: endComments };
  45. }
  46. function getPosition(document, directives, context) {
  47. var endMarkerIndex = get_match_index_1.getMatchIndex(context.text.slice(0, document.valueRange.origStart), /---\s*$/);
  48. // end marker should start with the first character on the line
  49. if (endMarkerIndex > 0 && !/[\r\n]/.test(context.text[endMarkerIndex - 1])) {
  50. endMarkerIndex = -1;
  51. }
  52. var range = endMarkerIndex === -1
  53. ? {
  54. origStart: document.valueRange.origStart,
  55. origEnd: document.valueRange.origStart
  56. }
  57. : {
  58. origStart: endMarkerIndex,
  59. origEnd: endMarkerIndex + 3
  60. };
  61. if (directives.length !== 0) {
  62. range.origStart = directives[0].position.start.offset;
  63. }
  64. return {
  65. position: context.transformRange(range),
  66. endMarkerPoint: endMarkerIndex === -1 ? null : context.transformOffset(endMarkerIndex)
  67. };
  68. }