BookParser.js 39 KB

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