BookParser.js 37 KB

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