BookParser.js 39 KB

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