BookParser.js 42 KB

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