BookParser.js 39 KB

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