BookParser.js 45 KB

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