BookParser.js 29 KB

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