BookParser.js 41 KB

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