BookParser.js 37 KB

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