BookParser.js 42 KB

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