BookParser.js 42 KB

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