BookParser.js 40 KB

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