BookParser.js 27 KB

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