BookParser.js 26 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607608609610611612613614615616617618619620621622623624625626627628629630631632633634635636637638639640641642643644645646647648649650651652653654655656657658659660661662663664665666667668669670671672673674675676677678679680681682683684685686687688689690691692693694695696697698699700701702703704705706707708709710711712713714715716717718719720721722723724725726727728729730731732733734735736737738739740741742743744745746747748749750751752753754755756757758759760761762763764765766
  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: Boolean,
  297. imageId: String,
  298. text: String,
  299. }*/
  300. let style = {};
  301. let image = {};
  302. const onTextNode = async(text) => {// eslint-disable-line no-unused-vars
  303. result.push({
  304. style: Object.assign({}, style),
  305. image,
  306. text
  307. });
  308. };
  309. const onStartNode = async(elemName, tail) => {// eslint-disable-line no-unused-vars
  310. switch (elemName) {
  311. case 'strong':
  312. style.bold = true;
  313. break;
  314. case 'emphasis':
  315. style.italic = true;
  316. break;
  317. case 'center':
  318. style.center = true;
  319. break;
  320. case 'image': {
  321. let attrs = sax.getAttrsSync(tail);
  322. let id = attrs.href.value;
  323. if (id) {
  324. id = id.substr(1);
  325. image = {inline: false, id};
  326. }
  327. break;
  328. }
  329. }
  330. };
  331. const onEndNode = async(elemName) => {// eslint-disable-line no-unused-vars
  332. switch (elemName) {
  333. case 'strong':
  334. style.bold = false;
  335. break;
  336. case 'emphasis':
  337. style.italic = false;
  338. break;
  339. case 'center':
  340. style.center = false;
  341. break;
  342. case 'image':
  343. image = {};
  344. break;
  345. }
  346. };
  347. sax.parseSync(s, {
  348. onStartNode, onEndNode, onTextNode
  349. });
  350. //длинные слова (или белиберду без пробелов) тоже разобьем
  351. const maxWordLength = this.maxWordLength;
  352. const parts = result;
  353. result = [];
  354. for (const part of parts) {
  355. let p = part;
  356. if (!p.image.id) {
  357. let i = 0;
  358. let spaceIndex = -1;
  359. while (i < p.text.length) {
  360. if (p.text[i] == ' ')
  361. spaceIndex = i;
  362. if (i - spaceIndex >= maxWordLength && i < p.text.length - 1 &&
  363. this.measureText(p.text.substr(spaceIndex + 1, i - spaceIndex), p.style) >= this.w - this.p) {
  364. result.push({style: p.style, image: p.image, text: p.text.substr(0, i + 1)});
  365. p = {style: p.style, text: p.text.substr(i + 1)};
  366. spaceIndex = -1;
  367. i = -1;
  368. }
  369. i++;
  370. }
  371. }
  372. result.push(p);
  373. }
  374. return result;
  375. }
  376. splitToSlogi(word) {
  377. let result = [];
  378. const glas = new Set(['а', 'А', 'о', 'О', 'и', 'И', 'е', 'Е', 'ё', 'Ё', 'э', 'Э', 'ы', 'Ы', 'у', 'У', 'ю', 'Ю', 'я', 'Я']);
  379. const soglas = new Set([
  380. 'б', 'в', 'г', 'д', 'ж', 'з', 'й', 'к', 'л', 'м', 'н', 'п', 'р', 'с', 'т', 'ф', 'х', 'ц', 'ч', 'ш', 'щ',
  381. 'Б', 'В', 'Г', 'Д', 'Ж', 'З', 'Й', 'К', 'Л', 'М', 'Н', 'П', 'Р', 'С', 'Т', 'Ф', 'Х', 'Ч', 'Ц', 'Ш', 'Щ'
  382. ]);
  383. const znak = new Set(['ь', 'Ь', 'ъ', 'Ъ', 'й', 'Й']);
  384. const alpha = new Set([...glas, ...soglas, ...znak]);
  385. let slog = '';
  386. let slogLen = 0;
  387. const len = word.length;
  388. word += ' ';
  389. for (let i = 0; i < len; i++) {
  390. slog += word[i];
  391. if (alpha.has(word[i]))
  392. slogLen++;
  393. if (slogLen > 1 && i < len - 2 && (
  394. //гласная, а следом не 2 согласные буквы
  395. (glas.has(word[i]) && !(soglas.has(word[i + 1]) &&
  396. soglas.has(word[i + 2])) && alpha.has(word[i + 1]) && alpha.has(word[i + 2])
  397. ) ||
  398. //предыдущая не согласная буква, текущая согласная, а следом согласная и согласная|гласная буквы
  399. (alpha.has(word[i - 1]) && !soglas.has(word[i - 1]) &&
  400. soglas.has(word[i]) && soglas.has(word[i + 1]) &&
  401. (glas.has(word[i + 2]) || soglas.has(word[i + 2])) &&
  402. alpha.has(word[i + 1]) && alpha.has(word[i + 2])
  403. ) ||
  404. //мягкий или твердый знак или Й
  405. (znak.has(word[i]) && alpha.has(word[i + 1]) && alpha.has(word[i + 2])) ||
  406. (word[i] == '-')
  407. ) &&
  408. //нельзя оставлять окончания на ь, ъ, й
  409. !(znak.has(word[i + 2]) && !alpha.has(word[i + 3]))
  410. ) {
  411. result.push(slog);
  412. slog = '';
  413. slogLen = 0;
  414. }
  415. }
  416. if (slog)
  417. result.push(slog);
  418. return result;
  419. }
  420. parsePara(paraIndex) {
  421. const para = this.para[paraIndex];
  422. if (!this.force &&
  423. para.parsed &&
  424. para.parsed.w === this.w &&
  425. para.parsed.p === this.p &&
  426. para.parsed.wordWrap === this.wordWrap &&
  427. para.parsed.maxWordLength === this.maxWordLength &&
  428. para.parsed.font === this.font &&
  429. para.parsed.cutEmptyParagraphs === this.cutEmptyParagraphs &&
  430. para.parsed.addEmptyParagraphs === this.addEmptyParagraphs &&
  431. para.parsed.showImages === this.showImages &&
  432. para.parsed.imageHeightLines === this.imageHeightLines
  433. )
  434. return para.parsed;
  435. const parsed = {
  436. w: this.w,
  437. p: this.p,
  438. wordWrap: this.wordWrap,
  439. maxWordLength: this.maxWordLength,
  440. font: this.font,
  441. cutEmptyParagraphs: this.cutEmptyParagraphs,
  442. addEmptyParagraphs: this.addEmptyParagraphs,
  443. showImages: this.showImages,
  444. imageHeightLines: this.imageHeightLines,
  445. visible: !(
  446. (this.cutEmptyParagraphs && para.cut) ||
  447. (para.addIndex > this.addEmptyParagraphs)
  448. )
  449. };
  450. const lines = []; /* array of
  451. {
  452. begin: Number,
  453. end: Number,
  454. first: Boolean,
  455. last: Boolean,
  456. parts: array of {
  457. style: {bold: Boolean, italic: Boolean, center: Boolean},
  458. image: {inline: Boolean, id: String, imageLine: Number, lineCount: Number, resize: Boolean},
  459. text: String,
  460. }
  461. }*/
  462. let parts = this.splitToStyle(para.text);
  463. let line = {begin: para.offset, parts: []};
  464. let partText = '';//накапливаемый кусок со стилем
  465. let str = '';//измеряемая строка
  466. let prevStr = '';//строка без крайнего слова
  467. let j = 0;//номер строки
  468. let style = {};
  469. let ofs = 0;//смещение от начала параграфа para.offset
  470. // тут начинается самый замес, перенос по слогам и стилизация
  471. for (const part of parts) {
  472. style = part.style;
  473. //изображения
  474. if (part.image.id && !part.image.inline) {
  475. const bin = this.binary[part.image.id];
  476. let lineCount = this.imageHeightLines;
  477. const c = Math.ceil(bin.h/this.lineHeight);
  478. lineCount = (c < lineCount ? c : lineCount);
  479. let i = 0;
  480. for (; i < lineCount - 1; i++) {
  481. line.end = para.offset + ofs;
  482. line.first = (j == 0);
  483. line.last = false;
  484. line.parts.push({style, text: '!', image: {inline: false, id: part.image.id, imageLine: i, lineCount, resize: (c > lineCount)}});
  485. lines.push(line);
  486. line = {begin: line.end + 1, parts: []};
  487. ofs++;
  488. j++;
  489. }
  490. line.first = (j == 0);
  491. line.last = true;
  492. line.parts.push({style, text: '!', image: {inline: false, id: part.image.id, imageLine: i, lineCount, resize: (c > lineCount)}});
  493. continue;
  494. }
  495. const words = part.text.split(' ');
  496. let sp1 = '';
  497. let sp2 = '';
  498. for (let i = 0; i < words.length; i++) {
  499. const word = words[i];
  500. ofs += word.length + (i < words.length - 1 ? 1 : 0);
  501. if (word == '' && i > 0 && i < words.length - 1)
  502. continue;
  503. str += sp1 + word;
  504. let p = (j == 0 ? parsed.p : 0);
  505. let w = this.measureText(str, style) + p;
  506. let wordTail = word;
  507. if (w > parsed.w && prevStr != '') {
  508. if (parsed.wordWrap) {//по слогам
  509. let slogi = this.splitToSlogi(word);
  510. if (slogi.length > 1) {
  511. let s = prevStr + sp1;
  512. let ss = sp1;
  513. let pw;
  514. const slogiLen = slogi.length;
  515. for (let k = 0; k < slogiLen - 1; k++) {
  516. let slog = slogi[0];
  517. let ww = this.measureText(s + slog + (slog[slog.length - 1] == '-' ? '' : '-'), style) + p;
  518. if (ww <= parsed.w) {
  519. s += slog;
  520. ss += slog;
  521. } else
  522. break;
  523. pw = ww;
  524. slogi.shift();
  525. }
  526. if (pw) {
  527. partText += ss + (ss[ss.length - 1] == '-' ? '' : '-');
  528. wordTail = slogi.join('');
  529. }
  530. }
  531. }
  532. if (partText != '')
  533. line.parts.push({style, text: partText});
  534. if (line.parts.length) {//корявенько, коррекция при переносе, отрефакторить не вышло
  535. let t = line.parts[line.parts.length - 1].text;
  536. if (t[t.length - 1] == ' ') {
  537. line.parts[line.parts.length - 1].text = t.trimRight();
  538. }
  539. }
  540. line.end = para.offset + ofs - wordTail.length - 1 - (i < words.length - 1 ? 1 : 0);
  541. if (line.end - line.begin < 0)
  542. console.error(`Parse error, empty line in paragraph ${paraIndex}`);
  543. line.first = (j == 0);
  544. line.last = false;
  545. lines.push(line);
  546. line = {begin: line.end + 1, parts: []};
  547. partText = '';
  548. sp2 = '';
  549. str = wordTail;
  550. j++;
  551. }
  552. prevStr = str;
  553. partText += sp2 + wordTail;
  554. sp1 = ' ';
  555. sp2 = ' ';
  556. }
  557. if (partText != '')
  558. line.parts.push({style, text: partText});
  559. partText = '';
  560. }
  561. if (line.parts.length) {//корявенько, коррекция при переносе
  562. let t = line.parts[line.parts.length - 1].text;
  563. if (t[t.length - 1] == ' ') {
  564. line.parts[line.parts.length - 1].text = t.trimRight();
  565. }
  566. line.end = para.offset + para.length - 1;
  567. if (line.end - line.begin < 0)
  568. console.error(`Parse error, empty line in paragraph ${paraIndex}`);
  569. line.first = (j == 0);
  570. line.last = true;
  571. lines.push(line);
  572. } else {//подстраховка
  573. if (lines.length) {
  574. line = lines[lines.length - 1];
  575. const end = para.offset + para.length - 1;
  576. if (line.end != end)
  577. console.error(`Parse error, wrong end in paragraph ${paraIndex}`);
  578. line.end = end;
  579. }
  580. }
  581. parsed.lines = lines;
  582. para.parsed = parsed;
  583. return parsed;
  584. }
  585. findLineIndex(bookPos, lines) {
  586. let result = undefined;
  587. //дихотомия
  588. let first = 0;
  589. let last = lines.length - 1;
  590. while (first < last) {
  591. let mid = first + Math.floor((last - first)/2);
  592. if (bookPos <= lines[mid].end)
  593. last = mid;
  594. else
  595. first = mid + 1;
  596. }
  597. if (last >= 0) {
  598. if (bookPos >= lines[last].begin && bookPos <= lines[last].end)
  599. result = last;
  600. }
  601. return result;
  602. }
  603. getLines(bookPos, n) {
  604. let result = [];
  605. let paraIndex = this.findParaIndex(bookPos);
  606. if (paraIndex === undefined)
  607. return null;
  608. if (n > 0) {
  609. let parsed = this.parsePara(paraIndex);
  610. let i = this.findLineIndex(bookPos, parsed.lines);
  611. if (i === undefined)
  612. return null;
  613. while (n > 0) {
  614. if (parsed.visible) {
  615. result.push(parsed.lines[i]);
  616. n--;
  617. }
  618. i++;
  619. if (i >= parsed.lines.length) {
  620. paraIndex++;
  621. if (paraIndex < this.para.length)
  622. parsed = this.parsePara(paraIndex);
  623. else
  624. break;
  625. i = 0;
  626. }
  627. }
  628. } else if (n < 0) {
  629. n = -n;
  630. let parsed = this.parsePara(paraIndex);
  631. let i = this.findLineIndex(bookPos, parsed.lines);
  632. if (i === undefined)
  633. return null;
  634. while (n > 0) {
  635. if (parsed.visible) {
  636. result.push(parsed.lines[i]);
  637. n--;
  638. }
  639. i--;
  640. if (i < 0) {
  641. paraIndex--;
  642. if (paraIndex >= 0)
  643. parsed = this.parsePara(paraIndex);
  644. else
  645. break;
  646. i = parsed.lines.length - 1;
  647. }
  648. }
  649. }
  650. if (!result.length)
  651. result = null;
  652. return result;
  653. }
  654. }