SettingsPage.vue 20 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597
  1. <template lang="includer">
  2. <Window ref="window" height="95%" width="600px" @close="close">
  3. <template slot="header">
  4. Настройки
  5. </template>
  6. <div class="col row">
  7. <div class="full-height">
  8. <q-tabs
  9. ref="tabs"
  10. class="bg-grey-3 text-black"
  11. v-model="selectedTab"
  12. left-icon="la la-caret-up"
  13. right-icon="la la-caret-down"
  14. active-color="white"
  15. active-bg-color="primary"
  16. indicator-color="black"
  17. vertical
  18. no-caps
  19. stretch
  20. inline-label
  21. >
  22. <div v-show="tabsScrollable" class="q-pt-lg"/>
  23. <q-tab class="tab" name="profiles" icon="la la-users" label="Профили" />
  24. <q-tab class="tab" name="view" icon="la la-eye" label="Вид" />
  25. <q-tab class="tab" name="buttons" icon="la la-grip-horizontal" label="Кнопки" />
  26. <q-tab class="tab" name="keys" icon="la la-gamepad" label="Управление" />
  27. <q-tab class="tab" name="pagemove" icon="la la-school" label="Листание" />
  28. <q-tab class="tab" name="others" icon="la la-list-ul" label="Прочее" />
  29. <q-tab class="tab" name="reset" icon="la la-broom" label="Сброс" />
  30. <div v-show="tabsScrollable" class="q-pt-lg"/>
  31. </q-tabs>
  32. </div>
  33. <div class="col fit">
  34. <!-- Профили --------------------------------------------------------------------->
  35. <div v-if="selectedTab == 'profiles'" class="fit tab-panel">
  36. @@include('./include/ProfilesTab.inc');
  37. </div>
  38. <!-- Вид ------------------------------------------------------------------------->
  39. <div v-if="selectedTab == 'view'" class="fit column">
  40. @@include('./include/ViewTab.inc');
  41. </div>
  42. <!-- Кнопки ---------------------------------------------------------------------->
  43. <div v-if="selectedTab == 'buttons'" class="fit tab-panel">
  44. @@include('./include/ButtonsTab.inc');
  45. </div>
  46. <!-- Управление ------------------------------------------------------------------>
  47. <div v-if="selectedTab == 'keys'" class="fit column">
  48. @@include('./include/KeysTab.inc');
  49. </div>
  50. <!-- Листание -------------------------------------------------------------------->
  51. <div v-if="selectedTab == 'pagemove'" class="fit tab-panel">
  52. @@include('./include/PageMoveTab.inc');
  53. </div>
  54. <!-- Прочее ---------------------------------------------------------------------->
  55. <div v-if="selectedTab == 'others'" class="fit tab-panel">
  56. @@include('./include/OthersTab.inc');
  57. </div>
  58. <!-- Сброс ----------------------------------------------------------------------->
  59. <div v-if="selectedTab == 'reset'" class="fit tab-panel">
  60. @@include('./include/ResetTab.inc');
  61. </div>
  62. </div>
  63. </div>
  64. </Window>
  65. </template>
  66. <script>
  67. //-----------------------------------------------------------------------------
  68. import Vue from 'vue';
  69. import Component from 'vue-class-component';
  70. import _ from 'lodash';
  71. import * as utils from '../../../share/utils';
  72. import Window from '../../share/Window.vue';
  73. import NumInput from '../../share/NumInput.vue';
  74. import UserHotKeys from './UserHotKeys/UserHotKeys.vue';
  75. import rstore from '../../../store/modules/reader';
  76. import defPalette from './defPalette';
  77. const hex = /^#[0-9a-fA-F]{3}([0-9a-fA-F]{3})?$/;
  78. export default @Component({
  79. components: {
  80. Window,
  81. NumInput,
  82. UserHotKeys,
  83. },
  84. data: function() {
  85. return Object.assign({}, rstore.settingDefaults);
  86. },
  87. watch: {
  88. settings: function() {
  89. this.settingsChanged();
  90. },
  91. form: function(newValue) {
  92. if (this.inited)
  93. this.commit('reader/setSettings', newValue);
  94. },
  95. fontBold: function(newValue) {
  96. this.fontWeight = (newValue ? 'bold' : '');
  97. },
  98. fontItalic: function(newValue) {
  99. this.fontStyle = (newValue ? 'italic' : '');
  100. },
  101. vertShift: function(newValue) {
  102. const font = (this.webFontName ? this.webFontName : this.fontName);
  103. if (this.fontShifts[font] != newValue) {
  104. this.fontShifts = Object.assign({}, this.fontShifts, {[font]: newValue});
  105. this.fontVertShift = newValue;
  106. }
  107. },
  108. fontName: function(newValue) {
  109. const font = (this.webFontName ? this.webFontName : newValue);
  110. this.vertShift = this.fontShifts[font] || 0;
  111. },
  112. webFontName: function(newValue) {
  113. const font = (newValue ? newValue : this.fontName);
  114. this.vertShift = this.fontShifts[font] || 0;
  115. },
  116. wallpaper: function(newValue) {
  117. if (newValue != '' && this.pageChangeAnimation == 'flip')
  118. this.pageChangeAnimation = '';
  119. },
  120. textColor: function(newValue) {
  121. this.textColorFiltered = newValue;
  122. },
  123. textColorFiltered: function(newValue) {
  124. if (hex.test(newValue))
  125. this.textColor = newValue;
  126. },
  127. backgroundColor: function(newValue) {
  128. this.bgColorFiltered = newValue;
  129. },
  130. bgColorFiltered: function(newValue) {
  131. if (hex.test(newValue))
  132. this.backgroundColor = newValue;
  133. },
  134. },
  135. })
  136. class SettingsPage extends Vue {
  137. selectedTab = 'profiles';
  138. selectedViewTab = 'color';
  139. selectedKeysTab = 'mouse';
  140. form = {};
  141. fontBold = false;
  142. fontItalic = false;
  143. vertShift = 0;
  144. tabsScrollable = false;
  145. textColorFiltered = '';
  146. bgColorFiltered = '';
  147. webFonts = [];
  148. fonts = [];
  149. serverStorageKeyVisible = false;
  150. toolButtons = [];
  151. rstore = {};
  152. created() {
  153. this.commit = this.$store.commit;
  154. this.reader = this.$store.state.reader;
  155. this.form = {};
  156. this.rstore = rstore;
  157. this.toolButtons = rstore.toolButtons;
  158. this.settingsChanged();
  159. }
  160. mounted() {
  161. this.$watch(
  162. '$refs.tabs.scrollable',
  163. (newValue) => {
  164. this.tabsScrollable = newValue && !this.$isMobileDevice;
  165. }
  166. );
  167. }
  168. init() {
  169. this.$refs.window.init();
  170. this.inited = true;
  171. }
  172. settingsChanged() {
  173. if (_.isEqual(this.form, this.settings))
  174. return;
  175. this.form = Object.assign({}, this.settings);
  176. if (!this.unwatch)
  177. this.unwatch = {};
  178. for (let prop in rstore.settingDefaults) {
  179. if (this.unwatch && this.unwatch[prop])
  180. this.unwatch[prop]();
  181. this[prop] = this.form[prop];
  182. this.unwatch[prop] = this.$watch(prop, (newValue) => {
  183. this.form = Object.assign({}, this.form, {[prop]: newValue});
  184. });
  185. }
  186. this.fontBold = (this.fontWeight == 'bold');
  187. this.fontItalic = (this.fontStyle == 'italic');
  188. this.fonts = rstore.fonts;
  189. this.webFonts = rstore.webFonts;
  190. const font = (this.webFontName ? this.webFontName : this.fontName);
  191. this.vertShift = this.fontShifts[font] || 0;
  192. this.textColorFiltered = this.textColor;
  193. this.bgColorFiltered = this.backgroundColor;
  194. }
  195. get mode() {
  196. return this.$store.state.config.mode;
  197. }
  198. get settings() {
  199. return this.$store.state.reader.settings;
  200. }
  201. get serverSyncEnabled() {
  202. return this.$store.state.reader.serverSyncEnabled;
  203. }
  204. set serverSyncEnabled(newValue) {
  205. this.commit('reader/setServerSyncEnabled', newValue);
  206. }
  207. get profiles() {
  208. return this.$store.state.reader.profiles;
  209. }
  210. get currentProfileOptions() {
  211. const profNames = Object.keys(this.profiles)
  212. profNames.sort();
  213. let result = [{label: 'Нет', value: ''}];
  214. profNames.forEach(name => {
  215. result.push({label: name, value: name});
  216. });
  217. return result;
  218. }
  219. get wallpaperOptions() {
  220. let result = [{label: 'Нет', value: ''}];
  221. for (let i = 1; i < 10; i++) {
  222. result.push({label: i, value: `paper${i}`});
  223. }
  224. return result;
  225. }
  226. get fontsOptions() {
  227. let result = [];
  228. this.fonts.forEach(font => {
  229. result.push({label: (font.label ? font.label : font.name), value: font.name});
  230. });
  231. return result;
  232. }
  233. get webFontsOptions() {
  234. let result = [{label: 'Нет', value: ''}];
  235. this.webFonts.forEach(font => {
  236. result.push({label: font.name, value: font.name});
  237. });
  238. return result;
  239. }
  240. get pageChangeAnimationOptions() {
  241. let result = [
  242. {label: 'Нет', value: ''},
  243. {label: 'Вверх-вниз', value: 'downShift'},
  244. {label: 'Вправо-влево', value: 'rightShift'},
  245. {label: 'Протаивание', value: 'thaw'},
  246. {label: 'Мерцание', value: 'blink'},
  247. {label: 'Вращение', value: 'rotate'},
  248. ];
  249. if (this.wallpaper == '')
  250. result.push({label: 'Листание', value: 'flip'});
  251. return result;
  252. }
  253. get currentProfile() {
  254. return this.$store.state.reader.currentProfile;
  255. }
  256. set currentProfile(newValue) {
  257. this.commit('reader/setCurrentProfile', newValue);
  258. }
  259. get partialStorageKey() {
  260. return this.serverStorageKey.substr(0, 7) + '***';
  261. }
  262. get serverStorageKey() {
  263. return this.$store.state.reader.serverStorageKey;
  264. }
  265. get setStorageKeyLink() {
  266. return `https://${window.location.host}/#/reader?setStorageAccessKey=${utils.toBase58(this.serverStorageKey)}`;
  267. }
  268. get predefineTextColors() {
  269. return defPalette.concat([
  270. '#ffffff',
  271. '#000000',
  272. '#202020',
  273. '#323232',
  274. '#aaaaaa',
  275. '#00c0c0',
  276. '#ebe2c9',
  277. '#cfdc99',
  278. '#478355',
  279. '#909080',
  280. ]);
  281. }
  282. get predefineBackgroundColors() {
  283. return defPalette.concat([
  284. '#ffffff',
  285. '#000000',
  286. '#202020',
  287. '#ebe2c9',
  288. '#cfdc99',
  289. '#478355',
  290. '#a6caf0',
  291. '#909080',
  292. '#808080',
  293. '#c8c8c8',
  294. ]);
  295. }
  296. colorPanStyle(type) {
  297. let result = 'width: 30px; height: 30px; border: 1px solid black; border-radius: 4px;';
  298. switch (type) {
  299. case 'text':
  300. result += `background-color: ${this.textColor};`
  301. break;
  302. case 'bg':
  303. result += `background-color: ${this.backgroundColor};`
  304. break;
  305. }
  306. return result;
  307. }
  308. needReload() {
  309. this.$root.notify.warning('Необходимо обновить страницу (F5), чтобы изменения возымели эффект');
  310. }
  311. needTextReload() {
  312. this.$root.notify.warning('Необходимо обновить книгу в обход кэша, чтобы изменения возымели эффект');
  313. }
  314. close() {
  315. this.$emit('do-action', {action: 'settings'});
  316. }
  317. async setDefaults() {
  318. try {
  319. if (await this.$root.stdDialog.confirm('Подтвердите установку настроек по умолчанию:', ' ')) {
  320. this.form = Object.assign({}, rstore.settingDefaults);
  321. for (let prop in rstore.settingDefaults) {
  322. this[prop] = this.form[prop];
  323. }
  324. }
  325. } catch (e) {
  326. //
  327. }
  328. }
  329. changeShowToolButton(buttonName) {
  330. this.showToolButton = Object.assign({}, this.showToolButton, {[buttonName]: !this.showToolButton[buttonName]});
  331. }
  332. async addProfile() {
  333. try {
  334. if (Object.keys(this.profiles).length >= 100) {
  335. this.$root.stdDialog.alert('Достигнут предел количества профилей', 'Ошибка');
  336. return;
  337. }
  338. const result = await this.$root.stdDialog.prompt('Введите произвольное название для профиля устройства:', ' ', {
  339. inputValidator: (str) => { if (!str) return 'Название не должно быть пустым'; else if (str.length > 50) return 'Слишком длинное название'; else return true; },
  340. });
  341. if (result && result.value) {
  342. if (this.profiles[result.value]) {
  343. this.$root.stdDialog.alert('Такой профиль уже существует', 'Ошибка');
  344. } else {
  345. const newProfiles = Object.assign({}, this.profiles, {[result.value]: 1});
  346. this.commit('reader/setAllowProfilesSave', true);
  347. await this.$nextTick();//ждем обработчики watch
  348. this.commit('reader/setProfiles', newProfiles);
  349. await this.$nextTick();//ждем обработчики watch
  350. this.commit('reader/setAllowProfilesSave', false);
  351. this.currentProfile = result.value;
  352. }
  353. }
  354. } catch (e) {
  355. //
  356. }
  357. }
  358. async delProfile() {
  359. if (!this.currentProfile)
  360. return;
  361. try {
  362. const result = await this.$root.stdDialog.prompt(`<b>Предупреждение!</b> Удаление профиля '${this.$sanitize(this.currentProfile)}' необратимо.` +
  363. `<br>Все настройки профиля будут потеряны, однако список читаемых книг сохранится.` +
  364. `<br><br>Введите 'да' для подтверждения удаления:`, ' ', {
  365. inputValidator: (str) => { if (str && str.toLowerCase() === 'да') return true; else return 'Удаление не подтверждено'; },
  366. });
  367. if (result && result.value && result.value.toLowerCase() == 'да') {
  368. if (this.profiles[this.currentProfile]) {
  369. const newProfiles = Object.assign({}, this.profiles);
  370. delete newProfiles[this.currentProfile];
  371. this.commit('reader/setAllowProfilesSave', true);
  372. await this.$nextTick();//ждем обработчики watch
  373. this.commit('reader/setProfiles', newProfiles);
  374. await this.$nextTick();//ждем обработчики watch
  375. this.commit('reader/setAllowProfilesSave', false);
  376. this.currentProfile = '';
  377. }
  378. }
  379. } catch (e) {
  380. //
  381. }
  382. }
  383. async delAllProfiles() {
  384. if (!Object.keys(this.profiles).length)
  385. return;
  386. try {
  387. const result = await this.$root.stdDialog.prompt(`<b>Предупреждение!</b> Удаление ВСЕХ профилей с настройками необратимо.` +
  388. `<br><br>Введите 'да' для подтверждения удаления:`, ' ', {
  389. inputValidator: (str) => { if (str && str.toLowerCase() === 'да') return true; else return 'Удаление не подтверждено'; },
  390. });
  391. if (result && result.value && result.value.toLowerCase() == 'да') {
  392. this.commit('reader/setAllowProfilesSave', true);
  393. await this.$nextTick();//ждем обработчики watch
  394. this.commit('reader/setProfiles', {});
  395. await this.$nextTick();//ждем обработчики watch
  396. this.commit('reader/setAllowProfilesSave', false);
  397. this.currentProfile = '';
  398. }
  399. } catch (e) {
  400. //
  401. }
  402. }
  403. async copyToClip(text, prefix) {
  404. const result = await utils.copyTextToClipboard(text);
  405. const suf = (prefix.substr(-1) == 'а' ? 'а' : '');
  406. const msg = (result ? `${prefix} успешно скопирован${suf} в буфер обмена` : 'Копирование не удалось');
  407. if (result)
  408. this.$root.notify.success(msg);
  409. else
  410. this.$root.notify.error(msg);
  411. }
  412. async showServerStorageKey() {
  413. this.serverStorageKeyVisible = !this.serverStorageKeyVisible;
  414. }
  415. async enterServerStorageKey(key) {
  416. try {
  417. const result = await this.$root.stdDialog.prompt(`<b>Предупреждение!</b> Изменение ключа доступа приведет к замене всех профилей и читаемых книг в читалке.` +
  418. `<br><br>Введите новый ключ доступа:`, ' ', {
  419. inputValidator: (str) => {
  420. try {
  421. if (str && utils.fromBase58(str).length == 32) {
  422. return true;
  423. }
  424. } catch (e) {
  425. //
  426. }
  427. return 'Неверный формат ключа';
  428. },
  429. inputValue: (key && _.isString(key) ? key : null),
  430. });
  431. if (result && result.value && utils.fromBase58(result.value).length == 32) {
  432. this.commit('reader/setServerStorageKey', result.value);
  433. }
  434. } catch (e) {
  435. //
  436. }
  437. }
  438. async generateServerStorageKey() {
  439. try {
  440. const result = await this.$root.stdDialog.prompt(`<b>Предупреждение!</b> Генерация нового ключа доступа приведет к удалению всех профилей и читаемых книг в читалке.` +
  441. `<br><br>Введите 'да' для подтверждения генерации нового ключа:`, ' ', {
  442. inputValidator: (str) => { if (str && str.toLowerCase() === 'да') return true; else return 'Генерация не подтверждена'; },
  443. });
  444. if (result && result.value && result.value.toLowerCase() == 'да') {
  445. this.$root.$emit('generateNewServerStorageKey');
  446. }
  447. } catch (e) {
  448. //
  449. }
  450. }
  451. keyHook(event) {
  452. if (!this.$root.stdDialog.active && event.type == 'keydown' && event.key == 'Escape') {
  453. this.close();
  454. }
  455. return true;
  456. }
  457. }
  458. //-----------------------------------------------------------------------------
  459. </script>
  460. <style scoped>
  461. .tab {
  462. justify-content: initial;
  463. }
  464. .tab-panel {
  465. overflow-x: hidden;
  466. overflow-y: auto;
  467. font-size: 90%;
  468. padding: 0 10px 15px 10px;
  469. }
  470. .part-header {
  471. border-top: 2px solid #bbbbbb;
  472. font-weight: bold;
  473. font-size: 110%;
  474. margin-top: 15px;
  475. margin-bottom: 5px;
  476. }
  477. .item {
  478. width: 100%;
  479. margin-top: 5px;
  480. margin-bottom: 5px;
  481. }
  482. .label-1 {
  483. width: 75px;
  484. }
  485. .label-2, .label-3, .label-4, .label-5 {
  486. width: 110px;
  487. }
  488. .label-6 {
  489. width: 100px;
  490. }
  491. .label-1, .label-2, .label-3, .label-4, .label-5, .label-6 {
  492. display: flex;
  493. flex-direction: column;
  494. justify-content: center;
  495. text-align: right;
  496. margin-right: 10px;
  497. overflow: hidden;
  498. }
  499. .text {
  500. font-size: 90%;
  501. line-height: 130%;
  502. }
  503. .button {
  504. margin: 3px 15px 3px 0;
  505. padding: 0 5px 0 5px;
  506. }
  507. .copy-icon {
  508. margin-left: 5px;
  509. cursor: pointer;
  510. font-size: 120%;
  511. color: blue;
  512. }
  513. .input {
  514. max-width: 150px;
  515. }
  516. .no-mp {
  517. margin: 0;
  518. padding: 0;
  519. }
  520. .col-left {
  521. width: 150px;
  522. }
  523. </style>