BookParser.js 39 KB

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