Skip to content

Instantly share code, notes, and snippets.

@frankli0324
Created July 20, 2023 10:41
Show Gist options
  • Save frankli0324/8ae8c523f71327417484eed7e59d5c18 to your computer and use it in GitHub Desktop.
Save frankli0324/8ae8c523f71327417484eed7e59d5c18 to your computer and use it in GitHub Desktop.
date range selector based on https://github.com/Vuepic/vue-datepicker
<template>
<DatePicker
class="date-range" ref="picker"
v-model="date" required
range auto-apply close-on-scroll
time-picker-inline hide-input-icon
text-input :text-input-options="{ openMenu: false}"
@focus="picker?.openMenu()"
:clearable="false"
:close-on-auto-apply="false"
:space-confirm="false"
:month-change-on-scroll="false"
:dark="theme === 'dark'"
model-type="timestamp"
format="MM/dd HH:mm"
:preset-ranges="presets"
:max-date="new Date()"></DatePicker>
<!-- https://github.com/Vuepic/vue-datepicker/issues/493 -->
</template>
<script setup lang="ts">
import DatePicker, { type DatePickerInstance } from '@vuepic/vue-datepicker';
import dayjs from 'dayjs';
import { inject, onMounted, ref, type Ref } from 'vue';
const picker = ref<DatePickerInstance>();
let date = ref([0, 0]);
let presets = ref<{ label: string, range: any[] }[]>([]);
const theme = inject<Ref<string>>('theme', ref("light"));
onMounted(() => {
function last(t: number, unit: dayjs.ManipulateType) {
return new Proxy<number[]>([], {
get: (_, p, __) => {
if (p === "length") return 2;
if (p === "map") return (cb: Function) => {
const now = dayjs();
return [
cb(now.unix() * 1000, 0),
cb(now.subtract(t, unit).unix() * 1000, 1),
];
}
}
})
}
const now = dayjs();
date.value = [now.unix() * 1000, now.unix() * 1000];
presets.value = [
{ label: 'last 24h', range: last(1, 'day') },
{ label: 'last 5min', range: last(5, 'minute') },
{ label: 'last 30min', range: last(30, 'minute') },
{ label: 'last 1h', range: last(1, 'hour') },
{ label: 'last 2h', range: last(2, 'hour') },
];
})
</script>
<style src="@vuepic/vue-datepicker/dist/main.css" />
<style scoped>
.date-range {
--dp-input-padding: 0;
--dp-background-color: transparent;
--dp-font-size: var(--text-font-size);
}
:deep(.dp__input_wrap) {
display: flex;
height: 28px;
}
:deep(.dp__input) {
border: none;
height: 100%;
text-align: center;
}
</style>
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment