BookParser.js 41 KB

1234567891011121314151617181920212223242526272829303132333435363738394041424344454647484950515253545556575859606162636465666768697071727374757677787980818283848586878889909192939495969798991001011021031041051061071081091101111121131141151161171181191201211221231241251261271281291301311321331341351361371381391401411421431441451461471481491501511521531541551561571581591601611621631641651661671681691701711721731741751761771781791801811821831841851861871881891901911921931941951961971981992002012022032042052062072082092102112122132142152162172182192202212222232242252262272282292302312322332342352362372382392402412422432442452462472482492502512522532542552562572582592602612622632642652662672682692702712722732742752762772782792802812822832842852862872882892902912922932942952962972982993003013023033043053063073083093103113123133143153163173183193203213223233243253263273283293303313323333343353363373383393403413423433443453463473483493503513523533543553563573583593603613623633643653663673683693703713723733743753763773783793803813823833843853863873883893903913923933943953963973983994004014024034044054064074084094104114124134144154164174184194204214224234244254264274284294304314324334344354364374384394404414424434444454464474484494504514524534544554564574584594604614624634644654664674684694704714724734744754764774784794804814824834844854864874884894904914924934944954964974984995005015025035045055065075085095105115125135145155165175185195205215225235245255265275285295305315325335345355365375385395405415425435445455465475485495505515525535545555565575585595605615625635645655665675685695705715725735745755765775785795805815825835845855865875885895905915925935945955965975985996006016026036046056066076086096106116126136146156166176186196206216226236246256266276286296306316326336346356366376386396406416426436446456466476486496506516526536546556566576586596606616626636646656666676686696706716726736746756766776786796806816826836846856866876886896906916926936946956966976986997007017027037047057067077087097107117127137147157167177187197207217227237247257267277287297307317327337347357367377387397407417427437447457467477487497507517527537547557567577587597607617627637647657667677687697707717727737747757767777787797807817827837847857867877887897907917927937947957967977987998008018028038048058068078088098108118128138148158168178188198208218228238248258268278288298308318328338348358368378388398408418428438448458468478488498508518528538548558568578588598608618628638648658668678688698708718728738748758768778788798808818828838848858868878888898908918928938948958968978988999009019029039049059069079089099109119129139149159169179189199209219229239249259269279289299309319329339349359369379389399409419429439449459469479489499509519529539549559569579589599609619629639649659669679689699709719729739749759769779789799809819829839849859869879889899909919929939949959969979989991000100110021003100410051006100710081009101010111012101310141015101610171018101910201021102210231024102510261027102810291030103110321033103410351036103710381039104010411042104310441045104610471048104910501051105210531054105510561057105810591060106110621063106410651066106710681069107010711072107310741075107610771078107910801081108210831084108510861087108810891090109110921093109410951096109710981099110011011102110311041105110611071108110911101111111211131114111511161117111811191120112111221123
  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. bold = true;
  338. space += 1;
  339. }
  340. }
  341. };
  342. const onEndNode = (elemName) => {// eslint-disable-line no-unused-vars
  343. if (tag == elemName) {
  344. if (tag == 'binary') {
  345. binaryId = '';
  346. }
  347. if (path.indexOf('/fictionbook/body') == 0) {
  348. if (tag == 'title') {
  349. isFirstTitlePara = false;
  350. bold = false;
  351. center = false;
  352. inTitle = false;
  353. }
  354. if (tag == 'section') {
  355. sectionLevel--;
  356. }
  357. if (tag == 'emphasis' || tag == 'strong' || tag == 'sup' || tag == 'sub') {
  358. growParagraph(`</${tag}>`, 0);
  359. }
  360. if (tag == 'p') {
  361. inPara = false;
  362. }
  363. if (tag == 'subtitle') {
  364. isFirstTitlePara = false;
  365. bold = false;
  366. center = false;
  367. inSubtitle = false;
  368. }
  369. if (tag == 'epigraph' || tag == 'annotation') {
  370. italic = false;
  371. space -= 1;
  372. if (tag == 'annotation')
  373. newParagraph();
  374. }
  375. if (tag == 'stanza') {
  376. newParagraph();
  377. }
  378. if (tag == 'text-author') {
  379. bold = false;
  380. space -= 1;
  381. newParagraph();
  382. }
  383. }
  384. path = path.substr(0, path.length - tag.length - 1);
  385. let i = path.lastIndexOf('/');
  386. if (i >= 0) {
  387. tag = path.substr(i + 1);
  388. } else {
  389. tag = path;
  390. }
  391. }
  392. };
  393. const onTextNode = (text) => {// eslint-disable-line no-unused-vars
  394. text = he.decode(text);
  395. text = text.replace(/>/g, '&gt;').replace(/</g, '&lt;').replace(/[\t\n\r\xa0]/g, ' ');
  396. if (text && text.trim() == '')
  397. text = ' ';
  398. if (!text)
  399. return;
  400. const authorLength = (fb2.author && fb2.author.length ? fb2.author.length : 0);
  401. switch (path) {
  402. case '/fictionbook/description/title-info/author/first-name':
  403. if (authorLength)
  404. fb2.author[authorLength - 1].firstName = text;
  405. break;
  406. case '/fictionbook/description/title-info/author/middle-name':
  407. if (authorLength)
  408. fb2.author[authorLength - 1].middleName = text;
  409. break;
  410. case '/fictionbook/description/title-info/author/last-name':
  411. if (authorLength)
  412. fb2.author[authorLength - 1].lastName = text;
  413. break;
  414. case '/fictionbook/description/title-info/genre':
  415. fb2.genre = text;
  416. break;
  417. case '/fictionbook/description/title-info/date':
  418. fb2.date = text;
  419. break;
  420. case '/fictionbook/description/title-info/book-title':
  421. fb2.bookTitle = text;
  422. break;
  423. case '/fictionbook/description/title-info/id':
  424. fb2.id = text;
  425. break;
  426. }
  427. if (path.indexOf('/fictionbook/description/title-info/annotation') == 0) {
  428. if (!fb2.annotation)
  429. fb2.annotation = '';
  430. if (tag != 'annotation')
  431. fb2.annotation += `<${tag}>${text}</${tag}>`;
  432. else
  433. fb2.annotation += text;
  434. }
  435. if (binaryId) {
  436. if (!this.sets.isTesting) {
  437. dimPromises.push(getImageDimensions(binaryId, binaryType, text));
  438. } else {
  439. dimPromises.push(this.sets.getImageDimensions(this, binaryId, binaryType, text));
  440. }
  441. }
  442. if (path.indexOf('/fictionbook/body/title') == 0 ||
  443. path.indexOf('/fictionbook/body/section') == 0 ||
  444. path.indexOf('/fictionbook/body/epigraph') == 0
  445. ) {
  446. let tOpen = (center ? '<center>' : '');
  447. tOpen += (bold ? '<strong>' : '');
  448. tOpen += (italic ? '<emphasis>' : '');
  449. tOpen += (space ? `<space w="${space}">` : '');
  450. let tClose = (space ? '</space>' : '');
  451. tClose += (italic ? '</emphasis>' : '');
  452. tClose += (bold ? '</strong>' : '');
  453. tClose += (center ? '</center>' : '');
  454. if (text != ' ')
  455. growParagraph(`${tOpen}${text}${tClose}`, text.length);
  456. else
  457. growParagraph(' ', 1);
  458. }
  459. };
  460. const onProgress = async(prog) => {
  461. await utils.sleep(1);
  462. callback(prog);
  463. };
  464. await sax.parse(data, {
  465. onStartNode, onEndNode, onTextNode, onProgress
  466. });
  467. correctCurrentPara();
  468. if (dimPromises.length) {
  469. try {
  470. await Promise.all(dimPromises);
  471. } catch (e) {
  472. //
  473. }
  474. }
  475. this.fb2 = fb2;
  476. this.para = para;
  477. this.textLength = paraOffset;
  478. callback(100);
  479. await utils.sleep(10);
  480. return {fb2};
  481. }
  482. imageHrefToId(id) {
  483. let local = false;
  484. if (id[0] == '#') {
  485. id = id.substr(1);
  486. local = true;
  487. }
  488. return {id, local};
  489. }
  490. findParaIndex(bookPos) {
  491. let result = undefined;
  492. //дихотомия
  493. let first = 0;
  494. let last = this.para.length - 1;
  495. while (first < last) {
  496. let mid = first + Math.floor((last - first)/2);
  497. if (bookPos <= this.para[mid].offset + this.para[mid].length - 1)
  498. last = mid;
  499. else
  500. first = mid + 1;
  501. }
  502. if (last >= 0) {
  503. const ofs = this.para[last].offset;
  504. if (bookPos >= ofs && bookPos < ofs + this.para[last].length)
  505. result = last;
  506. }
  507. return result;
  508. }
  509. splitToStyle(s) {
  510. let result = [];/*array of {
  511. style: {bold: Boolean, italic: Boolean, sup: Boolean, sub: Boolean, center: Boolean, space: Number},
  512. image: {local: Boolean, inline: Boolean, id: String},
  513. text: String,
  514. }*/
  515. let style = {};
  516. let image = {};
  517. //оптимизация по памяти
  518. const copyStyle = (s) => {
  519. const r = {};
  520. for (const prop in s) {
  521. if (s[prop])
  522. r[prop] = s[prop];
  523. }
  524. return r;
  525. };
  526. const onTextNode = async(text) => {// eslint-disable-line no-unused-vars
  527. result.push({
  528. style: copyStyle(style),
  529. image,
  530. text
  531. });
  532. };
  533. const onStartNode = async(elemName, tail) => {// eslint-disable-line no-unused-vars
  534. switch (elemName) {
  535. case 'strong':
  536. style.bold = true;
  537. break;
  538. case 'emphasis':
  539. style.italic = true;
  540. break;
  541. case 'sup':
  542. style.sup = true;
  543. break;
  544. case 'sub':
  545. style.sub = true;
  546. break;
  547. case 'center':
  548. style.center = true;
  549. break;
  550. case 'space': {
  551. let attrs = sax.getAttrsSync(tail);
  552. if (attrs.w && attrs.w.value)
  553. style.space = attrs.w.value;
  554. break;
  555. }
  556. case 'image': {
  557. let attrs = sax.getAttrsSync(tail);
  558. if (attrs.href && attrs.href.value) {
  559. image = this.imageHrefToId(attrs.href.value);
  560. image.inline = false;
  561. image.num = (attrs.num && attrs.num.value ? attrs.num.value : 0);
  562. }
  563. break;
  564. }
  565. case 'image-inline': {
  566. let attrs = sax.getAttrsSync(tail);
  567. if (attrs.href && attrs.href.value) {
  568. const img = this.imageHrefToId(attrs.href.value);
  569. img.inline = true;
  570. img.num = (attrs.num && attrs.num.value ? attrs.num.value : 0);
  571. result.push({
  572. style: copyStyle(style),
  573. image: img,
  574. text: ''
  575. });
  576. }
  577. break;
  578. }
  579. }
  580. };
  581. const onEndNode = async(elemName) => {// eslint-disable-line no-unused-vars
  582. switch (elemName) {
  583. case 'strong':
  584. style.bold = false;
  585. break;
  586. case 'emphasis':
  587. style.italic = false;
  588. break;
  589. case 'sup':
  590. style.sup = false;
  591. break;
  592. case 'sub':
  593. style.sub = false;
  594. break;
  595. case 'center':
  596. style.center = false;
  597. break;
  598. case 'space':
  599. style.space = 0;
  600. break;
  601. case 'image':
  602. image = {};
  603. break;
  604. case 'image-inline':
  605. break;
  606. }
  607. };
  608. sax.parseSync(s, {
  609. onStartNode, onEndNode, onTextNode
  610. });
  611. //длинные слова (или белиберду без пробелов) тоже разобьем
  612. const maxWordLength = this.sets.maxWordLength;
  613. const parts = result;
  614. result = [];
  615. for (const part of parts) {
  616. let p = part;
  617. if (!p.image.id) {
  618. let i = 0;
  619. let spaceIndex = -1;
  620. while (i < p.text.length) {
  621. if (p.text[i] == ' ')
  622. spaceIndex = i;
  623. if (i - spaceIndex >= maxWordLength && i < p.text.length - 1 &&
  624. this.measureText(p.text.substr(spaceIndex + 1, i - spaceIndex), p.style) >= this.sets.w - this.sets.p) {
  625. result.push({style: p.style, image: p.image, text: p.text.substr(0, i + 1)});
  626. p = {style: p.style, image: p.image, text: p.text.substr(i + 1)};
  627. spaceIndex = -1;
  628. i = -1;
  629. }
  630. i++;
  631. }
  632. }
  633. result.push(p);
  634. }
  635. return result;
  636. }
  637. splitToSlogi(word) {
  638. let result = [];
  639. const len = word.length;
  640. if (len > 3) {
  641. let slog = '';
  642. let slogLen = 0;
  643. word += ' ';
  644. for (let i = 0; i < len; i++) {
  645. slog += word[i];
  646. if (alpha.has(word[i]))
  647. slogLen++;
  648. if (slogLen > 1 && i < len - 2 && (
  649. //гласная, а следом не 2 согласные буквы
  650. (glas.has(word[i]) && !( soglas.has(word[i + 1]) && soglas.has(word[i + 2]) ) &&
  651. alpha.has(word[i + 1]) && alpha.has(word[i + 2])
  652. ) ||
  653. //предыдущая не согласная буква, текущая согласная, а следом согласная и согласная|гласная буквы
  654. (alpha.has(word[i - 1]) && !soglas.has(word[i - 1]) && soglas.has(word[i]) && soglas.has(word[i + 1]) &&
  655. ( glas.has(word[i + 2]) || soglas.has(word[i + 2]) ) &&
  656. alpha.has(word[i + 1]) && alpha.has(word[i + 2])
  657. ) ||
  658. //мягкий или твердый знак или Й
  659. (znak.has(word[i]) && alpha.has(word[i + 1]) && alpha.has(word[i + 2])) ||
  660. (word[i] == '-')
  661. ) &&
  662. //нельзя оставлять окончания на ь, ъ, й
  663. !(znak.has(word[i + 2]) && !alpha.has(word[i + 3]))
  664. ) {
  665. result.push(slog);
  666. slog = '';
  667. slogLen = 0;
  668. }
  669. }
  670. if (slog)
  671. result.push(slog);
  672. } else {
  673. result.push(word);
  674. }
  675. return result;
  676. }
  677. parsePara(paraIndex) {
  678. const para = this.para[paraIndex];
  679. const s = this.sets;
  680. //перераспарсиваем только при изменении одного из параметров
  681. if (!this.force &&
  682. para.parsed &&
  683. para.parsed.p === s.p &&
  684. para.parsed.w === s.w &&
  685. para.parsed.font === s.font &&
  686. para.parsed.fontSize === s.fontSize &&
  687. para.parsed.wordWrap === s.wordWrap &&
  688. para.parsed.cutEmptyParagraphs === s.cutEmptyParagraphs &&
  689. para.parsed.addEmptyParagraphs === s.addEmptyParagraphs &&
  690. para.parsed.maxWordLength === s.maxWordLength &&
  691. para.parsed.lineHeight === s.lineHeight &&
  692. para.parsed.showImages === s.showImages &&
  693. para.parsed.imageHeightLines === s.imageHeightLines &&
  694. para.parsed.imageFitWidth === s.imageFitWidth &&
  695. para.parsed.compactTextPerc === s.compactTextPerc &&
  696. para.parsed.testWidth === s.testWidth
  697. )
  698. return para.parsed;
  699. const parsed = {
  700. p: s.p,
  701. w: s.w,
  702. font: s.font,
  703. fontSize: s.fontSize,
  704. wordWrap: s.wordWrap,
  705. cutEmptyParagraphs: s.cutEmptyParagraphs,
  706. addEmptyParagraphs: s.addEmptyParagraphs,
  707. maxWordLength: s.maxWordLength,
  708. lineHeight: s.lineHeight,
  709. showImages: s.showImages,
  710. imageHeightLines: s.imageHeightLines,
  711. imageFitWidth: s.imageFitWidth,
  712. compactTextPerc: s.compactTextPerc,
  713. testWidth: s.testWidth,
  714. visible: true, //вычисляется позже
  715. };
  716. const lines = []; /* array of
  717. {
  718. begin: Number,
  719. end: Number,
  720. first: Boolean,
  721. last: Boolean,
  722. parts: array of {
  723. style: {bold: Boolean, italic: Boolean, center: Boolean},
  724. image: {local: Boolean, inline: Boolean, id: String, imageLine: Number, lineCount: Number, paraIndex: Number, w: Number, h: Number},
  725. text: String,
  726. }
  727. }*/
  728. let parts = this.splitToStyle(para.text);
  729. //инициализация парсера
  730. let line = {begin: para.offset, parts: []};
  731. let paragraphText = '';//текст параграфа
  732. let partText = '';//накапливаемый кусок со стилем
  733. let str = '';//измеряемая строка
  734. let prevStr = '';//строка без крайнего слова
  735. let j = 0;//номер строки
  736. let style = {};
  737. let ofs = 0;//смещение от начала параграфа para.offset
  738. let imgW = 0;
  739. let imageInPara = false;
  740. const compactWidth = this.measureText('W', {})*parsed.compactTextPerc/100;
  741. // тут начинается самый замес, перенос по слогам и стилизация, а также изображения
  742. for (const part of parts) {
  743. style = part.style;
  744. paragraphText += part.text;
  745. //изображения
  746. if (part.image.id && !part.image.inline) {
  747. imageInPara = true;
  748. let bin = this.binary[part.image.id];
  749. if (!bin)
  750. bin = {h: 1, w: 1};
  751. let lineCount = parsed.imageHeightLines;
  752. let c = Math.ceil(bin.h/parsed.lineHeight);
  753. const maxH = lineCount*parsed.lineHeight;
  754. let maxH2 = maxH;
  755. if (parsed.imageFitWidth && bin.w > parsed.w) {
  756. maxH2 = bin.h*parsed.w/bin.w;
  757. c = Math.ceil(maxH2/parsed.lineHeight);
  758. }
  759. lineCount = (c < lineCount ? c : lineCount);
  760. let imageHeight = (maxH2 < maxH ? maxH2 : maxH);
  761. imageHeight = (imageHeight <= bin.h ? imageHeight : bin.h);
  762. let imageWidth = (bin.h > imageHeight ? bin.w*imageHeight/bin.h : bin.w);
  763. let i = 0;
  764. for (; i < lineCount - 1; i++) {
  765. line.end = para.offset + ofs;
  766. line.first = (j == 0);
  767. line.last = false;
  768. line.parts.push({style, text: ' ', image: {
  769. local: part.image.local,
  770. inline: false,
  771. id: part.image.id,
  772. imageLine: i,
  773. lineCount,
  774. paraIndex,
  775. w: imageWidth,
  776. h: imageHeight,
  777. num: part.image.num
  778. }});
  779. lines.push(line);
  780. line = {begin: line.end + 1, parts: []};
  781. ofs++;
  782. j++;
  783. }
  784. line.first = (j == 0);
  785. line.last = true;
  786. line.parts.push({style, text: ' ',
  787. image: {local: part.image.local, inline: false, id: part.image.id,
  788. imageLine: i, lineCount, paraIndex, w: imageWidth, h: imageHeight, num: part.image.num}
  789. });
  790. continue;
  791. }
  792. if (part.image.id && part.image.inline && parsed.showImages) {
  793. const bin = this.binary[part.image.id];
  794. if (bin) {
  795. let imgH = (bin.h > parsed.fontSize ? parsed.fontSize : bin.h);
  796. imgW += bin.w*imgH/bin.h;
  797. line.parts.push({style, text: '',
  798. image: {local: part.image.local, inline: true, id: part.image.id, num: part.image.num}});
  799. }
  800. }
  801. let words = part.text.split(' ');
  802. let sp1 = '';
  803. let sp2 = '';
  804. for (let i = 0; i < words.length; i++) {
  805. const word = words[i];
  806. ofs += word.length + (i < words.length - 1 ? 1 : 0);
  807. if (word == '' && i > 0 && i < words.length - 1)
  808. continue;
  809. str += sp1 + word;
  810. let p = (j == 0 ? parsed.p : 0) + imgW;
  811. p = (style.space ? p + parsed.p*style.space : p);
  812. let w = this.measureText(str, style) + p;
  813. let wordTail = word;
  814. if (w > parsed.w + compactWidth && prevStr != '') {
  815. if (parsed.wordWrap) {//по слогам
  816. let slogi = this.splitToSlogi(word);
  817. if (slogi.length > 1) {
  818. let s = prevStr + sp1;
  819. let ss = sp1;
  820. let pw;
  821. const slogiLen = slogi.length;
  822. for (let k = 0; k < slogiLen - 1; k++) {
  823. let slog = slogi[0];
  824. let ww = this.measureText(s + slog + (slog[slog.length - 1] == '-' ? '' : '-'), style) + p;
  825. if (ww <= parsed.w + compactWidth) {
  826. s += slog;
  827. ss += slog;
  828. } else
  829. break;
  830. pw = ww;
  831. slogi.shift();
  832. }
  833. if (pw) {
  834. partText += ss + (ss[ss.length - 1] == '-' ? '' : '-');
  835. wordTail = slogi.join('');
  836. }
  837. }
  838. }
  839. if (partText != '')
  840. line.parts.push({style, text: partText});
  841. if (line.parts.length) {//корявенько, коррекция при переносе, отрефакторить не вышло
  842. let t = line.parts[line.parts.length - 1].text;
  843. if (t[t.length - 1] == ' ') {
  844. line.parts[line.parts.length - 1].text = t.trimRight();
  845. }
  846. }
  847. line.end = para.offset + ofs - wordTail.length - 1 - (i < words.length - 1 ? 1 : 0);
  848. if (line.end - line.begin < 0)
  849. console.error(`Parse error, empty line in paragraph ${paraIndex}`);
  850. line.first = (j == 0);
  851. line.last = false;
  852. lines.push(line);
  853. line = {begin: line.end + 1, parts: []};
  854. partText = '';
  855. sp2 = '';
  856. str = wordTail;
  857. imgW = 0;
  858. j++;
  859. }
  860. prevStr = str;
  861. partText += sp2 + wordTail;
  862. sp1 = ' ';
  863. sp2 = ' ';
  864. }
  865. if (partText != '')
  866. line.parts.push({style, text: partText});
  867. partText = '';
  868. }
  869. if (line.parts.length) {//корявенько, коррекция при переносе
  870. let t = line.parts[line.parts.length - 1].text;
  871. if (t[t.length - 1] == ' ') {
  872. line.parts[line.parts.length - 1].text = t.trimRight();
  873. }
  874. line.end = para.offset + para.length - 1;
  875. if (line.end - line.begin < 0)
  876. console.error(`Parse error, empty line in paragraph ${paraIndex}`);
  877. line.first = (j == 0);
  878. line.last = true;
  879. lines.push(line);
  880. } else {//подстраховка
  881. if (lines.length) {
  882. line = lines[lines.length - 1];
  883. const end = para.offset + para.length - 1;
  884. if (line.end != end)
  885. console.error(`Parse error, wrong end in paragraph ${paraIndex}`);
  886. line.end = end;
  887. }
  888. }
  889. //parsed.visible
  890. if (imageInPara) {
  891. parsed.visible = parsed.showImages;
  892. } else {
  893. parsed.visible = !(
  894. (para.addIndex > parsed.addEmptyParagraphs) ||
  895. (para.addIndex == 0 && parsed.cutEmptyParagraphs && paragraphText.trim() == '')
  896. );
  897. }
  898. parsed.lines = lines;
  899. para.parsed = parsed;
  900. return parsed;
  901. }
  902. findLineIndex(bookPos, lines) {
  903. let result = undefined;
  904. //дихотомия
  905. let first = 0;
  906. let last = lines.length - 1;
  907. while (first < last) {
  908. let mid = first + Math.floor((last - first)/2);
  909. if (bookPos <= lines[mid].end)
  910. last = mid;
  911. else
  912. first = mid + 1;
  913. }
  914. if (last >= 0) {
  915. if (bookPos >= lines[last].begin && bookPos <= lines[last].end)
  916. result = last;
  917. }
  918. return result;
  919. }
  920. getLines(bookPos, n) {
  921. let result = [];
  922. let paraIndex = this.findParaIndex(bookPos);
  923. if (paraIndex === undefined)
  924. return null;
  925. if (n > 0) {
  926. let parsed = this.parsePara(paraIndex);
  927. let i = this.findLineIndex(bookPos, parsed.lines);
  928. if (i === undefined)
  929. return null;
  930. while (n > 0) {
  931. if (parsed.visible) {
  932. result.push(parsed.lines[i]);
  933. n--;
  934. }
  935. i++;
  936. if (i >= parsed.lines.length) {
  937. paraIndex++;
  938. if (paraIndex < this.para.length)
  939. parsed = this.parsePara(paraIndex);
  940. else
  941. break;
  942. i = 0;
  943. }
  944. }
  945. } else if (n < 0) {
  946. n = -n;
  947. let parsed = this.parsePara(paraIndex);
  948. let i = this.findLineIndex(bookPos, parsed.lines);
  949. if (i === undefined)
  950. return null;
  951. while (n > 0) {
  952. if (parsed.visible) {
  953. result.push(parsed.lines[i]);
  954. n--;
  955. }
  956. i--;
  957. if (i < 0) {
  958. paraIndex--;
  959. if (paraIndex >= 0)
  960. parsed = this.parsePara(paraIndex);
  961. else
  962. break;
  963. i = parsed.lines.length - 1;
  964. }
  965. }
  966. }
  967. if (!result.length)
  968. result = null;
  969. return result;
  970. }
  971. }