BookParser.js 41 KB

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