BookParser.js 31 KB

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