BookParser.js 45 KB

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