BookParser.js 32 KB

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