BookParser.js 26 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607608609610611612613614615616617618619620621622623624625626627628629630631632633634635636637638639640641642643644645646647648649650651652653654655656657658659660661662663664665666667668669670671672673674675676677678679680681682683684685686687688689690691692693694695696697698699700701702703704705706707708709710711712713714715716717718719720721722723724725726727728729730731732733734735736737738739740741742743744745746747748749750751752753754755756757758759760761762763764765766767768769770771772773774775776777778
  1. import he from 'he';
  2. import sax from '../../../../server/core/BookConverter/sax';
  3. import {sleep} from '../../../share/utils';
  4. const maxImageLineCount = 100;
  5. export default class BookParser {
  6. constructor() {
  7. // defaults
  8. this.p = 30;// px, отступ параграфа
  9. this.w = 300;// px, ширина страницы
  10. this.wordWrap = false;// перенос по слогам
  11. //заглушка
  12. this.measureText = (text, style) => {// eslint-disable-line no-unused-vars
  13. return text.length*20;
  14. };
  15. }
  16. async parse(data, callback) {
  17. if (!callback)
  18. callback = () => {};
  19. callback(0);
  20. if (data.indexOf('<FictionBook') < 0) {
  21. throw new Error('Неверный формат файла');
  22. }
  23. //defaults
  24. let fb2 = {
  25. firstName: '',
  26. middleName: '',
  27. lastName: '',
  28. bookTitle: '',
  29. };
  30. let path = '';
  31. let tag = '';
  32. let center = false;
  33. let bold = false;
  34. let italic = false;
  35. this.binary = {};
  36. let binaryId = '';
  37. let binaryType = '';
  38. let dimPromises = [];
  39. let paraIndex = -1;
  40. let paraOffset = 0;
  41. let para = []; /*array of
  42. {
  43. index: Number,
  44. offset: Number, //сумма всех length до этого параграфа
  45. length: Number, //длина text без тегов
  46. text: String, //текст параграфа с вложенными тегами
  47. cut: Boolean, //параграф - кандидат на сокрытие (cutEmptyParagraphs)
  48. addIndex: Number, //индекс добавляемого пустого параграфа (addEmptyParagraphs)
  49. }
  50. */
  51. const getImageDimensions = (binaryId, binaryType, data) => {
  52. return new Promise (async(resolve, reject) => {
  53. const i = new Image();
  54. let resolved = false;
  55. i.onload = () => {
  56. resolved = true;
  57. this.binary[binaryId] = {
  58. w: i.width,
  59. h: i.height,
  60. type: binaryType,
  61. data
  62. };
  63. resolve();
  64. };
  65. i.src = `data:${binaryType};base64,${data}`;
  66. await sleep(30*1000);
  67. if (!resolved)
  68. reject('Не удалось получить размер изображения');
  69. });
  70. };
  71. const newParagraph = (text, len, addIndex) => {
  72. paraIndex++;
  73. let p = {
  74. index: paraIndex,
  75. offset: paraOffset,
  76. length: len,
  77. text: text,
  78. cut: (!addIndex && (len == 1 && text[0] == ' ')),
  79. addIndex: (addIndex ? addIndex : 0),
  80. };
  81. para[paraIndex] = p;
  82. paraOffset += p.length;
  83. };
  84. const growParagraph = (text, len) => {
  85. if (paraIndex < 0) {
  86. newParagraph(' ', 1);
  87. growParagraph(text, len);
  88. return;
  89. }
  90. let p = para[paraIndex];
  91. //добавление пустых (addEmptyParagraphs) параграфов
  92. if (p.length == 1 && p.text[0] == ' ' && len > 0) {
  93. paraIndex--;
  94. paraOffset -= p.length;
  95. for (let i = 0; i < 2; i++) {
  96. newParagraph(' ', 1, i + 1);
  97. }
  98. paraIndex++;
  99. p.index = paraIndex;
  100. p.offset = paraOffset;
  101. para[paraIndex] = p;
  102. paraOffset += p.length;
  103. }
  104. paraOffset -= p.length;
  105. //параграф оказался непустой
  106. if (p.length == 1 && p.text[0] == ' ' && len > 0) {
  107. p.length = 0;
  108. p.text = p.text.substr(1);
  109. p.cut = (len == 1 && text[0] == ' ');
  110. }
  111. p.length += len;
  112. p.text += text;
  113. para[paraIndex] = p;
  114. paraOffset += p.length;
  115. };
  116. const onStartNode = (elemName, tail) => {// eslint-disable-line no-unused-vars
  117. if (elemName == '?xml')
  118. return;
  119. tag = elemName;
  120. path += '/' + elemName;
  121. if (tag == 'binary') {
  122. let attrs = sax.getAttrsSync(tail);
  123. binaryType = (attrs['content-type'].value ? attrs['content-type'].value : '');
  124. if (binaryType == 'image/jpeg' || binaryType == 'image/png')
  125. binaryId = (attrs.id.value ? attrs.id.value : '');
  126. }
  127. if (tag == 'image') {
  128. let attrs = sax.getAttrsSync(tail);
  129. if (attrs.href.value)
  130. newParagraph(`<image href="${attrs.href.value}">${' '.repeat(maxImageLineCount)}</image>`, maxImageLineCount);
  131. }
  132. if (path.indexOf('/fictionbook/body') == 0) {
  133. if (tag == 'title') {
  134. newParagraph(' ', 1);
  135. bold = true;
  136. center = true;
  137. }
  138. if (tag == 'emphasis' || tag == 'strong') {
  139. growParagraph(`<${tag}>`, 0);
  140. }
  141. if ((tag == 'p' || tag == 'empty-line' || tag == 'v')) {
  142. newParagraph(' ', 1);
  143. }
  144. if (tag == 'subtitle') {
  145. newParagraph(' ', 1);
  146. bold = true;
  147. }
  148. if (tag == 'epigraph') {
  149. italic = true;
  150. }
  151. if (tag == 'poem') {
  152. newParagraph(' ', 1);
  153. }
  154. if (tag == 'text-author') {
  155. newParagraph(' <s> <s> <s> ', 4);
  156. }
  157. }
  158. };
  159. const onEndNode = (elemName) => {// eslint-disable-line no-unused-vars
  160. if (tag == elemName) {
  161. if (tag == 'binary') {
  162. binaryId = '';
  163. }
  164. if (path.indexOf('/fictionbook/body') == 0) {
  165. if (tag == 'title') {
  166. bold = false;
  167. center = false;
  168. }
  169. if (tag == 'emphasis' || tag == 'strong') {
  170. growParagraph(`</${tag}>`, 0);
  171. }
  172. if (tag == 'subtitle') {
  173. bold = false;
  174. }
  175. if (tag == 'epigraph') {
  176. italic = false;
  177. }
  178. if (tag == 'stanza') {
  179. newParagraph(' ', 1);
  180. }
  181. }
  182. path = path.substr(0, path.length - tag.length - 1);
  183. let i = path.lastIndexOf('/');
  184. if (i >= 0) {
  185. tag = path.substr(i + 1);
  186. } else {
  187. tag = path;
  188. }
  189. }
  190. };
  191. const onTextNode = (text) => {// eslint-disable-line no-unused-vars
  192. text = he.decode(text);
  193. text = text.replace(/>/g, '&gt;');
  194. text = text.replace(/</g, '&lt;');
  195. if (text != ' ' && text.trim() == '')
  196. text = text.trim();
  197. if (text == '')
  198. return;
  199. text = text.replace(/[\t\n\r]/g, ' ');
  200. switch (path) {
  201. case '/fictionbook/description/title-info/author/first-name':
  202. fb2.firstName = text;
  203. break;
  204. case '/fictionbook/description/title-info/author/middle-name':
  205. fb2.middleName = text;
  206. break;
  207. case '/fictionbook/description/title-info/author/last-name':
  208. fb2.lastName = text;
  209. break;
  210. case '/fictionbook/description/title-info/genre':
  211. fb2.genre = text;
  212. break;
  213. case '/fictionbook/description/title-info/date':
  214. fb2.date = text;
  215. break;
  216. case '/fictionbook/description/title-info/book-title':
  217. fb2.bookTitle = text;
  218. break;
  219. case '/fictionbook/description/title-info/id':
  220. fb2.id = text;
  221. break;
  222. }
  223. if (path.indexOf('/fictionbook/description/title-info/annotation') == 0) {
  224. if (!fb2.annotation)
  225. fb2.annotation = '';
  226. if (tag != 'annotation')
  227. fb2.annotation += `<${tag}>${text}</${tag}>`;
  228. else
  229. fb2.annotation += text;
  230. }
  231. let tOpen = (center ? '<center>' : '');
  232. tOpen += (bold ? '<strong>' : '');
  233. tOpen += (italic ? '<emphasis>' : '');
  234. let tClose = (italic ? '</emphasis>' : '');
  235. tClose += (bold ? '</strong>' : '');
  236. tClose += (center ? '</center>' : '');
  237. if (path.indexOf('/fictionbook/body/title') == 0) {
  238. growParagraph(`${tOpen}${text}${tClose}`, text.length);
  239. }
  240. if (path.indexOf('/fictionbook/body/section') == 0) {
  241. switch (tag) {
  242. case 'p':
  243. growParagraph(`${tOpen}${text}${tClose}`, text.length);
  244. break;
  245. default:
  246. growParagraph(`${tOpen}${text}${tClose}`, text.length);
  247. }
  248. }
  249. if (binaryId) {
  250. dimPromises.push(getImageDimensions(binaryId, binaryType, text));
  251. }
  252. };
  253. const onProgress = async(prog) => {
  254. await sleep(1);
  255. callback(prog);
  256. };
  257. await sax.parse(data, {
  258. onStartNode, onEndNode, onTextNode, onProgress
  259. });
  260. if (dimPromises.length) {
  261. try {
  262. await Promise.all(dimPromises);
  263. } catch (e) {
  264. //
  265. }
  266. }
  267. this.fb2 = fb2;
  268. this.para = para;
  269. this.textLength = paraOffset;
  270. callback(100);
  271. await sleep(10);
  272. return {fb2};
  273. }
  274. findParaIndex(bookPos) {
  275. let result = undefined;
  276. //дихотомия
  277. let first = 0;
  278. let last = this.para.length - 1;
  279. while (first < last) {
  280. let mid = first + Math.floor((last - first)/2);
  281. if (bookPos <= this.para[mid].offset + this.para[mid].length - 1)
  282. last = mid;
  283. else
  284. first = mid + 1;
  285. }
  286. if (last >= 0) {
  287. const ofs = this.para[last].offset;
  288. if (bookPos >= ofs && bookPos < ofs + this.para[last].length)
  289. result = last;
  290. }
  291. return result;
  292. }
  293. splitToStyle(s) {
  294. let result = [];/*array of {
  295. style: {bold: Boolean, italic: Boolean, center: Boolean},
  296. image: {local: Boolean, inline: Boolean, id: String},
  297. text: String,
  298. }*/
  299. let style = {};
  300. let image = {};
  301. const onTextNode = async(text) => {// eslint-disable-line no-unused-vars
  302. result.push({
  303. style: Object.assign({}, style),
  304. image,
  305. text
  306. });
  307. };
  308. const onStartNode = async(elemName, tail) => {// eslint-disable-line no-unused-vars
  309. switch (elemName) {
  310. case 'strong':
  311. style.bold = true;
  312. break;
  313. case 'emphasis':
  314. style.italic = true;
  315. break;
  316. case 'center':
  317. style.center = true;
  318. break;
  319. case 'image': {
  320. let attrs = sax.getAttrsSync(tail);
  321. let id = attrs.href.value;
  322. if (id) {
  323. let local = false;
  324. if (id[0] == '#') {
  325. id = id.substr(1);
  326. local = true;
  327. }
  328. image = {local, inline: false, id};
  329. }
  330. break;
  331. }
  332. }
  333. };
  334. const onEndNode = async(elemName) => {// eslint-disable-line no-unused-vars
  335. switch (elemName) {
  336. case 'strong':
  337. style.bold = false;
  338. break;
  339. case 'emphasis':
  340. style.italic = false;
  341. break;
  342. case 'center':
  343. style.center = false;
  344. break;
  345. case 'image':
  346. image = {};
  347. break;
  348. }
  349. };
  350. sax.parseSync(s, {
  351. onStartNode, onEndNode, onTextNode
  352. });
  353. //длинные слова (или белиберду без пробелов) тоже разобьем
  354. const maxWordLength = this.maxWordLength;
  355. const parts = result;
  356. result = [];
  357. for (const part of parts) {
  358. let p = part;
  359. if (!p.image.id) {
  360. let i = 0;
  361. let spaceIndex = -1;
  362. while (i < p.text.length) {
  363. if (p.text[i] == ' ')
  364. spaceIndex = i;
  365. if (i - spaceIndex >= maxWordLength && i < p.text.length - 1 &&
  366. this.measureText(p.text.substr(spaceIndex + 1, i - spaceIndex), p.style) >= this.w - this.p) {
  367. result.push({style: p.style, image: p.image, text: p.text.substr(0, i + 1)});
  368. p = {style: p.style, text: p.text.substr(i + 1)};
  369. spaceIndex = -1;
  370. i = -1;
  371. }
  372. i++;
  373. }
  374. }
  375. result.push(p);
  376. }
  377. return result;
  378. }
  379. splitToSlogi(word) {
  380. let result = [];
  381. const glas = new Set(['а', 'А', 'о', 'О', 'и', 'И', 'е', 'Е', 'ё', 'Ё', 'э', 'Э', 'ы', 'Ы', 'у', 'У', 'ю', 'Ю', 'я', 'Я']);
  382. const soglas = new Set([
  383. 'б', 'в', 'г', 'д', 'ж', 'з', 'й', 'к', 'л', 'м', 'н', 'п', 'р', 'с', 'т', 'ф', 'х', 'ц', 'ч', 'ш', 'щ',
  384. 'Б', 'В', 'Г', 'Д', 'Ж', 'З', 'Й', 'К', 'Л', 'М', 'Н', 'П', 'Р', 'С', 'Т', 'Ф', 'Х', 'Ч', 'Ц', 'Ш', 'Щ'
  385. ]);
  386. const znak = new Set(['ь', 'Ь', 'ъ', 'Ъ', 'й', 'Й']);
  387. const alpha = new Set([...glas, ...soglas, ...znak]);
  388. let slog = '';
  389. let slogLen = 0;
  390. const len = word.length;
  391. word += ' ';
  392. for (let i = 0; i < len; i++) {
  393. slog += word[i];
  394. if (alpha.has(word[i]))
  395. slogLen++;
  396. if (slogLen > 1 && i < len - 2 && (
  397. //гласная, а следом не 2 согласные буквы
  398. (glas.has(word[i]) && !(soglas.has(word[i + 1]) &&
  399. soglas.has(word[i + 2])) && alpha.has(word[i + 1]) && alpha.has(word[i + 2])
  400. ) ||
  401. //предыдущая не согласная буква, текущая согласная, а следом согласная и согласная|гласная буквы
  402. (alpha.has(word[i - 1]) && !soglas.has(word[i - 1]) &&
  403. soglas.has(word[i]) && soglas.has(word[i + 1]) &&
  404. (glas.has(word[i + 2]) || soglas.has(word[i + 2])) &&
  405. alpha.has(word[i + 1]) && alpha.has(word[i + 2])
  406. ) ||
  407. //мягкий или твердый знак или Й
  408. (znak.has(word[i]) && alpha.has(word[i + 1]) && alpha.has(word[i + 2])) ||
  409. (word[i] == '-')
  410. ) &&
  411. //нельзя оставлять окончания на ь, ъ, й
  412. !(znak.has(word[i + 2]) && !alpha.has(word[i + 3]))
  413. ) {
  414. result.push(slog);
  415. slog = '';
  416. slogLen = 0;
  417. }
  418. }
  419. if (slog)
  420. result.push(slog);
  421. return result;
  422. }
  423. parsePara(paraIndex) {
  424. const para = this.para[paraIndex];
  425. if (!this.force &&
  426. para.parsed &&
  427. para.parsed.w === this.w &&
  428. para.parsed.p === this.p &&
  429. para.parsed.wordWrap === this.wordWrap &&
  430. para.parsed.maxWordLength === this.maxWordLength &&
  431. para.parsed.font === this.font &&
  432. para.parsed.cutEmptyParagraphs === this.cutEmptyParagraphs &&
  433. para.parsed.addEmptyParagraphs === this.addEmptyParagraphs &&
  434. para.parsed.showImages === this.showImages &&
  435. para.parsed.imageHeightLines === this.imageHeightLines
  436. )
  437. return para.parsed;
  438. const parsed = {
  439. w: this.w,
  440. p: this.p,
  441. wordWrap: this.wordWrap,
  442. maxWordLength: this.maxWordLength,
  443. font: this.font,
  444. cutEmptyParagraphs: this.cutEmptyParagraphs,
  445. addEmptyParagraphs: this.addEmptyParagraphs,
  446. showImages: this.showImages,
  447. imageHeightLines: this.imageHeightLines,
  448. visible: !(
  449. (this.cutEmptyParagraphs && para.cut) ||
  450. (para.addIndex > this.addEmptyParagraphs)
  451. )
  452. };
  453. const lines = []; /* array of
  454. {
  455. begin: Number,
  456. end: Number,
  457. first: Boolean,
  458. last: Boolean,
  459. parts: array of {
  460. style: {bold: Boolean, italic: Boolean, center: Boolean},
  461. image: {local: Boolean, inline: Boolean, id: String, imageLine: Number, lineCount: Number, paraIndex: Number},
  462. text: String,
  463. }
  464. }*/
  465. let parts = this.splitToStyle(para.text);
  466. let line = {begin: para.offset, parts: []};
  467. let partText = '';//накапливаемый кусок со стилем
  468. let str = '';//измеряемая строка
  469. let prevStr = '';//строка без крайнего слова
  470. let j = 0;//номер строки
  471. let style = {};
  472. let ofs = 0;//смещение от начала параграфа para.offset
  473. // тут начинается самый замес, перенос по слогам и стилизация
  474. for (const part of parts) {
  475. style = part.style;
  476. //изображения
  477. if (part.image.id && !part.image.inline) {
  478. parsed.visible = this.showImages;
  479. const bin = this.binary[part.image.id];
  480. let lineCount = this.imageHeightLines;
  481. const c = Math.ceil(bin.h/this.lineHeight);
  482. lineCount = (c < lineCount ? c : lineCount);
  483. let i = 0;
  484. for (; i < lineCount - 1; i++) {
  485. line.end = para.offset + ofs;
  486. line.first = (j == 0);
  487. line.last = false;
  488. line.parts.push({style, text: ' ', image: {
  489. local: part.image.local,
  490. inline: false,
  491. id: part.image.id,
  492. imageLine: i,
  493. lineCount,
  494. paraIndex
  495. }});
  496. lines.push(line);
  497. line = {begin: line.end + 1, parts: []};
  498. ofs++;
  499. j++;
  500. }
  501. line.first = (j == 0);
  502. line.last = true;
  503. line.parts.push({style, text: ' ',
  504. image: {local: part.image.local, inline: false, id: part.image.id, imageLine: i, lineCount, paraIndex}});
  505. continue;
  506. }
  507. const words = part.text.split(' ');
  508. let sp1 = '';
  509. let sp2 = '';
  510. for (let i = 0; i < words.length; i++) {
  511. const word = words[i];
  512. ofs += word.length + (i < words.length - 1 ? 1 : 0);
  513. if (word == '' && i > 0 && i < words.length - 1)
  514. continue;
  515. str += sp1 + word;
  516. let p = (j == 0 ? parsed.p : 0);
  517. let w = this.measureText(str, style) + p;
  518. let wordTail = word;
  519. if (w > parsed.w && prevStr != '') {
  520. if (parsed.wordWrap) {//по слогам
  521. let slogi = this.splitToSlogi(word);
  522. if (slogi.length > 1) {
  523. let s = prevStr + sp1;
  524. let ss = sp1;
  525. let pw;
  526. const slogiLen = slogi.length;
  527. for (let k = 0; k < slogiLen - 1; k++) {
  528. let slog = slogi[0];
  529. let ww = this.measureText(s + slog + (slog[slog.length - 1] == '-' ? '' : '-'), style) + p;
  530. if (ww <= parsed.w) {
  531. s += slog;
  532. ss += slog;
  533. } else
  534. break;
  535. pw = ww;
  536. slogi.shift();
  537. }
  538. if (pw) {
  539. partText += ss + (ss[ss.length - 1] == '-' ? '' : '-');
  540. wordTail = slogi.join('');
  541. }
  542. }
  543. }
  544. if (partText != '')
  545. line.parts.push({style, text: partText});
  546. if (line.parts.length) {//корявенько, коррекция при переносе, отрефакторить не вышло
  547. let t = line.parts[line.parts.length - 1].text;
  548. if (t[t.length - 1] == ' ') {
  549. line.parts[line.parts.length - 1].text = t.trimRight();
  550. }
  551. }
  552. line.end = para.offset + ofs - wordTail.length - 1 - (i < words.length - 1 ? 1 : 0);
  553. if (line.end - line.begin < 0)
  554. console.error(`Parse error, empty line in paragraph ${paraIndex}`);
  555. line.first = (j == 0);
  556. line.last = false;
  557. lines.push(line);
  558. line = {begin: line.end + 1, parts: []};
  559. partText = '';
  560. sp2 = '';
  561. str = wordTail;
  562. j++;
  563. }
  564. prevStr = str;
  565. partText += sp2 + wordTail;
  566. sp1 = ' ';
  567. sp2 = ' ';
  568. }
  569. if (partText != '')
  570. line.parts.push({style, text: partText});
  571. partText = '';
  572. }
  573. if (line.parts.length) {//корявенько, коррекция при переносе
  574. let t = line.parts[line.parts.length - 1].text;
  575. if (t[t.length - 1] == ' ') {
  576. line.parts[line.parts.length - 1].text = t.trimRight();
  577. }
  578. line.end = para.offset + para.length - 1;
  579. if (line.end - line.begin < 0)
  580. console.error(`Parse error, empty line in paragraph ${paraIndex}`);
  581. line.first = (j == 0);
  582. line.last = true;
  583. lines.push(line);
  584. } else {//подстраховка
  585. if (lines.length) {
  586. line = lines[lines.length - 1];
  587. const end = para.offset + para.length - 1;
  588. if (line.end != end)
  589. console.error(`Parse error, wrong end in paragraph ${paraIndex}`);
  590. line.end = end;
  591. }
  592. }
  593. parsed.lines = lines;
  594. para.parsed = parsed;
  595. return parsed;
  596. }
  597. findLineIndex(bookPos, lines) {
  598. let result = undefined;
  599. //дихотомия
  600. let first = 0;
  601. let last = lines.length - 1;
  602. while (first < last) {
  603. let mid = first + Math.floor((last - first)/2);
  604. if (bookPos <= lines[mid].end)
  605. last = mid;
  606. else
  607. first = mid + 1;
  608. }
  609. if (last >= 0) {
  610. if (bookPos >= lines[last].begin && bookPos <= lines[last].end)
  611. result = last;
  612. }
  613. return result;
  614. }
  615. getLines(bookPos, n) {
  616. let result = [];
  617. let paraIndex = this.findParaIndex(bookPos);
  618. if (paraIndex === undefined)
  619. return null;
  620. if (n > 0) {
  621. let parsed = this.parsePara(paraIndex);
  622. let i = this.findLineIndex(bookPos, parsed.lines);
  623. if (i === undefined)
  624. return null;
  625. while (n > 0) {
  626. if (parsed.visible) {
  627. result.push(parsed.lines[i]);
  628. n--;
  629. }
  630. i++;
  631. if (i >= parsed.lines.length) {
  632. paraIndex++;
  633. if (paraIndex < this.para.length)
  634. parsed = this.parsePara(paraIndex);
  635. else
  636. break;
  637. i = 0;
  638. }
  639. }
  640. } else if (n < 0) {
  641. n = -n;
  642. let parsed = this.parsePara(paraIndex);
  643. let i = this.findLineIndex(bookPos, parsed.lines);
  644. if (i === undefined)
  645. return null;
  646. while (n > 0) {
  647. if (parsed.visible) {
  648. result.push(parsed.lines[i]);
  649. n--;
  650. }
  651. i--;
  652. if (i < 0) {
  653. paraIndex--;
  654. if (paraIndex >= 0)
  655. parsed = this.parsePara(paraIndex);
  656. else
  657. break;
  658. i = parsed.lines.length - 1;
  659. }
  660. }
  661. }
  662. if (!result.length)
  663. result = null;
  664. return result;
  665. }
  666. }