BookParser.js 34 KB

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