BookParser.js 34 KB

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