BookParser.js 45 KB

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