code
stringlengths 1
1.05M
| repo_name
stringlengths 6
83
| path
stringlengths 3
242
| language
stringclasses 222
values | license
stringclasses 20
values | size
int64 1
1.05M
|
|---|---|---|---|---|---|
<template>
<div>
<!-- auto refresh row -->
<el-row>
<el-col>
<div style="float: right;">
<el-tag type="info">
<i class="el-icon-refresh"></i>
{{ $t('message.auto_refresh') }}
</el-tag>
<el-tooltip class="item" effect="dark" :content="$t('message.auto_refresh_tip', {interval: refreshInterval / 1000})" placement="bottom">
<el-switch v-model="autoRefresh" @change="refreshInit">
</el-switch>
</el-tooltip>
</div>
</el-col>
</el-row>
<!-- server status row -->
<el-row :gutter="10" class="status-container status-card">
<!-- server -->
<el-col :span="8">
<el-card class="box-card">
<div slot="header">
<i class="fa fa-server"></i>
<span>{{ $t('message.server') }}</span>
</div>
<p class="server-status-tag-p">
<el-tag class='server-status-container' type="info" size="big">
{{ $t('message.redis_version') }}:
<span class="server-status-text">{{this.connectionStatus.redis_version}}</span>
</el-tag>
</p>
<p class="server-status-tag-p">
<el-tag class='server-status-container' type="info" size="big">
OS:
<span class="server-status-text" :title="connectionStatus.os">{{this.connectionStatus.os}}</span>
</el-tag>
</p>
<p class="server-status-tag-p">
<el-tag class='server-status-container' type="info" size="big">
{{ $t('message.process_id') }}:
<span class="server-status-text">{{this.connectionStatus.process_id}}</span>
</el-tag>
</p>
</el-card>
</el-col>
<!-- memory row -->
<el-col :span="8">
<el-card class="box-card">
<div slot="header">
<i class="fa fa-microchip"></i>
<span>{{ $t('message.memory') }}</span>
</div>
<p class="server-status-tag-p">
<el-tag class='server-status-container' type="info" size="big">
{{ $t('message.used_memory') }}:
<span class="server-status-text">{{$util.humanFileSize(connectionStatus.used_memory)}}</span>
</el-tag>
</p>
<p class="server-status-tag-p">
<el-tag class='server-status-container' type="info" size="big">
{{ $t('message.used_memory_peak') }}:
<span class="server-status-text">{{$util.humanFileSize(connectionStatus.used_memory_peak)}}</span>
</el-tag>
</p>
<p class="server-status-tag-p">
<el-tag class='server-status-container' type="info" size="big">
{{ $t('message.used_memory_lua') }}:
<span class="server-status-text">{{$util.humanFileSize(connectionStatus.used_memory_lua)}}</span>
</el-tag>
</p>
</el-card>
</el-col>
<!-- stats row -->
<el-col :span="8">
<el-card class="box-card">
<div slot="header">
<i class="fa fa-thermometer-three-quarters"></i>
<span>{{ $t('message.stats') }}</span>
</div>
<p class="server-status-tag-p">
<el-tag class='server-status-container' type="info" size="big">
{{ $t('message.connected_clients') }}:
<span class="server-status-text">{{this.connectionStatus.connected_clients}}</span>
</el-tag>
</p>
<p class="server-status-tag-p">
<el-tag class='server-status-container' type="info" size="big">
{{ $t('message.total_connections_received') }}:
<span class="server-status-text">{{this.connectionStatus.total_connections_received}}</span>
</el-tag>
</p>
<p class="server-status-tag-p">
<el-tag class='server-status-container' type="info" size="big">
{{ $t('message.total_commands_processed') }}:
<span class="server-status-text">{{this.connectionStatus.total_commands_processed}}</span>
</el-tag>
</p>
</el-card>
</el-col>
</el-row>
<!-- cluster key statistics -->
<el-row class="status-card">
<el-col>
<el-card class="box-card">
<div slot="header">
<i class="fa fa-bar-chart"></i>
<span>{{ $t('message.key_statistics') }}</span>
</div>
<el-table
:data="DBKeys"
stripe>
<el-table-column
v-if="isCluster"
prop="name"
sortable
label="Node">
</el-table-column>
<el-table-column
prop="db"
sortable
label="DB">
</el-table-column>
<el-table-column
sortable
prop="keys_show"
label="Keys"
:sort-method="sortByKeys">
</el-table-column>
<el-table-column
sortable
prop="expires_show"
label="Expires"
:sort-method="sortByExpires">
</el-table-column>
<!-- avg_ttl: tooltip can't be removed!, or the table's height will change -->
<el-table-column
sortable
prop="avg_ttl_show"
:show-overflow-tooltip='true'
label="Avg TTL"
:sort-method="sortByTTL">
</el-table-column>
</el-table>
</el-card>
</el-col>
</el-row>
<!-- redis all info -->
<el-row class="status-card">
<el-col>
<el-card class="box-card">
<div slot="header">
<i class="fa fa-info-circle"></i>
<span>{{ $t('message.all_redis_info') }}</span>
<!-- search input -->
<el-input v-model='allInfoFilter' size='mini' suffix-icon="el-icon-search" class='status-filter-input'>
</el-input>
</div>
<el-table
:data="AllRedisInfo"
stripe>
<el-table-column
prop="key"
sortable
label="Key">
</el-table-column>
<el-table-column
prop="value"
:show-overflow-tooltip='true'
label="Value">
</el-table-column>
</el-table>
</el-card>
</el-col>
</el-row>
<ScrollToTop parentNum='1'></ScrollToTop>
</div>
</template>
<script>
import ScrollToTop from '@/components/ScrollToTop';
export default {
data() {
return {
autoRefresh: false,
refreshTimer: null,
refreshInterval: 2000,
connectionStatus: {},
allInfoFilter: '',
DBKeys: [],
};
},
props: ['client', 'hotKeyScope'],
components: { ScrollToTop },
computed: {
AllRedisInfo() {
const infos = [];
const filter = this.allInfoFilter.toLowerCase();
// filter mode
if (filter) {
for (const i in this.connectionStatus) {
if (i.includes(filter)) {
infos.push({ key: i, value: this.connectionStatus[i] });
}
}
}
// all info
else {
for (const i in this.connectionStatus) {
infos.push({ key: i, value: this.connectionStatus[i] });
}
}
return infos;
},
isCluster() {
return this.connectionStatus['cluster_enabled'] == '1';
},
},
methods: {
initShow() {
this.client.info().then((reply) => {
this.connectionStatus = this.initStatus(reply);
// set global param
this.client.ardmRedisVersion = this.connectionStatus['redis_version'];
// init db keys info
if (this.isCluster) {
this.initClusterKeys();
}
else {
this.DBKeys = this.initDbKeys(this.connectionStatus);
}
}).catch((e) => {
// info command may be disabled
if (e.message.includes('unknown command')) {
this.$message.error({
message: this.$t('message.info_disabled'),
duration: 3000,
});
}
// no auth not show
else if (e.message.includes('NOAUTH')) {} else {
this.$message.error(e.message);
}
});
},
refreshInit() {
this.refreshTimer && clearInterval(this.refreshTimer);
if (this.autoRefresh) {
this.initShow();
this.refreshTimer = setInterval(() => {
this.initShow();
}, this.refreshInterval);
}
},
sortByKeys(a, b) {
return a.keys - b.keys;
},
sortByExpires(a, b) {
return a.expires - b.expires;
},
sortByTTL(a, b) {
return a.avg_ttl - b.avg_ttl;
},
initStatus(content) {
if (!content) {
return {};
}
content = content.split('\n');
const lines = {};
for (let i of content) {
i = i.replace(/\s/ig, '');
if (i.startsWith('#') || !i) continue;
const kv = i.split(':');
lines[kv[0]] = kv[1];
}
return lines;
},
initDbKeys(status, name = undefined) {
const dbs = [];
for (const i in status) {
// fix #1101 unexpected db prefix
// if (i.startsWith('db')) {
if (/^db\d+/.test(i)) {
const array = status[i].split(',');
const keys = parseInt(array[0] ? array[0].split('=')[1]: NaN);
const expires = parseInt(array[1] ? array[1].split('=')[1] : NaN);
const avg_ttl = parseInt(array[2] ? array[2].split('=')[1] : NaN);
// #1261 locale to the key count
dbs.push({
db: i,
keys,
expires,
avg_ttl,
keys_show: keys.toLocaleString(),
expires_show: expires.toLocaleString(),
avg_ttl_show: avg_ttl.toLocaleString(),
name,
});
}
}
return dbs;
},
initClusterKeys() {
// const nodes = this.client.nodes('master');
const nodes = this.client.nodes ? this.client.nodes('master') : [this.client];
if (!nodes || !nodes.length) {
return;
}
// get real node name in ssh+cluster, instead of local port
const natMap = this.client.options.natMap;
const clusterNodeNames = {};
if (natMap && Object.keys(natMap).length) {
for (const real in natMap) {
clusterNodeNames[`${natMap[real].host}:${natMap[real].port}`] = real;
}
}
nodes.map((node) => {
node.call('INFO', 'KEYSPACE').then((reply) => {
const { options } = node;
// fix #1221 node name in ssh+cluster
let name = `${options.host}:${options.port}`;
name = clusterNodeNames[name] || name;
const keys = this.initDbKeys(this.initStatus(reply), name);
// clear only when first reply, avoid jitter
if (this.DBKeys.length === nodes.length) {
this.DBKeys = [];
}
this.DBKeys = this.DBKeys.concat(keys);
// sort by node name
this.DBKeys.sort((a, b) => (a.name > b.name ? 1 : -1));
}).catch((e) => {
this.$message.error(e.message);
});
});
},
initShortcut() {
this.$shortcut.bind('ctrl+r, ⌘+r, f5', this.hotKeyScope, () => {
this.initShow();
return false;
});
},
},
mounted() {
this.initShow();
this.refreshInit();
this.initShortcut();
},
beforeDestroy() {
// clear interval when tab is closed
clearInterval(this.refreshTimer);
this.$shortcut.deleteScope(this.hotKeyScope);
},
};
</script>
<style type="text/css">
.el-row.status-card {
margin-top: 20px;
}
.server-status-tag-p {
height: 32px;
}
.server-status-container{
width: 100%;
overflow-x: hidden;
text-overflow: ellipsis;
}
.server-status-text{
color: #43b50b;
}
.status-filter-input {
float: right;
width: 100px;
}
/*fix table height changes[scrollTop changes] when tab toggled*/
.status-card .el-table__header-wrapper{
height: 50px;
}
.status-card .el-table__body-wrapper{
/*height: calc(100% - 50px) !important;*/
}
</style>
|
2301_77204479/AnotherRedisDesktopManager
|
src/components/Status.vue
|
Vue
|
mit
| 12,008
|
<template>
<div>
<el-tabs ref="tabs" class='tabs-container' v-model="selectedTabName" type="card" closable @tab-remove="removeTab" @tab-click="tabClick">
<el-tab-pane
v-for="(item) in tabs"
:key="item.name"
:name="item.name">
<span slot="label" :title="item.title">
<i :class="iconNameByComponent(item.component)"></i>
<span>{{ item.label }}</span>
</span>
<Status v-if="item.component === 'status'" :client='item.client' class='tab-content-wrappe' :hotKeyScope='item.name'></Status>
<CliTab v-else-if="item.component === 'cli'" :client='item.client' class='tab-content-wrappe' :hotKeyScope='item.name'></CliTab>
<DeleteBatch v-else-if="item.component === 'delbatch'" :client='item.client' :rule="item.rule" class='tab-content-wrappe' :hotKeyScope='item.name'></DeleteBatch>
<MemoryAnalysis v-else-if="item.component === 'memory'" :client='item.client' :pattern="item.pattern" class='tab-content-wrappe' :hotKeyScope='item.name'></MemoryAnalysis>
<SlowLog v-else-if="item.component === 'slowlog'" :client='item.client' class='tab-content-wrappe' :hotKeyScope='item.name'></SlowLog>
<KeyDetail v-else :client='item.client' :redisKey="item.redisKey" :keyType="item.keyType" class='tab-content-wrappe' :hotKeyScope='item.name'></KeyDetail>
</el-tab-pane>
</el-tabs>
<div ref="tabContextMenu" class="tabs-context-menu">
<ul>
<li @click="removeTab(preTabId)">{{ $t('message.close') }}</li>
<li @click="removeOtherTabs('other')">{{ $t('message.close_other') }}</li>
<li @click="removeOtherTabs('right')">{{ $t('message.close_right') }}</li>
<li @click="removeOtherTabs('left')">{{ $t('message.close_left') }}</li>
</ul>
</div>
</div>
</template>
<script>
import Status from '@/components/Status';
import CliTab from '@/components/CliTab';
import KeyDetail from '@/components/KeyDetail';
import DeleteBatch from '@/components/DeleteBatch';
import MemoryAnalysis from '@/components/MemoryAnalysis';
import SlowLog from '@/components/SlowLog';
export default {
data() {
return {
selectedTabName: '',
tabs: [],
};
},
components: {
Status, KeyDetail, CliTab, DeleteBatch, MemoryAnalysis, SlowLog,
},
watch: {
selectedTabName(value) {
// for mousewheel toggle tabs
value && this.$shortcut.setScope(value);
},
},
created() {
// key clicked
this.$bus.$on('clickedKey', (client, key, newTab = false) => {
this.addKeyTab(client, key, newTab);
});
// open status tab
this.$bus.$on('openStatus', (client, tabName) => {
this.addStatusTab(client, tabName);
});
// open cli tab
this.$bus.$on('openCli', (client, tabName) => {
this.addCliTab(client, tabName);
});
// open delete batch tab
this.$bus.$on('openDelBatch', (client, tabName, rule = {}) => {
this.addDelBatchTab(client, tabName, rule);
});
// open memory anaysis tab
this.$bus.$on('memoryAnalysis', (client, tabName, pattern = '') => {
this.addMemoryTab(client, tabName, pattern);
});
// open slowlog tab
this.$bus.$on('slowLog', (client, tabName) => {
this.addSlowLogTab(client, tabName);
});
// remove pre tab
this.$bus.$on('removePreTab', () => {
this.removeTab(this.selectedTabName);
});
// remove all tab
this.$bus.$on('removeAllTab', (connectionName) => {
// close all tabs
if (!connectionName) {
return this.tabs = [];
}
this.tabs = this.tabs.filter(tab => tab.client.options.connectionName != connectionName);
// still tabs left, solve selecting which tab
if (this.tabs.length) {
// previous selected left, do not change
const filteredTab = this.tabs.filter(tab => tab.name == this.selectedTabName);
!filteredTab.length && (this.selectedTabName = this.tabs[0].name);
}
});
},
methods: {
removeTab(removeName) {
if (!removeName) {
return;
}
const { tabs } = this;
let nextSelectTab;
if (this.selectedTabName == removeName) {
tabs.forEach((tab, index) => {
if (tab.name == removeName) {
nextSelectTab = tabs[index + 1] || tabs[index - 1];
}
});
}
nextSelectTab && (this.selectedTabName = nextSelectTab.name);
this.tabs = this.tabs.filter(tab => tab.name !== removeName);
this.$shortcut.deleteScope(removeName);
this.$shortcut.setScope(this.selectedTabName);
},
tabClick(tab, event) {
this.$shortcut.setScope(this.selectedTabName);
if (tab.$children && tab.$children[0] && (typeof tab.$children[0].tabClick === 'function')) {
tab.$children[0].tabClick();
}
},
addStatusTab(client, tabName, newTab = true) {
const newTabItem = {
name: `status_${tabName}`,
label: this.$util.cutString(tabName),
title: tabName,
client,
component: 'status',
};
this.addTab(newTabItem, newTab);
},
addCliTab(client, tabName, newTab = true) {
const newTabItem = {
name: `cli_${tabName}_${Math.random()}`,
label: this.$util.cutString(tabName),
title: tabName,
client,
component: 'cli',
};
this.addTab(newTabItem, newTab);
},
addDelBatchTab(client, tabName, rule = {}) {
const newTabItem = {
name: `del_batch_${tabName}_${Math.random()}`,
label: this.$util.cutString(tabName),
title: tabName,
client,
component: 'delbatch',
rule,
};
this.addTab(newTabItem, true);
},
addMemoryTab(client, tabName, pattern = '') {
const newTabItem = {
name: `memory_analysis_${tabName}_${Math.random()}`,
label: this.$util.cutString(tabName),
title: tabName,
client,
component: 'memory',
pattern,
};
this.addTab(newTabItem, true);
},
addSlowLogTab(client, tabName) {
const newTabItem = {
name: `slowlog_${tabName}_${Math.random()}`,
label: this.$util.cutString(tabName),
title: tabName,
client,
component: 'slowlog',
};
this.addTab(newTabItem, true);
},
addKeyTab(client, key, newTab = false) {
client.type(key).then((type) => {
// key not exists
if (type === 'none') {
this.$message.error({
message: `${key} ${this.$t('message.key_not_exists')}`,
duration: 1000,
});
return;
}
this.addTab(this.initKeyTabItem(client, key, type), newTab);
}).catch((e) => {
this.$message.error(`Type Error: ${e.message}`);
});
},
initKeyTabItem(client, key, type) {
const { cutString } = this.$util;
const dbIndex = client.condition ? client.condition.select : 0;
const { connectionName } = client.options;
const keyStr = this.$util.bufToString(key);
const label = `${cutString(keyStr)} | ${cutString(connectionName)} | DB${dbIndex}`;
const name = `${keyStr} | ${connectionName} | DB${dbIndex}`;
return {
name,
label,
title: name,
client,
component: 'key',
redisKey: key,
keyType: type,
};
},
addTab(newTabItem, newTab = false) {
let exists = false;
this.tabs.map((item) => {
(item.name === newTabItem.name) && (exists = true);
});
// if exists, select directly
if (exists) {
this.selectedTabName = newTabItem.name;
this.$shortcut.setScope(this.selectedTabName);
return;
}
// new tab append to tail
if (newTab) {
this.tabs.push(newTabItem);
}
// open tab on previous selected key tab
// or append to tail if previous tab is cli\status
else {
let replaced = false;
this.tabs = this.tabs.map((item) => {
// replace the selected tab with new tab item
if (item.name === this.selectedTabName && item.component === 'key') {
replaced = true;
return newTabItem;
}
return item;
});
// pre tab is preserve tab, append to tail
!replaced && (this.tabs.push(newTabItem));
}
this.selectedTabName = newTabItem.name;
this.$shortcut.setScope(this.selectedTabName);
},
iconNameByComponent(component) {
const map = {
cli: 'fa fa-terminal',
status: 'el-icon-info',
delbatch: 'el-icon-delete',
memory: 'fa fa-table',
slowlog: 'fa fa-hourglass-start',
};
const icon = map[component];
return icon || 'fa fa-key';
},
initShortcut() {
this.$shortcut.bind('ctrl+w, ⌘+w', () => {
const closeWindow = !this.tabs.length;
this.removeTab(this.selectedTabName);
return closeWindow;
});
},
bindTabEvents() {
const tabs = this.$refs.tabs.$el.querySelector('.el-tabs__header');
tabs && tabs.addEventListener('contextmenu', this.openContextMenu);
tabs && tabs.addEventListener('mousewheel', this.wheelToggleTabs);
},
wheelToggleTabs(event) {
let index = this.tabs.findIndex(item => item.name === this.selectedTabName);
// up: deltaY < 0
event.deltaY < 0 ? index-- : index++;
if (!this.tabs[index]) {
return;
}
this.selectedTabName = this.tabs[index].name;
},
openContextMenu(event) {
this.preTabId = '';
this.hideAllMenus();
const items = this.$refs.tabs.$el.querySelectorAll('.el-tabs__header .el-tabs__item');
if (!items.length) {
return;
}
for (const item of items) {
if (item.contains(event.srcElement)) {
this.preTabId = item.id.substr(4); // remove prefix "tab-"
}
}
if (!this.preTabId) {
return;
}
// show menu
const menu = this.$refs.tabContextMenu;
menu.style.left = `${event.clientX}px`;
menu.style.top = `${event.clientY}px`;
menu.style.display = 'block';
document.addEventListener('click', this.hideAllMenus, { once: true });
},
hideAllMenus() {
const menus = document.querySelectorAll('.tabs-context-menu');
if (menus.length === 0) {
return;
}
for (const menu of menus) {
menu.style.display = 'none';
}
},
removeOtherTabs(type = 'right') {
// find index of current contextMenu
const index = this.tabs.findIndex(item => item.name === this.preTabId);
if (index === -1) {
return;
}
switch (type) {
case 'right': {
this.tabs = this.tabs.slice(0, index + 1);
break;
}
case 'left': {
this.tabs = this.tabs.slice(index);
break;
}
case 'other': {
this.tabs = this.tabs.filter(item => item.name === this.preTabId);
break;
}
}
// change select tab only after current select is removed
const selectedTabExists = !!this.tabs.find(item => item.name === this.selectedTabName);
!selectedTabExists && (this.selectedTabName = this.preTabId);
},
},
mounted() {
this.initShortcut();
this.bindTabEvents();
},
};
</script>
<style type="text/css">
/*tabs header height*/
.tabs-container .el-tabs__item {
height: 34px;
line-height: 34px;
}
.tabs-container .el-tabs__nav-next, .tabs-container .el-tabs__nav-prev {
line-height: 34px;
}
/*height end*/
.tab-content-wrappe {
height: calc(100vh - 67px);
overflow-x: hidden;
overflow-y: auto;
/*padding-left: 5px;*/
padding-right: 8px;
}
/*tabs context menu*/
.tabs-context-menu {
display: none;
position: fixed;
top: 0;
left: 0;
padding: 0px;
z-index: 99999;
border-radius: 3px;
border: 2px solid lightgrey;
background: #fafafa;
}
.dark-mode .tabs-context-menu {
background: #263238;
}
.tabs-context-menu ul {
list-style: none;
padding: 0px;
margin: 0;
}
.tabs-context-menu ul li:not(:last-child) {
border-bottom: 1px solid lightgrey;
}
.tabs-context-menu ul li {
font-size: 13.4px;
padding: 6px 10px;
cursor: pointer;
color: #263238;
}
.dark-mode .tabs-context-menu ul li {
color: #fff;
}
.tabs-context-menu ul li:hover {
background: #e4e2e2;
}
.dark-mode .tabs-context-menu ul li:hover {
background: #344A4E;
}
/*context menu end*/
</style>
|
2301_77204479/AnotherRedisDesktopManager
|
src/components/Tabs.vue
|
Vue
|
mit
| 12,671
|
<template>
</template>
<script type="text/javascript">
import { ipcRenderer } from 'electron';
export default {
data() {
return {
manual: false,
updateChecking: false,
downloadProcessShow: false,
};
},
created() {
this.$bus.$on('update-check', (manual = false) => {
this.manual = manual;
// update checking running...
if (this.updateChecking) {
return;
}
this.updateChecking = true;
this.$notify.closeAll();
ipcRenderer.send('update-check');
});
},
methods: {
bindRendererListener() {
// already bind listening
if (ipcRenderer.binded) {
return;
}
ipcRenderer.binded = true;
ipcRenderer.on('update-available', (event, arg) => {
this.$notify.closeAll();
const ignoreUpdateKey = `IgnoreUpdateVersion_${arg.version}`;
// version ignored
if (!this.manual && localStorage[ignoreUpdateKey]) {
return this.resetDownloadProcess();
}
this.$confirm(arg.releaseNotes, {
title: `${this.$t('message.update_available')}: ${arg.version}`,
confirmButtonText: this.$t('message.begin_update'),
cancelButtonText: this.$t('message.ignore_this_version'),
dangerouslyUseHTMLString: true,
duration: 0,
}).then(() => {
// update btn clicked
this.manual = true;
ipcRenderer.send('continue-update');
}).catch(() => {
// ignore this version
localStorage[ignoreUpdateKey] = true;
this.resetDownloadProcess();
});
});
ipcRenderer.on('update-not-available', (event, arg) => {
this.$notify.closeAll();
this.resetDownloadProcess();
// latest version
this.manual && this.$notify.success({
title: this.$t('message.update_not_available'),
duration: 2000,
});
});
ipcRenderer.on('update-error', (event, arg) => {
this.resetDownloadProcess();
let message = '';
const error = (arg.code ? arg.code : arg.message).toLowerCase();
// auto update check at app init
if (!this.manual || !error) {
return;
}
// mac not support auto update
if (error.includes('zip') && error.includes('file')) {
message = this.$t('message.mac_not_support_auto_update');
}
// err_internet_disconnected err_name_not_resolved err_connection_refused
else {
message = `${this.$t('message.update_error')}: ${error}`;
}
this.$notify.error({
message,
duration: 0,
dangerouslyUseHTMLString: true,
});
});
ipcRenderer.on('download-progress', (event, arg) => {
if (!this.downloadProcessShow) {
const h = this.$createElement;
this.$notify({
message: h('el-progress', {
props: {
percentage: 0,
},
ref: 'downloadProgressBar',
}),
duration: 0,
customClass: 'download-progress-container',
});
this.downloadProcessShow = true;
}
this.setProgressBar(Math.floor(arg.percent));
});
ipcRenderer.on('update-downloaded', (event, arg) => {
// this.$notify.closeAll();
this.setProgressBar(100);
this.resetDownloadProcess();
this.$notify.success({
title: this.$t('message.update_downloaded'),
duration: 0,
});
});
},
setProgressBar(percent) {
this.downloadProcessShow
&& this.$refs.downloadProgressBar
&& this.$set(this.$refs.downloadProgressBar, 'percentage', percent);
},
resetDownloadProcess() {
this.updateChecking = false;
this.downloadProcessShow = false;
},
},
mounted() {
this.bindRendererListener();
},
};
</script>
<style type="text/css">
.download-progress-container .el-progress {
width: 280px;
}
</style>
|
2301_77204479/AnotherRedisDesktopManager
|
src/components/UpdateCheck.vue
|
Vue
|
mit
| 4,062
|
<template>
<div>
<!-- table toolbar -->
<div>
<!-- add button -->
<el-button type="primary" @click="showEditDialog({})">{{ $t('message.add_new_line') }}</el-button>
<!-- edit & add dialog -->
<el-dialog :title="dialogTitle" :visible.sync="editDialog" @open="openDialog" :close-on-click-modal="false">
<el-form label-position="top">
<!-- if ttl support -->
<el-form-item v-if="ttlSupport" label="Field">
<el-row :gutter="10">
<el-col :span="18">
<InputBinary :content.sync="editLineItem.key" placeholder="Field"></InputBinary>
</el-col>
<el-col :span="6">
<el-input v-model="editLineItem.ttl" placeholder="TTL (-1)" type="number"></el-input>
</el-col>
</el-row>
</el-form-item>
<!-- common field -->
<el-form-item v-else label="Field">
<InputBinary :content.sync="editLineItem.key" placeholder="Field"></InputBinary>
</el-form-item>
<el-form-item label="Value">
<FormatViewer ref="formatViewer" :redisKey="redisKey" :dataMap="editLineItem" :content='editLineItem.value'></FormatViewer>
</el-form-item>
</el-form>
<div slot="footer" class="dialog-footer">
<el-button @click="editDialog = false">{{ $t('el.messagebox.cancel') }}</el-button>
<el-button type="primary" @click="editLine">{{ $t('el.messagebox.confirm') }}</el-button>
</div>
</el-dialog>
</div>
<!-- vxe table must get a container with a fixed height -->
<div class="content-table-container">
<vxe-table
ref="contentTable"
size="mini" max-height="100%" min-height="72px"
border="default" stripe show-overflow="title"
:scroll-y="{enabled: true}"
:row-config="{isHover: true, height: 34}"
:column-config="{resizable: true}"
:empty-text="$t('el.table.emptyText')"
:data="hashData">
<vxe-column type="seq" :title="'ID (Total: ' + total + ')'" width="150"></vxe-column>
<vxe-column field="key" title="Key" sortable>
<template v-slot="scope">
{{ $util.bufToString(scope.row.key) }}
</template>
</vxe-column>
<vxe-column field="value" title="Value" sortable>
<template v-slot="scope">
{{ $util.cutString($util.bufToString(scope.row.value), 100) }}
</template>
</vxe-column>
<vxe-column v-if="ttlSupport" field="ttl" title="TTL" width="100" sortable></vxe-column>
<vxe-column title="Operate" width="166">
<template slot-scope="scope" slot="header">
<el-input size="mini"
:placeholder="$t('message.key_to_search')"
:suffix-icon="loadingIcon"
@keyup.native.enter='initShow()'
v-model="filterValue">
</el-input>
</template>
<template slot-scope="scope">
<el-button type="text" @click="$util.copyToClipboard(scope.row.value)" icon="el-icon-document" :title="$t('message.copy')"></el-button>
<el-button type="text" @click="showEditDialog(scope.row)" icon="el-icon-edit" :title="$t('message.edit_line')"></el-button>
<el-button type="text" @click="deleteLine(scope.row)" icon="el-icon-delete" :title="$t('el.upload.delete')"></el-button>
<el-button type="text" @click="dumpCommand(scope.row)" icon="fa fa-code" :title="$t('message.dump_to_clipboard')"></el-button>
</template>
</vxe-column>
</vxe-table>
</div>
<!-- load more content -->
<div class='content-more-container'>
<el-button
size='mini'
@click='initShow(false)'
:icon='loadingIcon'
:disabled='loadMoreDisable'
class='content-more-btn'>
{{ $t('message.load_more_keys') }}
</el-button>
</div>
</div>
</template>
<script>
import FormatViewer from '@/components/FormatViewer';
import InputBinary from '@/components/InputBinary';
import { VxeTable, VxeColumn } from 'vxe-table';
import versionCompare from 'node-version-compare';
export default {
data() {
return {
total: 0,
filterValue: '',
editDialog: false,
hashData: [], // {key: xxx, value: xxx}
beforeEditItem: {},
editLineItem: {},
loadingIcon: '',
pageSize: 200,
searchPageSize: 2000,
oneTimeListLength: 0,
scanStream: null,
loadMoreDisable: false,
};
},
components: {
FormatViewer, InputBinary, VxeTable, VxeColumn,
},
props: ['client', 'redisKey'],
computed: {
dialogTitle() {
return this.beforeEditItem.key ? this.$t('message.edit_line')
: this.$t('message.add_new_line');
},
ttlSupport() {
// avaiable since redis >= 7.4
return versionCompare(this.client.ardmRedisVersion, '7.4') >= 0;
},
},
watch: {
hashData(newValue, oldValue) {
// this.$refs.contentTable.refreshScroll()
// scroll to bottom while loading more
if (oldValue.length && (newValue.length > oldValue.length)) {
setTimeout(() => {
this.$refs.contentTable && this.$refs.contentTable.scrollTo(0, 99999999);
}, 0);
}
}
},
methods: {
initShow(resetTable = true) {
resetTable && this.resetTable();
this.loadingIcon = 'el-icon-loading';
if (!this.scanStream) {
this.initScanStream();
} else {
this.oneTimeListLength = 0;
this.scanStream.resume();
}
// total lines
this.initTotal();
},
initTotal() {
this.client.hlen(this.redisKey).then((reply) => {
this.total = reply;
}).catch((e) => {});
},
resetTable() {
// stop scanning first, #815
this.scanStream && this.scanStream.pause();
this.hashData = [];
this.scanStream = null;
this.oneTimeListLength = 0;
this.loadMoreDisable = false;
},
initTTL(hashData, startIndex = 0) {
if (!this.ttlSupport || !hashData.length) {
return;
}
const keys = hashData.map(line => line.key);
this.client.call('HTTL', this.redisKey, 'FIELDS', keys.length, ...keys).then(reply => {
reply.forEach((ttl, index) => {
this.hashData[startIndex + index].ttl = parseInt(ttl);
});
});
},
initScanStream() {
const scanOption = { match: this.getScanMatch(), count: this.pageSize };
scanOption.match != '*' && (scanOption.count = this.searchPageSize);
this.scanStream = this.client.hscanBufferStream(
this.redisKey,
scanOption,
);
this.scanStream.on('data', (reply) => {
const hashData = [];
for (let i = 0; i < reply.length; i += 2) {
hashData.push({
key: reply[i],
// keyDisplay: this.$util.bufToString(reply[i]),
value: reply[i + 1],
// valueDisplay: this.$util.bufToString(reply[i + 1]),
ttl: -1
});
}
const listLength = this.hashData.length;
this.oneTimeListLength += hashData.length;
this.hashData = this.hashData.concat(hashData);
// init hash field ttls
this.initTTL(hashData, listLength);
if (this.oneTimeListLength >= this.pageSize) {
this.scanStream.pause();
this.loadingIcon = '';
}
});
this.scanStream.on('end', () => {
this.loadingIcon = '';
this.loadMoreDisable = true;
});
this.scanStream.on('error', (e) => {
this.loadingIcon = '';
this.loadMoreDisable = true;
this.$message.error(e.message);
});
},
getScanMatch() {
return this.filterValue ? `*${this.filterValue}*` : '*';
},
openDialog() {
this.$nextTick(() => {
this.$refs.formatViewer.autoFormat();
});
},
showEditDialog(row) {
this.editLineItem = this.$util.cloneObjWithBuff(row);
this.beforeEditItem = row;
this.editDialog = true;
},
dumpCommand(item) {
const lines = item ? [item] : this.hashData;
const params = lines.map(line => `${this.$util.bufToQuotation(line.key)} ${
this.$util.bufToQuotation(line.value)}`);
const command = `HMSET ${this.$util.bufToQuotation(this.redisKey)} ${params.join(' ')}`;
this.$util.copyToClipboard(command);
this.$message.success({ message: this.$t('message.copy_success'), duration: 800 });
},
editLine() {
const key = this.redisKey;
const { client } = this;
const before = this.beforeEditItem;
const afterKey = this.editLineItem.key;
const afterValue = this.$refs.formatViewer.getContent();
const afterTTL = parseInt(this.editLineItem.ttl);
if (!afterKey || !afterValue) {
return;
}
this.editDialog = false;
client.hset(
key,
afterKey,
afterValue,
).then((reply) => {
// edit key && key changed
if (before.key && !before.key.equals(afterKey)) {
client.hdel(key, before.key);
}
// set ttl if supportted
if (this.ttlSupport && afterTTL > 0) {
this.client.call('HEXPIRE', key, afterTTL, "FIELDS", 1, afterKey);
}
// this.initShow(); // do not reinit, #786
const newLine = Object.assign(
{}, before,
{ key: afterKey, value: afterValue, ttl: afterTTL > 0 ? afterTTL : -1}
);
// edit line
if (before.key) {
this.$set(this.hashData, this.hashData.indexOf(before), newLine);
}
// new line
else {
this.hashData.push(newLine);
this.total++;
}
// reply==1:new field; reply==0 field exists
this.$message.success({
message: reply == 1 ? this.$t('message.add_success') : this.$t('message.modify_success'),
duration: 1000,
});
}).catch((e) => { this.$message.error(e.message); });
},
deleteLine(row) {
this.$confirm(
this.$t('message.confirm_to_delete_row_data'),
{ type: 'warning' },
).then(() => {
this.client.hdel(
this.redisKey,
row.key,
).then((reply) => {
if (reply == 1) {
this.$message.success({
message: this.$t('message.delete_success'),
duration: 1000,
});
// this.initShow(); // do not reinit, #786
this.hashData.splice(this.hashData.indexOf(row), 1);
this.total--;
}
}).catch((e) => { this.$message.error(e.message); });
}).catch(() => {});
},
},
mounted() {
this.initShow();
},
};
</script>
|
2301_77204479/AnotherRedisDesktopManager
|
src/components/contents/KeyContentHash.vue
|
Vue
|
mit
| 10,828
|
<template>
<div>
<!-- table toolbar -->
<div>
<!-- add button -->
<el-button type="primary" @click="showEditDialog({})">{{ $t('message.add_new_line') }}</el-button>
<!-- edit & add dialog -->
<el-dialog :title="dialogTitle" :visible.sync="editDialog" @open="openDialog" :close-on-click-modal="false">
<el-form>
<el-form-item label="Value">
<FormatViewer ref="formatViewer" :redisKey="redisKey" :dataMap="editLineItem" :content="editLineItem.value"></FormatViewer>
</el-form-item>
</el-form>
<div slot="footer" class="dialog-footer">
<el-button @click="editDialog = false">{{ $t('el.messagebox.cancel') }}</el-button>
<el-button type="primary" @click="editLine">{{ $t('el.messagebox.confirm') }}</el-button>
</div>
</el-dialog>
</div>
<!-- vxe table must get a container with a fixed height -->
<div class="content-table-container">
<vxe-table
ref="contentTable"
size="mini" max-height="100%" min-height="72px"
border="default" stripe show-overflow="title"
:scroll-y="{enabled: true}"
:row-config="{isHover: true, height: 34}"
:column-config="{resizable: true}"
:empty-text="$t('el.table.emptyText')"
:data="listData">
<vxe-column type="seq" :title="'ID (Total: ' + total + ')'" width="150"></vxe-column>
<vxe-column field="value" title="Value" sortable>
<template v-slot="scope">
{{ $util.cutString($util.bufToString(scope.row.value), 100) }}
</template>
</vxe-column>
<vxe-column title="Operate" width="166">
<template slot-scope="scope" slot="header">
<el-input size="mini"
:placeholder="$t('message.key_to_search')"
:suffix-icon="loadingIcon"
@keyup.native.enter='initShow()'
v-model="filterValue">
</el-input>
</template>
<template slot-scope="scope">
<el-button type="text" @click="$util.copyToClipboard(scope.row.value)" icon="el-icon-document" :title="$t('message.copy')"></el-button>
<el-button type="text" @click="showEditDialog(scope.row)" icon="el-icon-edit" :title="$t('message.edit_line')"></el-button>
<el-button type="text" @click="deleteLine(scope.row)" icon="el-icon-delete" :title="$t('el.upload.delete')"></el-button>
<el-button type="text" @click="dumpCommand(scope.row)" icon="fa fa-code" :title="$t('message.dump_to_clipboard')"></el-button>
</template>
</vxe-column>
</vxe-table>
</div>
<!-- load more content -->
<div class='content-more-container'>
<el-button
size='mini'
@click='loadMore'
:icon='loadingIcon'
:disabled='loadMoreDisable'
class='content-more-btn'>
{{ $t('message.load_more_keys') }}
</el-button>
</div>
</div>
</template>
<script>
import FormatViewer from '@/components/FormatViewer';
import { VxeTable, VxeColumn } from 'vxe-table';
export default {
data() {
return {
total: 0,
filterValue: '',
editDialog: false,
listData: [], // {value: xxx}
beforeEditItem: {},
editLineItem: {},
loadingIcon: '',
pageSize: 200,
searchPageSize: 2000,
pageIndex: 0,
oneTimeListLength: 0,
loadMoreDisable: false,
};
},
props: ['client', 'redisKey'],
components: { FormatViewer, VxeTable, VxeColumn },
computed: {
dialogTitle() {
return this.beforeEditItem.value ? this.$t('message.edit_line')
: this.$t('message.add_new_line');
},
},
watch: {
listData(newValue, oldValue) {
// this.$refs.contentTable.refreshScroll()
// scroll to bottom while loading more
if (oldValue.length && (newValue.length > oldValue.length)) {
setTimeout(() => {
this.$refs.contentTable && this.$refs.contentTable.scrollTo(0, 99999999);
}, 0);
}
}
},
methods: {
initShow(resetTable = true) {
resetTable && this.resetTable();
this.loadingIcon = 'el-icon-loading';
// scan
this.listScan();
// total lines
this.initTotal();
},
listScan() {
const { filterValue } = this;
const pageSize = filterValue ? this.searchPageSize : this.pageSize;
const start = pageSize * this.pageIndex;
const end = start + pageSize - 1;
this.client.lrangeBuffer([this.redisKey, start, end]).then((reply) => {
// scanning end
if (!reply || !reply.length) {
this.loadingIcon = '';
this.loadMoreDisable = true;
return;
}
const listData = [];
for (const i of reply) {
if (filterValue) {
if (!i.includes(filterValue)) {
continue;
}
}
listData.push({ value: i });
}
this.oneTimeListLength += listData.length;
this.listData = this.listData.concat(listData);
if (this.oneTimeListLength >= this.pageSize) {
this.loadingIcon = '';
this.oneTimeListLength = 0;
return;
}
if (this.cancelScanning) {
return;
}
// continue scanning until to pagesize
this.loadMore();
}).catch((e) => {
this.loadingIcon = '';
this.loadMoreDisable = true;
this.$message.error(e.message);
});
},
initTotal() {
this.client.llen(this.redisKey).then((reply) => {
this.total = reply;
}).catch((e) => {});
},
resetTable() {
this.listData = [];
this.pageIndex = 0;
this.oneTimeListLength = 0;
this.loadMoreDisable = false;
},
loadMore() {
this.pageIndex++;
this.listScan();
},
openDialog() {
this.$nextTick(() => {
this.$refs.formatViewer.autoFormat();
});
},
showEditDialog(row) {
this.editLineItem = this.$util.cloneObjWithBuff(row);
this.beforeEditItem = row;
this.editDialog = true;
},
dumpCommand(item) {
const lines = item ? [item] : this.listData;
const params = lines.map(line => this.$util.bufToQuotation(line.value));
const command = `RPUSH ${this.$util.bufToQuotation(this.redisKey)} ${params.join(' ')}`;
this.$util.copyToClipboard(command);
this.$message.success({ message: this.$t('message.copy_success'), duration: 800 });
},
editLine() {
const key = this.redisKey;
const { client } = this;
const before = this.beforeEditItem;
const afterValue = this.$refs.formatViewer.getContent();
if (!afterValue) {
return;
}
// not changed
if (before.value && before.value.equals(afterValue)) {
return this.editDialog = false;
}
this.editDialog = false;
const newLine = { value: afterValue };
// edit line
if (before.value) {
// fix #1082, keep list order
client.linsert(key, 'AFTER', before.value, afterValue).then((reply) => {
if (reply > 0) {
client.lrem(key, 1, before.value);
// this.initShow(); // do not reinit, #786
this.$set(this.listData, this.listData.indexOf(before), newLine);
this.$message.success({
message: this.$t('message.modify_success'),
duration: 1000,
});
}
// reply == -1, before.value has been removed
else {
this.$message.error({
message: `${this.$t('message.modify_failed')}, ${this.$t('message.value_not_exists')}`,
duration: 2000,
});
}
}).catch((e) => { this.$message.error(e.message); });
}
// new line
else {
client.rpush(key, afterValue).then((reply) => {
if (reply > 0) {
// this.initShow(); // do not reinit, #786
this.listData.push(newLine);
this.total++;
this.$message.success({
message: this.$t('message.add_success'),
duration: 1000,
});
}
}).catch((e) => { this.$message.error(e.message); });
}
},
deleteLine(row) {
this.$confirm(
this.$t('message.confirm_to_delete_row_data'),
{ type: 'warning' },
).then(() => {
this.client.lrem(
this.redisKey,
1,
row.value,
).then((reply) => {
if (reply > 0) {
this.$message.success({
message: this.$t('message.delete_success'),
duration: 1000,
});
// this.initShow(); // do not reinit, #786
this.listData.splice(this.listData.indexOf(row), 1);
this.total--;
} else {
this.$message.error({
message: this.$t('message.delete_failed'),
duration: 1000,
});
}
}).catch((e) => { this.$message.error(e.message); });
}).catch(() => {});
},
},
mounted() {
this.initShow();
},
beforeDestroy() {
this.cancelScanning = true;
},
};
</script>
|
2301_77204479/AnotherRedisDesktopManager
|
src/components/contents/KeyContentList.vue
|
Vue
|
mit
| 9,257
|
<template>
<el-form class='key-content-string'>
<!-- key content textarea -->
<el-form-item>
<FormatViewer
ref='formatViewer'
:content='content'
:binary='binary'
:redisKey='redisKey'
float=''>
</FormatViewer>
</el-form-item>
<!-- save btn -->
<el-button ref='saveBtn' type="primary"
@click="execSave" title='Ctrl+s' class="content-string-save-btn">
{{ $t('message.save') }}
</el-button>
</el-form>
</template>
<script>
import FormatViewer from '@/components/FormatViewer';
export default {
data() {
return {
content: Buffer.from(''),
binary: false,
};
},
props: ['client', 'redisKey', 'hotKeyScope'],
components: { FormatViewer },
methods: {
initShow() {
this.client.callBuffer('JSON.GET', [this.redisKey]).then((reply) => {
this.content = reply;
});
},
execSave() {
const content = this.$refs.formatViewer.getContent();
// viewer check failed, do not save
if (content === false) {
return;
}
if (!this.$util.isJson(content)) {
return this.$message.error(this.$t('message.json_format_failed'));
}
this.client.call('JSON.SET', [this.redisKey, '$', content]).then((reply) => {
if (reply === 'OK') {
this.setTTL();
this.initShow();
this.$message.success({
message: this.$t('message.modify_success'),
duration: 1000,
});
} else {
this.$message.error({
message: this.$t('message.modify_failed'),
duration: 1000,
});
}
}).catch((e) => {
this.$message.error(e.message);
});
},
setTTL() {
const ttl = parseInt(this.$parent.$parent.$refs.keyHeader.keyTTL);
if (ttl > 0) {
this.client.expire(this.redisKey, ttl).catch((e) => {
this.$message.error(`Expire Error: ${e.message}`);
}).then((reply) => {});
}
},
initShortcut() {
this.$shortcut.bind('ctrl+s, ⌘+s', this.hotKeyScope, () => {
// make input blur to fill the new value
// this.$refs.saveBtn.$el.focus();
this.execSave();
return false;
});
},
dumpCommand() {
const command = `JSON.SET ${this.$util.bufToQuotation(this.redisKey)} . ${
this.$util.bufToQuotation(this.content)}`;
this.$util.copyToClipboard(command);
this.$message.success({ message: this.$t('message.copy_success'), duration: 800 });
},
},
mounted() {
this.initShow();
this.initShortcut();
},
};
</script>
|
2301_77204479/AnotherRedisDesktopManager
|
src/components/contents/KeyContentReJson.vue
|
Vue
|
mit
| 2,613
|
<template>
<div>
<!-- table toolbar -->
<div>
<!-- add button -->
<el-button type="primary" @click="showEditDialog({})">{{ $t('message.add_new_line') }}</el-button>
<!-- edit & add dialog -->
<el-dialog :title="dialogTitle" :visible.sync="editDialog" @open="openDialog" :close-on-click-modal="false">
<el-form>
<el-form-item label="Value">
<FormatViewer ref="formatViewer" :redisKey="redisKey" :dataMap="editLineItem" :content="editLineItem.value"></FormatViewer>
</el-form-item>
</el-form>
<div slot="footer" class="dialog-footer">
<el-button @click="editDialog = false">{{ $t('el.messagebox.cancel') }}</el-button>
<el-button type="primary" @click="editLine">{{ $t('el.messagebox.confirm') }}</el-button>
</div>
</el-dialog>
</div>
<!-- vxe table must get a container with a fixed height -->
<div class="content-table-container">
<vxe-table
ref="contentTable"
size="mini" max-height="100%" min-height="72px"
border="default" stripe show-overflow="title"
:scroll-y="{enabled: true}"
:row-config="{isHover: true, height: 34}"
:column-config="{resizable: true}"
:empty-text="$t('el.table.emptyText')"
:data="setData">
<vxe-column type="seq" :title="'ID (Total: ' + total + ')'" width="150"></vxe-column>
<vxe-column field="value" title="Value" sortable>
<template v-slot="scope">
{{ $util.cutString($util.bufToString(scope.row.value), 100) }}
</template>
</vxe-column>
<vxe-column title="Operate" width="166">
<template slot-scope="scope" slot="header">
<el-input size="mini"
:placeholder="$t('message.key_to_search')"
:suffix-icon="loadingIcon"
@keyup.native.enter='initShow()'
v-model="filterValue">
</el-input>
</template>
<template slot-scope="scope">
<el-button type="text" @click="$util.copyToClipboard(scope.row.value)" icon="el-icon-document" :title="$t('message.copy')"></el-button>
<el-button type="text" @click="showEditDialog(scope.row)" icon="el-icon-edit" :title="$t('message.edit_line')"></el-button>
<el-button type="text" @click="deleteLine(scope.row)" icon="el-icon-delete" :title="$t('el.upload.delete')"></el-button>
<el-button type="text" @click="dumpCommand(scope.row)" icon="fa fa-code" :title="$t('message.dump_to_clipboard')"></el-button>
</template>
</vxe-column>
</vxe-table>
</div>
<!-- load more content -->
<div class='content-more-container'>
<el-button
size='mini'
@click='initShow(false)'
:icon='loadingIcon'
:disabled='loadMoreDisable'
class='content-more-btn'>
{{ $t('message.load_more_keys') }}
</el-button>
</div>
</div>
</template>
<script>
import FormatViewer from '@/components/FormatViewer';
import { VxeTable, VxeColumn } from 'vxe-table';
export default {
data() {
return {
total: 0,
filterValue: '',
editDialog: false,
setData: [], // {value: xxx}
beforeEditItem: {},
editLineItem: {},
loadingIcon: '',
pageSize: 200,
searchPageSize: 2000,
oneTimeListLength: 0,
scanStream: null,
loadMoreDisable: false,
};
},
props: ['client', 'redisKey'],
components: { FormatViewer, VxeTable, VxeColumn },
computed: {
dialogTitle() {
return this.beforeEditItem.value ? this.$t('message.edit_line')
: this.$t('message.add_new_line');
},
},
watch: {
setData(newValue, oldValue) {
// this.$refs.contentTable.refreshScroll()
// scroll to bottom while loading more
if (oldValue.length && (newValue.length > oldValue.length)) {
setTimeout(() => {
this.$refs.contentTable && this.$refs.contentTable.scrollTo(0, 99999999);
}, 0);
}
}
},
methods: {
initShow(resetTable = true) {
resetTable && this.resetTable();
this.loadingIcon = 'el-icon-loading';
if (!this.scanStream) {
this.initScanStream();
} else {
this.oneTimeListLength = 0;
this.scanStream.resume();
}
// total lines
this.initTotal();
},
initTotal() {
this.client.scard(this.redisKey).then((reply) => {
this.total = reply;
}).catch((e) => {});
},
resetTable() {
// stop scanning first, #815
this.scanStream && this.scanStream.pause();
this.setData = [];
this.scanStream = null;
this.oneTimeListLength = 0;
this.loadMoreDisable = false;
},
initScanStream() {
const scanOption = { match: this.getScanMatch(), count: this.pageSize };
scanOption.match != '*' && (scanOption.count = this.searchPageSize);
this.scanStream = this.client.sscanBufferStream(
this.redisKey,
scanOption,
);
this.scanStream.on('data', (reply) => {
const setData = [];
for (const i of reply) {
setData.push({
value: i,
// valueDisplay: this.$util.bufToString(i),
});
}
this.oneTimeListLength += setData.length;
this.setData = this.setData.concat(setData);
if (this.oneTimeListLength >= this.pageSize) {
this.scanStream.pause();
this.loadingIcon = '';
}
});
this.scanStream.on('end', () => {
this.loadingIcon = '';
this.loadMoreDisable = true;
});
this.scanStream.on('error', (e) => {
this.loadingIcon = '';
this.loadMoreDisable = true;
this.$message.error(e.message);
});
},
getScanMatch() {
return this.filterValue ? `*${this.filterValue}*` : '*';
},
openDialog() {
this.$nextTick(() => {
this.$refs.formatViewer.autoFormat();
});
},
showEditDialog(row) {
this.editLineItem = this.$util.cloneObjWithBuff(row);
this.beforeEditItem = row;
this.editDialog = true;
},
dumpCommand(item) {
const lines = item ? [item] : this.setData;
const params = lines.map(line => this.$util.bufToQuotation(line.value));
const command = `SADD ${this.$util.bufToQuotation(this.redisKey)} ${params.join(' ')}`;
this.$util.copyToClipboard(command);
this.$message.success({ message: this.$t('message.copy_success'), duration: 800 });
},
editLine() {
const key = this.redisKey;
const { client } = this;
const before = this.beforeEditItem;
const afterValue = this.$refs.formatViewer.getContent();
if (!afterValue) {
return;
}
// not changed
if (before.value && before.value.equals(afterValue)) {
return this.editDialog = false;
}
this.editDialog = false;
client.sadd(
key,
afterValue,
).then((reply) => {
// add success
if (reply == 1) {
// edit key remove previous value
if (before.value) {
client.srem(key, before.value);
}
// this.initShow(); // do not reinit, #786
const newLine = { value: afterValue };
// edit line
if (before.value) {
this.$set(this.setData, this.setData.indexOf(before), newLine);
}
// new line
else {
this.setData.push(newLine);
this.total++;
}
this.$message.success({
message: this.$t('message.add_success'),
duration: 1000,
});
}
// value exists
else if (reply == 0) {
this.$message.error({
message: this.$t('message.value_exists'),
duration: 1000,
});
}
}).catch((e) => { this.$message.error(e.message); });
},
deleteLine(row) {
this.$confirm(
this.$t('message.confirm_to_delete_row_data'),
{ type: 'warning' },
).then(() => {
this.client.srem(
this.redisKey,
row.value,
).then((reply) => {
if (reply == 1) {
this.$message.success({
message: this.$t('message.delete_success'),
duration: 1000,
});
// this.initShow(); // do not reinit, #786
this.setData.splice(this.setData.indexOf(row), 1);
this.total--;
}
}).catch((e) => { this.$message.error(e.message); });
}).catch(() => {});
},
},
mounted() {
this.initShow();
},
};
</script>
|
2301_77204479/AnotherRedisDesktopManager
|
src/components/contents/KeyContentSet.vue
|
Vue
|
mit
| 8,729
|
<template>
<div class="key-content-stream">
<!-- table toolbar -->
<div>
<el-form :inline="true">
<el-form-item>
<!-- add button -->
<el-button type="primary" @click='showEditDialog({id:"*"})'>{{ $t('message.add_new_line') }}</el-button>
<!-- groups info -->
<el-button type="primary" @click="initGroups">Groups</el-button>
</el-form-item>
<!-- max value -->
<el-form-item label="Max">
<el-input v-model="maxId" @keyup.enter.native="initShow" type="primary" placeholder="Max ID, default +" :title='$t("message.enter_to_search")' size="mini">Max</el-input>
</el-form-item>
<!-- min value -->
<el-form-item label="Min">
<el-input v-model="minId" @keyup.enter.native="initShow" type="primary" placeholder="Min ID, default -" :title='$t("message.enter_to_search")' size="mini">Min</el-input>
</el-form-item>
</el-form>
<!-- edit & add dialog -->
<el-dialog :title="dialogTitle" :visible.sync="editDialog" @open="openDialog" :close-on-click-modal="false">
<el-form>
<el-form-item label="ID">
<InputBinary :disabled="!!beforeEditItem.contentString" :content.sync="editLineItem.id"></InputBinary>
</el-form-item>
<el-form-item label="Value (JSON string)">
<FormatViewer :redisKey="redisKey" :dataMap="editLineItem" :disabled="!!beforeEditItem.contentString" ref="formatViewer" :content="editLineItem.contentString"></FormatViewer>
</el-form-item>
</el-form>
<div slot="footer" class="dialog-footer">
<el-button @click="editDialog = false">{{ $t('el.messagebox.cancel') }}</el-button>
<el-button v-if='!beforeEditItem.contentString' type="primary" @click="editLine">{{ $t('el.messagebox.confirm') }}</el-button>
</div>
</el-dialog>
<!-- groups info dialog -->
<el-dialog width='760px' title='Groups' :visible.sync="groupsVisible">
<el-table
size='mini'
ref='groupsTable'
min-height=300
@expand-change='initCousumers'
@row-click='toggleGroupRow'
:data="groups">
<el-table-column type="expand">
<template slot-scope="props">
<el-table :data='consumersDict[props.row.name]'>
<el-table-column width='62px'>
</el-table-column>
<el-table-column
label="Consumer Name"
prop="name">
</el-table-column>
<el-table-column
label="Pending"
prop="pending">
</el-table-column>
<el-table-column
label="Idle"
prop="idle">
</el-table-column>
</el-table>
</template>
</el-table-column>
<el-table-column
label="Group Name"
prop="name">
</el-table-column>
<el-table-column
label="Consumers"
prop="consumers">
</el-table-column>
<el-table-column
label="Pending"
prop="pending">
</el-table-column>
<el-table-column
label="Last Delivered Id"
prop="last-delivered-id">
</el-table-column>
</el-table>
</el-dialog>
</div>
<!-- vxe table must get a container with a fixed height -->
<div class="content-table-container">
<vxe-table
ref="contentTable"
size="mini" max-height="100%" min-height="72px"
border="default" stripe show-overflow="title"
:scroll-y="{enabled: true}"
:row-config="{isHover: true, height: 34}"
:column-config="{resizable: true}"
:empty-text="$t('el.table.emptyText')"
:data="lineData">
<vxe-column type="seq" :title="'ID (Total: ' + total + ')'" width="150"></vxe-column>
<vxe-column field="id" title="ID" sortable></vxe-column>
<vxe-column field="contentString" title="Value" sortable></vxe-column>
<vxe-column title="Operate" width="166">
<template slot-scope="scope" slot="header">
<el-input size="mini"
:placeholder="$t('message.key_to_search')"
:suffix-icon="loadingIcon"
@keyup.native.enter='initShow()'
v-model="filterValue">
</el-input>
</template>
<template slot-scope="scope">
<el-button type="text" @click="$util.copyToClipboard(scope.row.contentString)" icon="el-icon-document" :title="$t('message.copy')"></el-button>
<el-button type="text" @click="showEditDialog(scope.row)" icon="el-icon-view" :title="$t('message.detail')"></el-button>
<el-button type="text" @click="deleteLine(scope.row)" icon="el-icon-delete" :title="$t('el.upload.delete')"></el-button>
<el-button type="text" @click="dumpCommand(scope.row)" icon="fa fa-code" :title="$t('message.dump_to_clipboard')"></el-button>
</template>
</vxe-column>
</vxe-table>
</div>
<!-- load more content -->
<div class='content-more-container'>
<el-button
size='mini'
@click='initShow(false)'
:icon='loadingIcon'
:disabled='loadMoreDisable'
class='content-more-btn'>
{{ $t('message.load_more_keys') }}
</el-button>
</div>
</div>
</template>
<script>
import FormatViewer from '@/components/FormatViewer';
import InputBinary from '@/components/InputBinary';
import { VxeTable, VxeColumn } from 'vxe-table';
export default {
data() {
return {
total: 0,
editDialog: false,
lineData: [],
beforeEditItem: {},
editLineItem: {},
loadingIcon: '',
pageSize: 200,
searchPageSize: 2000,
loadMoreDisable: false,
minId: '-',
maxId: '+',
lastId: Buffer.from(''),
oneTimeListLength: 0,
filterValue: '',
groupsVisible: false,
groups: [],
consumersDict: {},
};
},
components: { FormatViewer, InputBinary, VxeTable, VxeColumn },
props: ['client', 'redisKey'],
computed: {
dialogTitle() {
return this.beforeEditItem.contentString ? this.$t('message.detail')
: this.$t('message.add_new_line');
},
},
watch: {
lineData(newValue, oldValue) {
// this.$refs.contentTable.refreshScroll()
// scroll to bottom while loading more
if (oldValue.length && (newValue.length > oldValue.length)) {
setTimeout(() => {
this.$refs.contentTable && this.$refs.contentTable.scrollTo(0, 99999999);
}, 0);
}
}
},
methods: {
initShow(resetTable = true) {
resetTable && this.resetTable();
this.loadingIcon = 'el-icon-loading';
// scan
this.listScan();
// total lines
this.initTotal();
},
listScan() {
const maxId = this.lastId.equals(Buffer.from(''))
? (this.maxId ? this.maxId : '+')
: this.lastId;
// +1 for padding the repeat
const pageSize = this.filterValue ? this.searchPageSize
: (this.lineData.length ? this.pageSize + 1 : this.pageSize);
this.client.xrevrangeBuffer([
this.redisKey,
maxId,
this.minId ? this.minId : '-',
'COUNT',
pageSize,
]).then((reply) => {
if (!reply.length) {
return this.loadingIcon = '';
}
// last line of this page
const lastLine = reply[reply.length - 1];
// scanning end
if (this.lastId.equals(lastLine[0])) {
this.loadingIcon = '';
this.oneTimeListLength = 0;
return;
}
const lineData = [];
for (const stream of reply) {
const streamId = stream[0];
const flatDict = stream[1];
// skip first line, it is repeat with the last one of previous page
if (this.lastId.equals(streamId)) {
continue;
}
const content = {};
const line = { id: streamId, content };
// add key value map
for (let i = 0; i < flatDict.length; i += 2) {
content[this.$util.bufToString(flatDict[i])] = this.$util.bufToString(flatDict[i + 1]);
}
line.contentString = JSON.stringify(line.content);
// filter k&v
if (this.filterValue && !line.contentString.includes(this.filterValue)) {
continue;
}
lineData.push(line);
}
// record last id for next load
this.lastId = lastLine[0];
this.oneTimeListLength += lineData.length;
this.lineData = this.lineData.concat(lineData);
if (this.oneTimeListLength >= this.pageSize) {
this.loadingIcon = '';
this.oneTimeListLength = 0;
return;
}
if (this.cancelScanning) {
return;
}
// continue scanning until to pagesize
this.listScan();
}).catch((e) => {
this.loadingIcon = '';
this.$message.error(e.message);
});
},
initTotal() {
this.client.xlen(this.redisKey).then((reply) => {
this.total = reply;
});
},
resetTable() {
this.lineData = [];
this.lastId = Buffer.from('');
this.oneTimeListLength = 0;
this.loadMoreDisable = false;
},
openDialog() {
this.$nextTick(() => {
this.$refs.formatViewer.autoFormat();
});
},
showEditDialog(row) {
this.editLineItem = this.$util.cloneObjWithBuff(row);
this.beforeEditItem = row;
this.editDialog = true;
},
dumpCommand(item) {
const lines = item ? [item] : this.lineData;
const params = lines.map((line) => {
const command = `XADD ${this.$util.bufToQuotation(this.redisKey)} ${line.id} `;
const dicts = [];
for (const field in line.content) {
dicts.push(this.$util.bufToQuotation(field), this.$util.bufToQuotation(line.content[field]));
}
return `${command} ${dicts.join(' ')}`;
});
// reverse: id asc order
this.$util.copyToClipboard(params.reverse().join('\n'));
this.$message.success({ message: this.$t('message.copy_success'), duration: 800 });
},
editLine() {
const afterId = this.editLineItem.id;
const afterValue = this.$refs.formatViewer.getContent();
if (!afterId || !afterValue) {
return;
}
if (!this.$util.isJson(afterValue)) {
return this.$message.error(this.$t('message.json_format_failed'));
}
const mapList = [];
const jsonObj = JSON.parse(afterValue);
for (const k in jsonObj) {
mapList.push(...[k, jsonObj[k]]);
}
this.client.xadd(
this.redisKey,
afterId,
mapList,
).then((reply) => {
// reply is id
if (reply) {
// this.initShow(); // do not reinit, #786
const newLine = { id: reply, content: jsonObj, contentString: afterValue };
this.lineData.unshift(newLine);
this.total++;
this.editDialog = false;
this.$message.success({
message: this.$t('message.add_success'),
duration: 1000,
});
}
}).catch((e) => {
this.$message.error(e.message);
});
},
deleteLine(row) {
this.$confirm(
this.$t('message.confirm_to_delete_row_data'),
{ type: 'warning' },
).then(() => {
this.client.xdel(
this.redisKey,
row.id,
).then((reply) => {
if (reply == 1) {
this.$message.success({
message: this.$t('message.delete_success'),
duration: 1000,
});
// this.initShow(); // do not reinit, #786
this.lineData.splice(this.lineData.indexOf(row), 1);
this.total--;
}
});
}).catch(() => {});
},
initGroups() {
// reset status
this.groups = [];
this.consumersDict = {};
// show dialog
this.groupsVisible = true;
this.client.call('XINFO', 'GROUPS', this.redisKey).then((reply) => {
this.groups = this.formatInfo(reply);
});
},
initCousumers(row, expandedRows) {
// exec only when opening
if (!expandedRows.filter(item => item.name === row.name).length) {
return;
}
this.client.call('XINFO', 'CONSUMERS', this.redisKey, row.name).then((reply) => {
this.$set(this.consumersDict, row.name, this.formatInfo(reply));
});
},
toggleGroupRow(row) {
this.$refs.groupsTable.toggleRowExpansion(row);
},
formatInfo(lines) {
const formatted = [];
for (const line of lines) {
const dict = {};
for (let j = 0; j < line.length - 1; j += 2) {
dict[line[j]] = line[j + 1];
}
formatted.push(dict);
}
return formatted;
},
},
mounted() {
this.initShow();
},
beforeDestroy() {
this.cancelScanning = true;
},
};
</script>
<style type="text/css">
/*key content table wrapper*/
/*less height due to stream top tools*/
.key-content-stream.key-content-container .content-table-container {
height: calc(100vh - 232px);
margin-top: 0px;
}
</style>
|
2301_77204479/AnotherRedisDesktopManager
|
src/components/contents/KeyContentStream.vue
|
Vue
|
mit
| 13,470
|
<template>
<el-form class='key-content-string'>
<!-- key content textarea -->
<el-form-item>
<FormatViewer
ref='formatViewer'
:content='content'
:binary='binary'
:redisKey='redisKey'
float=''>
</FormatViewer>
</el-form-item>
<!-- save btn -->
<el-button ref='saveBtn' type="primary"
@click="execSave" title='Ctrl+s' class="content-string-save-btn">
{{ $t('message.save') }}
</el-button>
</el-form>
</template>
<script>
import FormatViewer from '@/components/FormatViewer';
export default {
data() {
return {
content: Buffer.from(''),
binary: false,
};
},
props: ['client', 'redisKey', 'hotKeyScope'],
components: { FormatViewer },
methods: {
initShow() {
this.client.getBuffer(this.redisKey).then((reply) => {
this.content = reply;
// this.$refs.formatViewer.autoFormat();
});
},
execSave() {
const content = this.$refs.formatViewer.getContent();
// viewer check failed, do not save
if (content === false) {
return;
}
this.client.set(
this.redisKey,
content,
).then((reply) => {
if (reply === 'OK') {
// for compatibility, use expire instead of setex
this.setTTL();
this.initShow();
this.$message.success({
message: this.$t('message.modify_success'),
duration: 1000,
});
} else {
this.$message.error({
message: this.$t('message.modify_failed'),
duration: 1000,
});
}
}).catch((e) => {
this.$message.error(e.message);
});
},
setTTL() {
const ttl = parseInt(this.$parent.$parent.$refs.keyHeader.keyTTL);
if (ttl > 0) {
this.client.expire(this.redisKey, ttl).catch((e) => {
this.$message.error(`Expire Error: ${e.message}`);
}).then((reply) => {});
}
},
initShortcut() {
this.$shortcut.bind('ctrl+s, ⌘+s', this.hotKeyScope, () => {
// make input blur to fill the new value
// this.$refs.saveBtn.$el.focus();
this.execSave();
return false;
});
},
dumpCommand() {
const command = `SET ${this.$util.bufToQuotation(this.redisKey)} ${
this.$util.bufToQuotation(this.content)}`;
this.$util.copyToClipboard(command);
this.$message.success({ message: this.$t('message.copy_success'), duration: 800 });
},
},
mounted() {
this.initShow();
this.initShortcut();
},
};
</script>
|
2301_77204479/AnotherRedisDesktopManager
|
src/components/contents/KeyContentString.vue
|
Vue
|
mit
| 2,580
|
<template>
<div>
<!-- table toolbar -->
<div>
<!-- add button -->
<el-button type="primary" @click="showEditDialog({})">{{ $t('message.add_new_line') }}</el-button>
<!-- edit & add dialog -->
<el-dialog :title="dialogTitle" :visible.sync="editDialog" @open="openDialog" :close-on-click-modal="false">
<el-form>
<el-form-item label="Score">
<el-input v-model="editLineItem.score" autocomplete="off"></el-input>
</el-form-item>
<el-form-item label="Member">
<FormatViewer ref="formatViewer" :redisKey="redisKey" :dataMap="editLineItem" :content="editLineItem.member"></FormatViewer>
</el-form-item>
</el-form>
<div slot="footer" class="dialog-footer">
<el-button @click="editDialog = false">{{ $t('el.messagebox.cancel') }}</el-button>
<el-button type="primary" @click="editLine">{{ $t('el.messagebox.confirm') }}</el-button>
</div>
</el-dialog>
</div>
<!-- vxe table must get a container with a fixed height -->
<div class="content-table-container">
<vxe-table
ref="contentTable"
size="mini" max-height="100%" min-height="72px"
border="default" stripe show-overflow="title"
:scroll-y="{enabled: true}"
:row-config="{isHover: true, height: 34}"
:column-config="{resizable: true}"
:empty-text="$t('el.table.emptyText')"
:data="zsetData">
<vxe-column type="seq" :title="'ID (Total: ' + total + ')'" width="150"></vxe-column>
<vxe-column field="score" title="Score" sortable width="150"></vxe-column>
<vxe-column field="member" title="Member" sortable>
<template v-slot="scope">
{{ $util.cutString($util.bufToString(scope.row.member), 100) }}
</template>
</vxe-column>
<vxe-column title="Operate" width="166">
<template slot-scope="scope" slot="header">
<el-input size="mini"
:placeholder="$t('message.key_to_search')"
:suffix-icon="loadingIcon"
@keyup.native.enter='initShow()'
v-model="filterValue">
</el-input>
</template>
<template slot-scope="scope">
<el-button type="text" @click="$util.copyToClipboard(scope.row.member)" icon="el-icon-document" :title="$t('message.copy')"></el-button>
<el-button type="text" @click="showEditDialog(scope.row)" icon="el-icon-edit" :title="$t('message.edit_line')"></el-button>
<el-button type="text" @click="deleteLine(scope.row)" icon="el-icon-delete" :title="$t('el.upload.delete')"></el-button>
<el-button type="text" @click="dumpCommand(scope.row)" icon="fa fa-code" :title="$t('message.dump_to_clipboard')"></el-button>
</template>
</vxe-column>
</vxe-table>
</div>
<!-- load more content -->
<div class='content-more-container'>
<el-button
size='mini'
@click='initShow(false)'
:icon='loadingIcon'
:disabled='loadMoreDisable'
class='content-more-btn'>
{{ $t('message.load_more_keys') }}
</el-button>
</div>
</div>
</template>
<script>
import FormatViewer from '@/components/FormatViewer';
import { VxeTable, VxeColumn } from 'vxe-table';
export default {
data() {
return {
total: 0,
filterValue: '',
editDialog: false,
zsetData: [], // {score: 111, member: xxx}
beforeEditItem: {},
editLineItem: {},
loadingIcon: '',
pageSize: 200,
pageIndex: 0,
searchPageSize: 2000,
oneTimeListLength: 0,
scanStream: null,
loadMoreDisable: false,
};
},
props: ['client', 'redisKey'],
components: { FormatViewer, VxeTable, VxeColumn },
computed: {
dialogTitle() {
return this.beforeEditItem.member ? this.$t('message.edit_line')
: this.$t('message.add_new_line');
},
},
watch: {
zsetData(newValue, oldValue) {
// this.$refs.contentTable.refreshScroll()
// scroll to bottom while loading more
if (oldValue.length && (newValue.length > oldValue.length)) {
setTimeout(() => {
this.$refs.contentTable && this.$refs.contentTable.scrollTo(0, 99999999);
}, 0);
}
}
},
methods: {
initShow(resetTable = true) {
resetTable && this.resetTable();
this.loadingIcon = 'el-icon-loading';
// search mode, scan, random order
if (this.getScanMatch() != '*') {
this.getListScan();
}
// default mode, ordered
else {
this.getListRange(resetTable);
this.pageIndex++;
}
// total lines
this.initTotal();
},
initTotal() {
this.client.zcard(this.redisKey).then((reply) => {
this.total = reply;
}).catch((e) => {});
},
resetTable() {
// stop scanning first, #815
this.scanStream && this.scanStream.pause();
this.zsetData = [];
this.pageIndex = 0;
this.scanStream = null;
this.oneTimeListLength = 0;
this.loadMoreDisable = false;
},
getListRange(resetTable) {
const start = this.pageSize * this.pageIndex;
const end = start + this.pageSize - 1;
this.client.zrevrangeBuffer([this.redisKey, start, end, 'WITHSCORES']).then((reply) => {
const zsetData = this.solveList(reply);
this.zsetData = resetTable ? zsetData : this.zsetData.concat(zsetData);
(zsetData.length < this.pageSize) && (this.loadMoreDisable = true);
this.loadingIcon = '';
}).catch((e) => {
this.loadingIcon = '';
this.loadMoreDisable = true;
this.$message.error(e.message);
});
},
getListScan() {
if (!this.scanStream) {
this.initScanStream();
} else {
this.oneTimeListLength = 0;
this.scanStream.resume();
}
},
initScanStream() {
const scanOption = { match: this.getScanMatch(), count: this.pageSize };
scanOption.match != '*' && (scanOption.count = this.searchPageSize);
this.scanStream = this.client.zscanBufferStream(
this.redisKey,
scanOption,
);
this.scanStream.on('data', (reply) => {
const zsetData = this.solveList(reply);
this.oneTimeListLength += zsetData.length;
this.zsetData = this.zsetData.concat(zsetData);
if (this.oneTimeListLength >= this.pageSize) {
this.scanStream.pause();
this.loadingIcon = '';
}
});
this.scanStream.on('end', () => {
this.loadingIcon = '';
this.loadMoreDisable = true;
});
this.scanStream.on('error', (e) => {
this.loadingIcon = '';
this.loadMoreDisable = true;
this.$message.error(e.message);
});
},
solveList(list) {
if (!list) {
return [];
}
const zsetData = [];
for (let i = 0; i < list.length; i += 2) {
zsetData.push({
score: Number(list[i + 1]),
member: list[i],
// memberDisplay: this.$util.bufToString(list[i]),
});
}
return zsetData;
},
getScanMatch() {
return this.filterValue ? `*${this.filterValue}*` : '*';
},
openDialog() {
this.$nextTick(() => {
this.$refs.formatViewer.autoFormat();
});
},
showEditDialog(row) {
this.editLineItem = this.$util.cloneObjWithBuff(row);
this.beforeEditItem = row;
this.editDialog = true;
},
dumpCommand(item) {
const lines = item ? [item] : this.zsetData;
const params = lines.map(line => `${String(line.score)} ${
this.$util.bufToQuotation(line.member)}`);
const command = `ZADD ${this.$util.bufToQuotation(this.redisKey)} ${params.join(' ')}`;
this.$util.copyToClipboard(command);
this.$message.success({ message: this.$t('message.copy_success'), duration: 800 });
},
editLine() {
const key = this.redisKey;
const { client } = this;
const before = this.beforeEditItem;
const afterScore = this.editLineItem.score;
const afterMember = this.$refs.formatViewer.getContent();
if (!afterMember || isNaN(afterScore)) {
return;
}
this.editDialog = false;
client.zadd(
key,
afterScore,
afterMember,
).then((reply) => {
// edit key member changed
if (before.member && !before.member.equals(afterMember)) {
client.zrem(key, before.member);
}
// this.initShow(); // do not reinit, #786
const newLine = { score: afterScore, member: afterMember };
// edit line
if (before.member) {
this.$set(this.zsetData, this.zsetData.indexOf(before), newLine);
}
// new line
else {
this.zsetData.push(newLine);
this.total++;
}
this.$message.success({
message: reply == 1 ? this.$t('message.add_success') : this.$t('message.modify_success'),
duration: 1000,
});
}).catch((e) => { this.$message.error(e.message); });
},
deleteLine(row) {
this.$confirm(
this.$t('message.confirm_to_delete_row_data'),
{ type: 'warning' },
).then(() => {
this.client.zrem(
this.redisKey,
row.member,
).then((reply) => {
if (reply == 1) {
this.$message.success({
message: this.$t('message.delete_success'),
duration: 1000,
});
// this.initShow(); // do not reinit, #786
this.zsetData.splice(this.zsetData.indexOf(row), 1);
this.total--;
}
}).catch((e) => { this.$message.error(e.message); });
}).catch(() => {});
},
},
mounted() {
this.initShow();
},
};
</script>
|
2301_77204479/AnotherRedisDesktopManager
|
src/components/contents/KeyContentZset.vue
|
Vue
|
mit
| 9,931
|
<template>
<div>
<!-- </textarea> -->
<el-input ref='textInput' :disabled='disabled' type='textarea' v-model='contentDisplay'></el-input>
</div>
</template>
<script type="text/javascript">
export default {
data() {
return {
contentDisplay: '',
};
},
props: ['content', 'contentVisible', 'disabled'],
watch: {
content(val) {
// refresh
this.contentDisplay = this.$util.bufToBinary(val);
},
},
methods: {
getContent() {
return this.$util.binaryStringToBuffer(this.contentDisplay);
},
},
mounted() {
this.contentDisplay = this.$util.bufToBinary(this.content);
},
};
</script>
|
2301_77204479/AnotherRedisDesktopManager
|
src/components/viewers/ViewerBinary.vue
|
Vue
|
mit
| 656
|
<template>
<JsonEditor ref='editor' :content='newContent' :readOnly='false'></JsonEditor>
</template>
<script type="text/javascript">
import JsonEditor from '@/components/JsonEditor';
const JSONbig = require('@qii404/json-bigint')({ useNativeBigInt: false });
const zlib = require('zlib');
export default {
components: { JsonEditor },
props: ['content'],
computed: {
newContent() {
const { formatStr } = this;
if (typeof formatStr === 'string') {
if (this.$util.isJson(formatStr)) {
return JSONbig.parse(formatStr);
}
return formatStr;
}
return 'Zlib Brotli Parse Failed!';
},
formatStr() {
return this.$util.zippedToString(this.content, 'brotli');
},
},
methods: {
getContent() {
const content = this.$refs.editor.getRawContent(true);
return zlib.brotliCompressSync(content);
},
copyContent() {
return this.formatStr;
},
},
};
</script>
|
2301_77204479/AnotherRedisDesktopManager
|
src/components/viewers/ViewerBrotli.vue
|
Vue
|
mit
| 972
|
<template>
<JsonEditor ref='editor' :content='newContent' class='viewer-custom-editor'>
<p :title="fullCommand" class="command-preview">
<el-button size="mini" class="viewer-custom-copy-raw"
:title='$t("message.copy")' icon="el-icon-document" type="text"
@click="$util.copyToClipboard(fullCommand)">
</el-button>
{{ previewCommand }}
</p>
</JsonEditor>
</template>
<script type="text/javascript">
import storage from '@/storage';
import shell from 'child_process';
import JsonEditor from '@/components/JsonEditor';
import { ipcRenderer } from 'electron';
export default {
data() {
return {
execResult: '',
fullCommand: '',
previewCommand: '',
previewContentMax: 50,
writeHexFileSize: 8000,
};
},
components: { JsonEditor },
props: ['content', 'name', 'dataMap', 'redisKey'],
computed: {
newContent() {
if (this.$util.isJson(this.execResult)) {
return JSON.parse(this.execResult);
}
return this.execResult;
},
},
watch: {
content() {
this.execCommand();
},
},
methods: {
getCommand() {
const formatter = storage.getCustomFormatter(this.name);
if (!formatter) {
return false;
}
const { command } = formatter;
const { params } = formatter;
const paramsReplaced = this.replaceTemplate(params);
return `"${command}" ${paramsReplaced}`;
},
replaceTemplate(params) {
if (!params) {
return '';
}
const dataMap = this.dataMap ? this.dataMap : {};
const mapObj = {
'{KEY}': this.redisKey,
// "{VALUE}": this.content,
'{FIELD}': dataMap.key,
'{SCORE}': dataMap.score,
'{MEMBER}': dataMap.member,
};
const re = new RegExp(Object.keys(mapObj).join('|'), 'gi');
return params.replace(re, matched => mapObj[matched]);
},
execCommand() {
if (!this.content || !this.content.length) {
return this.execResult = '';
}
const command = this.getCommand();
const hexStr = this.content.toString('hex');
if (!command) {
return this.execResult = 'Command Error, Check Config!';
}
this.fullCommand = command.replace(
'{VALUE}',
this.content,
);
// in case of long content in template
this.previewCommand = command.replace(
'{VALUE}',
this.$util.cutString(this.content.toString(), this.previewContentMax),
);
// if content is too long, write to file simultaneously
// hex str is about 2 times of real size
if (hexStr.length > this.writeHexFileSize) {
ipcRenderer.invoke('getTempPath').then((reply) => {
// target file name
const fileName = `ardm_cv_${this.redisKey.toString('hex')}`;
const filePath = require('path').join(reply, fileName);
require('fs').writeFile(filePath, hexStr, (err) => {
if (err) {
return this.$message.error(err);
}
this.fullCommand = this.fullCommand
.replace('{HEX_FILE}', filePath)
.replace('{HEX}', '<Content Too Long, Use {HEX_FILE} Instead!>');
this.previewCommand = this.previewCommand
.replace('{HEX_FILE}', filePath)
.replace('{HEX}', '<Content Too Long, Use {HEX_FILE} Instead!>');
this.exec();
});
});
}
// common content just exec
else {
this.fullCommand = this.fullCommand
.replace('{HEX}', hexStr)
.replace('{HEX_FILE}', '<Use {HEX} Instead!>');
this.previewCommand = this.previewCommand
.replace(
'{HEX}',
this.$util.cutString(hexStr, this.previewContentMax),
)
.replace('{HEX_FILE}', '<Use {HEX} Instead!>');
this.exec();
}
},
exec() {
try {
shell.exec(this.fullCommand, (error, stdout, stderr) => {
if (error || stderr) {
this.execResult = error ? error.message : stderr;
} else {
this.execResult = stdout.trim();
}
});
} catch (e) {
return this.execResult = e.message;
}
},
},
mounted() {
this.execCommand();
},
};
</script>
<style type="text/css">
.text-formated-container .command-preview {
color: #9798a7;
word-break: break-all;
height: 40px;
overflow-y: auto;
line-height: 20px;
margin-bottom: 2px;
}
/*copy raw command btn*/
.text-formated-container .command-preview .viewer-custom-copy-raw {
padding: 0;
}
/*make monaco less height in custom viewer*/
.key-content-string .text-formated-container.viewer-custom-editor .monaco-editor-con {
height: calc(100vh - 331px);
/* min-height: 50px;*/
}
</style>
|
2301_77204479/AnotherRedisDesktopManager
|
src/components/viewers/ViewerCustom.vue
|
Vue
|
mit
| 4,834
|
<template>
<JsonEditor ref='editor' :content='newContent' :readOnly='false'></JsonEditor>
</template>
<script type="text/javascript">
import JsonEditor from '@/components/JsonEditor';
const JSONbig = require('@qii404/json-bigint')({ useNativeBigInt: false });
const zlib = require('zlib');
export default {
components: { JsonEditor },
props: ['content'],
computed: {
newContent() {
const { formatStr } = this;
if (typeof formatStr === 'string') {
if (this.$util.isJson(formatStr)) {
return JSONbig.parse(formatStr);
}
return formatStr;
}
return 'Zlib Deflate Parse Failed!';
},
formatStr() {
return this.$util.zippedToString(this.content, 'deflate');
},
},
methods: {
getContent() {
const content = this.$refs.editor.getRawContent(true);
return zlib.deflateSync(content);
},
copyContent() {
return this.formatStr;
},
},
};
</script>
|
2301_77204479/AnotherRedisDesktopManager
|
src/components/viewers/ViewerDeflate.vue
|
Vue
|
mit
| 967
|
<template>
<JsonEditor ref='editor' :content='newContent' :readOnly='false'></JsonEditor>
</template>
<script type="text/javascript">
import JsonEditor from '@/components/JsonEditor';
const JSONbig = require('@qii404/json-bigint')({ useNativeBigInt: false });
const zlib = require('zlib');
export default {
components: { JsonEditor },
props: ['content'],
computed: {
newContent() {
const { formatStr } = this;
if (typeof formatStr === 'string') {
if (this.$util.isJson(formatStr)) {
return JSONbig.parse(formatStr);
}
return formatStr;
}
return 'Zlib DeflateRaw Parse Failed!';
},
formatStr() {
return this.$util.zippedToString(this.content, 'deflateRaw');
},
},
methods: {
getContent() {
const content = this.$refs.editor.getRawContent(true);
return zlib.deflateRawSync(content);
},
copyContent() {
return this.formatStr;
},
},
};
</script>
|
2301_77204479/AnotherRedisDesktopManager
|
src/components/viewers/ViewerDeflateRaw.vue
|
Vue
|
mit
| 976
|
<template>
<JsonEditor ref='editor' :content='newContent' :readOnly='false'></JsonEditor>
</template>
<script type="text/javascript">
import JsonEditor from '@/components/JsonEditor';
const JSONbig = require('@qii404/json-bigint')({ useNativeBigInt: false });
const zlib = require('zlib');
export default {
components: { JsonEditor },
props: ['content'],
computed: {
newContent() {
const { formatStr } = this;
if (typeof formatStr === 'string') {
if (this.$util.isJson(formatStr)) {
return JSONbig.parse(formatStr);
}
return formatStr;
}
return 'Zlib Gzip Parse Failed!';
},
formatStr() {
return this.$util.zippedToString(this.content, 'gzip');
},
},
methods: {
getContent() {
const content = this.$refs.editor.getRawContent(true);
return zlib.gzipSync(content);
},
copyContent() {
return this.formatStr;
},
},
};
</script>
|
2301_77204479/AnotherRedisDesktopManager
|
src/components/viewers/ViewerGzip.vue
|
Vue
|
mit
| 958
|
<template>
<div>
<!-- </textarea> -->
<el-input ref='textInput' :disabled='disabled' type='textarea' v-model='contentDisplay'></el-input>
</div>
</template>
<script type="text/javascript">
export default {
data() {
return {
contentDisplay: '',
};
},
props: ['content', 'contentVisible', 'disabled'],
watch: {
content(val) {
// refresh
this.contentDisplay = this.$util.bufToString(val);
},
},
methods: {
getContent() {
return this.$util.xToBuffer(this.contentDisplay);
},
},
mounted() {
this.contentDisplay = this.$util.bufToString(this.content);
},
};
</script>
|
2301_77204479/AnotherRedisDesktopManager
|
src/components/viewers/ViewerHex.vue
|
Vue
|
mit
| 645
|
<template>
<JsonEditor ref='editor' :content='newContent' :readOnly='true'></JsonEditor>
</template>
<script type="text/javascript">
import JsonEditor from '@/components/JsonEditor';
import { ObjectInputStream } from 'java-object-serialization';
export default {
props: ['content'],
components: { JsonEditor },
computed: {
newContent() {
try {
// ref RedisInsight
const result = (new ObjectInputStream(this.content)).readObject();
if (typeof result !== 'object') {
return result;
}
const fields = Array.from(result.fields, ([key, value]) => ({ [key]: value }));
return { ...result, fields };
} catch (e) {
return 'Java unserialize failed!';
}
},
},
methods: {
getContent() {
this.$message.error('Java unserialization is readonly now!');
return false;
},
copyContent() {
return this.$refs.editor.getRawContent();
},
},
};
</script>
|
2301_77204479/AnotherRedisDesktopManager
|
src/components/viewers/ViewerJavaSerialize.vue
|
Vue
|
mit
| 975
|
<template>
<JsonEditor ref='editor' :content='newContent' :readOnly='disabled||false'></JsonEditor>
</template>
<script type="text/javascript">
import JsonEditor from '@/components/JsonEditor';
const JSONbig = require('@qii404/json-bigint')({ useNativeBigInt: false });
export default {
props: ['content', 'disabled'],
components: { JsonEditor },
computed: {
newContent() {
try {
const parsedObj = JSONbig.parse(this.content);
// if JSON.parse returns string, means raw content like "{\"name\":\"age\"}"
// (JSON string wrapped with quotation) issue #909
if (typeof parsedObj === 'string') {
this.jsonIsString = true;
}
return parsedObj;
} catch (e) {
// parse failed, return raw content to edit instead of error
return this.content.toString();
}
},
},
methods: {
getContent() {
const content = this.$refs.editor.getContent();
if (!content) {
return false;
}
// json in string, quotation wrapped and escaped,
if (this.jsonIsString) {
return JSONbig.stringify(content.toString());
}
return content;
},
},
};
</script>
|
2301_77204479/AnotherRedisDesktopManager
|
src/components/viewers/ViewerJson.vue
|
Vue
|
mit
| 1,203
|
<template>
<JsonEditor ref='editor' :content='newContent' :readOnly='false'></JsonEditor>
</template>
<script type="text/javascript">
import JsonEditor from '@/components/JsonEditor';
import { decode, encode } from 'algo-msgpack-with-bigint';
const JSONbig = require('@qii404/json-bigint')({ useNativeBigInt: true });
export default {
props: ['content'],
components: { JsonEditor },
computed: {
newContent() {
try {
return decode(this.content);
} catch (e) {
return this.$t('message.msgpack_format_failed');
}
},
},
methods: {
getContent() {
let content = this.$refs.editor.getRawContent();
// raw content is an object
if (typeof this.newContent !== 'string') {
try {
content = JSONbig.parse(content);
} catch (e) {
// object parse failed
this.$message.error({
message: `Raw content is an object, but now parse object failed: ${e.message}`,
duration: 6000,
});
return false;
}
}
// encode returns Uint8Array
return Buffer.from(encode(content));
},
copyContent() {
const content = decode(this.content);
return (typeof content === 'object') ? JSONbig.stringify(content) : content;
},
},
};
</script>
|
2301_77204479/AnotherRedisDesktopManager
|
src/components/viewers/ViewerMsgpack.vue
|
Vue
|
mit
| 1,323
|
<template>
<div class="size-too-large-viewer">
<el-alert
:closable='false'
:title='alertTitle'
type="error">
</el-alert>
<el-input :disabled='true' type='textarea' :value='contentDisplay'></el-input>
</div>
</template>
<script type="text/javascript">
export default {
data() {
return {
firstChars: 20000,
};
},
props: ['content', 'contentVisible', 'disabled'],
computed: {
contentDisplay() {
return `${this.$util.bufToString(this.content.slice(0, this.firstChars), false)
}...Show only the first ${this.firstChars} characters, the rest has been hidden...`;
},
alertTitle() {
return `Size too large, show only the first ${this.firstChars} characters and you cannot edit it.`;
},
},
};
</script>
<style type="text/css">
.size-too-large-viewer .el-alert {
margin: 3px 0 8px 0;
color: #f56c6c;
background-color: #f9dbdb;
}
/*text viewer box*/
.key-content-string .size-too-large-viewer .el-textarea textarea {
height: calc(100vh - 290px);
}
</style>
|
2301_77204479/AnotherRedisDesktopManager
|
src/components/viewers/ViewerOverSize.vue
|
Vue
|
mit
| 1,067
|
<template>
<JsonEditor ref='editor' :content='newContent' :readOnly='isPHPClass'></JsonEditor>
</template>
<script type="text/javascript">
import JsonEditor from '@/components/JsonEditor';
import { unserialize, serialize } from 'php-serialize';
export default {
props: ['content'],
data() {
return {
isPHPClass: false,
};
},
components: { JsonEditor },
computed: {
newContent() {
try {
const content = unserialize(this.content, {}, { strict: false });
if (content && content['__PHP_Incomplete_Class_Name']) {
this.isPHPClass = true;
}
return content;
} catch (e) {
return this.$t('message.php_unserialize_format_failed');
}
},
},
methods: {
getContent() {
let content = this.$refs.editor.getRawContent();
// raw content is an object
if (typeof this.newContent !== 'string') {
try {
content = JSON.parse(content);
} catch (e) {
// object parse failed
this.$message.error({
message: `Raw content is an object, but now parse object failed: ${e.message}`,
duration: 6000,
});
return false;
}
}
return serialize(content);
},
},
};
</script>
|
2301_77204479/AnotherRedisDesktopManager
|
src/components/viewers/ViewerPHPSerialize.vue
|
Vue
|
mit
| 1,288
|
<template>
<JsonEditor ref='editor' :content='newContent' :readOnly='true'></JsonEditor>
</template>
<script type="text/javascript">
import JsonEditor from '@/components/JsonEditor';
import { Parser } from 'pickleparser';
export default {
props: ['content'],
components: { JsonEditor },
computed: {
newContent() {
try {
return (new Parser()).parse(this.content);
} catch (e) {
return 'Pickle parsed failed!';
}
},
},
methods: {
getContent() {
this.$message.error('Pickle is readonly now!');
return false;
},
copyContent() {
return this.$refs.editor.getRawContent();
},
},
};
</script>
|
2301_77204479/AnotherRedisDesktopManager
|
src/components/viewers/ViewerPickle.vue
|
Vue
|
mit
| 677
|
<template>
<JsonEditor ref='editor' :content='newContent' :readOnly='false' class='protobuf-viewer'>
<div class="viewer-protobuf-header">
<!-- type selector -->
<el-select v-model="selectedType" filterable placeholder="Select Type" size="mini" class="type-selector">
<el-option
v-for="t of types"
:key="t"
:label="t"
:value="t">
</el-option>
</el-select>
<!-- select proto file -->
<el-button class="select-proto-btn" type='primary' size="mini" icon="el-icon-upload2" @click="selectProto">Select Proto Files</el-button>
</div>
<!-- selected files -->
<!-- <el-tag v-for="p of proto" :key="p" class="selected-proto-file-tag">{{ p }}</el-tag> -->
<hr>
</JsonEditor>
</template>
<script type="text/javascript">
import JsonEditor from '@/components/JsonEditor';
import { getData } from 'rawproto';
// import * as protobuf from 'protobufjs';
const protobuf = require('protobufjs/minimal');
const { dialog } = require('electron').remote;
export default {
data() {
return {
proto: [],
protoRoot: null,
types: ['Rawproto'],
selectedType: 'Rawproto',
};
},
components: { JsonEditor },
props: ['content'],
computed: {
newContent() {
try {
if (this.selectedType === 'Rawproto') {
return getData(this.content);
}
const type = this.protoRoot.lookupType(this.selectedType);
const message = type.decode(this.content);
return message.toJSON();
} catch (e) {
return 'Protobuf Decode Failed!';
}
},
},
methods: {
traverseTypes(current) {
if (current instanceof protobuf.Type) {
this.types.push(current.fullName);
}
if (current.nestedArray) {
current.nestedArray.forEach((nested) => {
this.traverseTypes(nested);
});
}
},
selectProto() {
dialog.showOpenDialog({
properties: ['openFile', 'multiSelections'],
filters: [
{
name: '.proto',
extensions: ['proto'],
},
],
}).then((result) => {
if (result.canceled) return;
this.proto = result.filePaths;
this.types = ['Rawproto'];
this.selectedType = 'Rawproto';
protobuf.load(this.proto).then((root) => {
this.protoRoot = root;
// init types
this.traverseTypes(root);
// first type as default
if (this.types.length > 0) {
this.selectedType = this.types[1];
}
}).catch((e) => {
this.$message.error(e.message);
});
}).catch((e) => {
this.$message.error(e.message);
});
},
getContent() {
if (!this.protoRoot) {
this.$message.error('Select a correct .proto file');
return false;
}
if (!this.selectedType || this.selectedType === 'Rawproto') {
this.$message.error('Select a correct Type to encode');
return false;
}
let content = this.$refs.editor.getRawContent();
const type = this.protoRoot.lookupType(this.selectedType);
try {
content = JSON.parse(content);
const err = type.verify(content);
if (err) {
this.$message.error(`Proto Verify Failed: ${err}`);
return false;
}
const message = type.create(content);
return type.encode(message).finish();
} catch (e) {
this.$message.error(this.$t('message.json_format_failed'));
return false;
}
},
copyContent() {
return JSON.stringify(this.newContent);
},
},
};
</script>
<style type="text/css">
.viewer-protobuf-header {
display: flex;
margin-top: 8px;
}
.viewer-protobuf-header .type-selector {
flex: 1;
margin-right: 10px;
}
.viewer-protobuf-header .select-proto-btn {
margin-top: 2px;
height: 27px;
}
.selected-proto-file-tag {
margin-right: 4px;
}
/*text viewer box*/
.key-content-string .text-formated-container.protobuf-viewer .monaco-editor-con {
height: calc(100vh - 331px);
}
</style>
|
2301_77204479/AnotherRedisDesktopManager
|
src/components/viewers/ViewerProtobuf.vue
|
Vue
|
mit
| 4,171
|
<template>
<div>
<!-- </textarea> -->
<el-input ref='textInput' :disabled='disabled' type='textarea' v-model='contentDisplay' @input='inputContent'>
</el-input>
</div>
</template>
<script type="text/javascript">
export default {
data() {
return {
confirmChange: false,
contentDisplay: '',
oldContentDisplay: '',
};
},
props: ['content', 'contentVisible', 'disabled'],
watch: {
content(val) {
// refresh
this.contentDisplay = val.toString();
this.oldContentDisplay = this.contentDisplay;
},
},
methods: {
getContent() {
// not changed
if (!this.contentVisible && !this.confirmChange) {
return this.content;
}
return Buffer.from(this.contentDisplay);
},
inputContent(value) {
// visible content do nothing
if (this.contentVisible) {
return;
}
// confirmed change content
if (this.confirmChange) {
return;
}
this.$confirm(this.$t('message.confirm_modify_unvisible_content')).then(_ => this.confirmChange = true).catch((_) => {
// recovery the input value
this.contentDisplay = this.oldContentDisplay;
});
},
},
mounted() {
this.contentDisplay = this.content.toString();
this.oldContentDisplay = this.contentDisplay;
},
};
</script>
|
2301_77204479/AnotherRedisDesktopManager
|
src/components/viewers/ViewerText.vue
|
Vue
|
mit
| 1,355
|
import Vue from 'vue';
import VueI18n from 'vue-i18n';
import locale from 'element-ui/lib/locale';
import enLocale from 'element-ui/lib/locale/lang/en';
import zhLocale from 'element-ui/lib/locale/lang/zh-CN';
import zhTwLocale from 'element-ui/lib/locale/lang/zh-TW';
import trTrLocale from 'element-ui/lib/locale/lang/tr-TR';
import ruLocale from 'element-ui/lib/locale/lang/ru-RU';
import ptBrLocale from 'element-ui/lib/locale/lang/pt-br';
import deLocale from 'element-ui/lib/locale/lang/de';
import frLocale from 'element-ui/lib/locale/lang/fr';
import uaLocale from 'element-ui/lib/locale/lang/ua';
import itLocale from 'element-ui/lib/locale/lang/it';
import esLocale from 'element-ui/lib/locale/lang/es';
import koLocale from 'element-ui/lib/locale/lang/ko';
import en from './langs/en';
import cn from './langs/cn';
import tw from './langs/tw';
import tr from './langs/tr';
import ru from './langs/ru';
import pt from './langs/pt';
import de from './langs/de';
import fr from './langs/fr';
import ua from './langs/ua';
import it from './langs/it';
import es from './langs/es';
import ko from './langs/ko';
Vue.use(VueI18n);
const messages = {
en: {
...en,
...enLocale,
},
cn: {
...cn,
...zhLocale,
},
tw: {
...tw,
...zhTwLocale,
},
tr: {
...tr,
...trTrLocale,
},
ru: {
...ru,
...ruLocale,
},
pt: {
...pt,
...ptBrLocale,
},
de: {
...de,
...deLocale,
},
fr: {
...fr,
...frLocale,
},
ua: {
...ua,
...uaLocale,
},
it: {
...it,
...itLocale,
},
es: {
...es,
...esLocale,
},
ko: {
...ko,
...koLocale,
},
};
const i18n = new VueI18n({
locale: localStorage.lang || 'en',
messages,
});
locale.i18n((key, value) => i18n.t(key, value));
export default i18n;
|
2301_77204479/AnotherRedisDesktopManager
|
src/i18n/i18n.js
|
JavaScript
|
mit
| 1,812
|
const cn = {
message: {
new_connection: '新建连接',
refresh_connection: '刷新',
edit_connection: '编辑连接',
duplicate_connection: '复制连接',
del_connection: '删除连接',
close_connection: '关闭连接',
add_new_line: '添加新行',
dump_to_clipboard: '复制为命令',
redis_version: 'Redis版本',
process_id: '进程ID',
used_memory: '已用内存',
used_memory_peak: '内存占用峰值',
used_memory_lua: 'Lua占用内存',
connected_clients: '客户端连接数',
total_connections_received: '历史连接数',
total_commands_processed: '历史命令数',
key_statistics: '键值统计',
all_redis_info: 'Redis信息全集',
server: '服务器',
memory: '内存',
stats: '状态',
settings: '基础设置',
ui_settings: '外观',
feature_settings: '功能',
common_settings: '通用',
confirm_to_delete_row_data: '确认删除该行数据?',
delete_success: '删除成功',
delete_failed: '删除失败',
modify_success: '修改成功',
modify_failed: '修改失败',
add_success: '添加成功',
add_failed: '添加失败',
value_exists: '值已存在',
value_not_exists: '该值不存在',
refresh_success: '刷新成功',
click_enter_to_rename: '点击或者按Enter键来重命名',
click_enter_to_ttl: '点击或者按Enter键来修改过期时间',
confirm_to_delete_key: '确认删除 {key} ?',
confirm_to_rename_key: '确认重命名 {old} -> {new} ?',
edit_line: '修改行',
auto_refresh: '自动刷新',
auto_refresh_tip: '自动刷新开关,每{interval}秒刷新一次',
key_not_exists: '键不存在',
collapse_all: '全部折叠',
expand_all: '全部展开',
json_format_failed: 'Json 格式化失败',
msgpack_format_failed: 'Msgpack 格式化失败',
php_unserialize_format_failed: 'PHP Unserialize 格式化失败',
clean_up: '清空',
redis_console: 'Redis 控制台',
confirm_to_delete_connection: '确认删除连接?',
connection_exists: '连接配置已存在',
close_to_edit_connection: '编辑前必须关闭连接,要继续么',
close_to_connection: '确认关闭连接?',
ttl_delete: '设置TTL<=0将删除该key,是否确认?',
max_page_reached: '已到达最大页码',
add_new_key: '新增Key',
enter_new_key: '请先输入新的key名称',
key_type: '类型',
save: '保存',
enter_to_search: 'Enter 键进行搜索',
export_success: '导出成功',
select_import_file: '选择配置文件',
import_success: '导入成功',
put_file_here: '将文件拖到此处,或点击选择',
config_connections: '连接配置',
import: '导入',
export: '导出',
open: '打开',
close: '关闭',
open_new_tab: '新窗口打开',
exact_search: '精确搜索',
enter_to_exec: '输入Redis命令后,按Enter键执行,上下键切换历史',
pre_version: '当前版本',
manual_update: '手动下载',
retry_too_many_times: '尝试重连次数过多,请检查Server状态',
key_to_search: '输入关键字搜索',
search_connection: '搜索链接',
begin_update: '更新',
ignore_this_version: '忽略该版本',
check_update: '检查更新',
update_checking: '检查更新中, 请稍后...',
update_available: '发现新版本',
update_not_available: '当前为最新版本',
update_error: '更新失败',
update_downloading: '下载中...',
update_download_progress: '下载进度',
update_downloaded: '更新下载完成,重启客户端生效.\
[Tips]: 如果您使用的是Windows,关闭软件后,请等待桌面图标刷新到正常状态(约10秒),然后再重新打开即可',
mac_not_support_auto_update: 'Mac暂时不支持自动更新,请手动<a href="https://github.com/qishibo/AnotherRedisDesktopManager/releases">下载</a>后重新安装,\
或者执行<br><code>brew reinstall --cask another-redis-desktop-manager </code>\
<br><hr><br>❤️如果您觉得好用,可以通过<a href="https://apps.apple.com/app/id1516451072">AppStore</a>赞助,并由AppStore帮您自动更新',
font_family: '字体选择',
font_faq_title: '字体设置说明',
font_faq: '1. 可以设置多个字体<br>2. 字体选择是有序的,建议首先选择英文字体,然后再选择中文字体<br>\
3. 某些异常情况无法加载系统字体列表时,可以手动输入已安装字体名称',
private_key_faq: '目前支持RSA格式私钥,即以<pre>-----BEGIN RSA PRIVATE KEY-----</pre>开头,\
以<pre>-----BEGIN OPENSSH PRIVATE KEY-----</pre>开头的,需要执行\
<pre>ssh-keygen -p -m pem -f ~/.ssh/id_rsa</pre>进行格式转换后再使用,该操作不会影响以前的私钥登陆',
dark_mode: '深色模式',
load_more_keys: '加载更多',
key_name: '键名',
project_home: '项目主页',
cluster_faq: '选择集群中任一节点配置填入即可,会自动识别其它节点',
redis_status: 'Redis信息',
confirm_flush_db: '确认删除db{db}中的所有键值么?',
flushdb: '删除所有键',
flushdb_prompt: '请输入 "{txt}"',
info_disabled: 'Info命令执行异常(可能已被禁用),无法显示Redis信息',
page_zoom: '页面缩放',
scan_disabled: 'Scan命令执行异常(可能已被禁用),无法显示Key列表',
key_type_not_support: '该类型暂不支持可视化展示,请使用命令行进行操作',
delete_folder: '扫描并删除整个文件夹',
multiple_select: '多项选择',
copy: '复制',
copy_success: '复制成功',
keys_to_be_deleted: '即将删除的键值',
delete_all: '全部删除',
clear_cache: '清除缓存',
mark_color: '标记颜色',
key_no_permission: '文件读取权限已过期,请手动重新选择密钥文件',
toggle_check_all: '全选 | 取消全选',
select_lang: '选择语言',
clear_cache_tip: '当客户端出现问题时,该操作会删除所有连接和配置,用于恢复客户端',
detail: '详情',
separator_tip: '树状显示的分隔符,设置为空可以禁用树状图,直接以列表展示',
confirm_modify_unvisible_content: '内容中包含不可见字符,你可以在Hex视图中进行安全编辑。如果继续在Text视图中编辑可能会导致编码错误,确定继续么?',
keys_per_loading: '加载数量',
keys_per_loading_tip: '每次加载的key数量, 设置过大可能会影响性能',
host: '地址',
port: '端口',
username: '用户名',
password: '密码',
connection_name: '连接名称',
separator: '分隔符',
timeout: '超时',
private_key: '私钥',
public_key: '公钥',
authority: '授权',
redis_node_password: 'Redis节点密码',
master_group_name: 'Master组名称',
command_log: '日志',
sentinel_faq: '多个哨兵任选其一即可,地址、端口、密码请填写哨兵配置,Redis节点密码为哨兵监听的Master节点密码',
hotkey: '快捷键',
persist: '持久化',
custom_formatter: '自定义格式化',
edit: '编辑',
new: '新增',
custom: '自定义',
hide_window: '隐藏窗口',
minimize_window: '最小化窗口',
maximize_window: '最大化窗口',
load_all_keys: '加载所有',
show_load_all_keys: '启用按钮以加载所有键',
load_all_keys_tip: '一次性加载所有key,当key的数量过多时,有可能会导致客户端卡顿,请酌情使用',
tree_node_overflow: 'key或者文件夹数量过多,仅保留{num}个进行展示。如未找到所需key,建议使用模糊搜索,或者设置分隔符来将key分散到文件夹中',
connection_readonly: '只读模式,禁止新增、编辑和删除',
memory_analysis: '内存分析',
begin: '开始',
pause: '暂停',
restart: '重新开始',
max_display: '最大显示数量: {num}',
max_scan: '最大扫描数量: {num}',
close_left: '关闭左侧标签',
close_right: '关闭右侧标签',
close_other: '关闭其他标签',
slow_log: '慢查询',
load_current_folder: '只加载该文件夹',
custom_name: '自定义名称',
},
};
export default cn;
|
2301_77204479/AnotherRedisDesktopManager
|
src/i18n/langs/cn.js
|
JavaScript
|
mit
| 8,382
|
const de = {
message: {
new_connection: 'Neue Verbindung',
refresh_connection: 'Aktualisieren',
edit_connection: 'Verbindung bearbeiten',
duplicate_connection: 'Verbindung kopieren',
del_connection: 'Verbindung löschen',
close_connection: 'Verbindung schließen',
add_new_line: 'Neue Zeile hinzufügen',
dump_to_clipboard: 'Als Befehl kopieren',
redis_version: 'Redis Version',
process_id: 'Prozess ID',
used_memory: 'Benutzter Speicher',
used_memory_peak: 'Benutzte Speicher-Spitze',
used_memory_lua: 'Benutzte Speicher-Lua',
connected_clients: 'Verbundene Clients',
total_connections_received: 'Totale Verbindungen',
total_commands_processed: 'Totale Kommandos',
key_statistics: 'Wichtige Statistiken',
all_redis_info: 'Alle Redis Infos',
server: 'Server',
memory: 'Speicher',
stats: 'Statistik',
settings: 'Einstellungen',
ui_settings: 'Aussehen',
feature_settings: 'Funktion',
common_settings: 'Allgemein',
confirm_to_delete_row_data: 'Soll die Zeile wirklich gelöscht werden?',
delete_success: 'Löschen erfolgreich',
delete_failed: 'Löschen fehlgeschlagen',
modify_success: 'Ändern erfolgreich',
modify_failed: 'Löschen fehlgeschlagen',
add_success: 'Hinzufügen erfolgreich',
add_failed: 'Hinzufügen fehlgeschlagen',
value_exists: 'Wert existiert',
value_not_exists: 'Der Wert existiert nicht',
refresh_success: 'Aktualisierung erfolgreich',
click_enter_to_rename: 'Klicken oder Enter drücken zum Umbenennen',
click_enter_to_ttl: 'Klicken oder Enter drücken zum Modifizieren TTL',
confirm_to_delete_key: 'Bestätigen zum löschen {key} ?',
confirm_to_rename_key: 'Bestätigen zum umbenennen {old} -> {new} ?',
edit_line: 'Zeile bearbeiten',
auto_refresh: 'Auto Aktualisierung',
auto_refresh_tip: 'Auto Aktualisierung Schalter, Aktualisiere alle {interval} Sekunden',
key_not_exists: 'Schlüssel existiert nicht',
collapse_all: 'Alle einklappen',
expand_all: 'Alle ausklappen',
json_format_failed: 'Json parsen fehlgeschlagen',
msgpack_format_failed: 'Msgpack parsen fehlgeschlagen',
php_unserialize_format_failed: 'PHP Unserialisieren fehlgeschlagen',
clean_up: 'Bereinigen',
redis_console: 'Redis Konsole',
confirm_to_delete_connection: 'Soll die Verbindung gelöscht werden?',
connection_exists: 'Verbindungs Konfiguration existiert bereits',
close_to_edit_connection: 'Verbindung muss vor bearbeitung geschlossen werden',
close_to_connection: 'Soll die Verbindung geschlossen werden?',
ttl_delete: 'TTL<=0 setzen - löscht den Schlüssel direkt',
max_page_reached: 'Maximale Seiten anzahl',
add_new_key: 'Neuer Schlüssel',
enter_new_key: 'Ersten Schlüssel-Namen eingeben',
key_type: 'Schlüssel typ',
save: 'Speichern',
enter_to_search: 'Eingabe zur Suche',
export_success: 'Exportieren erfolgreich',
select_import_file: 'Datei auswählen',
import_success: 'Importierung erfolgreich',
put_file_here: 'Ziehen sie die Datei hierher oder Klicken zur Selektierung',
config_connections: 'Verbindungen',
import: 'Importieren',
export: 'Exportieren',
open: 'Öffnen',
close: 'Schließen',
open_new_tab: 'Im neuen Fenster öffnen',
exact_search: 'Exakte Suche',
enter_to_exec: 'Enter drücken um Kommando auszuführen, Hoch - Runter zum wechseln der Historie',
pre_version: 'Version',
manual_update: 'Handbuch-Download',
retry_too_many_times: 'Zu viele Versuche, die Verbindung wieder herzustellen. Bitte überprüfen Sie den Server-Status',
key_to_search: 'Schlüsselwort-Suche',
search_connection: 'Verbindung suchen',
begin_update: 'Aktualisierung',
ignore_this_version: 'Ignoriere diese Version',
check_update: 'Aktualisierung prüfen',
update_checking: 'Nach Updates suchen ...',
update_available: 'Neue Version gefunden',
update_not_available: 'Ihre App ist auf dem neuesten Stand',
update_error: 'Aktualisierung fehlgeschlagen',
update_downloading: 'Herunterladen ...',
update_download_progress: 'Download Fortschritt',
update_downloaded: 'Update Download abgeschlossen, bitte starten Sie Ihre App neu.\
[Tips]: Wenn Sie Windows verwenden, warten Sie nach dem Schließen der App darauf, dass das Desktopsymbol auf einen normalen Zustand (ca. 10 Sekunden) aktualisiert wird, und öffnen Sie es dann erneut',
mac_not_support_auto_update: 'Mac unterstützt keine automatische Aktualisierung, bitte manuell <a href="https://github.com/qishibo/AnotherRedisDesktopManager/releases">herunterladen</a> und neu installieren,\
or ausführen <br><code>brew reinstall --cask another-redis-desktop-manager </code>\
<br><hr><br>❤️Wenn es für Sie nützlich ist, können Sie über den <a href="https://apps.apple.com/app/id1516451072">AppStore</a> sponsern, und der AppStore aktualisiert es automatisch für Sie.',
font_family: 'Schrift familie',
font_faq_title: 'Anweisungen zum Einstellen der Schriftart',
font_faq: '1. Mehrere Schriftarten können eingestellt werden<br>\
2. Die Auswahl der Schriftart ist geordnet. Es wird empfohlen, zuerst die englische Schriftart und dann die Schriftart in Ihrer Sprache zu wählen.<br>\
3. Wenn die Systemschriftenliste in einigen Ausnahmefällen nicht geladen werden kann, können Sie den Namen der installierten Schrift manuell eingeben.',
private_key_faq: 'RSA format private key is supported, which starts with <pre>-----BEGIN RSA PRIVATE KEY-----</pre>\
beginnt mit <pre>-----BEGIN OPENSSH PRIVATE KEY-----</pre>Sie müssen das Format konvertieren mittels <pre>ssh-keygen -p -m pem -f ~/.ssh/id_rsa</pre>Dieser Vorgang hat keine Auswirkungen auf die vorherige Anmeldung mit privatem Schlüssel',
dark_mode: 'Dunkel modus',
load_more_keys: 'mehr laden',
key_name: 'Schlüssel-Name',
project_home: 'Projekt Home',
cluster_faq: 'Wählen Sie einen beliebigen Knoten im Cluster zum Ausfüllen aus, und andere Knoten werden automatisch identifiziert.',
redis_status: 'Redis Info',
confirm_flush_db: 'Bestätigen Sie, um alle Schlüssel in db ({db}) zu löschen ?',
flushdb: 'Speichere Datenbank',
flushdb_prompt: 'Eingabe "{txt}"',
info_disabled: 'Info-Befehlsausführungsausnahme (kann deaktiviert worden sein), Redis-Info kann nicht angezeigt werden',
page_zoom: 'Seite vergrößern',
scan_disabled: 'Ausnahme bei der Ausführung von Scan-Befehlen (kann deaktiviert worden sein), Schlüsselliste kann nicht angezeigt werden',
key_type_not_support: 'Die visuelle Anzeige wird für diesen Typ wird nicht unterstützt. Bitte benutzen Sie die Konsole.',
delete_folder: 'Scannen und Löschen des gesamten Ordners',
multiple_select: 'Mehrere Auswahl',
copy: 'Kopieren',
copy_success: 'Erfolgreich kopieren',
keys_to_be_deleted: 'Zu löschende Schlüssel',
delete_all: 'Alle löschen',
clear_cache: 'Cache leeren',
mark_color: 'Farbe markieren',
key_no_permission: 'Die Berechtigung zum Lesen von Dateien ist abgelaufen. Wählen Sie die Schlüsseldatei erneut manuell aus',
toggle_check_all: 'Alle auswählen | Alle abwählen',
select_lang: 'Sprache auswählen',
clear_cache_tip: 'Wenn es ein Problem mit dem Client gibt, wird diese Operation alle Verbindungen und Konfigurationen löschen, um den Client wiederherzustellen',
detail: 'Detail',
separator_tip: 'Das Trennzeichen der Baumansicht wird auf leer gesetzt, um den Baum zu deaktivieren und Schlüssel als Liste anzuzeigen',
confirm_modify_unvisible_content: 'Der Inhalt enthält unsichtbare Zeichen, die Sie sicher in der "Hex View" bearbeiten können. Wenn die weitere Bearbeitung im "Text View" zu Codierungsfehlern führen kann, fahren Sie sicher fort?',
keys_per_loading: 'Anzahl der Schlüssel',
keys_per_loading_tip: 'Die Anzahl der Schlüssel, die jedes Mal geladen werden. Eine zu große Einstellung kann die Leistung beeinträchtigen',
host: 'Adresse',
port: 'Hafen',
username: 'Nutzername',
password: 'Passwort',
connection_name: 'Benutzerdefinierter Name',
separator: 'Separator',
timeout: 'Auszeit',
private_key: 'Privat Schlüssel',
public_key: 'Öffentlicher Schlüssel',
authority: 'Genehmigung',
redis_node_password: 'Passwort des Redis-Knotens',
master_group_name: 'Name der Gruppe Master',
command_log: 'Log',
sentinel_faq: 'Sie können einen von mehreren Sentinels auswählen. Bitte geben Sie die Sentinel-Konfiguration für Adresse, Port und Passwort ein. Das Redis-Knoten-Passwort ist das Passwort des vom Sentinel überwachten Master-Knotens.',
hotkey: 'Hotkey',
persist: 'Ablaufzeit entfernen',
custom_formatter: 'Benutzerdefinierter Formatierer',
edit: 'Bearbeiten',
new: 'Hinzufügen',
custom: 'Anpassen',
hide_window: 'Fenster ausblenden',
minimize_window: 'Fenster minimieren',
maximize_window: 'Fenster maximieren',
load_all_keys: 'alle laden',
show_load_all_keys: 'Schaltfläche aktivieren, um alle Schlüssel zu laden',
load_all_keys_tip: 'Alle Schlüssel auf einmal laden. Wenn die Anzahl der Schlüssel zu groß ist, kann der Client stecken bleiben. Bitte verwenden Sie es richtig',
tree_node_overflow: 'Zu viele Schlüssel oder Ordner, behalten Sie nur {num} für die Anzeige. Wenn Ihr Schlüssel nicht hier ist, wird eine unscharfe Suche empfohlen, oder den Trenner setzen, um die Schlüssel in Ordner zu verteilen',
connection_readonly: 'Readonly-Modus. Das Hinzufügen, Bearbeiten und Löschen ist untersagt',
memory_analysis: 'Gedächtnisanalyse',
begin: 'Start',
pause: 'Pause',
restart: 'Neu starten',
max_display: 'Maximale Anzahl von Displays: {num}',
max_scan: 'Maximale Anzahl an Scans: {num}',
close_left: 'Schließen Sie die linken Registerkarten',
close_right: 'Schließen Sie die rechten Registerkarten',
close_other: 'Schließen Sie andere Registerkarten',
slow_log: 'Langsame Abfrage',
load_current_folder: 'Nur aktuellen Ordner laden',
custom_name: 'Benutzerdefinierter Name',
},
};
export default de;
|
2301_77204479/AnotherRedisDesktopManager
|
src/i18n/langs/de.js
|
JavaScript
|
mit
| 10,234
|
const en = {
message: {
new_connection: 'New Connection',
refresh_connection: 'Refresh',
edit_connection: 'Edit Connection',
duplicate_connection: 'Duplicate Connection',
del_connection: 'Delete Connection',
close_connection: 'Close Connection',
add_new_line: 'Add New Line',
dump_to_clipboard: 'Copy as command',
redis_version: 'Redis Version',
process_id: 'Process ID',
used_memory: 'Used Memory',
used_memory_peak: 'Used Memory Peak',
used_memory_lua: 'Used Memory Lua',
connected_clients: 'Connected Clients',
total_connections_received: 'Total Connections',
total_commands_processed: 'Total Commands',
key_statistics: 'Key Statistics',
all_redis_info: 'All Redis Info',
server: 'Server',
memory: 'Memory',
stats: 'Stats',
settings: 'Settings',
ui_settings: 'Appearance',
feature_settings: 'Function',
common_settings: 'General',
confirm_to_delete_row_data: 'Confirm To Delete The Row Data?',
delete_success: 'Deletion Successful',
delete_failed: 'Deletion Failed',
modify_success: 'Successfully Modified',
modify_failed: 'Modification Failed',
add_success: 'Added Successfully',
add_failed: 'Addition Failed',
value_exists: 'Value Already Exists',
value_not_exists: 'The Value Does not Exist',
refresh_success: 'Refresh Success',
click_enter_to_rename: 'Click Or Press Enter To Rename',
click_enter_to_ttl: 'Click Or Press Enter To Modify TTL',
confirm_to_delete_key: 'Confirm To Delete {key} ?',
confirm_to_rename_key: 'Confirm To Rename {old} -> {new} ?',
edit_line: 'Edit Line',
auto_refresh: 'Auto Refresh',
auto_refresh_tip: 'Auto Refresh Switch, Refresh Every {interval} Seconds',
key_not_exists: 'Key Not Exists',
collapse_all: 'Collapse All',
expand_all: 'Expand All',
json_format_failed: 'Json Parse Failed',
msgpack_format_failed: 'Msgpack Parse Failed',
php_unserialize_format_failed: 'PHP Unserialize Failed',
clean_up: 'Clean Up',
redis_console: 'Redis Console',
confirm_to_delete_connection: 'Confirm To Delete Connection ?',
connection_exists: 'Connection Config Already Exists',
close_to_edit_connection: 'You Must Close The Connection Before Editing',
close_to_connection: 'Confirm To Close Connection ?',
ttl_delete: 'Set TTL<=0 Will Delete The Key Directly',
max_page_reached: 'Max Page Reached',
add_new_key: 'New Key',
enter_new_key: 'Enter Your New Key Name First',
key_type: 'Key Type',
save: 'Save',
enter_to_search: 'Enter To Search',
export_success: 'Export Success',
select_import_file: 'Select The File',
import_success: 'Import Success',
put_file_here: 'Drag File Here Or Click To Select',
config_connections: 'Connections',
import: 'Import',
export: 'Export',
open: 'Open',
close: 'Close',
open_new_tab: 'Open In New Tab',
exact_search: 'Exact Search',
enter_to_exec: 'Press Enter To Exec Commands, Up and Down To Switch History',
pre_version: 'Version',
manual_update: 'Manual Download',
retry_too_many_times: 'Too Many Attempts To Reconnect. Please Check The Server Status',
key_to_search: 'Keyword Search',
search_connection: 'Search Connection',
begin_update: 'Update',
ignore_this_version: 'Ignore this version',
check_update: 'Check Update',
update_checking: 'Checking For Updates, Wait A Moment...',
update_available: 'New Version Found',
update_not_available: 'Your version is up to date',
update_error: 'Update Failed',
update_downloading: 'Downloading...',
update_download_progress: 'Download Progress',
update_downloaded: 'Update Download Completed, Restart Your App Please.\
[Tips]: If you are using Windows, after closing the app, waiting the desktop icon to refresh to a normal state(about 10 seconds), and then you can reopen it',
mac_not_support_auto_update: 'Mac Does Not Support Automatic Update, Please Manually <a href="https://github.com/qishibo/AnotherRedisDesktopManager/releases">Download</a> And Reinstall,\
Or Run <br><code>brew reinstall --cask another-redis-desktop-manager </code>\
<br><hr><br>❤️if it\'s useful to you ,you can sponsor through <a href="https://apps.apple.com/app/id1516451072">AppStore</a>, and AppStore will automatically update it for you.',
font_family: 'Font Family',
font_faq_title: 'Font Setting Instructions',
font_faq: '1. Multiple fonts can be set<br>\
2. Font selection is orderly. It is suggested to choose English font first and then font in your language<br>\
3. When the system font list cannot be loaded in some exceptional cases, you can enter the installed font name manually.',
private_key_faq: 'RSA format private key is supported, which starts with <pre>-----BEGIN RSA PRIVATE KEY-----</pre>\
as to starts with<pre>-----BEGIN OPENSSH PRIVATE KEY-----</pre>you need to convert format via <pre>ssh-keygen -p -m pem -f ~/.ssh/id_rsa</pre>This operation will not affect the previous private key login',
dark_mode: 'Dark Mode',
load_more_keys: 'load more',
key_name: 'Key Name',
project_home: 'Project Home',
cluster_faq: 'Select any node in the cluster to fill in, and other nodes will be identified automatically.',
redis_status: 'Redis Info',
confirm_flush_db: 'Confirm to delete all the keys in db{db} ?',
flushdb: 'Flush DB',
flushdb_prompt: 'Input "{txt}"',
info_disabled: 'Info command execution exception(may have been disabled), redis info cannot be displayed',
page_zoom: 'Page Zoom',
scan_disabled: 'Scan command execution exception(may have been disabled), key list cannot be displayed',
key_type_not_support: 'Visual display is not supported for this type. Please use console',
delete_folder: 'Scan And Delete Whole Folder',
multiple_select: 'Multiple Select',
copy: 'Copy',
copy_success: 'Copy success',
keys_to_be_deleted: 'Keys To Be Deleted',
delete_all: 'Delete All',
clear_cache: 'Clear Cache',
mark_color: 'Mark Color',
key_no_permission: 'File read permission has expired, please reselect the key file manually',
toggle_check_all: 'Select all | Unselect all',
select_lang: 'Select Language',
clear_cache_tip: 'When there is a problem with the client, this operation will delete all the connections and configurations to recover the client',
detail: 'Detail',
separator_tip: 'The separator of the tree view, set to empty to disable tree and display keys as list',
confirm_modify_unvisible_content: 'The content contains invisible characters, you can edit safely in the "Hex View". If continuing to edit in the "Text View" may cause coding errors, sure to continue?',
keys_per_loading: 'Load Number',
keys_per_loading_tip: 'The number of keys loaded each time. Setting too large may affect performance',
host: 'Host',
port: 'Port',
username: 'Username',
password: 'Password',
connection_name: 'Connection Name',
separator: 'Separator',
timeout: 'Timeout',
private_key: 'Private Key',
public_key: 'Public Key',
authority: 'Authority',
redis_node_password: 'Redis Node Password',
master_group_name: 'Master Group Name',
command_log: 'Log',
sentinel_faq: 'You can choose one of multiple sentinels. Please fill in the sentinel configuration for the address, port and password. The Redis node password is the password of the Master node monitored by the sentinel.',
hotkey: 'Hot Key',
persist: 'Remove Expire Time',
custom_formatter: 'Custom Formatter',
edit: 'Edit',
new: 'New',
custom: 'Customize',
hide_window: 'Hide Window',
minimize_window: 'Minimize window',
maximize_window: 'Maximize window',
load_all_keys: 'load all',
show_load_all_keys: 'Enable button to load all keys',
load_all_keys_tip: 'Load all keys at one time. If the number of keys is too large, the client may get stuck. Please use it correctly',
tree_node_overflow: 'Too many keys or folders , keep only {num} for display. If your key is not here, fuzzy search is recommended, or set the separator to spread the keys into folders',
connection_readonly: 'Readonly mode. Adding, editing and deleting are prohibited',
memory_analysis: 'Memory Analysis',
begin: 'Begin',
pause: 'Pause',
restart: 'Restart',
max_display: 'Maximum number of displays: {num}',
max_scan: 'Maximum number of scans: {num}',
close_left: 'Close Left Tabs',
close_right: 'Close Tabs To The Right',
close_other: 'Close Other Tabs',
slow_log: 'Slow Query',
load_current_folder: 'Only Load Current Folder',
custom_name: 'Custom Name',
},
};
export default en;
|
2301_77204479/AnotherRedisDesktopManager
|
src/i18n/langs/en.js
|
JavaScript
|
mit
| 8,795
|
const es = {
message: {
new_connection: 'Nueva Conexión',
refresh_connection: 'Refrescar',
edit_connection: 'Editar Conexión',
duplicate_connection: 'Copiar Conexión',
del_connection: 'Eliminar Conexión',
close_connection: 'Cerrar Conexión',
add_new_line: 'Añadir Nueva Linea',
dump_to_clipboard: 'Copiar como comando',
redis_version: 'Versión Redis',
process_id: 'ID Proceso',
used_memory: 'Memoria Usada',
used_memory_peak: 'Pico Memoria Usada',
used_memory_lua: 'Lua Memoria Usada',
connected_clients: 'Clientes Conectados',
total_connections_received: 'Conexiones Totales',
total_commands_processed: 'Comandos Totales',
key_statistics: 'Estadisticas Clave',
all_redis_info: 'Toda Información Redis',
server: 'Servidor',
memory: 'Memoria',
stats: 'Estadísticas',
settings: 'Ajustes',
ui_settings: 'Apariencia',
feature_settings: 'Función',
common_settings: 'General',
confirm_to_delete_row_data: '¿Seguro quiere eliminar los datos de la fila?',
delete_success: 'Eliminado Correcto',
delete_failed: 'Eliminado Fallido',
modify_success: 'Modificación Correcta',
modify_failed: 'Modificación Fallida',
add_success: 'Añadido Correctamente',
add_failed: 'Añadido Fallido',
value_exists: 'Valor ya existente',
value_not_exists: 'El valor no existe',
refresh_success: 'Refresco Correcto',
click_enter_to_rename: 'Click o Presiona Enter para Renombrar',
click_enter_to_ttl: 'lick o Presiona Enter para Modificar el TTL',
confirm_to_delete_key: '¿Confirma eliminar {key} ?',
confirm_to_rename_key: 'Confirma renombrar {old} -> {new} ?',
edit_line: 'Editar Linea',
auto_refresh: 'Auto Refresco',
auto_refresh_tip: 'Auto Refresco Switch, Refrescar cara {interval} segundos',
key_not_exists: 'Clave no existe',
collapse_all: 'Contraer Todo',
expand_all: 'Expandir All',
json_format_failed: 'Error al parsear el Json',
msgpack_format_failed: 'Error al parsear Msgpack',
php_unserialize_format_failed: 'Error al deserializar PHP',
clean_up: 'Limpiar',
redis_console: 'Consola Redis',
confirm_to_delete_connection: '¿Confirma eliminar la conexión?',
connection_exists: 'Configuración de conexión ya existe',
close_to_edit_connection: 'Debe cerrar la conexión antes de editar',
close_to_connection: '¿Confirma cerrar la conexión?',
ttl_delete: 'Ajustar TTL<=0 eliminará la clave directamente',
max_page_reached: 'Página máxima alcanzada',
add_new_key: 'Nueva Clave',
enter_new_key: 'Ingrese su nuevo nombre de clave primero',
key_type: 'Tipo de Clave',
save: 'Guardar',
enter_to_search: 'Enter para buscar',
export_success: 'Exportación Correcta',
select_import_file: 'Selecciona el Fichero',
import_success: 'Importación Correcta',
put_file_here: 'Suelta un fichero aquí o Pincha en Seleccionar',
config_connections: 'Conexiones',
import: 'Importar',
export: 'Exportar',
open: 'Abrir',
close: 'Cerrar',
open_new_tab: 'Abrir en nueva Pestaña',
exact_search: 'Búsqueda exacta',
enter_to_exec: 'Presione Enter para ejecutar comandos, arriba y abajo para cambiar el historial',
pre_version: 'Versión',
manual_update: 'Descarga Manual',
retry_too_many_times: 'Demasiados intentos de reconexión. Verifique el estado del servidor',
key_to_search: 'Búsqueda por palabra clave',
search_connection: 'Conexión de búsqueda',
begin_update: 'Actualizar',
ignore_this_version: 'Ignorar esta versión',
check_update: 'Comprobar actualizaciones',
update_checking: 'Comprobando actualizaciones, espere un momento...',
update_available: 'Nueva Versión Encontrada',
update_not_available: 'Tu versión está actualizada',
update_error: 'Actualización Fallida',
update_downloading: 'Descargando...',
update_download_progress: 'Progreso de la descarga',
update_downloaded: 'Descarga de actualización completada, por favor, reinicia la aplicaicón.\
[Consejo]: Si está utilizando Windows, después de cerrar la aplicación, espere que el ícono del escritorio se actualice a un estado normal (alrededor de 10 segundos) y luego puede volver a abrirlo',
mac_not_support_auto_update: 'Mac no soporte actualizaciones automáticas. Manualmente puede <a href="https://github.com/qishibo/AnotherRedisDesktopManager/releases">Descargarla</a> y reinstalarla,\
o ejecute <br><code>brew reinstall --cask another-redis-desktop-manager </code>\
<br><hr><br>❤️si es útil para ti, puedes patronizarnos a través de <a href="https://apps.apple.com/app/id1516451072">AppStore</a>, y AppStore lo actualizará automáticamente por usted.',
font_family: 'Familia de la Fuente',
font_faq_title: 'Instrucciones Ajuste Fuente',
font_faq: '1. Se pueden configurar varias fuentes<br>\
2. La selección de fuentes es ordenada. Se sugiere elegir primero la fuente en inglés y luego la fuente en su idioma<br>\
3. Cuando la lista de fuentes del sistema no se puede cargar en algunos casos excepcionales, puede ingresar el nombre de la fuente instalada manualmente.',
private_key_faq: 'Se admite la clave privada en formato RSA, que comienza con <pre>-----BEGIN RSA PRIVATE KEY-----</pre>\
y comienza con<pre>-----BEGIN OPENSSH PRIVATE KEY-----</pre> necesita convertir el formato a través de <pre>ssh-keygen -p -m pem -f ~/.ssh/id_rsa</pre>Esta operación no afectará el inicio de sesión de clave privada anterior',
dark_mode: 'Modo Oscuro',
load_more_keys: 'cargar más',
key_name: 'Nombre Clave',
project_home: 'Home Proyecto',
cluster_faq: 'Seleccione cualquier nodo en el clúster para completar, y otros nodos se identificarán automáticamente.',
redis_status: 'Redis Info',
confirm_flush_db: '¿Confirmar para eliminar todas las claves en db{db} ?',
flushdb: 'Vaciar DB',
flushdb_prompt: 'Input "{txt}"',
info_disabled: 'Excepción de ejecución de comando de información (puede haberse deshabilitado), no se puede mostrar la información de redis',
page_zoom: 'Zoom Página',
scan_disabled: 'Excepción de ejecución de comando de escaneo (puede haberse deshabilitado), no se puede mostrar la lista de claves',
key_type_not_support: 'La visualización visual no es compatible con este tipo. Utilice la consola',
delete_folder: 'Escanear y eliminar toda la carpeta',
multiple_select: 'Selección múltiple',
copy: 'Copiar',
copy_success: 'Copiado correcto',
keys_to_be_deleted: 'Claves a ser eliminadas',
delete_all: 'Eliminar todas',
clear_cache: 'Limpiar Cache',
mark_color: 'Color de marca',
key_no_permission: 'El permiso de lectura de archivos ha caducado, vuelva a seleccionar el archivo clave manualmente',
toggle_check_all: 'Seleccionar todos | Deseleccionar todos',
select_lang: 'Seleccione el idioma',
clear_cache_tip: 'Cuando hay un problema con el cliente, esta operación eliminará todas las conexiones y configuraciones para recuperar el cliente',
detail: 'Detalle',
separator_tip: 'El separador de la vista de árbol, establecido en vacío para deshabilitar el árbol y mostrar las teclas como una lista',
confirm_modify_unvisible_content: 'El contenido contiene caracteres invisibles, puede editar de forma segura en la "Vista hexadecimal". Si continuar editando en la "Vista de texto" puede causar errores de codificación, ¿desea continuar?',
keys_per_loading: 'Numeros por Carga',
keys_per_loading_tip: 'El número de claves cargadas cada vez. Un ajuste demasiado grande puede afectar el rendimiento',
host: 'Host',
port: 'Puerto',
username: 'Usuario',
password: 'Password',
connection_name: 'Nombre de la Conexión',
separator: 'Separador',
timeout: 'Timeout',
private_key: 'Clave Privada',
public_key: 'Clave Pública',
authority: 'Autoridad',
redis_node_password: 'Redis Node Password',
master_group_name: 'Nombre Grupo Maestro',
command_log: 'Log',
sentinel_faq: 'Puede elegir uno de varios centinelas. Complete la configuración de Sentinel para la dirección, el puerto y la contraseña. La contraseña del nodo Redis es la contraseña del nodo maestro monitoreado por el centinela.',
hotkey: 'Hot Key',
persist: 'Eliminar tiempo expiración',
custom_formatter: 'Formato Personalizado',
edit: 'Editar',
new: 'Nuevo',
custom: 'Personalizar',
hide_window: 'Ocultar Ventana',
minimize_window: 'Minimizar Ventana',
maximize_window: 'Maximizar Ventana',
load_all_keys: 'Cargar todo',
show_load_all_keys: 'Habilitar botón para cargar todas las claves',
load_all_keys_tip: 'Cargue todas las claves a la vez. Si el número de claves es demasiado grande, el cliente puede atascarse. Por favor úsalo correctamente',
tree_node_overflow: 'Demasiadas claves o carpetas, mantenga solo {num} para mostrar. Si su clave no está aquí, se recomienda una búsqueda aproximada o configure el separador para distribuir las claves en carpetas',
connection_readonly: 'Modo de solo lectura. Prohibido agregar, editar y borrar',
memory_analysis: 'Análisis de memoria',
begin: 'Iniciar',
pause: 'Pausar',
restart: 'Reiniciar',
max_display: 'Número máximo de visualizaciones: {num}',
max_scan: 'Número máximo de escaneos: {num}',
close_left: 'Cerrar pestañas izquierdas',
close_right: 'Cerrar pestañas derechas',
close_other: 'Cerrar otras pestañas',
slow_log: 'Consulta lenta',
load_current_folder: 'Cargar solo la carpeta actual',
custom_name: 'Nombre personalizado',
},
};
export default es;
|
2301_77204479/AnotherRedisDesktopManager
|
src/i18n/langs/es.js
|
JavaScript
|
mit
| 9,782
|
const fr = {
message: {
new_connection: 'Nouvelle connexion',
refresh_connection: 'Actualiser',
edit_connection: 'Éditer connexion',
duplicate_connection: 'Copier la connexion',
del_connection: 'Supprimer connexion',
close_connection: 'Fermer connexion',
add_new_line: 'Ajouter nouvelle ligne',
dump_to_clipboard: 'Copier en tant que commande',
redis_version: 'Redis version',
process_id: 'ID du processus',
used_memory: 'Mémoire utilisée',
used_memory_peak: 'Pic de mémoire utilisée',
used_memory_lua: 'Mémoire utilisée Lua',
connected_clients: 'Clients connectés',
total_connections_received: 'Total des connexions reçues',
total_commands_processed: 'Total des commandes',
key_statistics: 'Statistiques clés',
all_redis_info: 'Toutes les informations Redis',
server: 'Serveur',
memory: 'Mémoire',
stats: 'Statistiques',
settings: 'Paramètres',
ui_settings: 'Apparence',
feature_settings: 'Fonction',
common_settings: 'Général',
confirm_to_delete_row_data: 'Supprimer les données de cette ligne ?',
delete_success: 'Suppression réussie',
delete_failed: 'Suppression échouée',
modify_success: 'Modification réussie',
modify_failed: 'Modification échouée',
add_success: 'Ajout réussi',
add_failed: 'Ajout échoué',
value_exists: 'La valeur existe',
value_not_exists: 'La valeur n\'existe pas',
refresh_success: 'Actualisation réussie',
click_enter_to_rename: 'Cliquez ou pressez Entrée pour renommer',
click_enter_to_ttl: 'Cliquez ou pressez Entrée pour modifier le TTL',
confirm_to_delete_key: 'Supprimer {key} ?',
confirm_to_rename_key: 'Renommer {old} -> {new} ?',
edit_line: 'Éditer la ligne',
auto_refresh: 'Actualisation automatique',
auto_refresh_tip: 'Interrupteur d\'actualisation automatique, actualise toutes les {interval} secondes',
key_not_exists: 'La clé n\'existe pas',
collapse_all: 'Tout fermer',
expand_all: 'Tout étendre',
json_format_failed: 'Échec de l\'analyse du JSON',
msgpack_format_failed: 'Échec de l\'analyse du Msgpack',
php_unserialize_format_failed: 'Échec de la désérialisation PHP',
clean_up: 'Nettoyer',
redis_console: 'Console Redis',
confirm_to_delete_connection: 'Supprimer la connexion ?',
connection_exists: 'Configuration de connexion existe déjà',
close_to_edit_connection: 'Vous devez fermer la connexion avant d\'éditer',
close_to_connection: 'Fermer la connexion ?',
ttl_delete: 'Définir TTL<=0 supprimera la clé directement',
max_page_reached: 'Page maximale atteinte',
add_new_key: 'Nouvelle clé',
enter_new_key: 'Entrez d\'abord votre nouveau nom de clé',
key_type: 'Type de la clé',
save: 'Enregistrer',
enter_to_search: 'Pressez Entrée pour rechercher',
export_success: 'Exportation réussie',
select_import_file: 'Sélectionner le fichier',
import_success: 'Importation réussie',
put_file_here: 'Glissez le fichier ici ou cliquez sur Sélectionner',
config_connections: 'Connexions',
import: 'Importation',
export: 'Exportation',
open: 'Ouvrir',
close: 'Fermer',
open_new_tab: 'Ouvrir dans un nouvel onglet',
exact_search: 'Recherche exacte',
enter_to_exec: 'Appuyez sur la touche Entrée pour les commandes d\'exécution, sur les touches haut et bas pour passer à l\'historique',
pre_version: 'Version',
manual_update: 'Téléchargement de la notice',
retry_too_many_times: 'Trop de tentatives pour se reconnecter. Veuillez vérifier l\'état du serveur',
key_to_search: 'Mot-clé de recherche',
search_connection: 'Rechercher une connexion',
begin_update: 'Mise à jour',
ignore_this_version: 'Ignorer cette version',
check_update: 'Vérifier la mise à jour',
update_checking: 'Vérification des mises à jour, patientez...',
update_available: 'Nouvelle version trouvée',
update_not_available: 'Votre application est à jour',
update_error: 'Mise à jour échouée',
update_downloading: 'Téléchargement...',
update_download_progress: 'Téléchargement en cours',
update_downloaded: 'Téléchargement de la mise à jour terminé, redémarrez l\'application s\'il vous plaît.\
[Tips]: Si vous utilisez Windows, après avoir fermé l\'application, attendez que l\'icône du bureau soit actualisée à un état normal (environ 10 secondes), puis vous pouvez la rouvrir',
mac_not_support_auto_update: 'Les Mac ne supportent pas les mises à jour automatique, vous pouvez <a href="https://github.com/qishibo/AnotherRedisDesktopManager/releases">télécharger</a> et réinstaller manuellement,\
ou lancer <br><code>brew reinstall --cask another-redis-desktop-manager </code>\
<br><hr><br>❤️si cela vous est utile, vous pouvez sponsoriser via l\'<a href="https://apps.apple.com/app/id1516451072">AppStore</a>, et l\'AppStore le mettra automatiquement à jour pour vous.',
font_family: 'Famille de polices',
font_faq_title: 'Instructions de configuration de polices',
font_faq: '1. Plusieurs polices peuvent être paramétrées<br>\
2. La sélection des polices est ordonnée. Il est suggéré de choisir d\'abord la police anglaise et ensuite la police de votre langue<br>\
3. Dans certains cas exceptionnels, lorsque la liste des polices du système ne peut être chargée, vous pouvez saisir manuellement le nom de la police installée.',
private_key_faq: 'La clé privée au format RSA est prise en charge, commançant par <pre>-----BEGIN RSA PRIVATE KEY-----</pre>\
pour commencer par <pre>-----BEGIN OPENSSH PRIVATE KEY-----</pre> vous devez convertir le format via <pre>ssh-keygen -p -m pem -f ~/.ssh/id_rsa</pre> Cette opéaration n\'affectera pas la précédente clé de connexion',
dark_mode: 'Mode sombre',
load_more_keys: 'charger plus',
key_name: 'Nom de la clé',
project_home: 'Accueil du projet',
cluster_faq: 'Sélectionnez n\'importe quel nœud du cluster à remplir, et les autres nœuds seront identifiés automatiquement.',
redis_status: 'Statut Redis',
confirm_flush_db: 'Supprimer toutes les clés dans la base de données {db} ?',
flushdb: 'Sauvegarde de la base de données',
flushdb_prompt: 'Entrer "{txt}"',
info_disabled: 'Exception d\'exécution de la commande Info (peut avoir été désactivée), l\'info redis ne peut pas être affichée',
page_zoom: 'Agrandir la page',
scan_disabled: 'Exception d\'exécution de la commande Scan (peut avoir été désactivée), la liste des clés ne peut pas être affichée',
key_type_not_support: 'L\'affichage visuel n\'est pas pris en charge pour ce type. Veuillez utiliser la console',
delete_folder: 'Analyser et supprimer tout le dossier',
multiple_select: 'Sélection multiple',
copy: 'Copie',
copy_success: 'Copier avec succès',
keys_to_be_deleted: 'Clés à supprimer',
delete_all: 'Supprimer tout',
clear_cache: 'Vider le cache',
mark_color: 'Couleur de la marque',
key_no_permission: 'L\'autorisation de lecture de fichier a expiré, veuillez resélectionner le fichier de clé manuellement',
toggle_check_all: 'Tout sélectionner | Tout désélectionner',
select_lang: 'Choisir la langue',
clear_cache_tip: 'Lorsqu\'un problème survient avec le client, cette action supprime toutes les connexions et configurations pour récupérer le client',
detail: 'Détail',
separator_tip: 'Le séparateur de l\'arborescence, défini sur vide pour désactiver l\'arborescence et afficher les clés sous forme de liste',
confirm_modify_unvisible_content: 'Le contenu contient des caractères invisibles, vous pouvez éditer en toute sécurité dans le "Hex View". Si continuer à modifier dans le "Text View" peut provoquer des erreurs de codage, assurez-vous de continuer?',
keys_per_loading: 'Nombre de clés',
keys_per_loading_tip: 'Le nombre de clés chargées à chaque fois. Un paramètre trop grand peut affecter les performances',
host: 'Adresse',
port: 'Port',
username: 'Nom d\'utilisateur',
password: 'Le mot de passe',
connection_name: 'Nom d\'usage',
separator: 'Délimiteur',
timeout: 'Temps libre',
private_key: 'Clé privée',
public_key: 'Clé publique',
authority: 'Autorité',
redis_node_password: 'Mot de passe du nœud Redis',
master_group_name: 'Nom du groupe Master',
command_log: 'Enregistrer',
sentinel_faq: 'Vous pouvez choisir l\'une des plusieurs sentinelles. Veuillez remplir la configuration de la sentinelle pour l\'adresse, le port et le mot de passe. Le mot de passe du nœud Redis est le mot de passe du nœud maître surveillé par la sentinelle.',
hotkey: 'Touche de raccourci',
persist: 'Supprimer l\'heure d\'expiration',
custom_formatter: 'Formateur personnalisé',
edit: 'Éditer',
new: 'Ajouter',
custom: 'Personnaliser',
hide_window: 'Masquer la fenêtre',
minimize_window: 'Réduire la fenêtre',
maximize_window: 'Agrandir la fenêtre',
load_all_keys: 'charger tout',
show_load_all_keys: 'Activer le bouton pour charger toutes les clés',
load_all_keys_tip: 'Chargez toutes les clés en même temps. Si le nombre de clés est trop important, le client peut rester bloqué. Veuillez l\'utiliser correctement',
tree_node_overflow: 'Il y a trop de touches ou de dossiers, ne laissant que {num} à afficher. Si votre clé n\'est pas ici, une recherche floue est recommandée, ou définissez un séparateur pour disperser la clé dans le dossier',
connection_readonly: 'Mode lecture seule. L\'ajout, la modification et la suppression sont interdits',
memory_analysis: 'Analyse de la mémoire',
begin: 'Commencer',
pause: 'Pause',
restart: 'Redémarrage',
max_display: 'Nombre maximal d\'affichages : {num}',
max_scan: 'Nombre maximal d\'analyses : {num}',
close_left: 'Fermer les onglets de gauche',
close_right: 'Fermer les onglets de droite',
close_other: 'Fermer les autres onglets',
slow_log: 'Requête lente',
load_current_folder: 'Charger uniquement le dossier actuel',
custom_name: 'Nom d\'usage',
},
};
export default fr;
|
2301_77204479/AnotherRedisDesktopManager
|
src/i18n/langs/fr.js
|
JavaScript
|
mit
| 10,319
|
const it = {
message: {
new_connection: 'Nuova Connessione',
refresh_connection: 'Ricaricare',
edit_connection: 'Modificare Connessione',
duplicate_connection: 'Copia connessione',
del_connection: 'Elimina Connessione',
close_connection: 'Chiudere Connessione',
add_new_line: 'Inserisci Nuova Riga',
dump_to_clipboard: 'Copia come comando',
redis_version: 'Versione del Redis',
process_id: 'ID del Processi',
used_memory: 'Memoria Usata',
used_memory_peak: 'Picco di Memoria Utilizzato',
used_memory_lua: 'Memoria Utilizzato Lua',
connected_clients: 'Clienti Connessi',
total_connections_received: 'Connessioni Totali',
total_commands_processed: 'Comandi Totali',
key_statistics: 'Principale Statistiche',
all_redis_info: 'Tutte le Informazioni su Redis',
server: 'Server',
memory: 'Memoria',
stats: 'Statistiche',
settings: 'Impostazioni',
ui_settings: 'Aspetto esteriore',
feature_settings: 'Funzione',
common_settings: 'Generale',
confirm_to_delete_row_data: 'Confermare per eliminare i dati della riga?',
delete_success: 'Eliminato con successo',
delete_failed: 'Eliminazione non riuscita',
modify_success: 'Modificato con successo',
modify_failed: 'Modificazione non riuscita',
add_success: 'Aggiunto con successo',
add_failed: 'Aggiunzione non riuscita',
value_exists: 'Valore esistente',
value_not_exists: 'Il valore non esiste',
refresh_success: 'Ricaricato con successo',
click_enter_to_rename: 'Fare clic o premere Invio per rinominare',
click_enter_to_ttl: 'Fare clic o premere Invio per modificare TTL',
confirm_to_delete_key: 'Conferma per eliminare {key} ?',
confirm_to_rename_key: 'Conferma per rinominare {old} -> {new} ?',
edit_line: 'Modificare linea',
auto_refresh: 'Auto aggiornamento',
auto_refresh_tip: 'Interruttore di aggiornamento automatico, Aggiorna ogni {interval} secondi',
key_not_exists: 'La chiave non esiste',
collapse_all: 'Comprimi tutti',
expand_all: 'Espandi tutti',
json_format_failed: 'Analisi Json non riuscita',
msgpack_format_failed: 'Analisi Msgpack non riuscita',
php_unserialize_format_failed: 'Serializzazione PHP non riuscito',
clean_up: 'Pulizia',
redis_console: 'Console del Redis',
confirm_to_delete_connection: 'Confermare per eliminare la connessione?',
connection_exists: 'La configurazione della connessione già esiste',
close_to_edit_connection: 'È necessario chiudere la connessione prima di modificare',
close_to_connection: 'Confermare per chiudere la connessione?',
ttl_delete: 'Impostare TTL<=0 Eliminerà la chiave direttamente',
max_page_reached: 'Pagina massima raggiunta',
add_new_key: 'Nuova chiave',
enter_new_key: 'Immettere prima il nuovo nome della chiave',
key_type: 'Tipo di chiave',
save: 'Salva',
enter_to_search: 'Premere Invio per cercare',
export_success: 'Esportazione riuscita',
select_import_file: 'Seleziona un file',
import_success: 'Importazione riuscita',
put_file_here: 'Trascina il file qui o fai clic per selezionare',
config_connections: 'Connessioni',
import: 'Importare',
export: 'Esportare',
open: 'Apri',
close: 'Chiude',
open_new_tab: 'Apri in una nuova scheda',
exact_search: 'Ricerca esatta',
enter_to_exec: 'Premi Invio per eseguire i comandi, su e giù per cambiare la cronologia',
pre_version: 'Versione',
manual_update: 'Scaricare Manuale',
retry_too_many_times: 'Troppi tentativi di riconnessione. Si prega di controllare lo stato del server',
key_to_search: 'Ricerca per parole chiave',
search_connection: 'Cerca connessione',
begin_update: 'Aggiornare',
ignore_this_version: 'Ignora questa versione',
check_update: 'Ricerca aggiornamenti',
update_checking: 'Alla ricerca di aggiornamenti esistenti, aspetta un attimo...',
update_available: 'Nuova versione trovata',
update_not_available: 'A sua applicazione è stata l\'ultima versione recente',
update_error: 'Aggiornamento non riuscito',
update_downloading: 'Scaricando...',
update_download_progress: 'Download in corso',
update_downloaded: 'Aggiornamento download completato, riavvia la app per favore.\
[Tips]: Se stai utilizzando Windows, dopo aver chiuso l\'app, attendi che l\'icona del desktop si aggiorni a uno stato normale (circa 10 secondi), quindi puoi riaprirla',
mac_not_support_auto_update: 'Il Mac non supporta l\'aggiornamento automatico, Si prega di <a href="https://github.com/qishibo/AnotherRedisDesktopManager/releases">scaricare</a> e reinstallare manualmente,\
o eseguire <br><code>brew reinstall --cask another-redis-desktop-manager </code>\
<br><hr><br>❤️se ti è utile, puoi sponsorizzare <a href="https://apps.apple.com/app/id1516451072">AppStore</a>, e AppStore lo aggiornerà automaticamente per te.',
font_family: 'Famiglia di font',
font_faq_title: 'Istruzioni per l\'impostazione dei fonti',
font_faq: '1. È possibile definire più sorgenti<br>\
2. La selezione della Font è ordinata. Si consiglia di scegliere prima il carattere inglese e poi il carattere nella tua lingua<br>\
3. Quando l\'elenco dei caratteri di sistema non può essere caricato in alcuni casi eccezionali, è possibile immettere manualmente il nome del carattere installato.',
private_key_faq: 'La chiave privata in formato RSA è compatibile e inizia con <pre>-----BEGIN RSA PRIVATE KEY-----</pre>\
ma se inizi con<pre>-----BEGIN OPENSSH PRIVATE KEY-----</pre>è necessario convertire il formato tramite <pre>ssh-keygen -p -m pem -f ~/.ssh/id_rsa</pre>Questa operazione non influirà sul precedente accesso con chiave privata',
dark_mode: 'Modalità scura',
load_more_keys: 'carica di più',
key_name: 'Nome della chiave',
project_home: 'Progetto Home',
cluster_faq: 'Seleziona qualsiasi nodo nel cluster da compilare e gli altri nodi verranno identificati automaticamente.',
redis_status: 'Informazione su Redis',
confirm_flush_db: 'Confermare per eliminare tutte le chiavi in db {db}?',
flushdb: 'Flush DB',
flushdb_prompt: 'ingresso "{txt}"',
info_disabled: 'Eccezione di esecuzione del comando Info (potrebbe essere stata disabilitata), le informazioni redis non possono essere visualizzate',
page_zoom: 'Zoom della pagina',
scan_disabled: 'Eccezione di esecuzione del comando di scansione (potrebbe essere stata disabilitata), l\'elenco delle chiavi non può essere visualizzato',
key_type_not_support: 'La visualizzazione visiva non è supportata per questo tipo. Si prega di utilizzare la console',
delete_folder: 'Scansiona ed elimina l\'intera cartella',
multiple_select: 'Selezione multipla',
copy: 'Copia',
copy_success: 'Copia realizzata con successo',
keys_to_be_deleted: 'Chiavi da eliminare',
delete_all: 'Cancella Tutto',
clear_cache: 'Cancella cache',
mark_color: 'Segna colore',
key_no_permission: 'Il permesso di lettura del file è scaduto, riseleziona manualmente il file della chiave',
toggle_check_all: 'Seleziona tutto | Deseleziona tutto',
select_lang: 'Seleziona la lingua',
clear_cache_tip: 'Quando si verifica un problema con il client, questa operazione eliminerà tutte le connessioni e le configurazioni per ripristinare il client',
detail: 'Dettaglio',
separator_tip: 'Il separatore della vista ad albero, impostato su vuoto per disabilitare l\'albero e visualizzare i tasti come elenco',
confirm_modify_unvisible_content: 'Il contenuto contiene caratteri invisibili, puoi modificare in sicurezza nella "Hex View". Se continuare a modificare nella "Text View" può causare errori di codifica, continuare?',
keys_per_loading: 'Numero di chiavi',
keys_per_loading_tip: 'Il numero di chiavi caricate ogni volta. Un\'impostazione troppo grande potrebbe influire sulle prestazioni',
host: 'Indirizzo',
port: 'Porta',
username: 'Nome utente',
password: 'Parola d\'ordine',
connection_name: 'Nome personalizzato',
separator: 'Delimitatore',
timeout: 'Tempo scaduto',
private_key: 'Chiave privata',
public_key: 'Chiave pubblica',
authority: 'Autorità',
redis_node_password: 'Password del nodo Redis',
master_group_name: 'Nome del gruppo Master',
command_log: 'Accedi',
sentinel_faq: 'Puoi scegliere una delle molteplici sentinelle. Si prega di compilare la configurazione sentinella per l\'indirizzo, la porta e la password. La password del nodo Redis è la password del nodo Master monitorato dalla sentinella.',
hotkey: 'Tasto di scelta rapida',
persist: 'Rimuovi l\'ora di scadenza',
custom_formatter: 'Formattatore personalizzato',
edit: 'Modifica',
new: 'Aggiungere',
custom: 'Personalizzare',
hide_window: 'Nascondi finestra',
minimize_window: 'Riduci finestra',
maximize_window: 'Massimizza finestra',
load_all_keys: 'carica tutto',
show_load_all_keys: 'Abilita pulsante per caricare tutte le chiavi',
load_all_keys_tip: 'Carica tutte le chiavi contemporaneamente. Se il numero di chiavi è troppo grande, il client potrebbe rimanere bloccato. Si prega di usarlo correttamente',
tree_node_overflow: 'Troppi tasti o cartelle, tenere solo {num} per la visualizzazione. Se la tua chiave non è qui, si raccomanda la ricerca sfocata, o impostare il separatore per distribuire le chiavi in cartelle',
connection_readonly: 'Modalità di sola lettura. È vietato aggiungere, modificare ed eliminare',
memory_analysis: 'Analisi della memoria',
begin: 'Inizio',
pause: 'Pausa',
restart: 'Ricomincia',
max_display: 'Numero massimo di visualizzazioni: {num}',
max_scan: 'Numero massimo di scansioni: {num}',
close_left: 'Chiudi le schede a sinistra',
close_right: 'Chiudi le schede a destra',
close_other: 'Chiudi altre schede',
slow_log: 'Interrogazione lenta',
load_current_folder: 'Carica solo la cartella corrente',
custom_name: 'Nome personalizzato',
},
};
export default it;
|
2301_77204479/AnotherRedisDesktopManager
|
src/i18n/langs/it.js
|
JavaScript
|
mit
| 10,153
|
const ko = {
message: {
new_connection: '새 연결',
refresh_connection: '새로고침',
edit_connection: '연결 편집',
duplicate_connection: '연결 복제',
del_connection: '연결 삭제',
close_connection: '연결 해제',
add_new_line: '새 행 추가',
dump_to_clipboard: '명령어 복사',
redis_version: '레디스 버전',
process_id: '프로세스 ID',
used_memory: '사용중인 메모리',
used_memory_peak: '최대 메모리 사용율',
used_memory_lua: 'Lua 메모리 사용율',
connected_clients: '클라이언트 연결',
total_connections_received: '총 연결수',
total_commands_processed: '총 명령어수',
key_statistics: '키 통계',
all_redis_info: '모든 레디스 정보',
server: '서버',
memory: '메모리',
stats: '상태',
settings: '설정',
ui_settings: '모양',
feature_settings: 'Function',
common_settings: '일반',
confirm_to_delete_row_data: '데이터 행을 삭제하시겠습니까?',
delete_success: '삭제하였습니다.',
delete_failed: '삭제 실패',
modify_success: '수정하였습니다.',
modify_failed: '수정 실패',
add_success: '추가하였습니다.',
add_failed: '추가 실패',
value_exists: '값이 존재합니다',
value_not_exists: '값이 존재하지 않습니다',
refresh_success: '새로고침 성공',
click_enter_to_rename: '클릭 또는 엔터로 이름 변경',
click_enter_to_ttl: '클릭 또는 엔터로 TTL 변경',
confirm_to_delete_key: '{key} 키를 삭제하시겠습니까?',
confirm_to_rename_key: '{old} -> {new} 이름으로 변경하시겠습니까?',
edit_line: '행 편집',
auto_refresh: '자동 새로고침',
auto_refresh_tip: '매 {interval}초마다 새로고침',
key_not_exists: '존재하지 않는 키',
collapse_all: '모두 접기',
expand_all: '모두 펴기',
json_format_failed: 'Json 변환 실패',
msgpack_format_failed: 'Msgpack 변환 실패',
php_unserialize_format_failed: 'PHP Unserialize 실패',
clean_up: '비우기',
redis_console: '레디스 콘솔',
confirm_to_delete_connection: '연결을 삭제하시겠습니까?',
connection_exists: '연결 설정이 이미 존재합니다',
close_to_edit_connection: '편집하기 전에 연결을 종료합니다.',
close_to_connection: '연결을 종료하시겠습니까?',
ttl_delete: 'TTL<=0 으로 설정하면 키가 바로 삭제됩니다.',
max_page_reached: '마지막 페이지',
add_new_key: '새 키',
enter_new_key: '새 키의 이름을 먼저 입력해주세요',
key_type: '키 유형',
save: '저장',
enter_to_search: '엔터로 검색',
export_success: '내보내기를 완료하였습니다.',
select_import_file: '파일을 선택해주세요',
import_success: '불러오기를 완료하였습니다.',
put_file_here: '파일을 이 곳으로 드래그하거나 클릭하여 선택해주세요',
config_connections: '연결',
import: '불러오기',
export: '내보내기',
open: '열기',
close: '닫기',
open_new_tab: '새 탭에서 열기',
exact_search: '완전일치 검색',
enter_to_exec: '엔터를 통해 명령을 실행하고, 방향키 위아래로 실행기록을 전환할 수 있습니다.',
pre_version: '버전',
manual_update: '직접 다운로드',
retry_too_many_times: '너무 많이 재연결을 시도하였습니다. 서버 상태를 확인해주세요.',
key_to_search: '키워드 검색',
search_connection: '검색 연결',
begin_update: '업데이트',
ignore_this_version: '이 버전 무시',
check_update: '업데이트 확인',
update_checking: '업데이트를 확인중입니다, 잠시만 기다려주세요...',
update_available: '새 버전을 찾았습니다.',
update_not_available: '최신버전입니다.',
update_error: '업데이트 실패',
update_downloading: '다운로드 중...',
update_download_progress: '다운로드 진행률',
update_downloaded: '업데이트가 완료되었습니다. 앱을 재시작해주세요.\
[도움말]: Windows를 사용하는 경우 앱을 종료한 후 바탕 화면 아이콘이 정상 상태(약 10초)로 새로 고쳐질 때까지 기다린 후 다시 열 수 있습니다.',
mac_not_support_auto_update: 'Mac은 자동 업데이트를 지원하지 않습니다. <a href="https://github.com/qishibo/AnotherRedisDesktopManager/releases">직접 다운로드</a>하여 재설치해주세요.\
또는 <br><code>brew reinstall --cask another-redis-desktop-manager</code> 명령을 실행하십시오.\
<br><hr><br>❤️만약 이 프로그램이 당신에게 유용하다면 <a href="https://apps.apple.com/app/id1516451072">앱스토어</a>를 통하여 후원하실 수 있습니다. 또한, 앱스토어는 자동으로 업데이트됩니다.',
font_family: '폰트 패밀리',
font_faq_title: '폰트 설정 지침',
font_faq: '1. 여러 폰트를 선택할 수 있습니다.<br>\
2. 폰트는 선택된 순서대로 로드됩니다. 영문 폰트를 먼저 선택하고 당신의 언어 폰트를 선택하는 것을 추천합니다.<br>\
3. 시스템 폰트가 목록에 없는 경우, 설치된 폰트명을 직접 입력할 수 있습니다.',
private_key_faq: '다음으로 시작하는 RSA 유형의 개인키를 지원합니다, <pre>-----BEGIN RSA PRIVATE KEY-----</pre>\
또는 <pre>-----BEGIN OPENSSH PRIVATE KEY-----</pre>형식 변경이 필요하다면 <pre>ssh-keygen -p -m pem -f ~/.ssh/id_rsa</pre>이 명령은 이전 개인키 로그인에 영향을 미치지 않습니다.',
dark_mode: '다크 모드',
load_more_keys: '더 불러오기',
key_name: '키 명',
project_home: '프로젝트 홈',
cluster_faq: '클러스터의 노드 중 아무거나 하나에 대하여 입력하면 다른 노드들은 자동으로 인식합니다.',
redis_status: '레디스 정보',
confirm_flush_db: '{db} 데이터베이스의 모든 키를 삭제하시겠습니까?',
flushdb: '데이터베이스 비우기',
flushdb_prompt: '진행하려면 "{txt}"를 입력해주세요.',
info_disabled: 'Info 명령 실행 예외(비활성화되었을 수 있음), Redis 정보를 표시할 수 없습니다.',
page_zoom: '화면 확대',
scan_disabled: '스캔 명령 실행 예외(비활성화되었을 수 있음), 키 목록을 표시할 수 없습니다.',
key_type_not_support: '이 유형에는 시각화 표현이 지원되지 않습니다. 콘솔을 이용해주세요.',
delete_folder: '모든 폴더를 스캔하고 삭제',
multiple_select: '다중 선택',
copy: '복사',
copy_success: '복사 되었습니다.',
keys_to_be_deleted: '삭제할 키',
delete_all: '모두 삭제',
clear_cache: '캐시 비우기',
mark_color: '라벨 색상',
key_no_permission: '파일 읽기 권한이 만료되었습니다, 파일을 직접 재선택해주세요.',
toggle_check_all: '모두 선택 | 모두 해제',
select_lang: '언어 선택',
clear_cache_tip: '클라이언트에 문제가 있을 때, 이 작업을 통해 모든 연결과 환경설정을 삭제하여 클라이언트를 복구할 수 있습니다.',
detail: '상세정보',
separator_tip: '트리뷰를 위한 구분자로, 비워두면 트리가 비활성화되고 목록으로 키를 표시합니다.',
confirm_modify_unvisible_content: '보이지않는 문자가 내용에 포함되어 있습니다. "Hex View"를 통해 안전하게 편집할 수 있습니다. "Text View"로 편집하면 오류가 발생할 수 있습니다. 정말로 계속 진행하시겠습니까?',
keys_per_loading: '한 번에 로드할 개수',
keys_per_loading_tip: '설정한 수 만큼 키를 불러옵니다. 너무 크게 설정하면 성능에 영향을 미칠 수 있습니다.',
host: '호스트',
port: '포트',
username: '사용자명',
password: '비밀번호',
connection_name: '이름',
separator: '구분자',
timeout: '연결시도 시간제한',
private_key: '개인키',
public_key: '공개키',
authority: '인증기관',
redis_node_password: '레디스 노드 비밀번호',
master_group_name: '마스터 그룹명',
command_log: '로그',
sentinel_faq: '여러 센티널 중 하나를 선택할 수 있습니다. 센티널의 주소, 포트 및 비밀번호를 입력하십시오. 레디스 노드 비밀번호는 센티널이 모니터링하는 마스터 노드의 비밀번호입니다.',
hotkey: '단축키',
persist: '만료시간 삭제',
custom_formatter: '사용자정의 형식',
edit: '편집',
new: '생성',
custom: '사용자정의',
hide_window: '창 숨기기',
minimize_window: '최소화',
maximize_window: '최대화',
load_all_keys: '모두 불러오기',
show_load_all_keys: '모두 불러오기 버튼 활성화',
load_all_keys_tip: '모든 키를 한 번에 불러옵니다. 만약 키가 너무 많다면 클라이언트가 멈출 수 있습니다. 사용에 주의 하십시오.',
tree_node_overflow: '키나 폴더가 너무 많으면 {num}개만 표시합니다. 찾으려는 키가 보이지 않으면 퍼지 검색을 권장합니다. 또는 구분자를 설정하여 키들을 폴더로 분류할 수 있습니다.',
connection_readonly: '읽기전용 모드입니다. 추가, 편집, 삭제가 제한됩니다.',
memory_analysis: '메모리 분석',
begin: '시작',
pause: '일시정지',
restart: '재시작',
max_display: '최대 표시제한: {num}',
max_scan: '최대 스캔제한: {num}',
close_left: '좌측 탭 닫기',
close_right: '우측 탭 닫기',
close_other: '다른 탭 닫기',
slow_log: '저성능 쿼리',
load_current_folder: '현재 폴더만 로드',
custom_name: '맞춤 이름',
},
};
export default ko;
|
2301_77204479/AnotherRedisDesktopManager
|
src/i18n/langs/ko.js
|
JavaScript
|
mit
| 10,087
|
const pt = {
message: {
new_connection: 'Nova Conexão',
refresh_connection: 'Atualizar',
edit_connection: 'Editar Conexão',
del_connection: 'Deletar Conexão',
duplicate_connection: 'Copiar Conexão',
close_connection: 'Encerrar Conexão',
add_new_line: 'Adicionar nova linha',
dump_to_clipboard: 'Copiar como comando',
redis_version: 'Versão do Redis',
process_id: 'ID do processo',
used_memory: 'Memória utilizada',
used_memory_peak: 'Pico de Memória Utilizada',
used_memory_lua: 'Memória Utilizada Lua',
connected_clients: 'Clientes conectados',
total_connections_received: 'Total de Conexões',
total_commands_processed: 'Total de Comandos',
key_statistics: 'Principais estatísticas',
all_redis_info: 'Todas as informações do Redis',
server: 'Servidor',
memory: 'Memória',
stats: 'Estatísticas',
settings: 'Configurações',
ui_settings: 'Aparência',
feature_settings: 'Função',
common_settings: 'Geral',
confirm_to_delete_row_data: 'Você deseja excluir os dados da linha?',
delete_success: 'Deleção executada com sucesso',
delete_failed: 'Houve uma falha na deleção',
modify_success: 'Modificação executada com sucesso',
modify_failed: 'Houve uma falha na modifição',
add_success: 'Sucesso ao adicionar',
add_failed: 'Falha ao adicionar',
value_exists: 'Valor existente',
value_not_exists: 'O valor não existe',
refresh_success: 'Sucesso ao atualizar',
click_enter_to_rename: 'Clique ou pressione Enter para renomear',
click_enter_to_ttl: 'Clique ou pressione Enter para modificar TTL',
confirm_to_delete_key: 'Você deseja deletar {key} ?',
confirm_to_rename_key: 'Confirmar o renome {old} -> {new} ?',
edit_line: 'Editar linha',
auto_refresh: 'Atualização Automática',
auto_refresh_tip: 'Interruptor de atualização automática, atualiza a cada {interval} segundos',
key_not_exists: 'Chave não existe',
collapse_all: 'Recolher todos',
expand_all: 'Expandir todos',
json_format_failed: 'Falha na análise do JSON',
msgpack_format_failed: 'Falha na análise do Msgpack',
php_unserialize_format_failed: 'Falha na desserialização do PHP',
clean_up: 'Limpar',
redis_console: 'Console do Redis',
confirm_to_delete_connection: 'Você deseja deletar a conexão?',
connection_exists: 'A configuração de conexão já existe',
close_to_edit_connection: 'Você deve encerrar a conexão antes de editar',
close_to_connection: 'Você deseja encerrar a conexão?',
ttl_delete: 'Definir TTL <= 0 excluirá a chave diretamente',
max_page_reached: 'Máxima página alcançada',
add_new_key: 'Nova Chave',
enter_new_key: 'Digite um novo nome de chave primeiro',
key_type: 'Tipo da Chave',
save: 'Salvar',
enter_to_search: 'Tecle ENTER para procurar',
export_success: 'Sucesso na Exportação',
select_import_file: 'Selecione o arquivo',
import_success: 'Sucesso na importação',
put_file_here: 'Arraste o arquivo aqui ou clique para selecionar',
config_connections: 'Conexões',
import: 'Importar',
export: 'Exportar',
open: 'Abrir',
close: 'Encerrar',
open_new_tab: 'Abrir em uma nova aba',
exact_search: 'Procura exata',
enter_to_exec: 'Pressione Enter para comandos de execução, para cima e para baixo para alternar o histórico',
pre_version: 'Versão',
manual_update: 'Download manual',
retry_too_many_times: 'Muitas tentativas de reconexões. Verifique o status do servidor',
key_to_search: 'Pesquisa por palavra-chave',
search_connection: 'Conexão de pesquisa',
begin_update: 'Atualizar',
ignore_this_version: 'Ignore esta versão',
check_update: 'Checar atualização',
update_checking: 'Procurando por atualizações existentes, aguarde um momento...',
update_available: 'Nova versão encontrada',
update_not_available: 'A sua aplicação está na versão mais recente',
update_error: 'Falha na atualização',
update_downloading: 'Downloading...',
update_download_progress: 'Download em progresso',
update_downloaded: 'Download da atualização concluído, reinicie seu aplicativo por favor.\
[Tips]: Se você estiver usando o Windows, depois de fechar o aplicativo, aguarde o ícone da área de trabalho para atualizar para um estado normal (cerca de 10 segundos), e então você pode reabri-lo',
mac_not_support_auto_update: 'Mac não suporta atualização automática, faça o <a href="https://github.com/qishibo/AnotherRedisDesktopManager/releases">download</a> e reinstale manualmente, \
Ou execute <br><code>brew reinstall --cask another-redis-desktop-manager </code>\
<br><hr><br>❤️se for útil para você, você pode patrocinar através da <a href="https://apps.apple.com/app/id1516451072">AppStore</a>, e a AppStore irá atualizá-lo automaticamente para você.',
font_family: 'Font Family',
font_faq_title: 'Instruções de configuração de fonte',
font_faq: '1. Múltiplas fontes podem ser definidas <br>\
2. A seleção da fonte é ordenada. É sugerido escolher a fonte em inglês primeiro e depois a fonte em seu idioma<br>\
3. Quando a lista de fontes do sistema não pode ser carregada em alguns casos excepcionais, você pode inserir o nome da fonte instalada manualmente.',
private_key_faq: 'A chave privada de formato RSA é compatível e começa com <pre>-----BEGIN RSA PRIVATE KEY-----</pre>\
mas se começar com<pre>-----BEGIN OPENSSH PRIVATE KEY-----</pre>você precisa converter o formato via <pre>ssh-keygen -p -m pem -f ~/.ssh/id_rsa</pre>Esta operação não afetará o login de chave privada anterior',
dark_mode: 'Modo noturno',
load_more_keys: 'carregar mais',
key_name: 'Nome da Chave',
project_home: 'Home do Projeto',
cluster_faq: 'Selecione qualquer nó no cluster para preencher e outros nós serão identificados automaticamente.',
redis_status: 'Informações do Redis',
confirm_flush_db: 'Confirme a exclusão de todas as chaves em db {db}?',
flushdb: 'Flush DB',
flushdb_prompt: 'Entrada "{txt}"',
info_disabled: 'Exceção de execução do comando de informação (pode ter sido desativado), as informações do redis não podem ser exibidas',
page_zoom: 'Zoom da página',
scan_disabled: 'Exceção de execução do comando de scan (pode ter sido desativada), a lista de chaves não pode ser exibida',
key_type_not_support: 'Visual display não é suportado para este tipo. Por favor, use console',
delete_folder: 'Verificar e excluir a pasta inteira',
multiple_select: 'Múltiplas Seleções',
copy: 'Copiar',
copy_success: 'Copiado com sucesso',
keys_to_be_deleted: 'Chaves a serem apagadas',
delete_all: 'Apagar Tudo',
clear_cache: 'Limpar cache',
mark_color: 'Cor da marca',
key_no_permission: 'A permissão de leitura do arquivo expirou, selecione novamente o arquivo de chave manualmente',
toggle_check_all: 'Selecionar tudo | Desmarcar tudo',
select_lang: 'Selecione o idioma',
clear_cache_tip: 'Quando há um problema com o cliente, esta operação irá deletar todas as conexões e configurações para restaurar o cliente',
detail: 'Detalhe',
separator_tip: 'O separador da visualização em árvore, definido como vazio para desativar a árvore e exibir as chaves como lista',
confirm_modify_unvisible_content: 'O conteúdo contém caracteres invisíveis, você pode editar com segurança no "Hex View". Se continuar a editar em "Text View" pode causar erros de codificação, deseja continuar?',
keys_per_loading: 'Número de chaves',
keys_per_loading_tip: 'O número de chaves carregadas a cada vez. A configuração muito grande pode afetar o desempenho',
host: 'Morada',
port: 'Porta',
username: 'Nome do usuário',
password: 'Senha',
connection_name: 'Nome personalizado',
separator: 'Separador',
timeout: 'Tempo esgotado',
private_key: 'Chave privada',
public_key: 'Chave pública',
authority: 'Autorização',
redis_node_password: 'Senha do nó Redis',
master_group_name: 'Nome do Grupo Master',
command_log: 'Registro',
sentinel_faq: 'Você pode escolher uma das várias sentinelas. Preencha a configuração da sentinela para o endereço, porta e senha. A senha do nó Redis é a senha do nó mestre monitorado pela sentinela.',
hotkey: 'Tecla de Atalho',
persist: 'Remover o tempo de expiração',
custom_formatter: 'Formatador Personalizado',
editar: 'Editar',
new: 'Adicionar',
custom: 'Customizar',
hide_window: 'Ocultar janela',
minimize_window: 'Minimize a janela',
maximize_window: 'Maximize a janela',
load_all_keys: 'carregar tudo',
show_load_all_keys: 'Habilite o botão para carregar todas as chaves',
load_all_keys_tip: 'Carregue todas as chaves de uma vez. Se o número de chaves for muito grande, o cliente pode ficar preso. Por favor, use-o corretamente',
tree_node_overflow: 'Muitas teclas ou pastas, manter apenas {num} para exibição. Se a sua chave não está aqui, é recomendada a pesquisa difusa, ou configurar o separador para espalhar as chaves em pastas',
connection_readonly: 'Modo somente leitura. Adição, edição e exclusão são proibidas',
memory_analysis: 'Análise de memória',
begin: 'Começar',
pause: 'Pausa',
restart: 'Reiniciar',
max_display: 'Número máximo de exibições: {num}',
max_scan: 'Número máximo de verificações: {num}',
close_left: 'Fechar abas esquerdas',
close_right: 'Fechar abas direitas',
close_other: 'Fechar outras guias',
slow_log: 'Consulta lenta',
load_current_folder: 'Carregar apenas a pasta atual',
custom_name: 'Nome personalizado',
},
};
export default pt;
|
2301_77204479/AnotherRedisDesktopManager
|
src/i18n/langs/pt.js
|
JavaScript
|
mit
| 9,914
|
const ru = {
message: {
new_connection: 'Новое подключение',
refresh_connection: 'Обновить',
edit_connection: 'Редактировать подключение',
duplicate_connection: 'Копировать соединение',
del_connection: 'Удалить подключение',
close_connection: 'Закрыть соединение',
add_new_line: 'Добавить новую строку',
dump_to_clipboard: 'Копировать как команду',
redis_version: 'Версия Redis',
process_id: 'ID процесса',
used_memory: 'Использовано памяти',
used_memory_peak: 'Пиковый объем памяти',
used_memory_lua: 'Использование памяти Lua',
connected_clients: 'Подключено клиентов',
total_connections_received: 'Количество подключений',
total_commands_processed: 'Количество команд',
key_statistics: 'Статистика по ключам',
all_redis_info: 'Вся информация Redis',
server: 'Сервер',
memory: 'Оперативная память',
stats: 'Статистика',
settings: 'Настройки',
ui_settings: 'Внешность',
feature_settings: 'Функция',
common_settings: 'Общий',
confirm_to_delete_row_data: 'Подтвердить удаление данной строки?',
delete_success: 'Успешно удалено',
delete_failed: 'Удалить не удалось',
modify_success: 'Успешно изменено',
modify_failed: 'Измененить не удалось',
add_success: 'Успешно добавлено',
add_failed: 'Добавить не удалось',
value_exists: 'Значение существует',
value_not_exists: 'Значение не существует',
refresh_success: 'Успешно обновлено',
click_enter_to_rename: 'Нажмите сюда или нажмите Enter, чтобы переименовать ключ.',
click_enter_to_ttl: 'Нажмите сюда или нажмите Enter, чтобы изменить время жизни ключа.',
confirm_to_delete_key: 'Подтвердите удаление {key} ?',
confirm_to_rename_key: 'Подтвердить переименование {old} -> {new} ?',
edit_line: 'Редактировать строку',
auto_refresh: 'Автоматическое обновление',
auto_refresh_tip: 'Автоматическое обновление, обновление каждые {interval} секунды',
key_not_exists: 'Ключ не существует',
collapse_all: 'Свернуть все',
expand_all: 'Развернуть все',
json_format_failed: 'Не удалось форматировать в JSON',
msgpack_format_failed: 'Не удалось форматировать в Msgpack',
php_unserialize_format_failed: 'PHP Unserialize форматирование не удалось',
clean_up: 'Очистить',
redis_console: 'Redis console',
confirm_to_delete_connection: 'Вы уверены, что хотите удалить подключение?',
connection_exists: 'Настройка с таким подключением уже существует',
close_to_edit_connection: 'Вы должны закрыть соединение перед редактированием. Вы уверены, что хотите продолжить?',
close_to_connection: 'Подтверждение закрытия соединения?',
ttl_delete: 'Установка TTL <= 0 удалит ключ. Вы уверены?',
max_page_reached: 'Достигнуто максимальное количество страниц',
add_new_key: 'Новый ключ',
enter_new_key: 'Пожалуйста, сначала введите новое имя ключа',
key_type: 'Тип ключа',
save: 'Сохранить',
enter_to_search: 'Введите ключ для поиска',
export_success: 'Успешно экспортировано',
select_import_file: 'Выберите файл',
import_success: 'Успешно импортировано',
put_file_here: 'Перетащите файлы сюда или нажмите, чтобы выбрать',
config_connections: 'Настройки подключения',
import: 'Импорт',
export: 'Экспорт',
open: 'Открыть',
close: 'Закрыть',
open_new_tab: 'Открыть в новом окне',
exact_search: 'Точный поиск',
enter_to_exec: 'После ввода команды Redis нажмите клавишу Enter для выполнения, клавиши вверх и вниз для переключения истории команд',
pre_version: 'Версия',
manual_update: 'Страница для скачивания',
retry_too_many_times: 'Слишком много попыток переподключения. Пожалуйста, проверьте состояние сервера',
key_to_search: 'Поиск по ключевым словам',
search_connection: 'Поиск соединения',
begin_update: 'Обновить',
ignore_this_version: 'Игнорировать эту версию',
check_update: 'Проверить обновление',
update_checking: 'Проверка обновлений, пожалуйста, подождите...',
update_available: 'Найдена новая версия',
update_not_available: 'У Вас последняя версия приложения',
update_error: 'Обновление не удалось',
update_downloading: 'Загрузка...',
update_download_progress: 'Прогресс загрузки',
update_downloaded: 'Обновление завершено, перезапустите приложение, пожалуйста.\
[Tips]: Если вы используете Windows, после закрытия приложения дождитесь обновления значка на рабочем столе до нормального состояния (около 10 секунд), а затем вы можете снова его открыть',
mac_not_support_auto_update: 'Mac не поддерживает автоматическое обновление, <a href="https://github.com/qishibo/AnotherRedisDesktopManager/releases">скачайте</a> и переустановите приложение вручную,\
Или выполните комманду <br><code>brew reinstall --cask another-redis-desktop-manager </code>\
<br><hr><br>❤️Если это полезно для вас, вы можете спонсировать через <a href="https://apps.apple.com/app/id1516451072">AppStore</a>, и AppStore автоматически обновит его для вас.',
font_family: 'Семейство шрифтов',
font_faq_title: 'Инструкции по настройке шрифта',
font_faq: '1. Можно установить несколько шрифтов.<br>\
2. Выбор шрифта происходит в последовательном порядке, рекомендуется сначала выбрать английский шрифт, а затем выбрать русский шрифт.<br>\
3. В некоторых исключительных случаях, когда список системных шрифтов не может быть загружен , вы можете вручную ввести имя установленного шрифта.',
private_key_faq: 'В настоящее время поддерживаются закрытые ключи формата RSA, начинающиеся с <pre>-----BEGIN RSA PRIVATE KEY-----</pre>\
Если ключ начинается с <pre>-----BEGIN OPENSSH PRIVATE KEY-----</pre> Вам нужно конвертировать его через <pre>ssh-keygen -p -m pem -f ~/.ssh/id_rsa</pre> Эта операция не повлияет на предыдущий вход в систему с закрытым ключом.',
dark_mode: 'Темная тема',
load_more_keys: 'загрузить ещё',
key_name: 'Имя ключа',
project_home: 'Страница приложения',
cluster_faq: 'Выберите любой узел в кластере и заполните его, он автоматически определит другие узлы.',
redis_status: 'Информация Redis',
confirm_flush_db: 'Вы уверены, что удалили все ключи в db {db}?',
flushdb: 'Удалить все ключи',
flushdb_prompt: 'Вход "{txt}"',
info_disabled: 'Исключение при выполнении команды Info (возможно, было отключено), информация о Redis не может быть отображена.',
page_zoom: 'Масштаб страницы',
scan_disabled: 'Исключение при выполнении команды Scan (возможно, было отключено), невозможно отобразить список ключей.',
key_type_not_support: 'показ этого типа пока не поддерживается, используйте консоль',
delete_folder: 'Сканировать и удалить всю папку',
multiple_select: 'Множественный выбор',
copy: 'Копировать',
copy_success: 'Успешно скопировано',
keys_to_be_deleted: 'Ключи для удаления',
delete_all: 'Удалить все',
clear_cache: 'Oчистить кэш',
mark_color: 'Цвет отметки',
key_no_permission: 'Срок действия разрешения на чтение файла истек, пожалуйста, повторно выберите ключевой файл вручную',
toggle_check_all: 'выбрать все | отменить выбор',
select_lang: 'Выбрать язык',
clear_cache_tip: 'Когда возникает проблема с клиентом, эта операция удалит все подключения и конфигурации для восстановления клиента',
detail: 'Информация',
separator_tip: 'Разделитель древовидного представления, установлен на пустой, чтобы отключить дерево и отображать ключи в виде списка',
confirm_modify_unvisible_content: 'Контент содержит невидимые символы, вы можете смело редактировать его в «Hex View». Если продолжение редактирования в «Text View» может вызвать ошибки кодирования, обязательно продолжить?',
keys_per_loading: 'Количество ключей',
keys_per_loading_tip: 'Количество ключей, загружаемых каждый раз. Установка слишком большого размера может повлиять на производительность',
host: 'Aдрес',
port: 'Порт',
username: 'Имя пользователя',
password: 'Пароль',
connection_name: 'Имя соединения',
separator: 'Pазделитель',
timeout: 'Tайм-аут',
private_key: 'Закрытый ключ',
public_key: 'Открытый ключ',
authority: 'Авторизация',
redis_node_password: 'Пароль узла Redis',
master_group_name: 'Master Имя группы',
command_log: 'Журнал логов',
sentinel_faq: 'Вы можете выбрать один из нескольких дозорных. Пожалуйста, заполните конфигурацию дозорных для адреса, порта и пароля. Пароль узла Redis - это пароль главного узла, который контролируется дозорным.',
hotkey: 'Горячие клавиши',
persist: 'Удалить время истечения',
custom_formatter: 'Пользовательский форматировщик',
edit: 'Редактировать',
new: 'Добавить',
custom: 'Настроить',
hide_window: 'Скрыть окно',
minimize_window: 'Свернуть окно',
maximize_window: 'Развернуть окно',
load_all_keys: 'загрузить все',
show_load_all_keys: 'Кнопка включения для загрузки всех ключей',
load_all_keys_tip: 'Загрузите все ключи одновременно. Если количество ключей слишком велико, клиент может застрять. Пожалуйста, используйте его правильно',
tree_node_overflow: 'Слишком много клавиш или папок, оставьте только {num} для отображения. Если вашего ключа здесь нет, рекомендуется использовать нечеткий поиск, или Настройка разделителя для разделения ключей в папку',
connection_readonly: 'Режим только для чтения. Добавление, редактирование и удаление запрещено',
memory_analysis: 'Анализ памяти',
begin: 'Начинать',
pause: 'Пауза',
restart: 'Начать сначала',
max_display: 'Максимальное количество дисплеев: {num}',
max_scan: 'Максимальное количество сканирований: {num}',
close_left: 'Закрыть левые вкладки',
close_right: 'Закрыть правые вкладки',
close_other: 'Закрыть другие вкладки',
slow_log: 'Медленный запрос',
load_current_folder: 'Загружать только текущую папку',
custom_name: 'Пользовательское имя',
},
};
export default ru;
|
2301_77204479/AnotherRedisDesktopManager
|
src/i18n/langs/ru.js
|
JavaScript
|
mit
| 14,716
|
const tr = {
message: {
new_connection: 'Yeni Bağlantı',
refresh_connection: 'Yenile',
edit_connection: 'Bağlantıyı Düzenle',
duplicate_connection: 'Bağlantıyı Kopyala',
del_connection: 'Bağlantıyı Sil',
close_connection: 'Bağlantıyı Kapat',
add_new_line: 'Yeni Satır Ekle',
dump_to_clipboard: 'Komut olarak kopyala',
redis_version: 'Redis Sürümü',
process_id: 'Süreç Kimliği',
used_memory: 'Kullanılan Bellek',
used_memory_peak: 'Kullanılan Maksimum Bellek',
used_memory_lua: 'Lua Tarafından Kullanılan Bellek',
connected_clients: 'Bağlı İstemciler',
total_connections_received: 'Toplam Bağlantı',
total_commands_processed: 'Toplam Komut',
key_statistics: 'Anahtar İstatistikleri',
all_redis_info: 'Tüm Redis Bilgisi',
server: 'Sunucu',
memory: 'Bellek',
stats: 'İstatistik',
settings: 'Ayarlar',
ui_settings: 'Dış görünüş',
feature_settings: 'Fonksiyon',
common_settings: 'Genel',
confirm_to_delete_row_data: 'Satır Verilerini Silmek İstiyor Musunuz?',
delete_success: 'Silme Başarılı',
delete_failed: 'Silme Başarısız',
modify_success: 'Güncelleme Başarılı',
modify_failed: 'Güncelleme Başarısız',
add_success: 'Ekleme Başarılı',
add_failed: 'Ekleme Başarısız',
value_exists: 'Değer Mevcut',
value_not_exists: 'Değer mevcut değil',
refresh_success: 'Yenileme Başarılı',
click_enter_to_rename: 'Yeniden Adlandırmak için Tıklayın veya Enter Tuşuna Basın',
click_enter_to_ttl: 'TTLyi Değiştirmek için Tıklayın veya Enter Tuşuna Basın',
confirm_to_delete_key: '{key} Anahtarı Silinsin mi?',
confirm_to_rename_key: 'Yeniden Adlandır {old} -> {new} ?',
edit_line: 'Satırı Düzenle',
auto_refresh: 'Otomatik Yenile',
auto_refresh_tip: 'Otomatik Yenileme, Her {interval} Saniyede Otomatik Yenile',
key_not_exists: 'Anahtar Mevcut Değil',
collapse_all: 'Hepsini Daralt',
expand_all: 'Hepsini Genişlet',
json_format_failed: 'Json Ayrıştırma Başarısız Oldu',
msgpack_format_failed: 'Msgpack Ayrıştırma Başarısız Oldu',
php_unserialize_format_failed: 'PHP Serileştirmesi Başarısız Oldu',
clean_up: 'Temizle',
redis_console: 'Redis Konsolu',
confirm_to_delete_connection: 'Bağlantıyı Silmeyi Onayla ?',
connection_exists: 'Bağlantı Yapılandırması Zaten Var',
close_to_edit_connection: 'Düzenlemeden Önce Bağlantıyı Kapatmalısınız',
close_to_connection: 'Bağlantıyı Kapatmayı Onayla ?',
ttl_delete: 'TTL Ayarı <= 0 Olan Anahtarlar Doğrudan Silinecek',
max_page_reached: 'Maks. Sayfaya Ulaşıldı',
add_new_key: 'Yeni Anahtar',
enter_new_key: 'Önce Yeni Anahtarın Adını Girin',
key_type: 'Anahtar Tipi',
save: 'Kaydet',
enter_to_search: 'Arama Yapmak İçin',
export_success: 'Dışa Aktarma Başarılı',
select_import_file: 'Dosyayı Seçin',
import_success: 'İçe Aktarma Başarılı',
put_file_here: 'Dosyayı Buraya Sürükle veya Seç',
config_connections: 'Bağlantılar',
import: 'İçe Aktar',
export: 'Dışa Aktar',
open: 'Aç',
close: 'Kapat',
open_new_tab: 'Yeni Sekmede Aç',
exact_search: 'Detaylı Arama',
enter_to_exec: 'Komutları Yürütmek için Enter, Geçmişi Değiştirmek için Yukarı ve Aşağı Tuşlarına Basın',
pre_version: 'Sürüm',
manual_update: 'Manuel İndirme',
retry_too_many_times: 'Yeniden Bağlanmak İçin Çok Fazla Deneme Yapıldı. Lütfen Sunucu Durumunu Kontrol Edin',
key_to_search: 'Anahtar Kelime Araması',
search_connection: 'Bağlantıyı Ara',
begin_update: 'Güncelle',
ignore_this_version: 'Bu sürümü yok sayın',
check_update: 'Güncellemeleri Denetle',
update_checking: 'Güncellemeler Kontrol Ediliyor, Birkaç Dakika Bekleyin ...',
update_available: 'Yeni Sürüm Bulundu',
update_not_available: 'Uygulamanız Güncel',
update_error: 'Güncelleştirme Başarısız',
update_downloading: 'İndiriliyor...',
update_download_progress: 'İndirme Durumu',
update_downloaded: 'Güncelleme İndirme Tamamlandı, Lütfen Uygulamanızı Yeniden Başlatın.\
[Tips]: Windows kullanıyorsanız, uygulamayı kapattıktan sonra masaüstü simgesinin normal duruma (yaklaşık 10 saniye) dönmesini bekleyin ve ardından yeniden açabilirsiniz',
mac_not_support_auto_update: 'Mac Otomatik Güncellemeyi Desteklemez, Lütfen Manuel Olarak <a href="https://github.com/qishibo/AnotherRedisDesktopManager/releases">İndirin</a> ve Yükleyin,\
veya Yükleme Komutunu Çalıştırın <br><code>brew reinstall --cask another-redis-desktop-manager </code>\
<br><hr><br>❤️sizin için yararlı olursa, <a href="https://apps.apple.com/app/id1516451072">AppStore</a> üzerinden sponsor olabilirsiniz ve AppStore sizin için otomatik olarak güncelleyecektir.',
font_family: 'Yazı Tipi Ailesi',
font_faq_title: 'Yazı Tipi Ayar Talimatları',
font_faq: '1. Birden fazla yazı tipi ayarlanabilir<br>\
2. Yazı tipi seçimi düzenli. Önce İngilizce yazı tipini sonra da kendi dilinizde yazı tipini seçmeniz önerilir<br>\
3. Bazı istisna durumlarda sistem yazı tipi listesi yüklenemediğinde, yüklü yazı tipi adını manuel girebilirsiniz.',
private_key_faq: '<pre>-----BEGIN RSA PRIVATE KEY-----</pre> ile başlayan RSA formatlı özel anahtar desteklenir\
<pre>-----BEGIN OPENSSH PRIVATE KEY-----</pre> ile başlayalım, <pre>ssh-keygen -p -m pem -f ~/.ssh/id_rsa</pre> ile formatı dönüştürmeniz gerekiyor. Bu işlem önceki özel anahtar girişini etkilemez',
dark_mode: 'Siyah Tema',
load_more_keys: 'devamını yükle',
key_name: 'Anahtar Adı',
project_home: 'Proje Ana Sayfası',
cluster_faq: 'Doldurmak için, kümedeki herhangi bir düğümü seçin, diğer düğümler otomatik olarak tanımlanacaktır.',
redis_status: 'Redis Bilgisi',
confirm_flush_db: 'Db {db} içindeki tüm anahtarları silmek istiyor musunuz?',
flushdb: 'Veritabanını Temizle',
flushdb_prompt: 'Giriş "{txt}"',
info_disabled: 'Bilgi komutu yürütme istisnası (devre dışı bırakılmış olabilir), yeniden bilgi gösterilemiyor',
page_zoom: 'Sayfa Yakınlaştırma',
scan_disabled: 'Tarama komutu yürütme istisnası (devre dışı bırakılmış olabilir), anahtar listesi görüntülenemiyor',
key_type_not_support: 'Görsel görüntüler bu tür için desteklenmiyor. Lütfen konsolu kullanın',
delete_folder: 'Tüm Klasörü Tara ve Sil',
multiple_select: 'Çoklu Seçim',
copy: 'Kopyala',
copy_success: 'Başarıyla kopyalandı',
keys_to_be_deleted: 'Silinecek Anahtarlar',
delete_all: 'Hepsini sil',
clear_cache: 'Önbelleği Temizle',
mark_color: 'Mark rengi',
key_no_permission: 'Dosya okuma izninin süresi doldu, lütfen anahtar dosyasını manuel olarak yeniden seçin',
toggle_check_all: 'Tümünü seç | Seçimini kaldır',
select_lang: 'Dil Seçin',
clear_cache_tip: 'İstemcide bir sorun olduğunda, bu işlem istemciyi geri yüklemek için tüm bağlantıları ve yapılandırmaları silecektir',
detail: 'Detay',
separator_tip: 'Ağaç görünümünün ayırıcısı, ağacı devre dışı bırakmak için boş olarak ayarlanır ve anahtarları liste olarak görüntüler',
confirm_modify_unvisible_content: 'İçerik görünmez karakterler içeriyor, "Hex View" içinde güvenle düzenleyebilirsiniz. "Text View" de düzenlemeye devam etmek kodlama hatalarına neden oluyorsa, devam edeceğinizden emin misiniz?',
keys_per_loading: 'Anahtar Sayısı',
keys_per_loading_tip: 'Her seferinde yüklenen anahtar sayısı. Çok büyük ayarlamak performansı etkileyebilir',
host: 'Adres',
port: 'Port',
username: 'Kullanıcı adı',
password: 'Parola',
connection_name: 'Bağlantı adı',
separator: 'Ayırıcı',
timeout: 'Zaman aşımı',
private_key: 'Özel anahtar',
public_key: 'Genel anahtar',
authority: 'Yetki',
redis_node_password: 'Redis düğüm şifresi',
master_group_name: 'Master Grubunun Adı',
command_log: 'Günlük',
sentinel_faq: 'Birden fazla nöbetçiden birini seçebilirsiniz. Lütfen adres, bağlantı noktası ve parola için sentinel yapılandırmasını doldurun. Redis düğüm parolası, nöbetçi tarafından izlenen Ana düğümün parolasıdır.',
hotkey: 'Kısayol Tuşu',
persist: 'Bitiş Süresini Kaldır',
custom_formatter: 'Özel Biçimlendirici',
edit: 'Düzenle',
new: 'Ekle',
custom: 'Özelleştir',
hide_window: 'Pencereyi gizle',
minimize_window: 'Pencereleri küçültür',
maximize_window: 'Pencereyi büyüt',
load_all_keys: 'hepsini yükle',
show_load_all_keys: 'Tüm anahtarları yüklemek için etkinleştir düğmesi',
load_all_keys_tip: 'Tüm anahtarları bir kerede yükleyin. Anahtar sayısı çok fazlaysa, istemci takılabilir. Lütfen doğru kullanın',
tree_node_overflow: 'Çok fazla anahtar veya klasör var, yalnızca {num} görüntüleme için ayrıldı. Anahtarınız burada değilse bulanık arama önerilir, veya anahtarı klasöre yaymak için bir ayırıcı ayarlayın',
connection_readonly: 'Salt okunur mod. Eklemek, düzenlemek ve silmek yasaktır',
memory_analysis: 'Bellek Analizi',
begin: 'Başlat',
pause: 'Duraklat',
restart: 'Tekrar başlat',
max_display: 'Maksimum ekran sayısı: {num}',
max_scan: 'Maksimum tarama sayısı: {num}',
close_left: 'Sol Sekmeleri Kapat',
close_right: 'Sağ Sekmeleri Kapat',
close_other: 'Diğer Sekmeleri Kapat',
slow_log: 'Yavaş Sorgu',
load_current_folder: 'Yalnızca Geçerli Klasörü Yükle',
custom_name: 'Özel Ad',
},
};
export default tr;
|
2301_77204479/AnotherRedisDesktopManager
|
src/i18n/langs/tr.js
|
JavaScript
|
mit
| 9,922
|
const tw = {
message: {
new_connection: '新增連線',
refresh_connection: '重新整理',
edit_connection: '編輯連線',
duplicate_connection: '複製連接',
del_connection: '刪除連線',
close_connection: '關閉連線',
add_new_line: '新增行',
dump_to_clipboard: '複製為命令',
redis_version: 'Redis 版本',
process_id: '處理程序 ID',
used_memory: '已使用記憶體',
used_memory_peak: '記憶體佔用峰值',
used_memory_lua: 'Lua 佔用記憶體',
connected_clients: '用戶端連線數',
total_connections_received: '歷史連線數',
total_commands_processed: '歷史命令數',
key_statistics: '鍵值統計',
all_redis_info: 'Redis 資訊總覽',
server: '伺服器',
memory: '記憶體',
stats: '狀態',
settings: '基本設定',
ui_settings: '外觀',
feature_settings: '功能',
common_settings: '通用',
confirm_to_delete_row_data: '確認刪除該行資料?',
delete_success: '刪除成功',
delete_failed: '刪除失敗',
modify_success: '修改成功',
modify_failed: '修改失敗',
add_success: '新增成功',
add_failed: '新增失敗',
value_exists: '值已存在',
value_not_exists: '該值不存在',
refresh_success: '重新整理成功',
click_enter_to_rename: '點擊或者按 Enter 鍵來重新命名',
click_enter_to_ttl: '點擊或者按 Enter 鍵來修改過期時間',
confirm_to_delete_key: '確認刪除 {key} ?',
confirm_to_rename_key: '確認重命名 {old} -> {new} ?',
edit_line: '修改行',
auto_refresh: '自動重新整理',
auto_refresh_tip: '自動重新整理開關,每 {interval} 秒重新整理一次',
key_not_exists: '鍵不存在',
collapse_all: '全部摺疊',
expand_all: '全部展開',
json_format_failed: 'JSON 格式化失敗',
msgpack_format_failed: 'Msgpack 格式化失敗',
php_unserialize_format_failed: 'PHP Unserialize 格式化失敗',
clean_up: '清空',
redis_console: 'Redis 控制台',
confirm_to_delete_connection: '確認刪除連線?',
connection_exists: '連線設定已存在',
close_to_edit_connection: '編輯前必須關閉連線,確定要繼續嗎',
close_to_connection: '確認關閉連線?',
ttl_delete: '設定 TTL<=0 將刪除該鍵,是否確認?',
max_page_reached: '已到達最大頁碼',
add_new_key: '新增鍵',
enter_new_key: '請先輸入新的鍵名',
key_type: '類型',
save: '儲存',
enter_to_search: 'Enter 鍵進行搜尋',
export_success: '匯出成功',
select_import_file: '選擇設定檔',
import_success: '匯入成功',
put_file_here: '將檔案拖到此處,或點擊選擇',
config_connections: '連線設定',
import: '匯入',
export: '匯出',
open: '打開',
close: '關閉',
open_new_tab: '以新視窗打開',
exact_search: '精確搜尋',
enter_to_exec: '輸入 Redis 指令後,按 Enter 鍵執行,上下鍵切換指令歷史紀錄',
pre_version: '目前版本',
manual_update: '手動下載',
retry_too_many_times: '嘗試重連次數過多,請檢查伺服器狀態',
key_to_search: '輸入關鍵字搜尋',
search_connection: '搜尋連接',
begin_update: '更新',
ignore_this_version: '忽略此版本',
check_update: '檢查更新',
update_checking: '檢查更新中, 請稍後...',
update_available: '發現新版本',
update_not_available: '目前為最新版本',
update_error: '更新失敗',
update_downloading: '下載中...',
update_download_progress: '下載進度',
update_downloaded: '更新下載完成,重啟用戶端生效.\
[Tips]: 如果您使用的是Windows,請在關閉應用程序後等待桌面圖標刷新到正常狀態(大約10秒),然後重新打開',
mac_not_support_auto_update: 'Mac 暫時不支援自動更新,請手動<a href="https://github.com/qishibo/AnotherRedisDesktopManager/releases">下載</a>後重新安裝,\
或者執行<br><code>brew reinstall --cask another-redis-desktop-manager </code>\
<br><hr><br>❤️如果對您有用,您可以通過<a href="https://apps.apple.com/app/id1516451072">AppStore</a>贊助,AppStore會自動為您更新。',
font_family: '字體選擇',
font_faq_title: '字體設定說明',
font_faq: '1. 可以設定多個字體<br>2. 字體選擇是有分先後順序的,建議首先選擇英文字體,然後再選擇中文字體<br>\
3. 某些異常情況無法載入系統字體列表時,可以手動輸入已安裝的字體名稱',
private_key_faq: '目前支持RSA格式私鑰,即以<pre>-----BEGIN RSA PRIVATE KEY-----</pre>開頭,\
以<pre>-----BEGIN OPENSSH PRIVATE KEY-----</pre>開頭的,需要執行\
<pre>ssh-keygen -p -m pem -f ~/.ssh/id_rsa</pre>進行格式轉換後再使用,該操作不會影響以前的私鑰登入',
dark_mode: '深色模式',
load_more_keys: '載入更多',
key_name: '鍵名',
project_home: '專案主頁',
cluster_faq: '選擇叢集中任一節點設定填入即可,會自動識別其它節點',
redis_status: 'Redis訊息',
confirm_flush_db: '確認刪除db{db}中的所有鍵值嗎?',
flushdb: '刪除所有鍵',
flushdb_prompt: '輸入 "{txt}"',
info_disabled: 'Info命令執行異常(可能已被禁用),無法顯示Redis訊息',
page_zoom: '頁面縮放',
scan_disabled: 'Scan命令執行異常(可能已被禁用),無法顯示key列表',
key_type_not_support: '該類型暫不支持視覺化展示,請使用Console',
delete_folder: '掃描並刪除整個資料夾',
multiple_select: '多項選擇',
copy: '複製',
copy_success: '複製成功',
keys_to_be_deleted: '即將刪除的鍵',
delete_all: '全部删除',
clear_cache: '清除緩存',
mark_color: '標記顏色',
key_no_permission: '文件讀取權限已過期,請手動重新選擇密鑰文件',
toggle_check_all: '全選 | 取消全選',
select_lang: '選擇語言',
clear_cache_tip: '如果客戶端出現問題,此操作將刪除所有連接和配置以恢復客戶端',
detail: '詳情',
separator_tip: '樹視圖的分隔符,設置為空可禁用樹並將鍵顯示為列表',
confirm_modify_unvisible_content: '內容包含不可見的字符,您可以在Hex視圖中進行安全編輯。如果繼續在Text視圖中進行編輯可能會導致編碼錯誤,確定要繼續嗎?',
keys_per_loading: '加載數量',
keys_per_loading_tip: '每次加載的key數量, 設置太大的話可能會影響使用性能',
host: '地址',
port: '端口',
username: '用戶名',
password: '密碼',
connection_name: '連接名稱',
separator: '分隔符',
timeout: '超時',
private_key: '私鑰',
public_key: '公鑰',
authority: '授權',
redis_node_password: 'Redis節點密碼',
master_group_name: 'Master組名',
command_log: '日誌',
sentinel_faq: '您可以選擇多個哨兵之一。 地址、端口、密碼請填寫哨兵配置。 Redis節點密碼是sentinel監控的Master節點的密碼。',
hotkey: '熱鍵',
persist: '刪除過期時間',
custom_formatter: '自定義格式化',
edit: '編輯',
new: '新增',
custom: '自定義',
hide_window: '隱藏窗口',
minimize_window: '最小化窗口',
maximize_window: '最大化窗口',
load_all_keys: '載入所有',
show_load_all_keys: '啟用按鈕以加載所有鍵',
load_all_keys_tip: '一次載入所有密鑰。如果密鑰數量過多,客戶端可能會卡住,請正確使用',
tree_node_overflow: '鍵或資料夾太多,僅保留{num}個以顯示。 如果您的鍵不在此處,建議使用模糊搜索,或設置分隔符以將密鑰分散到文件夾中',
connection_readonly: '只讀模式,禁止添加、編輯和刪除',
memory_analysis: '內存分析',
begin: '開始',
pause: '暫停',
restart: '重新開始',
max_display: '最大顯示數量:{num}',
max_scan: '最大掃描數量:{num}',
close_left: '關閉左側標籤',
close_right: '關閉右側標籤',
close_other: '關閉其他標籤',
slow_log: '慢查詢',
load_current_folder: '僅載入目前資料夾',
custom_name: '自訂名稱',
},
};
export default tw;
|
2301_77204479/AnotherRedisDesktopManager
|
src/i18n/langs/tw.js
|
JavaScript
|
mit
| 8,478
|
const ua = {
message: {
new_connection: 'Нове з`єднання',
refresh_connection: 'Оновити',
edit_connection: 'Редагувати з`єднання',
duplicate_connection: 'Копіювати підключення',
del_connection: 'Видалити з`єднання',
close_connection: 'Закрити з`єднання',
add_new_line: 'Додати новий рядок',
dump_to_clipboard: 'Копіювати як команду',
redis_version: 'Версія Redis',
process_id: 'ID процесу',
used_memory: 'Використано пам`яті',
used_memory_peak: 'Максимальний обсяг пам`яті',
used_memory_lua: 'Використання пам`яті Lua',
connected_clients: 'Підключено клієнтів',
total_connections_received: 'Кількість з`єднань',
total_commands_processed: 'Кількість команд',
key_statistics: 'Статистика по ключам',
all_redis_info: 'Вся інформація Redis',
server: 'Сервер',
memory: 'Оперативна пам`ять',
stats: 'Статистика',
settings: 'Налаштування',
ui_settings: 'Зовнішній вигляд',
feature_settings: 'Функція',
common_settings: 'Генеральний',
confirm_to_delete_row_data: 'Підтвердити видалення даних рядка?',
delete_success: 'Успішно видалено',
delete_failed: 'Видалити не вдалося',
modify_success: 'Успішно змінено',
modify_failed: 'Зміни не вдалося',
add_success: 'Успішно додано',
add_failed: 'Додати не вдалося',
value_exists: 'Значення вже існує',
value_not_exists: 'Значення не існує',
refresh_success: 'Успішно оновлено',
click_enter_to_rename: 'Натисніть сюди або Enter, щоб перейменувати ключ',
click_enter_to_ttl: 'Натисніть сюди або Enter, щоб змінити час життя ключа TTL',
confirm_to_delete_key: 'Підтвердіть видалення {key}?',
confirm_to_rename_key: 'Підтвердити перейменування {old} -> {new}?',
edit_line: 'Редагувати рядок',
auto_refresh: 'Автоматичне оновлення',
auto_refresh_tip: 'Автоматичне оновлення, оновлення кожні {interval} секунд',
key_not_exists: 'Ключ не існує',
collapse_all: 'Згорнути все',
expand_all: 'Розгорнути все',
json_format_failed: 'Не вдалося форматувати в JSON',
msgpack_format_failed: 'Не вдалося форматувати в MessagePack',
php_unserialize_format_failed: 'PHP Unserialize форматування невдале',
clean_up: 'Очистити',
redis_console: 'Redis консоль',
confirm_to_delete_connection: 'Ви впевнені, що хочете видалили з`єднання?',
connection_exists: 'Налаштування з таким з`єднанням вже існує',
close_to_edit_connection: 'Ви повинні закрити з`єднання перед змінами. Ви хочете продовжити?',
close_to_connection: 'Підтвердження закриття з`єднання?',
ttl_delete: 'Встановлення TTL <= 0 видалить ключ. Ви впевнені?',
max_page_reached: 'Досягнуто максимальну кількість сторінок',
add_new_key: 'Новий ключ',
enter_new_key: 'Будь ласка, спочатку введіть нове ім`я ключа',
key_type: 'Тип ключа',
save: 'Зберегти',
enter_to_search: 'Введіть ключ для пошуку',
export_success: 'Успішно експортовано',
select_import_file: 'Виберіть файл',
import_success: 'Успішно імпортовано',
put_file_here: 'Перетягніть файли сюди або натисніть, щоб вибрати',
config_connections: 'Налаштування з`єднання',
import: 'Імпорт',
export: 'Експорт',
open: 'Відкрити',
close: 'Закрити',
open_new_tab: 'Відкрити в новому вікні',
exact_search: 'Точний пошук',
enter_to_exec: 'Натисніть Enter для виконання команди, клавіші вгору і вниз для перемикання історії команд',
pre_version: 'Версія',
manual_update: 'Сторінка для зкачування',
retry_too_many_times: 'Занадто багато спроб з`єднатись. Будь ласка, перевірте стан сервера',
key_to_search: 'Пошук за ключовими словами',
search_connection: 'Пошук підключення',
begin_update: 'Оновити',
ignore_this_version: 'Ігнорувати цю версію',
check_update: 'Перевірити оновлення',
update_checking: 'Перевірка оновлень, будь ласка, чекайте ...',
update_available: 'Знайдена нова версія',
update_not_available: 'У Вас остання версія програми',
update_error: 'Оновлення не вдалося',
update_downloading: 'Завантаження ...',
update_download_progress: 'Прогрес завантаження',
update_downloaded: 'Оновлення завершено, запустіть програму, будь ласка.\
[Tips]: Якщо ви використовуєте Windows, після закриття програми, дочекавшись значка робочого столу, щоб оновити його до нормального стану (приблизно 10 секунд), а потім ви можете відкрити його знову',
mac_not_support_auto_update: 'MacOS не підтримує автоматичне оновлення, <a href="https://github.com/qishibo/AnotherRedisDesktopManager/releases">скачайте</a> і перевстановіть додаток вручну, \
Або виконайте комманду <br><code>brew reinstall --cask another-redis-desktop-manager </code>\
<br><hr><br>❤️якщо це корисно для вас, ви можете спонсорувати через <a href="https://apps.apple.com/app/id1516451072">AppStore</a>, і AppStore автоматично оновить його для вас.',
font_family: 'Шрифти',
font_faq_title: 'Інструкції з налаштування шрифту',
font_faq: '1. Можна встановити кілька шрифтів. <br>\
2. Вибір шрифту відбувається в послідовному порядку, рекомендується спочатку вибрати англійський шрифт, а потім вибрати український шрифт. <br> \
3. У деяких випадках, коли список системних шрифтів не може бути завантажений, ви можете вручну ввести ім`я встановленого шрифту',
private_key_faq: 'В даний час підтримуються закриті RSA ключі, що починаються з <pre> ----- BEGIN RSA PRIVATE KEY ----- </ pre> \
Якщо ключ починається з <pre> ----- BEGIN OPENSSH PRIVATE KEY ----- </ pre> Вам потрібно конвертувати його через <pre> ssh-keygen -p -m pem -f ~ / .ssh / id_rsa < / pre> Ця операція не вплине на попередній вхід в систему з закритим ключем',
dark_mode: 'Темна тема',
load_more_keys: 'завантажити ще',
key_name: 'Ім`я ключа',
project_home: 'Сторінка додатка',
cluster_faq: 'Виберіть будь-який вузол в кластері і заповніть його, він автоматично визначить інші вузли',
redis_status: 'Інформація Redis',
confirm_flush_db: 'Ви впевнені, що видалили всі ключі в db {db}?',
flushdb: 'Видалити всі ключі',
flushdb_prompt: 'введіть "{txt}"',
info_disabled: 'Виняток при виконанні команди Info (можливо, було відключено), інформація про Redis не відображається',
page_zoom: 'Масштаб сторінки',
scan_disabled: 'Виняток при виконанні команди Scan (можливо, було відключено), неможливо відобразити список ключів',
key_type_not_support: 'показ цього типу поки не підтримується, використовуйте консоль',
delete_folder: 'Сканувати та видаляти цілу папку',
multiple_select: 'Вибрати кілька',
copy: 'Копіювати',
copy_success: 'Копіювання успішно',
keys_to_be_deleted: 'Ключі для видалення',
delete_all: 'Видалити все',
clear_cache: 'Oчистити кеш',
mark_color: 'Позначити колір',
key_no_permission: 'Термін дії дозволу на читання файлу закінчився, будь-ласка, виберіть файл ключа вручну',
toggle_check_all: 'вибрати все | скасувати вибір усіх',
select_lang: 'Оберіть мову',
clear_cache_tip: 'Коли виникає проблема з клієнтом, ця операція видалить усі з\'єднання та конфігурації для відновлення клієнта',
detail: 'деталь',
separator_tip: 'Розділювач дерева, встановлений на порожній, щоб вимкнути дерево та клавіші відображення як список',
confirm_modify_unvisible_content: 'Вміст містить невидимі символи, ви можете безпечно редагувати їх у "Hex View". Якщо продовження редагування у "Text View" може спричинити помилки кодування, впевнено продовжувати?',
keys_per_loading: 'Кількість ключів',
keys_per_loading_tip: 'Кількість клавіш, що завантажуються кожного разу. Занадто велике значення може вплинути на продуктивність',
host: 'Aдресу',
port: 'Порт',
username: 'Ім\'я користувача',
password: 'Пароль',
connection_name: 'Спеціальна назва',
separator: 'Cепаратор',
timeout: 'Час вийшов',
private_key: 'Приватний ключ',
public_key: 'Відкритий ключ',
authority: 'Авторизація',
redis_node_password: 'Пароль вузла Redis',
master_group_name: 'Назва групи Master',
command_log: 'Журнал',
sentinel_faq: 'Ви можете вибрати один із декількох сторожових. Будь ласка, заповніть конфігурацію сторожової адреси, порту та пароля. Пароль вузла Redis - це пароль головного вузла, який контролює сторожовий.',
hotkey: 'Гаряча клавіша',
persist: 'Видаліть термін дії',
custom_formatter: 'Спеціальне форматування',
edit: 'Pедагувати',
new: 'Додати',
custom: 'Hалаштувати',
hide_window: 'Сховати вікно',
minimize_window: 'Згорнути вікно',
maximize_window: 'Розгорнути вікно',
load_all_keys: 'завантажити все',
show_load_all_keys: 'Кнопка «Увімкнути», щоб завантажити всі ключі',
load_all_keys_tip: 'Завантажте всі ключі одночасно. Якщо кількість ключів занадто велика, клієнт може застрягти. Будь ласка, використовуйте його правильно',
tree_node_overflow: 'Занадто багато ключів або папок, тільки {num} дисплея. Якщо ваш ключ не тут, рекомендується використовувати нечіткий пошук, або встановити роздільник для поширення ключів у теки',
connection_readonly: 'Режим лише для читання. Додавання, редагування та видалення заборонено',
memory_analysis: 'Аналіз пам\'яті',
begin: 'Почніть',
pause: 'Пауза',
restart: 'Перезавантажте',
max_display: 'Максимальна кількість показів: {num}',
max_scan: 'Максимальна кількість сканувань: {num}',
close_left: 'Закрити ліві вкладки',
close_right: 'Закрити праві вкладки',
close_other: 'Закрийте інші вкладки',
slow_log: 'Повільний запит',
load_current_folder: 'Завантажувати лише поточну папку',
custom_name: 'Спеціальна назва',
},
};
export default ua;
|
2301_77204479/AnotherRedisDesktopManager
|
src/i18n/langs/ua.js
|
JavaScript
|
mit
| 14,191
|
import Vue from 'vue';
import ElementUI from 'element-ui';
import 'font-awesome/css/font-awesome.css';
import App from './App';
import i18n from './i18n/i18n';
import bus from './bus';
import util from './util';
import storage from './storage';
import shortcut from './shortcut';
// vxe-table
// import VxeUITable from 'vxe-table';
import 'vxe-table/lib/style.css';
// Vue.use(VxeUITable);
Vue.prototype.$bus = bus;
Vue.prototype.$util = util;
Vue.prototype.$storage = storage;
Vue.prototype.$shortcut = shortcut;
Vue.use(ElementUI, { size: 'small' });
Vue.config.productionTip = false;
/* eslint-disable no-new */
const vue = new Vue({
el: '#app',
i18n,
components: { App },
template: '<App/>',
});
// handle uncaught exception
process.on('uncaughtException', (err, origin) => {
if (!err) {
return;
}
vue.$message.error({
message: `Uncaught Exception: ${err}`,
duration: 5000,
});
vue.$bus.$emit('closeConnection');
});
export default vue;
|
2301_77204479/AnotherRedisDesktopManager
|
src/main.js
|
JavaScript
|
mit
| 979
|
import Redis from 'ioredis';
import { createTunnel } from 'tunnel-ssh';
import vue from '@/main.js';
import { remote } from 'electron';
import { writeCMD } from '@/commands.js';
const fs = require('fs');
const { sendCommand } = Redis.prototype;
// redis command log
Redis.prototype.sendCommand = function (...options) {
const command = options[0];
// readonly mode
if (this.options.connectionReadOnly && writeCMD[command.name.toUpperCase()]) {
command.reject(new Error('You are in readonly mode! Unable to execute write command!'));
return command.promise;
}
// exec directly, without logs
if (this.withoutLogging === true) {
// invalid in next calling
this.withoutLogging = false;
return sendCommand.apply(this, options);
}
const start = performance.now();
const response = sendCommand.apply(this, options);
const cost = performance.now() - start;
const record = {
time: new Date(), connectionName: this.options.connectionName, command, cost,
};
vue.$bus.$emit('commandLog', record);
return response;
};
// fix ioredis hgetall key has been toString()
Redis.Command.setReplyTransformer('hgetall', (result) => {
const arr = [];
for (let i = 0; i < result.length; i += 2) {
arr.push([result[i], result[i + 1]]);
}
return arr;
});
export default {
createConnection(host, port, auth, config, promise = true, forceStandalone = false, removeDb = false) {
const options = this.getRedisOptions(host, port, auth, config);
let client = null;
if (removeDb) {
delete options.db;
}
if (forceStandalone) {
client = new Redis(options);
}
// sentinel redis
else if (config.sentinelOptions) {
const sentinelOptions = this.getSentinelOptions(host, port, auth, config);
client = new Redis(sentinelOptions);
}
// cluster redis
else if (config.cluster) {
const clusterOptions = this.getClusterOptions(options, config.natMap ? config.natMap : {});
client = new Redis.Cluster([{ port, host }], clusterOptions);
}
// standalone redis
else {
client = new Redis(options);
}
if (promise) {
return new Promise((resolve, reject) => {
resolve(client);
});
}
return client;
},
createSSHConnection(sshOptions, host, port, auth, config) {
const sshOptionsDict = this.getSSHOptions(sshOptions, host, port);
const configRaw = JSON.parse(JSON.stringify(config));
const sshConfigRaw = JSON.parse(JSON.stringify(sshOptionsDict));
const sshPromise = new Promise((resolve, reject) => {
createTunnel(...Object.values(sshOptionsDict)).then(([server, connection]) => {
const listenAddress = server.address();
// sentinel mode
if (configRaw.sentinelOptions) {
// this is a sentinel connection, remove db
const client = this.createConnection(listenAddress.address, listenAddress.port, auth, configRaw, false, true, true);
client.on('ready', () => {
client.call('sentinel', 'get-master-addr-by-name', configRaw.sentinelOptions.masterName).then((reply) => {
if (!reply) {
return reject(new Error(`Master name "${configRaw.sentinelOptions.masterName}" not exists!`));
}
// connect to the master node via ssh
this.createClusterSSHTunnels(sshConfigRaw, [{ host: reply[0], port: reply[1] }]).then((tunnels) => {
const sentinelClient = this.createConnection(
tunnels[0].localHost, tunnels[0].localPort, configRaw.sentinelOptions.nodePassword, configRaw, false, true,
);
return resolve(sentinelClient);
});
}).catch((e) => { reject(e); }); // sentinel exec failed
});
client.on('error', (e) => { reject(e); });
}
// ssh cluster mode
else if (configRaw.cluster) {
const client = this.createConnection(listenAddress.address, listenAddress.port, auth, configRaw, false, true);
client.on('ready', () => {
// get all cluster nodes info
client.call('cluster', 'nodes').then((reply) => {
const nodes = this.getClusterNodes(reply);
// create ssh tunnel for each node
this.createClusterSSHTunnels(sshConfigRaw, nodes).then((tunnels) => {
configRaw.natMap = this.initNatMap(tunnels);
// select first line of tunnels to connect
const clusterClient = this.createConnection(tunnels[0].localHost, tunnels[0].localPort, auth, configRaw, false);
resolve(clusterClient);
});
}).catch((e) => { reject(e); });
});
client.on('error', (e) => { reject(e); });
}
// ssh standalone redis
else {
const client = this.createConnection(listenAddress.address, listenAddress.port, auth, configRaw, false);
return resolve(client);
}
// create SSH tunnel failed
}).catch((e) => {
// vue.$message.error('SSH errror: ' + e.message);
// vue.$bus.$emit('closeConnection');
reject(e);
});
});
return sshPromise;
},
getSSHOptions(options, host, port) {
const tunnelOptions = {
autoClose: false,
};
// where your localTCP Server is listening
const serverOptions = {
// if port set to 0, the serverOptions will be null
// which means automatic assign by OS
// host: '127.0.0.1',
// port: 0,
};
// ssh server
const sshOptions = {
host: options.host,
port: options.port,
username: options.username,
password: options.password,
privateKey: this.getFileContent(options.privatekey, options.privatekeybookmark),
passphrase: options.passphrase ? options.passphrase : undefined,
readyTimeout: (options.timeout) > 0 ? (options.timeout * 1000) : 30000,
keepaliveInterval: 10000,
};
// forward link in ssh server
const forwardOptions = {
// set srcAddr/srcPort undefined to use server.address() automatically
// srcAddr: '127.0.0.1',
// srcPort: 0,
dstAddr: host,
dstPort: port,
};
// Tips: small dict is ordered, should replace to Map if dict is large
return {
tunnelOptions, serverOptions, sshOptions, forwardOptions,
};
},
getRedisOptions(host, port, auth, config) {
return {
// add additional host+port to options for "::1"
host,
port,
family: 0,
connectTimeout: 30000,
retryStrategy: times => this.retryStragety(times, { host, port }),
enableReadyCheck: false,
connectionName: config.connectionName ? config.connectionName : null,
password: auth,
db: config.db ? config.db : undefined,
// ACL support
username: config.username ? config.username : undefined,
tls: config.sslOptions ? this.getTLSOptions(config.sslOptions) : undefined,
connectionReadOnly: config.connectionReadOnly ? true : undefined,
// return int as string to avoid big number issues
stringNumbers: true,
};
},
getSentinelOptions(host, port, auth, config) {
return {
sentinels: [{ host, port }],
sentinelPassword: auth,
password: config.sentinelOptions.nodePassword,
name: config.sentinelOptions.masterName,
connectTimeout: 30000,
retryStrategy: times => this.retryStragety(times, { host, port }),
enableReadyCheck: false,
connectionName: config.connectionName ? config.connectionName : null,
db: config.db ? config.db : undefined,
// ACL support
username: config.username ? config.username : undefined,
tls: config.sslOptions ? this.getTLSOptions(config.sslOptions) : undefined,
};
},
getClusterOptions(redisOptions, natMap = {}) {
return {
connectionName: redisOptions.connectionName,
enableReadyCheck: false,
slotsRefreshTimeout: 30000,
redisOptions,
natMap,
};
},
getClusterNodes(nodes, type = 'master') {
const result = [];
nodes = nodes.split('\n');
for (let node of nodes) {
if (!node) {
continue;
}
node = node.trim().split(' ');
if (node[2].includes(type)) {
const dsn = node[1].split('@')[0];
const lastIndex = dsn.lastIndexOf(':');
const host = dsn.substr(0, lastIndex);
const port = dsn.substr(lastIndex + 1);
result.push({ host, port });
}
}
return result;
},
createClusterSSHTunnels(sshConfig, nodes) {
const sshTunnelStack = [];
for (const node of nodes) {
// tunnelssh will change 'config' param, so just copy it
const sshConfigCopy = JSON.parse(JSON.stringify(sshConfig));
// revocery the buffer after json.parse
if (sshConfigCopy.sshOptions.privateKey) {
sshConfigCopy.sshOptions.privateKey = Buffer.from(sshConfigCopy.sshOptions.privateKey);
}
sshConfigCopy.forwardOptions.dstHost = node.host;
sshConfigCopy.forwardOptions.dstPort = node.port;
const promise = new Promise((resolve, reject) => {
const sshPromise = createTunnel(...Object.values(sshConfigCopy));
sshPromise.then(([server, connection]) => {
const addr = server.address();
const line = {
localHost: addr.address,
localPort: addr.port,
dstHost: node.host,
dstPort: node.port,
};
resolve(line);
}).catch((e) => {
reject(e);
});
});
sshTunnelStack.push(promise);
}
return Promise.all(sshTunnelStack);
},
initNatMap(tunnels) {
const natMap = {};
for (const line of tunnels) {
natMap[`${line.dstHost}:${line.dstPort}`] = { host: line.localHost, port: line.localPort };
}
return natMap;
},
getTLSOptions(options) {
return {
// ca: options.ca ? fs.readFileSync(options.ca) : '',
// key: options.key ? fs.readFileSync(options.key) : '',
// cert: options.cert ? fs.readFileSync(options.cert) : '',
ca: this.getFileContent(options.ca, options.cabookmark),
key: this.getFileContent(options.key, options.keybookmark),
cert: this.getFileContent(options.cert, options.certbookmark),
checkServerIdentity: (servername, cert) =>
// skip certificate hostname validation
undefined,
rejectUnauthorized: false,
};
},
retryStragety(times, connection) {
const maxRetryTimes = 3;
if (times >= maxRetryTimes) {
vue.$message.error('Too Many Attempts To Reconnect. Please Check The Server Status!');
vue.$bus.$emit('closeConnection');
return false;
}
// reconnect after
return Math.min(times * 200, 1000);
},
getFileContent(file, bookmark = '') {
if (!file) {
return undefined;
}
try {
// mac app store version, read through bookmark
if (bookmark) {
const bookmarkClose = remote.app.startAccessingSecurityScopedResource(bookmark);
}
const content = fs.readFileSync(file);
(typeof bookmarkClose === 'function') && bookmarkClose();
return content;
} catch (e) {
// force alert
alert(`${vue.$t('message.key_no_permission')}\n[${e.message}]`);
vue.$bus.$emit('closeConnection');
return undefined;
}
},
};
|
2301_77204479/AnotherRedisDesktopManager
|
src/redisClient.js
|
JavaScript
|
mit
| 11,464
|
import Vue from 'vue';
import Router from 'vue-router';
import Tabs from '@/components/Tabs';
Vue.use(Router);
export default new Router({
routes: [
{
path: '/',
name: 'Tabs',
component: Tabs,
},
],
});
|
2301_77204479/AnotherRedisDesktopManager
|
src/router/index.js
|
JavaScript
|
mit
| 235
|
import keymaster from 'keymaster';
import { ipcRenderer } from 'electron';
// enable shortcut in input, textarea, select
keymaster.filter = e => true;
// prevent ctrl+r
keymaster('ctrl+r, ⌘+r', e => false);
// minimize window
keymaster('ctrl+h, ctrl+m, ⌘+m', (e) => {
ipcRenderer.send('minimizeWindow');
return false;
});
// hide window on mac
// (process.platform === 'darwin') && keymaster('⌘+h', e => {
// ipcRenderer.send('hideWindow');
// return false;
// });
// toggle maximize
keymaster('ctrl+enter, ⌘+enter', (e) => {
ipcRenderer.send('toggleMaximize');
return false;
});
export default {
bind: (...args) => keymaster(...args),
...keymaster,
};
|
2301_77204479/AnotherRedisDesktopManager
|
src/shortcut.js
|
JavaScript
|
mit
| 683
|
import utils from './util';
const { randomString } = utils;
export default {
getSetting(key) {
let settings = localStorage.getItem('settings');
settings = settings ? JSON.parse(settings) : {};
return key ? settings[key] : settings;
},
saveSettings(settings) {
settings = JSON.stringify(settings);
return localStorage.setItem('settings', settings);
},
getFontFamily() {
let fontFamily = this.getSetting('fontFamily');
// set to default font-family
if (
!fontFamily || !fontFamily.length
|| fontFamily.toString() === 'Default Initial'
) {
fontFamily = ['-apple-system', 'BlinkMacSystemFont', 'Segoe UI', 'Helvetica',
'Arial', 'sans-serif', 'Microsoft YaHei', 'Apple Color Emoji', 'Segoe UI Emoji'];
}
return fontFamily.map(line => `"${line}"`).join(',');
},
getCustomFormatter(name = '') {
let formatters = localStorage.getItem('customFormatters');
formatters = formatters ? JSON.parse(formatters) : [];
if (!name) {
return formatters;
}
for (const line of formatters) {
if (line.name === name) {
return line;
}
}
},
saveCustomFormatters(formatters = []) {
return localStorage.setItem('customFormatters', JSON.stringify(formatters));
},
addConnection(connection) {
this.editConnectionByKey(connection, '');
},
getConnections(returnList = false) {
let connections = localStorage.connections || '{}';
connections = JSON.parse(connections);
if (returnList) {
connections = Object.keys(connections).map(key => connections[key]);
this.sortConnections(connections);
}
return connections;
},
editConnectionByKey(connection, oldKey = '') {
oldKey = connection.key || oldKey;
const connections = this.getConnections();
delete connections[oldKey];
this.updateConnectionName(connection, connections);
const newKey = this.getConnectionKey(connection, true);
connection.key = newKey;
// new added has no order, add it. do not add when edit mode
if (!oldKey && isNaN(connection.order)) {
// connection.order = Object.keys(connections).length;
const maxOrder = Math.max(...Object.values(connections).map(item => (!isNaN(item.order) ? item.order : 0)));
connection.order = (maxOrder > 0 ? maxOrder : 0) + 1;
}
connections[newKey] = connection;
this.setConnections(connections);
},
editConnectionItem(connection, items = {}) {
const key = this.getConnectionKey(connection);
const connections = this.getConnections();
if (!connections[key]) {
return;
}
Object.assign(connection, items);
Object.assign(connections[key], items);
this.setConnections(connections);
},
updateConnectionName(connection, connections) {
let name = this.getConnectionName(connection);
for (const key in connections) {
// if 'name' same with others, add random suffix
if (this.getConnectionName(connections[key]) == name) {
name += ` (${randomString(3)})`;
break;
}
}
connection.name = name;
},
getConnectionName(connection) {
return connection.name || `${connection.host}@${connection.port}`;
},
setConnections(connections) {
localStorage.connections = JSON.stringify(connections);
},
deleteConnection(connection) {
const connections = this.getConnections();
const key = this.getConnectionKey(connection);
delete connections[key];
this.hookAfterDelConnection(connection);
this.setConnections(connections);
},
getConnectionKey(connection, forceUnique = false) {
if (Object.keys(connection).length === 0) {
return '';
}
if (connection.key) {
return connection.key;
}
if (forceUnique) {
return `${new Date().getTime()}_${randomString(5)}`;
}
return connection.host + connection.port + connection.name;
},
sortConnections(connections) {
connections.sort((a, b) => {
// drag ordered
if (!isNaN(a.order) && !isNaN(b.order)) {
return parseInt(a.order) <= parseInt(b.order) ? -1 : 1;
}
// no ordered, by key
if (a.key && b.key) {
return a.key < b.key ? -1 : 1;
}
return a.key ? 1 : (b.key ? -1 : 0);
});
},
reOrderAndStore(connections = []) {
const newConnections = {};
for (const index in connections) {
const connection = connections[index];
connection.order = parseInt(index);
newConnections[this.getConnectionKey(connection, true)] = connection;
}
this.setConnections(newConnections);
return newConnections;
},
getStorageKeyMap(type) {
const typeMap = {
cli_tip: 'cliTips',
last_db: 'lastSelectedDb',
custom_db: 'customDbName',
};
return type ? typeMap[type] : typeMap;
},
initStorageKey(prefix, connectionName) {
return `${prefix}_${connectionName}`;
},
getStorageKeyByName(type = 'cli_tip', connectionName = '') {
return this.initStorageKey(this.getStorageKeyMap(type), connectionName);
},
hookAfterDelConnection(connection) {
const connectionName = this.getConnectionName(connection);
const types = Object.keys(this.getStorageKeyMap());
const willRemovedKeys = [];
for (const type of types) {
willRemovedKeys.push(this.getStorageKeyByName(type, connectionName));
}
willRemovedKeys.forEach(k => localStorage.removeItem(k));
},
};
|
2301_77204479/AnotherRedisDesktopManager
|
src/storage.js
|
JavaScript
|
mit
| 5,446
|
export default {
data: {},
get(name) {
return this.data[name];
},
set(name, value) {
this.data[name] = value;
},
bufVisible(buf) {
if (typeof buf === 'string') {
return true;
}
return buf.equals(Buffer.from(buf.toString()));
},
bufToString(buf, forceHex = false) {
// if (typeof buf == 'string') {
// return buf;
// }
if (!Buffer.isBuffer(buf)) {
return buf;
}
if (!forceHex && this.bufVisible(buf)) {
return buf.toString();
}
return this.bufToHex(buf);
},
bufToQuotation(buf) {
const str = this.bufToString(buf).replaceAll('"', '\\"');
return `"${str}"`;
},
bufToHex(buf) {
const result = buf.toJSON().data.map((item) => {
if (item >= 32 && item <= 126) {
return String.fromCharCode(item);
}
return `\\x${item.toString(16).padStart(2, 0)}`;
});
return result.join('');
},
xToBuffer(str) {
let result = '';
for (let i = 0; i < str.length;) {
if (str.substr(i, 2) == '\\x') {
result += str.substr(i + 2, 2);
i += 4;
} else {
result += Buffer.from(str[i++]).toString('hex');
}
}
return Buffer.from(result, 'hex');
},
bufToBinary(buf) {
let binary = '';
for (const item of buf) {
binary += item.toString(2).padStart(8, 0);
}
return binary;
},
binaryStringToBuffer(str) {
const groups = str.match(/[01]{8}/g);
const numbers = groups.map(binary => parseInt(binary, 2));
return Buffer.from(new Uint8Array(numbers));
},
cutString(string, maxLength = 20) {
if (string.length <= maxLength) {
return string;
}
return `${string.substr(0, maxLength)}...`;
},
isJson(string) {
try {
const obj = JSON.parse(string);
return !!obj && typeof obj === 'object';
} catch (e) {}
return false;
},
isPHPSerialize(str) {
const phpSerialize = require('php-serialize');
try {
// phpSerialize.unserialize(str);
return phpSerialize.isSerialized(str.toString());
} catch (e) {}
return false;
},
isJavaSerialize(buf) {
try {
const { ObjectInputStream } = require('java-object-serialization');
const result = (new ObjectInputStream(buf)).readObject();
return typeof result === 'object';
} catch (e) {
return false;
}
},
isPickle(buf) {
try {
const { Parser } = require('pickleparser');
const result = (new Parser()).parse(buf);
return !!result;
} catch (e) {
return false;
}
},
isMsgpack(buf) {
const { decode } = require('algo-msgpack-with-bigint');
try {
const result = decode(buf);
if (['object', 'string'].includes(typeof result)) {
return true;
}
} catch (e) {}
return false;
},
isBrotli(buf) {
return typeof this.zippedToString(buf, 'brotli') === 'string';
},
isGzip(buf) {
return typeof this.zippedToString(buf, 'gzip') === 'string';
},
isDeflate(buf) {
return typeof this.zippedToString(buf, 'deflate') === 'string';
},
isDeflateRaw(buf) {
return typeof this.zippedToString(buf, 'deflateRaw') === 'string';
},
isProtobuf(buf) {
// fix #859, #880, exclude number type
if (!isNaN(buf)) {
return false;
}
const { getData } = require('rawproto');
try {
const result = getData(buf);
// fix #922 some str mismatch
if (result[0]) {
const firstEle = Object.values(result[0])[0];
if (firstEle < 1e-14 || firstEle.low) {
return false;
}
}
return true;
} catch (e) {}
return false;
},
zippedToString(buf, type = 'unzip') {
const zlib = require('zlib');
const funMap = {
// unzip will automatically detect Gzip or Deflate header
unzip: 'unzipSync',
gzip: 'gunzipSync',
deflate: 'inflateSync',
brotli: 'brotliDecompressSync',
deflateRaw: 'inflateRawSync',
};
try {
const decompressed = zlib[funMap[type]](buf);
if (Buffer.isBuffer(decompressed) && decompressed.length) {
return decompressed.toString();
}
} catch (e) {}
return false;
},
base64Encode(str) {
return Buffer.from(str, 'utf8').toString('base64');
},
base64Decode(str) {
return Buffer.from(str, 'base64').toString('utf8');
},
humanFileSize(size = 0) {
if (!size) {
return 0;
}
const i = Math.floor(Math.log(size) / Math.log(1024));
return (size / Math.pow(1024, i)).toFixed(2) * 1 + ['B', 'KB', 'MB', 'GB', 'TB'][i];
},
leftTime(seconds) {
if (seconds == 0 || seconds == -1) {
return '';
}
let str = '';
if (seconds >= 86400) {
str += `${parseInt(seconds / 60 / 60 / 24)} day, `;
}
if (seconds >= 3600) {
str += `${parseInt(seconds / 60 / 60 % 24)} hour, `;
}
if (seconds >= 60) {
str += `${parseInt(seconds / 60 % 60)} min, `;
}
str += `${parseInt(seconds % 60)} sec`;
return str;
},
cloneObjWithBuff(object) {
const clone = JSON.parse(JSON.stringify(object));
for (const i in clone) {
if ((typeof clone[i] === 'object') && (clone[i].type === 'Buffer')) {
clone[i] = Buffer.from(clone[i]);
}
}
return clone;
},
keysToList(keys) {
return keys.map((key) => {
const item = {
name: this.bufToString(key),
nameBuffer: key.toJSON(),
};
item.key = item.name;
return item;
});
},
keysToTree(keys, separator = ':', openStatus = {}, forceCut = 20000) {
const tree = {};
keys.forEach((key) => {
let currentNode = tree;
const keyStr = this.bufToString(key);
const keySplited = keyStr.split(separator);
const lastIndex = keySplited.length - 1;
keySplited.forEach((value, index) => {
// key node
if (index === lastIndex) {
currentNode[`${keyStr}\`k\``] = {
keyNode: true,
nameBuffer: key,
};
}
// folder node
else {
(currentNode[value] === undefined) && (currentNode[value] = {});
}
currentNode = currentNode[value];
});
});
// to tree format
return this.formatTreeData(tree, '', openStatus, separator, forceCut);
},
formatTreeData(tree, previousKey = '', openStatus = {}, separator = ':', forceCut = 20000) {
return Object.keys(tree).map((key) => {
const node = { name: key || '[Empty]' };
// folder node
if (!tree[key].keyNode && Object.keys(tree[key]).length > 0) {
// fullName
const tillNowKeyName = previousKey + key + separator;
// folder's fullName may same with key name, such as 'aa-'
// for unique, add 'F' prefix
node.key = `F${tillNowKeyName}`;
node.open = openStatus.has(node.key);
node.children = this.formatTreeData(tree[key], tillNowKeyName, openStatus, separator, forceCut);
node.keyCount = node.children.reduce((a, b) => a + (b.keyCount || 1), 0);
// too many children, force cut, do not incluence keyCount display
// node.open && node.children.length > forceCut && node.children.splice(forceCut);
// keep folder node in front of the tree and sorted(not include the outest list)
// async sort, only for opened folders
node.open && this.sortKeysAndFolder(node.children);
node.fullName = tillNowKeyName;
}
// key node
else {
// node.keyCount = 1;
node.name = key.replace(/`k`$/, '');
node.nameBuffer = tree[key].nameBuffer.toJSON();
node.key = node.name;
}
return node;
});
},
// nodes is reference, keep folder in front and sorted,
// keep keys in tail and sorted
// sortByData
sortKeysAndFolder(nodes) {
nodes.sort((a, b) => {
// a & b are all keys
if (!a.children && !b.children) {
return a.name > b.name ? 1 : -1;
}
// a & b are all folder
if (a.children && b.children) {
return a.name > b.name ? 1 : -1;
}
// a is folder, b is key
if (a.children) {
return -1;
}
// a is key, b is folder
return 1;
});
},
// sortByTreeNode
sortByTreeNodes(nodes) {
nodes.sort((a, b) => {
// a & b are all keys
if (a.isLeaf && b.isLeaf) {
return a.label > b.label ? 1 : -1;
}
// a & b are all folder
if (!a.isLeaf && !b.isLeaf) {
return a.label > b.label ? 1 : -1;
}
// a is folder, b is key
if (!a.isLeaf) {
return -1;
}
// a is key, b is folder
return 1;
});
},
copyToClipboard(text) {
const { clipboard } = require('electron');
clipboard.writeText(text ? text.toString() : '');
},
debounce(func, wait, immediate = false, context = null) {
let timeout; let
result;
const debounced = function () {
const args = arguments;
timeout && clearTimeout(timeout);
const later = function () {
timeout = null;
if (!immediate) result = func.apply(context, args);
};
const callNow = immediate && !timeout;
timeout = setTimeout(later, wait);
if (callNow) result = func.apply(context, args);
return result;
};
debounced.cancel = function () {
clearTimeout(timeout);
timeout = null;
};
return debounced;
},
randomString(len = 5) {
return Math.random().toString(36).substr(-len);
},
createAndDownloadFile(fileName, content) {
const aTag = document.createElement('a');
const blob = new Blob([content]);
aTag.download = fileName;
aTag.href = URL.createObjectURL(blob);
aTag.click();
URL.revokeObjectURL(blob);
},
arrayChunk(arr, size) {
return Array.from({ length: Math.ceil(arr.length / size) }, (v, i) => arr.splice(0, size));
},
};
|
2301_77204479/AnotherRedisDesktopManager
|
src/util.js
|
JavaScript
|
mit
| 9,916
|
<script>
export default {
onLaunch: function() {
// 检测网络状态
this.checkNetworkStatus();
// 获取token
const token = uni.getStorageSync('token');
if(token){
uni.switchTab({ url: '/pages/tabs/chat' })
}
},
onShow: function() {
},
onHide: function() {
},
methods: {
checkNetworkStatus() {
// 获取当前网络类型
uni.getNetworkType({
success: (res) => {
if (res.networkType === 'none') {
uni.showToast({
title: '无网络连接,请检查网络设置',
icon: 'none'
});
}
}
});
// 监听网络状态变化
uni.onNetworkStatusChange((res) => {
if (!res.isConnected) {
uni.showToast({
title: '网络连接已断开,请检查网络设置',
icon: 'none'
});
} else if (res.networkType === '2g' || res.networkType === '3g') {
uni.showToast({
title: '网络信号较弱,建议切换到更好的网络',
icon: 'none'
});
}
});
}
}
}
</script>
<style lang="scss">
/*每个页面公共css */
@import '@/uni_modules/uni-scss/index.scss';
/* #ifndef APP-NVUE */
/* #endif */
.example-info {
font-size: 14px;
color: #333;
padding: 10px;
}
.status_bar {
height: var(--status-bar-height);
width: 100%;
}
page {
font-size: 28rpx !important;
.container {
padding: 32rpx;
}
}
//flex公共样式
.flex {
display: flex;
}
.flex-1 {
flex: 1;
}
.flex-wrap {
flex-wrap: wrap;
}
.flex-center {
justify-content: center;
align-items: center;
}
.flex-between {
justify-content: space-between;
align-items: center;
}
.flex-column {
flex-direction: column;
}
.flex-column-center {
justify-content: center;
align-items: center;
}
.flex-column-between {
justify-content: space-between;
align-items: center;
}
.flex-column-start {
justify-content: flex-start;
align-items: flex-start;
}
.flex-column-end {
justify-content: flex-end;
align-items: flex-end;
}
.flex-column-around {
justify-content: space-around;
align-items: center;
}
.flex-column-between {
justify-content: space-between;
align-items: center;
}
.flex-column-start {
justify-content: flex-start;
align-items: flex-start;
}
.flex-column-end {
justify-content: flex-end;
align-items: flex-end;
}
.flex-column-around {
justify-content: space-around;
align-items: center;
}
.flex-column-between {
justify-content: space-between;
align-items: center;
}
.flex-column-start {
justify-content: flex-start;
align-items: flex-start;
}
.flex-column-end {
justify-content: flex-end;
align-items: flex-end;
}
.flex-start-center{
justify-content: flex-start;
align-items: center;
}
.flex-end-center{
justify-content: flex-end;
align-items: center;
}
</style>
|
2301_77169380/aionix-2
|
App.vue
|
Vue
|
mit
| 2,865
|
// 配置基础URL
// export const baseURL = 'http://47.97.254.154:8080/api'
// test
export const baseURL = 'http://47.97.254.154:8080/api'
export const clientId = '428a8310cd442757ae699df5d894f051'
export const appName = "Sider"
export const appVersion = 'V1.0.0'
|
2301_77169380/aionix-2
|
config/config.js
|
JavaScript
|
mit
| 268
|
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8" />
<script>
var coverSupport = 'CSS' in window && typeof CSS.supports === 'function' && (CSS.supports('top: env(a)') ||
CSS.supports('top: constant(a)'))
document.write(
'<meta name="viewport" content="width=device-width, user-scalable=no, initial-scale=1.0, maximum-scale=1.0, minimum-scale=1.0' +
(coverSupport ? ', viewport-fit=cover' : '') + '" />')
</script>
<title></title>
<!--preload-links-->
<!--app-context-->
</head>
<body>
<div id="app"><!--app-html--></div>
<script type="module" src="/main.js"></script>
</body>
</html>
|
2301_77169380/aionix-2
|
index.html
|
HTML
|
mit
| 672
|
// #ifndef VUE3
import Vue from 'vue'
import App from './App'
import { http } from './utils/request'
Vue.config.productionTip = false
Vue.prototype.$http = http
App.mpType = 'app'
const app = new Vue({
...App
})
app.$mount()
// #endif
// #ifdef VUE3
import { createSSRApp } from 'vue'
import App from './App.vue'
import { http } from './utils/request'
export function createApp() {
const app = createSSRApp(App)
app.config.globalProperties.$http = http
return {
app
}
}
// #endif
|
2301_77169380/aionix-2
|
main.js
|
JavaScript
|
mit
| 500
|
<template>
<view class="page-container">
<view class="status_bar"></view>
<view style="display: flex; align-items: center; height: 88rpx; position: relative;">
<image src="/static/indicator-back.png" style="width: 48rpx; height: 48rpx; position: absolute; top: 20rpx; left: 32rpx;" @tap="navBack"></image>
<view style="font-size: 36rpx; font-weight: 600; flex: 1; text-align: center;">联系我们</view>
</view>
<view style="padding-left: 32rpx;font-size: 28rpx; color: rgba(51, 51, 51, 1);">反馈内容</view>
<view class="input-box">
<textarea v-model="feedbackForm.content" placeholder="我们很想听您的心里话!无论您有什么想法或问题,请随时与我们分享。您的反馈对我们意义重大😊" class="text-area"></textarea>
<view class="image-box">
<image :src="item" v-for="(item,index) in feedbackForm.images" :key="index" class="image-item"></image>
<view class="image-item image-upload-box" @tap="selectImage">
<image src="/static/upload.png" style="width: 48rpx; height: 48rpx;"></image>
</view>
</view>
</view>
<view style="padding-left: 32rpx;font-size: 28rpx; color: rgba(51, 51, 51, 1); margin-top: 48rpx;">您的电子邮箱地址</view>
<view class="input-item">
<input v-model="feedbackForm.email" placeholder="请输入有效的电子邮箱地址" style="width: 100%;"/>
</view>
<view class="commit-button" :class="[buttonEnabled ? 'enabled' : '']" @tap="commit">提交</view>
</view>
</template>
<script setup>
import { reactive, computed} from 'vue'
import { http } from '@/utils/request'
import { appName, appVersion } from '@/config/config';
import { onMounted } from 'vue';
import { onLoad,onShow } from "@dcloudio/uni-app";
const feedbackForm = reactive({
content: '',
images: [],
email: '',
})
const buttonEnabled = computed(()=>{
return feedbackForm.content && feedbackForm.email
})
const navBack = ()=>{
uni.navigateBack();
}
const selectImage = ()=>{
if (feedbackForm.images.length >= 5) return;
uni.chooseImage({
count: 1,
success(data) {
const file = data.tempFilePaths[0];
http.upload(file).then(resp=>{
feedbackForm.images.push(resp.url);
})
}
})
}
const commit = ()=> {
if (!buttonEnabled) return;
http.post('/app/feedback/commit', {
content: feedbackForm.content,
images: JSON.stringify(feedbackForm.images),
email: feedbackForm.email
}).then((resp)=>{
uni.showToast({
title: "提交成功", icon: 'none'
});
feedbackForm.content = '';
feedbackForm.images = [];
feedbackForm.email = '';
})
}
</script>
<style lang="scss" scoped>
.page-container {
min-height: 500rpx;
background: linear-gradient(180deg, rgba(255, 255, 255, 0) 0%, rgba(255, 255, 255, 1) 100%), linear-gradient(90deg, rgba(194, 253, 255, 1) 0%, rgba(228, 252, 182, 1) 100%);
}
.input-box {
margin: 16rpx 32rpx 0 32rpx;
background-color: white;
border-radius: 16rpx;
box-shadow: 5px 5px 10px rgba(0, 0, 0, 0.1);
padding: 32rpx;
.text-area {
min-height: 64rpx;
width: 100%;
}
.image-box {
display: flex;
flex-direction: row;
align-items: center;
margin-top: 32rpx;
.image-item {
width: 60rpx;
height: 60rpx;
border-radius: 16rpx;
margin-right: 16rpx;
}
.image-upload-box {
border: 1px dashed rgba(153, 153, 153, 1);
display: flex;
align-items: center;
justify-content: center;
}
}
}
.input-item {
margin: 16rpx 32rpx 0 32rpx;
background-color: rgba(250, 250, 250, 1);
border-radius: 16rpx;
padding: 32rpx;
}
.commit-button {
position: fixed;
bottom: 64rpx;
left: 32rpx;
right: 32rpx;
height: 96rpx;
border-radius: 16rpx;
background: rgba(245, 245, 245, 1);
display: flex;
align-items: center;
justify-content: center;
}
.commit-button.enabled {
background: linear-gradient(90deg, rgba(177, 242, 201, 1) 0%, rgba(71, 214, 133, 1) 100%);
}
</style>
|
2301_77169380/aionix-2
|
pages/common/feedback.vue
|
Vue
|
mit
| 4,009
|
<template>
<view class="page-container">
<view class="status_bar"></view>
<view style="display: flex; align-items: center; height: 88rpx; position: relative;">
<image src="/static/indicator-back.png" style="width: 48rpx; height: 48rpx; position: absolute; top: 20rpx; left: 32rpx;" @tap="navBack"></image>
<view style="font-size: 36rpx; font-weight: 600; flex: 1; text-align: center;">邀请朋友</view>
</view>
<view class="box">
<view style="height: 112rpx; display: flex; align-items: center; padding-left: 32rpx; border-bottom: 1px dashed rgba(220, 220, 220, 1);">
<view style="font-size: 36rpx;font-weight: 600;">邀请流程</view>
</view>
<view style="display: flex; padding: 32rpx; align-items: center; justify-content: space-around">
<view >
<view style="display: flex; justify-content: center;">
<image src="/static/invite/link.png" style="width: 48rpx; height: 48rpx;"></image>
</view>
<view style="margin-top: 24rpx; color: rgba(153, 153, 153, 1); text-align: center;">发送链接</view>
</view>
<image src="/static/invite/step.png" style="width: 15rpx; height: 20rpx;"></image>
<view >
<view style="display: flex; justify-content: center;">
<image src="/static/invite/sigin.png" style="width: 48rpx; height: 48rpx;"></image>
</view>
<view style="margin-top: 24rpx; color: rgba(153, 153, 153, 1); text-align: center;">邀请注册</view>
</view>
<image src="/static/invite/step.png" style="width: 15rpx; height: 20rpx;"></image>
<view >
<view style="display: flex; justify-content: center;">
<image src="/static/invite/login.png" style="width: 48rpx; height: 48rpx;"></image>
</view>
<view style="margin-top: 24rpx; color: rgba(153, 153, 153, 1); text-align: center;">登录用户</view>
</view>
<image src="/static/invite/step.png" style="width: 15rpx; height: 20rpx;"></image>
<view >
<view style="display: flex; justify-content: center;">
<image src="/static/invite/gift.png" style="width: 48rpx; height: 48rpx;"></image>
</view>
<view style="margin-top: 24rpx; color: rgba(153, 153, 153, 1); text-align: center;">双方奖励</view>
</view>
</view>
</view>
<view class="box" style="padding: 32rpx;">
<view style="display: flex; align-items: center; justify-content: space-around;">
<view style="width: 256rpx;">
<view style="text-align: center;font-size: 32rpx; font-weight: 600;">第一个邀请</view>
</view>
<image src="/static/invite/arrow.png" style="width: 32rpx; height: 32rpx;"></image>
<view style="width: 256rpx;"></view>
</view>
</view>
</view>
</template>
<script setup>
import { reactive, computed} from 'vue'
import { http } from '@/utils/request'
import { appName, appVersion } from '@/config/config';
import { onMounted } from 'vue';
import { onLoad,onShow } from "@dcloudio/uni-app";
const navBack = ()=>{
uni.navigateBack();
}
const shareData = reactive({
firstDiamondCount: 0,
firstStartCount: 0,
moreDiamondCount: 0,
moreStarCount: 0,
registerDiamondCount: 0,
url: '',
})
onLoad((option)=>{
http.get("/app/user/share").then(resp=>{
console.log(resp);
Object.assign(shareData, resp.data);
})
})
</script>
<style lang="scss" scoped>
.page-container {
min-height: 500rpx;
background: linear-gradient(180deg, rgba(255, 255, 255, 0) 0%, rgba(255, 255, 255, 1) 100%), linear-gradient(90deg, rgba(194, 253, 255, 1) 0%, rgba(228, 252, 182, 1) 100%);
}
.box {
margin: 16rpx 32rpx 0 32rpx;
background-color: white;
border-radius: 16rpx;
box-shadow: 5px 5px 10px rgba(0, 0, 0, 0.1);
}
</style>
|
2301_77169380/aionix-2
|
pages/common/invite.vue
|
Vue
|
mit
| 3,703
|
<template>
<view>
<web-view :src="webData.url"></web-view>
</view>
</template>
<script setup>
import { reactive } from 'vue'
import { http } from '@/utils/request'
import { onLoad,onShow } from "@dcloudio/uni-app";
const webData = reactive({
url: '',
title: '',
})
const webViewStyle = reactive({
})
onLoad((option)=>{
webData.url = option.url;
webData.title = option.title;
uni.setNavigationBarTitle({
title: option.title || ''
})
console.log(option.title);
})
</script>
<style lang="scss" scoped>
</style>
|
2301_77169380/aionix-2
|
pages/common/web.vue
|
Vue
|
mit
| 551
|
<template>
<view class="login-page flex flex-column">
<view class="login-page-header flex flex-column">
<input type="number" :maxlength="11" placeholder="请输入手机账号" class="login-input-phone" v-model="loginForm.username" />
<input type="password" placeholder="请输入密码" class="login-input-password" v-model="loginForm.password" />
<view class="tip-text flex flex-center"><view>还没有账号?去</view>
<navigator url="/pages/register" :render-link="false" hover-class="none" class="tip-text-register">注册</navigator></view>
<view class="login-button" @tap="login"><text>登 录</text></view>
</view>
</view>
</template>
<script setup>
import { reactive } from 'vue'
import { http } from '@/utils/request'
import { clientId } from '@/config/config.js'
const loginForm = reactive({
username: 'test',
password: '123123',
clientId: clientId
})
const login = () => {
if(!loginForm.username || !loginForm.password){
uni.showToast({
title: '请输入手机账号和密码',
icon: 'none'
})
return
}
http.request({
url: '/app/user/login',
method: 'POST',
data: {
username: loginForm.username,
password: loginForm.password,
clientId: loginForm.clientId
}
}).then(res => {
if(res.code === 200){
uni.setStorageSync('token', res.data.access_token)
uni.showToast({
title: '登录成功',
icon: 'none'
})
uni.switchTab({ url: '/pages/tabs/chat' })
}
})
}
</script>
<style lang="scss" scoped>
.login-page{
height: 100%;
justify-content: center;
align-items: center;
padding: 0 90rpx;
}
.login-page-header{
font-size: 32rpx;
width: 100%;
.login-input-phone,
.login-input-password{
font-size: 26rpx;
height: 80rpx;
border: 1px solid #E5E5E5;
border-radius: 58rpx;
padding: 0 24rpx;
}
.login-input-password{
margin-top: 34rpx;
}
.tip-text{
font-size: 26rpx;
color: #999999;
margin-bottom: 120rpx;
margin-top: 18rpx;
text-align: center;
.tip-text-register{
color: #F35570;
padding: 10rpx;
}
}
.login-button{
padding: 24rpx 48rpx;
background: linear-gradient(90deg, #49f6fc 20%, #c5ff59 100%);
text-align: center;
border-radius: 58rpx;
font-size: 32rpx;
color: #333333;
font-weight: 500;
flex: 1;
}
}
</style>
|
2301_77169380/aionix-2
|
pages/login.vue
|
Vue
|
mit
| 2,338
|
<template>
<view class="page-container">
<view class="status_bar"></view>
<view style="display: flex; align-items: center; height: 88rpx; position: relative;">
<image src="/static/indicator-back.png" style="width: 48rpx; height: 48rpx; position: absolute; top: 20rpx; left: 32rpx;" @tap="navBack"></image>
<view style="font-size: 36rpx; font-weight: 600; flex: 1; text-align: center;">关于我们</view>
</view>
<view style="display: flex; justify-content: center; padding-top: 128rpx;">
<image src="/static/logo.png" style="width: 128rpx; height: 128rpx; border-radius: 16rpx;"></image>
</view>
<view style="display: flex; justify-content: center; margin-top: 32rpx; font-size: 48rpx; font-weight: 800; color: black;">{{appName}}</view>
<view style="display: flex; justify-content: center; margin-top: 10rpx; font-size: 32rpx; color: rgba(153, 153, 153, 1);">{{appVersion}}</view>
<view class="nav-box">
<view class="nav-item" @tap="settingItemClick(settings.serviceUrl, '服务条款')">
<view class="nav-title">服务条款</view>
<image src="/static/indicator-right.png" class="nav-icon"></image>
</view>
<view class="nav-divider"></view>
<view class="nav-item" @tap="settingItemClick(settings.privacyUrl, '隐私协议')">
<view class="nav-title">隐私协议</view>
<image src="/static/indicator-right.png" class="nav-icon"></image>
</view>
</view>
</view>
</template>
<script setup>
import { reactive } from 'vue'
import { http } from '@/utils/request'
import { appName, appVersion } from '@/config/config';
import { onMounted } from 'vue';
import { onLoad,onShow } from "@dcloudio/uni-app";
const settings = reactive({
serviceUrl: '',
privacyUrl: '',
})
const settingItemClick = (url,title) => {
uni.navigateTo({
url: '/pages/common/web?url=' + url + '&title=' + title
})
}
const navBack = ()=>{
uni.navigateBack();
}
onLoad((options)=>{
http.request({
url: '/app/settings/all',
method: 'GET'
}).then(resp => {
Object.assign(settings, resp.data);
})
})
</script>
<style lang="scss" scoped>
.page-container {
min-height: 500rpx;
background: linear-gradient(180deg, rgba(255, 255, 255, 0) 0%, rgba(255, 255, 255, 1) 100%), linear-gradient(90deg, rgba(194, 253, 255, 1) 0%, rgba(228, 252, 182, 1) 100%);
}
.nav-box {
margin-top: 120rpx;
background: rgba(250, 250, 250, 1);
margin-left: 32rpx;
margin-right: 32rpx;
.nav-item {
height: 108rpx;
padding-left: 30rpx;
padding-right: 30rpx;
display: flex;
align-items: center;
.nav-icon {
width: 48rpx;
height: 48rpx;
}
.nav-title {
flex: 1;
margin-left: 10rpx;
margin-right: 16rpx;
}
}
.nav-divider {
height: 1rpx;
border-bottom: 1rpx dashed rgba(241, 241, 241, 1);
}
}
</style>
|
2301_77169380/aionix-2
|
pages/my/about.vue
|
Vue
|
mit
| 2,856
|
<template>
<view>
<view style="display: flex; padding-top: 48rpx; padding-bottom: 48rpx; justify-content: center;">
<image src="/static/my/avatar-default.png" style="width: 168rpx; height: 168rpx; border-radius: 84rpx;"></image>
</view>
<view class="item-box" @tap="navToUpdateNickname">
<view class="item-title">昵称</view>
<view class="item-desc">{{user.name}}</view>
<image src="/static/indicator-right.png" style="width: 32rpx; height: 32rpx;" class="item-icon"></image>
</view>
<view class="item-box">
<view class="item-title">账号</view>
<view class="item-desc">{{user.username}}</view>
</view>
<view class="item-box">
<view class="item-title">User ID</view>
<view class="item-desc">{{user.inviteCode}}</view>
<image src="/static/copy.png" style="width: 48rpx; height: 48rpx;" class="item-icon" @tap="copyCode"></image>
</view>
<!-- <view class="item-box">
<view class="item-title">更多</view>
<image src="/static/indicator-right.png" style="width: 32rpx; height: 32rpx;" class="item-icon"></image>
</view> -->
<view class="item-box" style="justify-content: center; margin-top: 48rpx;"
@tap="confirmLogout">
<view style="color: rgba(243, 85, 112, 1);">退出登录</view>
</view>
</view>
</template>
<script setup>
import { reactive } from 'vue'
import { http } from '@/utils/request'
import { onMounted } from 'vue'
const user = reactive({
name: '',
username: '',
inviteCode: '',
})
const navToUpdateNickname = ()=>{
uni.navigateTo({
url: '/pages/my/update_nickname'
})
}
const getUserInfo = ()=>{
http.request({
url: '/app/user/login_user',
method: 'GET'
}).then(resp => {
Object.assign(user, resp.data);
})
}
const copyCode = ()=>{
uni.setClipboardData({
data: user.inviteCode,
success: ()=>{
uni.showToast({
title: '复制成功',
icon: 'none'
})
}
})
}
const confirmLogout = ()=>{
uni.showModal({
title: "确认",
content: "确认退出登录?",
success: (res)=> {
if (res.confirm) {
uni.setStorageSync('token', '');
uni.reLaunch({
url: '/pages/login'
})
}
}
})
}
onMounted(()=>{
getUserInfo();
uni.$on("app_update_user_info", ()=>{
getUserInfo();
})
})
</script>
<style lang="scss" scoped>
.item-box {
display: flex;
margin: 16rpx 32rpx 0 32rpx;
border-radius: 16rpx;
height: 100rpx;
padding: 0 16rpx;
flex-direction: row;
align-items: center;
background: rgba(250, 250, 250, 1);
.item-title {
font-size: 32rpx;
font-weight: 800;
flex: 1
}
.item-desc {
font-size: 28rpx;
color: rgba(153, 153, 153, 1);
}
.item-icon {
margin-left: 16rpx;
}
}
</style>
|
2301_77169380/aionix-2
|
pages/my/account.vue
|
Vue
|
mit
| 2,756
|
<template>
<view>
<view class="status_bar"></view>
<view style="display: flex; align-items: center; height: 88rpx; position: relative;">
<image src="/static/indicator-back.png" style="width: 48rpx; height: 48rpx; position: absolute; top: 20rpx; left: 32rpx;" @tap="navBack"></image>
<view style="font-size: 36rpx; font-weight: 600; flex: 1; text-align: center;">更改昵称</view>
<view style="position: absolute; right: 32rpx; top: 16rpx;" class="right-nav-button"
@tap="updateNickname">
<view class="content">保存</view>
</view>
</view>
<view style="margin: 48rpx 32rpx 0 32rpx; border-radius: 16rpx; background: rgba(250, 250, 250, 1); height: 100rpx;display: flex; align-items: center; padding-left: 32rpx; padding-right: 32rpx;" >
<input v-model="user.name" placeholder="请输入昵称" style="flex: 1;"/>
<image src="/static/clear.png" style="width: 40rpx; height: 40rpx;"></image>
</view>
</view>
</template>
<script setup>
import { reactive } from 'vue'
import { http } from '@/utils/request'
import { onMounted } from 'vue'
const user = reactive({
name: '',
})
const navBack = ()=>{
uni.navigateBack();
}
const getUserInfo = ()=>{
http.request({
url: '/app/user/login_user',
method: 'GET'
}).then(resp => {
Object.assign(user, resp.data);
})
}
const updateNickname = ()=>{
http.request({
url: '/app/user/updateName',
method: 'POST',
data: {
name: user.name
}
}).then(resp => {
uni.showToast({
title: "修改成功",
icon: 'none'
})
uni.$emit("app_update_user_info");
uni.navigateBack();
})
}
onMounted(()=>{
getUserInfo();
})
</script>
<style lang="scss" scoped>
.right-nav-button {
height: 56rpx;
border-radius: 28rpx;
width: 104rpx;
display: flex;
align-items: center;
justify-content: center;
background: linear-gradient(90deg, rgba(73, 246, 252, 1) 0%, rgba(197, 255, 89, 1) 100%);
.content {
font-size: 28rpx;
color: rgba(51, 51, 51, 1);
}
}
</style>
|
2301_77169380/aionix-2
|
pages/my/update_nickname.vue
|
Vue
|
mit
| 2,035
|
<template>
<view class="register-page flex flex-column">
<view class="register-page-header flex flex-column">
<input type="number" :maxlength="11" placeholder="请输入手机账号" class="register-input-phone" v-model="registerForm.account" />
<input type="password" placeholder="请输入密码" class="register-input-password" v-model="registerForm.password" />
<input type="text" placeholder="请输入邀请码(选填)" class="register-input-code" v-model="registerForm.inviteCode" />
<view class="tip-text flex flex-center">
<view>已有账号?去</view>
<navigator url="/pages/login" :render-link="false" hover-class="none" class="tip-text-login">登录</navigator>
</view>
<view class="register-button" @tap="register"><text>注 册</text></view>
</view>
</view>
</template>
<script setup>
import { reactive } from 'vue'
import { http } from '@/utils/request'
const registerForm = reactive({
account: '15616101240',
password: '123456',
inviteCode: ''
})
const register = () => {
if(!registerForm.account || !registerForm.password){
uni.showToast({
title: '请输入手机账号和密码',
icon: 'none'
})
return
}
http.request({
url: '/app/user/register',
method: 'POST',
data: {
account: registerForm.account,
password: registerForm.password,
inviteCode: registerForm.inviteCode
}
}).then(res => {
uni.showToast({
title: '注册成功',
icon: 'none'
})
uni.reLaunch({ url: '/pages/login' })
})
}
</script>
<style lang="scss" scoped>
.register-page{
height: 100%;
justify-content: center;
align-items: center;
padding: 0 90rpx;
}
.register-page-header{
font-size: 32rpx;
width: 100%;
.register-input-phone,
.register-input-password,
.register-input-code{
font-size: 26rpx;
height: 80rpx;
border: 1px solid #E5E5E5;
border-radius: 58rpx;
padding: 0 24rpx;
}
.register-input-password,
.register-input-code{
margin-top: 34rpx;
}
.tip-text{
font-size: 26rpx;
color: #999999;
margin-bottom: 120rpx;
margin-top: 18rpx;
text-align: center;
.tip-text-login{
color: #F35570;
padding: 10rpx;
}
}
.register-button{
padding: 24rpx 48rpx;
background: linear-gradient(90deg, #49f6fc 20%, #c5ff59 100%);
text-align: center;
border-radius: 58rpx;
font-size: 32rpx;
color: #333333;
font-weight: 500;
flex: 1;
}
}
</style>
|
2301_77169380/aionix-2
|
pages/register.vue
|
Vue
|
mit
| 2,504
|
<template>
<view class="container">
<!-- 自定义状态栏高度 -->
<view class="status_bar"></view>
<view class="flex-between flex header">
<view>
<view class="flex-center flex">
<uni-icons type="bars" size="24" color="#999" @tap="showLeftPopup"></uni-icons>
<view class="flex-column-center flex left" @tap="showPopup">
<image :src="modelList[modeIndex]?.icon" mode="widthFix" class="model-logo"></image>
<text class="model-name">{{ modelList[modeIndex]?.name || 'Model Name' }}</text>
<uni-icons type="right" size="12" color="#333"></uni-icons>
</view>
</view>
</view>
<view class="right flex flex-center">
<view class="sale">Sale</view>
<uni-icons type="chatboxes-filled" size="24" color="#E3E3E3"></uni-icons>
</view>
</view>
<view class="content">
<view class="flex-center flex title-box flex-column" v-if="messageList.length === 0">
<view class="title-text">"HI,how can i help you? "</view>
<image src="@/static/title-logo.png" mode="widthFix" class="title-logo"></image>
</view>
<view class="message-list" v-else>
<scroll-view scroll-y class="message-list-scroll">
<view>1212</view>
</scroll-view>
</view>
</view>
<view class="key-box">
<view class=" flex key-box-input">
<image v-if="!isShowKeyBox" src="@/static/add.png" @tap="()=>{isShowKeyBox = true}" mode="aspectFit"
class="add-icon"></image>
<image v-else src="@/static/colse.png" @tap="()=>{isShowKeyBox = false}" mode="aspectFit"
class="add-icon"></image>
<textarea :cursor-spacing='17' confirm-type='send' @confirm="sendMessage" auto-height v-model="textValue" placeholder="请问我任何问题..." class="textarea"></textarea>
</view>
<view class="flex-between flex key-box-btn" v-if="isShowKeyBox">
<view class="li flex flex-column">
<image src="@/static/xiangce.png" mode="aspectFit" class="add-icon"></image>
<text>相册</text>
</view>
<view class="li flex flex-column">
<image src="@/static/xiangji.png" mode="aspectFit" class="add-icon"></image>
<text>相机</text>
</view>
<view class="li flex flex-column">
<image src="@/static/file.png" mode="aspectFit" class="add-icon"></image>
<text>文件</text>
</view>
<view class="li flex flex-column">
<image src="@/static/tips.png" mode="aspectFit" class="add-icon"></image>
<text>提示词</text>
</view>
</view>
</view>
<!-- 添加弹窗 -->
<uni-popup ref="popup" type="top">
<view class="popup-content">
<view class="status_bar"></view>
<view class="flex flex-between flex-wrap">
<view :class="['flex flex-column-popup model-item', modeIndex === index ? 'active' : '']"
@tap="()=>{modeIndex = index;popup.close()}" v-for="(item, index) in modelList" :key="item.id">
<view class="li">
<view class="flex flex-start-center">
<image :src="item.icon" mode="widthFix" class="model-logo"></image>
<text class="model-name">{{item.name}}</text>
</view>
<view class="model-desc">
<text class="model-desc-text">{{ item.description }}</text>
</view>
<view class="flex flex-end-center model-consume">
<text class="consume">{{ `消耗 ${item.diamondFee || item.starFee} ` }}</text>
<image v-if="modeIndex === index" src="@/static/diamond-1.png" mode="aspectFit"
class="diamond"></image>
<image v-else src="@/static/diamond.png" mode="aspectFit" class="diamond"></image>
</view>
</view>
</view>
</view>
</view>
</uni-popup>
<!-- 添加左侧菜单弹窗 -->
<uni-popup ref="leftPopup" type="left" background-color="#fff">
<view class="left-popup-content">
<view class="status_bar"></view>
<view class="history">历史</view>
<scroll-view scroll-y class="menu-scroll">
<view class="menu-list">
<view class="menu-item">菜单项 1</view>
<view class="menu-item">菜单项 2</view>
<view class="menu-item">菜单项 3</view>
<view class="menu-item">菜单项 4</view>
<view class="menu-item">菜单项 5</view>
<view class="menu-item">菜单项 6</view>
<view class="menu-item">菜单项 7</view>
<view class="menu-item">菜单项 8</view>
</view>
</scroll-view>
</view>
</uni-popup>
<text :prop="options" :change:prop="renderScript.onChange" v-show="false"></text>
</view>
</template>
<script>
import { http } from '@/utils/request'
import { baseURL } from "@/config/config.js";
export default {
data() {
return {
modelName: 'Model Name',
popup: null,
modelList: [],
modeIndex: 5,
leftPopup: null,
isShowKeyBox: false,
messageList: [{
a: 1
}],
textValue: '',
options: {
baseURL: baseURL,
token: uni.getStorageSync('token'),
body: {
sessionId: '',
agentId: '',
modelId: '',
message: ''
}
}
}
},
onLoad() {
http.request({
url: '/app/model/list',
method: 'GET',
data: {
type: 'TEXT'
}
}).then(res => {
this.modelList = res.data;
})
},
methods: {
showPopup() {
this.$refs.popup.open();
},
showLeftPopup() {
this.$refs.leftPopup.open();
},
sendMessage(e) {
if(!this.textValue){
return uni.showToast({
title: '请输入内容',
icon: 'none'
})
};
this.options.body.message = this.textValue;
this.options.body.modelId = this.modelList[this.modeIndex]?.id;
},
getSseData(data) {
if (data != "[DONE]") {
const _data = JSON.parse(data);
if (_data.content) {
console.log(_data.content,_data.sessionId)
//listMessage.value[listMessage.value.length - 1]['content'] += _data.content;
}
}
},
sseDataEnd() {
console.log('sseDataEnd');
},
onopenSse() {
console.log('onopenSse');
}
}
}
</script>
<script module="renderScript" lang="renderjs">
import {
fetchEventSource
} from '@microsoft/fetch-event-source';
export default {
methods: {
onChange(newValue, oldValue, ownerInstance, instance) {
if(!newValue.body.message) return;
fetchEventSource(`${newValue.baseURL}/app/chat/completion`, {
method: 'POST',
headers: {
'Content-Type': 'application/json',
"Authorization": `Bearer ${newValue.token}`
},
body: JSON.stringify(newValue.body),
onmessage(ev) {
ownerInstance.callMethod('getSseData', ev.data)
},
onclose() {
ownerInstance.callMethod('sseDataEnd')
},
onerror(err) {
console.log('发生错误');
console.log(err)
},
async onopen(response) {
ownerInstance.callMethod('onopenSse')
},
});
}
}
}
</script>
<style lang="scss" scoped>
.message-list {
height: 100%;
.message-list-scroll {
background-color: #911c1c;
height: 100%;
}
}
.key-box-btn {
margin-top: 32rpx;
.li {
width: 146rpx;
height: 146rpx;
border-radius: 16rpx;
background: #f5f5f5;
font-size: 24rpx;
justify-content: center;
align-items: center;
image {
margin-bottom: 6rpx;
width: 48rpx;
height: 48rpx;
}
}
}
.key-box-input {
padding: 24rpx 18rpx;
font-size: 28rpx;
border-radius: 16rpx;
background: #f5f5f5;
align-items: center;
.add-icon {
width: 48rpx;
height: 48rpx;
flex-shrink: 0;
margin-right: 16rpx;
}
.textarea {
flex: 1;
font-size: 28rpx;
line-height: 40rpx;
}
}
.container {
display: flex;
flex-direction: column;
height: 100vh;
padding: 0 32rpx;
}
.content {
flex: 1;
padding: 32rpx 0;
}
.header {
padding-top: 32rpx;
}
.key-box {
padding-bottom: 32rpx;
}
.header,
.key-box,
.status_bar {
flex-shrink: 0;
}
.model-item {
margin-top: 14rpx;
}
.history {
font-size: 48rpx;
font-weight: 600;
padding: 20rpx 32rpx;
flex-shrink: 0;
}
.flex-column-popup {
&.active {
background: #000000;
.model-name,
.consume {
color: #fff;
}
.model-desc-text {
color: #888888;
}
}
border-radius: 16rpx;
background: #FAFAFAFF;
padding: 16rpx 0;
font-size: 24rpx;
width: 49%;
.li {
width: 100%;
.diamond {
width: 20rpx;
height: 26rpx;
}
.consume {
font-size: 24rpx;
}
.model-desc {
margin-top: 16rpx;
margin-bottom: 12rpx;
.model-desc-text {
line-height: 32rpx;
color: #888888;
}
}
.model-logo {
width: 48rpx;
height: 48rpx;
border-radius: 50%;
margin-right: 12rpx;
}
margin: 0 16rpx;
.model-name {
font-size: 28rpx;
font-weight: 500;
}
}
}
.model-logo {
width: 48rpx;
height: 48rpx;
border-radius: 50%;
margin-right: 12rpx;
}
.model-name {
font-size: 24rpx;
color: #333;
}
.left {
padding: 4rpx 16rpx 4rpx 4rpx;
margin-left: 16rpx;
border-style: solid;
border-width: 4rpx;
border-color: #49F6FC;
//border-image: linear-gradient(270deg, #C5FF59, #49F6FC) 1;
border-radius: 246rpx;
}
.sale {
margin-right: 36rpx;
padding: 10rpx 28rpx;
font-size: 28rpx;
background: linear-gradient(90deg, #49F6FC 0%, #C5FF59 100%);
border-radius: 246rpx;
}
.title-box {
margin-top: 140rpx;
.title-text {
font-size: 48rpx;
font-weight: 600;
}
.title-logo {
margin-top: 32rpx;
width: 191rpx;
height: 20.63rpx;
}
}
.popup-content {
padding: 20rpx;
background-color: #fff;
}
.left-popup-content {
width: 70vw;
height: 100vh;
display: flex;
flex-direction: column;
.menu-scroll {
flex: 1;
height: 0;
}
.menu-list {
padding: 0 32rpx;
.menu-item {
//padding: 30rpx 20rpx;
font-size: 28rpx;
border-bottom: 1rpx solid #eee;
&:active {
background-color: #f5f5f5;
}
}
}
}
</style>
|
2301_77169380/aionix-2
|
pages/tabs/chat.vue
|
Vue
|
mit
| 9,979
|
<template>
<view>
</view>
</template>
<script setup>
</script>
<style>
</style>
|
2301_77169380/aionix-2
|
pages/tabs/community.vue
|
Vue
|
mit
| 98
|
<template>
<view class="mine-page">
<view class="page-title">个人中心</view>
<view class="box main-box">
<view class="head">
<view class="vip">{{user.userType == 2 ? "全端版" : (user.userType == 1 ? "口袋版" : "基础版")}}</view>
<view class="tips">每日重置</view>
</view>
<view class="grade-box">
<view class="grade-item">
<view class="grade-number">{{user.balanceDiamond}}</view>
<view class="grade-name">
<view class="grade-name-box">
<image src="/static/diamond.png" style="width: 20rpx; height: 26rpx;"></image>
<view style="font-size: 24rpx; margin-left: 20rpx;">基础积分</view>
</view>
</view>
</view>
<view class="grade-divider"></view>
<view class="grade-item">
<view class="grade-number">{{user.balanceStar}}</view>
<view class="grade-name">
<view class="grade-name-box">
<image src="/static/star.png" style="width: 20rpx; height: 26rpx;"></image>
<view style="font-size: 24rpx; margin-left: 20rpx;">高级积分</view>
</view>
</view>
</view>
</view>
</view>
<view class="share-box">
<image src="/static/gift.png" style="width: 30rpx; height: 32rpx;"></image>
<view class="text">积分不足?升级获得更多积分</view>
</view>
<view class="box nav-box" v-for="(box,i) in navItems" :key="i">
<view v-for="(item,j) in box" :key="j">
<view class="nav-item" @tap="navItemClick(item)">
<image :src="item.icon" class="nav-icon"></image>
<view class="nav-title">{{item.title}}</view>
<image src="/static/indicator-right.png" style="width: 32rpx; height: 32rpx;"></image>
</view>
<view class="nav-divider" v-if="j < box.length -1"></view>
</view>
</view>
</view>
</template>
<script setup>
import { reactive } from 'vue'
import { http } from '@/utils/request'
import { onMounted } from 'vue'
import { onLoad,onShow } from "@dcloudio/uni-app";
const navItems = reactive([
[
{icon: '/static/my/account.png', title: "账户", action: '/pages/my/account'},
{icon: '/static/my/assist.png', title: "智能助手", action: ''},
],
[
{icon: '/static/my/chat.png', title: "聊天设置", action: ''},
],
[
{icon: '/static/my/invite.png', title: "邀请", action: '/pages/common/invite'},
// {icon: '/static/my/share.png', title: "分享", action: ''},
{icon: '/static/my/about.png', title: "关于我们", action: '/pages/my/about'},
{icon: '/static/my/contact.png', title: "联系我们", action: '/pages/common/feedback'},
],
])
const navItemClick = (item)=>{
if (item.action) {
uni.navigateTo({
url: item.action
})
}
}
const user = reactive({
type: 0,
balanceDiamond: 0,
balanceStar: 0,
})
const getUserInfo = ()=>{
http.request({
url: '/app/user/login_user',
method: 'GET'
}).then(resp => {
Object.assign(user, resp.data);
})
}
onShow(()=>{
getUserInfo();
})
</script>
<style lang="scss" scoped>
.mine-page {
position: relative;
min-height: 500rpx;
background: linear-gradient(180deg, rgba(255, 255, 255, 0) 0%, rgba(255, 255, 255, 1) 100%), linear-gradient(90deg, rgba(228, 252, 182, 1) 100%, rgba(194, 253, 255, 1) 0%);
padding-top: 88rpx;
}
.page-title {
font-size: 48rpx;
padding-left: 32rpx;
font-weight: 500;
}
.box {
border-radius: 16rpx;
margin-left: 32rpx;
margin-right: 32rpx;
}
.main-box {
margin-top: 48rpx;
background: rgba(255, 255, 255, 1);
box-shadow: 5px 5px 10px rgba(0, 0, 0, 0.1);
.head {
height: 112rpx;
display: flex;
padding-left: 32rpx;
padding-right: 32rpx;
flex-direction: row;
justify-content: space-between;
align-items: center;
border-bottom: 1rpx dashed rgba(245, 245, 245, 1);
.vip {
font-size: 36rpx;
font-weight: 600;
color: rgba(0, 0, 0, 1);
}
.tips {
font-size: 24rpx;
color: rgba(153, 153, 153, 1);
}
}
.grade-box {
display: flex;
flex-direction: row;
align-items: center;
.grade-item {
flex: 1;
.grade-number {
text-align: center;
font-size: 48rpx;
color: rgba(51, 51, 51, 1);
font-weight: 900;
}
.grade-name {
margin-top: 16rpx;
display: flex;
justify-content: center;
.grade-name-box {
display: flex;
flex-direction: row;
align-items: center;
padding-left: 16rpx;
padding-right: 16rpx;
padding-top: 6rpx;
padding-bottom: 6rpx;
background: rgba(250, 250, 250, 1);
border-radius: 24rpx;
}
}
}
.grade-divider {
width: 1rpx;
border-right: 1rpx dashed rgba(245, 245, 245, 1);
height: 182rpx;
}
}
}
.share-box {
background: rgba(0, 0, 0, 1);
border-radius: 16rpx;
margin: 32rpx 32rpx 0 32rpx;
display: flex;
align-items: center;
justify-content: center;
height: 80rpx;
flex-direction: row;
.text {
color: rgba(197, 255, 89, 1);
font-size: 32rpx;
margin-left: 16rpx;
}
}
.nav-box {
margin-top: 32rpx;
background: rgba(250, 250, 250, 1);
.nav-item {
height: 108rpx;
padding-left: 30rpx;
padding-right: 30rpx;
display: flex;
align-items: center;
.nav-icon {
width: 48rpx;
height: 48rpx;
}
.nav-title {
flex: 1;
margin-left: 10rpx;
margin-right: 16rpx;
}
}
.nav-divider {
height: 1rpx;
border-bottom: 1rpx dashed rgba(241, 241, 241, 1);
}
}
</style>
|
2301_77169380/aionix-2
|
pages/tabs/my.vue
|
Vue
|
mit
| 5,526
|
<template>
<view>
</view>
</template>
<script setup>
</script>
<style>
</style>
|
2301_77169380/aionix-2
|
pages/tabs/sessionList.vue
|
Vue
|
mit
| 98
|
<template>
<view></view>
</template>
<script setup>
import { reactive } from 'vue'
import { http } from '@/utils/request'
</script>
<style lang="scss" scoped>
</style>
|
2301_77169380/aionix-2
|
pages/template.vue
|
Vue
|
mit
| 172
|
@import '@/uni_modules/uni-scss/variables.scss';
|
2301_77169380/aionix-2
|
uni.scss
|
SCSS
|
mit
| 49
|
<template>
<view class="uni-badge--x">
<slot />
<text v-if="text" :class="classNames" :style="[positionStyle, customStyle, dotStyle]"
class="uni-badge" @click="onClick()">{{displayValue}}</text>
</view>
</template>
<script>
/**
* Badge 数字角标
* @description 数字角标一般和其它控件(列表、9宫格等)配合使用,用于进行数量提示,默认为实心灰色背景
* @tutorial https://ext.dcloud.net.cn/plugin?id=21
* @property {String} text 角标内容
* @property {String} size = [normal|small] 角标内容
* @property {String} type = [info|primary|success|warning|error] 颜色类型
* @value info 灰色
* @value primary 蓝色
* @value success 绿色
* @value warning 黄色
* @value error 红色
* @property {String} inverted = [true|false] 是否无需背景颜色
* @property {Number} maxNum 展示封顶的数字值,超过 99 显示 99+
* @property {String} absolute = [rightTop|rightBottom|leftBottom|leftTop] 开启绝对定位, 角标将定位到其包裹的标签的四角上
* @value rightTop 右上
* @value rightBottom 右下
* @value leftTop 左上
* @value leftBottom 左下
* @property {Array[number]} offset 距定位角中心点的偏移量,只有存在 absolute 属性时有效,例如:[-10, -10] 表示向外偏移 10px,[10, 10] 表示向 absolute 指定的内偏移 10px
* @property {String} isDot = [true|false] 是否显示为一个小点
* @event {Function} click 点击 Badge 触发事件
* @example <uni-badge text="1"></uni-badge>
*/
export default {
name: 'UniBadge',
emits: ['click'],
props: {
type: {
type: String,
default: 'error'
},
inverted: {
type: Boolean,
default: false
},
isDot: {
type: Boolean,
default: false
},
maxNum: {
type: Number,
default: 99
},
absolute: {
type: String,
default: ''
},
offset: {
type: Array,
default () {
return [0, 0]
}
},
text: {
type: [String, Number],
default: ''
},
size: {
type: String,
default: 'small'
},
customStyle: {
type: Object,
default () {
return {}
}
}
},
data() {
return {};
},
computed: {
width() {
return String(this.text).length * 8 + 12
},
classNames() {
const {
inverted,
type,
size,
absolute
} = this
return [
inverted ? 'uni-badge--' + type + '-inverted' : '',
'uni-badge--' + type,
'uni-badge--' + size,
absolute ? 'uni-badge--absolute' : ''
].join(' ')
},
positionStyle() {
if (!this.absolute) return {}
let w = this.width / 2,
h = 10
if (this.isDot) {
w = 5
h = 5
}
const x = `${- w + this.offset[0]}px`
const y = `${- h + this.offset[1]}px`
const whiteList = {
rightTop: {
right: x,
top: y
},
rightBottom: {
right: x,
bottom: y
},
leftBottom: {
left: x,
bottom: y
},
leftTop: {
left: x,
top: y
}
}
const match = whiteList[this.absolute]
return match ? match : whiteList['rightTop']
},
dotStyle() {
if (!this.isDot) return {}
return {
width: '10px',
minWidth: '0',
height: '10px',
padding: '0',
borderRadius: '10px'
}
},
displayValue() {
const {
isDot,
text,
maxNum
} = this
return isDot ? '' : (Number(text) > maxNum ? `${maxNum}+` : text)
}
},
methods: {
onClick() {
this.$emit('click');
}
}
};
</script>
<style lang="scss" >
$uni-primary: #2979ff !default;
$uni-success: #4cd964 !default;
$uni-warning: #f0ad4e !default;
$uni-error: #dd524d !default;
$uni-info: #909399 !default;
$bage-size: 12px;
$bage-small: scale(0.8);
.uni-badge--x {
/* #ifdef APP-NVUE */
// align-self: flex-start;
/* #endif */
/* #ifndef APP-NVUE */
display: inline-block;
/* #endif */
position: relative;
}
.uni-badge--absolute {
position: absolute;
}
.uni-badge--small {
transform: $bage-small;
transform-origin: center center;
}
.uni-badge {
/* #ifndef APP-NVUE */
display: flex;
overflow: hidden;
box-sizing: border-box;
font-feature-settings: "tnum";
min-width: 20px;
/* #endif */
justify-content: center;
flex-direction: row;
height: 20px;
padding: 0 4px;
line-height: 18px;
color: #fff;
border-radius: 100px;
background-color: $uni-info;
background-color: transparent;
border: 1px solid #fff;
text-align: center;
font-family: 'Helvetica Neue', Helvetica, sans-serif;
font-size: $bage-size;
/* #ifdef H5 */
z-index: 999;
cursor: pointer;
/* #endif */
&--info {
color: #fff;
background-color: $uni-info;
}
&--primary {
background-color: $uni-primary;
}
&--success {
background-color: $uni-success;
}
&--warning {
background-color: $uni-warning;
}
&--error {
background-color: $uni-error;
}
&--inverted {
padding: 0 5px 0 0;
color: $uni-info;
}
&--info-inverted {
color: $uni-info;
background-color: transparent;
}
&--primary-inverted {
color: $uni-primary;
background-color: transparent;
}
&--success-inverted {
color: $uni-success;
background-color: transparent;
}
&--warning-inverted {
color: $uni-warning;
background-color: transparent;
}
&--error-inverted {
color: $uni-error;
background-color: transparent;
}
}
</style>
|
2301_77169380/aionix-2
|
uni_modules/uni-badge/components/uni-badge/uni-badge.vue
|
Vue
|
mit
| 5,483
|
<template>
<view class="uni-breadcrumb">
<slot />
</view>
</template>
<script>
/**
* Breadcrumb 面包屑导航父组件
* @description 显示当前页面的路径,快速返回之前的任意页面
* @tutorial https://ext.dcloud.net.cn/plugin?id=xxx
* @property {String} separator 分隔符,默认为斜杠'/'
* @property {String} separatorClass 图标分隔符 class
*/
export default {
options: {
// #ifdef MP-TOUTIAO
virtualHost: false,
// #endif
// #ifndef MP-TOUTIAO
virtualHost: true
// #endif
},
props: {
separator: {
type: String,
default: '/'
},
separatorClass: {
type: String,
default: ''
}
},
provide() {
return {
uniBreadcrumb: this
}
}
}
</script>
<style lang="scss">
.uni-breadcrumb {
display: flex;
}
</style>
|
2301_77169380/aionix-2
|
uni_modules/uni-breadcrumb/components/uni-breadcrumb/uni-breadcrumb.vue
|
Vue
|
mit
| 822
|
<template>
<view class="uni-breadcrumb-item">
<view :class="{
'uni-breadcrumb-item--slot': true,
'uni-breadcrumb-item--slot-link': to && currentPage !== to
}" @click="navTo">
<slot />
</view>
<i v-if="separatorClass" class="uni-breadcrumb-item--separator" :class="separatorClass" />
<text v-else class="uni-breadcrumb-item--separator">{{ separator }}</text>
</view>
</template>
<script>
/**
* BreadcrumbItem 面包屑导航子组件
* @property {String/Object} to 路由跳转页面路径/对象
* @property {Boolean} replace 在使用 to 进行路由跳转时,启用 replace 将不会向 history 添加新记录(仅 h5 支持)
*/
export default {
data() {
return {
currentPage: ""
}
},
options: {
// #ifdef MP-TOUTIAO
virtualHost: false,
// #endif
// #ifndef MP-TOUTIAO
virtualHost: true
// #endif
},
props: {
to: {
type: String,
default: ''
},
replace:{
type: Boolean,
default: false
}
},
inject: {
uniBreadcrumb: {
from: "uniBreadcrumb",
default: null
}
},
created(){
const pages = getCurrentPages()
const page = pages[pages.length-1]
if(page){
this.currentPage = `/${page.route}`
}
},
computed: {
separator() {
return this.uniBreadcrumb.separator
},
separatorClass() {
return this.uniBreadcrumb.separatorClass
}
},
methods: {
navTo() {
const { to } = this
if (!to || this.currentPage === to){
return
}
if(this.replace){
uni.redirectTo({
url:to
})
}else{
uni.navigateTo({
url:to
})
}
}
}
}
</script>
<style lang="scss">
$uni-primary: #2979ff !default;
$uni-base-color: #6a6a6a !default;
$uni-main-color: #3a3a3a !default;
.uni-breadcrumb-item {
display: flex;
align-items: center;
white-space: nowrap;
font-size: 14px;
&--slot {
color: $uni-base-color;
padding: 0 10px;
&-link {
color: $uni-main-color;
font-weight: bold;
/* #ifndef APP-NVUE */
cursor: pointer;
/* #endif */
&:hover {
color: $uni-primary;
}
}
}
&--separator {
font-size: 12px;
color: $uni-base-color;
}
&:first-child &--slot {
padding-left: 0;
}
&:last-child &--separator {
display: none;
}
}
</style>
|
2301_77169380/aionix-2
|
uni_modules/uni-breadcrumb/components/uni-breadcrumb-item/uni-breadcrumb-item.vue
|
Vue
|
mit
| 2,305
|
/**
* @1900-2100区间内的公历、农历互转
* @charset UTF-8
* @github https://github.com/jjonline/calendar.js
* @Author Jea杨(JJonline@JJonline.Cn)
* @Time 2014-7-21
* @Time 2016-8-13 Fixed 2033hex、Attribution Annals
* @Time 2016-9-25 Fixed lunar LeapMonth Param Bug
* @Time 2017-7-24 Fixed use getTerm Func Param Error.use solar year,NOT lunar year
* @Version 1.0.3
* @公历转农历:calendar.solar2lunar(1987,11,01); //[you can ignore params of prefix 0]
* @农历转公历:calendar.lunar2solar(1987,09,10); //[you can ignore params of prefix 0]
*/
/* eslint-disable */
var calendar = {
/**
* 农历1900-2100的润大小信息表
* @Array Of Property
* @return Hex
*/
lunarInfo: [0x04bd8, 0x04ae0, 0x0a570, 0x054d5, 0x0d260, 0x0d950, 0x16554, 0x056a0, 0x09ad0, 0x055d2, // 1900-1909
0x04ae0, 0x0a5b6, 0x0a4d0, 0x0d250, 0x1d255, 0x0b540, 0x0d6a0, 0x0ada2, 0x095b0, 0x14977, // 1910-1919
0x04970, 0x0a4b0, 0x0b4b5, 0x06a50, 0x06d40, 0x1ab54, 0x02b60, 0x09570, 0x052f2, 0x04970, // 1920-1929
0x06566, 0x0d4a0, 0x0ea50, 0x06e95, 0x05ad0, 0x02b60, 0x186e3, 0x092e0, 0x1c8d7, 0x0c950, // 1930-1939
0x0d4a0, 0x1d8a6, 0x0b550, 0x056a0, 0x1a5b4, 0x025d0, 0x092d0, 0x0d2b2, 0x0a950, 0x0b557, // 1940-1949
0x06ca0, 0x0b550, 0x15355, 0x04da0, 0x0a5b0, 0x14573, 0x052b0, 0x0a9a8, 0x0e950, 0x06aa0, // 1950-1959
0x0aea6, 0x0ab50, 0x04b60, 0x0aae4, 0x0a570, 0x05260, 0x0f263, 0x0d950, 0x05b57, 0x056a0, // 1960-1969
0x096d0, 0x04dd5, 0x04ad0, 0x0a4d0, 0x0d4d4, 0x0d250, 0x0d558, 0x0b540, 0x0b6a0, 0x195a6, // 1970-1979
0x095b0, 0x049b0, 0x0a974, 0x0a4b0, 0x0b27a, 0x06a50, 0x06d40, 0x0af46, 0x0ab60, 0x09570, // 1980-1989
0x04af5, 0x04970, 0x064b0, 0x074a3, 0x0ea50, 0x06b58, 0x05ac0, 0x0ab60, 0x096d5, 0x092e0, // 1990-1999
0x0c960, 0x0d954, 0x0d4a0, 0x0da50, 0x07552, 0x056a0, 0x0abb7, 0x025d0, 0x092d0, 0x0cab5, // 2000-2009
0x0a950, 0x0b4a0, 0x0baa4, 0x0ad50, 0x055d9, 0x04ba0, 0x0a5b0, 0x15176, 0x052b0, 0x0a930, // 2010-2019
0x07954, 0x06aa0, 0x0ad50, 0x05b52, 0x04b60, 0x0a6e6, 0x0a4e0, 0x0d260, 0x0ea65, 0x0d530, // 2020-2029
0x05aa0, 0x076a3, 0x096d0, 0x04afb, 0x04ad0, 0x0a4d0, 0x1d0b6, 0x0d250, 0x0d520, 0x0dd45, // 2030-2039
0x0b5a0, 0x056d0, 0x055b2, 0x049b0, 0x0a577, 0x0a4b0, 0x0aa50, 0x1b255, 0x06d20, 0x0ada0, // 2040-2049
/** Add By JJonline@JJonline.Cn**/
0x14b63, 0x09370, 0x049f8, 0x04970, 0x064b0, 0x168a6, 0x0ea50, 0x06b20, 0x1a6c4, 0x0aae0, // 2050-2059
0x0a2e0, 0x0d2e3, 0x0c960, 0x0d557, 0x0d4a0, 0x0da50, 0x05d55, 0x056a0, 0x0a6d0, 0x055d4, // 2060-2069
0x052d0, 0x0a9b8, 0x0a950, 0x0b4a0, 0x0b6a6, 0x0ad50, 0x055a0, 0x0aba4, 0x0a5b0, 0x052b0, // 2070-2079
0x0b273, 0x06930, 0x07337, 0x06aa0, 0x0ad50, 0x14b55, 0x04b60, 0x0a570, 0x054e4, 0x0d160, // 2080-2089
0x0e968, 0x0d520, 0x0daa0, 0x16aa6, 0x056d0, 0x04ae0, 0x0a9d4, 0x0a2d0, 0x0d150, 0x0f252, // 2090-2099
0x0d520], // 2100
/**
* 公历每个月份的天数普通表
* @Array Of Property
* @return Number
*/
solarMonth: [31, 28, 31, 30, 31, 30, 31, 31, 30, 31, 30, 31],
/**
* 天干地支之天干速查表
* @Array Of Property trans["甲","乙","丙","丁","戊","己","庚","辛","壬","癸"]
* @return Cn string
*/
Gan: ['\u7532', '\u4e59', '\u4e19', '\u4e01', '\u620a', '\u5df1', '\u5e9a', '\u8f9b', '\u58ec', '\u7678'],
/**
* 天干地支之地支速查表
* @Array Of Property
* @trans["子","丑","寅","卯","辰","巳","午","未","申","酉","戌","亥"]
* @return Cn string
*/
Zhi: ['\u5b50', '\u4e11', '\u5bc5', '\u536f', '\u8fb0', '\u5df3', '\u5348', '\u672a', '\u7533', '\u9149', '\u620c', '\u4ea5'],
/**
* 天干地支之地支速查表<=>生肖
* @Array Of Property
* @trans["鼠","牛","虎","兔","龙","蛇","马","羊","猴","鸡","狗","猪"]
* @return Cn string
*/
Animals: ['\u9f20', '\u725b', '\u864e', '\u5154', '\u9f99', '\u86c7', '\u9a6c', '\u7f8a', '\u7334', '\u9e21', '\u72d7', '\u732a'],
/**
* 24节气速查表
* @Array Of Property
* @trans["小寒","大寒","立春","雨水","惊蛰","春分","清明","谷雨","立夏","小满","芒种","夏至","小暑","大暑","立秋","处暑","白露","秋分","寒露","霜降","立冬","小雪","大雪","冬至"]
* @return Cn string
*/
solarTerm: ['\u5c0f\u5bd2', '\u5927\u5bd2', '\u7acb\u6625', '\u96e8\u6c34', '\u60ca\u86f0', '\u6625\u5206', '\u6e05\u660e', '\u8c37\u96e8', '\u7acb\u590f', '\u5c0f\u6ee1', '\u8292\u79cd', '\u590f\u81f3', '\u5c0f\u6691', '\u5927\u6691', '\u7acb\u79cb', '\u5904\u6691', '\u767d\u9732', '\u79cb\u5206', '\u5bd2\u9732', '\u971c\u964d', '\u7acb\u51ac', '\u5c0f\u96ea', '\u5927\u96ea', '\u51ac\u81f3'],
/**
* 1900-2100各年的24节气日期速查表
* @Array Of Property
* @return 0x string For splice
*/
sTermInfo: ['9778397bd097c36b0b6fc9274c91aa', '97b6b97bd19801ec9210c965cc920e', '97bcf97c3598082c95f8c965cc920f',
'97bd0b06bdb0722c965ce1cfcc920f', 'b027097bd097c36b0b6fc9274c91aa', '97b6b97bd19801ec9210c965cc920e',
'97bcf97c359801ec95f8c965cc920f', '97bd0b06bdb0722c965ce1cfcc920f', 'b027097bd097c36b0b6fc9274c91aa',
'97b6b97bd19801ec9210c965cc920e', '97bcf97c359801ec95f8c965cc920f', '97bd0b06bdb0722c965ce1cfcc920f',
'b027097bd097c36b0b6fc9274c91aa', '9778397bd19801ec9210c965cc920e', '97b6b97bd19801ec95f8c965cc920f',
'97bd09801d98082c95f8e1cfcc920f', '97bd097bd097c36b0b6fc9210c8dc2', '9778397bd197c36c9210c9274c91aa',
'97b6b97bd19801ec95f8c965cc920e', '97bd09801d98082c95f8e1cfcc920f', '97bd097bd097c36b0b6fc9210c8dc2',
'9778397bd097c36c9210c9274c91aa', '97b6b97bd19801ec95f8c965cc920e', '97bcf97c3598082c95f8e1cfcc920f',
'97bd097bd097c36b0b6fc9210c8dc2', '9778397bd097c36c9210c9274c91aa', '97b6b97bd19801ec9210c965cc920e',
'97bcf97c3598082c95f8c965cc920f', '97bd097bd097c35b0b6fc920fb0722', '9778397bd097c36b0b6fc9274c91aa',
'97b6b97bd19801ec9210c965cc920e', '97bcf97c3598082c95f8c965cc920f', '97bd097bd097c35b0b6fc920fb0722',
'9778397bd097c36b0b6fc9274c91aa', '97b6b97bd19801ec9210c965cc920e', '97bcf97c359801ec95f8c965cc920f',
'97bd097bd097c35b0b6fc920fb0722', '9778397bd097c36b0b6fc9274c91aa', '97b6b97bd19801ec9210c965cc920e',
'97bcf97c359801ec95f8c965cc920f', '97bd097bd097c35b0b6fc920fb0722', '9778397bd097c36b0b6fc9274c91aa',
'97b6b97bd19801ec9210c965cc920e', '97bcf97c359801ec95f8c965cc920f', '97bd097bd07f595b0b6fc920fb0722',
'9778397bd097c36b0b6fc9210c8dc2', '9778397bd19801ec9210c9274c920e', '97b6b97bd19801ec95f8c965cc920f',
'97bd07f5307f595b0b0bc920fb0722', '7f0e397bd097c36b0b6fc9210c8dc2', '9778397bd097c36c9210c9274c920e',
'97b6b97bd19801ec95f8c965cc920f', '97bd07f5307f595b0b0bc920fb0722', '7f0e397bd097c36b0b6fc9210c8dc2',
'9778397bd097c36c9210c9274c91aa', '97b6b97bd19801ec9210c965cc920e', '97bd07f1487f595b0b0bc920fb0722',
'7f0e397bd097c36b0b6fc9210c8dc2', '9778397bd097c36b0b6fc9274c91aa', '97b6b97bd19801ec9210c965cc920e',
'97bcf7f1487f595b0b0bb0b6fb0722', '7f0e397bd097c35b0b6fc920fb0722', '9778397bd097c36b0b6fc9274c91aa',
'97b6b97bd19801ec9210c965cc920e', '97bcf7f1487f595b0b0bb0b6fb0722', '7f0e397bd097c35b0b6fc920fb0722',
'9778397bd097c36b0b6fc9274c91aa', '97b6b97bd19801ec9210c965cc920e', '97bcf7f1487f531b0b0bb0b6fb0722',
'7f0e397bd097c35b0b6fc920fb0722', '9778397bd097c36b0b6fc9274c91aa', '97b6b97bd19801ec9210c965cc920e',
'97bcf7f1487f531b0b0bb0b6fb0722', '7f0e397bd07f595b0b6fc920fb0722', '9778397bd097c36b0b6fc9274c91aa',
'97b6b97bd19801ec9210c9274c920e', '97bcf7f0e47f531b0b0bb0b6fb0722', '7f0e397bd07f595b0b0bc920fb0722',
'9778397bd097c36b0b6fc9210c91aa', '97b6b97bd197c36c9210c9274c920e', '97bcf7f0e47f531b0b0bb0b6fb0722',
'7f0e397bd07f595b0b0bc920fb0722', '9778397bd097c36b0b6fc9210c8dc2', '9778397bd097c36c9210c9274c920e',
'97b6b7f0e47f531b0723b0b6fb0722', '7f0e37f5307f595b0b0bc920fb0722', '7f0e397bd097c36b0b6fc9210c8dc2',
'9778397bd097c36b0b70c9274c91aa', '97b6b7f0e47f531b0723b0b6fb0721', '7f0e37f1487f595b0b0bb0b6fb0722',
'7f0e397bd097c35b0b6fc9210c8dc2', '9778397bd097c36b0b6fc9274c91aa', '97b6b7f0e47f531b0723b0b6fb0721',
'7f0e27f1487f595b0b0bb0b6fb0722', '7f0e397bd097c35b0b6fc920fb0722', '9778397bd097c36b0b6fc9274c91aa',
'97b6b7f0e47f531b0723b0b6fb0721', '7f0e27f1487f531b0b0bb0b6fb0722', '7f0e397bd097c35b0b6fc920fb0722',
'9778397bd097c36b0b6fc9274c91aa', '97b6b7f0e47f531b0723b0b6fb0721', '7f0e27f1487f531b0b0bb0b6fb0722',
'7f0e397bd097c35b0b6fc920fb0722', '9778397bd097c36b0b6fc9274c91aa', '97b6b7f0e47f531b0723b0b6fb0721',
'7f0e27f1487f531b0b0bb0b6fb0722', '7f0e397bd07f595b0b0bc920fb0722', '9778397bd097c36b0b6fc9274c91aa',
'97b6b7f0e47f531b0723b0787b0721', '7f0e27f0e47f531b0b0bb0b6fb0722', '7f0e397bd07f595b0b0bc920fb0722',
'9778397bd097c36b0b6fc9210c91aa', '97b6b7f0e47f149b0723b0787b0721', '7f0e27f0e47f531b0723b0b6fb0722',
'7f0e397bd07f595b0b0bc920fb0722', '9778397bd097c36b0b6fc9210c8dc2', '977837f0e37f149b0723b0787b0721',
'7f07e7f0e47f531b0723b0b6fb0722', '7f0e37f5307f595b0b0bc920fb0722', '7f0e397bd097c35b0b6fc9210c8dc2',
'977837f0e37f14998082b0787b0721', '7f07e7f0e47f531b0723b0b6fb0721', '7f0e37f1487f595b0b0bb0b6fb0722',
'7f0e397bd097c35b0b6fc9210c8dc2', '977837f0e37f14998082b0787b06bd', '7f07e7f0e47f531b0723b0b6fb0721',
'7f0e27f1487f531b0b0bb0b6fb0722', '7f0e397bd097c35b0b6fc920fb0722', '977837f0e37f14998082b0787b06bd',
'7f07e7f0e47f531b0723b0b6fb0721', '7f0e27f1487f531b0b0bb0b6fb0722', '7f0e397bd097c35b0b6fc920fb0722',
'977837f0e37f14998082b0787b06bd', '7f07e7f0e47f531b0723b0b6fb0721', '7f0e27f1487f531b0b0bb0b6fb0722',
'7f0e397bd07f595b0b0bc920fb0722', '977837f0e37f14998082b0787b06bd', '7f07e7f0e47f531b0723b0b6fb0721',
'7f0e27f1487f531b0b0bb0b6fb0722', '7f0e397bd07f595b0b0bc920fb0722', '977837f0e37f14998082b0787b06bd',
'7f07e7f0e47f149b0723b0787b0721', '7f0e27f0e47f531b0b0bb0b6fb0722', '7f0e397bd07f595b0b0bc920fb0722',
'977837f0e37f14998082b0723b06bd', '7f07e7f0e37f149b0723b0787b0721', '7f0e27f0e47f531b0723b0b6fb0722',
'7f0e397bd07f595b0b0bc920fb0722', '977837f0e37f14898082b0723b02d5', '7ec967f0e37f14998082b0787b0721',
'7f07e7f0e47f531b0723b0b6fb0722', '7f0e37f1487f595b0b0bb0b6fb0722', '7f0e37f0e37f14898082b0723b02d5',
'7ec967f0e37f14998082b0787b0721', '7f07e7f0e47f531b0723b0b6fb0722', '7f0e37f1487f531b0b0bb0b6fb0722',
'7f0e37f0e37f14898082b0723b02d5', '7ec967f0e37f14998082b0787b06bd', '7f07e7f0e47f531b0723b0b6fb0721',
'7f0e37f1487f531b0b0bb0b6fb0722', '7f0e37f0e37f14898082b072297c35', '7ec967f0e37f14998082b0787b06bd',
'7f07e7f0e47f531b0723b0b6fb0721', '7f0e27f1487f531b0b0bb0b6fb0722', '7f0e37f0e37f14898082b072297c35',
'7ec967f0e37f14998082b0787b06bd', '7f07e7f0e47f531b0723b0b6fb0721', '7f0e27f1487f531b0b0bb0b6fb0722',
'7f0e37f0e366aa89801eb072297c35', '7ec967f0e37f14998082b0787b06bd', '7f07e7f0e47f149b0723b0787b0721',
'7f0e27f1487f531b0b0bb0b6fb0722', '7f0e37f0e366aa89801eb072297c35', '7ec967f0e37f14998082b0723b06bd',
'7f07e7f0e47f149b0723b0787b0721', '7f0e27f0e47f531b0723b0b6fb0722', '7f0e37f0e366aa89801eb072297c35',
'7ec967f0e37f14998082b0723b06bd', '7f07e7f0e37f14998083b0787b0721', '7f0e27f0e47f531b0723b0b6fb0722',
'7f0e37f0e366aa89801eb072297c35', '7ec967f0e37f14898082b0723b02d5', '7f07e7f0e37f14998082b0787b0721',
'7f07e7f0e47f531b0723b0b6fb0722', '7f0e36665b66aa89801e9808297c35', '665f67f0e37f14898082b0723b02d5',
'7ec967f0e37f14998082b0787b0721', '7f07e7f0e47f531b0723b0b6fb0722', '7f0e36665b66a449801e9808297c35',
'665f67f0e37f14898082b0723b02d5', '7ec967f0e37f14998082b0787b06bd', '7f07e7f0e47f531b0723b0b6fb0721',
'7f0e36665b66a449801e9808297c35', '665f67f0e37f14898082b072297c35', '7ec967f0e37f14998082b0787b06bd',
'7f07e7f0e47f531b0723b0b6fb0721', '7f0e26665b66a449801e9808297c35', '665f67f0e37f1489801eb072297c35',
'7ec967f0e37f14998082b0787b06bd', '7f07e7f0e47f531b0723b0b6fb0721', '7f0e27f1487f531b0b0bb0b6fb0722'],
/**
* 数字转中文速查表
* @Array Of Property
* @trans ['日','一','二','三','四','五','六','七','八','九','十']
* @return Cn string
*/
nStr1: ['\u65e5', '\u4e00', '\u4e8c', '\u4e09', '\u56db', '\u4e94', '\u516d', '\u4e03', '\u516b', '\u4e5d', '\u5341'],
/**
* 日期转农历称呼速查表
* @Array Of Property
* @trans ['初','十','廿','卅']
* @return Cn string
*/
nStr2: ['\u521d', '\u5341', '\u5eff', '\u5345'],
/**
* 月份转农历称呼速查表
* @Array Of Property
* @trans ['正','一','二','三','四','五','六','七','八','九','十','冬','腊']
* @return Cn string
*/
nStr3: ['\u6b63', '\u4e8c', '\u4e09', '\u56db', '\u4e94', '\u516d', '\u4e03', '\u516b', '\u4e5d', '\u5341', '\u51ac', '\u814a'],
/**
* 返回农历y年一整年的总天数
* @param lunar Year
* @return Number
* @eg:var count = calendar.lYearDays(1987) ;//count=387
*/
lYearDays: function (y) {
var i; var sum = 348
for (i = 0x8000; i > 0x8; i >>= 1) { sum += (this.lunarInfo[y - 1900] & i) ? 1 : 0 }
return (sum + this.leapDays(y))
},
/**
* 返回农历y年闰月是哪个月;若y年没有闰月 则返回0
* @param lunar Year
* @return Number (0-12)
* @eg:var leapMonth = calendar.leapMonth(1987) ;//leapMonth=6
*/
leapMonth: function (y) { // 闰字编码 \u95f0
return (this.lunarInfo[y - 1900] & 0xf)
},
/**
* 返回农历y年闰月的天数 若该年没有闰月则返回0
* @param lunar Year
* @return Number (0、29、30)
* @eg:var leapMonthDay = calendar.leapDays(1987) ;//leapMonthDay=29
*/
leapDays: function (y) {
if (this.leapMonth(y)) {
return ((this.lunarInfo[y - 1900] & 0x10000) ? 30 : 29)
}
return (0)
},
/**
* 返回农历y年m月(非闰月)的总天数,计算m为闰月时的天数请使用leapDays方法
* @param lunar Year
* @return Number (-1、29、30)
* @eg:var MonthDay = calendar.monthDays(1987,9) ;//MonthDay=29
*/
monthDays: function (y, m) {
if (m > 12 || m < 1) { return -1 }// 月份参数从1至12,参数错误返回-1
return ((this.lunarInfo[y - 1900] & (0x10000 >> m)) ? 30 : 29)
},
/**
* 返回公历(!)y年m月的天数
* @param solar Year
* @return Number (-1、28、29、30、31)
* @eg:var solarMonthDay = calendar.leapDays(1987) ;//solarMonthDay=30
*/
solarDays: function (y, m) {
if (m > 12 || m < 1) { return -1 } // 若参数错误 返回-1
var ms = m - 1
if (ms == 1) { // 2月份的闰平规律测算后确认返回28或29
return (((y % 4 == 0) && (y % 100 != 0) || (y % 400 == 0)) ? 29 : 28)
} else {
return (this.solarMonth[ms])
}
},
/**
* 农历年份转换为干支纪年
* @param lYear 农历年的年份数
* @return Cn string
*/
toGanZhiYear: function (lYear) {
var ganKey = (lYear - 3) % 10
var zhiKey = (lYear - 3) % 12
if (ganKey == 0) ganKey = 10// 如果余数为0则为最后一个天干
if (zhiKey == 0) zhiKey = 12// 如果余数为0则为最后一个地支
return this.Gan[ganKey - 1] + this.Zhi[zhiKey - 1]
},
/**
* 公历月、日判断所属星座
* @param cMonth [description]
* @param cDay [description]
* @return Cn string
*/
toAstro: function (cMonth, cDay) {
var s = '\u9b54\u7faf\u6c34\u74f6\u53cc\u9c7c\u767d\u7f8a\u91d1\u725b\u53cc\u5b50\u5de8\u87f9\u72ee\u5b50\u5904\u5973\u5929\u79e4\u5929\u874e\u5c04\u624b\u9b54\u7faf'
var arr = [20, 19, 21, 21, 21, 22, 23, 23, 23, 23, 22, 22]
return s.substr(cMonth * 2 - (cDay < arr[cMonth - 1] ? 2 : 0), 2) + '\u5ea7'// 座
},
/**
* 传入offset偏移量返回干支
* @param offset 相对甲子的偏移量
* @return Cn string
*/
toGanZhi: function (offset) {
return this.Gan[offset % 10] + this.Zhi[offset % 12]
},
/**
* 传入公历(!)y年获得该年第n个节气的公历日期
* @param y公历年(1900-2100);n二十四节气中的第几个节气(1~24);从n=1(小寒)算起
* @return day Number
* @eg:var _24 = calendar.getTerm(1987,3) ;//_24=4;意即1987年2月4日立春
*/
getTerm: function (y, n) {
if (y < 1900 || y > 2100) { return -1 }
if (n < 1 || n > 24) { return -1 }
var _table = this.sTermInfo[y - 1900]
var _info = [
parseInt('0x' + _table.substr(0, 5)).toString(),
parseInt('0x' + _table.substr(5, 5)).toString(),
parseInt('0x' + _table.substr(10, 5)).toString(),
parseInt('0x' + _table.substr(15, 5)).toString(),
parseInt('0x' + _table.substr(20, 5)).toString(),
parseInt('0x' + _table.substr(25, 5)).toString()
]
var _calday = [
_info[0].substr(0, 1),
_info[0].substr(1, 2),
_info[0].substr(3, 1),
_info[0].substr(4, 2),
_info[1].substr(0, 1),
_info[1].substr(1, 2),
_info[1].substr(3, 1),
_info[1].substr(4, 2),
_info[2].substr(0, 1),
_info[2].substr(1, 2),
_info[2].substr(3, 1),
_info[2].substr(4, 2),
_info[3].substr(0, 1),
_info[3].substr(1, 2),
_info[3].substr(3, 1),
_info[3].substr(4, 2),
_info[4].substr(0, 1),
_info[4].substr(1, 2),
_info[4].substr(3, 1),
_info[4].substr(4, 2),
_info[5].substr(0, 1),
_info[5].substr(1, 2),
_info[5].substr(3, 1),
_info[5].substr(4, 2)
]
return parseInt(_calday[n - 1])
},
/**
* 传入农历数字月份返回汉语通俗表示法
* @param lunar month
* @return Cn string
* @eg:var cnMonth = calendar.toChinaMonth(12) ;//cnMonth='腊月'
*/
toChinaMonth: function (m) { // 月 => \u6708
if (m > 12 || m < 1) { return -1 } // 若参数错误 返回-1
var s = this.nStr3[m - 1]
s += '\u6708'// 加上月字
return s
},
/**
* 传入农历日期数字返回汉字表示法
* @param lunar day
* @return Cn string
* @eg:var cnDay = calendar.toChinaDay(21) ;//cnMonth='廿一'
*/
toChinaDay: function (d) { // 日 => \u65e5
var s
switch (d) {
case 10:
s = '\u521d\u5341'; break
case 20:
s = '\u4e8c\u5341'; break
break
case 30:
s = '\u4e09\u5341'; break
break
default :
s = this.nStr2[Math.floor(d / 10)]
s += this.nStr1[d % 10]
}
return (s)
},
/**
* 年份转生肖[!仅能大致转换] => 精确划分生肖分界线是“立春”
* @param y year
* @return Cn string
* @eg:var animal = calendar.getAnimal(1987) ;//animal='兔'
*/
getAnimal: function (y) {
return this.Animals[(y - 4) % 12]
},
/**
* 传入阳历年月日获得详细的公历、农历object信息 <=>JSON
* @param y solar year
* @param m solar month
* @param d solar day
* @return JSON object
* @eg:console.log(calendar.solar2lunar(1987,11,01));
*/
solar2lunar: function (y, m, d) { // 参数区间1900.1.31~2100.12.31
// 年份限定、上限
if (y < 1900 || y > 2100) {
return -1// undefined转换为数字变为NaN
}
// 公历传参最下限
if (y == 1900 && m == 1 && d < 31) {
return -1
}
// 未传参 获得当天
if (!y) {
var objDate = new Date()
} else {
var objDate = new Date(y, parseInt(m) - 1, d)
}
var i; var leap = 0; var temp = 0
// 修正ymd参数
var y = objDate.getFullYear()
var m = objDate.getMonth() + 1
var d = objDate.getDate()
var offset = (Date.UTC(objDate.getFullYear(), objDate.getMonth(), objDate.getDate()) - Date.UTC(1900, 0, 31)) / 86400000
for (i = 1900; i < 2101 && offset > 0; i++) {
temp = this.lYearDays(i)
offset -= temp
}
if (offset < 0) {
offset += temp; i--
}
// 是否今天
var isTodayObj = new Date()
var isToday = false
if (isTodayObj.getFullYear() == y && isTodayObj.getMonth() + 1 == m && isTodayObj.getDate() == d) {
isToday = true
}
// 星期几
var nWeek = objDate.getDay()
var cWeek = this.nStr1[nWeek]
// 数字表示周几顺应天朝周一开始的惯例
if (nWeek == 0) {
nWeek = 7
}
// 农历年
var year = i
var leap = this.leapMonth(i) // 闰哪个月
var isLeap = false
// 效验闰月
for (i = 1; i < 13 && offset > 0; i++) {
// 闰月
if (leap > 0 && i == (leap + 1) && isLeap == false) {
--i
isLeap = true; temp = this.leapDays(year) // 计算农历闰月天数
} else {
temp = this.monthDays(year, i)// 计算农历普通月天数
}
// 解除闰月
if (isLeap == true && i == (leap + 1)) { isLeap = false }
offset -= temp
}
// 闰月导致数组下标重叠取反
if (offset == 0 && leap > 0 && i == leap + 1) {
if (isLeap) {
isLeap = false
} else {
isLeap = true; --i
}
}
if (offset < 0) {
offset += temp; --i
}
// 农历月
var month = i
// 农历日
var day = offset + 1
// 天干地支处理
var sm = m - 1
var gzY = this.toGanZhiYear(year)
// 当月的两个节气
// bugfix-2017-7-24 11:03:38 use lunar Year Param `y` Not `year`
var firstNode = this.getTerm(y, (m * 2 - 1))// 返回当月「节」为几日开始
var secondNode = this.getTerm(y, (m * 2))// 返回当月「节」为几日开始
// 依据12节气修正干支月
var gzM = this.toGanZhi((y - 1900) * 12 + m + 11)
if (d >= firstNode) {
gzM = this.toGanZhi((y - 1900) * 12 + m + 12)
}
// 传入的日期的节气与否
var isTerm = false
var Term = null
if (firstNode == d) {
isTerm = true
Term = this.solarTerm[m * 2 - 2]
}
if (secondNode == d) {
isTerm = true
Term = this.solarTerm[m * 2 - 1]
}
// 日柱 当月一日与 1900/1/1 相差天数
var dayCyclical = Date.UTC(y, sm, 1, 0, 0, 0, 0) / 86400000 + 25567 + 10
var gzD = this.toGanZhi(dayCyclical + d - 1)
// 该日期所属的星座
var astro = this.toAstro(m, d)
return { 'lYear': year, 'lMonth': month, 'lDay': day, 'Animal': this.getAnimal(year), 'IMonthCn': (isLeap ? '\u95f0' : '') + this.toChinaMonth(month), 'IDayCn': this.toChinaDay(day), 'cYear': y, 'cMonth': m, 'cDay': d, 'gzYear': gzY, 'gzMonth': gzM, 'gzDay': gzD, 'isToday': isToday, 'isLeap': isLeap, 'nWeek': nWeek, 'ncWeek': '\u661f\u671f' + cWeek, 'isTerm': isTerm, 'Term': Term, 'astro': astro }
},
/**
* 传入农历年月日以及传入的月份是否闰月获得详细的公历、农历object信息 <=>JSON
* @param y lunar year
* @param m lunar month
* @param d lunar day
* @param isLeapMonth lunar month is leap or not.[如果是农历闰月第四个参数赋值true即可]
* @return JSON object
* @eg:console.log(calendar.lunar2solar(1987,9,10));
*/
lunar2solar: function (y, m, d, isLeapMonth) { // 参数区间1900.1.31~2100.12.1
var isLeapMonth = !!isLeapMonth
var leapOffset = 0
var leapMonth = this.leapMonth(y)
var leapDay = this.leapDays(y)
if (isLeapMonth && (leapMonth != m)) { return -1 }// 传参要求计算该闰月公历 但该年得出的闰月与传参的月份并不同
if (y == 2100 && m == 12 && d > 1 || y == 1900 && m == 1 && d < 31) { return -1 }// 超出了最大极限值
var day = this.monthDays(y, m)
var _day = day
// bugFix 2016-9-25
// if month is leap, _day use leapDays method
if (isLeapMonth) {
_day = this.leapDays(y, m)
}
if (y < 1900 || y > 2100 || d > _day) { return -1 }// 参数合法性效验
// 计算农历的时间差
var offset = 0
for (var i = 1900; i < y; i++) {
offset += this.lYearDays(i)
}
var leap = 0; var isAdd = false
for (var i = 1; i < m; i++) {
leap = this.leapMonth(y)
if (!isAdd) { // 处理闰月
if (leap <= i && leap > 0) {
offset += this.leapDays(y); isAdd = true
}
}
offset += this.monthDays(y, i)
}
// 转换闰月农历 需补充该年闰月的前一个月的时差
if (isLeapMonth) { offset += day }
// 1900年农历正月一日的公历时间为1900年1月30日0时0分0秒(该时间也是本农历的最开始起始点)
var stmap = Date.UTC(1900, 1, 30, 0, 0, 0)
var calObj = new Date((offset + d - 31) * 86400000 + stmap)
var cY = calObj.getUTCFullYear()
var cM = calObj.getUTCMonth() + 1
var cD = calObj.getUTCDate()
return this.solar2lunar(cY, cM, cD)
}
}
export default calendar
|
2301_77169380/aionix-2
|
uni_modules/uni-calendar/components/uni-calendar/calendar.js
|
JavaScript
|
mit
| 24,849
|
import en from './en.json'
import zhHans from './zh-Hans.json'
import zhHant from './zh-Hant.json'
export default {
en,
'zh-Hans': zhHans,
'zh-Hant': zhHant
}
|
2301_77169380/aionix-2
|
uni_modules/uni-calendar/components/uni-calendar/i18n/index.js
|
JavaScript
|
mit
| 162
|
<template>
<view class="uni-calendar-item__weeks-box" :class="{
'uni-calendar-item--disable':weeks.disable,
'uni-calendar-item--isDay':calendar.fullDate === weeks.fullDate && weeks.isDay,
'uni-calendar-item--checked':(calendar.fullDate === weeks.fullDate && !weeks.isDay) ,
'uni-calendar-item--before-checked':weeks.beforeMultiple,
'uni-calendar-item--multiple': weeks.multiple,
'uni-calendar-item--after-checked':weeks.afterMultiple,
}"
@click="choiceDate(weeks)">
<view class="uni-calendar-item__weeks-box-item">
<text v-if="selected&&weeks.extraInfo" class="uni-calendar-item__weeks-box-circle"></text>
<text class="uni-calendar-item__weeks-box-text" :class="{
'uni-calendar-item--isDay-text': weeks.isDay,
'uni-calendar-item--isDay':calendar.fullDate === weeks.fullDate && weeks.isDay,
'uni-calendar-item--checked':calendar.fullDate === weeks.fullDate && !weeks.isDay,
'uni-calendar-item--before-checked':weeks.beforeMultiple,
'uni-calendar-item--multiple': weeks.multiple,
'uni-calendar-item--after-checked':weeks.afterMultiple,
'uni-calendar-item--disable':weeks.disable,
}">{{weeks.date}}</text>
<text v-if="!lunar&&!weeks.extraInfo && weeks.isDay" class="uni-calendar-item__weeks-lunar-text" :class="{
'uni-calendar-item--isDay-text':weeks.isDay,
'uni-calendar-item--isDay':calendar.fullDate === weeks.fullDate && weeks.isDay,
'uni-calendar-item--checked':calendar.fullDate === weeks.fullDate && !weeks.isDay,
'uni-calendar-item--before-checked':weeks.beforeMultiple,
'uni-calendar-item--multiple': weeks.multiple,
'uni-calendar-item--after-checked':weeks.afterMultiple,
}">{{todayText}}</text>
<text v-if="lunar&&!weeks.extraInfo" class="uni-calendar-item__weeks-lunar-text" :class="{
'uni-calendar-item--isDay-text':weeks.isDay,
'uni-calendar-item--isDay':calendar.fullDate === weeks.fullDate && weeks.isDay,
'uni-calendar-item--checked':calendar.fullDate === weeks.fullDate && !weeks.isDay,
'uni-calendar-item--before-checked':weeks.beforeMultiple,
'uni-calendar-item--multiple': weeks.multiple,
'uni-calendar-item--after-checked':weeks.afterMultiple,
'uni-calendar-item--disable':weeks.disable,
}">{{weeks.isDay ? todayText : (weeks.lunar.IDayCn === '初一'?weeks.lunar.IMonthCn:weeks.lunar.IDayCn)}}</text>
<text v-if="weeks.extraInfo&&weeks.extraInfo.info" class="uni-calendar-item__weeks-lunar-text" :class="{
'uni-calendar-item--extra':weeks.extraInfo.info,
'uni-calendar-item--isDay-text':weeks.isDay,
'uni-calendar-item--isDay':calendar.fullDate === weeks.fullDate && weeks.isDay,
'uni-calendar-item--checked':calendar.fullDate === weeks.fullDate && !weeks.isDay,
'uni-calendar-item--before-checked':weeks.beforeMultiple,
'uni-calendar-item--multiple': weeks.multiple,
'uni-calendar-item--after-checked':weeks.afterMultiple,
'uni-calendar-item--disable':weeks.disable,
}">{{weeks.extraInfo.info}}</text>
</view>
</view>
</template>
<script>
import { initVueI18n } from '@dcloudio/uni-i18n'
import i18nMessages from './i18n/index.js'
const { t } = initVueI18n(i18nMessages)
export default {
emits:['change'],
props: {
weeks: {
type: Object,
default () {
return {}
}
},
calendar: {
type: Object,
default: () => {
return {}
}
},
selected: {
type: Array,
default: () => {
return []
}
},
lunar: {
type: Boolean,
default: false
}
},
computed: {
todayText() {
return t("uni-calender.today")
},
},
methods: {
choiceDate(weeks) {
this.$emit('change', weeks)
}
}
}
</script>
<style lang="scss" scoped>
$uni-font-size-base:14px;
$uni-text-color:#333;
$uni-font-size-sm:12px;
$uni-color-error: #e43d33;
$uni-opacity-disabled: 0.3;
$uni-text-color-disable:#c0c0c0;
$uni-primary: #2979ff !default;
.uni-calendar-item__weeks-box {
flex: 1;
/* #ifndef APP-NVUE */
display: flex;
/* #endif */
flex-direction: column;
justify-content: center;
align-items: center;
}
.uni-calendar-item__weeks-box-text {
font-size: $uni-font-size-base;
color: $uni-text-color;
}
.uni-calendar-item__weeks-lunar-text {
font-size: $uni-font-size-sm;
color: $uni-text-color;
}
.uni-calendar-item__weeks-box-item {
position: relative;
/* #ifndef APP-NVUE */
display: flex;
/* #endif */
flex-direction: column;
justify-content: center;
align-items: center;
width: 100rpx;
height: 100rpx;
}
.uni-calendar-item__weeks-box-circle {
position: absolute;
top: 5px;
right: 5px;
width: 8px;
height: 8px;
border-radius: 8px;
background-color: $uni-color-error;
}
.uni-calendar-item--disable {
background-color: rgba(249, 249, 249, $uni-opacity-disabled);
color: $uni-text-color-disable;
}
.uni-calendar-item--isDay-text {
color: $uni-primary;
}
.uni-calendar-item--isDay {
background-color: $uni-primary;
opacity: 0.8;
color: #fff;
}
.uni-calendar-item--extra {
color: $uni-color-error;
opacity: 0.8;
}
.uni-calendar-item--checked {
background-color: $uni-primary;
color: #fff;
opacity: 0.8;
}
.uni-calendar-item--multiple {
background-color: $uni-primary;
color: #fff;
opacity: 0.8;
}
.uni-calendar-item--before-checked {
background-color: #ff5a5f;
color: #fff;
}
.uni-calendar-item--after-checked {
background-color: #ff5a5f;
color: #fff;
}
</style>
|
2301_77169380/aionix-2
|
uni_modules/uni-calendar/components/uni-calendar/uni-calendar-item.vue
|
Vue
|
mit
| 5,445
|
<template>
<view class="uni-calendar">
<view v-if="!insert&&show" class="uni-calendar__mask" :class="{'uni-calendar--mask-show':aniMaskShow}" @click="clean"></view>
<view v-if="insert || show" class="uni-calendar__content" :class="{'uni-calendar--fixed':!insert,'uni-calendar--ani-show':aniMaskShow}">
<view v-if="!insert" class="uni-calendar__header uni-calendar--fixed-top">
<view class="uni-calendar__header-btn-box" @click="close">
<text class="uni-calendar__header-text uni-calendar--fixed-width">{{cancelText}}</text>
</view>
<view class="uni-calendar__header-btn-box" @click="confirm">
<text class="uni-calendar__header-text uni-calendar--fixed-width">{{okText}}</text>
</view>
</view>
<view class="uni-calendar__header">
<view class="uni-calendar__header-btn-box" @click.stop="pre">
<view class="uni-calendar__header-btn uni-calendar--left"></view>
</view>
<picker mode="date" :value="date" fields="month" @change="bindDateChange">
<text class="uni-calendar__header-text">{{ (nowDate.year||'') +' / '+( nowDate.month||'')}}</text>
</picker>
<view class="uni-calendar__header-btn-box" @click.stop="next">
<view class="uni-calendar__header-btn uni-calendar--right"></view>
</view>
<text class="uni-calendar__backtoday" @click="backToday">{{todayText}}</text>
</view>
<view class="uni-calendar__box">
<view v-if="showMonth" class="uni-calendar__box-bg">
<text class="uni-calendar__box-bg-text">{{nowDate.month}}</text>
</view>
<view class="uni-calendar__weeks">
<view class="uni-calendar__weeks-day">
<text class="uni-calendar__weeks-day-text">{{SUNText}}</text>
</view>
<view class="uni-calendar__weeks-day">
<text class="uni-calendar__weeks-day-text">{{monText}}</text>
</view>
<view class="uni-calendar__weeks-day">
<text class="uni-calendar__weeks-day-text">{{TUEText}}</text>
</view>
<view class="uni-calendar__weeks-day">
<text class="uni-calendar__weeks-day-text">{{WEDText}}</text>
</view>
<view class="uni-calendar__weeks-day">
<text class="uni-calendar__weeks-day-text">{{THUText}}</text>
</view>
<view class="uni-calendar__weeks-day">
<text class="uni-calendar__weeks-day-text">{{FRIText}}</text>
</view>
<view class="uni-calendar__weeks-day">
<text class="uni-calendar__weeks-day-text">{{SATText}}</text>
</view>
</view>
<view class="uni-calendar__weeks" v-for="(item,weekIndex) in weeks" :key="weekIndex">
<view class="uni-calendar__weeks-item" v-for="(weeks,weeksIndex) in item" :key="weeksIndex">
<calendar-item class="uni-calendar-item--hook" :weeks="weeks" :calendar="calendar" :selected="selected" :lunar="lunar" @change="choiceDate"></calendar-item>
</view>
</view>
</view>
</view>
</view>
</template>
<script>
import Calendar from './util.js';
import CalendarItem from './uni-calendar-item.vue'
import { initVueI18n } from '@dcloudio/uni-i18n'
import i18nMessages from './i18n/index.js'
const { t } = initVueI18n(i18nMessages)
/**
* Calendar 日历
* @description 日历组件可以查看日期,选择任意范围内的日期,打点操作。常用场景如:酒店日期预订、火车机票选择购买日期、上下班打卡等
* @tutorial https://ext.dcloud.net.cn/plugin?id=56
* @property {String} date 自定义当前时间,默认为今天
* @property {Boolean} lunar 显示农历
* @property {String} startDate 日期选择范围-开始日期
* @property {String} endDate 日期选择范围-结束日期
* @property {Boolean} range 范围选择
* @property {Boolean} insert = [true|false] 插入模式,默认为false
* @value true 弹窗模式
* @value false 插入模式
* @property {Boolean} clearDate = [true|false] 弹窗模式是否清空上次选择内容
* @property {Array} selected 打点,期待格式[{date: '2019-06-27', info: '签到', data: { custom: '自定义信息', name: '自定义消息头',xxx:xxx... }}]
* @property {Boolean} showMonth 是否选择月份为背景
* @event {Function} change 日期改变,`insert :ture` 时生效
* @event {Function} confirm 确认选择`insert :false` 时生效
* @event {Function} monthSwitch 切换月份时触发
* @example <uni-calendar :insert="true":lunar="true" :start-date="'2019-3-2'":end-date="'2019-5-20'"@change="change" />
*/
export default {
components: {
CalendarItem
},
emits:['close','confirm','change','monthSwitch'],
props: {
date: {
type: String,
default: ''
},
selected: {
type: Array,
default () {
return []
}
},
lunar: {
type: Boolean,
default: false
},
startDate: {
type: String,
default: ''
},
endDate: {
type: String,
default: ''
},
range: {
type: Boolean,
default: false
},
insert: {
type: Boolean,
default: true
},
showMonth: {
type: Boolean,
default: true
},
clearDate: {
type: Boolean,
default: true
}
},
data() {
return {
show: false,
weeks: [],
calendar: {},
nowDate: '',
aniMaskShow: false
}
},
computed:{
/**
* for i18n
*/
okText() {
return t("uni-calender.ok")
},
cancelText() {
return t("uni-calender.cancel")
},
todayText() {
return t("uni-calender.today")
},
monText() {
return t("uni-calender.MON")
},
TUEText() {
return t("uni-calender.TUE")
},
WEDText() {
return t("uni-calender.WED")
},
THUText() {
return t("uni-calender.THU")
},
FRIText() {
return t("uni-calender.FRI")
},
SATText() {
return t("uni-calender.SAT")
},
SUNText() {
return t("uni-calender.SUN")
},
},
watch: {
date(newVal) {
// this.cale.setDate(newVal)
this.init(newVal)
},
startDate(val){
this.cale.resetSatrtDate(val)
this.cale.setDate(this.nowDate.fullDate)
this.weeks = this.cale.weeks
},
endDate(val){
this.cale.resetEndDate(val)
this.cale.setDate(this.nowDate.fullDate)
this.weeks = this.cale.weeks
},
selected(newVal) {
this.cale.setSelectInfo(this.nowDate.fullDate, newVal)
this.weeks = this.cale.weeks
}
},
created() {
this.cale = new Calendar({
selected: this.selected,
startDate: this.startDate,
endDate: this.endDate,
range: this.range,
})
this.init(this.date)
},
methods: {
// 取消穿透
clean() {},
bindDateChange(e) {
const value = e.detail.value + '-1'
this.setDate(value)
const { year,month } = this.cale.getDate(value)
this.$emit('monthSwitch', {
year,
month
})
},
/**
* 初始化日期显示
* @param {Object} date
*/
init(date) {
this.cale.setDate(date)
this.weeks = this.cale.weeks
this.nowDate = this.calendar = this.cale.getInfo(date)
},
/**
* 打开日历弹窗
*/
open() {
// 弹窗模式并且清理数据
if (this.clearDate && !this.insert) {
this.cale.cleanMultipleStatus()
// this.cale.setDate(this.date)
this.init(this.date)
}
this.show = true
this.$nextTick(() => {
setTimeout(() => {
this.aniMaskShow = true
}, 50)
})
},
/**
* 关闭日历弹窗
*/
close() {
this.aniMaskShow = false
this.$nextTick(() => {
setTimeout(() => {
this.show = false
this.$emit('close')
}, 300)
})
},
/**
* 确认按钮
*/
confirm() {
this.setEmit('confirm')
this.close()
},
/**
* 变化触发
*/
change() {
if (!this.insert) return
this.setEmit('change')
},
/**
* 选择月份触发
*/
monthSwitch() {
let {
year,
month
} = this.nowDate
this.$emit('monthSwitch', {
year,
month: Number(month)
})
},
/**
* 派发事件
* @param {Object} name
*/
setEmit(name) {
let {
year,
month,
date,
fullDate,
lunar,
extraInfo
} = this.calendar
this.$emit(name, {
range: this.cale.multipleStatus,
year,
month,
date,
fulldate: fullDate,
lunar,
extraInfo: extraInfo || {}
})
},
/**
* 选择天触发
* @param {Object} weeks
*/
choiceDate(weeks) {
if (weeks.disable) return
this.calendar = weeks
// 设置多选
this.cale.setMultiple(this.calendar.fullDate)
this.weeks = this.cale.weeks
this.change()
},
/**
* 回到今天
*/
backToday() {
const nowYearMonth = `${this.nowDate.year}-${this.nowDate.month}`
const date = this.cale.getDate(new Date())
const todayYearMonth = `${date.year}-${date.month}`
this.init(date.fullDate)
if(nowYearMonth !== todayYearMonth) {
this.monthSwitch()
}
this.change()
},
/**
* 上个月
*/
pre() {
const preDate = this.cale.getDate(this.nowDate.fullDate, -1, 'month').fullDate
this.setDate(preDate)
this.monthSwitch()
},
/**
* 下个月
*/
next() {
const nextDate = this.cale.getDate(this.nowDate.fullDate, +1, 'month').fullDate
this.setDate(nextDate)
this.monthSwitch()
},
/**
* 设置日期
* @param {Object} date
*/
setDate(date) {
this.cale.setDate(date)
this.weeks = this.cale.weeks
this.nowDate = this.cale.getInfo(date)
}
}
}
</script>
<style lang="scss" scoped>
$uni-bg-color-mask: rgba($color: #000000, $alpha: 0.4);
$uni-border-color: #EDEDED;
$uni-text-color: #333;
$uni-bg-color-hover:#f1f1f1;
$uni-font-size-base:14px;
$uni-text-color-placeholder: #808080;
$uni-color-subtitle: #555555;
$uni-text-color-grey:#999;
.uni-calendar {
/* #ifndef APP-NVUE */
display: flex;
/* #endif */
flex-direction: column;
}
.uni-calendar__mask {
position: fixed;
bottom: 0;
top: 0;
left: 0;
right: 0;
background-color: $uni-bg-color-mask;
transition-property: opacity;
transition-duration: 0.3s;
opacity: 0;
/* #ifndef APP-NVUE */
z-index: 99;
/* #endif */
}
.uni-calendar--mask-show {
opacity: 1
}
.uni-calendar--fixed {
position: fixed;
/* #ifdef APP-NVUE */
bottom: 0;
/* #endif */
left: 0;
right: 0;
transition-property: transform;
transition-duration: 0.3s;
transform: translateY(460px);
/* #ifndef APP-NVUE */
bottom: calc(var(--window-bottom));
z-index: 99;
/* #endif */
}
.uni-calendar--ani-show {
transform: translateY(0);
}
.uni-calendar__content {
background-color: #fff;
}
.uni-calendar__header {
position: relative;
/* #ifndef APP-NVUE */
display: flex;
/* #endif */
flex-direction: row;
justify-content: center;
align-items: center;
height: 50px;
border-bottom-color: $uni-border-color;
border-bottom-style: solid;
border-bottom-width: 1px;
}
.uni-calendar--fixed-top {
/* #ifndef APP-NVUE */
display: flex;
/* #endif */
flex-direction: row;
justify-content: space-between;
border-top-color: $uni-border-color;
border-top-style: solid;
border-top-width: 1px;
}
.uni-calendar--fixed-width {
width: 50px;
}
.uni-calendar__backtoday {
position: absolute;
right: 0;
top: 25rpx;
padding: 0 5px;
padding-left: 10px;
height: 25px;
line-height: 25px;
font-size: 12px;
border-top-left-radius: 25px;
border-bottom-left-radius: 25px;
color: $uni-text-color;
background-color: $uni-bg-color-hover;
}
.uni-calendar__header-text {
text-align: center;
width: 100px;
font-size: $uni-font-size-base;
color: $uni-text-color;
}
.uni-calendar__header-btn-box {
/* #ifndef APP-NVUE */
display: flex;
/* #endif */
flex-direction: row;
align-items: center;
justify-content: center;
width: 50px;
height: 50px;
}
.uni-calendar__header-btn {
width: 10px;
height: 10px;
border-left-color: $uni-text-color-placeholder;
border-left-style: solid;
border-left-width: 2px;
border-top-color: $uni-color-subtitle;
border-top-style: solid;
border-top-width: 2px;
}
.uni-calendar--left {
transform: rotate(-45deg);
}
.uni-calendar--right {
transform: rotate(135deg);
}
.uni-calendar__weeks {
position: relative;
/* #ifndef APP-NVUE */
display: flex;
/* #endif */
flex-direction: row;
}
.uni-calendar__weeks-item {
flex: 1;
}
.uni-calendar__weeks-day {
flex: 1;
/* #ifndef APP-NVUE */
display: flex;
/* #endif */
flex-direction: column;
justify-content: center;
align-items: center;
height: 45px;
border-bottom-color: #F5F5F5;
border-bottom-style: solid;
border-bottom-width: 1px;
}
.uni-calendar__weeks-day-text {
font-size: 14px;
}
.uni-calendar__box {
position: relative;
}
.uni-calendar__box-bg {
/* #ifndef APP-NVUE */
display: flex;
/* #endif */
justify-content: center;
align-items: center;
position: absolute;
top: 0;
left: 0;
right: 0;
bottom: 0;
}
.uni-calendar__box-bg-text {
font-size: 200px;
font-weight: bold;
color: $uni-text-color-grey;
opacity: 0.1;
text-align: center;
/* #ifndef APP-NVUE */
line-height: 1;
/* #endif */
}
</style>
|
2301_77169380/aionix-2
|
uni_modules/uni-calendar/components/uni-calendar/uni-calendar.vue
|
Vue
|
mit
| 13,205
|
import CALENDAR from './calendar.js'
class Calendar {
constructor({
date,
selected,
startDate,
endDate,
range
} = {}) {
// 当前日期
this.date = this.getDate(new Date()) // 当前初入日期
// 打点信息
this.selected = selected || [];
// 范围开始
this.startDate = startDate
// 范围结束
this.endDate = endDate
this.range = range
// 多选状态
this.cleanMultipleStatus()
// 每周日期
this.weeks = {}
// this._getWeek(this.date.fullDate)
}
/**
* 设置日期
* @param {Object} date
*/
setDate(date) {
this.selectDate = this.getDate(date)
this._getWeek(this.selectDate.fullDate)
}
/**
* 清理多选状态
*/
cleanMultipleStatus() {
this.multipleStatus = {
before: '',
after: '',
data: []
}
}
/**
* 重置开始日期
*/
resetSatrtDate(startDate) {
// 范围开始
this.startDate = startDate
}
/**
* 重置结束日期
*/
resetEndDate(endDate) {
// 范围结束
this.endDate = endDate
}
/**
* 获取任意时间
*/
getDate(date, AddDayCount = 0, str = 'day') {
if (!date) {
date = new Date()
}
if (typeof date !== 'object') {
date = date.replace(/-/g, '/')
}
const dd = new Date(date)
switch (str) {
case 'day':
dd.setDate(dd.getDate() + AddDayCount) // 获取AddDayCount天后的日期
break
case 'month':
if (dd.getDate() === 31 && AddDayCount>0) {
dd.setDate(dd.getDate() + AddDayCount)
} else {
const preMonth = dd.getMonth()
dd.setMonth(preMonth + AddDayCount) // 获取AddDayCount天后的日期
const nextMonth = dd.getMonth()
// 处理 pre 切换月份目标月份为2月没有当前日(30 31) 切换错误问题
if(AddDayCount<0 && preMonth!==0 && nextMonth-preMonth>AddDayCount){
dd.setMonth(nextMonth+(nextMonth-preMonth+AddDayCount))
}
// 处理 next 切换月份目标月份为2月没有当前日(30 31) 切换错误问题
if(AddDayCount>0 && nextMonth-preMonth>AddDayCount){
dd.setMonth(nextMonth-(nextMonth-preMonth-AddDayCount))
}
}
break
case 'year':
dd.setFullYear(dd.getFullYear() + AddDayCount) // 获取AddDayCount天后的日期
break
}
const y = dd.getFullYear()
const m = dd.getMonth() + 1 < 10 ? '0' + (dd.getMonth() + 1) : dd.getMonth() + 1 // 获取当前月份的日期,不足10补0
const d = dd.getDate() < 10 ? '0' + dd.getDate() : dd.getDate() // 获取当前几号,不足10补0
return {
fullDate: y + '-' + m + '-' + d,
year: y,
month: m,
date: d,
day: dd.getDay()
}
}
/**
* 获取上月剩余天数
*/
_getLastMonthDays(firstDay, full) {
let dateArr = []
for (let i = firstDay; i > 0; i--) {
const beforeDate = new Date(full.year, full.month - 1, -i + 1).getDate()
dateArr.push({
date: beforeDate,
month: full.month - 1,
lunar: this.getlunar(full.year, full.month - 1, beforeDate),
disable: true
})
}
return dateArr
}
/**
* 获取本月天数
*/
_currentMonthDys(dateData, full) {
let dateArr = []
let fullDate = this.date.fullDate
for (let i = 1; i <= dateData; i++) {
let nowDate = full.year + '-' + (full.month < 10 ?
full.month : full.month) + '-' + (i < 10 ?
'0' + i : i)
// 是否今天
let isDay = fullDate === nowDate
// 获取打点信息
let info = this.selected && this.selected.find((item) => {
if (this.dateEqual(nowDate, item.date)) {
return item
}
})
// 日期禁用
let disableBefore = true
let disableAfter = true
if (this.startDate) {
// let dateCompBefore = this.dateCompare(this.startDate, fullDate)
// disableBefore = this.dateCompare(dateCompBefore ? this.startDate : fullDate, nowDate)
disableBefore = this.dateCompare(this.startDate, nowDate)
}
if (this.endDate) {
// let dateCompAfter = this.dateCompare(fullDate, this.endDate)
// disableAfter = this.dateCompare(nowDate, dateCompAfter ? this.endDate : fullDate)
disableAfter = this.dateCompare(nowDate, this.endDate)
}
let multiples = this.multipleStatus.data
let checked = false
let multiplesStatus = -1
if (this.range) {
if (multiples) {
multiplesStatus = multiples.findIndex((item) => {
return this.dateEqual(item, nowDate)
})
}
if (multiplesStatus !== -1) {
checked = true
}
}
let data = {
fullDate: nowDate,
year: full.year,
date: i,
multiple: this.range ? checked : false,
beforeMultiple: this.dateEqual(this.multipleStatus.before, nowDate),
afterMultiple: this.dateEqual(this.multipleStatus.after, nowDate),
month: full.month,
lunar: this.getlunar(full.year, full.month, i),
disable: !(disableBefore && disableAfter),
isDay
}
if (info) {
data.extraInfo = info
}
dateArr.push(data)
}
return dateArr
}
/**
* 获取下月天数
*/
_getNextMonthDays(surplus, full) {
let dateArr = []
for (let i = 1; i < surplus + 1; i++) {
dateArr.push({
date: i,
month: Number(full.month) + 1,
lunar: this.getlunar(full.year, Number(full.month) + 1, i),
disable: true
})
}
return dateArr
}
/**
* 获取当前日期详情
* @param {Object} date
*/
getInfo(date) {
if (!date) {
date = new Date()
}
const dateInfo = this.canlender.find(item => item.fullDate === this.getDate(date).fullDate)
return dateInfo
}
/**
* 比较时间大小
*/
dateCompare(startDate, endDate) {
// 计算截止时间
startDate = new Date(startDate.replace('-', '/').replace('-', '/'))
// 计算详细项的截止时间
endDate = new Date(endDate.replace('-', '/').replace('-', '/'))
if (startDate <= endDate) {
return true
} else {
return false
}
}
/**
* 比较时间是否相等
*/
dateEqual(before, after) {
// 计算截止时间
before = new Date(before.replace('-', '/').replace('-', '/'))
// 计算详细项的截止时间
after = new Date(after.replace('-', '/').replace('-', '/'))
if (before.getTime() - after.getTime() === 0) {
return true
} else {
return false
}
}
/**
* 获取日期范围内所有日期
* @param {Object} begin
* @param {Object} end
*/
geDateAll(begin, end) {
var arr = []
var ab = begin.split('-')
var ae = end.split('-')
var db = new Date()
db.setFullYear(ab[0], ab[1] - 1, ab[2])
var de = new Date()
de.setFullYear(ae[0], ae[1] - 1, ae[2])
var unixDb = db.getTime() - 24 * 60 * 60 * 1000
var unixDe = de.getTime() - 24 * 60 * 60 * 1000
for (var k = unixDb; k <= unixDe;) {
k = k + 24 * 60 * 60 * 1000
arr.push(this.getDate(new Date(parseInt(k))).fullDate)
}
return arr
}
/**
* 计算阴历日期显示
*/
getlunar(year, month, date) {
return CALENDAR.solar2lunar(year, month, date)
}
/**
* 设置打点
*/
setSelectInfo(data, value) {
this.selected = value
this._getWeek(data)
}
/**
* 获取多选状态
*/
setMultiple(fullDate) {
let {
before,
after
} = this.multipleStatus
if (!this.range) return
if (before && after) {
this.multipleStatus.before = ''
this.multipleStatus.after = ''
this.multipleStatus.data = []
} else {
if (!before) {
this.multipleStatus.before = fullDate
} else {
this.multipleStatus.after = fullDate
if (this.dateCompare(this.multipleStatus.before, this.multipleStatus.after)) {
this.multipleStatus.data = this.geDateAll(this.multipleStatus.before, this.multipleStatus.after);
} else {
this.multipleStatus.data = this.geDateAll(this.multipleStatus.after, this.multipleStatus.before);
}
}
}
this._getWeek(fullDate)
}
/**
* 获取每周数据
* @param {Object} dateData
*/
_getWeek(dateData) {
const {
year,
month
} = this.getDate(dateData)
let firstDay = new Date(year, month - 1, 1).getDay()
let currentDay = new Date(year, month, 0).getDate()
let dates = {
lastMonthDays: this._getLastMonthDays(firstDay, this.getDate(dateData)), // 上个月末尾几天
currentMonthDys: this._currentMonthDys(currentDay, this.getDate(dateData)), // 本月天数
nextMonthDays: [], // 下个月开始几天
weeks: []
}
let canlender = []
const surplus = 42 - (dates.lastMonthDays.length + dates.currentMonthDys.length)
dates.nextMonthDays = this._getNextMonthDays(surplus, this.getDate(dateData))
canlender = canlender.concat(dates.lastMonthDays, dates.currentMonthDys, dates.nextMonthDays)
let weeks = {}
// 拼接数组 上个月开始几天 + 本月天数+ 下个月开始几天
for (let i = 0; i < canlender.length; i++) {
if (i % 7 === 0) {
weeks[parseInt(i / 7)] = new Array(7)
}
weeks[parseInt(i / 7)][i % 7] = canlender[i]
}
this.canlender = canlender
this.weeks = weeks
}
//静态方法
// static init(date) {
// if (!this.instance) {
// this.instance = new Calendar(date);
// }
// return this.instance;
// }
}
export default Calendar
|
2301_77169380/aionix-2
|
uni_modules/uni-calendar/components/uni-calendar/util.js
|
JavaScript
|
mit
| 8,931
|
<template>
<view class="uni-card" :class="{ 'uni-card--full': isFull, 'uni-card--shadow': isShadow,'uni-card--border':border}"
:style="{'margin':isFull?0:margin,'padding':spacing,'box-shadow':isShadow?shadow:''}">
<!-- 封面 -->
<slot name="cover">
<view v-if="cover" class="uni-card__cover">
<image class="uni-card__cover-image" mode="widthFix" @click="onClick('cover')" :src="cover"></image>
</view>
</slot>
<slot name="title">
<view v-if="title || extra" class="uni-card__header">
<!-- 卡片标题 -->
<view class="uni-card__header-box" @click="onClick('title')">
<view v-if="thumbnail" class="uni-card__header-avatar">
<image class="uni-card__header-avatar-image" :src="thumbnail" mode="aspectFit" />
</view>
<view class="uni-card__header-content">
<text class="uni-card__header-content-title uni-ellipsis">{{ title }}</text>
<text v-if="title&&subTitle"
class="uni-card__header-content-subtitle uni-ellipsis">{{ subTitle }}</text>
</view>
</view>
<view class="uni-card__header-extra" @click="onClick('extra')">
<text class="uni-card__header-extra-text">{{ extra }}</text>
</view>
</view>
</slot>
<!-- 卡片内容 -->
<view class="uni-card__content" :style="{padding:padding}" @click="onClick('content')">
<slot></slot>
</view>
<view class="uni-card__actions" @click="onClick('actions')">
<slot name="actions"></slot>
</view>
</view>
</template>
<script>
/**
* Card 卡片
* @description 卡片视图组件
* @tutorial https://ext.dcloud.net.cn/plugin?id=22
* @property {String} title 标题文字
* @property {String} subTitle 副标题
* @property {Number} padding 内容内边距
* @property {Number} margin 卡片外边距
* @property {Number} spacing 卡片内边距
* @property {String} extra 标题额外信息
* @property {String} cover 封面图(本地路径需要引入)
* @property {String} thumbnail 标题左侧缩略图
* @property {Boolean} is-full = [true | false] 卡片内容是否通栏,为 true 时将去除padding值
* @property {Boolean} is-shadow = [true | false] 卡片内容是否开启阴影
* @property {String} shadow 卡片阴影
* @property {Boolean} border 卡片边框
* @event {Function} click 点击 Card 触发事件
*/
export default {
name: 'UniCard',
emits: ['click'],
props: {
title: {
type: String,
default: ''
},
subTitle: {
type: String,
default: ''
},
padding: {
type: String,
default: '10px'
},
margin: {
type: String,
default: '15px'
},
spacing: {
type: String,
default: '0 10px'
},
extra: {
type: String,
default: ''
},
cover: {
type: String,
default: ''
},
thumbnail: {
type: String,
default: ''
},
isFull: {
// 内容区域是否通栏
type: Boolean,
default: false
},
isShadow: {
// 是否开启阴影
type: Boolean,
default: true
},
shadow: {
type: String,
default: '0px 0px 3px 1px rgba(0, 0, 0, 0.08)'
},
border: {
type: Boolean,
default: true
}
},
methods: {
onClick(type) {
this.$emit('click', type)
}
}
}
</script>
<style lang="scss">
$uni-border-3: #EBEEF5 !default;
$uni-shadow-base:0 0px 6px 1px rgba($color: #a5a5a5, $alpha: 0.2) !default;
$uni-main-color: #3a3a3a !default;
$uni-base-color: #6a6a6a !default;
$uni-secondary-color: #909399 !default;
$uni-spacing-sm: 8px !default;
$uni-border-color:$uni-border-3;
$uni-shadow: $uni-shadow-base;
$uni-card-title: 15px;
$uni-cart-title-color:$uni-main-color;
$uni-card-subtitle: 12px;
$uni-cart-subtitle-color:$uni-secondary-color;
$uni-card-spacing: 10px;
$uni-card-content-color: $uni-base-color;
.uni-card {
margin: $uni-card-spacing;
padding: 0 $uni-spacing-sm;
border-radius: 4px;
overflow: hidden;
font-family: Helvetica Neue, Helvetica, PingFang SC, Hiragino Sans GB, Microsoft YaHei, SimSun, sans-serif;
background-color: #fff;
flex: 1;
.uni-card__cover {
position: relative;
margin-top: $uni-card-spacing;
flex-direction: row;
overflow: hidden;
border-radius: 4px;
.uni-card__cover-image {
flex: 1;
// width: 100%;
/* #ifndef APP-PLUS */
vertical-align: middle;
/* #endif */
}
}
.uni-card__header {
display: flex;
border-bottom: 1px $uni-border-color solid;
flex-direction: row;
align-items: center;
padding: $uni-card-spacing;
overflow: hidden;
.uni-card__header-box {
/* #ifndef APP-NVUE */
display: flex;
/* #endif */
flex: 1;
flex-direction: row;
align-items: center;
overflow: hidden;
}
.uni-card__header-avatar {
width: 40px;
height: 40px;
overflow: hidden;
border-radius: 5px;
margin-right: $uni-card-spacing;
.uni-card__header-avatar-image {
flex: 1;
width: 40px;
height: 40px;
}
}
.uni-card__header-content {
/* #ifndef APP-NVUE */
display: flex;
/* #endif */
flex-direction: column;
justify-content: center;
flex: 1;
// height: 40px;
overflow: hidden;
.uni-card__header-content-title {
font-size: $uni-card-title;
color: $uni-cart-title-color;
// line-height: 22px;
}
.uni-card__header-content-subtitle {
font-size: $uni-card-subtitle;
margin-top: 5px;
color: $uni-cart-subtitle-color;
}
}
.uni-card__header-extra {
line-height: 12px;
.uni-card__header-extra-text {
font-size: 12px;
color: $uni-cart-subtitle-color;
}
}
}
.uni-card__content {
padding: $uni-card-spacing;
font-size: 14px;
color: $uni-card-content-color;
line-height: 22px;
}
.uni-card__actions {
font-size: 12px;
}
}
.uni-card--border {
border: 1px solid $uni-border-color;
}
.uni-card--shadow {
position: relative;
/* #ifndef APP-NVUE */
box-shadow: $uni-shadow;
/* #endif */
}
.uni-card--full {
margin: 0;
border-left-width: 0;
border-left-width: 0;
border-radius: 0;
}
/* #ifndef APP-NVUE */
.uni-card--full:after {
border-radius: 0;
}
/* #endif */
.uni-ellipsis {
/* #ifndef APP-NVUE */
overflow: hidden;
white-space: nowrap;
text-overflow: ellipsis;
/* #endif */
/* #ifdef APP-NVUE */
lines: 1;
/* #endif */
}
</style>
|
2301_77169380/aionix-2
|
uni_modules/uni-card/components/uni-card/uni-card.vue
|
Vue
|
mit
| 6,362
|
<template>
<view class="uni-collapse">
<slot />
</view>
</template>
<script>
/**
* Collapse 折叠面板
* @description 展示可以折叠 / 展开的内容区域
* @tutorial https://ext.dcloud.net.cn/plugin?id=23
* @property {String|Array} value 当前激活面板改变时触发(如果是手风琴模式,参数类型为string,否则为array)
* @property {Boolean} accordion = [true|false] 是否开启手风琴效果是否开启手风琴效果
* @event {Function} change 切换面板时触发,如果是手风琴模式,返回类型为string,否则为array
*/
export default {
name: 'uniCollapse',
emits:['change','activeItem','input','update:modelValue'],
props: {
value: {
type: [String, Array],
default: ''
},
modelValue: {
type: [String, Array],
default: ''
},
accordion: {
// 是否开启手风琴效果
type: [Boolean, String],
default: false
},
},
data() {
return {}
},
computed: {
// TODO 兼容 vue2 和 vue3
dataValue() {
let value = (typeof this.value === 'string' && this.value === '') ||
(Array.isArray(this.value) && this.value.length === 0)
let modelValue = (typeof this.modelValue === 'string' && this.modelValue === '') ||
(Array.isArray(this.modelValue) && this.modelValue.length === 0)
if (value) {
return this.modelValue
}
if (modelValue) {
return this.value
}
return this.value
}
},
watch: {
dataValue(val) {
this.setOpen(val)
}
},
created() {
this.childrens = []
this.names = []
},
mounted() {
this.$nextTick(()=>{
this.setOpen(this.dataValue)
})
},
methods: {
setOpen(val) {
let str = typeof val === 'string'
let arr = Array.isArray(val)
this.childrens.forEach((vm, index) => {
if (str) {
if (val === vm.nameSync) {
if (!this.accordion) {
console.warn('accordion 属性为 false ,v-model 类型应该为 array')
return
}
vm.isOpen = true
}
}
if (arr) {
val.forEach(v => {
if (v === vm.nameSync) {
if (this.accordion) {
console.warn('accordion 属性为 true ,v-model 类型应该为 string')
return
}
vm.isOpen = true
}
})
}
})
this.emit(val)
},
setAccordion(self) {
if (!this.accordion) return
this.childrens.forEach((vm, index) => {
if (self !== vm) {
vm.isOpen = false
}
})
},
resize() {
this.childrens.forEach((vm, index) => {
// #ifndef APP-NVUE
vm.getCollapseHeight()
// #endif
// #ifdef APP-NVUE
vm.getNvueHwight()
// #endif
})
},
onChange(isOpen, self) {
let activeItem = []
if (this.accordion) {
activeItem = isOpen ? self.nameSync : ''
} else {
this.childrens.forEach((vm, index) => {
if (vm.isOpen) {
activeItem.push(vm.nameSync)
}
})
}
this.$emit('change', activeItem)
this.emit(activeItem)
},
emit(val){
this.$emit('input', val)
this.$emit('update:modelValue', val)
}
}
}
</script>
<style lang="scss" >
.uni-collapse {
/* #ifndef APP-NVUE */
width: 100%;
display: flex;
/* #endif */
/* #ifdef APP-NVUE */
flex: 1;
/* #endif */
flex-direction: column;
background-color: #fff;
}
</style>
|
2301_77169380/aionix-2
|
uni_modules/uni-collapse/components/uni-collapse/uni-collapse.vue
|
Vue
|
mit
| 3,358
|
<template>
<view class="uni-collapse-item">
<!-- onClick(!isOpen) -->
<view @click="onClick(!isOpen)" class="uni-collapse-item__title"
:class="{'is-open':isOpen &&titleBorder === 'auto' ,'uni-collapse-item-border':titleBorder !== 'none'}">
<view class="uni-collapse-item__title-wrap">
<slot name="title">
<view class="uni-collapse-item__title-box" :class="{'is-disabled':disabled}">
<image v-if="thumb" :src="thumb" class="uni-collapse-item__title-img" />
<text class="uni-collapse-item__title-text">{{ title }}</text>
</view>
</slot>
</view>
<view v-if="showArrow"
:class="{ 'uni-collapse-item__title-arrow-active': isOpen, 'uni-collapse-item--animation': showAnimation === true }"
class="uni-collapse-item__title-arrow">
<uni-icons :color="disabled?'#ddd':'#bbb'" size="14" type="bottom" />
</view>
</view>
<view class="uni-collapse-item__wrap" :class="{'is--transition':showAnimation}"
:style="{height: (isOpen?height:0) +'px'}">
<view :id="elId" ref="collapse--hook" class="uni-collapse-item__wrap-content"
:class="{open:isheight,'uni-collapse-item--border':border&&isOpen}">
<slot></slot>
</view>
</view>
</view>
</template>
<script>
// #ifdef APP-NVUE
const dom = weex.requireModule('dom')
// #endif
/**
* CollapseItem 折叠面板子组件
* @description 折叠面板子组件
* @property {String} title 标题文字
* @property {String} thumb 标题左侧缩略图
* @property {String} name 唯一标志符
* @property {Boolean} open = [true|false] 是否展开组件
* @property {Boolean} titleBorder = [true|false] 是否显示标题分隔线
* @property {String} border = ['auto'|'show'|'none'] 是否显示分隔线
* @property {Boolean} disabled = [true|false] 是否展开面板
* @property {Boolean} showAnimation = [true|false] 开启动画
* @property {Boolean} showArrow = [true|false] 是否显示右侧箭头
*/
export default {
name: 'uniCollapseItem',
props: {
// 列表标题
title: {
type: String,
default: ''
},
name: {
type: [Number, String],
default: ''
},
// 是否禁用
disabled: {
type: Boolean,
default: false
},
// #ifdef APP-PLUS
// 是否显示动画,app 端默认不开启动画,卡顿严重
showAnimation: {
type: Boolean,
default: false
},
// #endif
// #ifndef APP-PLUS
// 是否显示动画
showAnimation: {
type: Boolean,
default: true
},
// #endif
// 是否展开
open: {
type: Boolean,
default: false
},
// 缩略图
thumb: {
type: String,
default: ''
},
// 标题分隔线显示类型
titleBorder: {
type: String,
default: 'auto'
},
border: {
type: Boolean,
default: true
},
showArrow: {
type: Boolean,
default: true
}
},
data() {
// TODO 随机生生元素ID,解决百度小程序获取同一个元素位置信息的bug
const elId = `Uni_${Math.ceil(Math.random() * 10e5).toString(36)}`
return {
isOpen: false,
isheight: null,
height: 0,
elId,
nameSync: 0
}
},
watch: {
open(val) {
this.isOpen = val
this.onClick(val, 'init')
}
},
updated(e) {
this.$nextTick(() => {
this.init(true)
})
},
created() {
this.collapse = this.getCollapse()
this.oldHeight = 0
this.onClick(this.open, 'init')
},
// #ifndef VUE3
// TODO vue2
destroyed() {
if (this.__isUnmounted) return
this.uninstall()
},
// #endif
// #ifdef VUE3
// TODO vue3
unmounted() {
this.__isUnmounted = true
this.uninstall()
},
// #endif
mounted() {
if (!this.collapse) return
if (this.name !== '') {
this.nameSync = this.name
} else {
this.nameSync = this.collapse.childrens.length + ''
}
if (this.collapse.names.indexOf(this.nameSync) === -1) {
this.collapse.names.push(this.nameSync)
} else {
console.warn(`name 值 ${this.nameSync} 重复`);
}
if (this.collapse.childrens.indexOf(this) === -1) {
this.collapse.childrens.push(this)
}
this.init()
},
methods: {
init(type) {
// #ifndef APP-NVUE
this.getCollapseHeight(type)
// #endif
// #ifdef APP-NVUE
this.getNvueHwight(type)
// #endif
},
uninstall() {
if (this.collapse) {
this.collapse.childrens.forEach((item, index) => {
if (item === this) {
this.collapse.childrens.splice(index, 1)
}
})
this.collapse.names.forEach((item, index) => {
if (item === this.nameSync) {
this.collapse.names.splice(index, 1)
}
})
}
},
onClick(isOpen, type) {
if (this.disabled) return
this.isOpen = isOpen
if (this.isOpen && this.collapse) {
this.collapse.setAccordion(this)
}
if (type !== 'init') {
this.collapse.onChange(isOpen, this)
}
},
getCollapseHeight(type, index = 0) {
const views = uni.createSelectorQuery().in(this)
views
.select(`#${this.elId}`)
.fields({
size: true
}, data => {
// TODO 百度中可能获取不到节点信息 ,需要循环获取
if (index >= 10) return
if (!data) {
index++
this.getCollapseHeight(false, index)
return
}
// #ifdef APP-NVUE
this.height = data.height + 1
// #endif
// #ifndef APP-NVUE
this.height = data.height
// #endif
this.isheight = true
if (type) return
this.onClick(this.isOpen, 'init')
})
.exec()
},
getNvueHwight(type) {
const result = dom.getComponentRect(this.$refs['collapse--hook'], option => {
if (option && option.result && option.size) {
// #ifdef APP-NVUE
this.height = option.size.height + 1
// #endif
// #ifndef APP-NVUE
this.height = option.size.height
// #endif
this.isheight = true
if (type) return
this.onClick(this.open, 'init')
}
})
},
/**
* 获取父元素实例
*/
getCollapse(name = 'uniCollapse') {
let parent = this.$parent;
let parentName = parent.$options.name;
while (parentName !== name) {
parent = parent.$parent;
if (!parent) return false;
parentName = parent.$options.name;
}
return parent;
}
}
}
</script>
<style lang="scss">
.uni-collapse-item {
/* #ifndef APP-NVUE */
box-sizing: border-box;
/* #endif */
&__title {
/* #ifndef APP-NVUE */
display: flex;
width: 100%;
box-sizing: border-box;
/* #endif */
flex-direction: row;
align-items: center;
transition: border-bottom-color .3s;
// transition-property: border-bottom-color;
// transition-duration: 5s;
&-wrap {
width: 100%;
flex: 1;
}
&-box {
padding: 0 15px;
/* #ifndef APP-NVUE */
display: flex;
width: 100%;
box-sizing: border-box;
/* #endif */
flex-direction: row;
justify-content: space-between;
align-items: center;
height: 48px;
line-height: 48px;
background-color: #fff;
color: #303133;
font-size: 13px;
font-weight: 500;
/* #ifdef H5 */
cursor: pointer;
outline: none;
/* #endif */
&.is-disabled {
.uni-collapse-item__title-text {
color: #999;
}
}
}
&.uni-collapse-item-border {
border-bottom: 1px solid #ebeef5;
}
&.is-open {
border-bottom-color: transparent;
}
&-img {
height: 22px;
width: 22px;
margin-right: 10px;
}
&-text {
flex: 1;
font-size: 14px;
/* #ifndef APP-NVUE */
white-space: nowrap;
color: inherit;
/* #endif */
/* #ifdef APP-NVUE */
lines: 1;
/* #endif */
overflow: hidden;
text-overflow: ellipsis;
}
&-arrow {
/* #ifndef APP-NVUE */
display: flex;
box-sizing: border-box;
/* #endif */
align-items: center;
justify-content: center;
width: 20px;
height: 20px;
margin-right: 10px;
transform: rotate(0deg);
&-active {
transform: rotate(-180deg);
}
}
}
&__wrap {
/* #ifndef APP-NVUE */
will-change: height;
box-sizing: border-box;
/* #endif */
background-color: #fff;
overflow: hidden;
position: relative;
height: 0;
&.is--transition {
// transition: all 0.3s;
transition-property: height, border-bottom-width;
transition-duration: 0.3s;
/* #ifndef APP-NVUE */
will-change: height;
/* #endif */
}
&-content {
position: absolute;
font-size: 13px;
color: #303133;
// transition: height 0.3s;
border-bottom-color: transparent;
border-bottom-style: solid;
border-bottom-width: 0;
&.uni-collapse-item--border {
border-bottom-width: 1px;
border-bottom-color: red;
border-bottom-color: #ebeef5;
}
&.open {
position: relative;
}
}
}
&--animation {
transition-property: transform;
transition-duration: 0.3s;
transition-timing-function: ease;
}
}
</style>
|
2301_77169380/aionix-2
|
uni_modules/uni-collapse/components/uni-collapse-item/uni-collapse-item.vue
|
Vue
|
mit
| 9,003
|
<template>
<view class="uni-combox" :class="border ? '' : 'uni-combox__no-border'">
<view v-if="label" class="uni-combox__label" :style="labelStyle">
<text>{{label}}</text>
</view>
<view class="uni-combox__input-box">
<input class="uni-combox__input" type="text" :placeholder="placeholder"
placeholder-class="uni-combox__input-plac" v-model="inputVal" @input="onInput" @focus="onFocus"
@blur="onBlur" />
<uni-icons :type="showSelector? 'top' : 'bottom'" size="14" color="#999" @click="toggleSelector">
</uni-icons>
</view>
<view class="uni-combox__selector" v-if="showSelector">
<view class="uni-popper__arrow"></view>
<scroll-view scroll-y="true" class="uni-combox__selector-scroll">
<view class="uni-combox__selector-empty" v-if="filterCandidatesLength === 0">
<text>{{emptyTips}}</text>
</view>
<view class="uni-combox__selector-item" v-for="(item,index) in filterCandidates" :key="index"
@click="onSelectorClick(index)">
<text>{{item}}</text>
</view>
</scroll-view>
</view>
</view>
</template>
<script>
/**
* Combox 组合输入框
* @description 组合输入框一般用于既可以输入也可以选择的场景
* @tutorial https://ext.dcloud.net.cn/plugin?id=1261
* @property {String} label 左侧文字
* @property {String} labelWidth 左侧内容宽度
* @property {String} placeholder 输入框占位符
* @property {Array} candidates 候选项列表
* @property {String} emptyTips 筛选结果为空时显示的文字
* @property {String} value 组合框的值
*/
export default {
name: 'uniCombox',
emits: ['input', 'update:modelValue'],
props: {
border: {
type: Boolean,
default: true
},
label: {
type: String,
default: ''
},
labelWidth: {
type: String,
default: 'auto'
},
placeholder: {
type: String,
default: ''
},
candidates: {
type: Array,
default () {
return []
}
},
emptyTips: {
type: String,
default: '无匹配项'
},
// #ifndef VUE3
value: {
type: [String, Number],
default: ''
},
// #endif
// #ifdef VUE3
modelValue: {
type: [String, Number],
default: ''
},
// #endif
},
data() {
return {
showSelector: false,
inputVal: ''
}
},
computed: {
labelStyle() {
if (this.labelWidth === 'auto') {
return ""
}
return `width: ${this.labelWidth}`
},
filterCandidates() {
return this.candidates.filter((item) => {
return item.toString().indexOf(this.inputVal) > -1
})
},
filterCandidatesLength() {
return this.filterCandidates.length
}
},
watch: {
// #ifndef VUE3
value: {
handler(newVal) {
this.inputVal = newVal
},
immediate: true
},
// #endif
// #ifdef VUE3
modelValue: {
handler(newVal) {
this.inputVal = newVal
},
immediate: true
},
// #endif
},
methods: {
toggleSelector() {
this.showSelector = !this.showSelector
},
onFocus() {
this.showSelector = true
},
onBlur() {
setTimeout(() => {
this.showSelector = false
}, 153)
},
onSelectorClick(index) {
this.inputVal = this.filterCandidates[index]
this.showSelector = false
this.$emit('input', this.inputVal)
this.$emit('update:modelValue', this.inputVal)
},
onInput() {
setTimeout(() => {
this.$emit('input', this.inputVal)
this.$emit('update:modelValue', this.inputVal)
})
}
}
}
</script>
<style lang="scss" scoped>
.uni-combox {
font-size: 14px;
border: 1px solid #DCDFE6;
border-radius: 4px;
padding: 6px 10px;
position: relative;
/* #ifndef APP-NVUE */
display: flex;
/* #endif */
// height: 40px;
flex-direction: row;
align-items: center;
// border-bottom: solid 1px #DDDDDD;
}
.uni-combox__label {
font-size: 16px;
line-height: 22px;
padding-right: 10px;
color: #999999;
}
.uni-combox__input-box {
position: relative;
/* #ifndef APP-NVUE */
display: flex;
/* #endif */
flex: 1;
flex-direction: row;
align-items: center;
}
.uni-combox__input {
flex: 1;
font-size: 14px;
height: 22px;
line-height: 22px;
}
.uni-combox__input-plac {
font-size: 14px;
color: #999;
}
.uni-combox__selector {
/* #ifndef APP-NVUE */
box-sizing: border-box;
/* #endif */
position: absolute;
top: calc(100% + 12px);
left: 0;
width: 100%;
background-color: #FFFFFF;
border: 1px solid #EBEEF5;
border-radius: 6px;
box-shadow: 0 2px 12px 0 rgba(0, 0, 0, 0.1);
z-index: 2;
padding: 4px 0;
}
.uni-combox__selector-scroll {
/* #ifndef APP-NVUE */
max-height: 200px;
box-sizing: border-box;
/* #endif */
}
.uni-combox__selector-empty,
.uni-combox__selector-item {
/* #ifndef APP-NVUE */
display: flex;
cursor: pointer;
/* #endif */
line-height: 36px;
font-size: 14px;
text-align: center;
// border-bottom: solid 1px #DDDDDD;
padding: 0px 10px;
}
.uni-combox__selector-item:hover {
background-color: #f9f9f9;
}
.uni-combox__selector-empty:last-child,
.uni-combox__selector-item:last-child {
/* #ifndef APP-NVUE */
border-bottom: none;
/* #endif */
}
// picker 弹出层通用的指示小三角
.uni-popper__arrow,
.uni-popper__arrow::after {
position: absolute;
display: block;
width: 0;
height: 0;
border-color: transparent;
border-style: solid;
border-width: 6px;
}
.uni-popper__arrow {
filter: drop-shadow(0 2px 12px rgba(0, 0, 0, 0.03));
top: -6px;
left: 10%;
margin-right: 3px;
border-top-width: 0;
border-bottom-color: #EBEEF5;
}
.uni-popper__arrow::after {
content: " ";
top: 1px;
margin-left: -6px;
border-top-width: 0;
border-bottom-color: #fff;
}
.uni-combox__no-border {
border: none;
}
</style>
|
2301_77169380/aionix-2
|
uni_modules/uni-combox/components/uni-combox/uni-combox.vue
|
Vue
|
mit
| 5,806
|
import en from './en.json'
import zhHans from './zh-Hans.json'
import zhHant from './zh-Hant.json'
export default {
en,
'zh-Hans': zhHans,
'zh-Hant': zhHant
}
|
2301_77169380/aionix-2
|
uni_modules/uni-countdown/components/uni-countdown/i18n/index.js
|
JavaScript
|
mit
| 162
|
<template>
<view class="uni-countdown">
<text v-if="showDay" :style="[timeStyle]" class="uni-countdown__number">{{ d }}</text>
<text v-if="showDay" :style="[splitorStyle]" class="uni-countdown__splitor">{{dayText}}</text>
<text v-if="showHour" :style="[timeStyle]" class="uni-countdown__number">{{ h }}</text>
<text v-if="showHour" :style="[splitorStyle]" class="uni-countdown__splitor">{{ showColon ? ':' : hourText }}</text>
<text v-if="showMinute" :style="[timeStyle]" class="uni-countdown__number">{{ i }}</text>
<text v-if="showMinute" :style="[splitorStyle]" class="uni-countdown__splitor">{{ showColon ? ':' : minuteText }}</text>
<text :style="[timeStyle]" class="uni-countdown__number">{{ s }}</text>
<text v-if="!showColon" :style="[splitorStyle]" class="uni-countdown__splitor">{{secondText}}</text>
</view>
</template>
<script>
import {
initVueI18n
} from '@dcloudio/uni-i18n'
import messages from './i18n/index.js'
const {
t
} = initVueI18n(messages)
/**
* Countdown 倒计时
* @description 倒计时组件
* @tutorial https://ext.dcloud.net.cn/plugin?id=25
* @property {String} backgroundColor 背景色
* @property {String} color 文字颜色
* @property {Number} day 天数
* @property {Number} hour 小时
* @property {Number} minute 分钟
* @property {Number} second 秒
* @property {Number} timestamp 时间戳
* @property {Boolean} showDay = [true|false] 是否显示天数
* @property {Boolean} showHour = [true|false] 是否显示小时
* @property {Boolean} showMinute = [true|false] 是否显示分钟
* @property {Boolean} show-colon = [true|false] 是否以冒号为分隔符
* @property {String} splitorColor 分割符号颜色
* @event {Function} timeup 倒计时时间到触发事件
* @example <uni-countdown :day="1" :hour="1" :minute="12" :second="40"></uni-countdown>
*/
export default {
name: 'UniCountdown',
emits: ['timeup'],
props: {
showDay: {
type: Boolean,
default: true
},
showHour: {
type: Boolean,
default: true
},
showMinute: {
type: Boolean,
default: true
},
showColon: {
type: Boolean,
default: true
},
start: {
type: Boolean,
default: true
},
backgroundColor: {
type: String,
default: ''
},
color: {
type: String,
default: '#333'
},
fontSize: {
type: Number,
default: 14
},
splitorColor: {
type: String,
default: '#333'
},
day: {
type: Number,
default: 0
},
hour: {
type: Number,
default: 0
},
minute: {
type: Number,
default: 0
},
second: {
type: Number,
default: 0
},
timestamp: {
type: Number,
default: 0
}
},
data() {
return {
timer: null,
syncFlag: false,
d: '00',
h: '00',
i: '00',
s: '00',
leftTime: 0,
seconds: 0
}
},
computed: {
dayText() {
return t("uni-countdown.day")
},
hourText(val) {
return t("uni-countdown.h")
},
minuteText(val) {
return t("uni-countdown.m")
},
secondText(val) {
return t("uni-countdown.s")
},
timeStyle() {
const {
color,
backgroundColor,
fontSize
} = this
return {
color,
backgroundColor,
fontSize: `${fontSize}px`,
width: `${fontSize * 22 / 14}px`, // 按字体大小为 14px 时的比例缩放
lineHeight: `${fontSize * 20 / 14}px`,
borderRadius: `${fontSize * 3 / 14}px`,
}
},
splitorStyle() {
const { splitorColor, fontSize, backgroundColor } = this
return {
color: splitorColor,
fontSize: `${fontSize * 12 / 14}px`,
margin: backgroundColor ? `${fontSize * 4 / 14}px` : ''
}
}
},
watch: {
day(val) {
this.changeFlag()
},
hour(val) {
this.changeFlag()
},
minute(val) {
this.changeFlag()
},
second(val) {
this.changeFlag()
},
start: {
immediate: true,
handler(newVal, oldVal) {
if (newVal) {
this.startData();
} else {
if (!oldVal) return
clearInterval(this.timer)
}
}
}
},
created: function(e) {
this.seconds = this.toSeconds(this.timestamp, this.day, this.hour, this.minute, this.second)
this.countDown()
},
// #ifndef VUE3
destroyed() {
clearInterval(this.timer)
},
// #endif
// #ifdef VUE3
unmounted() {
clearInterval(this.timer)
},
// #endif
methods: {
toSeconds(timestamp, day, hours, minutes, seconds) {
if (timestamp) {
return timestamp - parseInt(new Date().getTime() / 1000, 10)
}
return day * 60 * 60 * 24 + hours * 60 * 60 + minutes * 60 + seconds
},
timeUp() {
clearInterval(this.timer)
this.$emit('timeup')
},
countDown() {
let seconds = this.seconds
let [day, hour, minute, second] = [0, 0, 0, 0]
if (seconds > 0) {
day = Math.floor(seconds / (60 * 60 * 24))
hour = Math.floor(seconds / (60 * 60)) - (day * 24)
minute = Math.floor(seconds / 60) - (day * 24 * 60) - (hour * 60)
second = Math.floor(seconds) - (day * 24 * 60 * 60) - (hour * 60 * 60) - (minute * 60)
} else {
this.timeUp()
}
if (day < 10) {
day = '0' + day
}
if (hour < 10) {
hour = '0' + hour
}
if (minute < 10) {
minute = '0' + minute
}
if (second < 10) {
second = '0' + second
}
this.d = day
this.h = hour
this.i = minute
this.s = second
},
startData() {
this.seconds = this.toSeconds(this.timestamp, this.day, this.hour, this.minute, this.second)
if (this.seconds <= 0) {
this.seconds = this.toSeconds(0, 0, 0, 0, 0)
this.countDown()
return
}
clearInterval(this.timer)
this.countDown()
this.timer = setInterval(() => {
this.seconds--
if (this.seconds < 0) {
this.timeUp()
return
}
this.countDown()
}, 1000)
},
update(){
this.startData();
},
changeFlag() {
if (!this.syncFlag) {
this.seconds = this.toSeconds(this.timestamp, this.day, this.hour, this.minute, this.second)
this.startData();
this.syncFlag = true;
}
}
}
}
</script>
<style lang="scss" scoped>
$font-size: 14px;
.uni-countdown {
display: flex;
flex-direction: row;
justify-content: flex-start;
align-items: center;
&__splitor {
margin: 0 2px;
font-size: $font-size;
color: #333;
}
&__number {
border-radius: 3px;
text-align: center;
font-size: $font-size;
}
}
</style>
|
2301_77169380/aionix-2
|
uni_modules/uni-countdown/components/uni-countdown/uni-countdown.vue
|
Vue
|
mit
| 6,506
|
<template>
<view class="uni-data-checklist" :style="{'margin-top':isTop+'px'}">
<template v-if="!isLocal">
<view class="uni-data-loading">
<uni-load-more v-if="!mixinDatacomErrorMessage" status="loading" iconType="snow" :iconSize="18"
:content-text="contentText"></uni-load-more>
<text v-else>{{mixinDatacomErrorMessage}}</text>
</view>
</template>
<template v-else>
<checkbox-group v-if="multiple" class="checklist-group" :class="{'is-list':mode==='list' || wrap}"
@change="change">
<label class="checklist-box"
:class="['is--'+mode,item.selected?'is-checked':'',(disabled || !!item.disabled)?'is-disable':'',index!==0&&mode==='list'?'is-list-border':'']"
:style="item.styleBackgroud" v-for="(item,index) in dataList" :key="index">
<checkbox class="hidden" hidden :disabled="disabled || !!item.disabled" :value="item[map.value]+''"
:checked="item.selected" />
<view v-if="(mode !=='tag' && mode !== 'list') || ( mode === 'list' && icon === 'left')"
class="checkbox__inner" :style="item.styleIcon">
<view class="checkbox__inner-icon"></view>
</view>
<view class="checklist-content" :class="{'list-content':mode === 'list' && icon ==='left'}">
<text class="checklist-text" :style="item.styleIconText">{{item[map.text]}}</text>
<view v-if="mode === 'list' && icon === 'right'" class="checkobx__list" :style="item.styleBackgroud"></view>
</view>
</label>
</checkbox-group>
<radio-group v-else class="checklist-group" :class="{'is-list':mode==='list','is-wrap':wrap}" @change="change">
<label class="checklist-box"
:class="['is--'+mode,item.selected?'is-checked':'',(disabled || !!item.disabled)?'is-disable':'',index!==0&&mode==='list'?'is-list-border':'']"
:style="item.styleBackgroud" v-for="(item,index) in dataList" :key="index">
<radio class="hidden" hidden :disabled="disabled || item.disabled" :value="item[map.value]+''"
:checked="item.selected" />
<view v-if="(mode !=='tag' && mode !== 'list') || ( mode === 'list' && icon === 'left')" class="radio__inner"
:style="item.styleBackgroud">
<view class="radio__inner-icon" :style="item.styleIcon"></view>
</view>
<view class="checklist-content" :class="{'list-content':mode === 'list' && icon ==='left'}">
<text class="checklist-text" :style="item.styleIconText">{{item[map.text]}}</text>
<view v-if="mode === 'list' && icon === 'right'" :style="item.styleRightIcon" class="checkobx__list"></view>
</view>
</label>
</radio-group>
</template>
</view>
</template>
<script>
/**
* DataChecklist 数据选择器
* @description 通过数据渲染 checkbox 和 radio
* @tutorial https://ext.dcloud.net.cn/plugin?id=xxx
* @property {String} mode = [default| list | button | tag] 显示模式
* @value default 默认横排模式
* @value list 列表模式
* @value button 按钮模式
* @value tag 标签模式
* @property {Boolean} multiple = [true|false] 是否多选
* @property {Array|String|Number} value 默认值
* @property {Array} localdata 本地数据 ,格式 [{text:'',value:''}]
* @property {Number|String} min 最小选择个数 ,multiple为true时生效
* @property {Number|String} max 最大选择个数 ,multiple为true时生效
* @property {Boolean} wrap 是否换行显示
* @property {String} icon = [left|right] list 列表模式下icon显示位置
* @property {Boolean} selectedColor 选中颜色
* @property {Boolean} emptyText 没有数据时显示的文字 ,本地数据无效
* @property {Boolean} selectedTextColor 选中文本颜色,如不填写则自动显示
* @property {Object} map 字段映射, 默认 map={text:'text',value:'value'}
* @value left 左侧显示
* @value right 右侧显示
* @event {Function} change 选中发生变化触发
*/
export default {
name: 'uniDataChecklist',
mixins: [uniCloud.mixinDatacom || {}],
emits: ['input', 'update:modelValue', 'change'],
props: {
mode: {
type: String,
default: 'default'
},
multiple: {
type: Boolean,
default: false
},
value: {
type: [Array, String, Number],
default () {
return ''
}
},
// TODO vue3
modelValue: {
type: [Array, String, Number],
default () {
return '';
}
},
localdata: {
type: Array,
default () {
return []
}
},
min: {
type: [Number, String],
default: ''
},
max: {
type: [Number, String],
default: ''
},
wrap: {
type: Boolean,
default: false
},
icon: {
type: String,
default: 'left'
},
selectedColor: {
type: String,
default: ''
},
selectedTextColor: {
type: String,
default: ''
},
emptyText: {
type: String,
default: '暂无数据'
},
disabled: {
type: Boolean,
default: false
},
map: {
type: Object,
default () {
return {
text: 'text',
value: 'value'
}
}
}
},
watch: {
localdata: {
handler(newVal) {
this.range = newVal
this.dataList = this.getDataList(this.getSelectedValue(newVal))
},
deep: true
},
mixinDatacomResData(newVal) {
this.range = newVal
this.dataList = this.getDataList(this.getSelectedValue(newVal))
},
value(newVal) {
this.dataList = this.getDataList(newVal)
// fix by mehaotian is_reset 在 uni-forms 中定义
// if(!this.is_reset){
// this.is_reset = false
// this.formItem && this.formItem.setValue(newVal)
// }
},
modelValue(newVal) {
this.dataList = this.getDataList(newVal);
// if(!this.is_reset){
// this.is_reset = false
// this.formItem && this.formItem.setValue(newVal)
// }
}
},
data() {
return {
dataList: [],
range: [],
contentText: {
contentdown: '查看更多',
contentrefresh: '加载中',
contentnomore: '没有更多'
},
isLocal: true,
styles: {
selectedColor: '#2979ff',
selectedTextColor: '#666',
},
isTop: 0
};
},
computed: {
dataValue() {
if (this.value === '') return this.modelValue
if (this.modelValue === '') return this.value
return this.value
}
},
created() {
// this.form = this.getForm('uniForms')
// this.formItem = this.getForm('uniFormsItem')
// this.formItem && this.formItem.setValue(this.value)
// if (this.formItem) {
// this.isTop = 6
// if (this.formItem.name) {
// // 如果存在name添加默认值,否则formData 中不存在这个字段不校验
// if(!this.is_reset){
// this.is_reset = false
// this.formItem.setValue(this.dataValue)
// }
// this.rename = this.formItem.name
// this.form.inputChildrens.push(this)
// }
// }
if (this.localdata && this.localdata.length !== 0) {
this.isLocal = true
this.range = this.localdata
this.dataList = this.getDataList(this.getSelectedValue(this.range))
} else {
if (this.collection) {
this.isLocal = false
this.loadData()
}
}
},
methods: {
loadData() {
this.mixinDatacomGet().then(res => {
this.mixinDatacomResData = res.result.data
if (this.mixinDatacomResData.length === 0) {
this.isLocal = false
this.mixinDatacomErrorMessage = this.emptyText
} else {
this.isLocal = true
}
}).catch(err => {
this.mixinDatacomErrorMessage = err.message
})
},
/**
* 获取父元素实例
*/
getForm(name = 'uniForms') {
let parent = this.$parent;
let parentName = parent.$options.name;
while (parentName !== name) {
parent = parent.$parent;
if (!parent) return false
parentName = parent.$options.name;
}
return parent;
},
change(e) {
const values = e.detail.value
let detail = {
value: [],
data: []
}
if (this.multiple) {
this.range.forEach(item => {
if (values.includes(item[this.map.value] + '')) {
detail.value.push(item[this.map.value])
detail.data.push(item)
}
})
} else {
const range = this.range.find(item => (item[this.map.value] + '') === values)
if (range) {
detail = {
value: range[this.map.value],
data: range
}
}
}
// this.formItem && this.formItem.setValue(detail.value)
// TODO 兼容 vue2
this.$emit('input', detail.value);
// // TOTO 兼容 vue3
this.$emit('update:modelValue', detail.value);
this.$emit('change', {
detail
})
if (this.multiple) {
// 如果 v-model 没有绑定 ,则走内部逻辑
// if (this.value.length === 0) {
this.dataList = this.getDataList(detail.value, true)
// }
} else {
this.dataList = this.getDataList(detail.value)
}
},
/**
* 获取渲染的新数组
* @param {Object} value 选中内容
*/
getDataList(value) {
// 解除引用关系,破坏原引用关系,避免污染源数据
let dataList = JSON.parse(JSON.stringify(this.range))
let list = []
if (this.multiple) {
if (!Array.isArray(value)) {
value = []
}
}
dataList.forEach((item, index) => {
item.disabled = item.disable || item.disabled || false
if (this.multiple) {
if (value.length > 0) {
let have = value.find(val => val === item[this.map.value])
item.selected = have !== undefined
} else {
item.selected = false
}
} else {
item.selected = value === item[this.map.value]
}
list.push(item)
})
return this.setRange(list)
},
/**
* 处理最大最小值
* @param {Object} list
*/
setRange(list) {
let selectList = list.filter(item => item.selected)
let min = Number(this.min) || 0
let max = Number(this.max) || ''
list.forEach((item, index) => {
if (this.multiple) {
if (selectList.length <= min) {
let have = selectList.find(val => val[this.map.value] === item[this.map.value])
if (have !== undefined) {
item.disabled = true
}
}
if (selectList.length >= max && max !== '') {
let have = selectList.find(val => val[this.map.value] === item[this.map.value])
if (have === undefined) {
item.disabled = true
}
}
}
this.setStyles(item, index)
list[index] = item
})
return list
},
/**
* 设置 class
* @param {Object} item
* @param {Object} index
*/
setStyles(item, index) {
// 设置自定义样式
item.styleBackgroud = this.setStyleBackgroud(item)
item.styleIcon = this.setStyleIcon(item)
item.styleIconText = this.setStyleIconText(item)
item.styleRightIcon = this.setStyleRightIcon(item)
},
/**
* 获取选中值
* @param {Object} range
*/
getSelectedValue(range) {
if (!this.multiple) return this.dataValue
let selectedArr = []
range.forEach((item) => {
if (item.selected) {
selectedArr.push(item[this.map.value])
}
})
return this.dataValue.length > 0 ? this.dataValue : selectedArr
},
/**
* 设置背景样式
*/
setStyleBackgroud(item) {
let styles = {}
let selectedColor = this.selectedColor ? this.selectedColor : '#2979ff'
if (this.selectedColor) {
if (this.mode !== 'list') {
styles['border-color'] = item.selected ? selectedColor : '#DCDFE6'
}
if (this.mode === 'tag') {
styles['background-color'] = item.selected ? selectedColor : '#f5f5f5'
}
}
let classles = ''
for (let i in styles) {
classles += `${i}:${styles[i]};`
}
return classles
},
setStyleIcon(item) {
let styles = {}
let classles = ''
if (this.selectedColor) {
let selectedColor = this.selectedColor ? this.selectedColor : '#2979ff'
styles['background-color'] = item.selected ? selectedColor : '#fff'
styles['border-color'] = item.selected ? selectedColor : '#DCDFE6'
if (!item.selected && item.disabled) {
styles['background-color'] = '#F2F6FC'
styles['border-color'] = item.selected ? selectedColor : '#DCDFE6'
}
}
for (let i in styles) {
classles += `${i}:${styles[i]};`
}
return classles
},
setStyleIconText(item) {
let styles = {}
let classles = ''
if (this.selectedColor) {
let selectedColor = this.selectedColor ? this.selectedColor : '#2979ff'
if (this.mode === 'tag') {
styles.color = item.selected ? (this.selectedTextColor ? this.selectedTextColor : '#fff') : '#666'
} else {
styles.color = item.selected ? (this.selectedTextColor ? this.selectedTextColor : selectedColor) : '#666'
}
if (!item.selected && item.disabled) {
styles.color = '#999'
}
}
for (let i in styles) {
classles += `${i}:${styles[i]};`
}
return classles
},
setStyleRightIcon(item) {
let styles = {}
let classles = ''
if (this.mode === 'list') {
styles['border-color'] = item.selected ? this.styles.selectedColor : '#DCDFE6'
}
for (let i in styles) {
classles += `${i}:${styles[i]};`
}
return classles
}
}
}
</script>
<style lang="scss">
$uni-primary: #2979ff !default;
$border-color: #DCDFE6;
$disable: 0.4;
@mixin flex {
/* #ifndef APP-NVUE */
display: flex;
/* #endif */
}
.uni-data-loading {
@include flex;
flex-direction: row;
justify-content: center;
align-items: center;
height: 36px;
padding-left: 10px;
color: #999;
}
.uni-data-checklist {
position: relative;
z-index: 0;
flex: 1;
// 多选样式
.checklist-group {
@include flex;
flex-direction: row;
flex-wrap: wrap;
&.is-list {
flex-direction: column;
}
.checklist-box {
@include flex;
flex-direction: row;
align-items: center;
position: relative;
margin: 5px 0;
margin-right: 25px;
.hidden {
position: absolute;
opacity: 0;
}
// 文字样式
.checklist-content {
@include flex;
flex: 1;
flex-direction: row;
align-items: center;
justify-content: space-between;
.checklist-text {
font-size: 14px;
color: #666;
margin-left: 5px;
line-height: 14px;
}
.checkobx__list {
border-right-width: 1px;
border-right-color: #007aff;
border-right-style: solid;
border-bottom-width: 1px;
border-bottom-color: #007aff;
border-bottom-style: solid;
height: 12px;
width: 6px;
left: -5px;
transform-origin: center;
transform: rotate(45deg);
opacity: 0;
}
}
// 多选样式
.checkbox__inner {
/* #ifndef APP-NVUE */
flex-shrink: 0;
box-sizing: border-box;
/* #endif */
position: relative;
width: 16px;
height: 16px;
border: 1px solid $border-color;
border-radius: 4px;
background-color: #fff;
z-index: 1;
.checkbox__inner-icon {
position: absolute;
/* #ifdef APP-NVUE */
top: 2px;
/* #endif */
/* #ifndef APP-NVUE */
top: 1px;
/* #endif */
left: 5px;
height: 8px;
width: 4px;
border-right-width: 1px;
border-right-color: #fff;
border-right-style: solid;
border-bottom-width: 1px;
border-bottom-color: #fff;
border-bottom-style: solid;
opacity: 0;
transform-origin: center;
transform: rotate(40deg);
}
}
// 单选样式
.radio__inner {
@include flex;
/* #ifndef APP-NVUE */
flex-shrink: 0;
box-sizing: border-box;
/* #endif */
justify-content: center;
align-items: center;
position: relative;
width: 16px;
height: 16px;
border: 1px solid $border-color;
border-radius: 16px;
background-color: #fff;
z-index: 1;
.radio__inner-icon {
width: 8px;
height: 8px;
border-radius: 10px;
opacity: 0;
}
}
// 默认样式
&.is--default {
// 禁用
&.is-disable {
/* #ifdef H5 */
cursor: not-allowed;
/* #endif */
.checkbox__inner {
background-color: #F2F6FC;
border-color: $border-color;
/* #ifdef H5 */
cursor: not-allowed;
/* #endif */
}
.radio__inner {
background-color: #F2F6FC;
border-color: $border-color;
}
.checklist-text {
color: #999;
}
}
// 选中
&.is-checked {
.checkbox__inner {
border-color: $uni-primary;
background-color: $uni-primary;
.checkbox__inner-icon {
opacity: 1;
transform: rotate(45deg);
}
}
.radio__inner {
border-color: $uni-primary;
.radio__inner-icon {
opacity: 1;
background-color: $uni-primary;
}
}
.checklist-text {
color: $uni-primary;
}
// 选中禁用
&.is-disable {
.checkbox__inner {
opacity: $disable;
}
.checklist-text {
opacity: $disable;
}
.radio__inner {
opacity: $disable;
}
}
}
}
// 按钮样式
&.is--button {
margin-right: 10px;
padding: 5px 10px;
border: 1px $border-color solid;
border-radius: 3px;
transition: border-color 0.2s;
// 禁用
&.is-disable {
/* #ifdef H5 */
cursor: not-allowed;
/* #endif */
border: 1px #eee solid;
opacity: $disable;
.checkbox__inner {
background-color: #F2F6FC;
border-color: $border-color;
/* #ifdef H5 */
cursor: not-allowed;
/* #endif */
}
.radio__inner {
background-color: #F2F6FC;
border-color: $border-color;
/* #ifdef H5 */
cursor: not-allowed;
/* #endif */
}
.checklist-text {
color: #999;
}
}
&.is-checked {
border-color: $uni-primary;
.checkbox__inner {
border-color: $uni-primary;
background-color: $uni-primary;
.checkbox__inner-icon {
opacity: 1;
transform: rotate(45deg);
}
}
.radio__inner {
border-color: $uni-primary;
.radio__inner-icon {
opacity: 1;
background-color: $uni-primary;
}
}
.checklist-text {
color: $uni-primary;
}
// 选中禁用
&.is-disable {
opacity: $disable;
}
}
}
// 标签样式
&.is--tag {
margin-right: 10px;
padding: 5px 10px;
border: 1px $border-color solid;
border-radius: 3px;
background-color: #f5f5f5;
.checklist-text {
margin: 0;
color: #666;
}
// 禁用
&.is-disable {
/* #ifdef H5 */
cursor: not-allowed;
/* #endif */
opacity: $disable;
}
&.is-checked {
background-color: $uni-primary;
border-color: $uni-primary;
.checklist-text {
color: #fff;
}
}
}
// 列表样式
&.is--list {
/* #ifndef APP-NVUE */
display: flex;
/* #endif */
padding: 10px 15px;
padding-left: 0;
margin: 0;
&.is-list-border {
border-top: 1px #eee solid;
}
// 禁用
&.is-disable {
/* #ifdef H5 */
cursor: not-allowed;
/* #endif */
.checkbox__inner {
background-color: #F2F6FC;
border-color: $border-color;
/* #ifdef H5 */
cursor: not-allowed;
/* #endif */
}
.checklist-text {
color: #999;
}
}
&.is-checked {
.checkbox__inner {
border-color: $uni-primary;
background-color: $uni-primary;
.checkbox__inner-icon {
opacity: 1;
transform: rotate(45deg);
}
}
.radio__inner {
border-color: $uni-primary;
.radio__inner-icon {
opacity: 1;
background-color: $uni-primary;
}
}
.checklist-text {
color: $uni-primary;
}
.checklist-content {
.checkobx__list {
opacity: 1;
border-color: $uni-primary;
}
}
// 选中禁用
&.is-disable {
.checkbox__inner {
opacity: $disable;
}
.checklist-text {
opacity: $disable;
}
}
}
}
}
}
}
</style>
|
2301_77169380/aionix-2
|
uni_modules/uni-data-checkbox/components/uni-data-checkbox/uni-data-checkbox.vue
|
Vue
|
mit
| 20,446
|
// #ifdef H5
export default {
name: 'Keypress',
props: {
disable: {
type: Boolean,
default: false
}
},
mounted () {
const keyNames = {
esc: ['Esc', 'Escape'],
tab: 'Tab',
enter: 'Enter',
space: [' ', 'Spacebar'],
up: ['Up', 'ArrowUp'],
left: ['Left', 'ArrowLeft'],
right: ['Right', 'ArrowRight'],
down: ['Down', 'ArrowDown'],
delete: ['Backspace', 'Delete', 'Del']
}
const listener = ($event) => {
if (this.disable) {
return
}
const keyName = Object.keys(keyNames).find(key => {
const keyName = $event.key
const value = keyNames[key]
return value === keyName || (Array.isArray(value) && value.includes(keyName))
})
if (keyName) {
// 避免和其他按键事件冲突
setTimeout(() => {
this.$emit(keyName, {})
}, 0)
}
}
document.addEventListener('keyup', listener)
this.$once('hook:beforeDestroy', () => {
document.removeEventListener('keyup', listener)
})
},
render: () => {}
}
// #endif
|
2301_77169380/aionix-2
|
uni_modules/uni-data-picker/components/uni-data-picker/keypress.js
|
JavaScript
|
mit
| 1,110
|
<template>
<view class="uni-data-tree">
<view class="uni-data-tree-input" @click="handleInput">
<slot :options="options" :data="inputSelected" :error="errorMessage">
<view class="input-value" :class="{'input-value-border': border}">
<text v-if="errorMessage" class="selected-area error-text">{{errorMessage}}</text>
<view v-else-if="loading && !isOpened" class="selected-area">
<uni-load-more class="load-more" :contentText="loadMore" status="loading"></uni-load-more>
</view>
<scroll-view v-else-if="inputSelected.length" class="selected-area" scroll-x="true">
<view class="selected-list">
<view class="selected-item" v-for="(item,index) in inputSelected" :key="index">
<text class="text-color">{{item.text}}</text><text v-if="index<inputSelected.length-1"
class="input-split-line">{{split}}</text>
</view>
</view>
</scroll-view>
<text v-else class="selected-area placeholder">{{placeholder}}</text>
<view v-if="clearIcon && !readonly && inputSelected.length" class="icon-clear" @click.stop="clear">
<uni-icons type="clear" color="#c0c4cc" size="24"></uni-icons>
</view>
<view class="arrow-area" v-if="(!clearIcon || !inputSelected.length) && !readonly ">
<view class="input-arrow"></view>
</view>
</view>
</slot>
</view>
<view class="uni-data-tree-cover" v-if="isOpened" @click="handleClose"></view>
<view class="uni-data-tree-dialog" v-if="isOpened">
<view class="uni-popper__arrow"></view>
<view class="dialog-caption">
<view class="title-area">
<text class="dialog-title">{{popupTitle}}</text>
</view>
<view class="dialog-close" @click="handleClose">
<view class="dialog-close-plus" data-id="close"></view>
<view class="dialog-close-plus dialog-close-rotate" data-id="close"></view>
</view>
</view>
<data-picker-view class="picker-view" ref="pickerView" v-model="dataValue" :localdata="localdata"
:preload="preload" :collection="collection" :field="field" :orderby="orderby" :where="where"
:step-searh="stepSearh" :self-field="selfField" :parent-field="parentField" :managed-mode="true" :map="map"
:ellipsis="ellipsis" @change="onchange" @datachange="ondatachange" @nodeclick="onnodeclick">
</data-picker-view>
</view>
</view>
</template>
<script>
import dataPicker from "../uni-data-pickerview/uni-data-picker.js"
import DataPickerView from "../uni-data-pickerview/uni-data-pickerview.vue"
/**
* DataPicker 级联选择
* @description 支持单列、和多列级联选择。列数没有限制,如果屏幕显示不全,顶部tab区域会左右滚动。
* @tutorial https://ext.dcloud.net.cn/plugin?id=3796
* @property {String} popup-title 弹出窗口标题
* @property {Array} localdata 本地数据,参考
* @property {Boolean} border = [true|false] 是否有边框
* @property {Boolean} readonly = [true|false] 是否仅读
* @property {Boolean} preload = [true|false] 是否预加载数据
* @value true 开启预加载数据,点击弹出窗口后显示已加载数据
* @value false 关闭预加载数据,点击弹出窗口后开始加载数据
* @property {Boolean} step-searh = [true|false] 是否分布查询
* @value true 启用分布查询,仅查询当前选中节点
* @value false 关闭分布查询,一次查询出所有数据
* @property {String|DBFieldString} self-field 分布查询当前字段名称
* @property {String|DBFieldString} parent-field 分布查询父字段名称
* @property {String|DBCollectionString} collection 表名
* @property {String|DBFieldString} field 查询字段,多个字段用 `,` 分割
* @property {String} orderby 排序字段及正序倒叙设置
* @property {String|JQLString} where 查询条件
* @event {Function} popupshow 弹出的选择窗口打开时触发此事件
* @event {Function} popuphide 弹出的选择窗口关闭时触发此事件
*/
export default {
name: 'UniDataPicker',
emits: ['popupopened', 'popupclosed', 'nodeclick', 'input', 'change', 'update:modelValue','inputclick'],
mixins: [dataPicker],
components: {
DataPickerView
},
props: {
options: {
type: [Object, Array],
default () {
return {}
}
},
popupTitle: {
type: String,
default: '请选择'
},
placeholder: {
type: String,
default: '请选择'
},
heightMobile: {
type: String,
default: ''
},
readonly: {
type: Boolean,
default: false
},
clearIcon: {
type: Boolean,
default: true
},
border: {
type: Boolean,
default: true
},
split: {
type: String,
default: '/'
},
ellipsis: {
type: Boolean,
default: true
}
},
data() {
return {
isOpened: false,
inputSelected: []
}
},
created() {
this.$nextTick(() => {
this.load();
})
},
watch: {
localdata: {
handler() {
this.load()
},
deep: true
},
},
methods: {
clear() {
this._dispatchEvent([]);
},
onPropsChange() {
this._treeData = [];
this.selectedIndex = 0;
this.load();
},
load() {
if (this.readonly) {
this._processReadonly(this.localdata, this.dataValue);
return;
}
// 回显本地数据
if (this.isLocalData) {
this.loadData();
this.inputSelected = this.selected.slice(0);
} else if (this.isCloudDataList || this.isCloudDataTree) { // 回显 Cloud 数据
this.loading = true;
this.getCloudDataValue().then((res) => {
this.loading = false;
this.inputSelected = res;
}).catch((err) => {
this.loading = false;
this.errorMessage = err;
})
}
},
show() {
this.isOpened = true
setTimeout(() => {
this.$refs.pickerView.updateData({
treeData: this._treeData,
selected: this.selected,
selectedIndex: this.selectedIndex
})
}, 200)
this.$emit('popupopened')
},
hide() {
this.isOpened = false
this.$emit('popupclosed')
},
handleInput() {
if (this.readonly) {
this.$emit('inputclick')
return
}
this.show()
},
handleClose(e) {
this.hide()
},
onnodeclick(e) {
this.$emit('nodeclick', e)
},
ondatachange(e) {
this._treeData = this.$refs.pickerView._treeData
},
onchange(e) {
this.hide()
this.$nextTick(() => {
this.inputSelected = e;
})
this._dispatchEvent(e)
},
_processReadonly(dataList, value) {
var isTree = dataList.findIndex((item) => {
return item.children
})
if (isTree > -1) {
let inputValue
if (Array.isArray(value)) {
inputValue = value[value.length - 1]
if (typeof inputValue === 'object' && inputValue.value) {
inputValue = inputValue.value
}
} else {
inputValue = value
}
this.inputSelected = this._findNodePath(inputValue, this.localdata)
return
}
if (!this.hasValue) {
this.inputSelected = []
return
}
let result = []
for (let i = 0; i < value.length; i++) {
var val = value[i]
var item = dataList.find((v) => {
return v.value == val
})
if (item) {
result.push(item)
}
}
if (result.length) {
this.inputSelected = result
}
},
_filterForArray(data, valueArray) {
var result = []
for (let i = 0; i < valueArray.length; i++) {
var value = valueArray[i]
var found = data.find((item) => {
return item.value == value
})
if (found) {
result.push(found)
}
}
return result
},
_dispatchEvent(selected) {
let item = {}
if (selected.length) {
var value = new Array(selected.length)
for (var i = 0; i < selected.length; i++) {
value[i] = selected[i].value
}
item = selected[selected.length - 1]
} else {
item.value = ''
}
if (this.formItem) {
this.formItem.setValue(item.value)
}
this.$emit('input', item.value)
this.$emit('update:modelValue', item.value)
this.$emit('change', {
detail: {
value: selected
}
})
}
}
}
</script>
<style>
.uni-data-tree {
flex: 1;
position: relative;
font-size: 14px;
}
.error-text {
color: #DD524D;
}
.input-value {
/* #ifndef APP-NVUE */
display: flex;
/* #endif */
flex-direction: row;
align-items: center;
flex-wrap: nowrap;
font-size: 14px;
/* line-height: 35px; */
padding: 0 10px;
padding-right: 5px;
overflow: hidden;
height: 35px;
/* #ifndef APP-NVUE */
box-sizing: border-box;
/* #endif */
}
.input-value-border {
border: 1px solid #e5e5e5;
border-radius: 5px;
}
.selected-area {
flex: 1;
overflow: hidden;
/* #ifndef APP-NVUE */
display: flex;
/* #endif */
flex-direction: row;
}
.load-more {
/* #ifndef APP-NVUE */
margin-right: auto;
/* #endif */
/* #ifdef APP-NVUE */
width: 40px;
/* #endif */
}
.selected-list {
/* #ifndef APP-NVUE */
display: flex;
/* #endif */
flex-direction: row;
flex-wrap: nowrap;
/* padding: 0 5px; */
}
.selected-item {
flex-direction: row;
/* padding: 0 1px; */
/* #ifndef APP-NVUE */
white-space: nowrap;
/* #endif */
}
.text-color {
color: #333;
}
.placeholder {
color: grey;
font-size: 12px;
}
.input-split-line {
opacity: .5;
}
.arrow-area {
position: relative;
width: 20px;
/* #ifndef APP-NVUE */
margin-bottom: 5px;
margin-left: auto;
display: flex;
/* #endif */
justify-content: center;
transform: rotate(-45deg);
transform-origin: center;
}
.input-arrow {
width: 7px;
height: 7px;
border-left: 1px solid #999;
border-bottom: 1px solid #999;
}
.uni-data-tree-cover {
position: fixed;
left: 0;
top: 0;
right: 0;
bottom: 0;
background-color: rgba(0, 0, 0, .4);
/* #ifndef APP-NVUE */
display: flex;
/* #endif */
flex-direction: column;
z-index: 100;
}
.uni-data-tree-dialog {
position: fixed;
left: 0;
/* #ifndef APP-NVUE */
top: 20%;
/* #endif */
/* #ifdef APP-NVUE */
top: 200px;
/* #endif */
right: 0;
bottom: 0;
background-color: #FFFFFF;
border-top-left-radius: 10px;
border-top-right-radius: 10px;
/* #ifndef APP-NVUE */
display: flex;
/* #endif */
flex-direction: column;
z-index: 102;
overflow: hidden;
/* #ifdef APP-NVUE */
width: 750rpx;
/* #endif */
}
.dialog-caption {
position: relative;
/* #ifndef APP-NVUE */
display: flex;
/* #endif */
flex-direction: row;
/* border-bottom: 1px solid #f0f0f0; */
}
.title-area {
/* #ifndef APP-NVUE */
display: flex;
/* #endif */
align-items: center;
/* #ifndef APP-NVUE */
margin: auto;
/* #endif */
padding: 0 10px;
}
.dialog-title {
/* font-weight: bold; */
line-height: 44px;
}
.dialog-close {
position: absolute;
top: 0;
right: 0;
bottom: 0;
/* #ifndef APP-NVUE */
display: flex;
/* #endif */
flex-direction: row;
align-items: center;
padding: 0 15px;
}
.dialog-close-plus {
width: 16px;
height: 2px;
background-color: #666;
border-radius: 2px;
transform: rotate(45deg);
}
.dialog-close-rotate {
position: absolute;
transform: rotate(-45deg);
}
.picker-view {
flex: 1;
overflow: hidden;
}
.icon-clear {
display: flex;
align-items: center;
}
/* #ifdef H5 */
@media all and (min-width: 768px) {
.uni-data-tree-cover {
background-color: transparent;
}
.uni-data-tree-dialog {
position: absolute;
top: 55px;
height: auto;
min-height: 400px;
max-height: 50vh;
background-color: #fff;
border: 1px solid #EBEEF5;
box-shadow: 0 2px 12px 0 rgba(0, 0, 0, 0.1);
border-radius: 4px;
overflow: unset;
}
.dialog-caption {
display: none;
}
.icon-clear {
/* margin-right: 5px; */
}
}
/* #endif */
/* picker 弹出层通用的指示小三角, todo:扩展至上下左右方向定位 */
/* #ifndef APP-NVUE */
.uni-popper__arrow,
.uni-popper__arrow::after {
position: absolute;
display: block;
width: 0;
height: 0;
border-color: transparent;
border-style: solid;
border-width: 6px;
}
.uni-popper__arrow {
filter: drop-shadow(0 2px 12px rgba(0, 0, 0, 0.03));
top: -6px;
left: 10%;
margin-right: 3px;
border-top-width: 0;
border-bottom-color: #EBEEF5;
}
.uni-popper__arrow::after {
content: " ";
top: 1px;
margin-left: -6px;
border-top-width: 0;
border-bottom-color: #fff;
}
/* #endif */
</style>
|
2301_77169380/aionix-2
|
uni_modules/uni-data-picker/components/uni-data-picker/uni-data-picker.vue
|
Vue
|
mit
| 13,919
|
export default {
props: {
localdata: {
type: [Array, Object],
default () {
return []
}
},
spaceInfo: {
type: Object,
default () {
return {}
}
},
collection: {
type: String,
default: ''
},
action: {
type: String,
default: ''
},
field: {
type: String,
default: ''
},
orderby: {
type: String,
default: ''
},
where: {
type: [String, Object],
default: ''
},
pageData: {
type: String,
default: 'add'
},
pageCurrent: {
type: Number,
default: 1
},
pageSize: {
type: Number,
default: 500
},
getcount: {
type: [Boolean, String],
default: false
},
getone: {
type: [Boolean, String],
default: false
},
gettree: {
type: [Boolean, String],
default: false
},
manual: {
type: Boolean,
default: false
},
value: {
type: [Array, String, Number],
default () {
return []
}
},
modelValue: {
type: [Array, String, Number],
default () {
return []
}
},
preload: {
type: Boolean,
default: false
},
stepSearh: {
type: Boolean,
default: true
},
selfField: {
type: String,
default: ''
},
parentField: {
type: String,
default: ''
},
multiple: {
type: Boolean,
default: false
},
map: {
type: Object,
default () {
return {
text: "text",
value: "value"
}
}
}
},
data() {
return {
loading: false,
errorMessage: '',
loadMore: {
contentdown: '',
contentrefresh: '',
contentnomore: ''
},
dataList: [],
selected: [],
selectedIndex: 0,
page: {
current: this.pageCurrent,
size: this.pageSize,
count: 0
}
}
},
computed: {
isLocalData() {
return !this.collection.length;
},
isCloudData() {
return this.collection.length > 0;
},
isCloudDataList() {
return (this.isCloudData && (!this.parentField && !this.selfField));
},
isCloudDataTree() {
return (this.isCloudData && this.parentField && this.selfField);
},
dataValue() {
let isModelValue = Array.isArray(this.modelValue) ? (this.modelValue.length > 0) : (this.modelValue !== null ||
this.modelValue !== undefined);
return isModelValue ? this.modelValue : this.value;
},
hasValue() {
if (typeof this.dataValue === 'number') {
return true
}
return (this.dataValue != null) && (this.dataValue.length > 0)
}
},
created() {
this.$watch(() => {
var al = [];
['pageCurrent',
'pageSize',
'spaceInfo',
'value',
'modelValue',
'localdata',
'collection',
'action',
'field',
'orderby',
'where',
'getont',
'getcount',
'gettree'
].forEach(key => {
al.push(this[key])
});
return al
}, (newValue, oldValue) => {
let needReset = false
for (let i = 2; i < newValue.length; i++) {
if (newValue[i] != oldValue[i]) {
needReset = true
break
}
}
if (newValue[0] != oldValue[0]) {
this.page.current = this.pageCurrent
}
this.page.size = this.pageSize
this.onPropsChange()
})
this._treeData = []
},
methods: {
onPropsChange() {
this._treeData = [];
},
// 填充 pickview 数据
async loadData() {
if (this.isLocalData) {
this.loadLocalData();
} else if (this.isCloudDataList) {
this.loadCloudDataList();
} else if (this.isCloudDataTree) {
this.loadCloudDataTree();
}
},
// 加载本地数据
async loadLocalData() {
this._treeData = [];
this._extractTree(this.localdata, this._treeData);
let inputValue = this.dataValue;
if (inputValue === undefined) {
return;
}
if (Array.isArray(inputValue)) {
inputValue = inputValue[inputValue.length - 1];
if (typeof inputValue === 'object' && inputValue[this.map.value]) {
inputValue = inputValue[this.map.value];
}
}
this.selected = this._findNodePath(inputValue, this.localdata);
},
// 加载 Cloud 数据 (单列)
async loadCloudDataList() {
if (this.loading) {
return;
}
this.loading = true;
try {
let response = await this.getCommand();
let responseData = response.result.data;
this._treeData = responseData;
this._updateBindData();
this._updateSelected();
this.onDataChange();
} catch (e) {
this.errorMessage = e;
} finally {
this.loading = false;
}
},
// 加载 Cloud 数据 (树形)
async loadCloudDataTree() {
if (this.loading) {
return;
}
this.loading = true;
try {
let commandOptions = {
field: this._cloudDataPostField(),
where: this._cloudDataTreeWhere()
};
if (this.gettree) {
commandOptions.startwith = `${this.selfField}=='${this.dataValue}'`;
}
let response = await this.getCommand(commandOptions);
let responseData = response.result.data;
this._treeData = responseData;
this._updateBindData();
this._updateSelected();
this.onDataChange();
} catch (e) {
this.errorMessage = e;
} finally {
this.loading = false;
}
},
// 加载 Cloud 数据 (节点)
async loadCloudDataNode(callback) {
if (this.loading) {
return;
}
this.loading = true;
try {
let commandOptions = {
field: this._cloudDataPostField(),
where: this._cloudDataNodeWhere()
};
let response = await this.getCommand(commandOptions);
let responseData = response.result.data;
callback(responseData);
} catch (e) {
this.errorMessage = e;
} finally {
this.loading = false;
}
},
// 回显 Cloud 数据
getCloudDataValue() {
if (this.isCloudDataList) {
return this.getCloudDataListValue();
}
if (this.isCloudDataTree) {
return this.getCloudDataTreeValue();
}
},
// 回显 Cloud 数据 (单列)
getCloudDataListValue() {
// 根据 field's as value标识匹配 where 条件
let where = [];
let whereField = this._getForeignKeyByField();
if (whereField) {
where.push(`${whereField} == '${this.dataValue}'`)
}
where = where.join(' || ');
if (this.where) {
where = `(${this.where}) && (${where})`
}
return this.getCommand({
field: this._cloudDataPostField(),
where
}).then((res) => {
this.selected = res.result.data;
return res.result.data;
});
},
// 回显 Cloud 数据 (树形)
getCloudDataTreeValue() {
return this.getCommand({
field: this._cloudDataPostField(),
getTreePath: {
startWith: `${this.selfField}=='${this.dataValue}'`
}
}).then((res) => {
let treePath = [];
this._extractTreePath(res.result.data, treePath);
this.selected = treePath;
return treePath;
});
},
getCommand(options = {}) {
/* eslint-disable no-undef */
let db = uniCloud.database(this.spaceInfo)
const action = options.action || this.action
if (action) {
db = db.action(action)
}
const collection = options.collection || this.collection
db = db.collection(collection)
const where = options.where || this.where
if (!(!where || !Object.keys(where).length)) {
db = db.where(where)
}
const field = options.field || this.field
if (field) {
db = db.field(field)
}
const orderby = options.orderby || this.orderby
if (orderby) {
db = db.orderBy(orderby)
}
const current = options.pageCurrent !== undefined ? options.pageCurrent : this.page.current
const size = options.pageSize !== undefined ? options.pageSize : this.page.size
const getCount = options.getcount !== undefined ? options.getcount : this.getcount
const getTree = options.gettree !== undefined ? options.gettree : this.gettree
const getOptions = {
getCount,
getTree
}
if (options.getTreePath) {
getOptions.getTreePath = options.getTreePath
}
db = db.skip(size * (current - 1)).limit(size).get(getOptions)
return db
},
_cloudDataPostField() {
let fields = [this.field];
if (this.parentField) {
fields.push(`${this.parentField} as parent_value`);
}
return fields.join(',');
},
_cloudDataTreeWhere() {
let result = []
let selected = this.selected
let parentField = this.parentField
if (parentField) {
result.push(`${parentField} == null || ${parentField} == ""`)
}
if (selected.length) {
for (var i = 0; i < selected.length - 1; i++) {
result.push(`${parentField} == '${selected[i].value}'`)
}
}
let where = []
if (this.where) {
where.push(`(${this.where})`)
}
if (result.length) {
where.push(`(${result.join(' || ')})`)
}
return where.join(' && ')
},
_cloudDataNodeWhere() {
let where = []
let selected = this.selected;
if (selected.length) {
where.push(`${this.parentField} == '${selected[selected.length - 1].value}'`);
}
where = where.join(' || ');
if (this.where) {
return `(${this.where}) && (${where})`
}
return where
},
_getWhereByForeignKey() {
let result = []
let whereField = this._getForeignKeyByField();
if (whereField) {
result.push(`${whereField} == '${this.dataValue}'`)
}
if (this.where) {
return `(${this.where}) && (${result.join(' || ')})`
}
return result.join(' || ')
},
_getForeignKeyByField() {
let fields = this.field.split(',');
let whereField = null;
for (let i = 0; i < fields.length; i++) {
const items = fields[i].split('as');
if (items.length < 2) {
continue;
}
if (items[1].trim() === 'value') {
whereField = items[0].trim();
break;
}
}
return whereField;
},
_updateBindData(node) {
const {
dataList,
hasNodes
} = this._filterData(this._treeData, this.selected)
let isleaf = this._stepSearh === false && !hasNodes
if (node) {
node.isleaf = isleaf
}
this.dataList = dataList
this.selectedIndex = dataList.length - 1
if (!isleaf && this.selected.length < dataList.length) {
this.selected.push({
value: null,
text: "请选择"
})
}
return {
isleaf,
hasNodes
}
},
_updateSelected() {
let dl = this.dataList
let sl = this.selected
let textField = this.map.text
let valueField = this.map.value
for (let i = 0; i < sl.length; i++) {
let value = sl[i].value
let dl2 = dl[i]
for (let j = 0; j < dl2.length; j++) {
let item2 = dl2[j]
if (item2[valueField] === value) {
sl[i].text = item2[textField]
break
}
}
}
},
_filterData(data, paths) {
let dataList = []
let hasNodes = true
dataList.push(data.filter((item) => {
return (item.parent_value === null || item.parent_value === undefined || item.parent_value === '')
}))
for (let i = 0; i < paths.length; i++) {
let value = paths[i].value
let nodes = data.filter((item) => {
return item.parent_value === value
})
if (nodes.length) {
dataList.push(nodes)
} else {
hasNodes = false
}
}
return {
dataList,
hasNodes
}
},
_extractTree(nodes, result, parent_value) {
let list = result || []
let valueField = this.map.value
for (let i = 0; i < nodes.length; i++) {
let node = nodes[i]
let child = {}
for (let key in node) {
if (key !== 'children') {
child[key] = node[key]
}
}
if (parent_value !== null && parent_value !== undefined && parent_value !== '') {
child.parent_value = parent_value
}
result.push(child)
let children = node.children
if (children) {
this._extractTree(children, result, node[valueField])
}
}
},
_extractTreePath(nodes, result) {
let list = result || []
for (let i = 0; i < nodes.length; i++) {
let node = nodes[i]
let child = {}
for (let key in node) {
if (key !== 'children') {
child[key] = node[key]
}
}
result.push(child)
let children = node.children
if (children) {
this._extractTreePath(children, result)
}
}
},
_findNodePath(key, nodes, path = []) {
let textField = this.map.text
let valueField = this.map.value
for (let i = 0; i < nodes.length; i++) {
let node = nodes[i]
let children = node.children
let text = node[textField]
let value = node[valueField]
path.push({
value,
text
})
if (value === key) {
return path
}
if (children) {
const p = this._findNodePath(key, children, path)
if (p.length) {
return p
}
}
path.pop()
}
return []
}
}
}
|
2301_77169380/aionix-2
|
uni_modules/uni-data-picker/components/uni-data-pickerview/uni-data-picker.js
|
JavaScript
|
mit
| 14,230
|
.uni-data-pickerview {
position: relative;
flex-direction: column;
overflow: hidden;
}
.loading-cover {
position: absolute;
left: 0;
top: 0;
right: 0;
bottom: 0;
align-items: center;
justify-content: center;
background-color: rgba(150, 150, 150, .1);
}
.error {
background-color: #fff;
padding: 15px;
}
.error-text {
color: #DD524D;
}
.selected-node-list {
flex-direction: row;
flex-wrap: nowrap;
}
.selected-node-item {
margin-left: 10px;
margin-right: 10px;
padding: 8px 10px 8px 10px;
border-bottom: 2px solid transparent;
}
.selected-node-item-active {
color: #007aff;
border-bottom-color: #007aff;
}
.list-view {
flex: 1;
}
.list-item {
flex-direction: row;
justify-content: space-between;
padding: 12px 15px;
border-bottom: 1px solid #f0f0f0;
}
.item-text {
color: #333333;
}
.item-text-disabled {
opacity: .5;
}
.item-text-overflow {
overflow: hidden;
}
.check {
margin-right: 5px;
border: 2px solid #007aff;
border-left: 0;
border-top: 0;
height: 12px;
width: 6px;
transform-origin: center;
transform: rotate(45deg);
}
|
2301_77169380/aionix-2
|
uni_modules/uni-data-picker/components/uni-data-pickerview/uni-data-pickerview.css
|
CSS
|
mit
| 1,115
|
<template>
<view class="uni-data-pickerview">
<scroll-view v-if="!isCloudDataList" class="selected-area" scroll-x="true">
<view class="selected-list">
<view
class="selected-item"
v-for="(item,index) in selected"
:key="index"
:class="{
'selected-item-active':index == selectedIndex
}"
@click="handleSelect(index)"
>
<text>{{item.text || ''}}</text>
</view>
</view>
</scroll-view>
<view class="tab-c">
<scroll-view class="list" :scroll-y="true">
<view class="item" :class="{'is-disabled': !!item.disable}" v-for="(item, j) in dataList[selectedIndex]" :key="j"
@click="handleNodeClick(item, selectedIndex, j)">
<text class="item-text">{{item[map.text]}}</text>
<view class="check" v-if="selected.length > selectedIndex && item[map.value] == selected[selectedIndex].value"></view>
</view>
</scroll-view>
<view class="loading-cover" v-if="loading">
<uni-load-more class="load-more" :contentText="loadMore" status="loading"></uni-load-more>
</view>
<view class="error-message" v-if="errorMessage">
<text class="error-text">{{errorMessage}}</text>
</view>
</view>
</view>
</template>
<script>
import dataPicker from "./uni-data-picker.js"
/**
* DataPickerview
* @description uni-data-pickerview
* @tutorial https://ext.dcloud.net.cn/plugin?id=3796
* @property {Array} localdata 本地数据,参考
* @property {Boolean} step-searh = [true|false] 是否分布查询
* @value true 启用分布查询,仅查询当前选中节点
* @value false 关闭分布查询,一次查询出所有数据
* @property {String|DBFieldString} self-field 分布查询当前字段名称
* @property {String|DBFieldString} parent-field 分布查询父字段名称
* @property {String|DBCollectionString} collection 表名
* @property {String|DBFieldString} field 查询字段,多个字段用 `,` 分割
* @property {String} orderby 排序字段及正序倒叙设置
* @property {String|JQLString} where 查询条件
*/
export default {
name: 'UniDataPickerView',
emits: ['nodeclick', 'change', 'datachange', 'update:modelValue'],
mixins: [dataPicker],
props: {
managedMode: {
type: Boolean,
default: false
},
ellipsis: {
type: Boolean,
default: true
}
},
created() {
if (!this.managedMode) {
this.$nextTick(() => {
this.loadData();
})
}
},
methods: {
onPropsChange() {
this._treeData = [];
this.selectedIndex = 0;
this.$nextTick(() => {
this.loadData();
})
},
handleSelect(index) {
this.selectedIndex = index;
},
handleNodeClick(item, i, j) {
if (item.disable) {
return;
}
const node = this.dataList[i][j];
const text = node[this.map.text];
const value = node[this.map.value];
if (i < this.selected.length - 1) {
this.selected.splice(i, this.selected.length - i)
this.selected.push({
text,
value
})
} else if (i === this.selected.length - 1) {
this.selected.splice(i, 1, {
text,
value
})
}
if (node.isleaf) {
this.onSelectedChange(node, node.isleaf)
return
}
const {
isleaf,
hasNodes
} = this._updateBindData()
// 本地数据
if (this.isLocalData) {
this.onSelectedChange(node, (!hasNodes || isleaf))
} else if (this.isCloudDataList) { // Cloud 数据 (单列)
this.onSelectedChange(node, true)
} else if (this.isCloudDataTree) { // Cloud 数据 (树形)
if (isleaf) {
this.onSelectedChange(node, node.isleaf)
} else if (!hasNodes) { // 请求一次服务器以确定是否为叶子节点
this.loadCloudDataNode((data) => {
if (!data.length) {
node.isleaf = true
} else {
this._treeData.push(...data)
this._updateBindData(node)
}
this.onSelectedChange(node, node.isleaf)
})
}
}
},
updateData(data) {
this._treeData = data.treeData
this.selected = data.selected
if (!this._treeData.length) {
this.loadData()
} else {
//this.selected = data.selected
this._updateBindData()
}
},
onDataChange() {
this.$emit('datachange');
},
onSelectedChange(node, isleaf) {
if (isleaf) {
this._dispatchEvent()
}
if (node) {
this.$emit('nodeclick', node)
}
},
_dispatchEvent() {
this.$emit('change', this.selected.slice(0))
}
}
}
</script>
<style lang="scss">
$uni-primary: #007aff !default;
.uni-data-pickerview {
flex: 1;
/* #ifndef APP-NVUE */
display: flex;
/* #endif */
flex-direction: column;
overflow: hidden;
height: 100%;
}
.error-text {
color: #DD524D;
}
.loading-cover {
position: absolute;
left: 0;
top: 0;
right: 0;
bottom: 0;
background-color: rgba(255, 255, 255, .5);
/* #ifndef APP-NVUE */
display: flex;
/* #endif */
flex-direction: column;
align-items: center;
z-index: 1001;
}
.load-more {
/* #ifndef APP-NVUE */
margin: auto;
/* #endif */
}
.error-message {
background-color: #fff;
position: absolute;
left: 0;
top: 0;
right: 0;
bottom: 0;
padding: 15px;
opacity: .9;
z-index: 102;
}
/* #ifdef APP-NVUE */
.selected-area {
width: 750rpx;
}
/* #endif */
.selected-list {
/* #ifndef APP-NVUE */
display: flex;
flex-wrap: nowrap;
/* #endif */
flex-direction: row;
padding: 0 5px;
border-bottom: 1px solid #f8f8f8;
}
.selected-item {
margin-left: 10px;
margin-right: 10px;
padding: 12px 0;
text-align: center;
/* #ifndef APP-NVUE */
white-space: nowrap;
/* #endif */
}
.selected-item-text-overflow {
width: 168px;
/* fix nvue */
overflow: hidden;
/* #ifndef APP-NVUE */
width: 6em;
white-space: nowrap;
text-overflow: ellipsis;
-o-text-overflow: ellipsis;
/* #endif */
}
.selected-item-active {
border-bottom: 2px solid $uni-primary;
}
.selected-item-text {
color: $uni-primary;
}
.tab-c {
position: relative;
flex: 1;
/* #ifndef APP-NVUE */
display: flex;
/* #endif */
flex-direction: row;
overflow: hidden;
}
.list {
flex: 1;
}
.item {
padding: 12px 15px;
/* border-bottom: 1px solid #f0f0f0; */
/* #ifndef APP-NVUE */
display: flex;
/* #endif */
flex-direction: row;
justify-content: space-between;
}
.is-disabled {
opacity: .5;
}
.item-text {
/* flex: 1; */
color: #333333;
}
.item-text-overflow {
width: 280px;
/* fix nvue */
overflow: hidden;
/* #ifndef APP-NVUE */
width: 20em;
white-space: nowrap;
text-overflow: ellipsis;
-o-text-overflow: ellipsis;
/* #endif */
}
.check {
margin-right: 5px;
border: 2px solid $uni-primary;
border-left: 0;
border-top: 0;
height: 12px;
width: 6px;
transform-origin: center;
/* #ifndef APP-NVUE */
transition: all 0.3s;
/* #endif */
transform: rotate(45deg);
}
</style>
|
2301_77169380/aionix-2
|
uni_modules/uni-data-picker/components/uni-data-pickerview/uni-data-pickerview.vue
|
Vue
|
mit
| 7,713
|
<template>
<view class="uni-stat__select">
<span v-if="label" class="uni-label-text hide-on-phone">{{label + ':'}}</span>
<view class="uni-stat-box" :class="{'uni-stat__actived': current}">
<view class="uni-select" :class="{'uni-select--disabled':disabled}">
<view class="uni-select__input-box" @click="toggleSelector">
<view v-if="current" class="uni-select__input-text">{{textShow}}</view>
<view v-else class="uni-select__input-text uni-select__input-placeholder">{{typePlaceholder}}</view>
<view v-if="current && clear && !disabled" @click.stop="clearVal">
<uni-icons type="clear" color="#c0c4cc" size="24" />
</view>
<view v-else>
<uni-icons :type="showSelector? 'top' : 'bottom'" size="14" color="#999" />
</view>
</view>
<view class="uni-select--mask" v-if="showSelector" @click="toggleSelector" />
<view class="uni-select__selector" :style="getOffsetByPlacement" v-if="showSelector">
<view :class="placement=='bottom'?'uni-popper__arrow_bottom':'uni-popper__arrow_top'"></view>
<scroll-view scroll-y="true" class="uni-select__selector-scroll">
<view class="uni-select__selector-empty" v-if="mixinDatacomResData.length === 0">
<text>{{emptyTips}}</text>
</view>
<view v-else class="uni-select__selector-item" v-for="(item,index) in mixinDatacomResData" :key="index"
@click="change(item)">
<text :class="{'uni-select__selector__disabled': item.disable}">{{formatItemName(item)}}</text>
</view>
</scroll-view>
</view>
</view>
</view>
</view>
</template>
<script>
/**
* DataChecklist 数据选择器
* @description 通过数据渲染的下拉框组件
* @tutorial https://uniapp.dcloud.io/component/uniui/uni-data-select
* @property {String} value 默认值
* @property {Array} localdata 本地数据 ,格式 [{text:'',value:''}]
* @property {Boolean} clear 是否可以清空已选项
* @property {Boolean} emptyText 没有数据时显示的文字 ,本地数据无效
* @property {String} label 左侧标题
* @property {String} placeholder 输入框的提示文字
* @property {Boolean} disabled 是否禁用
* @property {String} placement 弹出位置
* @value top 顶部弹出
* @value bottom 底部弹出(default)
* @event {Function} change 选中发生变化触发
*/
export default {
name: "uni-data-select",
mixins: [uniCloud.mixinDatacom || {}],
props: {
localdata: {
type: Array,
default () {
return []
}
},
value: {
type: [String, Number],
default: ''
},
modelValue: {
type: [String, Number],
default: ''
},
label: {
type: String,
default: ''
},
placeholder: {
type: String,
default: '请选择'
},
emptyTips: {
type: String,
default: '无选项'
},
clear: {
type: Boolean,
default: true
},
defItem: {
type: Number,
default: 0
},
disabled: {
type: Boolean,
default: false
},
// 格式化输出 用法 field="_id as value, version as text, uni_platform as label" format="{label} - {text}"
format: {
type: String,
default: ''
},
placement: {
type: String,
default: 'bottom'
}
},
data() {
return {
showSelector: false,
current: '',
mixinDatacomResData: [],
apps: [],
channels: [],
cacheKey: "uni-data-select-lastSelectedValue",
};
},
created() {
this.debounceGet = this.debounce(() => {
this.query();
}, 300);
if (this.collection && !this.localdata.length) {
this.debounceGet();
}
},
computed: {
typePlaceholder() {
const text = {
'opendb-stat-app-versions': '版本',
'opendb-app-channels': '渠道',
'opendb-app-list': '应用'
}
const common = this.placeholder
const placeholder = text[this.collection]
return placeholder ?
common + placeholder :
common
},
valueCom() {
// #ifdef VUE3
return this.modelValue;
// #endif
// #ifndef VUE3
return this.value;
// #endif
},
textShow() {
// 长文本显示
let text = this.current;
if (text.length > 10) {
return text.slice(0, 25) + '...';
}
return text;
},
getOffsetByPlacement() {
switch (this.placement) {
case 'top':
return "bottom:calc(100% + 12px);";
case 'bottom':
return "top:calc(100% + 12px);";
}
}
},
watch: {
localdata: {
immediate: true,
handler(val, old) {
if (Array.isArray(val) && old !== val) {
this.mixinDatacomResData = val
}
}
},
valueCom(val, old) {
this.initDefVal()
},
mixinDatacomResData: {
immediate: true,
handler(val) {
if (val.length) {
this.initDefVal()
}
}
},
},
methods: {
debounce(fn, time = 100) {
let timer = null
return function(...args) {
if (timer) clearTimeout(timer)
timer = setTimeout(() => {
fn.apply(this, args)
}, time)
}
},
// 执行数据库查询
query() {
this.mixinDatacomEasyGet();
},
// 监听查询条件变更事件
onMixinDatacomPropsChange() {
if (this.collection) {
this.debounceGet();
}
},
initDefVal() {
let defValue = ''
if ((this.valueCom || this.valueCom === 0) && !this.isDisabled(this.valueCom)) {
defValue = this.valueCom
} else {
let strogeValue
if (this.collection) {
strogeValue = this.getCache()
}
if (strogeValue || strogeValue === 0) {
defValue = strogeValue
} else {
let defItem = ''
if (this.defItem > 0 && this.defItem <= this.mixinDatacomResData.length) {
defItem = this.mixinDatacomResData[this.defItem - 1].value
}
defValue = defItem
}
if (defValue || defValue === 0) {
this.emit(defValue)
}
}
const def = this.mixinDatacomResData.find(item => item.value === defValue)
this.current = def ? this.formatItemName(def) : ''
},
/**
* @param {[String, Number]} value
* 判断用户给的 value 是否同时为禁用状态
*/
isDisabled(value) {
let isDisabled = false;
this.mixinDatacomResData.forEach(item => {
if (item.value === value) {
isDisabled = item.disable
}
})
return isDisabled;
},
clearVal() {
this.emit('')
if (this.collection) {
this.removeCache()
}
},
change(item) {
if (!item.disable) {
this.showSelector = false
this.current = this.formatItemName(item)
this.emit(item.value)
}
},
emit(val) {
this.$emit('input', val)
this.$emit('update:modelValue', val)
this.$emit('change', val)
if (this.collection) {
this.setCache(val);
}
},
toggleSelector() {
if (this.disabled) {
return
}
this.showSelector = !this.showSelector
},
formatItemName(item) {
let {
text,
value,
channel_code
} = item
channel_code = channel_code ? `(${channel_code})` : ''
if (this.format) {
// 格式化输出
let str = "";
str = this.format;
for (let key in item) {
str = str.replace(new RegExp(`{${key}}`, "g"), item[key]);
}
return str;
} else {
return this.collection.indexOf('app-list') > 0 ?
`${text}(${value})` :
(
text ?
text :
`未命名${channel_code}`
)
}
},
// 获取当前加载的数据
getLoadData() {
return this.mixinDatacomResData;
},
// 获取当前缓存key
getCurrentCacheKey() {
return this.collection;
},
// 获取缓存
getCache(name = this.getCurrentCacheKey()) {
let cacheData = uni.getStorageSync(this.cacheKey) || {};
return cacheData[name];
},
// 设置缓存
setCache(value, name = this.getCurrentCacheKey()) {
let cacheData = uni.getStorageSync(this.cacheKey) || {};
cacheData[name] = value;
uni.setStorageSync(this.cacheKey, cacheData);
},
// 删除缓存
removeCache(name = this.getCurrentCacheKey()) {
let cacheData = uni.getStorageSync(this.cacheKey) || {};
delete cacheData[name];
uni.setStorageSync(this.cacheKey, cacheData);
},
}
}
</script>
<style lang="scss">
$uni-base-color: #6a6a6a !default;
$uni-main-color: #333 !default;
$uni-secondary-color: #909399 !default;
$uni-border-3: #e5e5e5;
/* #ifndef APP-NVUE */
@media screen and (max-width: 500px) {
.hide-on-phone {
display: none;
}
}
/* #endif */
.uni-stat__select {
display: flex;
align-items: center;
// padding: 15px;
/* #ifdef H5 */
cursor: pointer;
/* #endif */
width: 100%;
flex: 1;
box-sizing: border-box;
}
.uni-stat-box {
width: 100%;
flex: 1;
}
.uni-stat__actived {
width: 100%;
flex: 1;
// outline: 1px solid #2979ff;
}
.uni-label-text {
font-size: 14px;
font-weight: bold;
color: $uni-base-color;
margin: auto 0;
margin-right: 5px;
}
.uni-select {
font-size: 14px;
border: 1px solid $uni-border-3;
box-sizing: border-box;
border-radius: 4px;
padding: 0 5px;
padding-left: 10px;
position: relative;
/* #ifndef APP-NVUE */
display: flex;
user-select: none;
/* #endif */
flex-direction: row;
align-items: center;
border-bottom: solid 1px $uni-border-3;
width: 100%;
flex: 1;
height: 35px;
&--disabled {
background-color: #f5f7fa;
cursor: not-allowed;
}
}
.uni-select__label {
font-size: 16px;
// line-height: 22px;
height: 35px;
padding-right: 10px;
color: $uni-secondary-color;
}
.uni-select__input-box {
height: 35px;
position: relative;
/* #ifndef APP-NVUE */
display: flex;
/* #endif */
flex: 1;
flex-direction: row;
align-items: center;
}
.uni-select__input {
flex: 1;
font-size: 14px;
height: 22px;
line-height: 22px;
}
.uni-select__input-plac {
font-size: 14px;
color: $uni-secondary-color;
}
.uni-select__selector {
/* #ifndef APP-NVUE */
box-sizing: border-box;
/* #endif */
position: absolute;
left: 0;
width: 100%;
background-color: #FFFFFF;
border: 1px solid #EBEEF5;
border-radius: 6px;
box-shadow: 0 2px 12px 0 rgba(0, 0, 0, 0.1);
z-index: 3;
padding: 4px 0;
}
.uni-select__selector-scroll {
/* #ifndef APP-NVUE */
max-height: 200px;
box-sizing: border-box;
/* #endif */
}
/* #ifdef H5 */
@media (min-width: 768px) {
.uni-select__selector-scroll {
max-height: 600px;
}
}
/* #endif */
.uni-select__selector-empty,
.uni-select__selector-item {
/* #ifndef APP-NVUE */
display: flex;
cursor: pointer;
/* #endif */
line-height: 35px;
font-size: 14px;
text-align: center;
/* border-bottom: solid 1px $uni-border-3; */
padding: 0px 10px;
}
.uni-select__selector-item:hover {
background-color: #f9f9f9;
}
.uni-select__selector-empty:last-child,
.uni-select__selector-item:last-child {
/* #ifndef APP-NVUE */
border-bottom: none;
/* #endif */
}
.uni-select__selector__disabled {
opacity: 0.4;
cursor: default;
}
/* picker 弹出层通用的指示小三角 */
.uni-popper__arrow_bottom,
.uni-popper__arrow_bottom::after,
.uni-popper__arrow_top,
.uni-popper__arrow_top::after,
{
position: absolute;
display: block;
width: 0;
height: 0;
border-color: transparent;
border-style: solid;
border-width: 6px;
}
.uni-popper__arrow_bottom {
filter: drop-shadow(0 2px 12px rgba(0, 0, 0, 0.03));
top: -6px;
left: 10%;
margin-right: 3px;
border-top-width: 0;
border-bottom-color: #EBEEF5;
}
.uni-popper__arrow_bottom::after {
content: " ";
top: 1px;
margin-left: -6px;
border-top-width: 0;
border-bottom-color: #fff;
}
.uni-popper__arrow_top {
filter: drop-shadow(0 2px 12px rgba(0, 0, 0, 0.03));
bottom: -6px;
left: 10%;
margin-right: 3px;
border-bottom-width: 0;
border-top-color: #EBEEF5;
}
.uni-popper__arrow_top::after {
content: " ";
bottom: 1px;
margin-left: -6px;
border-bottom-width: 0;
border-top-color: #fff;
}
.uni-select__input-text {
// width: 280px;
width: 100%;
color: $uni-main-color;
white-space: nowrap;
text-overflow: ellipsis;
-o-text-overflow: ellipsis;
overflow: hidden;
}
.uni-select__input-placeholder {
color: $uni-base-color;
font-size: 12px;
}
.uni-select--mask {
position: fixed;
top: 0;
bottom: 0;
right: 0;
left: 0;
z-index: 2;
}
</style>
|
2301_77169380/aionix-2
|
uni_modules/uni-data-select/components/uni-data-select/uni-data-select.vue
|
Vue
|
mit
| 12,377
|
// yyyy-MM-dd hh:mm:ss.SSS 所有支持的类型
function pad(str, length = 2) {
str += ''
while (str.length < length) {
str = '0' + str
}
return str.slice(-length)
}
const parser = {
yyyy: (dateObj) => {
return pad(dateObj.year, 4)
},
yy: (dateObj) => {
return pad(dateObj.year)
},
MM: (dateObj) => {
return pad(dateObj.month)
},
M: (dateObj) => {
return dateObj.month
},
dd: (dateObj) => {
return pad(dateObj.day)
},
d: (dateObj) => {
return dateObj.day
},
hh: (dateObj) => {
return pad(dateObj.hour)
},
h: (dateObj) => {
return dateObj.hour
},
mm: (dateObj) => {
return pad(dateObj.minute)
},
m: (dateObj) => {
return dateObj.minute
},
ss: (dateObj) => {
return pad(dateObj.second)
},
s: (dateObj) => {
return dateObj.second
},
SSS: (dateObj) => {
return pad(dateObj.millisecond, 3)
},
S: (dateObj) => {
return dateObj.millisecond
},
}
// 这都n年了iOS依然不认识2020-12-12,需要转换为2020/12/12
function getDate(time) {
if (time instanceof Date) {
return time
}
switch (typeof time) {
case 'string':
{
// 2020-12-12T12:12:12.000Z、2020-12-12T12:12:12.000
if (time.indexOf('T') > -1) {
return new Date(time)
}
return new Date(time.replace(/-/g, '/'))
}
default:
return new Date(time)
}
}
export function formatDate(date, format = 'yyyy/MM/dd hh:mm:ss') {
if (!date && date !== 0) {
return ''
}
date = getDate(date)
const dateObj = {
year: date.getFullYear(),
month: date.getMonth() + 1,
day: date.getDate(),
hour: date.getHours(),
minute: date.getMinutes(),
second: date.getSeconds(),
millisecond: date.getMilliseconds()
}
const tokenRegExp = /yyyy|yy|MM|M|dd|d|hh|h|mm|m|ss|s|SSS|SS|S/
let flag = true
let result = format
while (flag) {
flag = false
result = result.replace(tokenRegExp, function(matched) {
flag = true
return parser[matched](dateObj)
})
}
return result
}
export function friendlyDate(time, {
locale = 'zh',
threshold = [60000, 3600000],
format = 'yyyy/MM/dd hh:mm:ss'
}) {
if (time === '-') {
return time
}
if (!time && time !== 0) {
return ''
}
const localeText = {
zh: {
year: '年',
month: '月',
day: '天',
hour: '小时',
minute: '分钟',
second: '秒',
ago: '前',
later: '后',
justNow: '刚刚',
soon: '马上',
template: '{num}{unit}{suffix}'
},
en: {
year: 'year',
month: 'month',
day: 'day',
hour: 'hour',
minute: 'minute',
second: 'second',
ago: 'ago',
later: 'later',
justNow: 'just now',
soon: 'soon',
template: '{num} {unit} {suffix}'
}
}
const text = localeText[locale] || localeText.zh
let date = getDate(time)
let ms = date.getTime() - Date.now()
let absMs = Math.abs(ms)
if (absMs < threshold[0]) {
return ms < 0 ? text.justNow : text.soon
}
if (absMs >= threshold[1]) {
return formatDate(date, format)
}
let num
let unit
let suffix = text.later
if (ms < 0) {
suffix = text.ago
ms = -ms
}
const seconds = Math.floor((ms) / 1000)
const minutes = Math.floor(seconds / 60)
const hours = Math.floor(minutes / 60)
const days = Math.floor(hours / 24)
const months = Math.floor(days / 30)
const years = Math.floor(months / 12)
switch (true) {
case years > 0:
num = years
unit = text.year
break
case months > 0:
num = months
unit = text.month
break
case days > 0:
num = days
unit = text.day
break
case hours > 0:
num = hours
unit = text.hour
break
case minutes > 0:
num = minutes
unit = text.minute
break
default:
num = seconds
unit = text.second
break
}
if (locale === 'en') {
if (num === 1) {
num = 'a'
} else {
unit += 's'
}
}
return text.template.replace(/{\s*num\s*}/g, num + '').replace(/{\s*unit\s*}/g, unit).replace(/{\s*suffix\s*}/g,
suffix)
}
|
2301_77169380/aionix-2
|
uni_modules/uni-dateformat/components/uni-dateformat/date-format.js
|
JavaScript
|
mit
| 3,847
|
<template>
<text>{{dateShow}}</text>
</template>
<script>
import {friendlyDate} from './date-format.js'
/**
* Dateformat 日期格式化
* @description 日期格式化组件
* @tutorial https://ext.dcloud.net.cn/plugin?id=3279
* @property {Object|String|Number} date 日期对象/日期字符串/时间戳
* @property {String} locale 格式化使用的语言
* @value zh 中文
* @value en 英文
* @property {Array} threshold 应用不同类型格式化的阈值
* @property {String} format 输出日期字符串时的格式
*/
export default {
name: 'uniDateformat',
props: {
date: {
type: [Object, String, Number],
default () {
return '-'
}
},
locale: {
type: String,
default: 'zh',
},
threshold: {
type: Array,
default () {
return [0, 0]
}
},
format: {
type: String,
default: 'yyyy/MM/dd hh:mm:ss'
},
// refreshRate使用不当可能导致性能问题,谨慎使用
refreshRate: {
type: [Number, String],
default: 0
}
},
data() {
return {
refreshMark: 0
}
},
computed: {
dateShow() {
this.refreshMark
return friendlyDate(this.date, {
locale: this.locale,
threshold: this.threshold,
format: this.format
})
}
},
watch: {
refreshRate: {
handler() {
this.setAutoRefresh()
},
immediate: true
}
},
methods: {
refresh() {
this.refreshMark++
},
setAutoRefresh() {
clearInterval(this.refreshInterval)
if (this.refreshRate) {
this.refreshInterval = setInterval(() => {
this.refresh()
}, parseInt(this.refreshRate))
}
}
}
}
</script>
<style>
</style>
|
2301_77169380/aionix-2
|
uni_modules/uni-dateformat/components/uni-dateformat/uni-dateformat.vue
|
Vue
|
mit
| 1,698
|
<template>
<view class="uni-calendar-item__weeks-box" :class="{
'uni-calendar-item--disable':weeks.disable,
'uni-calendar-item--before-checked-x':weeks.beforeMultiple,
'uni-calendar-item--multiple': weeks.multiple,
'uni-calendar-item--after-checked-x':weeks.afterMultiple,
}" @click="choiceDate(weeks)" @mouseenter="handleMousemove(weeks)">
<view class="uni-calendar-item__weeks-box-item" :class="{
'uni-calendar-item--checked':calendar.fullDate === weeks.fullDate && (calendar.userChecked || !checkHover),
'uni-calendar-item--checked-range-text': checkHover,
'uni-calendar-item--before-checked':weeks.beforeMultiple,
'uni-calendar-item--multiple': weeks.multiple,
'uni-calendar-item--after-checked':weeks.afterMultiple,
'uni-calendar-item--disable':weeks.disable,
}">
<text v-if="selected && weeks.extraInfo" class="uni-calendar-item__weeks-box-circle"></text>
<text class="uni-calendar-item__weeks-box-text uni-calendar-item__weeks-box-text-disable uni-calendar-item--checked-text">{{weeks.date}}</text>
</view>
<view :class="{'uni-calendar-item--today': weeks.isToday}"></view>
</view>
</template>
<script>
export default {
props: {
weeks: {
type: Object,
default () {
return {}
}
},
calendar: {
type: Object,
default: () => {
return {}
}
},
selected: {
type: Array,
default: () => {
return []
}
},
checkHover: {
type: Boolean,
default: false
}
},
methods: {
choiceDate(weeks) {
this.$emit('change', weeks)
},
handleMousemove(weeks) {
this.$emit('handleMouse', weeks)
}
}
}
</script>
<style lang="scss" >
$uni-primary: #007aff !default;
.uni-calendar-item__weeks-box {
flex: 1;
/* #ifndef APP-NVUE */
display: flex;
/* #endif */
flex-direction: column;
justify-content: center;
align-items: center;
margin: 1px 0;
position: relative;
}
.uni-calendar-item__weeks-box-text {
font-size: 14px;
// font-family: Lato-Bold, Lato;
font-weight: bold;
color: darken($color: $uni-primary, $amount: 40%);
}
.uni-calendar-item__weeks-box-item {
position: relative;
/* #ifndef APP-NVUE */
display: flex;
/* #endif */
flex-direction: column;
justify-content: center;
align-items: center;
width: 40px;
height: 40px;
/* #ifdef H5 */
cursor: pointer;
/* #endif */
}
.uni-calendar-item__weeks-box-circle {
position: absolute;
top: 5px;
right: 5px;
width: 8px;
height: 8px;
border-radius: 8px;
background-color: #dd524d;
}
.uni-calendar-item__weeks-box .uni-calendar-item--disable {
cursor: default;
}
.uni-calendar-item--disable .uni-calendar-item__weeks-box-text-disable {
color: #D1D1D1;
}
.uni-calendar-item--today {
position: absolute;
top: 10px;
right: 17%;
background-color: #dd524d;
width:6px;
height: 6px;
border-radius: 50%;
}
.uni-calendar-item--extra {
color: #dd524d;
opacity: 0.8;
}
.uni-calendar-item__weeks-box .uni-calendar-item--checked {
background-color: $uni-primary;
border-radius: 50%;
box-sizing: border-box;
border: 3px solid #fff;
}
.uni-calendar-item--checked .uni-calendar-item--checked-text {
color: #fff;
}
.uni-calendar-item--multiple .uni-calendar-item--checked-range-text {
color: #333;
}
.uni-calendar-item--multiple {
background-color: #F6F7FC;
// color: #fff;
}
.uni-calendar-item--multiple .uni-calendar-item--before-checked,
.uni-calendar-item--multiple .uni-calendar-item--after-checked {
background-color: $uni-primary;
border-radius: 50%;
box-sizing: border-box;
border: 3px solid #F6F7FC;
}
.uni-calendar-item--before-checked .uni-calendar-item--checked-text,
.uni-calendar-item--after-checked .uni-calendar-item--checked-text {
color: #fff;
}
.uni-calendar-item--before-checked-x {
border-top-left-radius: 50px;
border-bottom-left-radius: 50px;
box-sizing: border-box;
background-color: #F6F7FC;
}
.uni-calendar-item--after-checked-x {
border-top-right-radius: 50px;
border-bottom-right-radius: 50px;
background-color: #F6F7FC;
}
</style>
|
2301_77169380/aionix-2
|
uni_modules/uni-datetime-picker/components/uni-datetime-picker/calendar-item.vue
|
Vue
|
mit
| 4,112
|
<template>
<view class="uni-calendar" @mouseleave="leaveCale">
<view v-if="!insert && show" class="uni-calendar__mask" :class="{'uni-calendar--mask-show':aniMaskShow}"
@click="maskClick"></view>
<view v-if="insert || show" class="uni-calendar__content"
:class="{'uni-calendar--fixed':!insert,'uni-calendar--ani-show':aniMaskShow, 'uni-calendar__content-mobile': aniMaskShow}">
<view class="uni-calendar__header" :class="{'uni-calendar__header-mobile' :!insert}">
<view class="uni-calendar__header-btn-box" @click.stop="changeMonth('pre')">
<view class="uni-calendar__header-btn uni-calendar--left"></view>
</view>
<picker mode="date" :value="date" fields="month" @change="bindDateChange">
<text
class="uni-calendar__header-text">{{ (nowDate.year||'') + yearText + ( nowDate.month||'') + monthText}}</text>
</picker>
<view class="uni-calendar__header-btn-box" @click.stop="changeMonth('next')">
<view class="uni-calendar__header-btn uni-calendar--right"></view>
</view>
<view v-if="!insert" class="dialog-close" @click="maskClick">
<view class="dialog-close-plus" data-id="close"></view>
<view class="dialog-close-plus dialog-close-rotate" data-id="close"></view>
</view>
</view>
<view class="uni-calendar__box">
<view v-if="showMonth" class="uni-calendar__box-bg">
<text class="uni-calendar__box-bg-text">{{nowDate.month}}</text>
</view>
<view class="uni-calendar__weeks" style="padding-bottom: 7px;">
<view class="uni-calendar__weeks-day">
<text class="uni-calendar__weeks-day-text">{{SUNText}}</text>
</view>
<view class="uni-calendar__weeks-day">
<text class="uni-calendar__weeks-day-text">{{MONText}}</text>
</view>
<view class="uni-calendar__weeks-day">
<text class="uni-calendar__weeks-day-text">{{TUEText}}</text>
</view>
<view class="uni-calendar__weeks-day">
<text class="uni-calendar__weeks-day-text">{{WEDText}}</text>
</view>
<view class="uni-calendar__weeks-day">
<text class="uni-calendar__weeks-day-text">{{THUText}}</text>
</view>
<view class="uni-calendar__weeks-day">
<text class="uni-calendar__weeks-day-text">{{FRIText}}</text>
</view>
<view class="uni-calendar__weeks-day">
<text class="uni-calendar__weeks-day-text">{{SATText}}</text>
</view>
</view>
<view class="uni-calendar__weeks" v-for="(item,weekIndex) in weeks" :key="weekIndex">
<view class="uni-calendar__weeks-item" v-for="(weeks,weeksIndex) in item" :key="weeksIndex">
<calendar-item class="uni-calendar-item--hook" :weeks="weeks" :calendar="calendar" :selected="selected"
:checkHover="range" @change="choiceDate" @handleMouse="handleMouse">
</calendar-item>
</view>
</view>
</view>
<view v-if="!insert && !range && hasTime" class="uni-date-changed uni-calendar--fixed-top"
style="padding: 0 80px;">
<view class="uni-date-changed--time-date">{{tempSingleDate ? tempSingleDate : selectDateText}}</view>
<time-picker type="time" :start="timepickerStartTime" :end="timepickerEndTime" v-model="time"
:disabled="!tempSingleDate" :border="false" :hide-second="hideSecond" class="time-picker-style">
</time-picker>
</view>
<view v-if="!insert && range && hasTime" class="uni-date-changed uni-calendar--fixed-top">
<view class="uni-date-changed--time-start">
<view class="uni-date-changed--time-date">{{tempRange.before ? tempRange.before : startDateText}}
</view>
<time-picker type="time" :start="timepickerStartTime" v-model="timeRange.startTime" :border="false"
:hide-second="hideSecond" :disabled="!tempRange.before" class="time-picker-style">
</time-picker>
</view>
<view style="line-height: 50px;">
<uni-icons type="arrowthinright" color="#999"></uni-icons>
</view>
<view class="uni-date-changed--time-end">
<view class="uni-date-changed--time-date">{{tempRange.after ? tempRange.after : endDateText}}</view>
<time-picker type="time" :end="timepickerEndTime" v-model="timeRange.endTime" :border="false"
:hide-second="hideSecond" :disabled="!tempRange.after" class="time-picker-style">
</time-picker>
</view>
</view>
<view v-if="!insert" class="uni-date-changed uni-date-btn--ok">
<view class="uni-datetime-picker--btn" @click="confirm">{{confirmText}}</view>
</view>
</view>
</view>
</template>
<script>
import {
Calendar,
getDate,
getTime
} from './util.js';
import calendarItem from './calendar-item.vue'
import timePicker from './time-picker.vue'
import {
initVueI18n
} from '@dcloudio/uni-i18n'
import i18nMessages from './i18n/index.js'
const {
t
} = initVueI18n(i18nMessages)
/**
* Calendar 日历
* @description 日历组件可以查看日期,选择任意范围内的日期,打点操作。常用场景如:酒店日期预订、火车机票选择购买日期、上下班打卡等
* @tutorial https://ext.dcloud.net.cn/plugin?id=56
* @property {String} date 自定义当前时间,默认为今天
* @property {String} startDate 日期选择范围-开始日期
* @property {String} endDate 日期选择范围-结束日期
* @property {Boolean} range 范围选择
* @property {Boolean} insert = [true|false] 插入模式,默认为false
* @value true 弹窗模式
* @value false 插入模式
* @property {Boolean} clearDate = [true|false] 弹窗模式是否清空上次选择内容
* @property {Array} selected 打点,期待格式[{date: '2019-06-27', info: '签到', data: { custom: '自定义信息', name: '自定义消息头',xxx:xxx... }}]
* @property {Boolean} showMonth 是否选择月份为背景
* @property {[String} defaultValue 选择器打开时默认显示的时间
* @event {Function} change 日期改变,`insert :ture` 时生效
* @event {Function} confirm 确认选择`insert :false` 时生效
* @event {Function} monthSwitch 切换月份时触发
* @example <uni-calendar :insert="true" :start-date="'2019-3-2'":end-date="'2019-5-20'"@change="change" />
*/
export default {
components: {
calendarItem,
timePicker
},
options: {
// #ifdef MP-TOUTIAO
virtualHost: false,
// #endif
// #ifndef MP-TOUTIAO
virtualHost: true
// #endif
},
props: {
date: {
type: String,
default: ''
},
defTime: {
type: [String, Object],
default: ''
},
selectableTimes: {
type: [Object],
default () {
return {}
}
},
selected: {
type: Array,
default () {
return []
}
},
startDate: {
type: String,
default: ''
},
endDate: {
type: String,
default: ''
},
startPlaceholder: {
type: String,
default: ''
},
endPlaceholder: {
type: String,
default: ''
},
range: {
type: Boolean,
default: false
},
hasTime: {
type: Boolean,
default: false
},
insert: {
type: Boolean,
default: true
},
showMonth: {
type: Boolean,
default: true
},
clearDate: {
type: Boolean,
default: true
},
checkHover: {
type: Boolean,
default: true
},
hideSecond: {
type: [Boolean],
default: false
},
pleStatus: {
type: Object,
default () {
return {
before: '',
after: '',
data: [],
fulldate: ''
}
}
},
defaultValue: {
type: [String, Object, Array],
default: ''
}
},
data() {
return {
show: false,
weeks: [],
calendar: {},
nowDate: {},
aniMaskShow: false,
firstEnter: true,
time: '',
timeRange: {
startTime: '',
endTime: ''
},
tempSingleDate: '',
tempRange: {
before: '',
after: ''
}
}
},
watch: {
date: {
immediate: true,
handler(newVal) {
if (!this.range) {
this.tempSingleDate = newVal
setTimeout(() => {
this.init(newVal)
}, 100)
}
}
},
defTime: {
immediate: true,
handler(newVal) {
if (!this.range) {
this.time = newVal
} else {
this.timeRange.startTime = newVal.start
this.timeRange.endTime = newVal.end
}
}
},
startDate(val) {
// 字节小程序 watch 早于 created
if (!this.cale) {
return
}
this.cale.setStartDate(val)
this.cale.setDate(this.nowDate.fullDate)
this.weeks = this.cale.weeks
},
endDate(val) {
// 字节小程序 watch 早于 created
if (!this.cale) {
return
}
this.cale.setEndDate(val)
this.cale.setDate(this.nowDate.fullDate)
this.weeks = this.cale.weeks
},
selected(newVal) {
// 字节小程序 watch 早于 created
if (!this.cale) {
return
}
this.cale.setSelectInfo(this.nowDate.fullDate, newVal)
this.weeks = this.cale.weeks
},
pleStatus: {
immediate: true,
handler(newVal) {
const {
before,
after,
fulldate,
which
} = newVal
this.tempRange.before = before
this.tempRange.after = after
setTimeout(() => {
if (fulldate) {
this.cale.setHoverMultiple(fulldate)
if (before && after) {
this.cale.lastHover = true
if (this.rangeWithinMonth(after, before)) return
this.setDate(before)
} else {
this.cale.setMultiple(fulldate)
this.setDate(this.nowDate.fullDate)
this.calendar.fullDate = ''
this.cale.lastHover = false
}
} else {
// 字节小程序 watch 早于 created
if (!this.cale) {
return
}
this.cale.setDefaultMultiple(before, after)
if (which === 'left' && before) {
this.setDate(before)
this.weeks = this.cale.weeks
} else if (after) {
this.setDate(after)
this.weeks = this.cale.weeks
}
this.cale.lastHover = true
}
}, 16)
}
}
},
computed: {
timepickerStartTime() {
const activeDate = this.range ? this.tempRange.before : this.calendar.fullDate
return activeDate === this.startDate ? this.selectableTimes.start : ''
},
timepickerEndTime() {
const activeDate = this.range ? this.tempRange.after : this.calendar.fullDate
return activeDate === this.endDate ? this.selectableTimes.end : ''
},
/**
* for i18n
*/
selectDateText() {
return t("uni-datetime-picker.selectDate")
},
startDateText() {
return this.startPlaceholder || t("uni-datetime-picker.startDate")
},
endDateText() {
return this.endPlaceholder || t("uni-datetime-picker.endDate")
},
okText() {
return t("uni-datetime-picker.ok")
},
yearText() {
return t("uni-datetime-picker.year")
},
monthText() {
return t("uni-datetime-picker.month")
},
MONText() {
return t("uni-calender.MON")
},
TUEText() {
return t("uni-calender.TUE")
},
WEDText() {
return t("uni-calender.WED")
},
THUText() {
return t("uni-calender.THU")
},
FRIText() {
return t("uni-calender.FRI")
},
SATText() {
return t("uni-calender.SAT")
},
SUNText() {
return t("uni-calender.SUN")
},
confirmText() {
return t("uni-calender.confirm")
},
},
created() {
// 获取日历方法实例
this.cale = new Calendar({
selected: this.selected,
startDate: this.startDate,
endDate: this.endDate,
range: this.range,
})
// 选中某一天
this.init(this.date)
},
methods: {
leaveCale() {
this.firstEnter = true
},
handleMouse(weeks) {
if (weeks.disable) return
if (this.cale.lastHover) return
let {
before,
after
} = this.cale.multipleStatus
if (!before) return
this.calendar = weeks
// 设置范围选
this.cale.setHoverMultiple(this.calendar.fullDate)
this.weeks = this.cale.weeks
// hover时,进入一个日历,更新另一个
if (this.firstEnter) {
this.$emit('firstEnterCale', this.cale.multipleStatus)
this.firstEnter = false
}
},
rangeWithinMonth(A, B) {
const [yearA, monthA] = A.split('-')
const [yearB, monthB] = B.split('-')
return yearA === yearB && monthA === monthB
},
// 蒙版点击事件
maskClick() {
this.close()
this.$emit('maskClose')
},
clearCalender() {
if (this.range) {
this.timeRange.startTime = ''
this.timeRange.endTime = ''
this.tempRange.before = ''
this.tempRange.after = ''
this.cale.multipleStatus.before = ''
this.cale.multipleStatus.after = ''
this.cale.multipleStatus.data = []
this.cale.lastHover = false
} else {
this.time = ''
this.tempSingleDate = ''
}
this.calendar.fullDate = ''
this.setDate(new Date())
},
bindDateChange(e) {
const value = e.detail.value + '-1'
this.setDate(value)
},
/**
* 初始化日期显示
* @param {Object} date
*/
init(date) {
// 字节小程序 watch 早于 created
if (!this.cale) {
return
}
this.cale.setDate(date || new Date())
this.weeks = this.cale.weeks
this.nowDate = this.cale.getInfo(date)
this.calendar = {
...this.nowDate
}
if (!date) {
// 优化date为空默认不选中今天
this.calendar.fullDate = ''
if (this.defaultValue && !this.range) {
// 暂时只支持移动端非范围选择
const defaultDate = new Date(this.defaultValue)
const fullDate = getDate(defaultDate)
const year = defaultDate.getFullYear()
const month = defaultDate.getMonth() + 1
const date = defaultDate.getDate()
const day = defaultDate.getDay()
this.calendar = {
fullDate,
year,
month,
date,
day
},
this.tempSingleDate = fullDate
this.time = getTime(defaultDate, this.hideSecond)
}
}
},
/**
* 打开日历弹窗
*/
open() {
// 弹窗模式并且清理数据
if (this.clearDate && !this.insert) {
this.cale.cleanMultipleStatus()
this.init(this.date)
}
this.show = true
this.$nextTick(() => {
setTimeout(() => {
this.aniMaskShow = true
}, 50)
})
},
/**
* 关闭日历弹窗
*/
close() {
this.aniMaskShow = false
this.$nextTick(() => {
setTimeout(() => {
this.show = false
this.$emit('close')
}, 300)
})
},
/**
* 确认按钮
*/
confirm() {
this.setEmit('confirm')
this.close()
},
/**
* 变化触发
*/
change(isSingleChange) {
if (!this.insert && !isSingleChange) return
this.setEmit('change')
},
/**
* 选择月份触发
*/
monthSwitch() {
let {
year,
month
} = this.nowDate
this.$emit('monthSwitch', {
year,
month: Number(month)
})
},
/**
* 派发事件
* @param {Object} name
*/
setEmit(name) {
if (!this.range) {
if (!this.calendar.fullDate) {
this.calendar = this.cale.getInfo(new Date())
this.tempSingleDate = this.calendar.fullDate
}
if (this.hasTime && !this.time) {
this.time = getTime(new Date(), this.hideSecond)
}
}
let {
year,
month,
date,
fullDate,
extraInfo
} = this.calendar
this.$emit(name, {
range: this.cale.multipleStatus,
year,
month,
date,
time: this.time,
timeRange: this.timeRange,
fulldate: fullDate,
extraInfo: extraInfo || {}
})
},
/**
* 选择天触发
* @param {Object} weeks
*/
choiceDate(weeks) {
if (weeks.disable) return
this.calendar = weeks
this.calendar.userChecked = true
// 设置多选
this.cale.setMultiple(this.calendar.fullDate, true)
this.weeks = this.cale.weeks
this.tempSingleDate = this.calendar.fullDate
const beforeDate = new Date(this.cale.multipleStatus.before).getTime()
const afterDate = new Date(this.cale.multipleStatus.after).getTime()
if (beforeDate > afterDate && afterDate) {
this.tempRange.before = this.cale.multipleStatus.after
this.tempRange.after = this.cale.multipleStatus.before
} else {
this.tempRange.before = this.cale.multipleStatus.before
this.tempRange.after = this.cale.multipleStatus.after
}
this.change(true)
},
changeMonth(type) {
let newDate
if (type === 'pre') {
newDate = this.cale.getPreMonthObj(this.nowDate.fullDate).fullDate
} else if (type === 'next') {
newDate = this.cale.getNextMonthObj(this.nowDate.fullDate).fullDate
}
this.setDate(newDate)
this.monthSwitch()
},
/**
* 设置日期
* @param {Object} date
*/
setDate(date) {
this.cale.setDate(date)
this.weeks = this.cale.weeks
this.nowDate = this.cale.getInfo(date)
}
}
}
</script>
<style lang="scss">
$uni-primary: #007aff !default;
.uni-calendar {
/* #ifndef APP-NVUE */
display: flex;
/* #endif */
flex-direction: column;
}
.uni-calendar__mask {
position: fixed;
bottom: 0;
top: 0;
left: 0;
right: 0;
background-color: rgba(0, 0, 0, 0.4);
transition-property: opacity;
transition-duration: 0.3s;
opacity: 0;
/* #ifndef APP-NVUE */
z-index: 99;
/* #endif */
}
.uni-calendar--mask-show {
opacity: 1
}
.uni-calendar--fixed {
position: fixed;
bottom: calc(var(--window-bottom));
left: 0;
right: 0;
transition-property: transform;
transition-duration: 0.3s;
transform: translateY(460px);
/* #ifndef APP-NVUE */
z-index: 99;
/* #endif */
}
.uni-calendar--ani-show {
transform: translateY(0);
}
.uni-calendar__content {
background-color: #fff;
}
.uni-calendar__content-mobile {
border-top-left-radius: 10px;
border-top-right-radius: 10px;
box-shadow: 0px 0px 5px 3px rgba(0, 0, 0, 0.1);
}
.uni-calendar__header {
position: relative;
/* #ifndef APP-NVUE */
display: flex;
/* #endif */
flex-direction: row;
justify-content: center;
align-items: center;
height: 50px;
}
.uni-calendar__header-mobile {
padding: 10px;
padding-bottom: 0;
}
.uni-calendar--fixed-top {
/* #ifndef APP-NVUE */
display: flex;
/* #endif */
flex-direction: row;
justify-content: space-between;
border-top-color: rgba(0, 0, 0, 0.4);
border-top-style: solid;
border-top-width: 1px;
}
.uni-calendar--fixed-width {
width: 50px;
}
.uni-calendar__backtoday {
position: absolute;
right: 0;
top: 25rpx;
padding: 0 5px;
padding-left: 10px;
height: 25px;
line-height: 25px;
font-size: 12px;
border-top-left-radius: 25px;
border-bottom-left-radius: 25px;
color: #fff;
background-color: #f1f1f1;
}
.uni-calendar__header-text {
text-align: center;
width: 100px;
font-size: 15px;
color: #666;
}
.uni-calendar__button-text {
text-align: center;
width: 100px;
font-size: 14px;
color: $uni-primary;
/* #ifndef APP-NVUE */
letter-spacing: 3px;
/* #endif */
}
.uni-calendar__header-btn-box {
/* #ifndef APP-NVUE */
display: flex;
/* #endif */
flex-direction: row;
align-items: center;
justify-content: center;
width: 50px;
height: 50px;
}
.uni-calendar__header-btn {
width: 9px;
height: 9px;
border-left-color: #808080;
border-left-style: solid;
border-left-width: 1px;
border-top-color: #555555;
border-top-style: solid;
border-top-width: 1px;
}
.uni-calendar--left {
transform: rotate(-45deg);
}
.uni-calendar--right {
transform: rotate(135deg);
}
.uni-calendar__weeks {
position: relative;
/* #ifndef APP-NVUE */
display: flex;
/* #endif */
flex-direction: row;
}
.uni-calendar__weeks-item {
flex: 1;
}
.uni-calendar__weeks-day {
flex: 1;
/* #ifndef APP-NVUE */
display: flex;
/* #endif */
flex-direction: column;
justify-content: center;
align-items: center;
height: 40px;
border-bottom-color: #F5F5F5;
border-bottom-style: solid;
border-bottom-width: 1px;
}
.uni-calendar__weeks-day-text {
font-size: 12px;
color: #B2B2B2;
}
.uni-calendar__box {
position: relative;
// padding: 0 10px;
padding-bottom: 7px;
}
.uni-calendar__box-bg {
/* #ifndef APP-NVUE */
display: flex;
/* #endif */
justify-content: center;
align-items: center;
position: absolute;
top: 0;
left: 0;
right: 0;
bottom: 0;
}
.uni-calendar__box-bg-text {
font-size: 200px;
font-weight: bold;
color: #999;
opacity: 0.1;
text-align: center;
/* #ifndef APP-NVUE */
line-height: 1;
/* #endif */
}
.uni-date-changed {
padding: 0 10px;
// line-height: 50px;
text-align: center;
color: #333;
border-top-color: #DCDCDC;
;
border-top-style: solid;
border-top-width: 1px;
flex: 1;
}
.uni-date-btn--ok {
padding: 20px 15px;
}
.uni-date-changed--time-start {
/* #ifndef APP-NVUE */
display: flex;
/* #endif */
align-items: center;
}
.uni-date-changed--time-end {
/* #ifndef APP-NVUE */
display: flex;
/* #endif */
align-items: center;
}
.uni-date-changed--time-date {
color: #999;
line-height: 50px;
/* #ifdef MP-TOUTIAO */
font-size: 16px;
/* #endif */
margin-right: 5px;
// opacity: 0.6;
}
.time-picker-style {
// width: 62px;
/* #ifndef APP-NVUE */
display: flex;
/* #endif */
justify-content: center;
align-items: center
}
.mr-10 {
margin-right: 10px;
}
.dialog-close {
position: absolute;
top: 0;
right: 0;
bottom: 0;
/* #ifndef APP-NVUE */
display: flex;
/* #endif */
flex-direction: row;
align-items: center;
padding: 0 25px;
margin-top: 10px;
}
.dialog-close-plus {
width: 16px;
height: 2px;
background-color: #737987;
border-radius: 2px;
transform: rotate(45deg);
}
.dialog-close-rotate {
position: absolute;
transform: rotate(-45deg);
}
.uni-datetime-picker--btn {
border-radius: 100px;
height: 40px;
line-height: 40px;
background-color: $uni-primary;
color: #fff;
font-size: 16px;
letter-spacing: 2px;
}
/* #ifndef APP-NVUE */
.uni-datetime-picker--btn:active {
opacity: 0.7;
}
/* #endif */
</style>
|
2301_77169380/aionix-2
|
uni_modules/uni-datetime-picker/components/uni-datetime-picker/calendar.vue
|
Vue
|
mit
| 22,102
|
import en from './en.json'
import zhHans from './zh-Hans.json'
import zhHant from './zh-Hant.json'
export default {
en,
'zh-Hans': zhHans,
'zh-Hant': zhHant
}
|
2301_77169380/aionix-2
|
uni_modules/uni-datetime-picker/components/uni-datetime-picker/i18n/index.js
|
JavaScript
|
mit
| 162
|
<template>
<view class="uni-datetime-picker">
<view @click="initTimePicker">
<slot>
<view class="uni-datetime-picker-timebox-pointer"
:class="{'uni-datetime-picker-disabled': disabled, 'uni-datetime-picker-timebox': border}">
<text class="uni-datetime-picker-text">{{time}}</text>
<view v-if="!time" class="uni-datetime-picker-time">
<text class="uni-datetime-picker-text">{{selectTimeText}}</text>
</view>
</view>
</slot>
</view>
<view v-if="visible" id="mask" class="uni-datetime-picker-mask" @click="tiggerTimePicker"></view>
<view v-if="visible" class="uni-datetime-picker-popup" :class="[dateShow && timeShow ? '' : 'fix-nvue-height']"
:style="fixNvueBug">
<view class="uni-title">
<text class="uni-datetime-picker-text">{{selectTimeText}}</text>
</view>
<view v-if="dateShow" class="uni-datetime-picker__container-box">
<picker-view class="uni-datetime-picker-view" :indicator-style="indicatorStyle" :value="ymd"
@change="bindDateChange">
<picker-view-column>
<view class="uni-datetime-picker-item" v-for="(item,index) in years" :key="index">
<text class="uni-datetime-picker-item">{{lessThanTen(item)}}</text>
</view>
</picker-view-column>
<picker-view-column>
<view class="uni-datetime-picker-item" v-for="(item,index) in months" :key="index">
<text class="uni-datetime-picker-item">{{lessThanTen(item)}}</text>
</view>
</picker-view-column>
<picker-view-column>
<view class="uni-datetime-picker-item" v-for="(item,index) in days" :key="index">
<text class="uni-datetime-picker-item">{{lessThanTen(item)}}</text>
</view>
</picker-view-column>
</picker-view>
<!-- 兼容 nvue 不支持伪类 -->
<text class="uni-datetime-picker-sign sign-left">-</text>
<text class="uni-datetime-picker-sign sign-right">-</text>
</view>
<view v-if="timeShow" class="uni-datetime-picker__container-box">
<picker-view class="uni-datetime-picker-view" :class="[hideSecond ? 'time-hide-second' : '']"
:indicator-style="indicatorStyle" :value="hms" @change="bindTimeChange">
<picker-view-column>
<view class="uni-datetime-picker-item" v-for="(item,index) in hours" :key="index">
<text class="uni-datetime-picker-item">{{lessThanTen(item)}}</text>
</view>
</picker-view-column>
<picker-view-column>
<view class="uni-datetime-picker-item" v-for="(item,index) in minutes" :key="index">
<text class="uni-datetime-picker-item">{{lessThanTen(item)}}</text>
</view>
</picker-view-column>
<picker-view-column v-if="!hideSecond">
<view class="uni-datetime-picker-item" v-for="(item,index) in seconds" :key="index">
<text class="uni-datetime-picker-item">{{lessThanTen(item)}}</text>
</view>
</picker-view-column>
</picker-view>
<!-- 兼容 nvue 不支持伪类 -->
<text class="uni-datetime-picker-sign" :class="[hideSecond ? 'sign-center' : 'sign-left']">:</text>
<text v-if="!hideSecond" class="uni-datetime-picker-sign sign-right">:</text>
</view>
<view class="uni-datetime-picker-btn">
<view @click="clearTime">
<text class="uni-datetime-picker-btn-text">{{clearText}}</text>
</view>
<view class="uni-datetime-picker-btn-group">
<view class="uni-datetime-picker-cancel" @click="tiggerTimePicker">
<text class="uni-datetime-picker-btn-text">{{cancelText}}</text>
</view>
<view @click="setTime">
<text class="uni-datetime-picker-btn-text">{{okText}}</text>
</view>
</view>
</view>
</view>
</view>
</template>
<script>
import {
initVueI18n
} from '@dcloudio/uni-i18n'
import i18nMessages from './i18n/index.js'
const {
t
} = initVueI18n(i18nMessages)
import {
fixIosDateFormat
} from './util'
/**
* DatetimePicker 时间选择器
* @description 可以同时选择日期和时间的选择器
* @tutorial https://ext.dcloud.net.cn/plugin?id=xxx
* @property {String} type = [datetime | date | time] 显示模式
* @property {Boolean} multiple = [true|false] 是否多选
* @property {String|Number} value 默认值
* @property {String|Number} start 起始日期或时间
* @property {String|Number} end 起始日期或时间
* @property {String} return-type = [timestamp | string]
* @event {Function} change 选中发生变化触发
*/
export default {
name: 'UniDatetimePicker',
data() {
return {
indicatorStyle: `height: 50px;`,
visible: false,
fixNvueBug: {},
dateShow: true,
timeShow: true,
title: '日期和时间',
// 输入框当前时间
time: '',
// 当前的年月日时分秒
year: 1920,
month: 0,
day: 0,
hour: 0,
minute: 0,
second: 0,
// 起始时间
startYear: 1920,
startMonth: 1,
startDay: 1,
startHour: 0,
startMinute: 0,
startSecond: 0,
// 结束时间
endYear: 2120,
endMonth: 12,
endDay: 31,
endHour: 23,
endMinute: 59,
endSecond: 59,
}
},
options: {
// #ifdef MP-TOUTIAO
virtualHost: false,
// #endif
// #ifndef MP-TOUTIAO
virtualHost: true
// #endif
},
props: {
type: {
type: String,
default: 'datetime'
},
value: {
type: [String, Number],
default: ''
},
modelValue: {
type: [String, Number],
default: ''
},
start: {
type: [Number, String],
default: ''
},
end: {
type: [Number, String],
default: ''
},
returnType: {
type: String,
default: 'string'
},
disabled: {
type: [Boolean, String],
default: false
},
border: {
type: [Boolean, String],
default: true
},
hideSecond: {
type: [Boolean, String],
default: false
}
},
watch: {
// #ifndef VUE3
value: {
handler(newVal) {
if (newVal) {
this.parseValue(fixIosDateFormat(newVal))
this.initTime(false)
} else {
this.time = ''
this.parseValue(Date.now())
}
},
immediate: true
},
// #endif
// #ifdef VUE3
modelValue: {
handler(newVal) {
if (newVal) {
this.parseValue(fixIosDateFormat(newVal))
this.initTime(false)
} else {
this.time = ''
this.parseValue(Date.now())
}
},
immediate: true
},
// #endif
type: {
handler(newValue) {
if (newValue === 'date') {
this.dateShow = true
this.timeShow = false
this.title = '日期'
} else if (newValue === 'time') {
this.dateShow = false
this.timeShow = true
this.title = '时间'
} else {
this.dateShow = true
this.timeShow = true
this.title = '日期和时间'
}
},
immediate: true
},
start: {
handler(newVal) {
this.parseDatetimeRange(fixIosDateFormat(newVal), 'start')
},
immediate: true
},
end: {
handler(newVal) {
this.parseDatetimeRange(fixIosDateFormat(newVal), 'end')
},
immediate: true
},
// 月、日、时、分、秒可选范围变化后,检查当前值是否在范围内,不在则当前值重置为可选范围第一项
months(newVal) {
this.checkValue('month', this.month, newVal)
},
days(newVal) {
this.checkValue('day', this.day, newVal)
},
hours(newVal) {
this.checkValue('hour', this.hour, newVal)
},
minutes(newVal) {
this.checkValue('minute', this.minute, newVal)
},
seconds(newVal) {
this.checkValue('second', this.second, newVal)
}
},
computed: {
// 当前年、月、日、时、分、秒选择范围
years() {
return this.getCurrentRange('year')
},
months() {
return this.getCurrentRange('month')
},
days() {
return this.getCurrentRange('day')
},
hours() {
return this.getCurrentRange('hour')
},
minutes() {
return this.getCurrentRange('minute')
},
seconds() {
return this.getCurrentRange('second')
},
// picker 当前值数组
ymd() {
return [this.year - this.minYear, this.month - this.minMonth, this.day - this.minDay]
},
hms() {
return [this.hour - this.minHour, this.minute - this.minMinute, this.second - this.minSecond]
},
// 当前 date 是 start
currentDateIsStart() {
return this.year === this.startYear && this.month === this.startMonth && this.day === this.startDay
},
// 当前 date 是 end
currentDateIsEnd() {
return this.year === this.endYear && this.month === this.endMonth && this.day === this.endDay
},
// 当前年、月、日、时、分、秒的最小值和最大值
minYear() {
return this.startYear
},
maxYear() {
return this.endYear
},
minMonth() {
if (this.year === this.startYear) {
return this.startMonth
} else {
return 1
}
},
maxMonth() {
if (this.year === this.endYear) {
return this.endMonth
} else {
return 12
}
},
minDay() {
if (this.year === this.startYear && this.month === this.startMonth) {
return this.startDay
} else {
return 1
}
},
maxDay() {
if (this.year === this.endYear && this.month === this.endMonth) {
return this.endDay
} else {
return this.daysInMonth(this.year, this.month)
}
},
minHour() {
if (this.type === 'datetime') {
if (this.currentDateIsStart) {
return this.startHour
} else {
return 0
}
}
if (this.type === 'time') {
return this.startHour
}
},
maxHour() {
if (this.type === 'datetime') {
if (this.currentDateIsEnd) {
return this.endHour
} else {
return 23
}
}
if (this.type === 'time') {
return this.endHour
}
},
minMinute() {
if (this.type === 'datetime') {
if (this.currentDateIsStart && this.hour === this.startHour) {
return this.startMinute
} else {
return 0
}
}
if (this.type === 'time') {
if (this.hour === this.startHour) {
return this.startMinute
} else {
return 0
}
}
},
maxMinute() {
if (this.type === 'datetime') {
if (this.currentDateIsEnd && this.hour === this.endHour) {
return this.endMinute
} else {
return 59
}
}
if (this.type === 'time') {
if (this.hour === this.endHour) {
return this.endMinute
} else {
return 59
}
}
},
minSecond() {
if (this.type === 'datetime') {
if (this.currentDateIsStart && this.hour === this.startHour && this.minute === this.startMinute) {
return this.startSecond
} else {
return 0
}
}
if (this.type === 'time') {
if (this.hour === this.startHour && this.minute === this.startMinute) {
return this.startSecond
} else {
return 0
}
}
},
maxSecond() {
if (this.type === 'datetime') {
if (this.currentDateIsEnd && this.hour === this.endHour && this.minute === this.endMinute) {
return this.endSecond
} else {
return 59
}
}
if (this.type === 'time') {
if (this.hour === this.endHour && this.minute === this.endMinute) {
return this.endSecond
} else {
return 59
}
}
},
/**
* for i18n
*/
selectTimeText() {
return t("uni-datetime-picker.selectTime")
},
okText() {
return t("uni-datetime-picker.ok")
},
clearText() {
return t("uni-datetime-picker.clear")
},
cancelText() {
return t("uni-datetime-picker.cancel")
}
},
mounted() {
// #ifdef APP-NVUE
const res = uni.getSystemInfoSync();
this.fixNvueBug = {
top: res.windowHeight / 2,
left: res.windowWidth / 2
}
// #endif
},
methods: {
/**
* @param {Object} item
* 小于 10 在前面加个 0
*/
lessThanTen(item) {
return item < 10 ? '0' + item : item
},
/**
* 解析时分秒字符串,例如:00:00:00
* @param {String} timeString
*/
parseTimeType(timeString) {
if (timeString) {
let timeArr = timeString.split(':')
this.hour = Number(timeArr[0])
this.minute = Number(timeArr[1])
this.second = Number(timeArr[2])
}
},
/**
* 解析选择器初始值,类型可以是字符串、时间戳,例如:2000-10-02、'08:30:00'、 1610695109000
* @param {String | Number} datetime
*/
initPickerValue(datetime) {
let defaultValue = null
if (datetime) {
defaultValue = this.compareValueWithStartAndEnd(datetime, this.start, this.end)
} else {
defaultValue = Date.now()
defaultValue = this.compareValueWithStartAndEnd(defaultValue, this.start, this.end)
}
this.parseValue(defaultValue)
},
/**
* 初始值规则:
* - 用户设置初始值 value
* - 设置了起始时间 start、终止时间 end,并 start < value < end,初始值为 value, 否则初始值为 start
* - 只设置了起始时间 start,并 start < value,初始值为 value,否则初始值为 start
* - 只设置了终止时间 end,并 value < end,初始值为 value,否则初始值为 end
* - 无起始终止时间,则初始值为 value
* - 无初始值 value,则初始值为当前本地时间 Date.now()
* @param {Object} value
* @param {Object} dateBase
*/
compareValueWithStartAndEnd(value, start, end) {
let winner = null
value = this.superTimeStamp(value)
start = this.superTimeStamp(start)
end = this.superTimeStamp(end)
if (start && end) {
if (value < start) {
winner = new Date(start)
} else if (value > end) {
winner = new Date(end)
} else {
winner = new Date(value)
}
} else if (start && !end) {
winner = start <= value ? new Date(value) : new Date(start)
} else if (!start && end) {
winner = value <= end ? new Date(value) : new Date(end)
} else {
winner = new Date(value)
}
return winner
},
/**
* 转换为可比较的时间戳,接受日期、时分秒、时间戳
* @param {Object} value
*/
superTimeStamp(value) {
let dateBase = ''
if (this.type === 'time' && value && typeof value === 'string') {
const now = new Date()
const year = now.getFullYear()
const month = now.getMonth() + 1
const day = now.getDate()
dateBase = year + '/' + month + '/' + day + ' '
}
if (Number(value)) {
value = parseInt(value)
dateBase = 0
}
return this.createTimeStamp(dateBase + value)
},
/**
* 解析默认值 value,字符串、时间戳
* @param {Object} defaultTime
*/
parseValue(value) {
if (!value) {
return
}
if (this.type === 'time' && typeof value === "string") {
this.parseTimeType(value)
} else {
let defaultDate = null
defaultDate = new Date(value)
if (this.type !== 'time') {
this.year = defaultDate.getFullYear()
this.month = defaultDate.getMonth() + 1
this.day = defaultDate.getDate()
}
if (this.type !== 'date') {
this.hour = defaultDate.getHours()
this.minute = defaultDate.getMinutes()
this.second = defaultDate.getSeconds()
}
}
if (this.hideSecond) {
this.second = 0
}
},
/**
* 解析可选择时间范围 start、end,年月日字符串、时间戳
* @param {Object} defaultTime
*/
parseDatetimeRange(point, pointType) {
// 时间为空,则重置为初始值
if (!point) {
if (pointType === 'start') {
this.startYear = 1920
this.startMonth = 1
this.startDay = 1
this.startHour = 0
this.startMinute = 0
this.startSecond = 0
}
if (pointType === 'end') {
this.endYear = 2120
this.endMonth = 12
this.endDay = 31
this.endHour = 23
this.endMinute = 59
this.endSecond = 59
}
return
}
if (this.type === 'time') {
const pointArr = point.split(':')
this[pointType + 'Hour'] = Number(pointArr[0])
this[pointType + 'Minute'] = Number(pointArr[1])
this[pointType + 'Second'] = Number(pointArr[2])
} else {
if (!point) {
pointType === 'start' ? this.startYear = this.year - 60 : this.endYear = this.year + 60
return
}
if (Number(point)) {
point = parseInt(point)
}
// datetime 的 end 没有时分秒, 则不限制
const hasTime = /[0-9]:[0-9]/
if (this.type === 'datetime' && pointType === 'end' && typeof point === 'string' && !hasTime.test(
point)) {
point = point + ' 23:59:59'
}
const pointDate = new Date(point)
this[pointType + 'Year'] = pointDate.getFullYear()
this[pointType + 'Month'] = pointDate.getMonth() + 1
this[pointType + 'Day'] = pointDate.getDate()
if (this.type === 'datetime') {
this[pointType + 'Hour'] = pointDate.getHours()
this[pointType + 'Minute'] = pointDate.getMinutes()
this[pointType + 'Second'] = pointDate.getSeconds()
}
}
},
// 获取 年、月、日、时、分、秒 当前可选范围
getCurrentRange(value) {
const range = []
for (let i = this['min' + this.capitalize(value)]; i <= this['max' + this.capitalize(value)]; i++) {
range.push(i)
}
return range
},
// 字符串首字母大写
capitalize(str) {
return str.charAt(0).toUpperCase() + str.slice(1)
},
// 检查当前值是否在范围内,不在则当前值重置为可选范围第一项
checkValue(name, value, values) {
if (values.indexOf(value) === -1) {
this[name] = values[0]
}
},
// 每个月的实际天数
daysInMonth(year, month) { // Use 1 for January, 2 for February, etc.
return new Date(year, month, 0).getDate();
},
/**
* 生成时间戳
* @param {Object} time
*/
createTimeStamp(time) {
if (!time) return
if (typeof time === "number") {
return time
} else {
time = time.replace(/-/g, '/')
if (this.type === 'date') {
time = time + ' ' + '00:00:00'
}
return Date.parse(time)
}
},
/**
* 生成日期或时间的字符串
*/
createDomSting() {
const yymmdd = this.year +
'-' +
this.lessThanTen(this.month) +
'-' +
this.lessThanTen(this.day)
let hhmmss = this.lessThanTen(this.hour) +
':' +
this.lessThanTen(this.minute)
if (!this.hideSecond) {
hhmmss = hhmmss + ':' + this.lessThanTen(this.second)
}
if (this.type === 'date') {
return yymmdd
} else if (this.type === 'time') {
return hhmmss
} else {
return yymmdd + ' ' + hhmmss
}
},
/**
* 初始化返回值,并抛出 change 事件
*/
initTime(emit = true) {
this.time = this.createDomSting()
if (!emit) return
if (this.returnType === 'timestamp' && this.type !== 'time') {
this.$emit('change', this.createTimeStamp(this.time))
this.$emit('input', this.createTimeStamp(this.time))
this.$emit('update:modelValue', this.createTimeStamp(this.time))
} else {
this.$emit('change', this.time)
this.$emit('input', this.time)
this.$emit('update:modelValue', this.time)
}
},
/**
* 用户选择日期或时间更新 data
* @param {Object} e
*/
bindDateChange(e) {
const val = e.detail.value
this.year = this.years[val[0]]
this.month = this.months[val[1]]
this.day = this.days[val[2]]
},
bindTimeChange(e) {
const val = e.detail.value
this.hour = this.hours[val[0]]
this.minute = this.minutes[val[1]]
this.second = this.seconds[val[2]]
},
/**
* 初始化弹出层
*/
initTimePicker() {
if (this.disabled) return
const value = fixIosDateFormat(this.time)
this.initPickerValue(value)
this.visible = !this.visible
},
/**
* 触发或关闭弹框
*/
tiggerTimePicker(e) {
this.visible = !this.visible
},
/**
* 用户点击“清空”按钮,清空当前值
*/
clearTime() {
this.time = ''
this.$emit('change', this.time)
this.$emit('input', this.time)
this.$emit('update:modelValue', this.time)
this.tiggerTimePicker()
},
/**
* 用户点击“确定”按钮
*/
setTime() {
this.initTime()
this.tiggerTimePicker()
}
}
}
</script>
<style lang="scss">
$uni-primary: #007aff !default;
.uni-datetime-picker {
/* #ifndef APP-NVUE */
/* width: 100%; */
/* #endif */
}
.uni-datetime-picker-view {
height: 130px;
width: 270px;
/* #ifndef APP-NVUE */
cursor: pointer;
/* #endif */
}
.uni-datetime-picker-item {
height: 50px;
line-height: 50px;
text-align: center;
font-size: 14px;
}
.uni-datetime-picker-btn {
margin-top: 60px;
/* #ifndef APP-NVUE */
display: flex;
cursor: pointer;
/* #endif */
flex-direction: row;
justify-content: space-between;
}
.uni-datetime-picker-btn-text {
font-size: 14px;
color: $uni-primary;
}
.uni-datetime-picker-btn-group {
/* #ifndef APP-NVUE */
display: flex;
/* #endif */
flex-direction: row;
}
.uni-datetime-picker-cancel {
margin-right: 30px;
}
.uni-datetime-picker-mask {
position: fixed;
bottom: 0px;
top: 0px;
left: 0px;
right: 0px;
background-color: rgba(0, 0, 0, 0.4);
transition-duration: 0.3s;
z-index: 998;
}
.uni-datetime-picker-popup {
border-radius: 8px;
padding: 30px;
width: 270px;
/* #ifdef APP-NVUE */
height: 500px;
/* #endif */
/* #ifdef APP-NVUE */
width: 330px;
/* #endif */
background-color: #fff;
position: fixed;
top: 50%;
left: 50%;
transform: translate(-50%, -50%);
transition-duration: 0.3s;
z-index: 999;
}
.fix-nvue-height {
/* #ifdef APP-NVUE */
height: 330px;
/* #endif */
}
.uni-datetime-picker-time {
color: grey;
}
.uni-datetime-picker-column {
height: 50px;
}
.uni-datetime-picker-timebox {
border: 1px solid #E5E5E5;
border-radius: 5px;
padding: 7px 10px;
/* #ifndef APP-NVUE */
box-sizing: border-box;
cursor: pointer;
/* #endif */
}
.uni-datetime-picker-timebox-pointer {
/* #ifndef APP-NVUE */
cursor: pointer;
/* #endif */
}
.uni-datetime-picker-disabled {
opacity: 0.4;
/* #ifdef H5 */
cursor: not-allowed !important;
/* #endif */
}
.uni-datetime-picker-text {
font-size: 14px;
line-height: 50px
}
.uni-datetime-picker-sign {
position: absolute;
top: 53px;
/* 减掉 10px 的元素高度,兼容nvue */
color: #999;
/* #ifdef APP-NVUE */
font-size: 16px;
/* #endif */
}
.sign-left {
left: 86px;
}
.sign-right {
right: 86px;
}
.sign-center {
left: 135px;
}
.uni-datetime-picker__container-box {
position: relative;
display: flex;
align-items: center;
justify-content: center;
margin-top: 40px;
}
.time-hide-second {
width: 180px;
}
</style>
|
2301_77169380/aionix-2
|
uni_modules/uni-datetime-picker/components/uni-datetime-picker/time-picker.vue
|
Vue
|
mit
| 22,881
|
<template>
<view class="uni-date">
<view class="uni-date-editor" @click="show">
<slot>
<view class="uni-date-editor--x"
:class="{'uni-date-editor--x__disabled': disabled,'uni-date-x--border': border}">
<view v-if="!isRange" class="uni-date-x uni-date-single">
<uni-icons class="icon-calendar" type="calendar" color="#c0c4cc" size="22"></uni-icons>
<view class="uni-date__x-input">{{ displayValue || singlePlaceholderText }}</view>
</view>
<view v-else class="uni-date-x uni-date-range">
<uni-icons class="icon-calendar" type="calendar" color="#c0c4cc" size="22"></uni-icons>
<view class="uni-date__x-input text-center">{{ displayRangeValue.startDate || startPlaceholderText }}</view>
<view class="range-separator">{{rangeSeparator}}</view>
<view class="uni-date__x-input text-center">{{ displayRangeValue.endDate || endPlaceholderText }}</view>
</view>
<view v-if="showClearIcon" class="uni-date__icon-clear" @click.stop="clear">
<uni-icons type="clear" color="#c0c4cc" size="22"></uni-icons>
</view>
</view>
</slot>
</view>
<view v-show="pickerVisible" class="uni-date-mask--pc" @click="close"></view>
<view v-if="!isPhone" v-show="pickerVisible" ref="datePicker" class="uni-date-picker__container">
<view v-if="!isRange" class="uni-date-single--x" :style="pickerPositionStyle">
<view class="uni-popper__arrow"></view>
<view v-if="hasTime" class="uni-date-changed popup-x-header">
<input class="uni-date__input text-center" type="text" v-model="inputDate" :placeholder="selectDateText" />
<time-picker type="time" v-model="pickerTime" :border="false" :disabled="!inputDate"
:start="timepickerStartTime" :end="timepickerEndTime" :hideSecond="hideSecond" style="width: 100%;">
<input class="uni-date__input text-center" type="text" v-model="pickerTime" :placeholder="selectTimeText"
:disabled="!inputDate" />
</time-picker>
</view>
<Calendar ref="pcSingle" :showMonth="false" :start-date="calendarRange.startDate"
:end-date="calendarRange.endDate" :date="calendarDate" @change="singleChange" :default-value="defaultValue"
style="padding: 0 8px;" />
<view v-if="hasTime" class="popup-x-footer">
<text class="confirm-text" @click="confirmSingleChange">{{okText}}</text>
</view>
</view>
<view v-else class="uni-date-range--x" :style="pickerPositionStyle">
<view class="uni-popper__arrow"></view>
<view v-if="hasTime" class="popup-x-header uni-date-changed">
<view class="popup-x-header--datetime">
<input class="uni-date__input uni-date-range__input" type="text" v-model="tempRange.startDate"
:placeholder="startDateText" />
<time-picker type="time" v-model="tempRange.startTime" :start="timepickerStartTime" :border="false"
:disabled="!tempRange.startDate" :hideSecond="hideSecond">
<input class="uni-date__input uni-date-range__input" type="text" v-model="tempRange.startTime"
:placeholder="startTimeText" :disabled="!tempRange.startDate" />
</time-picker>
</view>
<uni-icons type="arrowthinright" color="#999" style="line-height: 40px;"></uni-icons>
<view class="popup-x-header--datetime">
<input class="uni-date__input uni-date-range__input" type="text" v-model="tempRange.endDate"
:placeholder="endDateText" />
<time-picker type="time" v-model="tempRange.endTime" :end="timepickerEndTime" :border="false"
:disabled="!tempRange.endDate" :hideSecond="hideSecond">
<input class="uni-date__input uni-date-range__input" type="text" v-model="tempRange.endTime"
:placeholder="endTimeText" :disabled="!tempRange.endDate" />
</time-picker>
</view>
</view>
<view class="popup-x-body">
<Calendar ref="left" :showMonth="false" :start-date="calendarRange.startDate"
:end-date="calendarRange.endDate" :range="true" :pleStatus="endMultipleStatus" @change="leftChange"
@firstEnterCale="updateRightCale" style="padding: 0 8px;"/>
<Calendar ref="right" :showMonth="false" :start-date="calendarRange.startDate"
:end-date="calendarRange.endDate" :range="true" @change="rightChange" :pleStatus="startMultipleStatus"
@firstEnterCale="updateLeftCale" style="padding: 0 8px;border-left: 1px solid #F1F1F1;" />
</view>
<view v-if="hasTime" class="popup-x-footer">
<text @click="clear">{{clearText}}</text>
<text class="confirm-text" @click="confirmRangeChange">{{okText}}</text>
</view>
</view>
</view>
<Calendar v-if="isPhone" ref="mobile" :clearDate="false" :date="calendarDate" :defTime="mobileCalendarTime"
:start-date="calendarRange.startDate" :end-date="calendarRange.endDate" :selectableTimes="mobSelectableTime"
:startPlaceholder="startPlaceholder" :endPlaceholder="endPlaceholder" :default-value="defaultValue"
:pleStatus="endMultipleStatus" :showMonth="false" :range="isRange" :hasTime="hasTime" :insert="false"
:hideSecond="hideSecond" @confirm="mobileChange" @maskClose="close" @change="calendarClick"/>
</view>
</template>
<script>
/**
* DatetimePicker 时间选择器
* @description 同时支持 PC 和移动端使用日历选择日期和日期范围
* @tutorial https://ext.dcloud.net.cn/plugin?id=3962
* @property {String} type 选择器类型
* @property {String|Number|Array|Date} value 绑定值
* @property {String} placeholder 单选择时的占位内容
* @property {String} start 起始时间
* @property {String} end 终止时间
* @property {String} start-placeholder 范围选择时开始日期的占位内容
* @property {String} end-placeholder 范围选择时结束日期的占位内容
* @property {String} range-separator 选择范围时的分隔符
* @property {Boolean} border = [true|false] 是否有边框
* @property {Boolean} disabled = [true|false] 是否禁用
* @property {Boolean} clearIcon = [true|false] 是否显示清除按钮(仅PC端适用)
* @property {[String} defaultValue 选择器打开时默认显示的时间
* @event {Function} change 确定日期时触发的事件
* @event {Function} maskClick 点击遮罩层触发的事件
* @event {Function} show 打开弹出层
* @event {Function} close 关闭弹出层
* @event {Function} clear 清除上次选中的状态和值
**/
import Calendar from './calendar.vue'
import TimePicker from './time-picker.vue'
import {
initVueI18n
} from '@dcloudio/uni-i18n'
import i18nMessages from './i18n/index.js'
import {
getDateTime,
getDate,
getTime,
getDefaultSecond,
dateCompare,
checkDate,
fixIosDateFormat
} from './util'
export default {
name: 'UniDatetimePicker',
options: {
// #ifdef MP-TOUTIAO
virtualHost: false,
// #endif
// #ifndef MP-TOUTIAO
virtualHost: true
// #endif
},
components: {
Calendar,
TimePicker
},
data() {
return {
isRange: false,
hasTime: false,
displayValue: '',
inputDate: '',
calendarDate: '',
pickerTime: '',
calendarRange: {
startDate: '',
startTime: '',
endDate: '',
endTime: ''
},
displayRangeValue: {
startDate: '',
endDate: '',
},
tempRange: {
startDate: '',
startTime: '',
endDate: '',
endTime: ''
},
// 左右日历同步数据
startMultipleStatus: {
before: '',
after: '',
data: [],
fulldate: ''
},
endMultipleStatus: {
before: '',
after: '',
data: [],
fulldate: ''
},
pickerVisible: false,
pickerPositionStyle: null,
isEmitValue: false,
isPhone: false,
isFirstShow: true,
i18nT: () => {}
}
},
props: {
type: {
type: String,
default: 'datetime'
},
value: {
type: [String, Number, Array, Date],
default: ''
},
modelValue: {
type: [String, Number, Array, Date],
default: ''
},
start: {
type: [Number, String],
default: ''
},
end: {
type: [Number, String],
default: ''
},
returnType: {
type: String,
default: 'string'
},
placeholder: {
type: String,
default: ''
},
startPlaceholder: {
type: String,
default: ''
},
endPlaceholder: {
type: String,
default: ''
},
rangeSeparator: {
type: String,
default: '-'
},
border: {
type: [Boolean],
default: true
},
disabled: {
type: [Boolean],
default: false
},
clearIcon: {
type: [Boolean],
default: true
},
hideSecond: {
type: [Boolean],
default: false
},
defaultValue: {
type: [String, Object, Array],
default: ''
}
},
watch: {
type: {
immediate: true,
handler(newVal) {
this.hasTime = newVal.indexOf('time') !== -1
this.isRange = newVal.indexOf('range') !== -1
}
},
// #ifndef VUE3
value: {
immediate: true,
handler(newVal) {
if (this.isEmitValue) {
this.isEmitValue = false
return
}
this.initPicker(newVal)
}
},
// #endif
// #ifdef VUE3
modelValue: {
immediate: true,
handler(newVal) {
if (this.isEmitValue) {
this.isEmitValue = false
return
}
this.initPicker(newVal)
}
},
// #endif
start: {
immediate: true,
handler(newVal) {
if (!newVal) return
this.calendarRange.startDate = getDate(newVal)
if (this.hasTime) {
this.calendarRange.startTime = getTime(newVal)
}
}
},
end: {
immediate: true,
handler(newVal) {
if (!newVal) return
this.calendarRange.endDate = getDate(newVal)
if (this.hasTime) {
this.calendarRange.endTime = getTime(newVal, this.hideSecond)
}
}
},
},
computed: {
timepickerStartTime() {
const activeDate = this.isRange ? this.tempRange.startDate : this.inputDate
return activeDate === this.calendarRange.startDate ? this.calendarRange.startTime : ''
},
timepickerEndTime() {
const activeDate = this.isRange ? this.tempRange.endDate : this.inputDate
return activeDate === this.calendarRange.endDate ? this.calendarRange.endTime : ''
},
mobileCalendarTime() {
const timeRange = {
start: this.tempRange.startTime,
end: this.tempRange.endTime
}
return this.isRange ? timeRange : this.pickerTime
},
mobSelectableTime() {
return {
start: this.calendarRange.startTime,
end: this.calendarRange.endTime
}
},
datePopupWidth() {
// todo
return this.isRange ? 653 : 301
},
/**
* for i18n
*/
singlePlaceholderText() {
return this.placeholder || (this.type === 'date' ? this.selectDateText : this.selectDateTimeText)
},
startPlaceholderText() {
return this.startPlaceholder || this.startDateText
},
endPlaceholderText() {
return this.endPlaceholder || this.endDateText
},
selectDateText() {
return this.i18nT("uni-datetime-picker.selectDate")
},
selectDateTimeText() {
return this.i18nT("uni-datetime-picker.selectDateTime")
},
selectTimeText() {
return this.i18nT("uni-datetime-picker.selectTime")
},
startDateText() {
return this.startPlaceholder || this.i18nT("uni-datetime-picker.startDate")
},
startTimeText() {
return this.i18nT("uni-datetime-picker.startTime")
},
endDateText() {
return this.endPlaceholder || this.i18nT("uni-datetime-picker.endDate")
},
endTimeText() {
return this.i18nT("uni-datetime-picker.endTime")
},
okText() {
return this.i18nT("uni-datetime-picker.ok")
},
clearText() {
return this.i18nT("uni-datetime-picker.clear")
},
showClearIcon() {
return this.clearIcon && !this.disabled && (this.displayValue || (this.displayRangeValue.startDate && this
.displayRangeValue.endDate))
}
},
created() {
this.initI18nT()
this.platform()
},
methods: {
initI18nT() {
const vueI18n = initVueI18n(i18nMessages)
this.i18nT = vueI18n.t
},
initPicker(newVal) {
if ((!newVal && !this.defaultValue) || Array.isArray(newVal) && !newVal.length) {
this.$nextTick(() => {
this.clear(false)
})
return
}
if (!Array.isArray(newVal) && !this.isRange) {
if (newVal) {
this.displayValue = this.inputDate = this.calendarDate = getDate(newVal)
if (this.hasTime) {
this.pickerTime = getTime(newVal, this.hideSecond)
this.displayValue = `${this.displayValue} ${this.pickerTime}`
}
} else if (this.defaultValue) {
this.inputDate = this.calendarDate = getDate(this.defaultValue)
if (this.hasTime) {
this.pickerTime = getTime(this.defaultValue, this.hideSecond)
}
}
} else {
const [before, after] = newVal
if (!before && !after) return
const beforeDate = getDate(before)
const beforeTime = getTime(before, this.hideSecond)
const afterDate = getDate(after)
const afterTime = getTime(after, this.hideSecond)
const startDate = beforeDate
const endDate = afterDate
this.displayRangeValue.startDate = this.tempRange.startDate = startDate
this.displayRangeValue.endDate = this.tempRange.endDate = endDate
if (this.hasTime) {
this.displayRangeValue.startDate = `${beforeDate} ${beforeTime}`
this.displayRangeValue.endDate = `${afterDate} ${afterTime}`
this.tempRange.startTime = beforeTime
this.tempRange.endTime = afterTime
}
const defaultRange = {
before: beforeDate,
after: afterDate
}
this.startMultipleStatus = Object.assign({}, this.startMultipleStatus, defaultRange, {
which: 'right'
})
this.endMultipleStatus = Object.assign({}, this.endMultipleStatus, defaultRange, {
which: 'left'
})
}
},
updateLeftCale(e) {
const left = this.$refs.left
// 设置范围选
left.cale.setHoverMultiple(e.after)
left.setDate(this.$refs.left.nowDate.fullDate)
},
updateRightCale(e) {
const right = this.$refs.right
// 设置范围选
right.cale.setHoverMultiple(e.after)
right.setDate(this.$refs.right.nowDate.fullDate)
},
platform() {
if (typeof navigator !== "undefined") {
this.isPhone = navigator.userAgent.toLowerCase().indexOf('mobile') !== -1
return
}
const {
windowWidth
} = uni.getSystemInfoSync()
this.isPhone = windowWidth <= 500
this.windowWidth = windowWidth
},
show() {
this.$emit("show")
if (this.disabled) {
return
}
this.platform()
if (this.isPhone) {
setTimeout(() => {
this.$refs.mobile.open()
}, 0);
return
}
this.pickerPositionStyle = {
top: '10px'
}
const dateEditor = uni.createSelectorQuery().in(this).select(".uni-date-editor")
dateEditor.boundingClientRect(rect => {
if (this.windowWidth - rect.left < this.datePopupWidth) {
this.pickerPositionStyle.right = 0
}
}).exec()
setTimeout(() => {
this.pickerVisible = !this.pickerVisible
if (!this.isPhone && this.isRange && this.isFirstShow) {
this.isFirstShow = false
const {
startDate,
endDate
} = this.calendarRange
if (startDate && endDate) {
if (this.diffDate(startDate, endDate) < 30) {
this.$refs.right.changeMonth('pre')
}
} else {
// this.$refs.right.changeMonth('next')
if (this.isPhone) {
this.$refs.right.cale.lastHover = false;
}
}
}
}, 50)
},
close() {
setTimeout(() => {
this.pickerVisible = false
this.$emit('maskClick', this.value)
this.$refs.mobile && this.$refs.mobile.close()
}, 20)
},
setEmit(value) {
if (this.returnType === "timestamp" || this.returnType === "date") {
if (!Array.isArray(value)) {
if (!this.hasTime) {
value = value + ' ' + '00:00:00'
}
value = this.createTimestamp(value)
if (this.returnType === "date") {
value = new Date(value)
}
} else {
if (!this.hasTime) {
value[0] = value[0] + ' ' + '00:00:00'
value[1] = value[1] + ' ' + '00:00:00'
}
value[0] = this.createTimestamp(value[0])
value[1] = this.createTimestamp(value[1])
if (this.returnType === "date") {
value[0] = new Date(value[0])
value[1] = new Date(value[1])
}
}
}
this.$emit('update:modelValue', value)
this.$emit('input', value)
this.$emit('change', value)
this.isEmitValue = true
},
createTimestamp(date) {
date = fixIosDateFormat(date)
return Date.parse(new Date(date))
},
singleChange(e) {
this.calendarDate = this.inputDate = e.fulldate
if (this.hasTime) return
this.confirmSingleChange()
},
confirmSingleChange() {
if (!checkDate(this.inputDate)) {
const now = new Date()
this.calendarDate = this.inputDate = getDate(now)
this.pickerTime = getTime(now, this.hideSecond)
}
let startLaterInputDate = false
let startDate, startTime
if (this.start) {
let startString = this.start
if (typeof this.start === 'number') {
startString = getDateTime(this.start, this.hideSecond)
}
[startDate, startTime] = startString.split(' ')
if (this.start && !dateCompare(startDate, this.inputDate)) {
startLaterInputDate = true
this.inputDate = startDate
}
}
let endEarlierInputDate = false
let endDate, endTime
if (this.end) {
let endString = this.end
if (typeof this.end === 'number') {
endString = getDateTime(this.end, this.hideSecond)
}
[endDate, endTime] = endString.split(' ')
if (this.end && !dateCompare(this.inputDate, endDate)) {
endEarlierInputDate = true
this.inputDate = endDate
}
}
if (this.hasTime) {
if (startLaterInputDate) {
this.pickerTime = startTime || getDefaultSecond(this.hideSecond)
}
if (endEarlierInputDate) {
this.pickerTime = endTime || getDefaultSecond(this.hideSecond)
}
if (!this.pickerTime) {
this.pickerTime = getTime(Date.now(), this.hideSecond)
}
this.displayValue = `${this.inputDate} ${this.pickerTime}`
} else {
this.displayValue = this.inputDate
}
this.setEmit(this.displayValue)
this.pickerVisible = false
},
leftChange(e) {
const {
before,
after
} = e.range
this.rangeChange(before, after)
const obj = {
before: e.range.before,
after: e.range.after,
data: e.range.data,
fulldate: e.fulldate
}
this.startMultipleStatus = Object.assign({}, this.startMultipleStatus, obj)
this.$emit('calendarClick', e)
},
rightChange(e) {
const {
before,
after
} = e.range
this.rangeChange(before, after)
const obj = {
before: e.range.before,
after: e.range.after,
data: e.range.data,
fulldate: e.fulldate
}
this.endMultipleStatus = Object.assign({}, this.endMultipleStatus, obj)
this.$emit('calendarClick', e)
},
mobileChange(e) {
if (this.isRange) {
const {
before,
after
} = e.range
if (!before) {
return;
}
this.handleStartAndEnd(before, after, true)
if (this.hasTime) {
const {
startTime,
endTime
} = e.timeRange
this.tempRange.startTime = startTime
this.tempRange.endTime = endTime
}
this.confirmRangeChange()
} else {
if (this.hasTime) {
this.displayValue = e.fulldate + ' ' + e.time
} else {
this.displayValue = e.fulldate
}
this.setEmit(this.displayValue)
}
this.$refs.mobile.close()
},
rangeChange(before, after) {
if (!(before && after)) return
this.handleStartAndEnd(before, after, true)
if (this.hasTime) return
this.confirmRangeChange()
},
confirmRangeChange() {
if (!this.tempRange.startDate || !this.tempRange.endDate) {
this.pickerVisible = false
return
}
if (!checkDate(this.tempRange.startDate)) {
this.tempRange.startDate = getDate(Date.now())
}
if (!checkDate(this.tempRange.endDate)) {
this.tempRange.endDate = getDate(Date.now())
}
let start, end
let startDateLaterRangeStartDate = false
let startDateLaterRangeEndDate = false
let startDate, startTime
if (this.start) {
let startString = this.start
if (typeof this.start === 'number') {
startString = getDateTime(this.start, this.hideSecond)
}
[startDate, startTime] = startString.split(' ')
if (this.start && !dateCompare(this.start, this.tempRange.startDate)) {
startDateLaterRangeStartDate = true
this.tempRange.startDate = startDate
}
if (this.start && !dateCompare(this.start, this.tempRange.endDate)) {
startDateLaterRangeEndDate = true
this.tempRange.endDate = startDate
}
}
let endDateEarlierRangeStartDate = false
let endDateEarlierRangeEndDate = false
let endDate, endTime
if (this.end) {
let endString = this.end
if (typeof this.end === 'number') {
endString = getDateTime(this.end, this.hideSecond)
}
[endDate, endTime] = endString.split(' ')
if (this.end && !dateCompare(this.tempRange.startDate, this.end)) {
endDateEarlierRangeStartDate = true
this.tempRange.startDate = endDate
}
if (this.end && !dateCompare(this.tempRange.endDate, this.end)) {
endDateEarlierRangeEndDate = true
this.tempRange.endDate = endDate
}
}
if (!this.hasTime) {
start = this.displayRangeValue.startDate = this.tempRange.startDate
end = this.displayRangeValue.endDate = this.tempRange.endDate
} else {
if (startDateLaterRangeStartDate) {
this.tempRange.startTime = startTime || getDefaultSecond(this.hideSecond)
} else if (endDateEarlierRangeStartDate) {
this.tempRange.startTime = endTime || getDefaultSecond(this.hideSecond)
}
if (!this.tempRange.startTime) {
this.tempRange.startTime = getTime(Date.now(), this.hideSecond)
}
if (startDateLaterRangeEndDate) {
this.tempRange.endTime = startTime || getDefaultSecond(this.hideSecond)
} else if (endDateEarlierRangeEndDate) {
this.tempRange.endTime = endTime || getDefaultSecond(this.hideSecond)
}
if (!this.tempRange.endTime) {
this.tempRange.endTime = getTime(Date.now(), this.hideSecond)
}
start = this.displayRangeValue.startDate = `${this.tempRange.startDate} ${this.tempRange.startTime}`
end = this.displayRangeValue.endDate = `${this.tempRange.endDate} ${this.tempRange.endTime}`
}
if (!dateCompare(start, end)) {
[start, end] = [end, start]
}
this.displayRangeValue.startDate = start
this.displayRangeValue.endDate = end
const displayRange = [start, end]
this.setEmit(displayRange)
this.pickerVisible = false
},
handleStartAndEnd(before, after, temp = false) {
if (!before) return
if (!after) after = before;
const type = temp ? 'tempRange' : 'range'
const isStartEarlierEnd = dateCompare(before, after)
this[type].startDate = isStartEarlierEnd ? before : after
this[type].endDate = isStartEarlierEnd ? after : before
},
/**
* 比较时间大小
*/
dateCompare(startDate, endDate) {
// 计算截止时间
startDate = new Date(startDate.replace('-', '/').replace('-', '/'))
// 计算详细项的截止时间
endDate = new Date(endDate.replace('-', '/').replace('-', '/'))
return startDate <= endDate
},
/**
* 比较时间差
*/
diffDate(startDate, endDate) {
// 计算截止时间
startDate = new Date(startDate.replace('-', '/').replace('-', '/'))
// 计算详细项的截止时间
endDate = new Date(endDate.replace('-', '/').replace('-', '/'))
const diff = (endDate - startDate) / (24 * 60 * 60 * 1000)
return Math.abs(diff)
},
clear(needEmit = true) {
if (!this.isRange) {
this.displayValue = ''
this.inputDate = ''
this.pickerTime = ''
if (this.isPhone) {
this.$refs.mobile && this.$refs.mobile.clearCalender()
} else {
this.$refs.pcSingle && this.$refs.pcSingle.clearCalender()
}
if (needEmit) {
this.$emit('change', '')
this.$emit('input', '')
this.$emit('update:modelValue', '')
}
} else {
this.displayRangeValue.startDate = ''
this.displayRangeValue.endDate = ''
this.tempRange.startDate = ''
this.tempRange.startTime = ''
this.tempRange.endDate = ''
this.tempRange.endTime = ''
if (this.isPhone) {
this.$refs.mobile && this.$refs.mobile.clearCalender()
} else {
this.$refs.left && this.$refs.left.clearCalender()
this.$refs.right && this.$refs.right.clearCalender()
this.$refs.right && this.$refs.right.changeMonth('next')
}
if (needEmit) {
this.$emit('change', [])
this.$emit('input', [])
this.$emit('update:modelValue', [])
}
}
},
calendarClick(e) {
this.$emit('calendarClick', e)
}
}
}
</script>
<style lang="scss">
$uni-primary: #007aff !default;
.uni-date {
width: 100%;
flex: 1;
}
.uni-date-x {
display: flex;
flex-direction: row;
align-items: center;
justify-content: center;
border-radius: 4px;
background-color: #fff;
color: #666;
font-size: 14px;
flex: 1;
.icon-calendar {
padding-left: 3px;
}
.range-separator {
height: 35px;
/* #ifndef MP */
padding: 0 2px;
/* #endif */
line-height: 35px;
}
}
.uni-date-x--border {
box-sizing: border-box;
border-radius: 4px;
border: 1px solid #e5e5e5;
}
.uni-date-editor--x {
display: flex;
align-items: center;
position: relative;
}
.uni-date-editor--x .uni-date__icon-clear {
padding-right: 3px;
display: flex;
align-items: center;
/* #ifdef H5 */
cursor: pointer;
/* #endif */
}
.uni-date__x-input {
width: auto;
height: 35px;
/* #ifndef MP */
padding-left: 5px;
/* #endif */
position: relative;
flex: 1;
line-height: 35px;
font-size: 14px;
overflow: hidden;
}
.text-center {
text-align: center;
}
.uni-date__input {
height: 40px;
width: 100%;
line-height: 40px;
font-size: 14px;
}
.uni-date-range__input {
text-align: center;
max-width: 142px;
}
.uni-date-picker__container {
position: relative;
}
.uni-date-mask--pc {
position: fixed;
bottom: 0px;
top: 0px;
left: 0px;
right: 0px;
background-color: rgba(0, 0, 0, 0);
transition-duration: 0.3s;
z-index: 996;
}
.uni-date-single--x {
background-color: #fff;
position: absolute;
top: 0;
z-index: 999;
border: 1px solid #EBEEF5;
box-shadow: 0 2px 12px 0 rgba(0, 0, 0, 0.1);
border-radius: 4px;
}
.uni-date-range--x {
background-color: #fff;
position: absolute;
top: 0;
z-index: 999;
border: 1px solid #EBEEF5;
box-shadow: 0 2px 12px 0 rgba(0, 0, 0, 0.1);
border-radius: 4px;
}
.uni-date-editor--x__disabled {
opacity: 0.4;
cursor: default;
}
.uni-date-editor--logo {
width: 16px;
height: 16px;
vertical-align: middle;
}
/* 添加时间 */
.popup-x-header {
/* #ifndef APP-NVUE */
display: flex;
/* #endif */
flex-direction: row;
}
.popup-x-header--datetime {
/* #ifndef APP-NVUE */
display: flex;
/* #endif */
flex-direction: row;
flex: 1;
}
.popup-x-body {
display: flex;
}
.popup-x-footer {
padding: 0 15px;
border-top-color: #F1F1F1;
border-top-style: solid;
border-top-width: 1px;
line-height: 40px;
text-align: right;
color: #666;
}
.popup-x-footer text:hover {
color: $uni-primary;
cursor: pointer;
opacity: 0.8;
}
.popup-x-footer .confirm-text {
margin-left: 20px;
color: $uni-primary;
}
.uni-date-changed {
text-align: center;
color: #333;
border-bottom-color: #F1F1F1;
border-bottom-style: solid;
border-bottom-width: 1px;
}
.uni-date-changed--time text {
height: 50px;
line-height: 50px;
}
.uni-date-changed .uni-date-changed--time {
flex: 1;
}
.uni-date-changed--time-date {
color: #333;
opacity: 0.6;
}
.mr-50 {
margin-right: 50px;
}
/* picker 弹出层通用的指示小三角, todo:扩展至上下左右方向定位 */
.uni-popper__arrow,
.uni-popper__arrow::after {
position: absolute;
display: block;
width: 0;
height: 0;
border: 6px solid transparent;
border-top-width: 0;
}
.uni-popper__arrow {
filter: drop-shadow(0 2px 12px rgba(0, 0, 0, 0.03));
top: -6px;
left: 10%;
margin-right: 3px;
border-bottom-color: #EBEEF5;
}
.uni-popper__arrow::after {
content: " ";
top: 1px;
margin-left: -6px;
border-bottom-color: #fff;
}
</style>
|
2301_77169380/aionix-2
|
uni_modules/uni-datetime-picker/components/uni-datetime-picker/uni-datetime-picker.vue
|
Vue
|
mit
| 28,776
|
class Calendar {
constructor({
selected,
startDate,
endDate,
range,
} = {}) {
// 当前日期
this.date = this.getDateObj(new Date()) // 当前初入日期
// 打点信息
this.selected = selected || [];
// 起始时间
this.startDate = startDate
// 终止时间
this.endDate = endDate
// 是否范围选择
this.range = range
// 多选状态
this.cleanMultipleStatus()
// 每周日期
this.weeks = {}
this.lastHover = false
}
/**
* 设置日期
* @param {Object} date
*/
setDate(date) {
const selectDate = this.getDateObj(date)
this.getWeeks(selectDate.fullDate)
}
/**
* 清理多选状态
*/
cleanMultipleStatus() {
this.multipleStatus = {
before: '',
after: '',
data: []
}
}
setStartDate(startDate) {
this.startDate = startDate
}
setEndDate(endDate) {
this.endDate = endDate
}
getPreMonthObj(date) {
date = fixIosDateFormat(date)
date = new Date(date)
const oldMonth = date.getMonth()
date.setMonth(oldMonth - 1)
const newMonth = date.getMonth()
if (oldMonth !== 0 && newMonth - oldMonth === 0) {
date.setMonth(newMonth - 1)
}
return this.getDateObj(date)
}
getNextMonthObj(date) {
date = fixIosDateFormat(date)
date = new Date(date)
const oldMonth = date.getMonth()
date.setMonth(oldMonth + 1)
const newMonth = date.getMonth()
if (newMonth - oldMonth > 1) {
date.setMonth(newMonth - 1)
}
return this.getDateObj(date)
}
/**
* 获取指定格式Date对象
*/
getDateObj(date) {
date = fixIosDateFormat(date)
date = new Date(date)
return {
fullDate: getDate(date),
year: date.getFullYear(),
month: addZero(date.getMonth() + 1),
date: addZero(date.getDate()),
day: date.getDay()
}
}
/**
* 获取上一个月日期集合
*/
getPreMonthDays(amount, dateObj) {
const result = []
for (let i = amount - 1; i >= 0; i--) {
const month = dateObj.month - 1
result.push({
date: new Date(dateObj.year, month, -i).getDate(),
month,
disable: true
})
}
return result
}
/**
* 获取本月日期集合
*/
getCurrentMonthDays(amount, dateObj) {
const result = []
const fullDate = this.date.fullDate
for (let i = 1; i <= amount; i++) {
const currentDate = `${dateObj.year}-${dateObj.month}-${addZero(i)}`
const isToday = fullDate === currentDate
// 获取打点信息
const info = this.selected && this.selected.find((item) => {
if (this.dateEqual(currentDate, item.date)) {
return item
}
})
// 日期禁用
let disableBefore = true
let disableAfter = true
if (this.startDate) {
disableBefore = dateCompare(this.startDate, currentDate)
}
if (this.endDate) {
disableAfter = dateCompare(currentDate, this.endDate)
}
let multiples = this.multipleStatus.data
let multiplesStatus = -1
if (this.range && multiples) {
multiplesStatus = multiples.findIndex((item) => {
return this.dateEqual(item, currentDate)
})
}
const checked = multiplesStatus !== -1
result.push({
fullDate: currentDate,
year: dateObj.year,
date: i,
multiple: this.range ? checked : false,
beforeMultiple: this.isLogicBefore(currentDate, this.multipleStatus.before, this.multipleStatus.after),
afterMultiple: this.isLogicAfter(currentDate, this.multipleStatus.before, this.multipleStatus.after),
month: dateObj.month,
disable: (this.startDate && !dateCompare(this.startDate, currentDate)) || (this.endDate && !dateCompare(
currentDate, this.endDate)),
isToday,
userChecked: false,
extraInfo: info
})
}
return result
}
/**
* 获取下一个月日期集合
*/
_getNextMonthDays(amount, dateObj) {
const result = []
const month = dateObj.month + 1
for (let i = 1; i <= amount; i++) {
result.push({
date: i,
month,
disable: true
})
}
return result
}
/**
* 获取当前日期详情
* @param {Object} date
*/
getInfo(date) {
if (!date) {
date = new Date()
}
return this.calendar.find(item => item.fullDate === this.getDateObj(date).fullDate)
}
/**
* 比较时间是否相等
*/
dateEqual(before, after) {
before = new Date(fixIosDateFormat(before))
after = new Date(fixIosDateFormat(after))
return before.valueOf() === after.valueOf()
}
/**
* 比较真实起始日期
*/
isLogicBefore(currentDate, before, after) {
let logicBefore = before
if (before && after) {
logicBefore = dateCompare(before, after) ? before : after
}
return this.dateEqual(logicBefore, currentDate)
}
isLogicAfter(currentDate, before, after) {
let logicAfter = after
if (before && after) {
logicAfter = dateCompare(before, after) ? after : before
}
return this.dateEqual(logicAfter, currentDate)
}
/**
* 获取日期范围内所有日期
* @param {Object} begin
* @param {Object} end
*/
geDateAll(begin, end) {
var arr = []
var ab = begin.split('-')
var ae = end.split('-')
var db = new Date()
db.setFullYear(ab[0], ab[1] - 1, ab[2])
var de = new Date()
de.setFullYear(ae[0], ae[1] - 1, ae[2])
var unixDb = db.getTime() - 24 * 60 * 60 * 1000
var unixDe = de.getTime() - 24 * 60 * 60 * 1000
for (var k = unixDb; k <= unixDe;) {
k = k + 24 * 60 * 60 * 1000
arr.push(this.getDateObj(new Date(parseInt(k))).fullDate)
}
return arr
}
/**
* 获取多选状态
*/
setMultiple(fullDate) {
if (!this.range) return
let {
before,
after
} = this.multipleStatus
if (before && after) {
if (!this.lastHover) {
this.lastHover = true
return
}
this.multipleStatus.before = fullDate
this.multipleStatus.after = ''
this.multipleStatus.data = []
this.multipleStatus.fulldate = ''
this.lastHover = false
} else {
if (!before) {
this.multipleStatus.before = fullDate
this.multipleStatus.after = undefined;
this.lastHover = false
} else {
this.multipleStatus.after = fullDate
if (dateCompare(this.multipleStatus.before, this.multipleStatus.after)) {
this.multipleStatus.data = this.geDateAll(this.multipleStatus.before, this.multipleStatus
.after);
} else {
this.multipleStatus.data = this.geDateAll(this.multipleStatus.after, this.multipleStatus
.before);
}
this.lastHover = true
}
}
this.getWeeks(fullDate)
}
/**
* 鼠标 hover 更新多选状态
*/
setHoverMultiple(fullDate) {
//抖音小程序点击会触发hover事件,需要避免一下
// #ifndef MP-TOUTIAO
if (!this.range || this.lastHover) return
const {
before
} = this.multipleStatus
if (!before) {
this.multipleStatus.before = fullDate
} else {
this.multipleStatus.after = fullDate
if (dateCompare(this.multipleStatus.before, this.multipleStatus.after)) {
this.multipleStatus.data = this.geDateAll(this.multipleStatus.before, this.multipleStatus.after);
} else {
this.multipleStatus.data = this.geDateAll(this.multipleStatus.after, this.multipleStatus.before);
}
}
this.getWeeks(fullDate)
// #endif
}
/**
* 更新默认值多选状态
*/
setDefaultMultiple(before, after) {
this.multipleStatus.before = before
this.multipleStatus.after = after
if (before && after) {
if (dateCompare(before, after)) {
this.multipleStatus.data = this.geDateAll(before, after);
this.getWeeks(after)
} else {
this.multipleStatus.data = this.geDateAll(after, before);
this.getWeeks(before)
}
}
}
/**
* 获取每周数据
* @param {Object} dateData
*/
getWeeks(dateData) {
const {
year,
month,
} = this.getDateObj(dateData)
const preMonthDayAmount = new Date(year, month - 1, 1).getDay()
const preMonthDays = this.getPreMonthDays(preMonthDayAmount, this.getDateObj(dateData))
const currentMonthDayAmount = new Date(year, month, 0).getDate()
const currentMonthDays = this.getCurrentMonthDays(currentMonthDayAmount, this.getDateObj(dateData))
const nextMonthDayAmount = 42 - preMonthDayAmount - currentMonthDayAmount
const nextMonthDays = this._getNextMonthDays(nextMonthDayAmount, this.getDateObj(dateData))
const calendarDays = [...preMonthDays, ...currentMonthDays, ...nextMonthDays]
const weeks = new Array(6)
for (let i = 0; i < calendarDays.length; i++) {
const index = Math.floor(i / 7)
if (!weeks[index]) {
weeks[index] = new Array(7)
}
weeks[index][i % 7] = calendarDays[i]
}
this.calendar = calendarDays
this.weeks = weeks
}
}
function getDateTime(date, hideSecond) {
return `${getDate(date)} ${getTime(date, hideSecond)}`
}
function getDate(date) {
date = fixIosDateFormat(date)
date = new Date(date)
const year = date.getFullYear()
const month = date.getMonth() + 1
const day = date.getDate()
return `${year}-${addZero(month)}-${addZero(day)}`
}
function getTime(date, hideSecond) {
date = fixIosDateFormat(date)
date = new Date(date)
const hour = date.getHours()
const minute = date.getMinutes()
const second = date.getSeconds()
return hideSecond ? `${addZero(hour)}:${addZero(minute)}` : `${addZero(hour)}:${addZero(minute)}:${addZero(second)}`
}
function addZero(num) {
if (num < 10) {
num = `0${num}`
}
return num
}
function getDefaultSecond(hideSecond) {
return hideSecond ? '00:00' : '00:00:00'
}
function dateCompare(startDate, endDate) {
startDate = new Date(fixIosDateFormat(startDate))
endDate = new Date(fixIosDateFormat(endDate))
return startDate <= endDate
}
function checkDate(date) {
const dateReg = /((19|20)\d{2})(-|\/)\d{1,2}(-|\/)\d{1,2}/g
return date.match(dateReg)
}
//ios低版本15及以下,无法匹配 没有 ’秒‘ 时的情况,所以需要在末尾 秒 加上 问号
const dateTimeReg = /^\d{4}-(0?[1-9]|1[012])-(0?[1-9]|[12][0-9]|3[01])( [0-5]?[0-9]:[0-5]?[0-9](:[0-5]?[0-9])?)?$/;
function fixIosDateFormat(value) {
if (typeof value === 'string' && dateTimeReg.test(value)) {
value = value.replace(/-/g, '/')
}
return value
}
export {
Calendar,
getDateTime,
getDate,
getTime,
addZero,
getDefaultSecond,
dateCompare,
checkDate,
fixIosDateFormat
}
|
2301_77169380/aionix-2
|
uni_modules/uni-datetime-picker/components/uni-datetime-picker/util.js
|
JavaScript
|
mit
| 10,060
|
// #ifdef H5
export default {
name: 'Keypress',
props: {
disable: {
type: Boolean,
default: false
}
},
mounted () {
const keyNames = {
esc: ['Esc', 'Escape'],
tab: 'Tab',
enter: 'Enter',
space: [' ', 'Spacebar'],
up: ['Up', 'ArrowUp'],
left: ['Left', 'ArrowLeft'],
right: ['Right', 'ArrowRight'],
down: ['Down', 'ArrowDown'],
delete: ['Backspace', 'Delete', 'Del']
}
const listener = ($event) => {
if (this.disable) {
return
}
const keyName = Object.keys(keyNames).find(key => {
const keyName = $event.key
const value = keyNames[key]
return value === keyName || (Array.isArray(value) && value.includes(keyName))
})
if (keyName) {
// 避免和其他按键事件冲突
setTimeout(() => {
this.$emit(keyName, {})
}, 0)
}
}
document.addEventListener('keyup', listener)
// this.$once('hook:beforeDestroy', () => {
// document.removeEventListener('keyup', listener)
// })
},
render: () => {}
}
// #endif
|
2301_77169380/aionix-2
|
uni_modules/uni-drawer/components/uni-drawer/keypress.js
|
JavaScript
|
mit
| 1,119
|
<template>
<view v-if="visibleSync" :class="{ 'uni-drawer--visible': showDrawer }" class="uni-drawer" @touchmove.stop.prevent="clear">
<view class="uni-drawer__mask" :class="{ 'uni-drawer__mask--visible': showDrawer && mask }" @tap="close('mask')" />
<view class="uni-drawer__content" :class="{'uni-drawer--right': rightMode,'uni-drawer--left': !rightMode, 'uni-drawer__content--visible': showDrawer}" :style="{width:drawerWidth+'px'}">
<slot />
</view>
<!-- #ifdef H5 -->
<keypress @esc="close('mask')" />
<!-- #endif -->
</view>
</template>
<script>
// #ifdef H5
import keypress from './keypress.js'
// #endif
/**
* Drawer 抽屉
* @description 抽屉侧滑菜单
* @tutorial https://ext.dcloud.net.cn/plugin?id=26
* @property {Boolean} mask = [true | false] 是否显示遮罩
* @property {Boolean} maskClick = [true | false] 点击遮罩是否关闭
* @property {Boolean} mode = [left | right] Drawer 滑出位置
* @value left 从左侧滑出
* @value right 从右侧侧滑出
* @property {Number} width 抽屉的宽度 ,仅 vue 页面生效
* @event {Function} close 组件关闭时触发事件
*/
export default {
name: 'UniDrawer',
components: {
// #ifdef H5
keypress
// #endif
},
emits:['change'],
props: {
/**
* 显示模式(左、右),只在初始化生效
*/
mode: {
type: String,
default: ''
},
/**
* 蒙层显示状态
*/
mask: {
type: Boolean,
default: true
},
/**
* 遮罩是否可点击关闭
*/
maskClick:{
type: Boolean,
default: true
},
/**
* 抽屉宽度
*/
width: {
type: Number,
default: 220
}
},
data() {
return {
visibleSync: false,
showDrawer: false,
rightMode: false,
watchTimer: null,
drawerWidth: 220
}
},
created() {
// #ifndef APP-NVUE
this.drawerWidth = this.width
// #endif
this.rightMode = this.mode === 'right'
},
methods: {
clear(){},
close(type) {
// fixed by mehaotian 抽屉尚未完全关闭或遮罩禁止点击时不触发以下逻辑
if((type === 'mask' && !this.maskClick) || !this.visibleSync) return
this._change('showDrawer', 'visibleSync', false)
},
open() {
// fixed by mehaotian 处理重复点击打开的事件
if(this.visibleSync) return
this._change('visibleSync', 'showDrawer', true)
},
_change(param1, param2, status) {
this[param1] = status
if (this.watchTimer) {
clearTimeout(this.watchTimer)
}
this.watchTimer = setTimeout(() => {
this[param2] = status
this.$emit('change',status)
}, status ? 50 : 300)
}
}
}
</script>
<style lang="scss" scoped>
$uni-mask: rgba($color: #000000, $alpha: 0.4) ;
// 抽屉宽度
$drawer-width: 220px;
.uni-drawer {
/* #ifndef APP-NVUE */
display: block;
/* #endif */
position: fixed;
top: 0;
left: 0;
right: 0;
bottom: 0;
overflow: hidden;
z-index: 999;
}
.uni-drawer__content {
/* #ifndef APP-NVUE */
display: block;
/* #endif */
position: absolute;
top: 0;
width: $drawer-width;
bottom: 0;
background-color: $uni-bg-color;
transition: transform 0.3s ease;
}
.uni-drawer--left {
left: 0;
/* #ifdef APP-NVUE */
transform: translateX(-$drawer-width);
/* #endif */
/* #ifndef APP-NVUE */
transform: translateX(-100%);
/* #endif */
}
.uni-drawer--right {
right: 0;
/* #ifdef APP-NVUE */
transform: translateX($drawer-width);
/* #endif */
/* #ifndef APP-NVUE */
transform: translateX(100%);
/* #endif */
}
.uni-drawer__content--visible {
transform: translateX(0px);
}
.uni-drawer__mask {
/* #ifndef APP-NVUE */
display: block;
/* #endif */
opacity: 0;
position: absolute;
top: 0;
left: 0;
bottom: 0;
right: 0;
background-color: $uni-mask;
transition: opacity 0.3s;
}
.uni-drawer__mask--visible {
/* #ifndef APP-NVUE */
display: block;
/* #endif */
opacity: 1;
}
</style>
|
2301_77169380/aionix-2
|
uni_modules/uni-drawer/components/uni-drawer/uni-drawer.vue
|
Vue
|
mit
| 3,988
|
/**
* @desc 函数防抖
* @param func 目标函数
* @param wait 延迟执行毫秒数
* @param immediate true - 立即执行, false - 延迟执行
*/
export const debounce = function(func, wait = 1000, immediate = true) {
let timer;
return function() {
let context = this,
args = arguments;
if (timer) clearTimeout(timer);
if (immediate) {
let callNow = !timer;
timer = setTimeout(() => {
timer = null;
}, wait);
if (callNow) func.apply(context, args);
} else {
timer = setTimeout(() => {
func.apply(context, args);
}, wait)
}
}
}
/**
* @desc 函数节流
* @param func 函数
* @param wait 延迟执行毫秒数
* @param type 1 使用表时间戳,在时间段开始的时候触发 2 使用表定时器,在时间段结束的时候触发
*/
export const throttle = (func, wait = 1000, type = 1) => {
let previous = 0;
let timeout;
return function() {
let context = this;
let args = arguments;
if (type === 1) {
let now = Date.now();
if (now - previous > wait) {
func.apply(context, args);
previous = now;
}
} else if (type === 2) {
if (!timeout) {
timeout = setTimeout(() => {
timeout = null;
func.apply(context, args)
}, wait)
}
}
}
}
|
2301_77169380/aionix-2
|
uni_modules/uni-easyinput/components/uni-easyinput/common.js
|
JavaScript
|
mit
| 1,251
|
<template>
<view class="uni-easyinput" :class="{ 'uni-easyinput-error': msg }" :style="boxStyle">
<view class="uni-easyinput__content" :class="inputContentClass" :style="inputContentStyle">
<uni-icons v-if="prefixIcon" class="content-clear-icon" :type="prefixIcon" color="#c0c4cc"
@click="onClickIcon('prefix')" size="22"></uni-icons>
<slot name="left">
</slot>
<!-- #ifdef MP-ALIPAY -->
<textarea :enableNative="enableNative" v-if="type === 'textarea'" class="uni-easyinput__content-textarea"
:class="{ 'input-padding': inputBorder }" :name="name" :value="val" :placeholder="placeholder"
:placeholderStyle="placeholderStyle" :disabled="disabled" placeholder-class="uni-easyinput__placeholder-class"
:maxlength="inputMaxlength" :focus="focused" :autoHeight="autoHeight" :cursor-spacing="cursorSpacing"
:adjust-position="adjustPosition" @input="onInput" @blur="_Blur" @focus="_Focus" @confirm="onConfirm"
@keyboardheightchange="onkeyboardheightchange"></textarea>
<input :enableNative="enableNative" v-else :type="type === 'password' ? 'text' : type"
class="uni-easyinput__content-input" :style="inputStyle" :name="name" :value="val"
:password="!showPassword && type === 'password'" :placeholder="placeholder" :placeholderStyle="placeholderStyle"
placeholder-class="uni-easyinput__placeholder-class" :disabled="disabled" :maxlength="inputMaxlength"
:focus="focused" :confirmType="confirmType" :cursor-spacing="cursorSpacing" :adjust-position="adjustPosition"
@focus="_Focus" @blur="_Blur" @input="onInput" @confirm="onConfirm"
@keyboardheightchange="onkeyboardheightchange" />
<!-- #endif -->
<!-- #ifndef MP-ALIPAY -->
<textarea v-if="type === 'textarea'" class="uni-easyinput__content-textarea"
:class="{ 'input-padding': inputBorder }" :name="name" :value="val" :placeholder="placeholder"
:placeholderStyle="placeholderStyle" :disabled="disabled" placeholder-class="uni-easyinput__placeholder-class"
:maxlength="inputMaxlength" :focus="focused" :autoHeight="autoHeight" :cursor-spacing="cursorSpacing"
:adjust-position="adjustPosition" @input="onInput" @blur="_Blur" @focus="_Focus" @confirm="onConfirm"
@keyboardheightchange="onkeyboardheightchange"></textarea>
<input v-else :type="type === 'password' ? 'text' : type" class="uni-easyinput__content-input" :style="inputStyle"
:name="name" :value="val" :password="!showPassword && type === 'password'" :placeholder="placeholder"
:placeholderStyle="placeholderStyle" placeholder-class="uni-easyinput__placeholder-class" :disabled="disabled"
:maxlength="inputMaxlength" :focus="focused" :confirmType="confirmType" :cursor-spacing="cursorSpacing"
:adjust-position="adjustPosition" @focus="_Focus" @blur="_Blur" @input="onInput" @confirm="onConfirm"
@keyboardheightchange="onkeyboardheightchange" />
<!-- #endif -->
<template v-if="type === 'password' && passwordIcon">
<!-- 开启密码时显示小眼睛 -->
<uni-icons v-if="isVal" class="content-clear-icon" :class="{ 'is-textarea-icon': type === 'textarea' }"
:type="showPassword ? 'eye-slash-filled' : 'eye-filled'" :size="22"
:color="focusShow ? primaryColor : '#c0c4cc'" @click="onEyes"></uni-icons>
</template>
<template v-if="suffixIcon">
<uni-icons v-if="suffixIcon" class="content-clear-icon" :type="suffixIcon" color="#c0c4cc"
@click="onClickIcon('suffix')" size="22"></uni-icons>
</template>
<template v-else>
<uni-icons v-if="clearable && isVal && !disabled && type !== 'textarea'" class="content-clear-icon"
:class="{ 'is-textarea-icon': type === 'textarea' }" type="clear" :size="clearSize"
:color="msg ? '#dd524d' : focusShow ? primaryColor : '#c0c4cc'" @click="onClear"></uni-icons>
</template>
<slot name="right"></slot>
</view>
</view>
</template>
<script>
/**
* Easyinput 输入框
* @description 此组件可以实现表单的输入与校验,包括 "text" 和 "textarea" 类型。
* @tutorial https://ext.dcloud.net.cn/plugin?id=3455
* @property {String} value 输入内容
* @property {String } type 输入框的类型(默认text) password/text/textarea/..
* @value text 文本输入键盘
* @value textarea 多行文本输入键盘
* @value password 密码输入键盘
* @value number 数字输入键盘,注意iOS上app-vue弹出的数字键盘并非9宫格方式
* @value idcard 身份证输入键盘,信、支付宝、百度、QQ小程序
* @value digit 带小数点的数字键盘 ,App的nvue页面、微信、支付宝、百度、头条、QQ小程序支持
* @property {Boolean} clearable 是否显示右侧清空内容的图标控件,点击可清空输入框内容(默认true)
* @property {Boolean} autoHeight 是否自动增高输入区域,type为textarea时有效(默认true)
* @property {String } placeholder 输入框的提示文字
* @property {String } placeholderStyle placeholder的样式(内联样式,字符串),如"color: #ddd"
* @property {Boolean} focus 是否自动获得焦点(默认false)
* @property {Boolean} disabled 是否禁用(默认false)
* @property {Number } maxlength 最大输入长度,设置为 -1 的时候不限制最大长度(默认140)
* @property {String } confirmType 设置键盘右下角按钮的文字,仅在type="text"时生效(默认done)
* @property {Number } clearSize 清除图标的大小,单位px(默认15)
* @property {String} prefixIcon 输入框头部图标
* @property {String} suffixIcon 输入框尾部图标
* @property {String} primaryColor 设置主题色(默认#2979ff)
* @property {Boolean} trim 是否自动去除两端的空格
* @property {Boolean} cursorSpacing 指定光标与键盘的距离,单位 px
* @property {Boolean} ajust-position 当键盘弹起时,是否上推内容,默认值:true
* @value both 去除两端空格
* @value left 去除左侧空格
* @value right 去除右侧空格
* @value start 去除左侧空格
* @value end 去除右侧空格
* @value all 去除全部空格
* @value none 不去除空格
* @property {Boolean} inputBorder 是否显示input输入框的边框(默认true)
* @property {Boolean} passwordIcon type=password时是否显示小眼睛图标
* @property {Object} styles 自定义颜色
* @event {Function} input 输入框内容发生变化时触发
* @event {Function} focus 输入框获得焦点时触发
* @event {Function} blur 输入框失去焦点时触发
* @event {Function} confirm 点击完成按钮时触发
* @event {Function} iconClick 点击图标时触发
* @example <uni-easyinput v-model="mobile"></uni-easyinput>
*/
function obj2strClass(obj) {
let classess = '';
for (let key in obj) {
const val = obj[key];
if (val) {
classess += `${key} `;
}
}
return classess;
}
function obj2strStyle(obj) {
let style = '';
for (let key in obj) {
const val = obj[key];
style += `${key}:${val};`;
}
return style;
}
export default {
name: 'uni-easyinput',
emits: [
'click',
'iconClick',
'update:modelValue',
'input',
'focus',
'blur',
'confirm',
'clear',
'eyes',
'change',
'keyboardheightchange'
],
model: {
prop: 'modelValue',
event: 'update:modelValue'
},
options: {
// #ifdef MP-TOUTIAO
virtualHost: false,
// #endif
// #ifndef MP-TOUTIAO
virtualHost: true
// #endif
},
inject: {
form: {
from: 'uniForm',
default: null
},
formItem: {
from: 'uniFormItem',
default: null
}
},
props: {
name: String,
value: [Number, String],
modelValue: [Number, String],
type: {
type: String,
default: 'text'
},
clearable: {
type: Boolean,
default: true
},
autoHeight: {
type: Boolean,
default: false
},
placeholder: {
type: String,
default: ' '
},
placeholderStyle: String,
focus: {
type: Boolean,
default: false
},
disabled: {
type: Boolean,
default: false
},
maxlength: {
type: [Number, String],
default: 140
},
confirmType: {
type: String,
default: 'done'
},
clearSize: {
type: [Number, String],
default: 24
},
inputBorder: {
type: Boolean,
default: true
},
prefixIcon: {
type: String,
default: ''
},
suffixIcon: {
type: String,
default: ''
},
trim: {
type: [Boolean, String],
default: false
},
cursorSpacing: {
type: Number,
default: 0
},
passwordIcon: {
type: Boolean,
default: true
},
adjustPosition: {
type: Boolean,
default: true
},
primaryColor: {
type: String,
default: '#2979ff'
},
styles: {
type: Object,
default() {
return {
color: '#333',
backgroundColor: '#fff',
disableColor: '#F7F6F6',
borderColor: '#e5e5e5'
};
}
},
errorMessage: {
type: [String, Boolean],
default: ''
},
// #ifdef MP-ALIPAY
enableNative: {
type: Boolean,
default: false
}
// #endif
},
data() {
return {
focused: false,
val: '',
showMsg: '',
border: false,
isFirstBorder: false,
showClearIcon: false,
showPassword: false,
focusShow: false,
localMsg: '',
isEnter: false // 用于判断当前是否是使用回车操作
};
},
computed: {
// 输入框内是否有值
isVal() {
const val = this.val;
// fixed by mehaotian 处理值为0的情况,字符串0不在处理范围
if (val || val === 0) {
return true;
}
return false;
},
msg() {
// console.log('computed', this.form, this.formItem);
// if (this.form) {
// return this.errorMessage || this.formItem.errMsg;
// }
// TODO 处理头条 formItem 中 errMsg 不更新的问题
return this.localMsg || this.errorMessage;
},
// 因为uniapp的input组件的maxlength组件必须要数值,这里转为数值,用户可以传入字符串数值
inputMaxlength() {
return Number(this.maxlength);
},
// 处理外层样式的style
boxStyle() {
return `color:${
this.inputBorder && this.msg ? '#e43d33' : this.styles.color
};`;
},
// input 内容的类和样式处理
inputContentClass() {
return obj2strClass({
'is-input-border': this.inputBorder,
'is-input-error-border': this.inputBorder && this.msg,
'is-textarea': this.type === 'textarea',
'is-disabled': this.disabled,
'is-focused': this.focusShow
});
},
inputContentStyle() {
const focusColor = this.focusShow
? this.primaryColor
: this.styles.borderColor;
const borderColor =
this.inputBorder && this.msg ? '#dd524d' : focusColor;
return obj2strStyle({
'border-color': borderColor || '#e5e5e5',
'background-color': this.disabled
? this.styles.disableColor
: this.styles.backgroundColor
});
},
// input右侧样式
inputStyle() {
const paddingRight =
this.type === 'password' || this.clearable || this.prefixIcon
? ''
: '10px';
return obj2strStyle({
'padding-right': paddingRight,
'padding-left': this.prefixIcon ? '' : '10px'
});
}
},
watch: {
value(newVal) {
this.val = newVal;
},
modelValue(newVal) {
this.val = newVal;
},
focus(newVal) {
this.$nextTick(() => {
this.focused = this.focus;
this.focusShow = this.focus;
});
}
},
created() {
this.init();
// TODO 处理头条vue3 computed 不监听 inject 更改的问题(formItem.errMsg)
if (this.form && this.formItem) {
this.$watch('formItem.errMsg', newVal => {
this.localMsg = newVal;
});
}
},
mounted() {
this.$nextTick(() => {
this.focused = this.focus;
this.focusShow = this.focus;
});
},
methods: {
/**
* 初始化变量值
*/
init() {
if (this.value || this.value === 0) {
this.val = this.value;
} else if (
this.modelValue ||
this.modelValue === 0 ||
this.modelValue === ''
) {
this.val = this.modelValue;
} else {
this.val = null;
}
},
/**
* 点击图标时触发
* @param {Object} type
*/
onClickIcon(type) {
this.$emit('iconClick', type);
},
/**
* 显示隐藏内容,密码框时生效
*/
onEyes() {
this.showPassword = !this.showPassword;
this.$emit('eyes', this.showPassword);
},
/**
* 输入时触发
* @param {Object} event
*/
onInput(event) {
let value = event.detail.value;
// 判断是否去除空格
if (this.trim) {
if (typeof this.trim === 'boolean' && this.trim) {
value = this.trimStr(value);
}
if (typeof this.trim === 'string') {
value = this.trimStr(value, this.trim);
}
}
if (this.errMsg) this.errMsg = '';
this.val = value;
// TODO 兼容 vue2
this.$emit('input', value);
// TODO 兼容 vue3
this.$emit('update:modelValue', value);
},
/**
* 外部调用方法
* 获取焦点时触发
* @param {Object} event
*/
onFocus() {
this.$nextTick(() => {
this.focused = true;
});
this.$emit('focus', null);
},
_Focus(event) {
this.focusShow = true;
this.$emit('focus', event);
},
/**
* 外部调用方法
* 失去焦点时触发
* @param {Object} event
*/
onBlur() {
this.focused = false;
this.$emit('blur', null);
},
_Blur(event) {
let value = event.detail.value;
this.focusShow = false;
this.$emit('blur', event);
// 根据类型返回值,在event中获取的值理论上讲都是string
if (this.isEnter === false) {
this.$emit('change', this.val);
}
// 失去焦点时参与表单校验
if (this.form && this.formItem) {
const { validateTrigger } = this.form;
if (validateTrigger === 'blur') {
this.formItem.onFieldChange();
}
}
},
/**
* 按下键盘的发送键
* @param {Object} e
*/
onConfirm(e) {
this.$emit('confirm', this.val);
this.isEnter = true;
this.$emit('change', this.val);
this.$nextTick(() => {
this.isEnter = false;
});
},
/**
* 清理内容
* @param {Object} event
*/
onClear(event) {
this.val = '';
// TODO 兼容 vue2
this.$emit('input', '');
// TODO 兼容 vue2
// TODO 兼容 vue3
this.$emit('update:modelValue', '');
// 点击叉号触发
this.$emit('clear');
},
/**
* 键盘高度发生变化的时候触发此事件
* 兼容性:微信小程序2.7.0+、App 3.1.0+
* @param {Object} event
*/
onkeyboardheightchange(event) {
this.$emit('keyboardheightchange', event);
},
/**
* 去除空格
*/
trimStr(str, pos = 'both') {
if (pos === 'both') {
return str.trim();
} else if (pos === 'left') {
return str.trimLeft();
} else if (pos === 'right') {
return str.trimRight();
} else if (pos === 'start') {
return str.trimStart();
} else if (pos === 'end') {
return str.trimEnd();
} else if (pos === 'all') {
return str.replace(/\s+/g, '');
} else if (pos === 'none') {
return str;
}
return str;
}
}
};
</script>
<style lang="scss">
$uni-error: #e43d33;
$uni-border-1: #dcdfe6 !default;
.uni-easyinput {
/* #ifndef APP-NVUE */
width: 100%;
/* #endif */
flex: 1;
position: relative;
text-align: left;
color: #333;
font-size: 14px;
}
.uni-easyinput__content {
flex: 1;
/* #ifndef APP-NVUE */
width: 100%;
display: flex;
box-sizing: border-box;
// min-height: 36px;
/* #endif */
flex-direction: row;
align-items: center;
// 处理border动画刚开始显示黑色的问题
border-color: #fff;
transition-property: border-color;
transition-duration: 0.3s;
}
.uni-easyinput__content-input {
/* #ifndef APP-NVUE */
width: auto;
/* #endif */
position: relative;
overflow: hidden;
flex: 1;
line-height: 1;
font-size: 14px;
height: 35px;
// min-height: 36px;
/*ifdef H5*/
& ::-ms-reveal {
display: none;
}
& ::-ms-clear {
display: none;
}
& ::-o-clear {
display: none;
}
/*endif*/
}
.uni-easyinput__placeholder-class {
color: #999;
font-size: 12px;
// font-weight: 200;
}
.is-textarea {
align-items: flex-start;
}
.is-textarea-icon {
margin-top: 5px;
}
.uni-easyinput__content-textarea {
position: relative;
overflow: hidden;
flex: 1;
line-height: 1.5;
font-size: 14px;
margin: 6px;
margin-left: 0;
height: 80px;
min-height: 80px;
/* #ifndef APP-NVUE */
min-height: 80px;
width: auto;
/* #endif */
}
.input-padding {
padding-left: 10px;
}
.content-clear-icon {
padding: 0 5px;
}
.label-icon {
margin-right: 5px;
margin-top: -1px;
}
// 显示边框
.is-input-border {
/* #ifndef APP-NVUE */
display: flex;
box-sizing: border-box;
/* #endif */
flex-direction: row;
align-items: center;
border: 1px solid $uni-border-1;
border-radius: 4px;
/* #ifdef MP-ALIPAY */
overflow: hidden;
/* #endif */
}
.uni-error-message {
position: absolute;
bottom: -17px;
left: 0;
line-height: 12px;
color: $uni-error;
font-size: 12px;
text-align: left;
}
.uni-error-msg--boeder {
position: relative;
bottom: 0;
line-height: 22px;
}
.is-input-error-border {
border-color: $uni-error;
.uni-easyinput__placeholder-class {
color: mix(#fff, $uni-error, 50%);
}
}
.uni-easyinput--border {
margin-bottom: 0;
padding: 10px 15px;
// padding-bottom: 0;
border-top: 1px #eee solid;
}
.uni-easyinput-error {
padding-bottom: 0;
}
.is-first-border {
/* #ifndef APP-NVUE */
border: none;
/* #endif */
/* #ifdef APP-NVUE */
border-width: 0;
/* #endif */
}
.is-disabled {
background-color: #f7f6f6;
color: #d5d5d5;
.uni-easyinput__placeholder-class {
color: #d5d5d5;
font-size: 12px;
}
}
</style>
|
2301_77169380/aionix-2
|
uni_modules/uni-easyinput/components/uni-easyinput/uni-easyinput.vue
|
Vue
|
mit
| 18,079
|
<template>
<view class="uni-cursor-point">
<view v-if="popMenu && (leftBottom||rightBottom||leftTop||rightTop) && content.length > 0" :class="{
'uni-fab--leftBottom': leftBottom,
'uni-fab--rightBottom': rightBottom,
'uni-fab--leftTop': leftTop,
'uni-fab--rightTop': rightTop
}" class="uni-fab"
:style="nvueBottom"
>
<view :class="{
'uni-fab__content--left': horizontal === 'left',
'uni-fab__content--right': horizontal === 'right',
'uni-fab__content--flexDirection': direction === 'vertical',
'uni-fab__content--flexDirectionStart': flexDirectionStart,
'uni-fab__content--flexDirectionEnd': flexDirectionEnd,
'uni-fab__content--other-platform': !isAndroidNvue
}" :style="{ width: boxWidth, height: boxHeight, backgroundColor: styles.backgroundColor }"
class="uni-fab__content" elevation="5">
<view v-if="flexDirectionStart || horizontalLeft" class="uni-fab__item uni-fab__item--first" />
<view v-for="(item, index) in content" :key="index" :class="{ 'uni-fab__item--active': isShow }"
class="uni-fab__item" @click="_onItemClick(index, item)">
<image :src="item.active ? item.selectedIconPath : item.iconPath" class="uni-fab__item-image"
mode="aspectFit" />
<text class="uni-fab__item-text"
:style="{ color: item.active ? styles.selectedColor : styles.color }">{{ item.text }}</text>
</view>
<view v-if="flexDirectionEnd || horizontalRight" class="uni-fab__item uni-fab__item--first" />
</view>
</view>
<view :class="{
'uni-fab__circle--leftBottom': leftBottom,
'uni-fab__circle--rightBottom': rightBottom,
'uni-fab__circle--leftTop': leftTop,
'uni-fab__circle--rightTop': rightTop,
'uni-fab__content--other-platform': !isAndroidNvue
}" class="uni-fab__circle uni-fab__plus" :style="{ 'background-color': styles.buttonColor, 'bottom': nvueBottom }" @click="_onClick">
<uni-icons class="fab-circle-icon" :type="styles.icon" :color="styles.iconColor" size="32"
:class="{'uni-fab__plus--active': isShow && content.length > 0}"></uni-icons>
<!-- <view class="fab-circle-v" :class="{'uni-fab__plus--active': isShow && content.length > 0}"></view>
<view class="fab-circle-h" :class="{'uni-fab__plus--active': isShow && content.length > 0}"></view> -->
</view>
</view>
</template>
<script>
let platform = 'other'
// #ifdef APP-NVUE
platform = uni.getSystemInfoSync().platform
// #endif
/**
* Fab 悬浮按钮
* @description 点击可展开一个图形按钮菜单
* @tutorial https://ext.dcloud.net.cn/plugin?id=144
* @property {Object} pattern 可选样式配置项
* @property {Object} horizontal = [left | right] 水平对齐方式
* @value left 左对齐
* @value right 右对齐
* @property {Object} vertical = [bottom | top] 垂直对齐方式
* @value bottom 下对齐
* @value top 上对齐
* @property {Object} direction = [horizontal | vertical] 展开菜单显示方式
* @value horizontal 水平显示
* @value vertical 垂直显示
* @property {Array} content 展开菜单内容配置项
* @property {Boolean} popMenu 是否使用弹出菜单
* @event {Function} trigger 展开菜单点击事件,返回点击信息
* @event {Function} fabClick 悬浮按钮点击事件
*/
export default {
name: 'UniFab',
emits: ['fabClick', 'trigger'],
props: {
pattern: {
type: Object,
default () {
return {}
}
},
horizontal: {
type: String,
default: 'left'
},
vertical: {
type: String,
default: 'bottom'
},
direction: {
type: String,
default: 'horizontal'
},
content: {
type: Array,
default () {
return []
}
},
show: {
type: Boolean,
default: false
},
popMenu: {
type: Boolean,
default: true
}
},
data() {
return {
fabShow: false,
isShow: false,
isAndroidNvue: platform === 'android',
styles: {
color: '#3c3e49',
selectedColor: '#007AFF',
backgroundColor: '#fff',
buttonColor: '#007AFF',
iconColor: '#fff',
icon: 'plusempty'
}
}
},
computed: {
contentWidth(e) {
return (this.content.length + 1) * 55 + 15 + 'px'
},
contentWidthMin() {
return '55px'
},
// 动态计算宽度
boxWidth() {
return this.getPosition(3, 'horizontal')
},
// 动态计算高度
boxHeight() {
return this.getPosition(3, 'vertical')
},
// 计算左下位置
leftBottom() {
return this.getPosition(0, 'left', 'bottom')
},
// 计算右下位置
rightBottom() {
return this.getPosition(0, 'right', 'bottom')
},
// 计算左上位置
leftTop() {
return this.getPosition(0, 'left', 'top')
},
rightTop() {
return this.getPosition(0, 'right', 'top')
},
flexDirectionStart() {
return this.getPosition(1, 'vertical', 'top')
},
flexDirectionEnd() {
return this.getPosition(1, 'vertical', 'bottom')
},
horizontalLeft() {
return this.getPosition(2, 'horizontal', 'left')
},
horizontalRight() {
return this.getPosition(2, 'horizontal', 'right')
},
// 计算 nvue bottom
nvueBottom() {
const safeBottom = uni.getSystemInfoSync().windowBottom;
// #ifdef APP-NVUE
return 30 + safeBottom
// #endif
// #ifndef APP-NVUE
return 30
// #endif
}
},
watch: {
pattern: {
handler(val, oldVal) {
this.styles = Object.assign({}, this.styles, val)
},
deep: true
}
},
created() {
this.isShow = this.show
if (this.top === 0) {
this.fabShow = true
}
// 初始化样式
this.styles = Object.assign({}, this.styles, this.pattern)
},
methods: {
_onClick() {
this.$emit('fabClick')
if (!this.popMenu) {
return
}
this.isShow = !this.isShow
},
open() {
this.isShow = true
},
close() {
this.isShow = false
},
/**
* 按钮点击事件
*/
_onItemClick(index, item) {
if (!this.isShow) {
return
}
this.$emit('trigger', {
index,
item
})
},
/**
* 获取 位置信息
*/
getPosition(types, paramA, paramB) {
if (types === 0) {
return this.horizontal === paramA && this.vertical === paramB
} else if (types === 1) {
return this.direction === paramA && this.vertical === paramB
} else if (types === 2) {
return this.direction === paramA && this.horizontal === paramB
} else {
return this.isShow && this.direction === paramA ? this.contentWidth : this.contentWidthMin
}
}
}
}
</script>
<style lang="scss" >
$uni-shadow-base:0 1px 5px 2px rgba($color: #000000, $alpha: 0.3) !default;
.uni-fab {
position: fixed;
/* #ifndef APP-NVUE */
display: flex;
/* #endif */
justify-content: center;
align-items: center;
z-index: 10;
border-radius: 45px;
box-shadow: $uni-shadow-base;
}
.uni-cursor-point {
/* #ifdef H5 */
cursor: pointer;
/* #endif */
}
.uni-fab--active {
opacity: 1;
}
.uni-fab--leftBottom {
left: 15px;
bottom: 30px;
/* #ifdef H5 */
left: calc(15px + var(--window-left));
bottom: calc(30px + var(--window-bottom));
/* #endif */
// padding: 10px;
}
.uni-fab--leftTop {
left: 15px;
top: 30px;
/* #ifdef H5 */
left: calc(15px + var(--window-left));
top: calc(30px + var(--window-top));
/* #endif */
// padding: 10px;
}
.uni-fab--rightBottom {
right: 15px;
bottom: 30px;
/* #ifdef H5 */
right: calc(15px + var(--window-right));
bottom: calc(30px + var(--window-bottom));
/* #endif */
// padding: 10px;
}
.uni-fab--rightTop {
right: 15px;
top: 30px;
/* #ifdef H5 */
right: calc(15px + var(--window-right));
top: calc(30px + var(--window-top));
/* #endif */
// padding: 10px;
}
.uni-fab__circle {
position: fixed;
/* #ifndef APP-NVUE */
display: flex;
/* #endif */
justify-content: center;
align-items: center;
width: 55px;
height: 55px;
background-color: #3c3e49;
border-radius: 45px;
z-index: 11;
// box-shadow: $uni-shadow-base;
}
.uni-fab__circle--leftBottom {
left: 15px;
bottom: 30px;
/* #ifdef H5 */
left: calc(15px + var(--window-left));
bottom: calc(30px + var(--window-bottom));
/* #endif */
}
.uni-fab__circle--leftTop {
left: 15px;
top: 30px;
/* #ifdef H5 */
left: calc(15px + var(--window-left));
top: calc(30px + var(--window-top));
/* #endif */
}
.uni-fab__circle--rightBottom {
right: 15px;
bottom: 30px;
/* #ifdef H5 */
right: calc(15px + var(--window-right));
bottom: calc(30px + var(--window-bottom));
/* #endif */
}
.uni-fab__circle--rightTop {
right: 15px;
top: 30px;
/* #ifdef H5 */
right: calc(15px + var(--window-right));
top: calc(30px + var(--window-top));
/* #endif */
}
.uni-fab__circle--left {
left: 0;
}
.uni-fab__circle--right {
right: 0;
}
.uni-fab__circle--top {
top: 0;
}
.uni-fab__circle--bottom {
bottom: 0;
}
.uni-fab__plus {
font-weight: bold;
}
// .fab-circle-v {
// position: absolute;
// width: 2px;
// height: 24px;
// left: 0;
// top: 0;
// right: 0;
// bottom: 0;
// /* #ifndef APP-NVUE */
// margin: auto;
// /* #endif */
// background-color: white;
// transform: rotate(0deg);
// transition: transform 0.3s;
// }
// .fab-circle-h {
// position: absolute;
// width: 24px;
// height: 2px;
// left: 0;
// top: 0;
// right: 0;
// bottom: 0;
// /* #ifndef APP-NVUE */
// margin: auto;
// /* #endif */
// background-color: white;
// transform: rotate(0deg);
// transition: transform 0.3s;
// }
.fab-circle-icon {
transform: rotate(0deg);
transition: transform 0.3s;
font-weight: 200;
}
.uni-fab__plus--active {
transform: rotate(135deg);
}
.uni-fab__content {
/* #ifndef APP-NVUE */
box-sizing: border-box;
display: flex;
/* #endif */
flex-direction: row;
border-radius: 55px;
overflow: hidden;
transition-property: width, height;
transition-duration: 0.2s;
width: 55px;
border-color: #DDDDDD;
border-width: 1rpx;
border-style: solid;
}
.uni-fab__content--other-platform {
border-width: 0px;
box-shadow: $uni-shadow-base;
}
.uni-fab__content--left {
justify-content: flex-start;
}
.uni-fab__content--right {
justify-content: flex-end;
}
.uni-fab__content--flexDirection {
flex-direction: column;
justify-content: flex-end;
}
.uni-fab__content--flexDirectionStart {
flex-direction: column;
justify-content: flex-start;
}
.uni-fab__content--flexDirectionEnd {
flex-direction: column;
justify-content: flex-end;
}
.uni-fab__item {
/* #ifndef APP-NVUE */
display: flex;
/* #endif */
flex-direction: column;
justify-content: center;
align-items: center;
width: 55px;
height: 55px;
opacity: 0;
transition: opacity 0.2s;
}
.uni-fab__item--active {
opacity: 1;
}
.uni-fab__item-image {
width: 20px;
height: 20px;
margin-bottom: 4px;
}
.uni-fab__item-text {
color: #FFFFFF;
font-size: 12px;
line-height: 12px;
margin-top: 2px;
}
.uni-fab__item--first {
width: 55px;
}
</style>
|
2301_77169380/aionix-2
|
uni_modules/uni-fab/components/uni-fab/uni-fab.vue
|
Vue
|
mit
| 11,160
|
import en from './en.json'
import zhHans from './zh-Hans.json'
import zhHant from './zh-Hant.json'
export default {
en,
'zh-Hans': zhHans,
'zh-Hant': zhHant
}
|
2301_77169380/aionix-2
|
uni_modules/uni-fav/components/uni-fav/i18n/index.js
|
JavaScript
|
mit
| 162
|
<template>
<view :class="[circle === true || circle === 'true' ? 'uni-fav--circle' : '']" :style="[{ backgroundColor: checked ? bgColorChecked : bgColor }]"
@click="onClick" class="uni-fav">
<!-- #ifdef MP-ALIPAY -->
<view class="uni-fav-star" v-if="!checked && (star === true || star === 'true')">
<uni-icons :color="fgColor" :style="{color: checked ? fgColorChecked : fgColor}" size="14" type="star-filled" />
</view>
<!-- #endif -->
<!-- #ifndef MP-ALIPAY -->
<uni-icons :color="fgColor" :style="{color: checked ? fgColorChecked : fgColor}" class="uni-fav-star" size="14" type="star-filled"
v-if="!checked && (star === true || star === 'true')" />
<!-- #endif -->
<text :style="{color: checked ? fgColorChecked : fgColor}" class="uni-fav-text">{{ checked ? contentFav : contentDefault }}</text>
</view>
</template>
<script>
/**
* Fav 收藏按钮
* @description 用于收藏功能,可点击切换选中、不选中的状态
* @tutorial https://ext.dcloud.net.cn/plugin?id=864
* @property {Boolean} star = [true|false] 按钮是否带星星
* @property {String} bgColor 未收藏时的背景色
* @property {String} bgColorChecked 已收藏时的背景色
* @property {String} fgColor 未收藏时的文字颜色
* @property {String} fgColorChecked 已收藏时的文字颜色
* @property {Boolean} circle = [true|false] 是否为圆角
* @property {Boolean} checked = [true|false] 是否为已收藏
* @property {Object} contentText = [true|false] 收藏按钮文字
* @property {Boolean} stat 是否开启统计功能
* @event {Function} click 点击 fav按钮触发事件
* @example <uni-fav :checked="true"/>
*/
import {
initVueI18n
} from '@dcloudio/uni-i18n'
import messages from './i18n/index.js'
const { t } = initVueI18n(messages)
export default {
name: "UniFav",
// TODO 兼容 vue3,需要注册事件
emits: ['click'],
props: {
star: {
type: [Boolean, String],
default: true
},
bgColor: {
type: String,
default: "#eeeeee"
},
fgColor: {
type: String,
default: "#666666"
},
bgColorChecked: {
type: String,
default: "#007aff"
},
fgColorChecked: {
type: String,
default: "#FFFFFF"
},
circle: {
type: [Boolean, String],
default: false
},
checked: {
type: Boolean,
default: false
},
contentText: {
type: Object,
default () {
return {
contentDefault: "",
contentFav: ""
};
}
},
stat:{
type: Boolean,
default: false
}
},
computed: {
contentDefault() {
return this.contentText.contentDefault || t("uni-fav.collect")
},
contentFav() {
return this.contentText.contentFav || t("uni-fav.collected")
},
},
watch: {
checked() {
if (uni.report && this.stat) {
if (this.checked) {
uni.report("收藏", "收藏");
} else {
uni.report("取消收藏", "取消收藏");
}
}
}
},
methods: {
onClick() {
this.$emit("click");
}
}
};
</script>
<style lang="scss" >
$fav-height: 25px;
.uni-fav {
/* #ifndef APP-NVUE */
display: flex;
/* #endif */
flex-direction: row;
align-items: center;
justify-content: center;
width: 60px;
height: $fav-height;
line-height: $fav-height;
text-align: center;
border-radius: 3px;
/* #ifdef H5 */
cursor: pointer;
/* #endif */
}
.uni-fav--circle {
border-radius: 30px;
}
.uni-fav-star {
/* #ifndef APP-NVUE */
display: flex;
/* #endif */
height: $fav-height;
line-height: 24px;
margin-right: 3px;
align-items: center;
justify-content: center;
}
.uni-fav-text {
/* #ifndef APP-NVUE */
display: flex;
/* #endif */
height: $fav-height;
line-height: $fav-height;
align-items: center;
justify-content: center;
font-size: 12px;
}
</style>
|
2301_77169380/aionix-2
|
uni_modules/uni-fav/components/uni-fav/uni-fav.vue
|
Vue
|
mit
| 3,847
|
'use strict';
const ERR_MSG_OK = 'chooseAndUploadFile:ok';
const ERR_MSG_FAIL = 'chooseAndUploadFile:fail';
function chooseImage(opts) {
const {
count,
sizeType = ['original', 'compressed'],
sourceType,
extension
} = opts
return new Promise((resolve, reject) => {
// 微信由于旧接口不再维护,针对微信小程序平台改用chooseMedia接口
// #ifdef MP-WEIXIN
uni.chooseMedia({
count,
sizeType,
sourceType,
mediaType: ['image'],
extension,
success(res) {
res.tempFiles.forEach(item => {
item.path = item.tempFilePath;
})
resolve(normalizeChooseAndUploadFileRes(res, 'image'));
},
fail(res) {
reject({
errMsg: res.errMsg.replace('chooseImage:fail', ERR_MSG_FAIL),
});
},
})
// #endif
// #ifndef MP-WEIXIN
uni.chooseImage({
count,
sizeType,
sourceType,
extension,
success(res) {
resolve(normalizeChooseAndUploadFileRes(res, 'image'));
},
fail(res) {
reject({
errMsg: res.errMsg.replace('chooseImage:fail', ERR_MSG_FAIL),
});
},
});
// #endif
});
}
function chooseVideo(opts) {
const {
count,
camera,
compressed,
maxDuration,
sourceType,
extension
} = opts;
return new Promise((resolve, reject) => {
// 微信由于旧接口不再维护,针对微信小程序平台改用chooseMedia接口
// #ifdef MP-WEIXIN
uni.chooseMedia({
count,
compressed,
maxDuration,
sourceType,
extension,
mediaType: ['video'],
success(res) {
const {
tempFiles,
} = res;
resolve(normalizeChooseAndUploadFileRes({
errMsg: 'chooseVideo:ok',
tempFiles: tempFiles.map(item => {
return {
name: item.name || '',
path: item.tempFilePath,
thumbTempFilePath: item.thumbTempFilePath,
size:item.size,
type: (res.tempFile && res.tempFile.type) || '',
width:item.width,
height:item.height,
duration:item.duration,
fileType: 'video',
cloudPath: '',
}
}),
}, 'video'));
},
fail(res) {
reject({
errMsg: res.errMsg.replace('chooseVideo:fail', ERR_MSG_FAIL),
});
},
})
// #endif
// #ifndef MP-WEIXIN
uni.chooseVideo({
camera,
compressed,
maxDuration,
sourceType,
extension,
success(res) {
const {
tempFilePath,
duration,
size,
height,
width
} = res;
resolve(normalizeChooseAndUploadFileRes({
errMsg: 'chooseVideo:ok',
tempFilePaths: [tempFilePath],
tempFiles: [{
name: (res.tempFile && res.tempFile.name) || '',
path: tempFilePath,
size,
type: (res.tempFile && res.tempFile.type) || '',
width,
height,
duration,
fileType: 'video',
cloudPath: '',
}, ],
}, 'video'));
},
fail(res) {
reject({
errMsg: res.errMsg.replace('chooseVideo:fail', ERR_MSG_FAIL),
});
},
});
// #endif
});
}
function chooseAll(opts) {
const {
count,
extension
} = opts;
return new Promise((resolve, reject) => {
let chooseFile = uni.chooseFile;
if (typeof wx !== 'undefined' &&
typeof wx.chooseMessageFile === 'function') {
chooseFile = wx.chooseMessageFile;
}
if (typeof chooseFile !== 'function') {
return reject({
errMsg: ERR_MSG_FAIL + ' 请指定 type 类型,该平台仅支持选择 image 或 video。',
});
}
chooseFile({
type: 'all',
count,
extension,
success(res) {
resolve(normalizeChooseAndUploadFileRes(res));
},
fail(res) {
reject({
errMsg: res.errMsg.replace('chooseFile:fail', ERR_MSG_FAIL),
});
},
});
});
}
function normalizeChooseAndUploadFileRes(res, fileType) {
res.tempFiles.forEach((item, index) => {
if (!item.name) {
item.name = item.path.substring(item.path.lastIndexOf('/') + 1);
}
if (fileType) {
item.fileType = fileType;
}
item.cloudPath =
Date.now() + '_' + index + item.name.substring(item.name.lastIndexOf('.'));
});
if (!res.tempFilePaths) {
res.tempFilePaths = res.tempFiles.map((file) => file.path);
}
return res;
}
function uploadCloudFiles(files, max = 5, onUploadProgress) {
files = JSON.parse(JSON.stringify(files))
const len = files.length
let count = 0
let self = this
return new Promise(resolve => {
while (count < max) {
next()
}
function next() {
let cur = count++
if (cur >= len) {
!files.find(item => !item.url && !item.errMsg) && resolve(files)
return
}
const fileItem = files[cur]
const index = self.files.findIndex(v => v.uuid === fileItem.uuid)
fileItem.url = ''
delete fileItem.errMsg
uniCloud
.uploadFile({
filePath: fileItem.path,
cloudPath: fileItem.cloudPath,
fileType: fileItem.fileType,
onUploadProgress: res => {
res.index = index
onUploadProgress && onUploadProgress(res)
}
})
.then(res => {
fileItem.url = res.fileID
fileItem.index = index
if (cur < len) {
next()
}
})
.catch(res => {
fileItem.errMsg = res.errMsg || res.message
fileItem.index = index
if (cur < len) {
next()
}
})
}
})
}
function uploadFiles(choosePromise, {
onChooseFile,
onUploadProgress
}) {
return choosePromise
.then((res) => {
if (onChooseFile) {
const customChooseRes = onChooseFile(res);
if (typeof customChooseRes !== 'undefined') {
return Promise.resolve(customChooseRes).then((chooseRes) => typeof chooseRes === 'undefined' ?
res : chooseRes);
}
}
return res;
})
.then((res) => {
if (res === false) {
return {
errMsg: ERR_MSG_OK,
tempFilePaths: [],
tempFiles: [],
};
}
return res
})
}
function chooseAndUploadFile(opts = {
type: 'all'
}) {
if (opts.type === 'image') {
return uploadFiles(chooseImage(opts), opts);
} else if (opts.type === 'video') {
return uploadFiles(chooseVideo(opts), opts);
}
return uploadFiles(chooseAll(opts), opts);
}
export {
chooseAndUploadFile,
uploadCloudFiles
};
|
2301_77169380/aionix-2
|
uni_modules/uni-file-picker/components/uni-file-picker/choose-and-upload-file.js
|
JavaScript
|
mit
| 6,017
|
<template>
<view class="uni-file-picker">
<view v-if="title" class="uni-file-picker__header">
<text class="file-title">{{ title }}</text>
<text class="file-count">{{ filesList.length }}/{{ limitLength }}</text>
</view>
<upload-image v-if="fileMediatype === 'image' && showType === 'grid'" :readonly="readonly"
:image-styles="imageStyles" :files-list="filesList" :limit="limitLength" :disablePreview="disablePreview"
:delIcon="delIcon" @uploadFiles="uploadFiles" @choose="choose" @delFile="delFile">
<slot>
<view class="is-add">
<view class="icon-add"></view>
<view class="icon-add rotate"></view>
</view>
</slot>
</upload-image>
<upload-file v-if="fileMediatype !== 'image' || showType !== 'grid'" :readonly="readonly"
:list-styles="listStyles" :files-list="filesList" :showType="showType" :delIcon="delIcon"
@uploadFiles="uploadFiles" @choose="choose" @delFile="delFile">
<slot><button type="primary" size="mini">选择文件</button></slot>
</upload-file>
</view>
</template>
<script>
import {
chooseAndUploadFile,
uploadCloudFiles
} from './choose-and-upload-file.js'
import {
get_file_ext,
get_extname,
get_files_and_is_max,
get_file_info,
get_file_data
} from './utils.js'
import uploadImage from './upload-image.vue'
import uploadFile from './upload-file.vue'
let fileInput = null
/**
* FilePicker 文件选择上传
* @description 文件选择上传组件,可以选择图片、视频等任意文件并上传到当前绑定的服务空间
* @tutorial https://ext.dcloud.net.cn/plugin?id=4079
* @property {Object|Array} value 组件数据,通常用来回显 ,类型由return-type属性决定
* @property {Boolean} disabled = [true|false] 组件禁用
* @value true 禁用
* @value false 取消禁用
* @property {Boolean} readonly = [true|false] 组件只读,不可选择,不显示进度,不显示删除按钮
* @value true 只读
* @value false 取消只读
* @property {String} return-type = [array|object] 限制 value 格式,当为 object 时 ,组件只能单选,且会覆盖
* @value array 规定 value 属性的类型为数组
* @value object 规定 value 属性的类型为对象
* @property {Boolean} disable-preview = [true|false] 禁用图片预览,仅 mode:grid 时生效
* @value true 禁用图片预览
* @value false 取消禁用图片预览
* @property {Boolean} del-icon = [true|false] 是否显示删除按钮
* @value true 显示删除按钮
* @value false 不显示删除按钮
* @property {Boolean} auto-upload = [true|false] 是否自动上传,值为true则只触发@select,可自行上传
* @value true 自动上传
* @value false 取消自动上传
* @property {Number|String} limit 最大选择个数 ,h5 会自动忽略多选的部分
* @property {String} title 组件标题,右侧显示上传计数
* @property {String} mode = [list|grid] 选择文件后的文件列表样式
* @value list 列表显示
* @value grid 宫格显示
* @property {String} file-mediatype = [image|video|all] 选择文件类型
* @value image 只选择图片
* @value video 只选择视频
* @value all 选择所有文件
* @property {Array} file-extname 选择文件后缀,根据 file-mediatype 属性而不同
* @property {Object} list-style mode:list 时的样式
* @property {Object} image-styles 选择文件后缀,根据 file-mediatype 属性而不同
* @event {Function} select 选择文件后触发
* @event {Function} progress 文件上传时触发
* @event {Function} success 上传成功触发
* @event {Function} fail 上传失败触发
* @event {Function} delete 文件从列表移除时触发
*/
export default {
name: 'uniFilePicker',
components: {
uploadImage,
uploadFile
},
options: {
virtualHost: true
},
emits: ['select', 'success', 'fail', 'progress', 'delete', 'update:modelValue', 'input'],
props: {
// #ifdef VUE3
modelValue: {
type: [Array, Object],
default () {
return []
}
},
// #endif
// #ifndef VUE3
value: {
type: [Array, Object],
default () {
return []
}
},
// #endif
disabled: {
type: Boolean,
default: false
},
disablePreview: {
type: Boolean,
default: false
},
delIcon: {
type: Boolean,
default: true
},
// 自动上传
autoUpload: {
type: Boolean,
default: true
},
// 最大选择个数 ,h5只能限制单选或是多选
limit: {
type: [Number, String],
default: 9
},
// 列表样式 grid | list | list-card
mode: {
type: String,
default: 'grid'
},
// 选择文件类型 image/video/all
fileMediatype: {
type: String,
default: 'image'
},
// 文件类型筛选
fileExtname: {
type: [Array, String],
default () {
return []
}
},
title: {
type: String,
default: ''
},
listStyles: {
type: Object,
default () {
return {
// 是否显示边框
border: true,
// 是否显示分隔线
dividline: true,
// 线条样式
borderStyle: {}
}
}
},
imageStyles: {
type: Object,
default () {
return {
width: 'auto',
height: 'auto'
}
}
},
readonly: {
type: Boolean,
default: false
},
returnType: {
type: String,
default: 'array'
},
sizeType: {
type: Array,
default () {
return ['original', 'compressed']
}
},
sourceType: {
type: Array,
default () {
return ['album', 'camera']
}
},
provider: {
type: String,
default: '' // 默认上传到 unicloud 内置存储 extStorage 扩展存储
}
},
data() {
return {
files: [],
localValue: []
}
},
watch: {
// #ifndef VUE3
value: {
handler(newVal, oldVal) {
this.setValue(newVal, oldVal)
},
immediate: true
},
// #endif
// #ifdef VUE3
modelValue: {
handler(newVal, oldVal) {
this.setValue(newVal, oldVal)
},
immediate: true
},
// #endif
},
computed: {
filesList() {
let files = []
this.files.forEach(v => {
files.push(v)
})
return files
},
showType() {
if (this.fileMediatype === 'image') {
return this.mode
}
return 'list'
},
limitLength() {
if (this.returnType === 'object') {
return 1
}
if (!this.limit) {
return 1
}
if (this.limit >= 9) {
return 9
}
return this.limit
}
},
created() {
// TODO 兼容不开通服务空间的情况
if (!(uniCloud.config && uniCloud.config.provider)) {
this.noSpace = true
uniCloud.chooseAndUploadFile = chooseAndUploadFile
}
this.form = this.getForm('uniForms')
this.formItem = this.getForm('uniFormsItem')
if (this.form && this.formItem) {
if (this.formItem.name) {
this.rename = this.formItem.name
this.form.inputChildrens.push(this)
}
}
},
methods: {
/**
* 公开用户使用,清空文件
* @param {Object} index
*/
clearFiles(index) {
if (index !== 0 && !index) {
this.files = []
this.$nextTick(() => {
this.setEmit()
})
} else {
this.files.splice(index, 1)
}
this.$nextTick(() => {
this.setEmit()
})
},
/**
* 公开用户使用,继续上传
*/
upload() {
let files = []
this.files.forEach((v, index) => {
if (v.status === 'ready' || v.status === 'error') {
files.push(Object.assign({}, v))
}
})
return this.uploadFiles(files)
},
async setValue(newVal, oldVal) {
const newData = async (v) => {
const reg = /cloud:\/\/([\w.]+\/?)\S*/
let url = ''
if(v.fileID){
url = v.fileID
}else{
url = v.url
}
if (reg.test(url)) {
v.fileID = url
v.url = await this.getTempFileURL(url)
}
if(v.url) v.path = v.url
return v
}
if (this.returnType === 'object') {
if (newVal) {
await newData(newVal)
} else {
newVal = {}
}
} else {
if (!newVal) newVal = []
for(let i =0 ;i < newVal.length ;i++){
let v = newVal[i]
await newData(v)
}
}
this.localValue = newVal
if (this.form && this.formItem &&!this.is_reset) {
this.is_reset = false
this.formItem.setValue(this.localValue)
}
let filesData = Object.keys(newVal).length > 0 ? newVal : [];
this.files = [].concat(filesData)
},
/**
* 选择文件
*/
choose() {
if (this.disabled) return
if (this.files.length >= Number(this.limitLength) && this.showType !== 'grid' && this.returnType ===
'array') {
uni.showToast({
title: `您最多选择 ${this.limitLength} 个文件`,
icon: 'none'
})
return
}
this.chooseFiles()
},
/**
* 选择文件并上传
*/
chooseFiles() {
const _extname = get_extname(this.fileExtname)
// 获取后缀
uniCloud
.chooseAndUploadFile({
type: this.fileMediatype,
compressed: false,
sizeType: this.sizeType,
sourceType: this.sourceType,
// TODO 如果为空,video 有问题
extension: _extname.length > 0 ? _extname : undefined,
count: this.limitLength - this.files.length, //默认9
onChooseFile: this.chooseFileCallback,
onUploadProgress: progressEvent => {
this.setProgress(progressEvent, progressEvent.index)
}
})
.then(result => {
this.setSuccessAndError(result.tempFiles)
})
.catch(err => {
console.log('选择失败', err)
})
},
/**
* 选择文件回调
* @param {Object} res
*/
async chooseFileCallback(res) {
const _extname = get_extname(this.fileExtname)
const is_one = (Number(this.limitLength) === 1 &&
this.disablePreview &&
!this.disabled) ||
this.returnType === 'object'
// 如果这有一个文件 ,需要清空本地缓存数据
if (is_one) {
this.files = []
}
let {
filePaths,
files
} = get_files_and_is_max(res, _extname)
if (!(_extname && _extname.length > 0)) {
filePaths = res.tempFilePaths
files = res.tempFiles
}
let currentData = []
for (let i = 0; i < files.length; i++) {
if (this.limitLength - this.files.length <= 0) break
files[i].uuid = Date.now()
let filedata = await get_file_data(files[i], this.fileMediatype)
filedata.progress = 0
filedata.status = 'ready'
this.files.push(filedata)
currentData.push({
...filedata,
file: files[i]
})
}
this.$emit('select', {
tempFiles: currentData,
tempFilePaths: filePaths
})
res.tempFiles = files
// 停止自动上传
if (!this.autoUpload || this.noSpace) {
res.tempFiles = []
}
res.tempFiles.forEach((fileItem, index) => {
this.provider && (fileItem.provider = this.provider);
const fileNameSplit = fileItem.name.split('.')
const ext = fileNameSplit.pop()
const fileName = fileNameSplit.join('.').replace(/[\s\/\?<>\\:\*\|":]/g, '_')
fileItem.cloudPath = fileName + '_' + Date.now() + '_' + index + '.' + ext
})
},
/**
* 批传
* @param {Object} e
*/
uploadFiles(files) {
files = [].concat(files)
return uploadCloudFiles.call(this, files, 5, res => {
this.setProgress(res, res.index, true)
})
.then(result => {
this.setSuccessAndError(result)
return result;
})
.catch(err => {
console.log(err)
})
},
/**
* 成功或失败
*/
async setSuccessAndError(res, fn) {
let successData = []
let errorData = []
let tempFilePath = []
let errorTempFilePath = []
for (let i = 0; i < res.length; i++) {
const item = res[i]
const index = item.uuid ? this.files.findIndex(p => p.uuid === item.uuid) : item.index
if (index === -1 || !this.files) break
if (item.errMsg === 'request:fail') {
this.files[index].url = item.path
this.files[index].status = 'error'
this.files[index].errMsg = item.errMsg
// this.files[index].progress = -1
errorData.push(this.files[index])
errorTempFilePath.push(this.files[index].url)
} else {
this.files[index].errMsg = ''
this.files[index].fileID = item.url
const reg = /cloud:\/\/([\w.]+\/?)\S*/
if (reg.test(item.url)) {
this.files[index].url = await this.getTempFileURL(item.url)
}else{
this.files[index].url = item.url
}
this.files[index].status = 'success'
this.files[index].progress += 1
successData.push(this.files[index])
tempFilePath.push(this.files[index].fileID)
}
}
if (successData.length > 0) {
this.setEmit()
// 状态改变返回
this.$emit('success', {
tempFiles: this.backObject(successData),
tempFilePaths: tempFilePath
})
}
if (errorData.length > 0) {
this.$emit('fail', {
tempFiles: this.backObject(errorData),
tempFilePaths: errorTempFilePath
})
}
},
/**
* 获取进度
* @param {Object} progressEvent
* @param {Object} index
* @param {Object} type
*/
setProgress(progressEvent, index, type) {
const fileLenth = this.files.length
const percentNum = (index / fileLenth) * 100
const percentCompleted = Math.round((progressEvent.loaded * 100) / progressEvent.total)
let idx = index
if (!type) {
idx = this.files.findIndex(p => p.uuid === progressEvent.tempFile.uuid)
}
if (idx === -1 || !this.files[idx]) return
// fix by mehaotian 100 就会消失,-1 是为了让进度条消失
this.files[idx].progress = percentCompleted - 1
// 上传中
this.$emit('progress', {
index: idx,
progress: parseInt(percentCompleted),
tempFile: this.files[idx]
})
},
/**
* 删除文件
* @param {Object} index
*/
delFile(index) {
this.$emit('delete', {
index,
tempFile: this.files[index],
tempFilePath: this.files[index].url
})
this.files.splice(index, 1)
this.$nextTick(() => {
this.setEmit()
})
},
/**
* 获取文件名和后缀
* @param {Object} name
*/
getFileExt(name) {
const last_len = name.lastIndexOf('.')
const len = name.length
return {
name: name.substring(0, last_len),
ext: name.substring(last_len + 1, len)
}
},
/**
* 处理返回事件
*/
setEmit() {
let data = []
if (this.returnType === 'object') {
data = this.backObject(this.files)[0]
this.localValue = data?data:null
} else {
data = this.backObject(this.files)
if (!this.localValue) {
this.localValue = []
}
this.localValue = [...data]
}
// #ifdef VUE3
this.$emit('update:modelValue', this.localValue)
// #endif
// #ifndef VUE3
this.$emit('input', this.localValue)
// #endif
},
/**
* 处理返回参数
* @param {Object} files
*/
backObject(files) {
let newFilesData = []
files.forEach(v => {
newFilesData.push({
extname: v.extname,
fileType: v.fileType,
image: v.image,
name: v.name,
path: v.path,
size: v.size,
fileID:v.fileID,
url: v.url,
// 修改删除一个文件后不能再上传的bug, #694
uuid: v.uuid,
status: v.status,
cloudPath: v.cloudPath
})
})
return newFilesData
},
async getTempFileURL(fileList) {
fileList = {
fileList: [].concat(fileList)
}
const urls = await uniCloud.getTempFileURL(fileList)
return urls.fileList[0].tempFileURL || ''
},
/**
* 获取父元素实例
*/
getForm(name = 'uniForms') {
let parent = this.$parent;
let parentName = parent.$options.name;
while (parentName !== name) {
parent = parent.$parent;
if (!parent) return false;
parentName = parent.$options.name;
}
return parent;
}
}
}
</script>
<style>
.uni-file-picker {
/* #ifndef APP-NVUE */
box-sizing: border-box;
overflow: hidden;
width: 100%;
/* #endif */
flex: 1;
}
.uni-file-picker__header {
padding-top: 5px;
padding-bottom: 10px;
/* #ifndef APP-NVUE */
display: flex;
/* #endif */
justify-content: space-between;
}
.file-title {
font-size: 14px;
color: #333;
}
.file-count {
font-size: 14px;
color: #999;
}
.is-add {
/* #ifndef APP-NVUE */
display: flex;
/* #endif */
align-items: center;
justify-content: center;
}
.icon-add {
width: 50px;
height: 5px;
background-color: #f1f1f1;
border-radius: 2px;
}
.rotate {
position: absolute;
transform: rotate(90deg);
}
</style>
|
2301_77169380/aionix-2
|
uni_modules/uni-file-picker/components/uni-file-picker/uni-file-picker.vue
|
Vue
|
mit
| 16,857
|