BookParser.js 26 KB

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