BookParser.js 29 KB

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