BookParser.js 30 KB

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