BookParser.js 40 KB

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