BookParser.js 42 KB

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