wrapWord.js 1.6 KB

123456789101112131415161718192021222324252627282930313233343536373839404142
  1. "use strict";
  2. var __importDefault = (this && this.__importDefault) || function (mod) {
  3. return (mod && mod.__esModule) ? mod : { "default": mod };
  4. };
  5. Object.defineProperty(exports, "__esModule", { value: true });
  6. exports.wrapWord = void 0;
  7. const slice_ansi_1 = __importDefault(require("slice-ansi"));
  8. const strip_ansi_1 = __importDefault(require("strip-ansi"));
  9. const calculateStringLengths = (input, size) => {
  10. let subject = (0, strip_ansi_1.default)(input);
  11. const chunks = [];
  12. // https://regex101.com/r/gY5kZ1/1
  13. const re = new RegExp('(^.{1,' + String(Math.max(size, 1)) + '}(\\s+|$))|(^.{1,' + String(Math.max(size - 1, 1)) + '}(\\\\|/|_|\\.|,|;|-))');
  14. do {
  15. let chunk;
  16. const match = re.exec(subject);
  17. if (match) {
  18. chunk = match[0];
  19. subject = subject.slice(chunk.length);
  20. const trimmedLength = chunk.trim().length;
  21. const offset = chunk.length - trimmedLength;
  22. chunks.push([trimmedLength, offset]);
  23. }
  24. else {
  25. chunk = subject.slice(0, size);
  26. subject = subject.slice(size);
  27. chunks.push([chunk.length, 0]);
  28. }
  29. } while (subject.length);
  30. return chunks;
  31. };
  32. const wrapWord = (input, size) => {
  33. const result = [];
  34. let startIndex = 0;
  35. calculateStringLengths(input, size).forEach(([length, offset]) => {
  36. result.push((0, slice_ansi_1.default)(input, startIndex, startIndex + length));
  37. startIndex += length + offset;
  38. });
  39. return result;
  40. };
  41. exports.wrapWord = wrapWord;
  42. //# sourceMappingURL=wrapWord.js.map