BookParser.js 31 KB

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