BookParser.js 41 KB

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