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 class="select-none space-y-3 bg-white p-1 text-base">
<div class="flex items-center text-gray-700">
<div
class="flex h-6 w-6 cursor-pointer items-center justify-center rounded hover:bg-gray-100"
>
<FeatherIcon @click="prevMonth" name="chevron-left" class="h-5 w-5" />
</div>
<div class="flex-1 text-center text-lg font-medium text-blue-500">
{{ formatMonth }}
</div>
<div
class="flex h-6 w-6 cursor-pointer items-center justify-center rounded hover:bg-gray-100"
>
<FeatherIcon @click="nextMonth" name="chevron-right" class="h-5 w-5" />
</div>
</div>
<div class="flex space-x-2">
<Input class="w-[7rem]" type="text" v-model="fromDate"></Input>
<Input class="w-[7rem]" type="text" v-model="toDate"></Input>
</div>
<div class="mt-2 flex flex-col items-center justify-center text-base">
<div class="flex w-full items-center justify-center text-gray-600">
<div
class="flex h-[32px] w-[32px] items-center justify-center text-center"
v-for="(d, i) in ['S', 'M', 'T', 'W', 'T', 'F', 'S']"
:key="i"
>
{{ d }}
</div>
</div>
<div v-for="(week, i) in datesAsWeeks" :key="i">
<div class="flex w-full items-center">
<div
v-for="date in week"
:key="toValue(date)"
class="flex h-[32px] w-[32px] cursor-pointer items-center justify-center hover:bg-blue-50 hover:text-blue-500"
:class="{
'text-gray-600': date.getMonth() !== currentMonth - 1,
'text-blue-500': toValue(date) === toValue(today),
'bg-blue-50 text-blue-500': isInRange(date),
'rounded-l-md bg-blue-100':
fromDate && toValue(date) === toValue(fromDate),
'rounded-r-md bg-blue-100': toDate && toValue(date) === toValue(toDate),
}"
@click="() => handleDateClick(date)"
>
{{ date.getDate() }}
</div>
</div>
</div>
</div>
<div class="mt-1 flex w-full justify-end space-x-2">
<Button @click="() => clearDates()" :disabled="!value"> Clear </Button>
<Button @click="selectDates()" :disabled="!fromDate || !toDate" variant="solid">
Apply
</Button>
</div>
</div>
</template>
<script>
export default {
name: 'DateRangePicker',
props: ['value', 'placeholder', 'formatter', 'readonly', 'inputClass'],
emits: ['change'],
data() {
const fromDate = this.value ? this.value.split(',')[0] : ''
const toDate = this.value ? this.value.split(',')[1] : ''
return {
currentYear: null,
currentMonth: null,
fromDate,
toDate,
}
},
created() {
this.selectCurrentMonthYear()
},
computed: {
today() {
return this.getDate()
},
datesAsWeeks() {
let datesAsWeeks = []
let dates = this.dates.slice()
while (dates.length) {
let week = dates.splice(0, 7)
datesAsWeeks.push(week)
}
return datesAsWeeks
},
dates() {
if (!(this.currentYear && this.currentMonth)) {
return []
}
let monthIndex = this.currentMonth - 1
let year = this.currentYear
let firstDayOfMonth = this.getDate(year, monthIndex, 1)
let lastDayOfMonth = this.getDate(year, monthIndex + 1, 0)
let leftPaddingCount = firstDayOfMonth.getDay()
let rightPaddingCount = 6 - lastDayOfMonth.getDay()
let leftPadding = this.getDatesAfter(firstDayOfMonth, -leftPaddingCount)
let rightPadding = this.getDatesAfter(lastDayOfMonth, rightPaddingCount)
let daysInMonth = this.getDaysInMonth(monthIndex, year)
let datesInMonth = this.getDatesAfter(firstDayOfMonth, daysInMonth - 1)
let dates = [...leftPadding, firstDayOfMonth, ...datesInMonth, ...rightPadding]
if (dates.length < 42) {
const finalPadding = this.getDatesAfter(dates.at(-1), 42 - dates.length)
dates = dates.concat(...finalPadding)
}
return dates
},
formatMonth() {
let date = this.getDate(this.currentYear, this.currentMonth - 1, 1)
return date.toLocaleString('en-US', {
month: 'short',
year: 'numeric',
})
},
},
methods: {
handleDateClick(date) {
if (this.fromDate && this.toDate) {
this.fromDate = this.toValue(date)
this.toDate = ''
} else if (this.fromDate && !this.toDate) {
this.toDate = this.toValue(date)
} else {
this.fromDate = this.toValue(date)
}
this.swapDatesIfNecessary()
},
selectDates() {
if (!this.fromDate && !this.toDate) {
return this.$emit('change', '')
}
this.$emit('change', `${this.fromDate},${this.toDate}`)
},
swapDatesIfNecessary() {
if (!this.fromDate || !this.toDate) {
return
}
// if fromDate is greater than toDate, swap them
let fromDate = this.getDate(this.fromDate)
let toDate = this.getDate(this.toDate)
if (fromDate > toDate) {
let temp = fromDate
fromDate = toDate
toDate = temp
}
this.fromDate = this.toValue(fromDate)
this.toDate = this.toValue(toDate)
},
selectCurrentMonthYear() {
let date = this.toDate ? this.getDate(this.toDate) : this.today
this.currentYear = date.getFullYear()
this.currentMonth = date.getMonth() + 1
},
prevMonth() {
this.changeMonth(-1)
},
nextMonth() {
this.changeMonth(1)
},
changeMonth(adder) {
this.currentMonth = this.currentMonth + adder
if (this.currentMonth < 1) {
this.currentMonth = 12
this.currentYear = this.currentYear - 1
}
if (this.currentMonth > 12) {
this.currentMonth = 1
this.currentYear = this.currentYear + 1
}
},
getDatesAfter(date, count) {
let incrementer = 1
if (count < 0) {
incrementer = -1
count = Math.abs(count)
}
let dates = []
while (count) {
date = this.getDate(
date.getFullYear(),
date.getMonth(),
date.getDate() + incrementer
)
dates.push(date)
count--
}
if (incrementer === -1) {
return dates.reverse()
}
return dates
},
getDaysInMonth(monthIndex, year) {
let daysInMonthMap = [31, 28, 31, 30, 31, 30, 31, 31, 30, 31, 30, 31]
let daysInMonth = daysInMonthMap[monthIndex]
if (monthIndex === 1 && this.isLeapYear(year)) {
return 29
}
return daysInMonth
},
isLeapYear(year) {
if (year % 400 === 0) return true
if (year % 100 === 0) return false
if (year % 4 === 0) return true
return false
},
toValue(date) {
if (!date) {
return ''
}
if (typeof date === 'string') {
return date
}
// toISOString is buggy and reduces the day by one
// this is because it considers the UTC timestamp
// in order to circumvent that we need to use luxon/moment
// but that refactor could take some time, so fixing the time difference
// as suggested in this answer.
// https://stackoverflow.com/a/16084846/3541205
date.setHours(0, -date.getTimezoneOffset(), 0, 0)
return date.toISOString().slice(0, 10)
},
getDate(...args) {
let d = new Date(...args)
return d
},
isInRange(date) {
if (!this.fromDate || !this.toDate) {
return false
}
return date >= this.getDate(this.fromDate) && date <= this.getDate(this.toDate)
},
formatDates(value) {
if (!value) {
return ''
}
const values = value.split(',')
return this.formatter(values[0]) + ' to ' + this.formatter(values[1])
},
clearDates() {
this.fromDate = ''
this.toDate = ''
this.selectDates()
},
},
}
</script>
|
2302_79757062/insights
|
frontend/src/components/Controls/DateRangePickerFlat.vue
|
Vue
|
agpl-3.0
| 7,256
|
<script setup>
import Tabs from '@/components/Tabs.vue'
import { computed } from 'vue'
defineEmits(['tab-change'])
const props = defineProps(['placeholder', 'tabs', 'value'])
const tabs = computed(() =>
Object.keys(props.tabs).map((key) => ({
label: key,
active: props.tabs[key],
}))
)
function getLabel() {
return props.value?.label || props.value
}
</script>
<template>
<Popover class="flex w-full [&>div:first-child]:w-full" :hideOnBlur="false">
<template #target="{ togglePopover }">
<input
readonly
type="text"
:value="getLabel()"
:placeholder="placeholder"
@focus="togglePopover()"
class="form-input block h-7 w-full cursor-text select-none rounded border-gray-400 text-sm placeholder-gray-500"
/>
</template>
<template #body="{ togglePopover }">
<div
class="my-2 flex select-none flex-col space-y-3 rounded border bg-white p-3 text-base shadow-md"
>
<Tabs
:tabs="tabs"
:model-value="getLabel()"
@update:model-value="$emit('tab-change', $event.label)"
/>
<slot name="inputs"></slot>
<div class="flex w-full justify-end">
<Button variant="solid" @click="togglePopover()"> Done </Button>
</div>
</div>
</template>
</Popover>
</template>
|
2302_79757062/insights
|
frontend/src/components/Controls/InputWithTabs.vue
|
Vue
|
agpl-3.0
| 1,244
|
<script setup>
const props = defineProps({ link: { type: String, required: true } })
function openLink() {
window.open(props.link, '_blank')
}
</script>
<template>
<div class="relative">
<slot></slot>
<div
v-if="props.link"
class="absolute top-0 right-0 flex h-full w-8 cursor-pointer items-center justify-center"
@click.prevent.stop="openLink"
>
<FeatherIcon name="link-2" class="h-4 w-4 text-gray-600 hover:text-gray-800" />
</div>
</div>
</template>
|
2302_79757062/insights
|
frontend/src/components/Controls/LinkIcon.vue
|
Vue
|
agpl-3.0
| 477
|
<template>
<Combobox multiple nullable v-slot="{ open: isComboboxOpen }" v-model="selectedOptions">
<Popover class="w-full">
<template #target="{ open: openPopover }">
<div class="w-full">
<ComboboxButton
class="form-input flex h-fit w-full items-center justify-between rounded border-gray-400 bg-gray-100"
:class="{
'rounded-b-none': isComboboxOpen,
'p-1': selectedOptions.length > 0,
'px-3 py-1.5': selectedOptions.length === 0,
}"
@click="openPopover()"
>
<span
v-if="selectedOptions.length > 0"
class="flex w-[calc(100%-1rem)] space-x-1.5 p-0.5 text-gray-800"
>
<span
class="flex h-6 items-center rounded bg-white px-2 text-sm shadow"
v-for="option in selectedOptions"
:key="option.value || option"
>
<span class="text-ellipsis whitespace-nowrap">
{{ option.label || option.value || option }}
</span>
</span>
</span>
<span class="text-base text-gray-600" v-else>
{{ placeholder || '' }}
</span>
<FeatherIcon
name="chevron-down"
class="h-4 w-4 text-gray-600"
aria-hidden="true"
/>
</ComboboxButton>
</div>
</template>
<template #body="{ close: closePopover }">
<div v-show="isComboboxOpen" class="rounded rounded-t-none bg-white px-1.5 shadow">
<ComboboxOptions static class="max-h-[20rem] overflow-y-auto">
<div
class="sticky top-0 mb-1.5 flex items-stretch space-x-1.5 bg-white pt-1.5"
>
<div class="relative -m-1 flex flex-1 overflow-hidden p-1">
<ComboboxInput
class="form-input block w-full border-gray-400 placeholder-gray-500"
ref="input"
type="text"
@change="
(e) => {
query = e.target.value
emit('inputChange', e.target.value)
}
"
:value="query"
autocomplete="off"
placeholder="Search..."
/>
<div
v-if="loading"
class="absolute right-2 flex h-full items-center"
>
<LoadingIndicator class="h-3 w-3" />
</div>
</div>
<Button icon="x" @click="selectedOptions = []" />
</div>
<div
v-if="filteredOptions.length === 0"
class="flex h-7 w-full items-center rounded bg-gray-50 px-3 text-sm font-light"
>
No results found
</div>
<ComboboxOption
v-for="(option, idx) in filteredOptions"
:key="idx"
:value="option"
v-show="filteredOptions.length > 0"
@click="
() => {
$refs.input.el.focus()
// need to manually remove option from selectedOptions
// because clicking on an option twice doesn't unselect it
toggleSelection(option)
}
"
v-slot="{ active }"
>
<div
class="flex h-7 w-full cursor-pointer items-center justify-between rounded px-3 text-base"
:class="{
'bg-gray-100 text-gray-800': active,
'bg-white': !active,
}"
>
<div class="flex items-baseline space-x-2">
<span>{{ option.label }}</span>
<span
v-if="option.description"
class="text-sm font-light text-gray-600"
>
{{ option.description }}
</span>
</div>
<FeatherIcon
name="check"
class="h-4 w-4"
v-show="isSelected(option)"
/>
</div>
</ComboboxOption>
<div class="sticky bottom-0 flex justify-end space-x-2 bg-white py-2">
<Button variant="secondary" @click.prevent.stop="selectOrClearAll()">
{{ selectedOptions.length > 0 ? 'Clear' : 'Select All' }}
</Button>
<Button
variant="solid"
@click="$emit('apply', selectedOptions) || closePopover()"
>
Apply
</Button>
</div>
</ComboboxOptions>
</div>
</template>
</Popover>
</Combobox>
</template>
<script setup>
import {
Combobox,
ComboboxButton,
ComboboxInput,
ComboboxOption,
ComboboxOptions,
} from '@headlessui/vue'
import { LoadingIndicator } from 'frappe-ui'
import { computed, inject, ref } from 'vue'
const emit = defineEmits(['inputChange', 'change', 'update:modelValue', 'apply'])
const props = defineProps({
label: {
type: String,
default: '',
},
placeholder: {
type: String,
default: '',
},
value: Array,
modelValue: Array,
options: {
type: Array,
default: [],
},
loading: {
type: Boolean,
default: false,
},
})
const query = ref('')
const options = computed(() => makeOptions(props.options.slice()))
function makeOptions(options) {
// make sure options are objects with a label property and a value property with no duplicates
if (!options || options.length === 0) {
return []
}
if (options[0].hasOwnProperty('label') && options[0].hasOwnProperty('value')) {
// pass through
}
if (typeof options[0] === 'string') {
options = options.map((option) => {
return {
label: option,
value: option,
}
})
}
options = options.filter((option, index, self) => {
return option && option.value && self.findIndex((t) => t.value === option.value) === index
})
return options
}
const valueProp = props.modelValue ? 'modelValue' : 'value'
const selectedOptions = computed({
get() {
return makeOptions(props[valueProp]?.slice())
},
set(val) {
emit('change', val)
emit('update:modelValue', val)
},
})
function isSelected(option) {
return selectedOptions.value.findIndex((t) => t.value === option.value) > -1
}
function toggleSelection(option) {
if (isSelected(option)) {
selectedOptions.value = selectedOptions.value.filter((t) => t.value !== option.value)
} else {
selectedOptions.value = [...selectedOptions.value, option]
}
}
const $utils = inject('$utils')
const filteredOptions = computed(() => {
return !query.value
? options.value
: $utils.fuzzySearch(options.value, {
term: query.value,
keys: ['label', 'value'],
})
})
const selectOrClearAll = () => {
selectedOptions.value = selectedOptions.value.length > 0 ? [] : filteredOptions.value
}
</script>
|
2302_79757062/insights
|
frontend/src/components/Controls/ListPicker.vue
|
Vue
|
agpl-3.0
| 6,182
|
<template>
<Popover class="flex w-full [&>div:first-child]:w-full">
<template #target="{ togglePopover }">
<input
readonly
type="text"
:value="_value"
:placeholder="placeholder"
@focus="togglePopover()"
class="form-input block h-7 w-full cursor-text select-none rounded border-gray-400 text-sm placeholder-gray-500"
/>
</template>
<template #body="{ togglePopover }">
<div
class="my-2 flex w-[18rem] select-none flex-col space-y-3 rounded border bg-white p-3 text-base shadow-md"
>
<Tabs :tabs="['Last', 'Current', 'Next']" v-model="span"></Tabs>
<div class="flex space-x-2">
<Input
v-if="span !== 'Current'"
type="number"
v-model="interval"
class="w-full text-sm"
/>
<Input
type="select"
v-model="intervalType"
class="w-full text-sm"
:options="['Day', 'Week', 'Month', 'Quarter', 'Year', 'Fiscal Year']"
>
</Input>
</div>
<div class="flex justify-end">
<Button
variant="solid"
@click="
() => {
apply()
togglePopover()
}
"
>
Done
</Button>
</div>
</div>
</template>
</Popover>
</template>
<script>
import Tabs from '@/components/Tabs.vue'
export default {
name: 'TimespanPicker',
components: { Tabs },
emits: ['update:modelValue', 'change'],
props: ['value', 'modelValue', 'placeholder'],
data() {
const initalValue = (this.valuePropPassed() ? this.value : this.modelValue?.value) || ''
let [span, interval, intervalType] = initalValue.split(' ')
if (span == 'Current') intervalType = interval // eg. Current Day
if (intervalType?.at(-1) == 's') intervalType = intervalType.slice(0, -1) // eg. Days
return {
span: span || 'Last',
interval: interval || '1',
intervalType: intervalType || 'Day',
}
},
computed: {
_value() {
return this.span === 'Current'
? `${this.span} ${this.intervalType}`
: `${this.span} ${this.interval} ${this.intervalType}`
},
},
watch: {
interval(new_val) {
if (new_val < 1) {
this.interval = 1
}
},
},
methods: {
valuePropPassed() {
return this.value !== undefined
},
apply() {
if (this.valuePropPassed()) {
this.$emit('change', this._value)
} else {
this.$emit('update:modelValue', {
value: this._value,
label: this._value,
})
}
},
},
}
</script>
|
2302_79757062/insights
|
frontend/src/components/Controls/TimespanPicker.vue
|
Vue
|
agpl-3.0
| 2,396
|
<template>
<div class="flex select-none flex-col space-y-3 text-base">
<Tabs :tabs="['Last', 'Current', 'Next']" v-model="span"></Tabs>
<div class="flex space-x-2">
<Input
v-if="span !== 'Current'"
type="number"
v-model="interval"
class="w-full text-sm"
/>
<Input
type="select"
v-model="intervalType"
class="w-full text-sm"
:options="['Day', 'Week', 'Month', 'Quarter', 'Year', 'Fiscal Year']"
>
</Input>
</div>
<div class="flex justify-end">
<Button variant="solid" @click="apply()"> Done </Button>
</div>
</div>
</template>
<script>
import Tabs from '@/components/Tabs.vue'
export default {
name: 'TimespanPicker',
components: { Tabs },
emits: ['update:modelValue', 'change'],
props: ['value', 'modelValue', 'placeholder'],
data() {
const initalValue = (this.valuePropPassed() ? this.value : this.modelValue?.value) || ''
let [span, interval, intervalType] = initalValue.split(' ')
if (span == 'Current') intervalType = interval // eg. Current Day
if (intervalType?.at(-1) == 's') intervalType = intervalType.slice(0, -1) // eg. Days
return {
span: span || 'Last',
interval: interval || '1',
intervalType: intervalType || 'Day',
}
},
computed: {
_value() {
return this.span === 'Current'
? `${this.span} ${this.intervalType}`
: `${this.span} ${this.interval} ${this.intervalType}`
},
},
watch: {
interval(new_val) {
if (new_val < 1) {
this.interval = 1
}
},
},
methods: {
valuePropPassed() {
return this.value !== undefined
},
apply() {
if (this.valuePropPassed()) {
this.$emit('change', this._value)
} else {
this.$emit('update:modelValue', {
value: this._value,
label: this._value,
})
this.$emit('change', {
value: this._value,
label: this._value,
})
}
},
},
}
</script>
|
2302_79757062/insights
|
frontend/src/components/Controls/TimespanPickerFlat.vue
|
Vue
|
agpl-3.0
| 1,864
|
<script setup>
import { GripVertical, X } from 'lucide-vue-next'
import { computed } from 'vue'
import Draggable from 'vuedraggable'
const emit = defineEmits(['update:items', 'sort'])
const props = defineProps({
items: { type: Array, required: true },
group: { type: String, required: true },
itemKey: { type: String, default: 'value' },
emptyText: { type: String, default: 'No items' },
showEmptyState: { type: Boolean, default: true },
showHandle: { type: Boolean, default: true },
})
const items = computed({
get: () => props.items,
set: (value) => emit('update:items', value || []),
})
function onChange(e) {
if (e.moved) {
emit('sort', { oldIndex: e.moved.oldIndex, newIndex: e.moved.newIndex })
items.value.splice(e.moved.newIndex, 0, items.value.splice(e.moved.oldIndex, 1)[0])
}
if (e.added) {
items.value.splice(e.added.newIndex, 0, e.added.element)
}
if (e.removed) {
items.value.splice(e.removed.oldIndex, 1)
}
}
</script>
<template>
<Draggable
class="w-full"
:model-value="items"
:group="props.group"
:item-key="itemKey"
@change="onChange"
>
<template #item="{ element: item, index: idx }">
<div class="mb-2 flex items-center gap-1 last:mb-0">
<GripVertical
v-if="props.showHandle"
class="h-4 w-4 flex-shrink-0 cursor-grab text-gray-500"
/>
<div class="flex flex-1 flex-col justify-center">
<slot name="item" :item="item" :index="idx">
<div
class="group form-input flex h-7 flex-1 cursor-pointer items-center justify-between px-2"
>
<div class="flex items-center space-x-2">
<div>{{ typeof item === 'object' ? item[itemKey] : item }}</div>
</div>
<div class="flex items-center space-x-2">
<X
@click.prevent.stop="items.splice(idx, 1)"
class="invisible h-4 w-4 text-gray-600 transition-all hover:text-gray-800 group-hover:visible"
/>
</div>
</div>
</slot>
</div>
<slot name="item-suffix" :item="item" :index="idx" />
</div>
</template>
<template v-if="showEmptyState && !items?.length">
<div
class="flex h-16 items-center justify-center rounded border border-dashed text-sm text-gray-600"
>
{{ props.emptyText }}
</div>
</template>
</Draggable>
</template>
|
2302_79757062/insights
|
frontend/src/components/DraggableList.vue
|
Vue
|
agpl-3.0
| 2,272
|
<script setup></script>
<template>
<Popover placement="bottom-start">
<template #target="{ togglePopover }">
<Button icon="more-horizontal" @click="togglePopover"></Button>
</template>
<template #body="{ togglePopover }">
<div
class="relative mt-1 max-h-[26rem] w-[16rem] overflow-y-auto rounded-lg bg-white p-3 text-base shadow-2xl"
>
<slot v-bind="{ togglePopover }"></slot>
</div>
</template>
</Popover>
</template>
|
2302_79757062/insights
|
frontend/src/components/DraggableListItemMenu.vue
|
Vue
|
agpl-3.0
| 450
|
<script setup>
defineProps({ info: Object })
</script>
<template>
<div class="ml-auto w-[20rem] rounded border bg-white p-2 shadow-lg">
<p>{{ info?.description }}</p>
<div class="mt-2 rounded bg-gray-50 p-2 text-xs leading-5">
<code>
<span class="text-gray-600"># Syntax</span>
<br />
{{ info?.syntax }}
<br />
<br />
<span class="text-gray-600"># Example</span>
<br />
{{ info?.example }}
</code>
</div>
</div>
</template>
|
2302_79757062/insights
|
frontend/src/components/ExpressionHelp.vue
|
Vue
|
agpl-3.0
| 471
|
<template>
<div class="relative flex flex-1 overflow-hidden rounded py-3">
<div
v-if="props.rows.length == 0"
class="absolute top-0 flex h-full w-full items-center justify-center text-lg font-light text-gray-600"
>
<span>No Data</span>
</div>
<div class="flex flex-1 flex-col overflow-auto text-base">
<table>
<thead class="sticky top-0" v-if="props.header">
<tr>
<slot name="header">
<td
v-for="head in props.header"
class="whitespace-nowrap bg-gray-100 px-2.5 py-1.5 font-medium text-gray-600 first:rounded-l-md last:rounded-r-md"
scope="col"
>
{{ head }}
</td>
</slot>
</tr>
</thead>
<tbody>
<tr v-for="(row, index) in props.rows" class="border-b">
<td v-for="cell in row" class="whitespace-nowrap bg-white px-2.5 py-2">
{{ ellipsis(cell, 100) }}
</td>
</tr>
</tbody>
</table>
</div>
</div>
</template>
<script setup>
import { ellipsis } from '@/utils'
const props = defineProps(['header', 'rows'])
</script>
|
2302_79757062/insights
|
frontend/src/components/Grid.vue
|
Vue
|
agpl-3.0
| 1,061
|
<script setup>
import { computed, ref, inject } from 'vue'
import { TextEditor, call } from 'frappe-ui'
const props = defineProps({ modelValue: Boolean })
const emit = defineEmits(['update:modelValue'])
const show = computed({
get: () => props.modelValue,
set: (value) => emit('update:modelValue', value),
})
const content = ref('')
const isCritical = ref(false)
const dialogOptions = { title: 'Contact the Team', size: '2xl' }
const selectedTabIndex = ref(0)
const tabs = [
{
label: 'Question',
description: 'How do I...',
iconName: 'help-circle',
placeholder: 'I am not sure how to...',
},
{
label: 'Feedback',
description: 'What if there was...',
iconName: 'rss',
placeholder: 'I think it would be great if...',
},
{
label: 'Bug Report',
description: 'When I try to...',
iconName: 'alert-triangle',
placeholder: 'I found a bug, when I try to...',
},
]
function close() {
show.value = false
selectedTabIndex.value = 0
content.value = ''
isCritical.value = false
}
const $notify = inject('$notify')
const sending = ref(false)
async function submit() {
sending.value = true
await call('insights.api.contact_team', {
message_type: tabs[selectedTabIndex.value].label,
message_content: content.value,
is_critical: isCritical.value,
})
sending.value = false
close()
$notify({
title: 'Message Sent',
message: 'Your message has been sent to the team.',
variant: 'success',
})
}
</script>
<template>
<Dialog :options="dialogOptions" v-model="show" :dismissable="true" @onClose="close">
<template #body-content>
<div class="flex w-full flex-col space-y-4 text-base">
<div
class="flex w-full cursor-pointer items-center space-x-2 rounded bg-gray-100 p-1.5"
>
<div
v-for="(tab, index) in tabs"
class="flex h-full flex-1 items-center justify-between bg-transparent px-3 py-1.5 transition-all"
:class="[selectedTabIndex === index ? 'rounded bg-white shadow' : '']"
@click="selectedTabIndex = index"
>
<div class="flex flex-col">
<p>{{ tab.label }}</p>
<p class="text-xs text-gray-600">{{ tab.description }}</p>
</div>
<FeatherIcon :name="tab.iconName" class="h-5 w-5 text-gray-500" />
</div>
</div>
<div class="flex h-[20rem] flex-col rounded border px-4 py-2 shadow">
<TextEditor
:key="selectedTabIndex"
editor-class="flex flex-1 prose-sm flex flex-col justify-end"
:placeholder="tabs[selectedTabIndex].placeholder"
:content="content"
:editable="true"
@change="content = $event"
/>
</div>
<span class="!mt-2 text-sm text-gray-600">
You can use markdown syntax to format your message. You can also drag and drop
images to upload them.
</span>
<div class="mt-2 flex items-center justify-between">
<Input
v-show="selectedTabIndex == 2"
label="I am not able to use the app because of this bug"
type="checkbox"
v-model="isCritical"
/>
<Button
variant="solid"
:loading="sending"
:label="selectedTabIndex === 2 ? 'Report Bug' : 'Send'"
@click="submit"
/>
</div>
</div>
</template>
</Dialog>
</template>
|
2302_79757062/insights
|
frontend/src/components/HelpDialog.vue
|
Vue
|
agpl-3.0
| 3,193
|
<template>
<svg
width="512"
height="512"
viewBox="0 0 512 512"
fill="none"
xmlns="http://www.w3.org/2000/svg"
xmlns:xlink="http://www.w3.org/1999/xlink"
>
<path d="M0 0H512V512H0V0Z" fill="url(#pattern0)" />
<defs>
<pattern id="pattern0" patternContentUnits="objectBoundingBox" width="1" height="1">
<use xlink:href="#image0_2_4" transform="scale(0.00195312)" />
</pattern>
<image
id="image0_2_4"
width="512"
height="512"
xlink:href="data:image/png;base64,iVBORw0KGgoAAAANSUhEUgAAAgAAAAIACAMAAADDpiTIAAAAA3NCSVQICAjb4U/gAAAACXBIWXMAABWQAAAVkAGpSVgPAAAAGXRFWHRTb2Z0d2FyZQB3d3cuaW5rc2NhcGUub3Jnm+48GgAAAwBQTFRF////AAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAACyO34QAAAP90Uk5TAAECAwQFBgcICQoLDA0ODxAREhMUFRYXGBkaGxwdHh8gISIjJCUmJygpKissLS4vMDEyMzQ1Njc4OTo7PD0+P0BBQkNERUZHSElKS0xNTk9QUVJTVFVWV1hZWltcXV5fYGFiY2RlZmdoaWprbG1ub3BxcnN0dXZ3eHl6e3x9fn+AgYKDhIWGh4iJiouMjY6PkJGSk5SVlpeYmZqbnJ2en6ChoqOkpaanqKmqq6ytrq+wsbKztLW2t7i5uru8vb6/wMHCw8TFxsfIycrLzM3Oz9DR0tPU1dbX2Nna29zd3t/g4eLj5OXm5+jp6uvs7e7v8PHy8/T19vf4+fr7/P3+6wjZNQAAFktJREFUeNrtnXmAVvP6wL/vLE2ZmiajxdKUFGUYTZao5lYKSb+roqRLkqXCRbuM23bxk1+4RLQg95JS1KVGCpFKki0xSpY2LdJU0zZjZt7fH9xrZr5n+Z7tfU/nfD5/ct7nPPM8n973PGf5HiEAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAMBjkjMv7N7x9JoUIozU+csrO8qj0Wg0Gt2/YmRzChIuei77NVqJjWNqUZXQkPthVGb3X5OpTCio+++oNt9dTHFCwNk/RvX4dSDlCTx/Looa8HgiFQo2fymLGjI7Qo2CTOsjURMmUKQAc8qOqCl9KVNgSfzYvP/RI9kUKqgMiKqwhEIFlBpblQSIdqZUwWSUWv+jnzAJBJJqexUFiF5BsYLIZar9jz5LsYLI08oC7EqgWsEj8pOyANGLKFfwyFHvf3Q85Qoe3S0I8E/KFTwGWxDgHcoVPCZYEKCAcgWP6RYEOEC5gsezCBBuHuInINwMsyDA25QrePRhDAw3jSwIMJZyBZCt6gK0ploB5CXl/u/ghoAg0kZZgGkUK5C8rSpAF2oVSNor9n8NpQooy9UE6EClAkpnpf7nU6jA8rVC/w9nUaegcnG5ef/Le1GnoJKucipoHHUKLLMU+s/j4cFF5WrQoywQEVhOKTRtf/FNlCmwRMzPAxa0o0zB5W6z9m+/ha//AJNlsjbMlyOPo0gBptpn8g/+y6t+XzBm3wfDm1KiYKNxR+hIIUSNFpe1bVKD8gSeXHlxuPd5Ajg8pP0g9X9/I8oSHmbKPwD9qEp46Cn3fy5VCQ8N9sgz//GUJTzky5d8L6Mq4eE2+QdgMlUJD2ccks/5M/mHh6Q1Uv9LzqUs4UFjXZA8qhIeLiyV+r+Si37hIfVbqf9FTShLeJgq/wBw00+I6Cb3fwFVCQ91d0n931mXsoQHjRdEdqMq4eFmuf9TqUp4OE1+Q+S3qZQlNCSulPpfytI/ISKPReBDzbkl8sIfSZQlNNQokPp/6HTK4sW/tOGPzX7/m7VvTBvfp7aP0pos/wAMplluE7l48paKl1kXD6rvk8wuk1eCWES/XK/y5/LyKg+l+yGz47dLmf3cgIa5/N3/juYzdr8MS4l/bnPlvHrQMXcZWqr3mOXHJ8c7t+vlpJ6jY66SMtNopd0L45tco/1SSt/Xomeu/sauMnzU+mifeCaX8J6UUBkrP7hK0jsmay2U/CmO2Y2Q83mQnnk9ZFc95m4ct+Syi6VsPk2mZ25yi8JqW1/E67pbypdSLkfOpGducvJhlQV3H45Tdo/IqdxJz1xF7f17RzLjklxH+RTgEpZ+dJWzytTWXH8hHsmlb5Hy2HsyPXOVNxTfulB2dhyS03gtUG9a5ir1FL8A4nIUcI2cxYu0zF1uVn7z0obYH57ulZLYXJuWuctC9ZfvnRHj1CJL5ZUgOtAxd6l5VF2AETHO7S45hUl0zGUusPD+1VmxTe1MeTHYdSl0zGX+bEGA92OaWfKn8kWpbBrmNgMtCLApppn9r5zAcPrlOuMsCHA4lom1k8fTZSwG6z7/sCBAtHrs8qr1vbT3fZm0y32GWuj/vhjm9Zy8++voVpwPAtfFLq0e8t7n0CwvyLIgwMKYZdXgZ2nn21gM1hNqlKsLMCVmWS2STwFeQq+8YZu6AC/E6kL8YHnfj9MpbzjrZwu/AYtj86TY6fJisF9Xp1WecO1BK2NgdFeXGOSU9JF8V3IrWuUFyU9ELVL+aLV4nJsaTa+84OSVUet86vVF4dbyM2orOAXoBR12Re1w0NulOVM3Sns8cCrN8oCRpVGbvJLuYVrPyPu7kWa5T9prUfts9u7RvCvkvb1Gt9wna0PUCaVjPVqive5O+dnkE2hXvKc/DT7w5tLcAnlPXWlX/Kc/DQp7eZDZAHk/Tyt9MDHrursrM6hdTTrt4vSnwQzX38/eRF4MdoPKTmpNO6T1JMvqc2i2e9OfBt/kuJuZxmKwv16g8LncH3QSLB7NY4QSIyxPf2/u1Ps/xUNcLfC98h7GKnws84B+7oNouOr0N7XR/xVp/fetPUS9fH056rmXWyt5MdjVKovBLjWQt6gxPVea/o70F0JkTCiU2p9XSwgRGVKsV+Gdrr20tcbX8knHZgqf62b49cWjhErT33ctf/+CuPe7ivcAvnHVf/4FtvxG9/LQIy5dHtIYTQaqfO5BQwG+p+sK09/COn9sdVKvh55dsDx/5sO3nVPxEsxx0z2+PHRpuc1b0JYaH8Fk0Pj/dFZv+iu7T+lQrleh7uWhAc6z01gMdrfa7ScmtzSxoJzZ9LfnUsUImR/oVnlOutP0XpGDXqn2yZ3GAnSg9cbT3xr1c7qJY3VHyB/bOkvvOo3zTAIB3Jv+XtWd/iw9b9tuszeXhzL3ycelNRHA++nvcH+LkdJf0a30cvuXhxKWyUK1EQgQs+nPCjfpXkgsvNpugsPlYPcLBPB8+nvD1qHbGZ/qFnu6vctD2fIqJWuTEcAn059MtUd1nyYqsPGVIlLWyT9NzQUC+GX606CL7gXFo3dbt2qSHOYOgQD+mf40qP+mbsHzrV4e6iB/n7wVQQCPp79nHK62FBnq1uWh2vJk+ctJAgG8nf5ucB48R//y0CQrl4f+JQewNk0gQEymP5nUGbpF/0T9nZ695U//UyCAD6c/reY5vzyksRjsj2kI4On0l+febVyNVujWfbbSmr6RJXJ+7QUCeDj9/ezqShuJ4/QvD6mcy73ThTXJESB2058GufqXh8aYXh5qIS8G+3k1BPBy+nP/6f70ufqXhxqaHKZ8Ip9IOksggK+nPw1uPqRX/L1XGX5Q426+oQIBPJv+Nnn1oEzzz3TLP63K5aHGfYdOnDn7iftuzkkQbeXFYN+JIIDT6e9xvUq8nu7ZTlMe07889Id1ka5TK9xzvD9fPnoobCgQ4BiY/jS4XP/y0F2/7Ti5/1emzyD1FQjgcPrbGZPpT4P6i3VbsKieEOLyzebPoL0sEMCj6e+jhp7vOzJM9/LQjkvTZig8g7i1DgJ4NP09XS0W+2+lu+pI+W6VFeg6CQTwZvrrF6MMUp9z8rD5YwIBjq3pT4Nr9tnu//rqCHCsTX8aNLK7+khxS4EAXkx/98Z4jYzE8faWHxwlEMDaQXeK0vTX2WL70itj5zbv3C02+r88AQGUOXfc3FWbS6K/fLFo6q0nuDj9nfPYCums/qbZAy0/8lVnnnUBHKwGHTIBcqdUehz617dubOTO9Jc0pkQ7ysdnWk7ylkNWBdiShAAqZL+pXlNr01/kLd1AR9tYzrP551YN6I0A5jSYWaZe0U3WXrN6h0GojTUsp5ryD4sCrEQAU8638Hqf6L9rW4rd0HDt2Ik2su2625oB5yOACX2PqFfT8vQ3wDDcRlvfV29ZEuB5BDAmz0IxrU5/QjxtfJre1smkyPBiCzl/jgDGZ3ot1HK19Wt/a4wjXmxzYLWwKm0RAhhx3mH1Uk6xce3vG+OQ3W2m/aUFbesjgD711Y//Dl9vZwceCWDlpYRtEUCfGcpl/DZb+EeAZAvvpY32QwBdsko9mv48FuBEK2PAGATQ5Q3FGpbaXh/fGwFSrQgwBAH0uEj5mprtXXh0DHAgBieDQyDAZNUaltbzmQBW3k3WDgH0UL/APthnArxnQYBTEUDvdIp6EZf5TIDJ6qkXJiGADhMsXAOo4y8BOqunPoszgXpYucGmlb8ESCpUzrwPAuixyoIA/+MvAbTWANOmpDYC6LHZggCDfCbApaqJ239DdOAFiJRYEODvPhNAvKs4wJ6JADoc/2gsnq/yTIDz1C4HTBMIoH0yNc/aw1Yj/SaAeFkl7UMnIoAWybftsHhv5XW+E+CknxTSHigQQOPH/9pNlh+w6Og7AUTro6ZZTxYIINPlMxuPWDXznwDierOklyYhgPzvZpmdRyy3CR8KYHY/65p0gQBVaPGavYesp/hSANHb6FGxWdUFAlSm4bP2HrGORrv4UwDRSveCZnme02oFToCMSUdstj9alOJTAcQJT2qfzvrYeX8CJoDVwb8SDwu/CiBE0znyKaFNvV1YvsKmADW6jX5y/poNK+dPHZkT8U37rQ/+Fdlbx8cCCJH9QKWlIvfN6pXsRlg7AmQMWFDxsGTXvzr7ov12Bv+KjBC+FkAIcfrw6Qs/+amw4N2XJl6a7FJM6wLUHFskbfbJNYlx77+twb8CP1T3vQBeYFWApNu0P/Fly/j+HRcuc9b+6KEcgQDmAmTo3qdYPCohfn+F6eBvelGtvKdAAHMBmhv9yi5N9evg/8vwU82esxwtEMBcgI7GM9byWr4c/A89UFuIOoZ3hpU7639YBDhzv8k/o1VpMc8/Nc8kqZIpDX7bcLGBIj0FApgLkPGd6ZHUPL8N/uUvn/bfbe/RO6X+Q45AAHMBklWeUxkUy9zNB//FlVqbqXmouHdEdYEACgKMUBmmjpwVu9RNB//V0hDbZWnVw8Wih+u4kEoYBDhe7SGFt2M2+Jt9IX3dQ+tj9Qa//8dqgdumdElxJZkwCPCIx0+pWhz855uksXWA7rnJ2tldb53w2MjrOjZzLZ0QCJB5VFGAWHwFNHzObPAfVj2mVQyBAPcon1PNdiWvpNM6t2+u/fOc8YiJjAfvrx3jKoZAAPUn7O5zmlJKv2eWfv/bP/HiVXlVrzan3mc2+D/VIOZVDL4A9dXXWV7tLKETJ1RZJXf76AonGJNvN0m4fNZpcahi8AW4Sf2yWll9B+m0elHj3qe9Y37/So/0NTsX9WbLuFQx+AJMsXBhtXj9vAeuP9/WdYFROgd329oLIcTl1gd/BHBJgAXWL7Bvf+epv17S0Mr9YrVe1X/8dVyizcEfAVwR4GO791kc/HTWmN7ZSkNZ8wLDG3ZMdrRlQBxvSgq+AD9FHVH2ff6jt7Y3Pjhod8DBDvbEePAPnQDFUTco/PD5UVeeof0oW93t9uPGfvAPnQDbou5RUrDgof4XplfOI/Km/XhxGPxDJ8BHUdfZ+d4zd3dpnGD5TKMvBv/QCTA/6hGHv5gz/tqc49r+avPzcRr8QyfAk1FPKbd5jPFhe39UMfgC9Iv6kK99U9jgC5BR6rv2b7kxUSBArAQQ7/us/XuGpvioiiEQYJiv2n/w72m+qmIIBDjxkH/aX/JkfZ9VMQz3BN7vl/aXv9TEd1UMgwBpam8zXnzfi2uLvOx/voPBv2buXdNmVmbiNc0ix4IAaR2GTq+S+oNXN4mlAIZvSP8vP9YRQoiTO93+xJIt5V70f7+Dv/Um7ctNyxr5XoDIndqvPl10YgwFSFik8OvcukLo1Jxrx8/5/LDLBtheFbHmQr2QB67xuQAZuouG/9ItdgKItK9MuzNcQ97GXe56etkO1wSw/WavZ/RjHmnhbwFm64c+kBk7AUSTPSbNWaj/c1r7gn4PvvqVC1eVM2z+oZcYBf0o0c8CXG0Ue2kMBRAXGG89t6bZ3hKbdRs+Y8XPDvpfbPeQbblh2K5+FmCdYfA2MRRAZBrcllmqvspWRtubHn59o62zy5tt/p2JxucxxvlYgFTjQt0dSwFEqu59m7svtrrrai16jH5htcWFHe0+dXC2cdhFPhYg1zj4SzEVQIie2u8zXdzQbgYNOtxuYWCcY3MvVxqHLfCxADeYXBKPsQAiaaB0SH94apajJCzcb3SDzV10Nw77jY8F6O/Nd6JtAYRIuWL6roo/y6OOd3gk+jfl/pdmIED8BRBCJLQdNH7a68ue/1vf1nWdn47MURbA9tt9EcBdAVxmnaoAdyBAIAXopdj/bTUQIJACRNarCTBAIEAgBRA9lfq/PhEBAiqAmKnQ/zIH7yVAAJ8LkLrBXIBRAgECK4BoaXof0YsCAQIsgLjIZPGn1dURINACiPP3GmUyz9nbCBDA/wKILP3zQeVjHd66iQDHgAAiZZLOdcGt3Z2GRoBjQQAhcrVWgioc6Xz9FwQ4NgQQovWrVdak/O4BNxZ0R4BjRQAhMnpP/+H33RetHXO2O0ER4NgRQAghUk5p1eVPzWq6FxABji0BXAcBEAABEAABEAABEAABEAABEAABEAABEAABEAABEAABEAABEAABEAABEAABEAABEAABEAABEAABEAABEAABEAABEAABEAABEAABEAABEAABEAABEAABEAABEAABEAABEAABEAABEAABEAABEAABEAABEAABEAABEAABEAABEAABEAABEAABEAABEAABEAABEAABEAABEAABEAABEAABEAABEAABEAABEOBYEOCkbveMq8wdbVPdalTKebdWCZ7XszEC+EiAtpp/bNkrJ7jR/tSnSrSib7sSAXwiQMLEMp0td17uvP/nf6uXx/PHIYAvBBimv+nhZk77n2GQzGQE8IMAZxwx2HZFgsMmvWwQvLwDAvhAgDmGG/dwlkqOYfCPEMAHAmw23Hiis1QGGwYvSUGAuAtQz3jjd52l8pxx9AsQIO4C5BpvvN1ZKiuNo1+PAHEXoIPxxjudpbLaOHp/BEAABEAABEAABEAABEAABEAABEAABEAABEAABEAABEAABEAABEAABEAABEAABEAABEAABEAABEAABEAABEAABEAABEAABEAABEAABEAABEAABEAABEAABEAABEAABEAABEAABEAABEAABEAABEAABEAABEAABEAABEAABEAABEAABEAABEAABEAABEAABEAABEAABEAABEAABEAABEAABEAABEAABEAABEAABEAABEAABEAABEAABEAABEAABEAABEAABEAABEAABEAABEAABEAABEAABEAABEAABEAABEAABEAABEAABEAABEAABEAABEAABEAABEAABEAABEAABEAABEAABEAABEAABEAABEAABEAABEAABEAABEAABEAABEAABEAABEAABEAABEAABEAABEAABEAABEAABEAABEAABEAABEAABEAABEAABEAABEAAqwK0Md54i7NUlhtH7+soeFfj4Oucpb7OOHpXR8H7Ggdf7iz1LcbR21TauHa54cb5zlKZYpxKtqPgmcbBZzlLfZZx9ExHwbONg09xlnq+YfDy2pW33mC49XhnqdxoGPxQorPouwyjD3EWfIhh8F3OgiceMox+o7Po4w2Db6iy9XTDrTs5S6VZmVHwpc6Ci7mGqZ/rLPi5hsHnOkx9qVHwsmbOgncyTH16la3r7zHYeJ7Dv1NMMgh+NMth8MZFBtFnOE19hkHwosYOg2cdNYg+yWnq8wyC76lfdes++hvvrus0leoF+tHvcRpcDDI4ek1zGjzN4FhqkOPU79EPXlDdafC6u/Wj99GYSfbpbLs2y/HfKRou0fv3PyLBefTbD+pEX9HUefCmK3SCH7zdefCEEXrfAUsaOo+etVYn+D7NyfuUORo/A+Ub85KEGwxcr3EgsD+/hSvBm8wv1Ei9YEiCG8EThhRozEiF85u4knqL/P0aP//rB7oSPClvo0bqe+acoveBU7v3qUyndOEaqblVgl/VPOJa8EjTnlWid0hzL/W0DlWC92zqYurNr6oSPTfVvdTTO1UJ3v1UAQAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAD+4f8B5ag1RaLG5XAAAAAASUVORK5CYII="
/>
</defs>
</svg>
</template>
|
2302_79757062/insights
|
frontend/src/components/Icons/ComboChartIcon.vue
|
Vue
|
agpl-3.0
| 9,721
|
<template>
<svg
xmlns="http://www.w3.org/2000/svg"
viewBox="0 0 24 24"
fill="none"
stroke="currentColor"
stroke-width="2"
stroke-linecap="round"
stroke-linejoin="round"
>
<circle cx="12" cy="9" r="1"></circle>
<circle cx="19" cy="9" r="1"></circle>
<circle cx="5" cy="9" r="1"></circle>
<circle cx="12" cy="15" r="1"></circle>
<circle cx="19" cy="15" r="1"></circle>
<circle cx="5" cy="15" r="1"></circle>
</svg>
</template>
<script>
export default {
name: 'DragHandleIcon',
}
</script>
|
2302_79757062/insights
|
frontend/src/components/Icons/DragHandleIcon.vue
|
Vue
|
agpl-3.0
| 517
|
<template>
<svg
xmlns="http://www.w3.org/2000/svg"
width="800px"
height="800px"
viewBox="0 0 24 24"
fill="none"
>
<g id="Navigation / House_01">
<path
id="Vector"
d="M20 17.0002V11.4522C20 10.9179 19.9995 10.6506 19.9346 10.4019C19.877 10.1816 19.7825 9.97307 19.6546 9.78464C19.5102 9.57201 19.3096 9.39569 18.9074 9.04383L14.1074 4.84383C13.3608 4.19054 12.9875 3.86406 12.5674 3.73982C12.1972 3.63035 11.8026 3.63035 11.4324 3.73982C11.0126 3.86397 10.6398 4.19014 9.89436 4.84244L5.09277 9.04383C4.69064 9.39569 4.49004 9.57201 4.3457 9.78464C4.21779 9.97307 4.12255 10.1816 4.06497 10.4019C4 10.6506 4 10.9179 4 11.4522V17.0002C4 17.932 4 18.3978 4.15224 18.7654C4.35523 19.2554 4.74432 19.6452 5.23438 19.8482C5.60192 20.0005 6.06786 20.0005 6.99974 20.0005C7.93163 20.0005 8.39808 20.0005 8.76562 19.8482C9.25568 19.6452 9.64467 19.2555 9.84766 18.7654C9.9999 18.3979 10 17.932 10 17.0001V16.0001C10 14.8955 10.8954 14.0001 12 14.0001C13.1046 14.0001 14 14.8955 14 16.0001V17.0001C14 17.932 14 18.3979 14.1522 18.7654C14.3552 19.2555 14.7443 19.6452 15.2344 19.8482C15.6019 20.0005 16.0679 20.0005 16.9997 20.0005C17.9316 20.0005 18.3981 20.0005 18.7656 19.8482C19.2557 19.6452 19.6447 19.2554 19.8477 18.7654C19.9999 18.3978 20 17.932 20 17.0002Z"
stroke="currentColor"
stroke-width="1.5"
stroke-linecap="round"
stroke-linejoin="round"
/>
</g>
</svg>
</template>
|
2302_79757062/insights
|
frontend/src/components/Icons/HomeIcon.vue
|
Vue
|
agpl-3.0
| 1,418
|
<template>
<svg xmlns="http://www.w3.org/2000/svg" width="16" height="16" viewBox="0 0 16 16" fill="none">
<rect width="16" height="16" rx="4.5" class="currentColor fill-current" />
<circle cx="8" cy="8" r="3" fill="white" />
</svg>
</template>
|
2302_79757062/insights
|
frontend/src/components/Icons/IndicatorIcon.vue
|
Vue
|
agpl-3.0
| 251
|
<template>
<svg xmlns="http://www.w3.org/2000/svg" height="20" width="20">
<path
strokeWidth="1"
fill="currentColor"
d="M13.333 15.833Q12.812 15.833 12.406 15.75Q12 15.667 11.667 15.5Q12.667 14.708 13.229 13.25Q13.792 11.792 13.792 10Q13.792 8.208 13.229 6.75Q12.667 5.292 11.667 4.5Q12 4.333 12.406 4.25Q12.812 4.167 13.333 4.167Q15.771 4.167 17.469 5.865Q19.167 7.562 19.167 10Q19.167 12.438 17.469 14.135Q15.771 15.833 13.333 15.833ZM10 14.792Q8.958 14.792 8.25 13.406Q7.542 12.021 7.542 10Q7.542 7.979 8.25 6.594Q8.958 5.208 10 5.208Q11.042 5.208 11.75 6.594Q12.458 7.979 12.458 10Q12.458 12.021 11.75 13.406Q11.042 14.792 10 14.792ZM6.667 15.833Q4.229 15.833 2.531 14.135Q0.833 12.438 0.833 10Q0.833 7.562 2.531 5.865Q4.229 4.167 6.667 4.167Q7.188 4.167 7.594 4.25Q8 4.333 8.333 4.5Q7.333 5.292 6.771 6.75Q6.208 8.208 6.208 10Q6.208 11.792 6.771 13.25Q7.333 14.708 8.333 15.5Q8 15.667 7.594 15.75Q7.188 15.833 6.667 15.833Z"
/>
</svg>
</template>
|
2302_79757062/insights
|
frontend/src/components/Icons/JoinFullIcon.vue
|
Vue
|
agpl-3.0
| 967
|
<template>
<svg width="16" height="17" viewBox="0 0 16 17" fill="none" xmlns="http://www.w3.org/2000/svg">
<path
d="M2 4.5H14"
stroke="currentColor"
stroke-miterlimit="10"
stroke-linecap="round"
stroke-linejoin="round"
/>
<path
d="M4 8.5H12"
stroke="currentColor"
stroke-miterlimit="10"
stroke-linecap="round"
stroke-linejoin="round"
/>
<path
d="M6.5 12.5H9.5"
stroke="currentColor"
stroke-miterlimit="10"
stroke-linecap="round"
stroke-linejoin="round"
/>
</svg>
</template>
|
2302_79757062/insights
|
frontend/src/components/ListFilter/FilterIcon.vue
|
Vue
|
agpl-3.0
| 534
|
<template>
<NestedPopover>
<template #target>
<Button label="Filter">
<template #prefix><FilterIcon class="h-4" /></template>
<template v-if="filters.length" #suffix>
<div
class="flex h-5 w-5 items-center justify-center rounded bg-gray-900 pt-[1px] text-xs font-medium text-white"
>
{{ filters.length }}
</div>
</template>
</Button>
</template>
<template #body="{ close }">
<div class="my-2 rounded-lg border border-gray-100 bg-white shadow-xl">
<div class="min-w-[400px] p-2">
<div
v-if="filters.length"
v-for="(filter, i) in filters"
:key="i"
id="filter-list"
class="mb-3 flex items-center justify-between gap-2"
>
<div class="flex flex-1 items-center gap-2">
<div class="w-13 flex-shrink-0 pl-2 text-end text-base text-gray-600">
{{ i == 0 ? 'Where' : 'And' }}
</div>
<div id="fieldname" class="!min-w-[140px] flex-1">
<Autocomplete
:modelValue="filter.fieldname"
:options="fields"
@update:modelValue="filter.fieldname = $event.value"
placeholder="Filter by..."
/>
</div>
<div id="operator" class="!min-w-[140px] flex-shrink-0">
<FormControl
type="select"
:modelValue="filter.operator"
@update:modelValue="filter.operator = $event"
:options="getOperators(filter.field.fieldtype)"
placeholder="Operator"
/>
</div>
<div id="value" class="!min-w-[140px] flex-1">
<SearchComplete
v-if="
typeLink.includes(filter.field.fieldtype) &&
['=', '!='].includes(filter.operator)
"
:doctype="filter.field.options"
:modelValue="filter.value"
@update:modelValue="filter.value = $event"
placeholder="Value"
/>
<component
v-else
:is="
getValueSelector(
filter.field.fieldtype,
filter.field.options
)
"
v-model="filter.value"
placeholder="Value"
/>
</div>
</div>
<div class="flex-shrink-0">
<Button variant="ghost" icon="x" @click="removeFilter(i)" />
</div>
</div>
<div v-else class="mb-3 flex h-7 items-center px-3 text-sm text-gray-600">
Empty - Choose a field to filter by
</div>
<div class="flex items-center justify-between gap-2">
<Autocomplete
:modelValue="''"
:options="fields"
@update:modelValue="(field) => addFilter(field.value)"
placeholder="Filter by..."
>
<template #target="{ togglePopover }">
<Button
class="!text-gray-600"
variant="ghost"
@click="togglePopover()"
label="Add filter"
>
<template #prefix>
<FeatherIcon name="plus" class="h-4" />
</template>
</Button>
</template>
</Autocomplete>
<Button
v-if="filters.length"
class="!text-gray-600"
variant="ghost"
label="Clear all filter"
@click="filters = []"
/>
</div>
</div>
</div>
</template>
</NestedPopover>
</template>
<script setup>
import { Autocomplete, FeatherIcon, FormControl } from 'frappe-ui'
import { computed, h, ref, watch } from 'vue'
import FilterIcon from './FilterIcon.vue'
import NestedPopover from './NestedPopover.vue'
import SearchComplete from './SearchComplete.vue'
const typeCheck = ['Check']
const typeLink = ['Link']
const typeNumber = ['Float', 'Int']
const typeSelect = ['Select']
const typeString = ['Data', 'Long Text', 'Small Text', 'Text Editor', 'Text', 'JSON', 'Code']
const emits = defineEmits(['update:modelValue'])
const props = defineProps({
modelValue: {
type: Object,
default: () => ({}),
},
docfields: {
type: Array,
default: () => [],
},
})
const fields = computed(() => {
const fields = props.docfields
.filter((field) => {
return (
!field.is_virtual &&
(typeCheck.includes(field.fieldtype) ||
typeLink.includes(field.fieldtype) ||
typeNumber.includes(field.fieldtype) ||
typeSelect.includes(field.fieldtype) ||
typeString.includes(field.fieldtype))
)
})
.map((field) => {
return {
label: field.label,
value: field.fieldname,
description: field.fieldtype,
...field,
}
})
return fields
})
const filters = ref(makeFiltersList(props.modelValue))
watch(filters, (value) => emits('update:modelValue', makeFiltersDict(value)), { deep: true })
watch(
() => props.modelValue,
(value) => {
const newFilters = makeFiltersList(value)
if (JSON.stringify(filters.value) !== JSON.stringify(newFilters)) {
filters.value = newFilters
}
},
{ deep: true }
)
function makeFiltersList(filtersDict) {
return Object.entries(filtersDict).map(([fieldname, [operator, value]]) => {
const field = getField(fieldname)
return {
fieldname,
operator,
value,
field,
}
})
}
function getField(fieldname) {
return fields.value.find((f) => f.fieldname === fieldname)
}
function makeFiltersDict(filtersList) {
return filtersList.reduce((acc, filter) => {
const { fieldname, operator, value } = filter
acc[fieldname] = [operator, value]
return acc
}, {})
}
function getOperators(fieldtype) {
let options = []
if (typeString.includes(fieldtype) || typeLink.includes(fieldtype)) {
options.push(
...[
{ label: 'Equals', value: '=' },
{ label: 'Not Equals', value: '!=' },
{ label: 'Like', value: 'like' },
{ label: 'Not Like', value: 'not like' },
]
)
}
if (typeNumber.includes(fieldtype)) {
options.push(
...[
{ label: '<', value: '<' },
{ label: '>', value: '>' },
{ label: '<=', value: '<=' },
{ label: '>=', value: '>=' },
{ label: 'Equals', value: '=' },
{ label: 'Not Equals', value: '!=' },
]
)
}
if (typeSelect.includes(fieldtype)) {
options.push(
...[
{ label: 'Equals', value: '=' },
{ label: 'Not Equals', value: '!=' },
]
)
}
if (typeCheck.includes(fieldtype)) {
options.push(...[{ label: 'Equals', value: '=' }])
}
return options
}
function getDefaultOperator(fieldtype) {
if (
typeSelect.includes(fieldtype) ||
typeLink.includes(fieldtype) ||
typeCheck.includes(fieldtype) ||
typeNumber.includes(fieldtype)
) {
return '='
}
return 'like'
}
function getValueSelector(fieldtype, options) {
if (typeSelect.includes(fieldtype) || typeCheck.includes(fieldtype)) {
const _options = fieldtype == 'Check' ? ['Yes', 'No'] : getSelectOptions(options)
return h(FormControl, {
type: 'select',
options: _options,
})
} else {
return h(FormControl, { type: 'text' })
}
}
function getDefaultValue(field) {
if (typeSelect.includes(field.fieldtype)) {
return getSelectOptions(field.options)[0]
}
if (typeCheck.includes(field.fieldtype)) {
return 'Yes'
}
return ''
}
function getSelectOptions(options) {
return options.split('\n')
}
function addFilter(fieldname) {
const field = getField(fieldname)
const filter = {
fieldname,
operator: getDefaultOperator(field.fieldtype),
value: getDefaultValue(field),
field,
}
filters.value = [...filters.value, filter]
}
function removeFilter(index) {
filters.value = filters.value.filter((_, i) => i !== index)
}
</script>
|
2302_79757062/insights
|
frontend/src/components/ListFilter/ListFilter.vue
|
Vue
|
agpl-3.0
| 7,331
|
<template>
<Popover v-slot="{ open }">
<PopoverButton
as="div"
ref="reference"
@click="updatePosition"
@focusin="updatePosition"
@keydown="updatePosition"
v-slot="{ open }"
>
<slot name="target" v-bind="{ open }" />
</PopoverButton>
<div v-show="open">
<PopoverPanel v-slot="{ open, close }" ref="popover" static class="z-[100]">
<slot name="body" v-bind="{ open, close }" />
</PopoverPanel>
</div>
</Popover>
</template>
<script setup>
import { Popover, PopoverButton, PopoverPanel } from '@headlessui/vue'
import { createPopper } from '@popperjs/core'
import { nextTick, ref, onBeforeUnmount } from 'vue'
const props = defineProps({
placement: {
type: String,
default: 'bottom-start',
},
})
const reference = ref(null)
const popover = ref(null)
let popper = ref(null)
function setupPopper() {
if (!popper.value) {
popper.value = createPopper(reference.value.el, popover.value.el, {
placement: props.placement,
})
} else {
popper.value.update()
}
}
function updatePosition() {
nextTick(() => setupPopper())
}
onBeforeUnmount(() => {
popper.value?.destroy()
})
</script>
|
2302_79757062/insights
|
frontend/src/components/ListFilter/NestedPopover.vue
|
Vue
|
agpl-3.0
| 1,141
|
<template>
<Autocomplete
placeholder="Select an option"
:options="options"
:modelValue="selection"
@update:query="(q) => onUpdateQuery(q)"
@update:modelValue="(v) => (selection = v.value)"
/>
</template>
<script setup>
import { Autocomplete, createListResource } from 'frappe-ui'
import { computed, watch } from 'vue'
const emit = defineEmits(['update:modelValue'])
const props = defineProps({
value: {
type: String,
required: false,
default: '',
},
doctype: {
type: String,
required: true,
},
searchField: {
type: String,
required: false,
default: 'name',
},
labelField: {
type: String,
required: false,
default: 'name',
},
valueField: {
type: String,
required: false,
default: 'name',
},
pageLength: {
type: Number,
required: false,
default: 10,
},
})
watch(
() => props.doctype,
(value) => {
r.doctype = value
r.reload()
}
)
const selection = computed({
get: () => props.value,
set: (value) => emit('update:modelValue', value),
})
const r = createListResource({
doctype: props.doctype,
pageLength: props.pageLength,
cache: ['link_doctype', props.doctype],
auto: true,
fields: [props.labelField, props.searchField, props.valueField],
onSuccess: () => {},
})
const options = computed(() => {
const allOptions =
r.data?.map((result) => ({
label: result[props.labelField],
value: result[props.valueField],
})) || []
if (selection.value && !allOptions.find((o) => o.value === selection.value)) {
allOptions.push({
label: selection.value,
value: selection.value,
})
}
return allOptions
})
function onUpdateQuery(query) {
r.update({
filters: {
[props.searchField]: ['like', `%${query}%`],
},
})
r.reload()
}
</script>
|
2302_79757062/insights
|
frontend/src/components/ListFilter/SearchComplete.vue
|
Vue
|
agpl-3.0
| 1,728
|
<template>
<div class="h-full w-full pt-4 sm:pt-16">
<div class="relative z-10">
<div class="flex">
<img src="../assets/insights-logo-new.svg" class="mx-auto h-12" />
</div>
<div
class="mx-auto bg-white px-4 py-8 sm:mt-6 sm:w-96 sm:rounded-lg sm:px-8 sm:shadow-xl"
>
<div class="mb-6 text-center">
<span class="text-base text-gray-900">{{ props.title }}</span>
</div>
<slot></slot>
</div>
</div>
<div class="fixed bottom-4 z-[1] flex w-full justify-center">
<FrappeLogo class="h-4" />
</div>
</div>
</template>
<script setup>
import FrappeLogo from './Icons/FrappeLogo.vue'
const props = defineProps(['title'])
</script>
|
2302_79757062/insights
|
frontend/src/components/LoginBox.vue
|
Vue
|
agpl-3.0
| 675
|
<script setup>
import { computed } from 'vue'
const props = defineProps({
show: { type: Boolean, default: false },
title: { type: String },
types: { type: Array, default: () => [] },
})
const emit = defineEmits(['update:show'])
const show = computed({
get: () => props.show,
set: (value) => emit('update:show', value),
})
</script>
<template>
<Dialog v-model="show">
<template #body>
<div class="bg-white px-4 py-5 text-base sm:p-6">
<h3 v-if="title" class="text-lg font-medium leading-6 text-gray-900">
{{ title }}
</h3>
<!-- There are three types of query builder -->
<div class="mt-4 grid grid-cols-1 gap-6">
<div
v-for="(type, index) in types"
:key="index"
class="group flex cursor-pointer items-center space-x-4"
@click="type.onClick()"
>
<div
class="rounded border p-4 text-gray-500 shadow-sm transition-all group-hover:scale-105"
>
<FeatherIcon
v-if="type.icon"
:name="type.icon"
class="h-6 w-6 text-gray-500"
/>
<img v-if="type.imgSrc" :src="type.imgSrc" class="h-6 w-6" />
</div>
<div>
<div class="flex items-center space-x-2">
<p
class="text-lg font-medium leading-6 text-gray-900 transition-colors group-hover:text-blue-500"
>
{{ type.label }}
</p>
<Badge v-if="type.tag" theme="green">
{{ type.tag }}
</Badge>
</div>
<p class="text-sm leading-5 text-gray-600">
{{ type.description }}
</p>
</div>
</div>
</div>
</div>
</template>
</Dialog>
</template>
|
2302_79757062/insights
|
frontend/src/components/NewDialogWithTypes.vue
|
Vue
|
agpl-3.0
| 1,630
|
<template>
<div class="flex min-w-0 items-center">
<router-link
class="flex items-center rounded px-0.5 py-1 text-lg font-medium text-gray-600 hover:text-gray-700 focus:outline-none focus-visible:ring-2 focus-visible:ring-gray-400"
:to="{ path: '/' }"
>
<HomeIcon class="w-4" />
</router-link>
<span class="mx-1 text-base text-gray-500"> <ChevronRight class="w-4" /> </span>
<template v-if="dropdownItems.length">
<Dropdown class="h-7" :options="dropdownItems">
<Button variant="ghost">
<template #icon>
<MoreHorizontal class="w-4 text-gray-600" />
</template>
</Button>
</Dropdown>
<span class="ml-1 mr-0.5 text-base text-gray-500"> / </span>
</template>
<div class="flex min-w-0 items-center overflow-hidden text-ellipsis whitespace-nowrap">
<template v-for="(item, i) in linkItems" :key="item.label">
<component v-if="item.component" :is="item.component" />
<component
v-else
:is="item.route ? 'router-link' : 'div'"
class="flex items-center rounded px-0.5 py-1 text-lg font-medium focus:outline-none focus-visible:ring-2 focus-visible:ring-gray-400"
:class="[
i == linkItems.length - 1
? 'text-gray-900'
: 'text-gray-600 hover:text-gray-700',
]"
:to="item.route"
>
<slot name="prefix" :item="item" />
<span>
{{ item.label }}
</span>
</component>
<span v-if="i != linkItems.length - 1" class="mx-1 text-base text-gray-500">
<ChevronRight class="w-4" />
</span>
</template>
</div>
</div>
</template>
<script setup>
import { useWindowSize } from '@vueuse/core'
import { Dropdown } from 'frappe-ui'
import { ChevronRight } from 'lucide-vue-next'
import { HomeIcon, MoreHorizontal } from 'lucide-vue-next'
import { computed } from 'vue'
import { useRouter } from 'vue-router'
const props = defineProps({
items: {
type: Array,
required: true,
},
})
const router = useRouter()
const { width } = useWindowSize()
const items = computed(() => {
return (props.items || []).filter(Boolean)
})
const dropdownItems = computed(() => {
if (width.value > 640) return []
let allExceptLastTwo = items.value.slice(0, -2)
return allExceptLastTwo.map((item) => ({
...item,
icon: null,
label: item.label,
onClick: () => router.push(item.route),
}))
})
const linkItems = computed(() => {
if (width.value > 640) return items.value
let lastTwo = items.value.slice(-2)
return lastTwo
})
</script>
|
2302_79757062/insights
|
frontend/src/components/PageBreadcrumbs.vue
|
Vue
|
agpl-3.0
| 2,469
|
<script setup>
const props = defineProps({
title: { type: String },
actions: { type: Array },
})
</script>
<template>
<div class="flex h-14 flex-shrink-0 items-center justify-between">
<div class="flex items-center space-x-4">
<div class="text-3xl font-medium text-gray-900">{{ title }}</div>
<slot name="title-items"></slot>
</div>
<div class="flex space-x-4">
<Button
v-for="action in actions"
:key="action.label"
:variant="action.variant"
:iconLeft="action.iconLeft"
@click="action.onClick"
:class="
action.variant === 'primary'
? '!rounded bg-gray-900 text-gray-50 hover:bg-gray-800 '
: ''
"
>
{{ action.label }}
</Button>
</div>
</div>
</template>
|
2302_79757062/insights
|
frontend/src/components/PageTitle.vue
|
Vue
|
agpl-3.0
| 730
|
<template>
<div ref="reference">
<div
ref="target"
:class="['flex', $attrs.class]"
@click="updatePosition"
@focusin="updatePosition"
@keydown="updatePosition"
@mouseover="onMouseover"
@mouseleave="onMouseleave"
>
<slot name="target" v-bind="{ togglePopover, updatePosition, open, close, isOpen }" />
</div>
<teleport to="#frappeui-popper-root">
<div
ref="popover"
class="relative z-[100]"
:class="[popoverContainerClass, popoverClass]"
:style="{ minWidth: targetWidth ? targetWidth + 'px' : null }"
@mouseover="pointerOverTargetOrPopup = true"
@mouseleave="onMouseleave"
>
<transition v-bind="popupTransition">
<div v-show="isOpen">
<slot
name="body"
v-bind="{ togglePopover, updatePosition, open, close, isOpen }"
>
<div
class="rounded-lg border border-gray-100 bg-white shadow-xl"
:class="bodyClass"
>
<slot
name="body-main"
v-bind="{
togglePopover,
updatePosition,
open,
close,
isOpen,
}"
/>
</div>
</slot>
</div>
</transition>
</div>
</teleport>
</div>
</template>
<script>
import { createPopper } from '@popperjs/core'
export default {
name: 'Popover',
inheritAttrs: false,
props: {
show: {
default: undefined,
},
trigger: {
type: String,
default: 'click', // click, hover
},
hoverDelay: {
type: Number,
default: 0,
},
leaveDelay: {
type: Number,
default: 0,
},
placement: {
type: String,
default: 'bottom-start',
},
popoverClass: [String, Object, Array],
bodyClass: [String, Object, Array],
transition: {
default: null,
},
hideOnBlur: {
default: true,
},
},
emits: ['open', 'close', 'update:show'],
expose: ['open', 'close'],
data() {
return {
popoverContainerClass: 'body-container',
showPopup: false,
targetWidth: null,
pointerOverTargetOrPopup: false,
}
},
watch: {
show(val) {
if (val) {
this.open()
} else {
this.close()
}
},
},
created() {
if (typeof window === 'undefined') return
if (!document.getElementById('frappeui-popper-root')) {
const root = document.createElement('div')
root.id = 'frappeui-popper-root'
document.body.appendChild(root)
}
},
mounted() {
this.listener = (e) => {
if (!this.isOpen) return
const clickedElement = e.target
const reference = this.$refs.reference
const popoverBody = this.$refs.popover
const insideClick =
clickedElement === reference ||
clickedElement === popoverBody ||
reference?.contains(clickedElement) ||
popoverBody?.contains(clickedElement)
if (insideClick) {
return
}
const root = document.getElementById('frappeui-popper-root')
const insidePopoverRoot = root.contains(clickedElement)
if (!insidePopoverRoot) {
return this.close()
}
const bodyClass = `.${this.popoverContainerClass}`
const clickedElementBody = clickedElement?.closest(bodyClass)
const currentPopoverBody = reference?.closest(bodyClass)
const isSiblingClicked =
clickedElementBody &&
currentPopoverBody &&
clickedElementBody === currentPopoverBody
if (isSiblingClicked) {
this.close()
}
}
if (this.hideOnBlur) {
document.addEventListener('click', this.listener)
// https://github.com/tailwindlabs/headlessui/issues/834#issuecomment-1030907894
document.addEventListener('mousedown', this.listener)
}
this.$nextTick(() => {
this.targetWidth = this.$refs['target'].clientWidth
})
},
beforeDestroy() {
this.popper && this.popper.destroy()
document.removeEventListener('click', this.listener)
document.removeEventListener('mousedown', this.listener)
},
computed: {
showPropPassed() {
return this.show != null
},
isOpen: {
get() {
if (this.showPropPassed) {
return this.show
}
return this.showPopup
},
set(val) {
val = Boolean(val)
if (this.showPropPassed) {
this.$emit('update:show', val)
} else {
this.showPopup = val
}
if (val === false) {
this.$emit('close')
} else if (val === true) {
this.$emit('open')
}
},
},
popupTransition() {
let templates = {
default: {
enterActiveClass: 'transition duration-150 ease-out',
enterFromClass: 'translate-y-1 opacity-0',
enterToClass: 'translate-y-0 opacity-100',
leaveActiveClass: 'transition duration-150 ease-in',
leaveFromClass: 'translate-y-0 opacity-100',
leaveToClass: 'translate-y-1 opacity-0',
},
}
if (typeof this.transition === 'string') {
return templates[this.transition]
}
return this.transition
},
},
methods: {
setupPopper() {
if (!this.popper) {
this.popper = createPopper(this.$refs.reference, this.$refs.popover, {
placement: this.placement,
})
} else {
this.updatePosition()
}
},
updatePosition() {
this.popper && this.popper.update()
},
togglePopover(flag) {
if (flag instanceof Event) {
flag = null
}
if (flag == null) {
flag = !this.isOpen
}
flag = Boolean(flag)
if (flag) {
this.open()
} else {
this.close()
}
},
open() {
this.isOpen = true
this.$nextTick(() => this.setupPopper())
},
close() {
this.isOpen = false
},
onMouseover() {
this.pointerOverTargetOrPopup = true
if (this.leaveTimer) {
clearTimeout(this.leaveTimer)
this.leaveTimer = null
}
if (this.trigger === 'hover') {
if (this.hoverDelay) {
this.hoverTimer = setTimeout(() => {
if (this.pointerOverTargetOrPopup) {
this.open()
}
}, Number(this.hoverDelay) * 1000)
} else {
this.open()
}
}
},
onMouseleave(e) {
this.pointerOverTargetOrPopup = false
if (this.hoverTimer) {
clearTimeout(this.hoverTimer)
this.hoverTimer = null
}
if (this.trigger === 'hover') {
if (this.leaveTimer) {
clearTimeout(this.leaveTimer)
}
if (this.leaveDelay) {
this.leaveTimer = setTimeout(() => {
if (!this.pointerOverTargetOrPopup) {
this.close()
}
}, Number(this.leaveDelay) * 1000)
} else {
if (!this.pointerOverTargetOrPopup) {
this.close()
}
}
}
},
},
}
</script>
|
2302_79757062/insights
|
frontend/src/components/Popover.vue
|
Vue
|
agpl-3.0
| 6,322
|
<template>
<Dialog v-model="show" :dismissable="true">
<template #body>
<div class="bg-white px-4 py-5 sm:p-6">
<h3 class="mb-3 text-lg font-medium leading-6 text-gray-900">
{{ title }}
</h3>
<div class="space-y-3 text-base">
<div class="space-y-4">
<div class="flex items-center space-x-4 rounded border px-4 py-2">
<FeatherIcon name="globe" class="h-5 w-5 text-blue-500" />
<div class="flex flex-1 flex-col">
<div class="font-medium text-gray-800">Create Public Link</div>
<div class="text-sm text-gray-700">
Anyone with the link can view this
{{ resourceType.replace('Insights ', '').toLowerCase() }}
</div>
</div>
<Checkbox v-model="isPublic" />
</div>
<div class="flex overflow-hidden rounded bg-gray-100" v-if="publicLink">
<div
class="font-code form-input flex-1 overflow-hidden text-ellipsis whitespace-nowrap rounded-r-none text-sm text-gray-600"
>
{{ publicLink }}
</div>
<Tooltip text="Copy Link" :hoverDelay="0.1">
<Button
class="w-8 rounded-none bg-gray-200 hover:bg-gray-300"
icon="link-2"
@click="copyToClipboard(publicLink)"
>
</Button>
</Tooltip>
<Tooltip text="Copy iFrame" :hoverDelay="0.1">
<Button
class="w-8 rounded-l-none bg-gray-200 hover:bg-gray-300"
icon="code"
@click="copyToClipboard(iFrame)"
>
</Button>
</Tooltip>
</div>
</div>
</div>
</div>
</template>
</Dialog>
</template>
<script setup>
import { copyToClipboard } from '@/utils'
import { createResource } from 'frappe-ui'
import { computed, watch } from 'vue'
const emit = defineEmits(['update:show', 'togglePublicAccess'])
const props = defineProps({
show: {
type: Boolean,
required: true,
},
resourceType: {
type: String,
required: true,
},
resourceName: {
type: String,
required: true,
},
isPublic: {
type: Boolean,
default: false,
},
})
const show = computed({
get: () => props.show,
set: (value) => {
emit('update:show', value)
},
})
const title = computed(() => {
return `Share ${props.resourceType.replace('Insights ', '')}`
})
const isPublic = computed({
get: () => props.isPublic,
set: (value) => {
emit('togglePublicAccess', value ? 1 : 0)
},
})
const getPublicKey = createResource({
url: 'insights.api.public.get_public_key',
params: {
resource_type: props.resourceType,
resource_name: props.resourceName,
},
})
watch(
isPublic,
(newVal, oldVal) => {
if (newVal && !oldVal) {
getPublicKey.fetch()
}
},
{ immediate: true }
)
const resourceTypeTitle = props.resourceType.replace('Insights ', '').toLowerCase()
const publicLink = computed(() => {
const publickKey = getPublicKey.data
const base = `${window.location.origin}/insights/public/${resourceTypeTitle}/`
return isPublic.value && publickKey ? base + publickKey : null
})
const iFrame = computed(() => {
const publickKey = getPublicKey.data
const base = `${window.location.origin}/insights/public/${resourceTypeTitle}/`
const iframeAttrs = `width="800" height="600" frameborder="0" allowtransparency`
return isPublic.value && publickKey
? `<iframe src="${base + publickKey}" ${iframeAttrs}></iframe>`
: null
})
</script>
|
2302_79757062/insights
|
frontend/src/components/PublicShareDialog.vue
|
Vue
|
agpl-3.0
| 3,344
|
<script setup>
import ContentEditable from './ContentEditable.vue'
import { computed } from 'vue'
const emit = defineEmits(['update:modelValue'])
const props = defineProps({ modelValue: String | Number, placeholder: String })
const value = computed({
get: () => props.modelValue || '',
set: (value) => emit('update:modelValue', value),
})
</script>
<template>
<ContentEditable
v-model="value"
:placeholder="props.placeholder"
class="h-7 cursor-pointer px-2.5 leading-7 outline-none ring-0 transition-all focus:outline-none"
:class="$attrs.class"
/>
</template>
|
2302_79757062/insights
|
frontend/src/components/ResizeableInput.vue
|
Vue
|
agpl-3.0
| 574
|
<template>
<div class="flex">
<div class="flex-1">
<p class="font-medium leading-6 text-gray-900">{{ label }}</p>
<span class="text-gray-600">
{{ description }}
</span>
</div>
<div class="flex flex-1 items-center pl-20">
<slot />
</div>
</div>
</template>
<script setup>
const props = defineProps({
label: {
type: String,
required: true,
},
description: {
type: String,
required: true,
},
})
</script>
|
2302_79757062/insights
|
frontend/src/components/Setting.vue
|
Vue
|
agpl-3.0
| 441
|
<template>
<Dialog v-model="show" :dismissable="true">
<template #body>
<div class="bg-white px-4 py-5 sm:p-6">
<h3 class="mb-3 text-lg font-medium leading-6 text-gray-900">
{{ title }}
</h3>
<div class="space-y-3 text-base">
<div v-if="props.allowPublicAccess" class="space-y-4">
<div class="flex items-center space-x-4 rounded border px-4 py-2">
<FeatherIcon name="globe" class="h-5 w-5 text-blue-500" />
<div class="flex flex-1 flex-col">
<div class="font-medium text-gray-600">Create Public Link</div>
<div class="text-sm text-gray-500">
Anyone with the link can view this
{{ resourceType.replace('Insights ', '').toLowerCase() }}
</div>
</div>
<Checkbox v-model="isPublic" />
</div>
<div class="flex overflow-hidden rounded bg-gray-100" v-if="publicLink">
<div
class="font-code form-input flex-1 overflow-hidden text-ellipsis whitespace-nowrap rounded-r-none text-sm text-gray-600"
>
{{ publicLink }}
</div>
<Tooltip text="Copy Link" :hoverDelay="0.1">
<Button
class="w-8 rounded-none bg-gray-200 hover:bg-gray-300"
icon="link-2"
@click="copyToClipboard(publicLink)"
>
</Button>
</Tooltip>
<Tooltip text="Copy iFrame" :hoverDelay="0.1">
<Button
class="w-8 rounded-l-none bg-gray-200 hover:bg-gray-300"
icon="code"
@click="copyToClipboard(iFrame)"
>
</Button>
</Tooltip>
</div>
</div>
<div v-if="settings.enable_permissions">
<Autocomplete
v-model="newTeam"
placeholder="Add a team to share with"
:options="unauthorizedTeams"
:autofocus="false"
@update:modelValue="handleAccessGrant"
/>
<div class="space-y-3">
<div class="font-medium text-gray-600">Teams with access</div>
<div v-if="authorizedTeams.length > 0" class="space-y-3">
<div
class="flex items-center text-gray-600"
v-for="team in authorizedTeams"
:key="team.name"
>
<Avatar :label="team.team_name" />
<div class="ml-2 flex flex-col">
<span>{{ team.team_name }}</span>
<span class="text-gray-500"
>{{ team.members_count }} members</span
>
</div>
<Button
icon="x"
class="ml-auto"
variant="minimal"
@click="handleAccessRevoke(team.name)"
></Button>
</div>
</div>
<div
v-else
class="flex h-20 items-center justify-center rounded border-2 border-dashed text-sm font-light text-gray-500"
>
Only you have access to this
{{ resourceType.replace('Insights ', '').toLowerCase() }}
</div>
</div>
</div>
</div>
</div>
</template>
</Dialog>
</template>
<script setup>
import settingsStore from '@/stores/settingsStore'
import { copyToClipboard } from '@/utils'
import { createResource } from 'frappe-ui'
import { computed, ref, watch } from 'vue'
const settings = settingsStore().settings
const emit = defineEmits(['update:show', 'togglePublicAccess'])
const props = defineProps({
show: {
type: Boolean,
required: true,
},
resourceType: {
type: String,
required: true,
},
resourceName: {
type: String,
required: true,
},
allowPublicAccess: {
type: Boolean,
default: false,
},
isPublic: {
type: Boolean,
default: false,
},
})
const show = computed({
get: () => props.show,
set: (value) => {
emit('update:show', value)
},
})
const title = computed(() => {
return `Share ${props.resourceType.replace('Insights ', '')}`
})
const isPublic = computed({
get: () => props.isPublic,
set: (value) => {
emit('togglePublicAccess', value ? 1 : 0)
},
})
const getPublicKey = createResource({
url: 'insights.api.public.get_public_key',
params: {
resource_type: props.resourceType,
resource_name: props.resourceName,
},
})
watch(
isPublic,
(newVal, oldVal) => {
if (newVal && !oldVal) {
getPublicKey.fetch()
}
},
{ immediate: true }
)
const publicLink = computed(() => {
const publickKey = getPublicKey.data
const base = `${window.location.origin}/insights/public/dashboard/`
return isPublic.value && publickKey ? base + publickKey : null
})
const iFrame = computed(() => {
const publickKey = getPublicKey.data
const base = `${window.location.origin}/insights/public/dashboard/`
const iframeAttrs = `width="800" height="600" frameborder="0" allowtransparency`
return isPublic.value && publickKey
? `<iframe src="${base + publickKey}" ${iframeAttrs}></iframe>`
: null
})
const getAccessInfo = createResource({
url: 'insights.api.permissions.get_resource_access_info',
params: {
resource_type: props.resourceType,
resource_name: props.resourceName,
},
})
watch(show, (newVal, oldVal) => {
if (newVal && !oldVal) {
getAccessInfo.fetch()
}
})
const authorizedTeams = computed(() => {
return getAccessInfo.data?.authorized_teams || []
})
const newTeam = ref(null)
const unauthorizedTeams = computed(() => {
return getAccessInfo.data?.unauthorized_teams.map((team) => {
return {
label: team.team_name,
value: team.name,
description: team.members_count + ' members',
}
})
})
const grantAccess = createResource({
url: 'insights.api.permissions.grant_access',
})
function handleAccessGrant(team) {
grantAccess
.submit({
resource_type: props.resourceType,
resource_name: props.resourceName,
team: team.value,
})
.then(() => {
getAccessInfo.fetch()
})
newTeam.value = null
}
const revokeAccess = createResource({
url: 'insights.api.permissions.revoke_access',
})
function handleAccessRevoke(team) {
revokeAccess
.submit({
resource_type: props.resourceType,
resource_name: props.resourceName,
team: team,
})
.then(() => {
getAccessInfo.fetch()
})
}
</script>
|
2302_79757062/insights
|
frontend/src/components/ShareDialog.vue
|
Vue
|
agpl-3.0
| 5,962
|
<template>
<div
class="rg:w-60 flex w-14 flex-shrink-0 flex-col border-r border-gray-300 bg-white"
v-if="currentRoute"
>
<div class="flex flex-grow flex-col overflow-y-auto p-2.5">
<div class="rg:flex hidden flex-shrink-0 items-end text-sm text-gray-600">
<img src="../assets/insights-logo-new.svg" class="h-7" />
</div>
<router-link to="/" class="rg:hidden flex cursor-pointer">
<img src="../assets/insights-logo-new.svg" class="rounded" />
</router-link>
<div class="mt-4 flex flex-col">
<nav class="flex-1 space-y-1 pb-4 text-base">
<Tooltip
v-for="route in sidebarItems"
:key="route.path"
placement="right"
:hoverDelay="0.1"
class="w-full"
>
<template #body>
<div
class="w-fit rounded border border-gray-100 bg-gray-800 px-2 py-1 text-xs text-white shadow-xl"
>
{{ route.label }}
</div>
</template>
<router-link
:to="route.path"
:class="[
route.current
? 'bg-gray-200/70'
: 'text-gray-700 hover:bg-gray-50 hover:text-gray-800',
'rg:justify-start group flex w-full items-center justify-center rounded p-2 font-medium',
]"
aria-current="page"
>
<component
:is="route.icon"
:stroke-width="1.5"
:class="[
route.current
? 'text-gray-800'
: 'text-gray-700 group-hover:text-gray-700',
'rg:mr-3 rg:h-4 rg:w-4 mr-0 h-5 w-5 flex-shrink-0',
]"
/>
<span class="rg:inline-block hidden">{{ route.label }}</span>
</router-link>
</Tooltip>
</nav>
</div>
<div class="mt-auto flex flex-col items-center gap-2 text-base text-gray-600">
<Button variant="ghost" @click="open('https://docs.frappeinsights.com')">
<BookOpen class="h-4 text-gray-600" />
</Button>
<Dropdown
placement="left"
:options="[
{
label: 'Documentation',
icon: 'help-circle',
onClick: () => open('https://docs.frappeinsights.com'),
},
{
label: 'Join Telegram Group',
icon: 'message-circle',
onClick: () => open('https://t.me/frappeinsights'),
},
{
label: 'Help',
icon: 'life-buoy',
onClick: () => (showHelpDialog = true),
},
session.user.is_admin
? {
label: 'Switch to Desk',
icon: 'grid',
onClick: () => open('/app'),
}
: null,
{
label: 'Switch to Insights v3',
icon: 'grid',
onClick: () => (showSwitchToV3Dialog = true),
},
{
label: 'Logout',
icon: 'log-out',
onClick: () => session.logout(),
},
]"
>
<template v-slot="{ open }">
<button
class="flex w-full items-center space-x-2 rounded p-1 text-left text-base font-medium"
:class="open ? 'bg-gray-300' : 'hover:bg-gray-200'"
>
<Avatar
size="xl"
:label="session.user.full_name"
:image="session.user.user_image"
/>
<span
class="rg:inline ml-2 hidden overflow-hidden text-ellipsis whitespace-nowrap"
>
{{ session.user.full_name }}
</span>
<FeatherIcon name="chevron-down" class="rg:inline hidden h-4 w-4" />
</button>
</template>
</Dropdown>
</div>
</div>
</div>
<HelpDialog v-model="showHelpDialog" />
<Dialog
v-model="showSwitchToV3Dialog"
:options="{
title: 'Insights v3 ✨',
actions: [
{
label: 'Continue',
variant: 'solid',
onClick: openInsightsV3,
},
],
}"
>
<template #body-content>
<div class="prose prose-sm mb-4">
<p>
Switch to the newest version of Insights, built from the ground up for a better
experience.
</p>
<p>
You can always switch back to this version by clicking the "Switch to Insights
v2" button in the new version.
</p>
</div>
<FormControl
type="checkbox"
label="Set Insights v3 as default"
:modelValue="session.user.default_version === 'v3'"
@update:modelValue="session.user.default_version = $event ? 'v3' : ''"
/>
</template>
</Dialog>
</template>
<script setup>
import { Avatar } from 'frappe-ui'
import HelpDialog from '@/components/HelpDialog.vue'
import sessionStore from '@/stores/sessionStore'
import settingsStore from '@/stores/settingsStore'
import {
Book,
BookOpen,
Database,
GanttChartSquare,
HomeIcon,
LayoutPanelTop,
Settings,
User,
Users,
} from 'lucide-vue-next'
import { computed, ref, watch } from 'vue'
import { useRoute } from 'vue-router'
const session = sessionStore()
const settings = settingsStore().settings
const showHelpDialog = ref(false)
const showSwitchToV3Dialog = ref(false)
const sidebarItems = ref([
{
path: '/',
label: 'Home',
icon: HomeIcon,
name: 'Home',
current: false,
},
{
path: '/dashboard',
label: 'Dashboards',
icon: LayoutPanelTop,
name: 'Dashboard',
current: false,
},
{
path: '/query',
label: 'Query',
icon: GanttChartSquare,
name: 'QueryList',
current: false,
},
{
path: '/data-source',
label: 'Data Sources',
icon: Database,
name: 'Data Source',
},
{
path: '/notebook',
label: 'Notebook',
icon: Book,
name: 'Notebook',
current: false,
},
{
path: '/settings',
label: 'Settings',
icon: Settings,
name: 'Settings',
current: false,
},
])
watch(
() => session.user.is_admin && settings?.enable_permissions,
(isAdmin) => {
if (isAdmin) {
// add users & teams item after settings item
if (sidebarItems.value.find((item) => item.name === 'Teams')) {
return
}
const settingsIndex = sidebarItems.value.findIndex((item) => item.name === 'Settings')
sidebarItems.value.splice(settingsIndex, 0, {
path: '/users',
label: 'Users',
icon: User,
name: 'Users',
current: false,
})
sidebarItems.value.splice(settingsIndex + 1, 0, {
path: '/teams',
label: 'Teams',
icon: Users,
name: 'Teams',
current: false,
})
}
}
)
const route = useRoute()
const currentRoute = computed(() => {
sidebarItems.value.forEach((item) => {
// check if /<route> or /<route>/<id> is in sidebar item path
item.current = route.path.match(new RegExp(`^${item.path}(/|$)`))
})
return route.path
})
const open = (url) => window.open(url, '_blank')
function openInsightsV3() {
session
.updateDefaultVersion(
// if default version is v2, then /insights always redirects to /insights_v2
// so it is not possible to switch to v3 from v2
// so we need to remove the default_version
session.user.default_version === 'v2' ? '' : session.user.default_version
)
.then(() => {
window.location.href = '/insights'
})
}
</script>
|
2302_79757062/insights
|
frontend/src/components/Sidebar.vue
|
Vue
|
agpl-3.0
| 6,760
|
import { LoadingIndicator } from 'frappe-ui'
export default {
name: 'SuspenseFallback',
components: { LoadingIndicator },
render() {
return (
<div class="flex h-full w-full flex-col items-center justify-center">
<LoadingIndicator class="h-10 w-10 text-gray-400" />
</div>
)
},
}
|
2302_79757062/insights
|
frontend/src/components/SuspenseFallback.jsx
|
JavaScript
|
agpl-3.0
| 297
|
<script setup>
import { SearchIcon } from 'lucide-vue-next'
const emit = defineEmits(['update:modelValue'])
const props = defineProps({ modelValue: String })
</script>
<template>
<FormControl
type="text"
autocomplete="off"
:modelValue="modelValue"
@update:modelValue="emit('update:modelValue', $event)"
>
<template #prefix>
<SearchIcon class="h-3 w-3 text-gray-500" />
</template>
</FormControl>
</template>
|
2302_79757062/insights
|
frontend/src/components/Table/TableColumnFilter.vue
|
Vue
|
agpl-3.0
| 428
|
<script setup>
import { PackageOpen } from 'lucide-vue-next'
</script>
<template>
<div
class="absolute top-0 flex h-full w-full flex-col items-center justify-center gap-2 text-base text-gray-500"
>
<PackageOpen class="h-12 w-12 text-gray-400" stroke-width="1" />
<div class="text-center">No results to display</div>
</div>
</template>
|
2302_79757062/insights
|
frontend/src/components/Table/TableEmpty.vue
|
Vue
|
agpl-3.0
| 345
|
<script setup>
import { FlexRender } from '@tanstack/vue-table'
import { ChevronDown, ChevronRight } from 'lucide-vue-next'
const props = defineProps({
row: { type: Object, required: true },
cell: { type: Object, required: true },
})
</script>
<template>
<div class="flex gap-1">
<ChevronDown
v-if="row.getIsExpanded()"
class="h-4 w-4 cursor-pointer text-gray-600 hover:text-gray-800"
@click="row.getToggleExpandedHandler()?.($event)"
/>
<ChevronRight
v-else
class="h-4 w-4 cursor-pointer text-gray-600 hover:text-gray-800"
@click="row.getToggleExpandedHandler()?.($event)"
/>
<FlexRender :render="cell.column.columnDef.cell" :props="cell.getContext()" />
</div>
</template>
|
2302_79757062/insights
|
frontend/src/components/Table/TableGroupedCell.vue
|
Vue
|
agpl-3.0
| 709
|
<script setup>
import { LinkIcon } from 'lucide-vue-next'
const props = defineProps({
label: { type: String, required: true },
url: { type: String, required: true },
})
</script>
<template>
<a :href="url" target="_blank" class="flex items-center gap-1 hover:underline">
<LinkIcon class="h-3 w-3" />
<span>{{ label }}</span>
</a>
</template>
|
2302_79757062/insights
|
frontend/src/components/Table/TableLinkCell.vue
|
Vue
|
agpl-3.0
| 351
|
<script setup>
import { formatNumber } from '@/utils'
import { COLOR_MAP } from '@/utils/colors'
const props = defineProps({
value: { type: Number, required: true },
prefix: { type: String, required: false, default: '' },
suffix: { type: String, required: false, default: '' },
decimals: { type: Number, required: false, default: 2 },
minValue: { type: Number, required: true },
maxValue: { type: Number, required: true },
showInlineBarChart: { type: Boolean, required: false, default: false },
})
</script>
<template>
<div class="flex items-center gap-2">
<div class="tnum flex-1 flex-shrink-0 text-right">
{{ prefix }}{{ formatNumber(value, decimals) }}{{ suffix }}
</div>
<div
v-if="showInlineBarChart"
class="flex overflow-hidden rounded-full"
:class="minValue < 0 ? 'w-24' : 'w-20'"
>
<div v-if="minValue < 0" class="h-2 flex-1 bg-red-200">
<div
v-if="value < 0"
class="float-right h-full"
:style="{
width: `${(Math.abs(value) / maxValue) * 100}%`,
backgroundColor: COLOR_MAP.red,
}"
></div>
</div>
<div class="h-2 flex-1 bg-blue-200">
<div
v-if="value > 0"
class="h-full bg-blue-500"
:style="{
width: `${(value / maxValue) * 100}%`,
backgroundColor: COLOR_MAP.blue,
}"
></div>
</div>
</div>
</div>
</template>
|
2302_79757062/insights
|
frontend/src/components/Table/TableNumberCell.vue
|
Vue
|
agpl-3.0
| 1,341
|
<script setup>
import {
FlexRender,
getCoreRowModel,
getExpandedRowModel,
getFilteredRowModel,
getGroupedRowModel,
getPaginationRowModel,
getSortedRowModel,
useVueTable,
} from '@tanstack/vue-table'
import { debounce } from 'frappe-ui'
import { ChevronLeft, ChevronRight } from 'lucide-vue-next'
import { computed, ref } from 'vue'
import TableColumnFilter from './TableColumnFilter.vue'
import TableEmpty from './TableEmpty.vue'
import TableGroupedCell from './TableGroupedCell.vue'
import { filterFunction } from './utils'
const props = defineProps({
columns: { type: Array, required: true },
data: { type: Array, required: true },
showFilters: { type: Boolean, required: false, default: false },
showFooter: { type: Boolean, required: false, default: false },
showPagination: { type: Boolean, required: false, default: true },
})
const showFooter = computed(() => {
return props.columns.some((column) => column.footer) && props.showFooter
})
const sorting = ref([])
const grouping = ref([])
const columnFilters = ref([])
const table = useVueTable({
get data() {
return props.data
},
get columns() {
return props.columns
},
initialState: {
pagination: {
pageSize: 100,
pageIndex: 0,
},
},
state: {
get sorting() {
return sorting.value
},
get grouping() {
return grouping.value
},
get columnFilters() {
return columnFilters.value
},
},
filterFns: { filterFunction },
getCoreRowModel: getCoreRowModel(),
getExpandedRowModel: getExpandedRowModel(),
getGroupedRowModel: getGroupedRowModel(),
getFilteredRowModel: getFilteredRowModel(),
getSortedRowModel: getSortedRowModel(),
getPaginationRowModel: getPaginationRowModel(),
onColumnFiltersChange: debounce((updaterOrValue) => {
columnFilters.value =
typeof updaterOrValue == 'function'
? updaterOrValue(columnFilters.value)
: updaterOrValue
}, 300),
onSortingChange: debounce((updaterOrValue) => {
sorting.value =
typeof updaterOrValue == 'function' ? updaterOrValue(sorting.value) : updaterOrValue
}, 300),
})
const pageLength = computed(() => table.getState().pagination.pageSize)
const currPage = computed(() => table.getState().pagination.pageIndex + 1)
const totalPage = computed(() => table.getPageCount())
const pageStart = computed(() => (currPage.value - 1) * pageLength.value + 1)
const pageEnd = computed(() => {
const end = currPage.value * pageLength.value
return end > props.data.length ? props.data.length : end
})
const totalRows = computed(() => props.data.length)
const showPagination = computed(
() => props.showPagination && props.data?.length && totalRows.value > pageLength.value
)
</script>
<template>
<div class="flex h-full w-full flex-col overflow-hidden">
<div class="relative flex flex-1 flex-col overflow-auto text-base">
<TableEmpty v-if="props.data?.length == 0" />
<table
v-if="props?.columns?.length || props.data?.length"
class="border-separate border-spacing-0"
>
<thead class="sticky top-0 bg-gray-50">
<tr v-for="headerGroup in table.getHeaderGroups()" :key="headerGroup.id">
<td
v-for="header in headerGroup.headers"
:key="header.id"
:colSpan="header.colSpan"
class="border-b border-r text-gray-800"
:width="header.column.columnDef.id === 'index' ? '6rem' : 'auto'"
>
<div
class="flex items-center gap-2 truncate py-2 px-3"
:class="[
header.column.columnDef.isNumber ? 'text-right' : '',
header.column.getCanSort()
? 'cursor-pointer hover:text-gray-800'
: '',
]"
@click.prevent="header.column.getToggleSortingHandler()?.($event)"
>
<FlexRender
v-if="!header.isPlaceholder"
:render="header.column.columnDef.header"
:props="header.getContext()"
/>
<span
v-if="header.column.getIsSorted()"
class="text-[10px] text-gray-400"
>
{{
header.column.getIsSorted() == 'desc'
? '▼'
: header.column.getIsSorted() == 'asc'
? '▲'
: ''
}}
</span>
<div v-if="$slots.columnActions" class="ml-4">
<slot
name="columnActions"
:column="header.column.columnDef"
></slot>
</div>
</div>
<div
class="border-t p-1"
v-if="
props.showFilters &&
header.column.getCanFilter() &&
!header.isPlaceholder
"
>
<TableColumnFilter
:isNumber="header.column.columnDef.isNumber"
:modelValue="header.column.getFilterValue()"
@update:modelValue="header.column.setFilterValue($event)"
/>
</div>
</td>
</tr>
</thead>
<tbody>
<tr v-for="(row, index) in table.getRowModel().rows" :key="row.id">
<td
v-for="cell in row.getVisibleCells()"
:key="cell.id"
class="truncate border-b border-r py-2 px-3"
:class="[
cell.column.columnDef.isNumber ? 'tnum text-right' : '',
cell.column.columnDef.id !== 'index' ? 'min-w-[6rem] ' : '',
]"
>
<TableGroupedCell v-if="cell.getIsGrouped()" :row="row" :cell="cell" />
<div v-else-if="!cell.getIsPlaceholder()">
<FlexRender
:render="cell.column.columnDef.cell"
:props="cell.getContext()"
/>
</div>
</td>
</tr>
<tr height="99%" class="border-b"></tr>
</tbody>
<tfoot v-if="showFooter" class="sticky bottom-0 bg-white">
<tr v-for="footerGroup in table.getFooterGroups()" :key="footerGroup.id">
<td
v-for="header in footerGroup.headers"
:key="header.id"
:colSpan="header.colSpan"
class="truncate border-y border-r py-2 px-3 text-left font-medium first:pl-4 last:pr-2"
:class="[header.column.columnDef.isNumber ? 'tnum text-right' : '']"
>
<FlexRender
v-if="!header.isPlaceholder"
:render="header.column.columnDef.footer"
:props="header.getContext()"
/>
</td>
</tr>
</tfoot>
</table>
</div>
<div v-if="showPagination" class="flex flex-shrink-0 items-center justify-end gap-3 p-1">
<p class="tnum text-sm text-gray-600">
{{ pageStart }} - {{ pageEnd }} of {{ totalRows }} rows
</p>
<div class="flex gap-2">
<Button
variant="ghost"
@click="table.previousPage()"
:disabled="!table.getCanPreviousPage()"
>
<ChevronLeft class="h-4 w-4 text-gray-600" />
</Button>
<Button
variant="ghost"
@click="table.nextPage()"
:disabled="!table.getCanNextPage()"
>
<ChevronRight class="h-4 w-4 text-gray-600" />
</Button>
</div>
</div>
</div>
</template>
|
2302_79757062/insights
|
frontend/src/components/Table/TanstackTable.vue
|
Vue
|
agpl-3.0
| 6,759
|
import { ellipsis, formatNumber } from '@/utils'
import { Badge } from 'frappe-ui'
import { h } from 'vue'
import TableLinkCell from './TableLinkCell.vue'
import TableNumberCell from './TableNumberCell.vue'
export function filterFunction(row, columnId, filterValue) {
const column = columnId
const value = row.getValue(column)
const isNumber = row.getVisibleCells().find((cell) => cell.column.id == column)?.column
.columnDef.isNumber
if (isNumber) {
// check for an operator in the filter value: >, <, >=, <=, =, !=
const operator = ['>=', '<=', '!=', '=', '>', '<'].find((op) => filterValue.startsWith(op))
if (operator) {
const filterValueNumber = Number(filterValue.replace(operator, ''))
switch (operator) {
case '>':
return Number(value) > filterValueNumber
case '<':
return Number(value) < filterValueNumber
case '>=':
return Number(value) >= filterValueNumber
case '<=':
return Number(value) <= filterValueNumber
case '=':
return Number(value) == filterValueNumber
case '!=':
return Number(value) != filterValueNumber
}
}
// check for a range in the filter value: 1-10
const data = filterValue.match(/(\d+)-(\d+)/)
if (data) {
const [min, max] = data.slice(1)
return Number(value) >= Number(min) && Number(value) <= Number(max)
}
}
return String(value).toLowerCase().includes(filterValue.toLowerCase())
}
export function getFormattedCell(cell) {
const parsedPills = parsePills(cell)
if (parsedPills) {
return h(
'div',
parsedPills.map((item) => h(Badge, { label: item }))
)
}
const isNumber = typeof cell == 'number'
const cellValue = isNumber ? formatNumber(cell) : ellipsis(cell, 100)
return h('div', { class: isNumber ? 'text-right tnum' : '' }, cellValue)
}
export function getCellComponent(cell, column) {
const value = cell.getValue()
column.column_options = column.column_options || {}
const columnType = column.column_options.column_type || column.type
const parsedPills = parsePills(value)
if (parsedPills) {
return h(
'div',
parsedPills.map((item) => h(Badge, { label: item }))
)
}
if (columnType == 'Link') {
return h(TableLinkCell, {
label: value,
url: column.column_options.link_url.replace('{{value}}', value),
})
}
if (columnType == 'Number') {
const allValues = cell.table
.getCoreRowModel()
.rows.map((r) => r.getValue(column.column || column.label))
return h(TableNumberCell, {
value: value,
prefix: column.column_options.prefix,
suffix: column.column_options.suffix,
decimals: column.column_options.decimals,
minValue: Math.min(...allValues),
maxValue: Math.max(...allValues),
showInlineBarChart: column.column_options.show_inline_bar_chart,
})
}
const isNumber = typeof value == 'number'
return h(
'div',
{ class: isNumber ? 'text-right tnum' : '' },
isNumber ? formatNumber(value) : value
)
}
function parsePills(cell) {
try {
const parsedPills = JSON.parse(cell)
if (Array.isArray(parsedPills) && parsedPills.length) {
return parsedPills
}
} catch (e) {
return undefined
}
}
|
2302_79757062/insights
|
frontend/src/components/Table/utils.js
|
JavaScript
|
agpl-3.0
| 3,108
|
<template>
<div class="flex h-7 w-full cursor-pointer select-none items-center rounded border bg-gray-100">
<div
v-for="tab in tabs"
class="flex h-full flex-1 items-center justify-center truncate px-4 transition-all"
:class="{
'rounded bg-white shadow':
tab.active ||
currentTab === tab.value ||
(currentTab === undefined && tab.default),
'cursor-not-allowed': tab.disabled,
}"
@click="handleClick(tab)"
>
{{ tab.label }}
</div>
</div>
</template>
<script setup>
import { computed } from 'vue'
const currentTab = defineModel()
const emit = defineEmits(['switch'])
const props = defineProps({ tabs: { type: Array, required: true } })
const tabs = computed(() => {
if (typeof props.tabs?.[0] == 'string') {
return props.tabs.map((label) => ({ label, value: label }))
}
return props.tabs
})
function handleClick(tab) {
if (tab.disabled) return
currentTab.value = tab.value
emit('switch', tab)
}
</script>
|
2302_79757062/insights
|
frontend/src/components/Tabs.vue
|
Vue
|
agpl-3.0
| 962
|
<template>
<div class="m-2 flex transition duration-200 ease-out">
<div :class="['w-[22rem] rounded bg-white p-3 shadow-md', variantClasses]">
<div class="flex items-start">
<div v-if="icon || variantIcon" class="mr-2 pt-1">
<FeatherIcon
:name="icon || variantIcon"
:class="['h-4 w-4 rounded-full', variantIconClasses, iconClasses]"
/>
</div>
<div>
<slot>
<p class="text-base font-medium leading-5 text-gray-900">
{{ title }}
</p>
<p v-if="message" class="text-base text-gray-600">
<span v-if="containsHTML" v-html="message"></span>
<span v-else>{{ message }}</span>
</p>
</slot>
</div>
<div class="ml-auto pl-2">
<slot name="actions">
<!-- <button class="grid h-5 w-5 place-items-center rounded hover:bg-gray-100">
<FeatherIcon name="x" class="h-4 w-4 text-gray-700" />
</button> -->
</slot>
</div>
</div>
</div>
</div>
</template>
<script>
import { FeatherIcon } from 'frappe-ui'
const variant = ['success', 'info', 'warning', 'error']
export default {
name: 'Toast',
props: {
icon: {
type: String,
},
iconClasses: {
type: String,
},
title: {
type: String,
},
message: {
type: String,
},
variant: {
type: String,
default: 'info',
},
},
components: {
FeatherIcon,
},
data() {
return {
shown: false,
}
},
computed: {
containsHTML() {
return this.message?.includes('<')
},
variantClasses() {
if (this.variant === 'success') {
return 'bg-green-50'
}
if (this.variant === 'info') {
return 'bg-blue-50'
}
if (this.variant === 'warning') {
return 'bg-orange-50'
}
if (this.variant === 'error') {
return 'bg-red-50'
}
},
variantIcon() {
if (this.variant === 'success') {
return 'check'
}
if (this.variant === 'info') {
return 'info'
}
if (this.variant === 'warning') {
return 'alert-circle'
}
if (this.variant === 'error') {
return 'x'
}
},
variantIconClasses() {
if (this.variant === 'success') {
return 'text-white bg-green-600 p-0.5'
}
if (this.variant === 'info') {
return 'text-white bg-blue-600'
}
if (this.variant === 'warning') {
return 'text-white bg-orange-600'
}
if (this.variant === 'error') {
return 'text-white bg-red-600 p-0.5'
}
},
},
}
</script>
|
2302_79757062/insights
|
frontend/src/components/Toast.vue
|
Vue
|
agpl-3.0
| 2,395
|
<template>
<Popover trigger="hover" :hoverDelay="hoverDelay" :placement="placement">
<template #target>
<slot />
</template>
<template #body>
<slot name="body">
<div
class="w-fit rounded bg-gray-800 px-2 py-1 text-center text-xs text-white shadow-xl"
:class="bodyClasses"
>
{{ text }}
</div>
</slot>
</template>
</Popover>
</template>
<script>
export default {
name: 'Tooltip',
props: {
hoverDelay: {
default: 0.5,
},
placement: {
default: 'bottom',
},
text: {
type: String,
default: '',
},
bodyClasses: {
type: String,
default: '',
},
},
}
</script>
|
2302_79757062/insights
|
frontend/src/components/Tooltip.vue
|
Vue
|
agpl-3.0
| 634
|
<script setup></script>
<template>
<div class="flex h-14 items-center justify-between border-b bg-white px-3"></div>
</template>
|
2302_79757062/insights
|
frontend/src/components/Topbar.vue
|
Vue
|
agpl-3.0
| 130
|
<script setup>
import { slideDownTransition } from '@/utils/transitions'
import { createPopper } from '@popperjs/core'
import { whenever } from '@vueuse/core'
import { computed, onBeforeUnmount, onMounted, ref } from 'vue'
const emit = defineEmits(['update:show'])
const props = defineProps({
show: { type: Boolean, default: undefined },
placement: { type: String, default: 'bottom-start' },
targetElement: { type: Object, required: true },
transition: { type: Object, default: slideDownTransition },
autoClose: { type: Boolean, default: true },
})
const showPropPassed = props.show !== undefined
const _show = ref(false)
const show = computed({
get: () => (showPropPassed ? props.show : _show.value),
set: (value) => (showPropPassed ? emit('update:show', value) : (_show.value = value)),
})
if (!document.getElementById('frappeui-popper-root')) {
const root = document.createElement('div')
root.id = 'frappeui-popper-root'
document.body.appendChild(root)
}
let popper = null
const popover = ref(null)
const toggle = () => (show.value = !show.value)
const open = () => (show.value = true)
const close = () => (show.value = false)
onMounted(() => {
if (!props.targetElement) {
console.warn('Popover: targetElement is required')
return
}
popper = createPopper(props.targetElement, popover.value, {
placement: props.placement,
modifiers: [
{
name: 'offset',
options: {
offset: [0, 8],
},
},
],
})
updatePosition()
window.addEventListener('resize', updatePosition)
window.addEventListener('scroll', updatePosition)
props.targetElement.addEventListener('click', open)
props.targetElement.addEventListener('focus', open)
if (props.autoClose) document.addEventListener('click', handleClickOutside)
})
const handleClickOutside = (e) => {
const insidePopover = popover.value.contains(e.target)
if (insidePopover) return
const insideTarget = props.targetElement.contains(e.target)
if (insideTarget) return
const popoverRoot = document.getElementById('frappeui-popper-root')
const insidePopoverRoot = popoverRoot.contains(e.target)
if (insidePopoverRoot) return
close()
}
const updatePosition = () => show.value && popper?.update()
whenever(show, updatePosition)
onBeforeUnmount(() => {
popper?.destroy()
window.removeEventListener('resize', updatePosition)
window.removeEventListener('scroll', updatePosition)
props.targetElement.removeEventListener('click', toggle)
props.targetElement.removeEventListener('focus', open)
if (props.autoClose) document.removeEventListener('click', handleClickOutside)
})
defineExpose({ toggle, open, close, isOpen: show })
</script>
<template>
<teleport to="#frappeui-popper-root">
<div ref="popover" class="z-[100]">
<transition v-bind="transition">
<div v-show="show">
<slot v-bind="{ toggle }"> </slot>
</div>
</transition>
</div>
</teleport>
</template>
|
2302_79757062/insights
|
frontend/src/components/UsePopover.vue
|
Vue
|
agpl-3.0
| 2,886
|
<script setup>
import { onMounted, ref, onBeforeUnmount, computed } from 'vue'
import UsePopover from './UsePopover.vue'
const props = defineProps({
content: { type: String, default: null },
targetElement: { type: Object, required: true },
placement: { type: String, default: 'top' },
hoverDelay: { type: Number, default: 0.5 },
})
const popover = ref(null)
let openTimer = null
let closeTimer = null
const listeners = {
mouseenter: () => {
closeTimer && (closeTimer = clearTimeout(closeTimer)) // clear and reset the timer
openTimer = setTimeout(() => popover.value.open(), props.hoverDelay * 1000)
},
mouseleave: () => {
openTimer && (openTimer = clearTimeout(openTimer)) // clear and reset the timer
closeTimer = setTimeout(() => popover.value.close(), props.hoverDelay * 1000)
},
}
const isVisible = computed(() => popover.value?.isOpen)
onMounted(() => {
props.targetElement.addEventListener('mouseenter', listeners.mouseenter)
props.targetElement.addEventListener('mouseleave', listeners.mouseleave)
})
onBeforeUnmount(() => {
props.targetElement.removeEventListener('mouseenter', listeners.mouseenter)
props.targetElement.removeEventListener('mouseleave', listeners.mouseleave)
})
</script>
<template>
<UsePopover ref="popover" :targetElement="props.targetElement" :placement="props.placement">
<slot name="content" v-bind="{ visible: isVisible }">
<div
v-if="props.content"
class="z-10 rounded border border-gray-100 bg-gray-800 px-2 py-1 text-xs text-white shadow-xl"
>
{{ props.content }}
</div>
</slot>
</UsePopover>
</template>
|
2302_79757062/insights
|
frontend/src/components/UseTooltip.vue
|
Vue
|
agpl-3.0
| 1,590
|
<script setup>
import ContentEditable from '@/components/ContentEditable.vue'
import VueGridLayout from '@/dashboard/VueGridLayout.vue'
import useDashboard from '@/dashboard/useDashboard'
import BaseLayout from '@/layouts/BaseLayout.vue'
import { updateDocumentTitle } from '@/utils'
import widgets from '@/widgets/widgets'
import { debounce } from 'frappe-ui'
import { computed, provide, ref } from 'vue'
import DashboardEmptyState from './DashboardEmptyState.vue'
import DashboardItem from './DashboardItem.vue'
import DashboardNavbarButtons from './DashboardNavbarButtons.vue'
import DashboardQueryOption from './DashboardQueryOption.vue'
import DashboardSidebarWidgets from './DashboardWidgetsOptions.vue'
import UseDropZone from './UseDropZone.vue'
const props = defineProps({
name: { type: String, required: true },
})
const dashboard = useDashboard(props.name)
provide('dashboard', dashboard)
const draggingWidget = ref(false)
function addWidget(dropEvent) {
const initialXandY = calcInitialXY(dropEvent)
draggingWidget.value = false
const widgetType = dashboard.draggingWidget?.type
if (widgetType) {
const itemID = Math.floor(Math.random() * 1000000)
dashboard.addItem({
item_id: itemID,
item_type: widgetType,
initialX: initialXandY.x,
initialY: initialXandY.y,
})
dashboard.setCurrentItem(itemID)
dashboard.draggingWidget = null
}
}
const gridLayout = ref(null)
function calcInitialXY({ x, y }) {
const colWidth = gridLayout.value.getBoundingClientRect().width / 20
const rowHeight = 30
return {
x: Math.round(x / colWidth),
y: Math.round(y / rowHeight),
}
}
const pageMeta = computed(() => {
return {
title: dashboard.doc.title || props.name,
subtitle: 'Dashboard',
}
})
updateDocumentTitle(pageMeta)
const debouncedUpdateTitle = debounce((value) => dashboard.updateTitle(value), 500)
</script>
<template>
<BaseLayout v-if="dashboard.doc.name">
<template #navbar>
<div class="flex flex-shrink-0 items-center space-x-4">
<ContentEditable
class="rounded-sm text-lg font-medium !text-gray-800 focus:ring-2 focus:ring-gray-700 focus:ring-offset-4"
:class="[dashboard.editing ? '' : 'cursor-default']"
:value="dashboard.doc.title"
:disabled="!dashboard.editing"
@change="dashboard.updateTitle($event)"
placeholder="Untitled Dashboard"
></ContentEditable>
</div>
<DashboardNavbarButtons />
</template>
<template #content>
<div class="h-full w-full overflow-y-auto p-2">
<div
ref="gridLayout"
class="dashboard relative flex h-fit min-h-screen w-full flex-1 flex-col"
>
<UseDropZone
v-if="dashboard.editing && draggingWidget"
class="absolute left-0 top-0 z-10 h-full w-full"
:onDrop="addWidget"
:showCollision="true"
colliderClass=".dashboard-item"
:ghostWidth="(dashboard.draggingWidget?.defaultWidth || 4) * 50.8"
:ghostHeight="(dashboard.draggingWidget?.defaultHeight || 2) * 30"
>
</UseDropZone>
<VueGridLayout
class="h-fit w-full"
:class="[dashboard.editing ? 'mb-[20rem] ' : '']"
:items="dashboard.doc.items"
:disabled="!dashboard.editing"
v-model:layouts="dashboard.itemLayouts"
>
<template #item="{ item }">
<DashboardItem :item="item" :key="item.item_id" />
</template>
</VueGridLayout>
<DashboardEmptyState
v-if="!dashboard.doc.items.length"
class="absolute left-1/2 top-1/2 mx-auto -translate-x-1/2 -translate-y-1/2 transform"
/>
</div>
</div>
</template>
<template #sidebar v-if="dashboard.editing && dashboard.sidebar.open">
<div class="w-[21rem] overflow-y-auto border-l bg-white p-3 px-4 shadow-sm">
<div v-if="!dashboard.currentItem">
<div class="mb-3 font-semibold text-gray-800">Widgets</div>
<DashboardSidebarWidgets @dragChange="draggingWidget = $event" />
</div>
<div v-else class="space-y-4">
<!-- Widget Options -->
<div class="flex items-center text-lg font-medium text-gray-500">
<Button
variant="outline"
icon="arrow-left"
@click="dashboard.currentItem = undefined"
></Button>
<div class="ml-2 text-gray-800">Back</div>
</div>
<Input
type="select"
label="Widget Type"
class="w-full"
:options="widgets.list.map((widget) => widget.type)"
v-model="dashboard.currentItem.item_type"
/>
<DashboardQueryOption
v-if="dashboard.isChart(dashboard.currentItem)"
v-model="dashboard.currentItem.options.query"
@update:model-value="dashboard.loadCurrentItemQuery"
/>
<component
v-if="widgets.getOptionComponent(dashboard.currentItem.item_type)"
:is="widgets.getOptionComponent(dashboard.currentItem.item_type)"
v-model="dashboard.currentItem.options"
:columns="dashboard.currentItem.query?.results.columns"
:key="
dashboard.currentItem.item_id &&
dashboard.currentItem.item_type &&
dashboard.currentItem.query?.doc?.name
"
/>
<div class="flex space-x-2">
<Button
iconLeft="refresh-ccw"
variant="outline"
@click="dashboard.resetOptions(dashboard.currentItem)"
>
Reset Options
</Button>
<Button
iconLeft="trash"
variant="outline"
class="ml-auto text-red-500"
@click="dashboard.removeItem(dashboard.currentItem)"
>
Delete Widget
</Button>
</div>
</div>
</div>
</template>
</BaseLayout>
</template>
|
2302_79757062/insights
|
frontend/src/dashboard/Dashboard.vue
|
Vue
|
agpl-3.0
| 5,531
|
<script setup>
import { inject } from 'vue'
const dashboard = inject('dashboard')
</script>
<template>
<div class="flex flex-1 flex-col items-center justify-center space-y-1">
<div class="text-base font-light text-gray-600">
{{
!dashboard.editing ? "You haven't added any charts." : 'Drag and drop charts here.'
}}
</div>
<div
v-if="!dashboard.editing"
class="cursor-pointer text-sm font-light text-blue-500 hover:underline"
@click="dashboard.edit"
>
Add a chart
</div>
</div>
</template>
|
2302_79757062/insights
|
frontend/src/dashboard/DashboardEmptyState.vue
|
Vue
|
agpl-3.0
| 524
|
<script setup>
import UsePopover from '@/components/UsePopover.vue'
import { downloadImage } from '@/utils'
import useChartData from '@/widgets/useChartData'
import widgets from '@/widgets/widgets'
import { whenever } from '@vueuse/shared'
import { Maximize } from 'lucide-vue-next'
import { computed, inject, provide, reactive, ref, watch } from 'vue'
import DashboardItemActions from './DashboardItemActions.vue'
const dashboard = inject('dashboard')
const props = defineProps({
item: { type: Object, required: true },
})
let isChart = dashboard.isChart(props.item)
let chartFilters = isChart ? computed(() => dashboard.filtersByChart[props.item.item_id]) : null
let chartData = reactive({})
if (isChart) {
const query = computed(() => props.item.options.query)
chartData = useChartData({
resultsFetcher() {
return dashboard.getChartResults(props.item.item_id)
},
})
// load chart data
whenever(
query,
async () => {
await chartData.load(query.value)
setGuessedChart()
},
{ immediate: true }
)
dashboard.onRefresh(() => chartData.load(query.value))
dashboard.refreshChartFilters(props.item.item_id)
watch(chartFilters, () => chartData.load(query.value))
}
const itemRef = ref(null) // used for popover
const widget = ref(null)
provide('widgetRef', widget)
function setGuessedChart() {
if (!props.item.options.query) return
if (props.item.options.title) return
if (!props.item.item_type) return
if (
props.item.options.query == dashboard.currentItem?.options.query &&
!props.item.options.title
) {
props.item.options.title = dashboard.currentItem.query.doc.title
}
const guessedChart = chartData.getGuessedChart(props.item.item_type)
if (props.item.item_type !== guessedChart.type) return
props.item.options = {
...props.item.options,
...guessedChart.options,
title: props.item.options.title,
}
}
function openQueryInNewTab() {
window.open(`/insights/query/build/${props.item.options.query}`, '_blank')
}
const fullscreenDialog = ref(false)
const chartRef = ref(null)
const downloading = ref(false)
function downloadChartImage() {
if (!chartRef.value) {
$notify({
variant: 'error',
title: 'Chart container reference not found',
})
return
}
downloading.value = true
const title = props.item.options.title
downloadImage(chartRef.value.$el, `${title}.png`).then(() => {
downloading.value = false
})
}
</script>
<template>
<div class="dashboard-item h-full min-h-[60px] w-full p-2 [&>div:first-child]:h-full">
<div
ref="itemRef"
class="group relative flex h-full rounded"
:class="{
' bg-white shadow': dashboard.isChart(item),
'ring-2 ring-gray-700 ring-offset-2':
item.item_id === dashboard.currentItem?.item_id,
'cursor-grab': dashboard.editing,
}"
@click.prevent.stop="dashboard.setCurrentItem(item.item_id)"
>
<div
v-if="chartData.loading"
class="absolute inset-0 z-[10000] flex h-full w-full items-center justify-center rounded bg-white"
>
<LoadingIndicator class="w-6 text-gray-300" />
</div>
<component
ref="widget"
:class="[dashboard.editing ? 'pointer-events-none' : '']"
:is="widgets.getComponent(item.item_type)"
:item_id="item.item_id"
:data="chartData.data"
:options="item.options"
/>
<div class="absolute right-3 top-3 z-[10001] flex items-center">
<div v-if="chartFilters?.length">
<Tooltip :text="chartFilters.map((c) => c.label || c.column?.label).join(', ')">
<div
class="flex items-center space-x-1 rounded-full bg-gray-100 px-2 py-1 text-sm leading-3 text-gray-600"
>
<span>{{ chartFilters.length }}</span>
<FeatherIcon name="filter" class="h-3 w-3" @mousedown.prevent.stop="" />
</div>
</Tooltip>
</div>
<div v-if="!dashboard.editing && isChart" class="invisible group-hover:visible">
<Button variant="ghost" @click="fullscreenDialog = true">
<template #icon> <Maximize class="h-4 w-4" /> </template>
</Button>
</div>
<div
v-if="!dashboard.editing && item.options.query"
class="invisible -mb-1 -mt-1 flex cursor-pointer rounded p-1 text-gray-600 hover:bg-gray-100 group-hover:visible"
>
<FeatherIcon
name="external-link"
class="h-4 w-4"
@click="openQueryInNewTab(item)"
/>
</div>
</div>
</div>
<UsePopover
v-if="dashboard.editing && itemRef"
:targetElement="itemRef"
:show="dashboard.editing && dashboard.currentItem?.item_id === item.item_id"
placement="top-end"
>
<DashboardItemActions :item="item" />
</UsePopover>
<Dialog
v-if="item.item_type"
v-model="fullscreenDialog"
:options="{
size: '7xl',
}"
>
<template #body>
<div class="relative flex h-[40rem] w-full p-1">
<component
v-if="item.item_type"
ref="chartRef"
:is="widgets.getComponent(item.item_type)"
:options="item.options"
:data="chartData.data"
/>
<div class="absolute top-0 right-0 p-2">
<Button
variant="outline"
@click="downloadChartImage"
:loading="downloading"
icon="download"
>
</Button>
</div>
</div>
</template>
</Dialog>
</div>
</template>
|
2302_79757062/insights
|
frontend/src/dashboard/DashboardItem.vue
|
Vue
|
agpl-3.0
| 5,199
|
<script setup>
import { downloadImage } from '@/utils'
import { inject } from 'vue'
const props = defineProps({ item: Object })
const dashboard = inject('dashboard')
const widgetRef = inject('widgetRef')
const actions = [
{
icon: 'external-link',
label: 'Open Query',
hidden: (item) => item.item_type === 'Filter' || item.item_type === 'Text',
onClick(item) {
if (!item.options.query) return
window.open(`/insights/query/build/${item.options.query}`, '_blank')
},
},
{
icon: 'download',
label: 'Download',
hidden: (item) => item.item_type === 'Filter' || item.item_type === 'Text',
onClick() {
downloadImage(widgetRef.value.$el, `${props.item.options.title}.png`)
},
},
{
icon: 'trash',
label: 'Delete',
onClick: (item) => dashboard.removeItem(item),
},
]
</script>
<template>
<div class="flex cursor-pointer rounded bg-gray-800 p-1 shadow-sm">
<div
v-for="action in actions"
:key="action.label"
class="px-1 py-0.5"
:class="{ hidden: action.hidden && action.hidden(item) }"
@click="action.onClick(item)"
>
<FeatherIcon :name="action.icon" class="h-3.5 w-3.5 text-white" />
</div>
</div>
</template>
|
2302_79757062/insights
|
frontend/src/dashboard/DashboardItemActions.vue
|
Vue
|
agpl-3.0
| 1,167
|
<template>
<header class="sticky top-0 z-10 flex items-center justify-between bg-white px-5 py-2.5">
<PageBreadcrumbs class="h-7" :items="[{ label: 'Dashboards' }]" />
<div class="space-x-2.5">
<Button label="New Dashboard" variant="solid" @click="showDialog = true">
<template #prefix>
<Plus class="h-4 w-4" />
</template>
</Button>
</div>
</header>
<div class="flex flex-1 space-y-4 overflow-hidden bg-white px-5 py-2">
<div
v-if="dashboards?.list?.length"
class="flex flex-1 flex-col space-y-6 overflow-y-auto p-1"
>
<DashboardsGroup
v-if="favorites.length > 0"
:dashboards="favorites"
title="Favorites"
/>
<DashboardsGroup
v-if="settings.enable_permissions"
:dashboards="privates"
title="Private"
/>
<DashboardsGroup :dashboards="sortedDashboards" title="All" :enableSearch="true" />
</div>
<div v-else class="flex flex-1 flex-col items-center justify-center space-y-1">
<div class="text-base font-light text-gray-600">
You haven't created any dashboards yet.
</div>
<div
class="cursor-pointer text-sm font-light text-blue-500 hover:underline"
@click="showDialog = true"
>
Create a new dashboard
</div>
</div>
</div>
<Dialog :options="{ title: 'New Dashboard' }" v-model="showDialog">
<template #body-content>
<Input
type="text"
label="Title"
placeholder="Enter a suitable title..."
v-model="newDashboardTitle"
/>
</template>
<template #actions>
<Button
class="w-full"
variant="solid"
@click="createDashboard"
:loading="dashboards.creating"
>
Create
</Button>
</template>
</Dialog>
</template>
<script setup>
import PageBreadcrumbs from '@/components/PageBreadcrumbs.vue'
import useDashboards from '@/dashboard/useDashboards'
import settingsStore from '@/stores/settingsStore'
import { updateDocumentTitle } from '@/utils'
import { Plus } from 'lucide-vue-next'
import { computed, ref } from 'vue'
import { useRoute, useRouter } from 'vue-router'
import DashboardsGroup from './DashboardListGroup.vue'
const settings = settingsStore().settings
const dashboards = useDashboards()
dashboards.reload()
const sortedDashboards = computed(() => {
// sort alphabetically
return dashboards.list.sort((a, b) => a.title.localeCompare(b.title))
})
const favorites = computed(() => {
return dashboards.list.filter((dashboard) => dashboard.is_favourite)
})
const privates = computed(() => {
return dashboards.list.filter((dashboard) => dashboard.is_private)
})
const showDialog = ref(false)
const route = useRoute()
if (route.hash == '#new') {
showDialog.value = true
}
const newDashboardTitle = ref('')
const router = useRouter()
async function createDashboard() {
const name = await dashboards.create(newDashboardTitle.value)
showDialog.value = false
newDashboardTitle.value = ''
router.push(`/dashboard/${name}`)
}
const pageMeta = ref({ title: 'Dashboards' })
updateDocumentTitle(pageMeta)
</script>
|
2302_79757062/insights
|
frontend/src/dashboard/DashboardList.vue
|
Vue
|
agpl-3.0
| 2,988
|
<script setup>
import useDashboards from '@/dashboard/useDashboards'
import { getShortNumber } from '@/utils'
const props = defineProps({
dashboard: { type: Object, required: true },
})
const dashboards = useDashboards()
function toggleFavourite() {
dashboards.toggleLike(props.dashboard)
}
</script>
<template>
<router-link
class="flex w-full cursor-pointer"
:to="{
name: 'Dashboard',
params: { name: dashboard.name },
}"
>
<div
class="flex h-full flex-1 flex-col space-y-3 overflow-hidden rounded bg-white p-4 shadow"
>
<div class="flex w-full items-center justify-between overflow-hidden">
<div class="flex h-6 items-center overflow-hidden">
<div class="flex-1 truncate text-xl font-medium text-gray-800">
{{ dashboard.title }}
</div>
<span
class="ml-1 flex h-5 w-5 flex-shrink-0 cursor-pointer items-center justify-center rounded hover:bg-gray-100"
:class="{
'text-yellow-500': dashboard.is_favourite,
'text-gray-600': !dashboard.is_favourite,
}"
@click.prevent.stop="toggleFavourite()"
>
{{ dashboard.is_favourite ? '★' : '☆' }}
</span>
</div>
<FeatherIcon name="arrow-right" class="h-4 w-4 text-gray-600" />
</div>
<div class="flex w-full items-end justify-between">
<div class="flex gap-2">
<div class="flex h-6 items-center text-sm text-gray-600">
<FeatherIcon name="eye" class="mr-1 h-4 w-4" />
{{ getShortNumber(dashboard.view_count) }}
</div>
<div class="flex h-6 items-center text-sm text-gray-600">
<FeatherIcon name="bar-chart-2" class="mr-1 h-4 w-4" />
{{ dashboard.charts.length }}
</div>
</div>
<div class="flex h-6 items-center text-sm text-gray-600">
Updated {{ dashboard.modified_from_now }}
</div>
</div>
</div>
</router-link>
</template>
|
2302_79757062/insights
|
frontend/src/dashboard/DashboardListCard.vue
|
Vue
|
agpl-3.0
| 1,856
|
<script setup>
import { ref, computed } from 'vue'
import DashboardCard from './DashboardListCard.vue'
const props = defineProps({
title: { type: String, required: true },
dashboards: { type: Array, required: true },
enableSearch: { type: Boolean, default: false },
})
const searchTerm = ref('')
const filteredDashboards = computed(() => {
if (!searchTerm.value) return props.dashboards
return props.dashboards.filter((dashboard) => {
return dashboard.title.toLowerCase().includes(searchTerm.value.toLowerCase())
})
})
</script>
<template>
<div>
<div class="flex items-center">
<div class="text-xl font-medium text-gray-700">{{ title }}</div>
<Badge variant="outline" :label="String(dashboards.length)" class="ml-2" />
<div v-if="enableSearch" class="ml-auto flex items-center">
<Input
ref="searchInput"
v-model="searchTerm"
iconLeft="search"
placeholder="Search..."
/>
</div>
</div>
<div class="mt-4 grid grid-cols-1 gap-4 md:grid-cols-2 lg:grid-cols-4">
<div class="col-span-1" v-for="dashboard in filteredDashboards">
<DashboardCard :key="dashboard.id" :dashboard="dashboard" />
</div>
<div
v-if="searchTerm && filteredDashboards.length === 0"
class="w-full text-center text-gray-600"
>
No dashboards found.
</div>
</div>
</div>
</template>
|
2302_79757062/insights
|
frontend/src/dashboard/DashboardListGroup.vue
|
Vue
|
agpl-3.0
| 1,334
|
<script setup>
import { downloadImage } from '@/utils'
import { inject, ref } from 'vue'
import { useRouter } from 'vue-router'
const dashboard = inject('dashboard')
const showDeleteDialog = ref(false)
const router = useRouter()
async function handleDelete() {
await dashboard.deleteDashboard()
showDeleteDialog.value = false
router.push({ name: 'Dashboards' })
}
async function downloadDashboardImage() {
const $el = document.querySelector('.dashboard')
await downloadImage($el, `${dashboard.doc.title}.png`)
}
</script>
<template>
<Dropdown
v-if="dashboard.doc"
placement="left"
:button="{ icon: 'more-vertical', variant: 'outline' }"
:options="[
{
label: 'Export as PNG',
variant: 'outline',
icon: 'download',
onClick: () => downloadDashboardImage(),
},
{
label: 'Delete',
variant: 'outline',
icon: 'trash-2',
onClick: () => (showDeleteDialog = true),
},
]"
/>
<Dialog
v-model="showDeleteDialog"
:dismissable="true"
:options="{
title: 'Delete Dashboard',
message: 'Are you sure you want to delete this dashboard?',
icon: { name: 'trash', variant: 'solid', theme: 'red' },
actions: [
{ label: 'Cancel', variant: 'outline', onClick: () => (showDeleteDialog = false) },
{ label: 'Yes', variant: 'solid', theme: 'red', onClick: handleDelete },
],
}"
>
</Dialog>
</template>
|
2302_79757062/insights
|
frontend/src/dashboard/DashboardMenuButton.vue
|
Vue
|
agpl-3.0
| 1,372
|
<script setup>
import { useMagicKeys, whenever } from '@vueuse/core'
import { inject } from 'vue'
import DashboardMenuButton from './DashboardMenuButton.vue'
import DashboardShareButton from './DashboardShareButton.vue'
const dashboard = inject('dashboard')
const keys = useMagicKeys()
const cmdE = keys['Meta+E']
whenever(cmdE, dashboard.edit)
const cmdS = keys['Meta+S']
whenever(cmdS, dashboard.save)
const cmdD = keys['Meta+D']
whenever(cmdD, dashboard.discardChanges)
</script>
<template>
<div class="flex flex-shrink-0 justify-end space-x-2">
<DashboardShareButton v-if="!dashboard.editing && dashboard.canShare" />
<Button variant="outline" v-if="!dashboard.editing" @click="dashboard.refresh">
Refresh
</Button>
<Button v-if="dashboard.editing" variant="outline" @click="dashboard.discardChanges">
Cancel
</Button>
<Button v-if="!dashboard.editing" variant="outline" @click="dashboard.edit"> Edit </Button>
<Button v-else variant="solid" @click="dashboard.save" :loading="dashboard.loading">
Save
</Button>
<DashboardMenuButton />
</div>
</template>
|
2302_79757062/insights
|
frontend/src/dashboard/DashboardNavbarButtons.vue
|
Vue
|
agpl-3.0
| 1,089
|
<script setup>
import { Dialog as HDialog, DialogOverlay, TransitionChild, TransitionRoot } from '@headlessui/vue'
import { computed } from 'vue'
import DashboardQueryEditor from './DashboardQueryEditor.vue'
const emit = defineEmits(['update:show', 'close'])
const props = defineProps({
show: { type: Boolean, required: true },
query: { type: String, required: true },
})
const show = computed({
get: () => props.show,
set: (value) => {
emit('update:show', value)
if (!value) emit('close')
},
})
function openQueryInNewTab() {
window.open(`/insights/query/build/${props.query}`, '_blank')
}
</script>
<template>
<TransitionRoot as="template" :show="show">
<HDialog as="div" class="fixed inset-0 z-10 overflow-y-auto" @close="show = false">
<div class="flex h-full min-h-screen flex-col items-center p-10">
<TransitionChild
as="template"
enter="ease-out duration-300"
enter-from="opacity-0"
enter-to="opacity-100"
leave="ease-in duration-200"
leave-from="opacity-100"
leave-to="opacity-0"
>
<DialogOverlay
class="fixed inset-0 bg-gray-500 bg-opacity-75 transition-opacity"
/>
</TransitionChild>
<TransitionChild
as="template"
enter="ease-out duration-300"
enter-from="opacity-0 translate-y-4 sm:-translate-y-12 sm:scale-95"
enter-to="opacity-100 translate-y-0 sm:scale-100"
leave="ease-in duration-200"
leave-from="opacity-100 translate-y-0 sm:scale-100"
leave-to="opacity-0 translate-y-4 sm:translate-y-0 sm:scale-95"
>
<div
class="flex h-full w-full max-w-7xl transform gap-2 overflow-hidden text-base transition-all"
>
<div v-if="show" class="flex-1 overflow-hidden rounded bg-white shadow-xl">
<DashboardQueryEditor :name="props.query" class="h-full" />
</div>
<div v-if="show" class="flex flex-shrink-0 flex-col space-y-2">
<Button
apperance="white"
icon="x"
class="shadow-xl"
@click="show = false"
></Button>
<Button
apperance="white"
icon="maximize-2"
class="shadow-xl"
@click="openQueryInNewTab"
></Button>
</div>
</div>
</TransitionChild>
</div>
</HDialog>
</TransitionRoot>
</template>
|
2302_79757062/insights
|
frontend/src/dashboard/DashboardQueryDialog.vue
|
Vue
|
agpl-3.0
| 2,274
|
<script setup>
import Query from '@/query/Query.vue'
import QueryHeader from '@/query/QueryHeader.vue'
const props = defineProps(['name'])
</script>
<template>
<div class="flex w-full flex-col p-2">
<Query :name="props.name" :hideTabs="true" />
</div>
</template>
|
2302_79757062/insights
|
frontend/src/dashboard/DashboardQueryEditor.vue
|
Vue
|
agpl-3.0
| 269
|
<script setup>
import Query from '@/query/Query.vue'
import useQueryStore from '@/stores/queryStore'
import { computed, ref } from 'vue'
const emit = defineEmits(['update:modelValue'])
const props = defineProps(['modelValue'])
const queryName = computed({
get: () => props.modelValue,
set: (value) => emit('update:modelValue', value),
})
const queryStore = useQueryStore()
const queryOptions = computed(() =>
queryStore.list.map((query) => ({
label: query.title,
value: query.name,
}))
)
function openQueryInNewTab() {
window.open(`/insights/query/build/${queryName.value}`, '_blank')
}
const showCreateQuery = ref(false)
const newQuery = ref(null)
async function createQuery() {
newQuery.value = await queryStore.create({ is_assisted_query: 1 })
showCreateQuery.value = true
}
async function deleteQuery() {
await queryStore.delete(newQuery.value.name)
showCreateQuery.value = false
newQuery.value = null
}
async function selectQuery() {
await queryStore.reload()
emit('update:modelValue', newQuery.value.name)
showCreateQuery.value = false
newQuery.value = null
}
</script>
<template>
<div class="space-y-2">
<span class="mb-2 block text-sm leading-4 text-gray-700">Query</span>
<div class="relative">
<Autocomplete
placeholder="Select a query"
:options="queryOptions"
:allowCreate="true"
@createOption="createQuery"
:modelValue="queryName"
@update:modelValue="queryName = $event?.value"
/>
<div
v-if="queryName"
class="absolute right-0 top-0 flex h-full w-8 cursor-pointer items-center justify-center rounded bg-gray-100"
@click="openQueryInNewTab"
>
<FeatherIcon
name="maximize-2"
class="h-3.5 w-3.5 text-gray-600 hover:text-gray-900"
/>
</div>
</div>
</div>
<Dialog v-model="showCreateQuery" :dismissable="false" :options="{ size: '2xl' }">
<template #body>
<div v-if="newQuery" class="flex h-[46rem] w-full flex-col justify-end p-4 text-base">
<Query :name="newQuery.name" :hideTabs="true" />
<div class="ml-auto space-x-2 px-2">
<Button
variant="solid"
theme="red"
@click="deleteQuery"
:loading="queryStore.deleting"
>
Discard
</Button>
<Button variant="solid" @click="selectQuery"> Done </Button>
</div>
</div>
</template>
</Dialog>
</template>
|
2302_79757062/insights
|
frontend/src/dashboard/DashboardQueryOption.vue
|
Vue
|
agpl-3.0
| 2,329
|
<script setup>
import ShareDialog from '@/components/ShareDialog.vue'
import { inject, ref } from 'vue'
const dashboard = inject('dashboard')
const showShareDialog = ref(false)
</script>
<template>
<Badge v-if="dashboard.isPrivate" theme="yellow"> Private </Badge>
<Button variant="outline" @click="showShareDialog = true"> Share </Button>
<ShareDialog
v-if="dashboard.doc"
v-model:show="showShareDialog"
:resource-type="dashboard.doc.doctype"
:resource-name="dashboard.doc.name"
:allow-public-access="true"
:isPublic="Boolean(dashboard.doc.is_public)"
@togglePublicAccess="dashboard.togglePublicAccess"
/>
</template>
|
2302_79757062/insights
|
frontend/src/dashboard/DashboardShareButton.vue
|
Vue
|
agpl-3.0
| 641
|
<script setup>
import widgets from '@/widgets/widgets'
import { inject } from 'vue'
const dashboard = inject('dashboard')
const emit = defineEmits(['dragChange'])
function onDragStart(widget) {
emit('dragChange', widget)
dashboard.draggingWidget = widget
}
</script>
<template>
<div class="grid grid-cols-3 gap-3">
<template v-for="widget in widgets.list" :key="widget.type">
<div
:draggable="true"
class="cursor-grab rounded border border-gray-100 bg-gray-50 pb-2 pt-1 text-center"
@dragend="emit('dragChange', false)"
@dragstart="onDragStart(widget)"
>
<div class="flex w-full items-center justify-center p-2 text-center">
<component
:is="widgets.getIcon(widget.type)"
class="h-6 w-6"
:stroke-width="1"
/>
</div>
<span>{{ widget.type }}</span>
</div>
</template>
</div>
</template>
|
2302_79757062/insights
|
frontend/src/dashboard/DashboardWidgetsOptions.vue
|
Vue
|
agpl-3.0
| 858
|
<script setup>
import VueGridLayout from '@/dashboard/VueGridLayout.vue'
import usePublicDashboard from '@/dashboard/usePublicDashboard'
import BaseLayout from '@/layouts/BaseLayout.vue'
import { provide } from 'vue'
import DashboardEmptyState from './DashboardEmptyState.vue'
import PublicDashboardItem from './PublicDashboardItem.vue'
const props = defineProps({ public_key: String })
const dashboard = usePublicDashboard(props.public_key)
provide('dashboard', dashboard)
</script>
<template>
<BaseLayout>
<template #navbar>
<div class="whitespace-nowrap px-1.5 text-2xl font-medium">
{{ dashboard.doc.title }}
</div>
</template>
<template #content>
<div class="h-full w-full overflow-y-auto bg-white px-4 py-2">
<div
ref="gridLayout"
class="dashboard relative flex h-fit min-h-screen w-full flex-1 flex-col"
>
<VueGridLayout
:key="JSON.stringify(dashboard.itemLayouts)"
class="h-fit w-full"
:items="dashboard.doc.items"
:disabled="true"
v-model:layouts="dashboard.itemLayouts"
>
<template #item="{ item }">
<PublicDashboardItem :item="item" :key="item.item_id" />
</template>
</VueGridLayout>
<DashboardEmptyState
v-if="!dashboard.doc.items.length"
class="absolute left-1/2 top-1/2 mx-auto -translate-x-1/2 -translate-y-1/2 transform"
/>
</div>
</div>
</template>
</BaseLayout>
</template>
|
2302_79757062/insights
|
frontend/src/dashboard/PublicDashboard.vue
|
Vue
|
agpl-3.0
| 1,431
|
<script setup>
import InvalidWidget from '@/widgets/InvalidWidget.vue'
import useChartData from '@/widgets/useChartData'
import widgets from '@/widgets/widgets'
import { whenever } from '@vueuse/shared'
import { computed, inject, reactive, watch } from 'vue'
const dashboard = inject('dashboard')
const props = defineProps({
item: { type: Object, required: true },
})
let chartFilters = null
let isChart = dashboard.isChart(props.item)
let chartData = reactive({})
if (isChart) {
const query = computed(() => props.item.options.query)
chartData = useChartData({
resultsFetcher() {
return dashboard.getChartResults(props.item.item_id)
},
})
whenever(query, () => chartData.load(query.value), { immediate: true })
dashboard.onRefresh(() => chartData.load(query.value))
chartFilters = computed(() => dashboard.filtersByChart[props.item.item_id])
dashboard.refreshChartFilters(props.item.item_id)
watch(chartFilters, () => {
chartData.load(props.item.options.query)
})
}
</script>
<template>
<div class="dashboard-item h-full min-h-[60px] w-full p-1.5">
<div class="flex h-full w-full">
<div
class="group relative flex h-full w-full rounded"
:class="{
'bg-white shadow': item.item_type !== 'Filter' && item.item_type !== 'Text',
}"
>
<div
v-if="chartData.loading"
class="absolute inset-0 z-[10000] flex h-full w-full items-center justify-center rounded bg-white"
>
<LoadingIndicator class="w-6 text-gray-300" />
</div>
<component
ref="widget"
:is="widgets.getComponent(item.item_type)"
:data="chartData.data"
:item_id="item.item_id"
:options="item.options"
>
<template #placeholder>
<InvalidWidget
class="absolute"
title="Insufficient options"
icon="settings"
:message="null"
icon-class="text-gray-500"
/>
</template>
</component>
</div>
</div>
</div>
</template>
|
2302_79757062/insights
|
frontend/src/dashboard/PublicDashboardItem.vue
|
Vue
|
agpl-3.0
| 1,936
|
<script setup>
import DatePickerFlat from '@/components/Controls/DatePickerFlat.vue'
import DateRangePickerFlat from '@/components/Controls/DateRangePickerFlat.vue'
import TimespanPickerFlat from '@/components/Controls/TimespanPickerFlat.vue'
import { fieldtypesToIcon, formatDate, isEmptyObj } from '@/utils'
import { getOperatorOptions } from '@/utils/'
import { Combobox, ComboboxInput, ComboboxOption, ComboboxOptions } from '@headlessui/vue'
import { call, debounce } from 'frappe-ui'
import { computed, inject, reactive, ref, watch } from 'vue'
const emit = defineEmits(['apply', 'reset'])
const props = defineProps({
label: String,
column: Object,
operator: Object,
value: Object,
disableColumns: Boolean,
})
const columns = ref([])
const operators = computed(() => getOperatorOptions(props.column?.type))
const filter = reactive({
type: 'simple',
label: props.label,
column: props.column,
operator: props.operator,
value: props.value,
})
watch(
() => props,
() => {
filter.label = props.label
filter.column = props.column
filter.operator = props.operator
filter.value = props.value
},
{ immediate: true, deep: true }
)
watch(
() => filter.operator,
(operator) => {
if (operator && ['in', 'not_in'].includes(operator.value) && !filter.value) {
filter.value = []
}
},
{ immediate: true }
)
const isOpen = ref(false)
const applyDisabled = computed(() => {
return isEmptyObj(filter.column) || isEmptyObj(filter.operator) || isEmptyObj(filter.value)
})
function applyFilter() {
if (applyDisabled.value) return
emit('apply', filter)
}
const selecting = computed(() => {
if (!filter.column) return 'column'
if (!filter.operator) return 'operator'
return 'value'
})
const showDatePicker = computed(() => {
return (
['Date', 'Datetime'].includes(filter.column?.type) &&
['=', '!=', '>', '>=', '<', '<=', 'between'].includes(filter.operator?.value)
)
})
const showTimespanPicker = computed(
() =>
['Date', 'Datetime'].includes(filter.column?.type) && filter.operator?.value === 'timespan'
)
const showValuePicker = computed(
() =>
['=', '!=', 'is', 'in', 'not_in'].includes(filter.operator?.value) &&
filter.column?.type == 'String'
)
const dashboard = inject('dashboard')
const item_id = inject('item_id')
const columnValues = ref([])
const checkAndFetchColumnValues = debounce(async function (search_text = '') {
if (
isEmptyObj(filter.column) ||
!['=', '!=', 'in', 'not_in'].includes(filter.operator?.value)
) {
return
}
if (filter.column?.type == 'String') {
let method = 'insights.api.data_sources.fetch_column_values'
let params = {
data_source: filter.column.data_source,
table: filter.column.table,
column: filter.column.column,
search_text,
}
if (dashboard.isPublic) {
method = 'insights.api.public.fetch_column_values_public'
params = {
public_key: dashboard.doc.public_key,
item_id: item_id,
}
}
columnValues.value = await call(method, params)
}
}, 300)
const values = computed(() => {
if (filter.operator?.value == 'is') {
return [
{ label: 'Set', value: 'set' },
{ label: 'Not Set', value: 'not set' },
]
}
return columnValues.value.map((value) => ({ label: value, value }))
})
watch(
() => showValuePicker.value,
(show) => show && checkAndFetchColumnValues(),
{ immediate: true }
)
const operatorLabel = computed(() => {
// if (['between', 'timespan'].includes(filter.operator?.value)) {
// return ':'
// }
// if (['in', 'not_in'].includes(filter.operator?.value)) {
// return filter.operator?.label
// }
return filter.operator?.label
})
function resetFilter() {
filter.column = props.disableColumns ? filter.column : null
filter.operator = null
filter.value = null
emit('reset')
}
const valueLabel = computed(() => filter.value?.label || filter.value?.value)
const isMultiple = computed(() => ['in', 'not_in'].includes(filter.operator?.value))
if (isMultiple.value && Array.isArray(filter.value)) {
// for backward compatibility
const values = filter.value[0]?.value ? filter.value.map((v) => v.value) : filter.value
filter.value = {
label: `${filter.value?.length} values`,
value: values,
}
}
const comboboxModelValue = computed({
get: () => {
return !isMultiple.value
? filter.value
: filter.value?.value?.map((value) => {
return { label: value, value }
})
},
set: (value) => {
if (!isMultiple.value) {
filter.value = value
return
}
const values = value
?.map((v) => v.value)
.reduce((acc, value) => {
// remove the ones which appear more than once
// since clicking on same value adds it twice
if (acc.includes(value)) {
return acc.filter((v) => v !== value)
}
return [...acc, value]
}, [])
const multipleValueLabel = values?.length > 1 ? `${values.length} values` : values?.[0]
filter.value = { label: multipleValueLabel, value: values }
},
})
function onComboboxValueChange(value, togglePopover) {}
function isValueSelected(value) {
if (isMultiple.value) {
return filter.value?.value?.includes(value)
}
return filter.value?.value === value
}
</script>
<template>
<div class="w-full [&:first-child]:w-full">
<Popover class="w-full" @close="applyFilter">
<template #target="{ togglePopover, isOpen }">
<div class="flex h-8 w-full rounded bg-white shadow">
<button
class="flex flex-1 flex-shrink-0 items-center gap-1.5 overflow-hidden rounded bg-white p-1 pl-3 text-base font-medium leading-5 text-gray-900"
@click="togglePopover"
>
<span v-if="!filter.column" class="font-normal text-gray-600">
Select a filter...
</span>
<div class="flex flex-shrink-0 items-center gap-1">
<component
:is="fieldtypesToIcon[filter.column?.type || 'String']"
class="h-4 w-4 flex-shrink-0 text-gray-600"
/>
<span class="truncate">{{ props.label || filter.column?.label }}</span>
</div>
<span v-if="filter.operator" class="flex-shrink-0 text-green-700">
{{ operatorLabel }}
</span>
<span v-if="filter.value" class="flex-shrink-0 truncate">
{{ valueLabel }}
</span>
</button>
<div class="flex h-8 items-center rounded">
<Button
v-if="isOpen || !applyDisabled"
icon="x"
variant="ghost"
@click.prevent.stop="resetFilter()"
/>
<FeatherIcon v-else name="chevron-down" class="mr-2 h-4 w-4" />
</div>
</div>
</template>
<template #body="{ togglePopover }">
<!-- Column Selector -->
<div
v-if="selecting === 'column'"
class="mt-2 flex w-fit flex-col rounded bg-white p-2 text-base shadow"
>
<div class="mb-1 px-1 text-sm text-gray-500">Select a column</div>
<div
class="cursor-pointer rounded px-2 py-1.5 hover:bg-gray-100"
v-for="column in columns"
:key="column.value"
@click.prevent.stop="filter.column = column"
>
{{ column.label }}
</div>
</div>
<!-- Operator Selector -->
<div
v-if="selecting === 'operator'"
class="mt-2 flex w-fit flex-col rounded bg-white p-2 text-base shadow"
>
<div class="mb-1 px-1 text-sm text-gray-500">Select an operator</div>
<div
class="cursor-pointer rounded px-2 py-1.5 hover:bg-gray-100"
v-for="operator in operators"
:key="operator.value"
@click.prevent.stop="filter.operator = operator"
>
{{ operator.label }}
</div>
</div>
<!-- Value Selector -->
<div
v-if="selecting === 'value'"
class="mt-2 flex w-fit flex-col rounded bg-white p-2 text-base shadow"
>
<Combobox
v-if="showValuePicker"
as="div"
nullable
:multiple="isMultiple"
v-model="comboboxModelValue"
@update:model-value="!isMultiple && togglePopover(false)"
>
<ComboboxInput
v-if="filter.operator?.value != 'is'"
autocomplete="off"
placeholder="Filter..."
@input="checkAndFetchColumnValues($event.target.value)"
class="form-input mb-2 block h-7 w-full border-gray-400 placeholder-gray-500"
/>
<ComboboxOptions static class="flex max-h-[20rem] flex-col overflow-hidden">
<div class="mb-1 px-1 text-sm text-gray-500">Select an option</div>
<div class="flex-1 overflow-y-auto">
<ComboboxOption
v-for="value in values"
:key="value.value"
:value="value"
v-slot="{ active }"
>
<div
class="flex cursor-pointer items-center rounded px-2 py-1.5 hover:bg-gray-100"
:class="{ 'bg-gray-100': active }"
>
<span>{{ value.label }}</span>
<FeatherIcon
v-if="isValueSelected(value.value)"
name="check"
class="ml-auto h-3.5 w-3.5"
/>
</div>
</ComboboxOption>
</div>
</ComboboxOptions>
</Combobox>
<TimespanPickerFlat
v-else-if="showTimespanPicker"
v-model="filter.value"
@change="togglePopover(false)"
/>
<DateRangePickerFlat
v-else-if="showDatePicker && filter.operator?.value == 'between'"
:value="filter.value?.value"
@change="
(dates) => {
filter.value = {
value: dates,
label: dates
.split(',')
.map((date) => formatDate(date))
.join(' to '),
}
togglePopover(false)
}
"
/>
<DatePickerFlat
v-else-if="showDatePicker"
:value="filter.value?.value"
@change="
(date) => {
filter.value = {
value: date,
label: formatDate(date),
}
togglePopover(false)
}
"
/>
<div v-else class="flex items-center gap-2">
<Input
:model-value="filter.value?.value"
@update:model-value="filter.value = { value: $event, label: $event }"
placeholder="Enter a value"
/>
<Button variant="solid" icon="check" @click="togglePopover(false)" />
</div>
</div>
</template>
</Popover>
</div>
</template>
|
2302_79757062/insights
|
frontend/src/dashboard/SimpleFilter.vue
|
Vue
|
agpl-3.0
| 10,057
|
<script setup>
import { computed, onMounted, onUnmounted, reactive, ref, watchEffect } from 'vue'
const props = defineProps({
onDrop: { type: Function },
showCollision: { type: Boolean, default: false },
colliderClass: { type: String, default: '.collider' },
ghostWidth: { type: Number, default: 128 },
ghostHeight: { type: Number, default: 48 },
})
const state = reactive({
isDragging: false,
collides: false,
ghost: { x: 0, y: 0 },
minLeft: 0,
maxLeft: 0,
minTop: 0,
maxTop: 0,
ghostWidth: computed(() => props.ghostWidth),
ghostHeight: computed(() => props.ghostHeight),
})
function updateBoundary() {
const rect = dropZone.value.getBoundingClientRect()
state.minLeft = rect.left + state.ghostWidth / 2
state.minTop = rect.top + state.ghostHeight / 2
state.maxLeft = rect.right - state.ghostWidth / 2
state.maxTop = rect.bottom - state.ghostHeight / 2
}
function updateGhostElement(event) {
if (!state.isDragging) return
let x = event.clientX
let y = event.clientY
if (x < state.minLeft) x = 0
else if (x > state.maxLeft) x = state.maxLeft - state.minLeft
else x = x - state.ghostWidth / 2 - (state.minLeft - state.ghostWidth / 2)
if (y < state.minTop) y = 0
else if (y > state.maxTop) y = state.maxTop - state.minTop
else y = y - state.ghostHeight / 2 - (state.minTop - state.ghostHeight / 2)
state.ghost.x = x
state.ghost.y = y
if (props.showCollision) checkCollision()
}
const checkCollision = function () {
requestAnimationFrame(() => {
const ghostElement = document.querySelector('.ghost-element')
if (!ghostElement) return
const ghostRect = ghostElement.getBoundingClientRect()
// check if the ghost element intersects with any element with collider class
const intersects = Array.from(document.querySelectorAll(props.colliderClass)).some((el) => {
const rect = el.getBoundingClientRect()
return (
ghostRect.left < rect.right &&
ghostRect.right > rect.left &&
ghostRect.top < rect.bottom &&
ghostRect.bottom > rect.top
)
})
state.collides = intersects
})
}
const dropZone = ref(null)
const dragEnter = async (event) => {
updateBoundary()
updateGhostElement(event)
state.isDragging = true
}
const dragend = () => (state.isDragging = false)
onMounted(() => {
updateBoundary()
window.addEventListener('dragover', updateGhostElement)
window.addEventListener('dragend', dragend)
resetPosition()
})
onUnmounted(() => {
window.removeEventListener('dragover', updateGhostElement)
window.removeEventListener('dragend', dragend)
})
const drop = (event) => {
state.isDragging = false
// consider rect scroll
const x = event.clientX - state.minLeft
const y = event.clientY - state.minTop
const collides = state.collides
props.onDrop && props.onDrop({ x, y, collides })
}
watchEffect(() => !state.isDragging && resetPosition())
function resetPosition() {
state.ghost.x = state.maxLeft - state.minLeft
state.ghost.y = 0
}
</script>
<template>
<div
ref="dropZone"
@dragenter.prevent="dragEnter"
@dragover.prevent="() => {}"
@drop.prevent="drop"
>
<div
class="ghost-element absolute rounded bg-gray-200/60 transition-all duration-75 ease-out"
:class="[props.showCollision && state.collides ? 'bg-red-200/60' : '']"
:style="{
opacity: state.isDragging ? 1 : 0,
transform: `translate(${state.ghost.x}px, ${state.ghost.y}px)`,
width: `${state.ghostWidth}px`,
height: `${state.ghostHeight}px`,
}"
></div>
</div>
</template>
|
2302_79757062/insights
|
frontend/src/dashboard/UseDropZone.vue
|
Vue
|
agpl-3.0
| 3,459
|
<template>
<grid-layout ref="grid" :layout="layouts" v-bind="options" @update:layout="layouts = $event">
<template #default="{ gridItemProps }">
<grid-item
v-for="(layout, index) in layouts"
v-bind="gridItemProps"
:key="layout.i"
:i="layout.i"
:x="layout.x"
:y="layout.y"
:w="layout.w"
:h="layout.h"
>
<slot name="item" :item="props.items[index]">
<pre class="h-full w-full rounded bg-white p-4 shadow">
{{ { i: layout.i, x: layout.x, y: layout.y, w: layout.w, h: layout.h } }}
</pre
>
</slot>
</grid-item>
</template>
</grid-layout>
</template>
<script setup>
import { reactive, ref, watch, watchEffect, computed } from 'vue'
const emit = defineEmits(['update:layouts'])
const props = defineProps({
items: { type: Array, required: true },
layouts: { type: Array, required: true },
disabled: { type: Boolean, default: false },
})
const options = reactive({
colNum: 20,
margin: [0, 0],
rowHeight: 30,
isDraggable: false,
isResizable: false,
responsive: true,
verticalCompact: false,
preventCollision: true,
useCssTransforms: true,
cols: { lg: 20, md: 20, sm: 20, xs: 1, xxs: 1 },
})
const layouts = computed({
get: () => props.layouts,
set: (value) => emit('update:layouts', value),
})
async function toggleEnable(disable) {
if (options.isDraggable === !disable && options.isResizable === !disable) return
options.isDraggable = !disable
options.isResizable = !disable
}
watch(() => props.disabled, toggleEnable, 200)
</script>
<style lang="scss">
.vgl-layout {
--vgl-placeholder-bg: #b1b1b1;
--vgl-placeholder-opacity: 20%;
--vgl-placeholder-z-index: 2;
--vgl-item-resizing-z-index: 3;
--vgl-item-resizing-opacity: 60%;
--vgl-item-dragging-z-index: 3;
--vgl-item-dragging-opacity: 100%;
--vgl-resizer-size: 10px;
--vgl-resizer-border-color: #444;
--vgl-resizer-border-width: 2px;
}
.vgl-item--placeholder {
z-index: var(--vgl-placeholder-z-index, 2);
user-select: none;
background-color: var(--vgl-placeholder-bg);
opacity: var(--vgl-placeholder-opacity);
transition-duration: 100ms;
border-radius: 1rem;
}
.vgl-item__resizer {
position: absolute;
right: 10px;
bottom: 10px;
box-sizing: border-box;
width: var(--vgl-resizer-size);
height: var(--vgl-resizer-size);
cursor: se-resize;
}
.vgl-item__resizer:before {
position: absolute;
inset: 0 3px 3px 0;
content: '';
border: 0 solid var(--vgl-resizer-border-color);
border-right-width: var(--vgl-resizer-border-width);
border-bottom-width: var(--vgl-resizer-border-width);
}
</style>
|
2302_79757062/insights
|
frontend/src/dashboard/VueGridLayout.vue
|
Vue
|
agpl-3.0
| 2,566
|
import useQuery from '@/query/resources/useQuery'
import sessionStore from '@/stores/sessionStore'
import { areDeeplyEqual, safeJSONParse } from '@/utils'
import { createToast } from '@/utils/toasts'
import widgets from '@/widgets/widgets'
import { createDocumentResource, debounce } from 'frappe-ui'
import { getLocal, saveLocal } from 'frappe-ui/src/resources/local'
import { reactive } from 'vue'
const session = sessionStore()
export default function useDashboard(name) {
const resource = getDashboardResource(name)
const state = reactive({
doc: {
doctype: 'Insights Dashboard',
name: undefined,
owner: undefined,
title: undefined,
items: [],
},
isOwner: false,
canShare: false,
isPrivate: false,
editing: false,
loading: false,
deleting: false,
currentItem: undefined,
draggingWidget: undefined,
sidebar: {
open: true,
position: 'right',
},
itemLayouts: [],
filterStates: {},
filtersByChart: {},
refreshCallbacks: [],
})
async function reload() {
state.loading = true
await resource.get.fetch()
state.doc = resource.doc
state.itemLayouts = state.doc.items.map(makeLayoutObject)
state.isOwner = state.doc.owner == session.user.email
state.canShare = state.isOwner || session.user.is_admin
resource.is_private.fetch().then((res) => (state.isPrivate = res))
state.loading = false
}
reload()
async function save() {
if (!state.editing) return
state.loading = true
state.doc.items.forEach((item, idx) => (item.idx = idx))
state.doc.items.forEach(updateItemLayout)
await resource.setValue.submit(state.doc)
await reload()
state.currentItem = undefined
state.loading = false
state.editing = false
window.location.reload()
}
async function deleteDashboard() {
state.deleting = true
await resource.delete.submit()
state.deleting = false
}
function addItem(item) {
if (!state.editing) return
state.doc.items.push(transformItem(item))
state.itemLayouts.push(getNewLayout(item))
}
function updateItemLayout(item) {
const layout = state.itemLayouts.find((layout) => layout.i === parseInt(item.item_id))
item.layout = layout || item.layout
}
function removeItem(item) {
if (!state.editing) return
const item_index = state.doc.items.findIndex((i) => i.item_id === item.item_id)
state.doc.items.splice(item_index, 1)
state.itemLayouts.splice(item_index, 1)
state.currentItem = undefined
}
function setCurrentItem(item_id) {
if (!state.editing) return
state.currentItem = state.doc.items.find((i) => i.item_id === item_id)
state.loadCurrentItemQuery(state.currentItem.options.query)
}
function getFilterStateKey(item_id) {
return `filterState-${state.doc.name}-${item_id}`
}
async function getFilterState(item_id) {
if (!state.filterStates[item_id]) {
state.filterStates[item_id] = await getLocal(getFilterStateKey(item_id))
}
return state.filterStates[item_id]
}
async function setFilterState(item_id, value) {
const filterState = value
? {
operator: value.operator,
value: value.value,
}
: undefined
if (areDeeplyEqual(filterState, state.filterStates[item_id])) return
saveLocal(getFilterStateKey(item_id), filterState).then(() => {
state.filterStates[item_id] = filterState
refreshLinkedCharts(item_id)
})
}
function refreshLinkedCharts(filter_id) {
state.doc.items.some((item) => {
if (item.item_id === filter_id) {
const charts = Object.keys(item.options.links) || []
charts.forEach((chart) => {
refreshChartFilters(chart)
})
return true
}
})
}
async function refreshChartFilters(chart_id) {
const promises = state.doc.items
.filter((item) => item.item_type === 'Filter')
.map(async (filter) => {
const chart_column = filter.options.links?.[chart_id]
if (!chart_column) return
const filter_state = await getFilterState(filter.item_id)
if (filter_state && filter_state.value?.value) {
return {
label: filter.options.label,
column: chart_column,
value: filter_state.value.value,
operator: filter_state.operator.value,
column_type: chart_column.type,
}
}
const default_operator = filter.options.defaultOperator
const default_value = filter.options.defaultValue
if (default_operator?.value && default_value?.value) {
return {
label: filter.options.label,
column: chart_column,
value: default_value.value,
operator: default_operator.value,
column_type: chart_column.type,
}
}
})
const filters = await Promise.all(promises)
state.filtersByChart[chart_id] = filters.filter(Boolean)
}
async function getChartFilters(chart_id) {
if (!state.filtersByChart[chart_id]) {
await refreshChartFilters(chart_id)
}
return state.filtersByChart[chart_id]
}
async function getChartResults(itemId, queryName) {
if (!queryName)
state.doc.items.some((item) => {
if (item.item_id === itemId) {
queryName = item.options.query
return true
}
})
if (!queryName) {
throw new Error(`Query not found for item ${itemId}`)
}
const filters = await getChartFilters(itemId)
return resource.fetch_chart_data.submit({
item_id: itemId,
query_name: queryName,
filters,
})
}
function refreshFilter(filter_id) {
const filter = state.doc.items.find((item) => item.item_id === filter_id)
Object.keys(filter.options.links).forEach((item_id) => {
Object.keys(state.queryResults).forEach((key) => {
if (key.startsWith(`${item_id}-`)) {
delete state.queryResults[key]
getChartResults(item_id)
}
})
})
}
async function refresh() {
await resource.clear_charts_cache.submit()
await reload()
state.refreshCallbacks.forEach((fn) => fn())
}
function onRefresh(fn) {
state.refreshCallbacks.push(fn)
}
const updateTitle = debounce(function (title) {
if (!title || !state.editing) return
state.doc.title = title
}, 500)
function makeLayoutObject(item) {
return {
i: parseInt(item.item_id),
x: item.layout.x || 0,
y: item.layout.y || 0,
w: item.layout.w || widgets[item.item_type].defaultWidth,
h: item.layout.h || widgets[item.item_type].defaultHeight,
}
}
function getNewLayout(item) {
// get the next available position
// consider the height and width of the item
const defaultWidth = widgets[item.item_type].defaultWidth
const defaultHeight = widgets[item.item_type].defaultHeight
const initialX = item.initialX
const initialY = item.initialY
delete item.initialX
delete item.initialY
return {
i: parseInt(item.item_id),
x: initialX || 0,
y: initialY || 0,
w: defaultWidth,
h: defaultHeight,
}
}
function togglePublicAccess(isPublic) {
if (state.doc.is_public === isPublic) return
resource.setValue.submit({ is_public: isPublic }).then(() => {
createToast({
title: 'Dashboard access updated',
variant: 'success',
})
state.doc.is_public = isPublic
})
}
function loadCurrentItemQuery(query) {
if (!query || !state.currentItem) return
state.currentItem.query = useQuery(query)
state.currentItem.query.reload()
}
const edit = () => ((state.editing = true), (state.currentItem = undefined))
const discardChanges = () => (
(state.editing = false), reload(), (state.currentItem = undefined)
)
const toggleSidebar = () => (state.sidebar.open = !state.sidebar.open)
const setSidebarPosition = (position) => (state.sidebar.position = position)
const isChart = (item) => !['Filter', 'Text'].includes(item.item_type)
const resetOptions = (item) => {
item.options = {
query: item.options.query,
}
}
return Object.assign(state, {
reload,
save,
addItem,
removeItem,
setCurrentItem,
getChartResults,
getFilterStateKey,
getFilterState,
setFilterState,
refreshFilter,
refreshChartFilters,
edit,
discardChanges,
toggleSidebar,
setSidebarPosition,
updateTitle,
deleteDashboard,
refresh,
onRefresh,
isChart,
togglePublicAccess,
loadCurrentItemQuery,
resetOptions,
})
}
function getDashboardResource(name) {
return createDocumentResource({
doctype: 'Insights Dashboard',
name: name,
whitelistedMethods: {
fetch_chart_data: 'fetch_chart_data',
clear_charts_cache: 'clear_charts_cache',
is_private: 'is_private',
},
transform(doc) {
doc.items = doc.items.map(transformItem)
return doc
},
})
}
function transformItem(item) {
item.options = safeJSONParse(item.options, {})
item.layout = safeJSONParse(item.layout, {})
return item
}
|
2302_79757062/insights
|
frontend/src/dashboard/useDashboard.js
|
JavaScript
|
agpl-3.0
| 8,531
|
import dayjs from '@/utils/dayjs'
import { call, createResource } from 'frappe-ui'
import { defineStore } from 'pinia'
export default defineStore('dashboards', {
state: () => ({
list: [],
loading: false,
creating: false,
deleting: false,
currentDashboard: undefined,
}),
actions: {
async reload() {
this.loading = true
this.list = await dashboards.fetch()
this.loading = false
return this
},
async create(title) {
if (!title) return
this.creating = true
const { name } = await call('insights.api.dashboards.create_dashboard', { title })
this.creating = false
this.reload()
return name
},
async toggleLike(dashboard) {
await call('frappe.desk.like.toggle_like', {
doctype: 'Insights Dashboard',
name: dashboard.name,
add: !dashboard.is_favourite ? 'Yes' : 'No',
})
this.reload()
},
async delete(dashboard) {
this.deleting = true
await call('frappe.client.delete', {
doctype: 'Insights Dashboard',
name: dashboard.name,
})
this.deleting = false
this.reload()
},
setCurrentDashboard(dashboard) {
this.currentDashboard = dashboard
},
resetCurrentDashboard() {
this.currentDashboard = undefined
},
},
})
const dashboards = createResource({
url: 'insights.api.dashboards.get_dashboard_list',
initialData: [],
cache: 'dashboardsList',
transform(data) {
return data.map((dashboard) => {
dashboard.modified_from_now = dayjs(dashboard.modified).fromNow()
return dashboard
})
},
})
export function getQueriesColumn(query_names) {
return call(
'insights.insights.doctype.insights_dashboard.insights_dashboard.get_queries_column',
{
query_names,
}
)
}
export function getQueryColumns(query) {
return call(
'insights.insights.doctype.insights_dashboard.insights_dashboard.get_query_columns',
{
query,
}
)
}
|
2302_79757062/insights
|
frontend/src/dashboard/useDashboards.js
|
JavaScript
|
agpl-3.0
| 1,851
|
import { areDeeplyEqual, safeJSONParse } from '@/utils'
import widgets from '@/widgets/widgets'
import { createResource } from 'frappe-ui'
import { getLocal, saveLocal } from 'frappe-ui/src/resources/local'
import { reactive } from 'vue'
export default function usePublicDashboard(public_key) {
const resource = getPublicDashboard(public_key)
const state = reactive({
isPublic: true,
doc: {
doctype: 'Insights Dashboard',
name: undefined,
owner: undefined,
title: undefined,
items: [],
},
loading: false,
itemLayouts: [],
filterStates: {},
filtersByChart: {},
refreshCallbacks: [],
})
async function reload() {
state.loading = true
await resource.fetch()
state.doc = resource.data
state.itemLayouts = state.doc.items.map(makeLayoutObject)
state.loading = false
}
reload()
function getFilterStateKey(item_id) {
return `filterState-${state.doc.name}-${item_id}`
}
async function getFilterState(item_id) {
if (!state.filterStates[item_id]) {
state.filterStates[item_id] = await getLocal(getFilterStateKey(item_id))
}
return state.filterStates[item_id]
}
async function setFilterState(item_id, value) {
const filterState = value
? {
operator: value.operator,
value: value.value,
}
: undefined
if (areDeeplyEqual(filterState, state.filterStates[item_id])) return
saveLocal(getFilterStateKey(item_id), filterState).then(() => {
state.filterStates[item_id] = filterState
refreshLinkedCharts(item_id)
})
}
function refreshLinkedCharts(filter_id) {
state.doc.items.some((item) => {
if (item.item_id === filter_id) {
const charts = Object.keys(item.options.links) || []
charts.forEach((chart) => {
refreshChartFilters(chart)
})
return true
}
})
}
async function refreshChartFilters(chart_id) {
const promises = state.doc.items
.filter((item) => item.item_type === 'Filter')
.map(async (filter) => {
const chart_column = filter.options.links?.[chart_id]
if (!chart_column) return
const filter_state = await getFilterState(filter.item_id)
if (!filter_state || !filter_state.value?.value) return
return {
label: filter.options.label,
column: chart_column,
value: filter_state.value.value,
operator: filter_state.operator.value,
column_type: chart_column.type,
}
})
const filters = await Promise.all(promises)
state.filtersByChart[chart_id] = filters.filter(Boolean)
}
async function getChartFilters(chart_id) {
if (!state.filtersByChart[chart_id]) {
await refreshChartFilters(chart_id)
}
return state.filtersByChart[chart_id]
}
async function getChartResults(itemId, queryName) {
if (!queryName)
state.doc.items.some((item) => {
if (item.item_id === itemId) {
queryName = item.options.query
return true
}
})
if (!queryName) {
throw new Error(`Query not found for item ${itemId}`)
}
const filters = await getChartFilters(itemId)
return await resource.fetch_chart_data.submit({
public_key,
item_id: itemId,
query_name: queryName,
filters,
})
}
function refreshFilter(filter_id) {
const filter = state.doc.items.find((item) => item.item_id === filter_id)
Object.keys(filter.options.links).forEach((item_id) => {
Object.keys(state.queryResults).forEach((key) => {
if (key.startsWith(`${item_id}-`)) {
delete state.queryResults[key]
getChartResults(item_id)
}
})
})
}
async function refresh() {
await reload()
state.refreshCallbacks.forEach((fn) => fn())
}
function onRefresh(fn) {
state.refreshCallbacks.push(fn)
}
function makeLayoutObject(item) {
return {
i: parseInt(item.item_id),
x: item.layout.x || 0,
y: item.layout.y || 0,
w: item.layout.w || widgets[item.item_type].defaultWidth,
h: item.layout.h || widgets[item.item_type].defaultHeight,
}
}
const isChart = (item) => !['Filter', 'Text'].includes(item.item_type)
return Object.assign(state, {
reload,
getChartResults,
getFilterStateKey,
getFilterState,
setFilterState,
refreshFilter,
refreshChartFilters,
refresh,
onRefresh,
isChart,
})
}
function getPublicDashboard(public_key) {
const resource = createResource({
url: 'insights.api.public.get_public_dashboard',
params: { public_key },
transform(doc) {
doc.items = doc.items.map(transformItem)
return doc
},
})
resource.fetch_chart_data = createResource({
url: 'insights.api.public.get_public_dashboard_chart_data',
})
return resource
}
function transformItem(item) {
item.options = safeJSONParse(item.options, {})
item.layout = safeJSONParse(item.layout, {})
return item
}
|
2302_79757062/insights
|
frontend/src/dashboard/usePublicDashboard.js
|
JavaScript
|
agpl-3.0
| 4,659
|
<script setup>
import { computed } from 'vue'
import MariaDBForm from './MariaDBForm.vue'
const props = defineProps({ show: Boolean })
const emit = defineEmits(['update:show'])
const show = computed({
get: () => props.show,
set: (value) => emit('update:show', value),
})
</script>
<template>
<Dialog v-model="show" :options="{ title: 'Connect to MariaDB' }">
<template #body-content>
<MariaDBForm @submit="show = false" />
</template>
</Dialog>
</template>
|
2302_79757062/insights
|
frontend/src/datasource/ConnectMariaDBDialog.vue
|
Vue
|
agpl-3.0
| 469
|
<script setup>
import { computed } from 'vue'
import PostgreSQLForm from './PostgreSQLForm.vue'
const props = defineProps({ show: Boolean })
const emit = defineEmits(['update:show'])
const show = computed({
get: () => props.show,
set: (value) => emit('update:show', value),
})
</script>
<template>
<Dialog v-model="show" :options="{ title: 'Connect to PostgreDB' }">
<template #body-content>
<PostgreSQLForm @submit="show = false" />
</template>
</Dialog>
</template>
|
2302_79757062/insights
|
frontend/src/datasource/ConnectPostgreDBDialog.vue
|
Vue
|
agpl-3.0
| 480
|
<template>
<header class="sticky top-0 z-10 flex items-center justify-between bg-white px-5 py-2.5">
<PageBreadcrumbs
class="h-7"
:items="[
{ label: 'Data Sources', route: { path: '/data-source' } },
{ label: dataSource.doc.title },
]"
/>
</header>
<div class="mb-4 flex h-full flex-col gap-2 overflow-auto px-4">
<div class="flex gap-2 overflow-visible py-1">
<FormControl placeholder="Search by Title" v-model="searchQuery" :debounce="300">
<template #prefix>
<SearchIcon class="h-4 w-4 text-gray-500" />
</template>
</FormControl>
<Button
variant="outline"
iconLeft="link-2"
@click="router.push(`/data-source/${dataSource.doc.name}/relationships`)"
>
Manage Relationships
</Button>
<Dropdown
placement="left"
:button="{ icon: 'more-horizontal', variant: 'outline' }"
:options="dropdownActions"
/>
</div>
<ListView
:columns="tableListColumns"
:rows="filteredTableList"
:row-key="'name'"
:options="{
showTooltip: false,
getRowRoute: (table) => ({
name: 'DataSourceTable',
params: { name: dataSource.doc.name, table: table.name },
}),
emptyState: {
title: 'No tables.',
description: 'No tables to display.',
button: {
label: 'Sync Tables',
variant: 'solid',
onClick: syncTables,
},
},
}"
>
</ListView>
</div>
<Dialog
v-model="showDeleteDialog"
:dismissable="true"
:options="{
title: 'Delete Data Source',
message: 'Are you sure you want to delete this data source?',
icon: { name: 'trash', appearance: 'danger' },
actions: [
{
label: 'Delete',
variant: 'solid',
theme: 'red',
onClick: async () => {
await dataSource.delete()
router.push({ name: 'DataSourceList' })
},
},
],
}"
>
</Dialog>
</template>
<script setup lang="jsx">
import IndicatorIcon from '@/components/Icons/IndicatorIcon.vue'
import PageBreadcrumbs from '@/components/PageBreadcrumbs.vue'
import { ListView } from 'frappe-ui'
import { SearchIcon } from 'lucide-vue-next'
import { computed, inject, provide, ref, watchEffect } from 'vue'
import { useRouter } from 'vue-router'
import useDataSource from './useDataSource'
const props = defineProps({
name: {
type: String,
required: true,
},
})
const router = useRouter()
const dataSource = useDataSource(props.name)
provide('dataSource', dataSource)
dataSource.fetchTables()
const searchQuery = ref('')
const filteredTableList = computed(() => {
const tableList = dataSource.tableList.filter((t) => !t.is_query_based)
if (!tableList.length) return []
if (!searchQuery.value) return tableList
return tableList.filter((table) => {
return table.label.toLowerCase().includes(searchQuery.value.toLowerCase())
})
})
const showDeleteDialog = ref(false)
const dropdownActions = computed(() => {
return [
{
label: 'Sync Tables',
icon: 'refresh-cw',
onClick: syncTables,
},
{
label: 'Delete',
icon: 'trash',
onClick: () => (showDeleteDialog.value = true),
},
]
})
const $notify = inject('$notify')
function syncTables() {
dataSource
.syncTables()
.catch((err) => $notify({ title: 'Error Syncing Tables', variant: 'error' }))
}
watchEffect(() => {
if (dataSource.doc?.name) {
const title = dataSource.doc.title || dataSource.doc.name
document.title = `${title} - Frappe Insights`
}
})
const tableListColumns = [
{ label: 'Table', key: 'label' },
{
label: 'Status',
key: 'status',
getLabel: ({ row }) => (row.hidden ? 'Disabled' : 'Enabled'),
prefix: ({ row }) => {
const color = row.hidden ? 'text-gray-500' : 'text-green-500'
return <IndicatorIcon class={color} />
},
},
]
</script>
|
2302_79757062/insights
|
frontend/src/datasource/DataSource.vue
|
Vue
|
agpl-3.0
| 3,719
|
<template>
<header class="sticky top-0 z-10 flex items-center justify-between bg-white px-5 py-2.5">
<PageBreadcrumbs class="h-7" :items="[{ label: 'Data Sources' }]" />
<div>
<Button label="New Data Source" variant="solid" @click="new_dialog = true">
<template #prefix>
<PlusIcon class="w-4" />
</template>
</Button>
</div>
</header>
<div class="mb-4 flex h-full flex-col gap-2 overflow-auto px-4">
<div class="flex gap-2 overflow-visible py-1">
<FormControl placeholder="Search by Title" v-model="searchQuery" :debounce="300">
<template #prefix>
<SearchIcon class="h-4 w-4 text-gray-500" />
</template>
</FormControl>
</div>
<ListView
:columns="dataSourceListColumns"
:rows="filteredSourceList"
:row-key="'name'"
:options="{
showTooltip: false,
getRowRoute: (dataSource) => ({
name: 'DataSource',
params: { name: dataSource.name },
}),
emptyState: {
title: 'No Data Sources.',
description: 'No data sources to display.',
button: {
label: 'New Data Source',
variant: 'solid',
onClick: () => (new_dialog = true),
},
},
}"
>
</ListView>
</div>
<NewDialogWithTypes
v-model:show="new_dialog"
title="Select Source Type"
:types="databaseTypes"
/>
<ConnectMariaDBDialog v-model:show="showConnectMariaDBDialog" />
<ConnectPostgreDBDialog v-model:show="showConnectPostgreDBDialog" />
<UploadCSVFileDialog v-model:show="showCSVFileUploadDialog" />
</template>
<script setup lang="jsx">
import IndicatorIcon from '@/components/Icons/IndicatorIcon.vue'
import NewDialogWithTypes from '@/components/NewDialogWithTypes.vue'
import PageBreadcrumbs from '@/components/PageBreadcrumbs.vue'
import ConnectMariaDBDialog from '@/datasource/ConnectMariaDBDialog.vue'
import ConnectPostgreDBDialog from '@/datasource/ConnectPostgreDBDialog.vue'
import UploadCSVFileDialog from '@/datasource/UploadCSVFileDialog.vue'
import useDataSourceStore from '@/stores/dataSourceStore'
import { updateDocumentTitle } from '@/utils'
import { ListView } from 'frappe-ui'
import { PlusIcon, SearchIcon } from 'lucide-vue-next'
import { ref, computed } from 'vue'
import { useRoute, useRouter } from 'vue-router'
const new_dialog = ref(false)
const route = useRoute()
if (route.hash == '#new') {
new_dialog.value = true
}
const sources = useDataSourceStore()
const searchQuery = ref('')
const filteredSourceList = computed(() => {
if (searchQuery.value) {
return sources.list.filter((source) => {
return source.title.toLowerCase().includes(searchQuery.value.toLowerCase())
})
}
return sources.list
})
const router = useRouter()
const showConnectMariaDBDialog = ref(false)
const showConnectPostgreDBDialog = ref(false)
const showCSVFileUploadDialog = ref(false)
const databaseTypes = ref([
{
label: 'MariaDB',
description: 'Connect to a MariaDB database',
imgSrc: new URL('/src/assets/MariaDBIcon.png', import.meta.url),
onClick: () => {
new_dialog.value = false
showConnectMariaDBDialog.value = true
},
},
{
label: 'PostgreSQL',
description: 'Connect to a PostgreSQL database',
imgSrc: new URL('/src/assets/PostgreSQLIcon.png', import.meta.url),
onClick: () => {
new_dialog.value = false
showConnectPostgreDBDialog.value = true
},
},
{
label: 'CSV',
description: 'Upload a CSV file',
imgSrc: new URL('/src/assets/SheetIcon.png', import.meta.url),
onClick: () => {
new_dialog.value = false
showCSVFileUploadDialog.value = true
},
},
])
const dataSourceListColumns = [
{ label: 'Title', key: 'title' },
{
label: 'Status',
key: 'status',
prefix: ({ row }) => {
const color = row.status == 'Inactive' ? 'text-gray-500' : 'text-green-500'
return <IndicatorIcon class={color} />
},
},
{ label: 'Database Type', key: 'database_type' },
{ label: 'Created', key: 'created_from_now' },
]
const pageMeta = ref({ title: 'Data Sources' })
updateDocumentTitle(pageMeta)
</script>
|
2302_79757062/insights
|
frontend/src/datasource/DataSourceList.vue
|
Vue
|
agpl-3.0
| 3,975
|
<script setup>
import PageBreadcrumbs from '@/components/PageBreadcrumbs.vue'
import TableRelationshipEditor from './TableRelationshipEditor.vue'
import useDataSource from './useDataSource'
import { provide } from 'vue'
const props = defineProps({
name: {
type: String,
required: true,
},
})
const dataSource = useDataSource(props.name)
provide('dataSource', dataSource)
dataSource.fetchTables()
</script>
<template>
<header class="sticky top-0 z-10 flex items-center justify-between bg-white px-5 py-2.5 shadow">
<PageBreadcrumbs
class="h-7"
:items="[
{ label: 'Data Sources', route: { path: '/data-source' } },
{
label: dataSource.doc?.title || dataSource.doc?.name,
route: { path: `/data-source/${dataSource.doc?.name}` },
},
{ label: 'Relationships' },
]"
/>
</header>
<div v-if="dataSource.doc" class="flex h-full w-full overflow-hidden">
<TableRelationshipEditor v-if="dataSource.doc.name" />
</div>
</template>
|
2302_79757062/insights
|
frontend/src/datasource/DataSourceRelationships.vue
|
Vue
|
agpl-3.0
| 973
|
<template>
<header class="sticky top-0 z-10 flex items-center bg-white px-5 py-2.5">
<PageBreadcrumbs
class="h-7"
:items="[
{
label: 'Data Sources',
href: '/data-source',
route: { path: '/data-source' },
},
{
label: props.name,
route: { path: `/data-source/${props.name}` },
},
{
label: dataSourceTable.doc?.label || props.table,
},
]"
/>
<div v-if="dataSourceTable.doc" class="ml-2 flex items-center space-x-2.5">
<Badge variant="subtle" :theme="hidden ? 'gray' : 'green'" size="md">
{{ hidden ? 'Disabled' : 'Enabled' }}
</Badge>
<Dropdown
placement="left"
:button="{
icon: 'more-horizontal',
variant: 'ghost',
}"
:options="[
{
label: hidden ? 'Enable' : 'Disable',
icon: hidden ? 'eye' : 'eye-off',
onClick: () => (hidden = !hidden),
},
{
label: 'Sync Table',
icon: 'refresh-cw',
onClick: () => dataSourceTable.sync(),
},
{
label: 'Add Link',
icon: 'link',
onClick: () => (addLinkDialog = true),
},
]"
/>
</div>
</header>
<div class="flex flex-1 flex-col overflow-hidden bg-white px-6 py-2">
<div
v-if="
dataSourceTable.doc &&
dataSourceTable.doc.columns &&
dataSourceTable.rows?.data &&
!dataSourceTable.syncing
"
class="flex flex-1 flex-col overflow-hidden"
>
<!-- <div class="flex h-6 flex-shrink-0 space-x-1 text-sm font-light text-gray-600">
{{ dataSourceTable.doc.columns.length }} Columns -
{{ dataSourceTable.rows.length }} Rows
</div> -->
<div class="flex flex-1 overflow-auto">
<Grid :header="true" :rows="dataSourceTable.rows.data">
<template #header>
<DataSourceTableColumnHeader
:columns="dataSourceTable.doc.columns"
@update-column-type="dataSourceTable.updateColumnType"
/>
</template>
</Grid>
</div>
</div>
<div
v-else
class="mt-2 flex h-full w-full flex-col items-center justify-center rounded bg-gray-50"
>
<LoadingIndicator class="mb-2 w-8 text-gray-500" />
<div class="text-lg text-gray-600">Syncing columns from database...</div>
</div>
</div>
<Dialog :options="{ title: 'Create a Link' }" v-model="addLinkDialog">
<template #body-content>
<div class="space-y-4">
<div>
<div class="mb-2 block text-sm leading-4 text-gray-700">Table</div>
<Autocomplete
ref="$autocomplete"
v-model="newLink.table"
:options="tableOptions"
placeholder="Select a table..."
/>
</div>
<div>
<div class="mb-2 block text-sm leading-4 text-gray-700">
Select a column from {{ dataSourceTable.doc.label }}
</div>
<Autocomplete
v-model="newLink.primaryKey"
:options="
dataSourceTable.doc.columns.map((c) => ({
label: `${c.label} (${c.type})`,
value: c.column,
}))
"
/>
</div>
<div v-if="newLink.table?.value">
<div class="mb-2 block text-sm leading-4 text-gray-700">
Select a column from {{ newLink.table.label }}
</div>
<Autocomplete v-model="newLink.foreignKey" :options="foreignKeyOptions" />
</div>
</div>
</template>
<template #actions>
<Button
variant="solid"
@click="createLink"
:loading="creatingLink"
:disabled="createLinkDisabled"
>
Create
</Button>
</template>
</Dialog>
</template>
<script setup>
import Grid from '@/components/Grid.vue'
import PageBreadcrumbs from '@/components/PageBreadcrumbs.vue'
import useDataSourceTable from '@/datasource/useDataSourceTable'
import { Badge, Dropdown, LoadingIndicator, createResource } from 'frappe-ui'
import { computed, inject, nextTick, reactive, ref, watch, watchEffect } from 'vue'
import DataSourceTableColumnHeader from './DataSourceTableColumnHeader.vue'
const props = defineProps({
name: {
// data source name
type: String,
required: true,
},
table: {
// table name
type: String,
required: true,
},
})
const addLinkDialog = ref(false)
const newLink = reactive({
table: {},
primaryKey: {},
foreignKey: {},
})
const dataSourceTable = await useDataSourceTable({ name: props.table })
dataSourceTable.fetchPreview()
const hidden = computed({
get() {
return dataSourceTable.doc.hidden
},
set(value) {
if (value !== dataSourceTable.hidden) {
dataSourceTable.updateVisibility(Boolean(value))
}
},
})
const getTableOptions = createResource({
url: 'insights.api.data_sources.get_tables',
params: {
data_source: props.name,
},
initialData: [],
auto: true,
})
const tableOptions = computed(() =>
getTableOptions.data.map((table) => ({
...table,
value: table.table,
}))
)
const getForeignKeyOptions = createResource({
url: 'insights.api.data_sources.get_table_columns',
initialData: [],
})
watch(
() => newLink.table,
(table) => {
if (table) {
getForeignKeyOptions.submit({
data_source: props.name,
table: table.table,
})
} else {
foreignKeyOptions.value = []
}
}
)
const foreignKeyOptions = computed({
get() {
return (
getForeignKeyOptions.data?.columns?.map((c) => {
return {
label: `${c.label} (${c.type})`,
value: c.column,
}
}) || []
)
},
set(value) {
getForeignKeyOptions.data = value
},
})
const createLinkDisabled = computed(() => {
return (
!newLink.table ||
!(newLink.primaryKey && newLink.primaryKey.value) ||
!(newLink.foreignKey && newLink.foreignKey.value)
)
})
const $notify = inject('$notify')
const createLinkResource = createResource({
url: 'insights.api.data_sources.create_table_link',
onSuccess() {
newLink.table = ''
newLink.primaryKey = ''
newLink.foreignKey = ''
addLinkDialog.value = false
$notify({
variant: 'success',
title: 'Success',
message: 'Link created successfully',
})
},
})
const creatingLink = computed(() => createLinkResource.loading)
function createLink() {
if (createLinkDisabled.value) return
createLinkResource.submit({
data_source: props.name,
primary_table: {
label: dataSourceTable.doc.label,
table: dataSourceTable.doc.table,
},
foreign_table: {
label: newLink.table.label,
table: newLink.table.table,
},
primary_key: newLink.primaryKey.value,
foreign_key: newLink.foreignKey.value,
})
}
const $autocomplete = ref(null)
watch(addLinkDialog, async (val) => {
if (val) {
await nextTick()
setTimeout(() => {
$autocomplete.value.input.$el.blur()
$autocomplete.value.input.$el.focus()
}, 500)
}
})
watchEffect(() => {
if (dataSourceTable.doc?.label) {
const title = dataSourceTable.doc.title || dataSourceTable.doc.label
document.title = `${title} - Frappe Insights`
}
})
</script>
|
2302_79757062/insights
|
frontend/src/datasource/DataSourceTable.vue
|
Vue
|
agpl-3.0
| 6,689
|
<template>
<td
v-for="col in $props.columns"
class="bg-gray-100 px-2.5 py-1.5 first:rounded-l-md last:rounded-r-md"
scope="col"
>
<div class="flex items-center">
<span class="mr-2 overflow-hidden text-ellipsis whitespace-nowrap">
{{ col.label }} : {{ col.type }}
</span>
<div class="h-6">
<Popover>
<template #target="{ togglePopover }">
<div
class="cursor-pointer rounded p-1 hover:bg-gray-200"
@click="togglePopover()"
>
<FeatherIcon name="more-horizontal" class="h-4 w-4" />
</div>
</template>
<template #body="{ isOpen, togglePopover }">
<div
v-if="isOpen"
class="flex items-end space-x-2 rounded bg-white px-3 py-2 shadow-md"
>
<Input
class="w-40"
type="select"
label="Change Type"
:options="[
'String',
'Integer',
'Decimal',
'Text',
'Datetime',
'Date',
'Time',
]"
v-model="col.type"
></Input>
<Button
icon="check"
variant="solid"
@click="$emit('update-column-type', col) & togglePopover()"
></Button>
</div>
</template>
</Popover>
</div>
</div>
</td>
</template>
<script setup>
import { ref } from 'vue'
defineEmits(['update-column-type'])
defineProps({ columns: Object })
</script>
|
2302_79757062/insights
|
frontend/src/datasource/DataSourceTableColumnHeader.vue
|
Vue
|
agpl-3.0
| 1,381
|
<script setup>
import Attachment from '@/components/Controls/Attachment.vue'
import Autocomplete from '@/components/Controls/Autocomplete.vue'
import useDataSourceStore from '@/stores/dataSourceStore'
import { FileUploader, createResource } from 'frappe-ui'
import { computed, reactive, ref, watch } from 'vue'
import Draggable from 'vuedraggable'
const emit = defineEmits(['submit'])
const columnTypes = ['String', 'Integer', 'Decimal', 'Date', 'Datetime']
const table = reactive({
label: '',
name: '',
data_source: 'Query Store',
file: null,
ifExists: 'Overwrite',
})
const columns = ref([])
const getColumns = createResource({
url: 'insights.api.data_sources.get_columns_from_uploaded_file',
initialData: [],
onSuccess: (data) => {
columns.value = data?.map((c) => {
return {
label: c.label,
name: scrubName(c.label),
type: c.type || 'String',
}
})
},
})
function removeColumn(column) {
columns.value = columns.value.filter((c) => c.column !== column)
}
const importDisabled = computed(
() =>
!table.data_source ||
!table.label ||
!table.file ||
columns.length === 0 ||
importingTable.value
)
watch(
() => table.file,
(newFile) => {
table.label = newFile ? newFile.file_name?.replace(/\.[^/.]+$/, '') : ''
table.name = newFile ? scrubName(table.label) : ''
newFile ? getColumns.submit({ filename: newFile.name }) : (getColumns.data = [])
}
)
function scrubName(name) {
return name?.toLocaleLowerCase().replace(/[^a-zA-Z0-9]/g, '_')
}
const import_csv = createResource({
url: 'insights.api.data_sources.import_csv',
})
const dataSourceStore = useDataSourceStore()
const importingTable = ref(false)
function submit() {
importingTable.value = true
const data = {
table_label: table.label,
table_name: table.name,
filename: table.file.name,
if_exists: table.ifExists,
columns: columns.value,
data_source: table.data_source,
}
import_csv
.submit(data)
.then(() => {
emit('submit')
reset()
})
.catch((err) => {
importingTable.value = false
console.error(err)
})
}
function reset() {
table.label = ''
table.name = ''
table.file = null
table.ifExists = 'Overwrite'
table.data_source = ''
columns.value = []
importingTable.value = false
}
</script>
<template>
<div>
<FileUploader v-if="false" @success="(file) => (table.file = file)">
<template #default="{ progress, uploading, openFileSelector }">
<div
class="flex cursor-pointer flex-col items-center justify-center rounded border border-dashed border-gray-300 p-8 text-base"
@click="openFileSelector"
>
<FeatherIcon name="upload" class="h-8 w-8 text-gray-500" />
<div class="mt-2 text-gray-600">
<p v-if="!uploading" class="text-center font-medium text-blue-500">
Select a file
</p>
<p v-else class="text-center font-medium text-blue-500">
Uploading... ({{ progress }}%)
</p>
<p v-if="!uploading" class="mt-1 text-center text-xs">
Only CSV files upto 10MB
</p>
</div>
</div>
</template>
</FileUploader>
<div class="mt-4 grid grid-cols-1 gap-4 lg:grid-cols-2">
<transition-group name="fade">
<div>
<span class="mb-2 block text-sm leading-4 text-gray-700">Data Source</span>
<Autocomplete
placeholder="Select Data Source"
:modelValue="table.data_source"
@update:modelValue="table.data_source = $event?.value"
:options="dataSourceStore.getDropdownOptions({ allow_imports: 1 })"
/>
</div>
<Attachment
v-model="table.file"
label="File"
fileType=".csv"
placeholder="Upload CSV File"
/>
<Input
v-if="table.file"
label="New Table Label"
type="text"
placeholder="eg. Sales Data"
v-model="table.label"
/>
<Input
v-if="table.file"
label="New Table Name"
type="text"
placeholder="eg. sales_data"
v-model="table.name"
/>
<Input
v-if="table.file"
type="select"
label="Action if exists"
v-model="table.ifExists"
:options="['Fail', 'Overwrite', 'Append']"
/>
</transition-group>
</div>
</div>
<div v-if="table.data_source && table.file" class="mt-4">
<span class="text-base font-medium leading-6 text-gray-900"> Columns </span>
<div
v-if="columns?.length"
class="mt-2 flex max-h-[15rem] flex-col overflow-hidden text-base"
>
<div
class="sticky right-0 top-0 z-10 flex h-8 w-full cursor-pointer items-center space-x-8 pr-8 pb-1 text-xs uppercase text-gray-600"
>
<span class="flex-1"> CSV Column </span>
<span class="flex-1"> Column Name </span>
<span class="flex-1"> Column Type </span>
</div>
<div class="flex flex-col overflow-y-auto">
<Draggable class="w-full" v-model="columns" group="columns" item-key="column">
<template #item="{ element: column }">
<div
class="flex h-10 w-full cursor-pointer items-center space-x-8 text-gray-600"
>
<span
class="flex-1 overflow-hidden text-ellipsis whitespace-nowrap text-base font-medium"
>
{{ column.label }}
</span>
<Input
class="flex-1 !text-sm"
type="text"
:value="column.name"
@change="(name) => (column.name = name)"
/>
<Input
class="flex-1 !text-sm"
type="select"
:options="columnTypes"
:value="column.type"
@change="(type) => (column.type = type)"
/>
<Button
class="!ml-0"
icon="x"
variant="minimal"
@click="removeColumn(column.column)"
/>
</div>
</template>
</Draggable>
</div>
</div>
<div
v-else-if="getColumns.loading"
class="mt-2 flex flex-col items-center justify-center space-y-2 p-12 text-center text-sm"
>
<LoadingIndicator class="h-4 w-4 text-gray-500" />
<p class="text-gray-600">Loading columns...</p>
</div>
<div v-else class="mt-2 flex flex-col space-y-3 p-12 text-center text-sm text-gray-600">
No columns found in the uploaded file.<br />
Please upload a different file.
</div>
</div>
<div class="mt-4 flex justify-between pt-2">
<div class="ml-auto flex items-center space-x-2">
<Button
variant="solid"
@click="submit"
:disabled="importDisabled"
:loading="importingTable"
>
Import
</Button>
</div>
</div>
</template>
|
2302_79757062/insights
|
frontend/src/datasource/FileSourceForm.vue
|
Vue
|
agpl-3.0
| 6,346
|
<script setup>
import Form from '@/pages/Form.vue'
import useDataSourceStore from '@/stores/dataSourceStore'
import { computed, reactive, ref } from 'vue'
const props = defineProps({ submitLabel: String })
const emit = defineEmits(['submit'])
const database = reactive({})
const form = ref(null)
const fields = [
{ name: 'title', label: 'Title', type: 'text', placeholder: 'My Database', required: true },
{
label: 'Host',
name: 'host',
type: 'text',
placeholder: 'localhost',
required: true,
defaultValue: 'localhost',
},
{
label: 'Port',
name: 'port',
type: 'number',
placeholder: '3306',
required: true,
defaultValue: 3306,
},
{
label: 'Database Name',
name: 'name',
type: 'text',
placeholder: 'DB_1267891',
required: true,
},
{
label: 'Username',
name: 'username',
type: 'text',
placeholder: 'read_only_user',
required: true,
},
{
label: 'Password',
name: 'password',
type: 'password',
placeholder: '**********',
required: true,
},
{ label: 'Use secure connection (SSL)?', name: 'useSSL', type: 'checkbox' },
]
const sources = useDataSourceStore()
const areRequiredFieldsFilled = computed(() => {
return Boolean(fields.filter((field) => field.required).every((field) => database[field.name]))
})
const testConnectionDisabled = computed(() => {
return areRequiredFieldsFilled.value === false || sources.testing
})
const connected = ref(null)
const connectLabel = computed(() => {
if (sources.testing) return ''
if (connected.value === null) return 'Connect'
if (connected.value) return 'Connected'
return 'Failed, Retry?'
})
const connectIcon = computed(() => {
if (connected.value === null) return
if (connected.value) return 'check'
return 'alert-circle'
})
const submitDisabled = computed(() => {
return areRequiredFieldsFilled.value === false || !connected.value || sources.creating
})
const submitLabel = computed(() => {
if (sources.creating) return ''
return props.submitLabel || 'Add Database'
})
const testing = ref(false)
const testConnection = async () => {
database['type'] = 'MariaDB'
testing.value = true
connected.value = await sources.testConnection({ database })
testing.value = false
}
const creating = ref(false)
const createNewDatabase = async () => {
database['type'] = 'MariaDB'
creating.value = true
await sources.create({ database })
creating.value = false
emit('submit')
}
</script>
<template>
<Form ref="form" class="flex-1" v-model="database" :meta="{ fields }"> </Form>
<div class="mt-6 flex justify-between pt-2">
<div class="ml-auto flex items-center space-x-2">
<Button
variant="outline"
:disabled="testConnectionDisabled"
@click="testConnection"
loadingText="Connecting..."
:loading="testing"
:iconLeft="connectIcon"
>
{{ connectLabel }}
</Button>
<Button
variant="solid"
:disabled="submitDisabled"
loadingText="Adding Database..."
:loading="creating"
@click="createNewDatabase"
>
{{ submitLabel }}
</Button>
</div>
</div>
</template>
|
2302_79757062/insights
|
frontend/src/datasource/MariaDBForm.vue
|
Vue
|
agpl-3.0
| 3,042
|
<script setup>
import useDataSourceStore from '@/stores/dataSourceStore'
import { computed, reactive, ref } from 'vue'
import Form from '../pages/Form.vue'
const props = defineProps({ submitLabel: String })
const emit = defineEmits(['submit'])
const database = reactive({})
const form = ref(null)
const fields = computed(() => [
{ name: 'title', label: 'Title', type: 'text', placeholder: 'My Database', required: true },
{
label: 'Host',
name: 'host',
type: 'text',
placeholder: 'localhost',
required: !database.connection_string,
defaultValue: 'localhost',
},
{
label: 'Port',
name: 'port',
type: 'number',
placeholder: '5432',
required: !database.connection_string,
defaultValue: 5432,
},
{
label: 'Database Name',
name: 'name',
type: 'text',
placeholder: 'DB_1267891',
required: !database.connection_string,
},
{
label: 'Username',
name: 'username',
type: 'text',
placeholder: 'read_only_user',
required: !database.connection_string,
},
{
label: 'Password',
name: 'password',
type: 'password',
placeholder: '**********',
required: !database.connection_string,
},
{ label: 'Use secure connection (SSL)?', name: 'useSSL', type: 'checkbox' },
])
const sources = useDataSourceStore()
const areRequiredFieldsFilled = computed(() => {
return Boolean(
fields.value.filter((field) => field.required).every((field) => database[field.name]) ||
(database.title && database.connection_string)
)
})
const testConnectionDisabled = computed(() => {
return areRequiredFieldsFilled.value === false || sources.testing
})
const connected = ref(null)
const connectLabel = computed(() => {
if (sources.testing) return ''
if (connected.value === null) return 'Connect'
if (connected.value) return 'Connected'
return 'Failed, Retry?'
})
const connectIcon = computed(() => {
if (connected.value === null) return
if (connected.value) return 'check'
return 'alert-circle'
})
const submitDisabled = computed(() => {
return areRequiredFieldsFilled.value === false || !connected.value || sources.creating
})
const submitLabel = computed(() => {
if (sources.creating) return ''
return props.submitLabel || 'Add Database'
})
const testing = ref(false)
const testConnection = async () => {
database['type'] = 'PostgreSQL'
testing.value = true
sources
.testConnection({ database })
.then((result) => {
connected.value = result
})
.catch((error) => {
connected.value = false
})
.finally(() => {
testing.value = false
})
}
const creating = ref(false)
const createNewDatabase = async () => {
database['type'] = 'PostgreSQL'
creating.value = true
await sources.create({ database })
creating.value = false
emit('submit')
}
</script>
<template>
<Form ref="form" class="flex-1" v-model="database" :meta="{ fields }"> </Form>
<div class="my-4 flex items-center space-x-2 text-sm">
<p class="mb-0.5 h-1 flex-1 border-b" />
<p>OR</p>
<p class="mb-0.5 h-1 flex-1 border-b" />
</div>
<Input
v-model="database.connection_string"
label="Connection String"
placeholder="postgres://user:password@host:port/database"
/>
<div class="mt-6 flex justify-between pt-2">
<div class="ml-auto flex items-center space-x-2">
<Button
variant="outline"
:disabled="testConnectionDisabled"
@click="testConnection"
loadingText="Connecting..."
:loading="testing"
:iconLeft="connectIcon"
>
{{ connectLabel }}
</Button>
<Button
variant="solid"
:disabled="submitDisabled"
loadingText="Adding Database..."
:loading="creating"
@click="createNewDatabase"
>
{{ submitLabel }}
</Button>
</div>
</div>
</template>
|
2302_79757062/insights
|
frontend/src/datasource/PostgreSQLForm.vue
|
Vue
|
agpl-3.0
| 3,661
|
<script setup>
import sessionStore from '@/stores/sessionStore'
import { call } from 'frappe-ui'
import { inject, ref } from 'vue'
const emit = defineEmits(['submit'])
const selectedDataset = ref(null)
const sampleDatasets = [
{
name: 'ecommerce',
title: 'eCommerce',
description: 'An eCommerce dataset with orders, products, customers, and suppliers data.',
icon: 'shopping-cart',
},
]
const $notify = inject('$notify')
const settingUpSampleData = ref(false)
async function setupSampleData() {
if (selectedDataset.value === null) {
$notify({
title: 'Please select a dataset',
message: 'Please select a dataset to continue',
type: 'error',
})
return
}
settingUpSampleData.value = true
await call('insights.api.setup.setup_sample_data', {
dataset: sampleDatasets[selectedDataset.value].name,
})
settingUpSampleData.value = false
emit('submit')
}
const session = sessionStore()
const $socket = inject('$socket')
const progressLabel = ref('Continue')
$socket.on('insights_demo_setup_progress', (data) => {
if (data.user == session.user.email) {
progressLabel.value = `${data.progress.toFixed(0)}% complete...`
if (data.progress == 100) {
progressLabel.value = 'Continue'
}
}
})
</script>
<template>
<div class="grid grid-cols-1 gap-4">
<div
v-for="(dataset, index) in sampleDatasets"
class="col-span-1 flex cursor-pointer items-center rounded border border-gray-300 px-4 py-3 transition-all"
:class="selectedDataset === index ? 'border-gray-600' : 'hover:border-gray-300'"
@click="selectedDataset = index"
>
<div v-if="dataset.icon" class="mr-3 p-2 text-gray-600">
<FeatherIcon :name="dataset.icon" class="h-8 w-8" />
</div>
<div>
<div class="font-bold text-gray-900">
{{ dataset.title }}
</div>
<div class="text-base text-gray-700">{{ dataset.description }}</div>
</div>
</div>
</div>
<div class="mt-6 flex flex-shrink-0 justify-end space-x-3">
<Button
variant="solid"
@click="setupSampleData"
:loading="settingUpSampleData"
:disabled="settingUpSampleData || selectedDataset === null"
>
{{ progressLabel }}
</Button>
</div>
</template>
|
2302_79757062/insights
|
frontend/src/datasource/SampleDatasetList.vue
|
Vue
|
agpl-3.0
| 2,160
|
<script setup>
import { BaseEdge, EdgeLabelRenderer, getBezierPath, useVueFlow } from '@vue-flow/core'
import { computed, inject } from 'vue'
const props = defineProps({
id: { type: String, required: true },
sourceX: { type: Number, required: true },
sourceY: { type: Number, required: true },
targetX: { type: Number, required: true },
targetY: { type: Number, required: true },
sourcePosition: { type: String, required: true },
targetPosition: { type: String, required: true },
data: { type: Object, required: false },
markerEnd: { type: String, required: false },
style: { type: Object, required: false },
})
const state = inject('state')
const path = computed(() => getBezierPath(props))
const dropdownOptions = [
{
group: 'Cardinality',
items: [
{
label: 'One to One',
onClick: () => state.setCardinality(props.id, '1:1'),
},
{
label: 'One to Many',
onClick: () => state.setCardinality(props.id, '1:N'),
},
{
label: 'Many to One',
onClick: () => state.setCardinality(props.id, 'N:1'),
},
{
label: 'Many to Many',
onClick: () => state.setCardinality(props.id, 'N:N'),
},
],
},
{
group: 'Actions',
items: [
{
label: 'Delete',
icon: 'trash',
onClick: () => state.deleteRelationship(props.id),
},
],
},
]
</script>
<script>
export default {
inheritAttrs: false,
}
</script>
<template>
<BaseEdge :id="id" :style="style" :path="path[0]" :marker-end="markerEnd" />
<EdgeLabelRenderer>
<div
:style="{
pointerEvents: 'all',
position: 'absolute',
transform: `translate(-50%, -50%) translate(${path[1]}px,${path[2]}px)`,
}"
class="nodrag nopan"
>
<Dropdown :options="dropdownOptions">
<Button variant="outline">
<span class="truncate font-mono"> {{ data.cardinality || '1:1' }} </span>
</Button>
</Dropdown>
</div>
</EdgeLabelRenderer>
</template>
|
2302_79757062/insights
|
frontend/src/datasource/TableEdge.vue
|
Vue
|
agpl-3.0
| 1,896
|
<script setup>
import useDataSourceTable from '@/datasource/useDataSourceTable'
import { fieldtypesToIcon } from '@/utils'
import { Handle, Position } from '@vue-flow/core'
import { inject, ref, watch } from 'vue'
const state = inject('state')
const edges = inject('edges')
const props = defineProps({ tablename: { type: String, required: true } })
const table = await useDataSourceTable({ name: props.tablename })
const columns = ref([...table.doc.columns])
watch(
edges,
() => {
if (!edges.value?.length) return
// based on the current edges, move the columns that are in the edges to the top
const columnsInEdges = edges.value
.filter(
(edge) =>
edge.data.primary_table === table.doc.table ||
edge.data.foreign_table === table.doc.table
)
.map((edge) =>
edge.data.primary_table === table.doc.table
? edge.data.primary_column
: edge.data.foreign_column
)
const newColumns = [...table.doc.columns]
newColumns.sort((a, b) => {
if (columnsInEdges.includes(a.column) && !columnsInEdges.includes(b.column)) return -1
if (!columnsInEdges.includes(a.column) && columnsInEdges.includes(b.column)) return 1
return 0
})
columns.value = newColumns
},
{ immediate: true }
)
function onColumnDragStart(event, column) {
if (event.dataTransfer) {
event.dataTransfer.setData(
'dragging-column',
JSON.stringify({
table: table.doc.table,
column: column.column,
label: column.label,
type: column.type,
})
)
event.dataTransfer.effectAllowed = 'move'
}
}
function onColumnDragOver(event) {
event.preventDefault()
if (event.dataTransfer) {
event.dataTransfer.dropEffect = 'move'
}
}
function onColumnDrop(event, column) {
state.highlightColumn(null)
event.preventDefault()
event.stopPropagation()
const data = event.dataTransfer?.getData('dragging-column')
if (!data) return
const fromColumn = JSON.parse(data)
if (fromColumn.table === table.doc.table) return
const toColumn = {
table: table.doc.table,
column: column.column,
label: column.label,
type: column.type,
}
state.createRelationship(fromColumn, toColumn)
}
function isHighlighted(column) {
if (!state.highlightedColumn) return false
return (
state.highlightedColumn.table === column.table &&
state.highlightedColumn.column === column.column
)
}
function getTopOffset(idx) {
return `${idx * 32 + 8}px`
}
</script>
<template>
<div class="w-56 overflow-hidden rounded bg-white shadow">
<div class="flex items-center border-b bg-gray-50 px-4 py-2">
<span class="truncate font-medium">{{ table.doc.label }}</span>
</div>
<div class="nowheel flex max-h-72 flex-col overflow-y-auto">
<div
v-for="(column, idx) in columns"
:key="column.column"
class="nodrag group relative flex cursor-grab items-center border-b px-3 py-2 text-sm hover:bg-gray-50"
:draggable="true"
@dragover="onColumnDragOver"
@dragstart="onColumnDragStart($event, column)"
@drop="onColumnDrop($event, column)"
@dragenter="state.highlightColumn(column)"
:class="isHighlighted(column) ? 'bg-gray-100' : ''"
>
<component
:is="fieldtypesToIcon[column.type]"
class="mr-2 h-4 w-4 text-gray-500"
></component>
<span class="truncate">{{ column.label }}</span>
<Handle
class="invisible"
:id="column.column"
type="source"
:position="Position.Right"
:style="{
right: '0px',
top: '15px',
}"
/>
<Handle
class="invisible"
:id="column.column"
type="target"
:position="Position.Left"
:style="{
left: '0px',
top: '15px',
}"
/>
</div>
</div>
</div>
</template>
|
2302_79757062/insights
|
frontend/src/datasource/TableNode.vue
|
Vue
|
agpl-3.0
| 3,664
|
<script setup>
import { whenHasValue } from '@/utils'
import { MarkerType, VueFlow, useVueFlow } from '@vue-flow/core'
import { useStorage, watchDebounced } from '@vueuse/core'
import { Grip } from 'lucide-vue-next'
import { computed, inject, nextTick, provide, reactive, ref, watch } from 'vue'
import TableEdge from './TableEdge.vue'
import TableNode from './TableNode.vue'
import useDataSourceTable from './useDataSourceTable'
const dataSource = inject('dataSource')
const searchQuery = ref('')
const filteredList = computed(() => {
if (!searchQuery.value) {
return dataSource.tableList.filter((table) => !table.is_query_based).slice(0, 100)
}
return dataSource.tableList
.filter(
(table) =>
!table.is_query_based &&
table.label.toLowerCase().includes(searchQuery.value.toLowerCase())
)
.slice(0, 100)
})
const state = reactive({
highlightedColumn: null,
highlightColumn(column) {
state.highlightedColumn = column
},
createRelationship(fromColumn, toColumn) {
if (!fromColumn.table || !fromColumn.column || !toColumn.table || !toColumn.column) {
console.warn('Invalid relationship')
return
}
const newEdge = {
id: `${fromColumn.table}.${fromColumn.column} -> ${toColumn.table}.${toColumn.column}`,
source: fromColumn.table,
target: toColumn.table,
sourceHandle: fromColumn.column,
targetHandle: toColumn.column,
type: 'custom',
data: {
primary_table: fromColumn.table,
primary_column: fromColumn.column,
foreign_table: toColumn.table,
foreign_column: toColumn.column,
cardinality: '1:1',
},
markerEnd: MarkerType.ArrowClosed,
}
canvas.addEdges([newEdge])
dataSource.updateTableRelationship(newEdge.data)
},
setCardinality(id, cardinality) {
const edge = canvas.findEdge(id)
if (!edge) return
edge.data.cardinality = cardinality
dataSource.updateTableRelationship(edge.data)
},
deleteRelationship(id) {
const edge = canvas.findEdge(id)
dataSource.deleteTableRelationship(edge.data)
canvas.removeEdges([id])
},
})
provide('state', state)
const canvas = useVueFlow({ nodes: [] })
const storedNodes = useStorage(
`insights:${dataSource.doc.name}:${dataSource.doc.creation}:nodes`,
[]
)
const nodes = computed(() => canvas.nodes.value)
const edges = computed(() => canvas.edges.value)
provide('edges', edges)
// load locally stored nodes
if (storedNodes.value.length) {
canvas.addNodes(storedNodes.value)
const promises = storedNodes.value.map((node) => {
if (node.type == 'table') {
return displayTableRelationships(node.data.tablename)
}
return Promise.resolve()
})
await Promise.all(promises)
}
// when nodes change, store them locally
watchDebounced(
nodes,
(newNodes) => {
if (JSON.stringify(newNodes) == JSON.stringify(storedNodes.value)) return
storedNodes.value = newNodes
},
{ deep: true, debounce: 1000 }
)
function onTableDragStart(event, table) {
if (event.dataTransfer) {
event.dataTransfer.setData('dragging-table', JSON.stringify(table))
event.dataTransfer.effectAllowed = 'move'
}
}
function onTableDragOver(event) {
event.preventDefault()
if (event.dataTransfer) {
event.dataTransfer.dropEffect = 'move'
}
}
const $notify = inject('$notify')
async function onTableDrop(event) {
event.preventDefault()
const table = JSON.parse(event.dataTransfer?.getData('dragging-table'))
if (!table) return
if (canvas.findNode(table.table)) {
$notify({ title: 'Table already added', variant: 'warning' })
return
}
const { left, top } = canvas.vueFlowRef.value.getBoundingClientRect()
const newNode = {
id: table.table,
type: 'table',
data: { tablename: table.name },
position: canvas.project({
x: event.clientX - left,
y: event.clientY - top,
}),
}
canvas.addNodes([newNode])
displayTableRelationships(table.name)
// align node position after drop, so it's centered to the mouse
nextTick(() => {
const node = canvas.findNode(newNode.id)
const stop = watch(
() => node.dimensions,
(dimensions) => {
if (dimensions.width > 0 && dimensions.height > 0) {
node.position = {
x: node.position.x - node.dimensions.width / 2,
y: node.position.y - node.dimensions.height / 2,
}
stop()
}
},
{ deep: true, flush: 'post' }
)
})
}
async function displayTableRelationships(tablename) {
const table = await useDataSourceTable({ name: tablename })
await whenHasValue(() => table.doc.name)
if (!table.doc.table_links) return
table.doc.table_links.forEach((link) => {
const foreignTableNode = canvas.findNode(link.foreign_table)
if (!foreignTableNode) return
const edgeData = {
primary_table: table.doc.table,
primary_column: link.primary_key,
foreign_table: link.foreign_table,
foreign_column: link.foreign_key,
cardinality: link.cardinality,
}
const newEdge = {
id: `${table.doc.table}.${link.primary_key} -> ${link.foreign_table}.${link.foreign_key}`,
source: table.doc.table,
target: link.foreign_table,
sourceHandle: link.primary_key,
targetHandle: link.foreign_key,
type: 'custom',
data: edgeData,
markerEnd: MarkerType.ArrowClosed,
}
if (!canvas.findEdge(newEdge.id)) {
canvas.addEdges([newEdge])
}
})
}
function calculatePosition(idx) {
const startX = 50
const startY = 50
const nodeWidth = 300
const nodeHeight = 300
const canvasWidth = 1000
const canvasHeight = Infinity
const x = startX + (idx % 4) * nodeWidth
const y = startY + Math.floor(idx / 4) * nodeHeight
return canvas.project({ x, y })
}
function onEdgeChange(args) {
if (!args?.[0]) return
if (args[0].type == 'remove') {
const [from, to] = args[0].id.split(' -> ')
const [fromTable, fromColumn] = from.split('.')
const [toTable, toColumn] = to.split('.')
dataSource.deleteTableRelationship({
primary_table: fromTable,
primary_column: fromColumn,
foreign_table: toTable,
foreign_column: toColumn,
})
}
}
</script>
<template>
<div class="relative flex flex-1 items-center justify-center bg-gray-50" @drop="onTableDrop">
<VueFlow @dragover="onTableDragOver" @edges-change="onEdgeChange">
<template #node-table="{ data }">
<Suspense>
<TableNode :tablename="data.tablename" />
<template #fallback>
<div
class="flex w-56 items-center justify-center overflow-hidden rounded bg-white py-8 shadow"
>
<LoadingIndicator class="h-6 w-6 text-gray-400" />
</div>
</template>
</Suspense>
</template>
<template #edge-custom="props">
<TableEdge v-bind="props" />
</template>
</VueFlow>
<div
v-if="!nodes.length"
class="absolute top-1/2 left-1/2 -translate-x-1/2 -translate-y-1/2 transform text-center text-gray-700"
>
Drag and drop tables from the left panel to create relationships.
</div>
</div>
<div class="flex w-[21rem] flex-shrink-0 flex-col gap-3 overflow-hidden bg-white p-4 shadow">
<div class="flex items-center justify-between">
<div class="text-xl font-medium">Tables</div>
</div>
<Input placeholder="Search" icon-left="search" v-model="searchQuery" />
<div class="flex-1 overflow-hidden">
<div
v-if="filteredList.length"
class="flex h-full flex-col gap-2 overflow-y-auto overflow-x-hidden overflow-y-hidden"
>
<div
v-for="table in filteredList"
:key="table.name"
class="group -mx-1 flex cursor-pointer items-center justify-between rounded-md px-2 py-1 hover:bg-gray-100"
:draggable="true"
@dragstart="onTableDragStart($event, table)"
>
<div class="flex items-center space-x-2 py-1">
<Grip class="h-4 w-4 rotate-90 text-gray-600" />
<span> {{ table.label }} </span>
</div>
</div>
</div>
<div v-if="!filteredList.length" class="flex h-full items-center justify-center">
<div class="text-center text-gray-600">
No tables.
<div class="mt-1 text-base text-gray-700">No tables to display.</div>
</div>
</div>
</div>
</div>
</template>
|
2302_79757062/insights
|
frontend/src/datasource/TableRelationshipEditor.vue
|
Vue
|
agpl-3.0
| 7,933
|
<script setup>
import { computed } from 'vue'
import FileSourceForm from './FileSourceForm.vue'
const emit = defineEmits(['update:show'])
const props = defineProps({ show: Boolean })
const show = computed({
get: () => props.show,
set: (val) => emit('update:show', val),
})
</script>
<template>
<Dialog :options="{ title: 'CSV Import' }" v-model="show">
<template #body-content>
<FileSourceForm @submit="show = false" />
</template>
</Dialog>
</template>
|
2302_79757062/insights
|
frontend/src/datasource/UploadCSVFileDialog.vue
|
Vue
|
agpl-3.0
| 467
|
import { getDocumentResource } from '@/api'
import useCacheStore from '@/stores/cacheStore'
import { computed, reactive, ref, UnwrapRef } from 'vue'
function useDataSource(name: string) {
const cacheStore = useCacheStore()
if (cacheStore.getDataSource(name)) {
return cacheStore.getDataSource(name)
}
const resource: DataSourceResource = getDocumentResource('Insights Data Source', name)
resource.fetchIfNeeded()
const doc = computed({
get: () => resource.doc || {},
set: (value: object) => (resource.doc = value),
})
const tableList = ref<DataSourceTableListItem[]>([])
const queryList = ref<QueryAsTableListItem[]>([])
const dropdownOptions = ref<DataSourceTableOption[]>([])
const groupedTableOptions = ref<DataSourceTableGroupedOption[]>([])
async function fetchTables() {
const promises = [resource.get_tables.submit(), resource.get_queries.submit()]
const responses = await Promise.all(promises)
tableList.value = responses[0]
queryList.value = responses[1]
dropdownOptions.value = makeDropdownOptions()
groupedTableOptions.value = makeGroupedTableOptions()
return tableList.value
}
function makeDropdownOptions() {
if (!tableList.value?.length) return []
return (
tableList.value
.filter((t) => !t.hidden)
// remove duplicates
.filter((sourceTable, index, self) => {
return (
self.findIndex((t) => {
return t.table === sourceTable.table
}) === index
)
})
.map((sourceTable) => {
return {
table: sourceTable.table,
value: sourceTable.table,
label: sourceTable.label,
description: sourceTable.table,
data_source: name,
}
})
)
}
function makeGroupedTableOptions() {
if (!tableList.value?.length) return []
const tablesByGroup: Record<string, DataSourceTableOption[]> = {
Tables: [],
Queries: [],
}
tableList.value
.filter((t) => !t.hidden && !t.is_query_based)
.forEach((table: DataSourceTableListItem) => {
tablesByGroup['Tables'].push({
table: table.table,
label: table.label,
value: table.table,
description: table.table,
data_source: name,
})
})
queryList.value.forEach((query: QueryAsTableListItem) => {
tablesByGroup['Queries'].push({
table: query.name,
label: query.title,
value: query.name,
description: query.name,
data_source: name,
})
})
return Object.entries(tablesByGroup).map(([group, tables]) => {
return { group, items: tables }
})
}
function updateTableRelationship(tableRelationship: TableRelationship) {
return resource.update_table_link.submit({ data: tableRelationship })
}
function deleteTableRelationship(tableRelationship: TableRelationship) {
return resource.delete_table_link.submit({ data: tableRelationship })
}
const dataSource: DataSource = reactive({
doc,
tableList,
dropdownOptions,
groupedTableOptions,
loading: resource.loading,
fetchTables,
updateTableRelationship,
deleteTableRelationship,
syncTables: () => resource.enqueue_sync_tables.submit(),
delete: () => resource.delete.submit(),
})
cacheStore.setDataSource(name, dataSource)
return dataSource
}
type TableRelationship = {
primary_table: string
secondary_table: string
primary_column: string
secondary_column: string
cardinality: string
}
export default useDataSource
export type DataSource = UnwrapRef<{
doc: object
tableList: DataSourceTableListItem[]
dropdownOptions: DataSourceTableOption[]
groupedTableOptions: DataSourceTableGroupedOption[]
loading: boolean
fetchTables: () => Promise<DataSourceTableListItem[]>
updateTableRelationship: (tableRelationship: TableRelationship) => Promise<any>
deleteTableRelationship: (tableRelationship: TableRelationship) => Promise<any>
syncTables: () => Promise<any>
delete: () => Promise<any>
}>
|
2302_79757062/insights
|
frontend/src/datasource/useDataSource.ts
|
TypeScript
|
agpl-3.0
| 3,830
|
import { fetchTableName, getDocumentResource } from '@/api'
import useCacheStore from '@/stores/cacheStore'
import { whenHasValue } from '@/utils'
import { useStorage } from '@vueuse/core'
import { UnwrapRef, computed, reactive } from 'vue'
export type GetTableParams =
| {
name: string
}
| {
table: string
data_source: string
}
async function useDataSourceTable(params: GetTableParams) {
const name = await getTableName(params)
const cacheStore = useCacheStore()
if (cacheStore.getTable(name)) {
return cacheStore.getTable(name)
}
const resource: TableResource = getDocumentResource('Insights Table', name)
await resource.fetchIfNeeded()
await whenHasValue(() => resource.doc)
const doc = computed<any>({
get: () => resource.doc || {},
set: (value: any) => (resource.doc = value),
})
const columns = computed(() => {
if (!doc.value?.columns) return []
return doc.value.columns.map((column: any) => {
return {
column: column.column,
type: column.type,
label: column.label,
table: doc.value.table,
table_label: doc.value.label,
data_source: doc.value.data_source,
}
})
})
const table: DataSourceTable = reactive({
doc,
columns,
rows: computed(() => resource.getPreview.data),
loading: resource.loading,
syncing: resource.syncTable.loading,
sync: () => resource.syncTable.submit(),
fetchPreview: () => resource.getPreview.submit(),
updateVisibility: (hidden: boolean) => {
return resource.updateVisibility.submit({ hidden })
},
updateColumnType: (column: any) => {
return resource.update_column_type.submit({
column: column.column,
newtype: column.type,
})
},
})
cacheStore.setTable(name, table)
return table
}
const today = new Date().toISOString().split('T')[0]
const dailyCacheKey = `insights:table-name-cache-{${today}}`
for (const key of Object.keys(localStorage)) {
if (key.startsWith('insights:table-name-cache-')) {
localStorage.removeItem(key)
}
}
type TableNameCache = Record<string, string>
const tableNameCache = useStorage<TableNameCache>(dailyCacheKey, {})
async function getTableName(params: GetTableParams): Promise<string> {
if ('name' in params) return params.name
const key = `${params.data_source}:${params.table}`
if (tableNameCache.value[key]) {
return tableNameCache.value[key]
}
const _name = await fetchTableName(params.data_source, params.table)
tableNameCache.value[key] = _name
return _name
}
export default useDataSourceTable
export type DataSourceTable = UnwrapRef<{
doc: any
columns: any[]
rows: any[]
loading: boolean
syncing: boolean
sync: () => Promise<any>
fetchPreview: () => Promise<any>
updateColumnType: (column: any) => Promise<any>
updateVisibility: (hidden: boolean) => Promise<any>
}>
|
2302_79757062/insights
|
frontend/src/datasource/useDataSourceTable.ts
|
TypeScript
|
agpl-3.0
| 2,777
|
import {
Button,
FeatherIcon,
Input,
onOutsideClickDirective,
Dialog,
ErrorMessage,
Dropdown,
Badge,
Avatar,
Tooltip,
LoadingIndicator,
FormControl,
} from 'frappe-ui'
import Checkbox from '@/components/Controls/Checkbox.vue'
import Autocomplete from '@/components/Controls/Autocomplete.vue'
import Popover from '@/components/Popover.vue'
import utils from './utils'
import { createToast } from './utils/toasts'
import dayjs from './utils/dayjs'
export function registerGlobalComponents(app) {
app.component('Input', Input)
app.component('Badge', Badge)
app.component('Button', Button)
app.component('Dialog', Dialog)
app.component('Avatar', Avatar)
app.component('Popover', Popover)
app.component('Tooltip', Tooltip)
app.component('Checkbox', Checkbox)
app.component('Dropdown', Dropdown)
app.component('FormControl', FormControl)
app.component('LoadingIndicator', LoadingIndicator)
app.component('Autocomplete', Autocomplete)
app.component('ErrorMessage', ErrorMessage)
app.component('FeatherIcon', FeatherIcon)
app.directive('on-outside-click', onOutsideClickDirective)
}
export function registerControllers(app) {
app.provide('$utils', utils)
app.provide('$dayjs', dayjs)
app.provide('$notify', createToast)
if (import.meta.env.DEV) {
window.$utils = utils
window.$dayjs = dayjs
window.$notify = createToast
}
}
|
2302_79757062/insights
|
frontend/src/globals.js
|
JavaScript
|
agpl-3.0
| 1,358
|
<script setup>
import sessionStore from '@/stores/sessionStore'
import { inject } from 'vue'
import HomeOnboarding from './HomeOnboarding.vue'
import HomePinnedItems from './HomePinnedItems.vue'
import HomeQuickActions from './HomeQuickActions.vue'
import HomeRecentRecords from './HomeRecentRecords.vue'
const session = sessionStore()
const $dayjs = inject('$dayjs')
const today = $dayjs().format('dddd, D MMMM')
document.title = 'Home | Frappe Insights'
</script>
<template>
<div class="flex flex-1 flex-col space-y-8 overflow-hidden bg-white p-6">
<div class="space-y-2">
<div class="text-3xl font-bold text-gray-900">
Hello, {{ session.user.first_name }} 👋
</div>
<div class="text-lg text-gray-600">{{ today }}</div>
</div>
<HomeOnboarding></HomeOnboarding>
<HomeQuickActions></HomeQuickActions>
<HomePinnedItems></HomePinnedItems>
<HomeRecentRecords></HomeRecentRecords>
</div>
</template>
|
2302_79757062/insights
|
frontend/src/home/Home.vue
|
Vue
|
agpl-3.0
| 929
|
<script setup>
import { useStorage } from '@vueuse/core'
import { computed, reactive, ref } from 'vue'
import { useRouter } from 'vue-router'
import ProgressRing from './ProgressRing.vue'
const router = useRouter()
const showOnboarding = ref(false)
const steps = reactive([
{
title: 'Connect Your Data',
name: 'connect_data',
description:
"Insights needs access to your data to start analyzing it. Don't worry, we do not store your data.",
primary_button: {
label: 'Create Data Source',
action: () => router.push('/data-source#new'),
},
},
{
title: 'Build Your First Query',
name: 'build_query',
description:
"Let's introduce you to the query builder, where you'll be spending most of your time building queries.",
primary_button: {
label: 'Build Query',
action: () => router.push('/query#new'),
},
},
{
title: 'Create Your First Dashboard',
name: 'create_dashboard',
description:
'Organize your visualizations meaningfully by creating a dashboard for you and your team.',
primary_button: {
label: 'Create Dashboard',
action: () => router.push('/dashboard#new'),
},
},
{
title: 'All set! 🎉',
name: 'all_set',
description: 'You are all set to use Insights. We hope you enjoy using it!',
primary_button: {
label: 'Close',
action: () => completeOnboarding(),
},
},
])
const initialOnboardingStatus = steps.reduce((acc, step) => ({ [step.name]: false }), {})
const onboarding = useStorage('insights:onboardingStatus', initialOnboardingStatus)
const currentStep = computed(() => {
return steps.findIndex((step) => !onboarding.value[step.name])
})
function skipCurrentStep() {
onboarding.value = { ...onboarding.value, [steps[currentStep.value].name]: true }
}
function completeOnboarding() {
onboarding.value = { ...onboarding.value, all_set: true }
showOnboarding.value = false
}
</script>
<template>
<div v-if="!onboarding.all_set && currentStep < steps.length">
<div class="flex items-center justify-between rounded bg-gray-50 px-4 py-3">
<div class="flex items-center space-x-2">
<ProgressRing
class="text-gray-900"
:progress="(currentStep / steps.length) * 100"
:progressLabel="currentStep"
/>
<div>
<div class="text-lg font-bold text-gray-900">Get Started with Insights</div>
<div class="mt-1 text-gray-600">
Follow through a couple of steps to get yourself familiar with Insights.
</div>
</div>
</div>
<div class="flex justify-end space-x-2">
<Button variant="outline" iconLeft="x" @click="completeOnboarding"> Skip </Button>
<Button variant="solid" iconRight="arrow-right" @click="showOnboarding = true">
{{ steps.length - currentStep }} step(s) left
</Button>
</div>
</div>
</div>
<Dialog
v-if="!onboarding.all_set && currentStep < steps.length"
v-model="showOnboarding"
:options="{
title: steps[currentStep].title,
size: '2xl',
}"
>
<template #body-content>
<div class="flex flex-col items-center justify-center space-y-4">
<div
v-if="steps[currentStep].name !== 'all_set'"
:key="steps[currentStep].name"
class="flex w-full items-center justify-center overflow-hidden rounded shadow-md"
>
<video autoplay loop muted class="h-full w-full">
<source
v-if="steps[currentStep].name === 'connect_data'"
src="../assets/add-data-source-new.mp4"
type="video/mp4"
/>
<source
v-if="steps[currentStep].name === 'build_query'"
src="../assets/build-first-query-new.mp4"
type="video/mp4"
/>
<source
v-if="steps[currentStep].name === 'create_dashboard'"
src="../assets/create-first-dashboard-new.mp4"
type="video/mp4"
/>
Your browser does not support the video tag.
</video>
</div>
<div class="">
{{ steps[currentStep].description }}
</div>
<div class="flex w-full justify-end space-x-2">
<Button
v-if="steps[currentStep].name !== 'all_set'"
variant="ghost"
@click="skipCurrentStep"
>
Skip
</Button>
<Button variant="solid" @click="steps[currentStep].primary_button.action">
{{ steps[currentStep].primary_button.label }}
</Button>
</div>
</div>
</template>
</Dialog>
</template>
|
2302_79757062/insights
|
frontend/src/home/HomeOnboarding.vue
|
Vue
|
agpl-3.0
| 4,293
|
<script setup>
import { ref } from 'vue'
const showNewPinDialog = ref(false)
</script>
<template>
<div>
<div class="flex items-center space-x-2">
<div class="rounded bg-gray-100 p-1">
<FeatherIcon name="bookmark" class="h-4 w-4" />
</div>
<div class="text-lg">Pinned Charts</div>
</div>
<div class="mt-4 grid grid-cols-1 gap-4 md:grid-cols-2 lg:grid-cols-4">
<div
class="col-span-1 flex cursor-pointer items-center space-x-2 rounded border border-dashed bg-gray-50 p-4 transition-all hover:border-gray-400"
@click="showNewPinDialog = true"
>
<div class="rounded p-1">
<FeatherIcon name="plus" class="h-4 w-4 text-gray-600" />
</div>
<div class="text-lg text-gray-600">Select a chart</div>
</div>
</div>
</div>
<Dialog v-model="showNewPinDialog">
<!-- show a coming soon message for now -->
<template #body>
<div class="flex flex-col items-center justify-center space-y-4 p-6">
<div class="h-72 w-full rounded bg-gray-200"></div>
<div class="">Coming soon!</div>
</div>
</template>
</Dialog>
</template>
|
2302_79757062/insights
|
frontend/src/home/HomePinnedItems.vue
|
Vue
|
agpl-3.0
| 1,083
|
<template>
<div>
<div class="flex items-center space-x-2">
<div class="rounded bg-gray-100 p-1">
<FeatherIcon name="arrow-up-right" class="h-4 w-4" />
</div>
<div class="text-lg">Quick Actions</div>
</div>
<div class="mt-4 grid grid-cols-1 gap-4 md:grid-cols-2 lg:grid-cols-4">
<div
class="col-span-1 flex cursor-pointer items-center justify-between rounded border border-transparent bg-white p-4 shadow transition-all hover:border-gray-400"
@click="$router.push('/data-source#new')"
>
<div class="text-lg font-medium text-gray-900">Connect Data Source</div>
<div class="rounded bg-gray-100 p-1">
<FeatherIcon name="plus" class="h-4 w-4 text-gray-900" />
</div>
</div>
<div
class="col-span-1 flex cursor-pointer items-center justify-between rounded border border-transparent bg-white p-4 shadow transition-all hover:border-gray-400"
@click="$router.push('/query#new')"
>
<div class="text-lg font-medium text-gray-900">Create a Query</div>
<div class="rounded bg-gray-100 p-1">
<FeatherIcon name="plus" class="h-4 w-4 text-gray-900" />
</div>
</div>
<div
class="col-span-1 flex cursor-pointer items-center justify-between rounded border border-transparent bg-white p-4 shadow transition-all hover:border-gray-400"
@click="$router.push('/dashboard#new')"
>
<div class="text-lg font-medium text-gray-900">Create a Dashboard</div>
<div class="rounded bg-gray-100 p-1">
<FeatherIcon name="plus" class="h-4 w-4 text-gray-900" />
</div>
</div>
</div>
</div>
</template>
|
2302_79757062/insights
|
frontend/src/home/HomeQuickActions.vue
|
Vue
|
agpl-3.0
| 1,588
|
<script setup>
import { call } from 'frappe-ui'
import { inject, ref } from 'vue'
import { useRouter } from 'vue-router'
const $dayjs = inject('$dayjs')
const recent_records = ref([])
call('insights.api.home.get_last_viewed_records').then((data) => {
recent_records.value = data.map((d) => {
const record_type = d.reference_doctype.replace('Insights ', '')
const routeName = record_type.replace(' ', '')
return {
title: d.title,
type: record_type,
name: d.reference_name,
notebook: d.notebook,
last_viewed: $dayjs(d.creation).format('MMM DD, YYYY hh:mm A'),
last_viewed_from_now: `Last viewed ${$dayjs(d.creation).fromNow()}`,
}
})
})
const router = useRouter()
function openRecord(row) {
const { type, notebook, name } = row
switch (type) {
case 'Notebook Page':
return router.push(`/notebook/${notebook}/${name}`)
case 'Dashboard':
return router.push(`/dashboard/${name}`)
case 'Query':
return router.push(`/query/build/${name}`)
default:
break
}
}
</script>
<template>
<div class="flex h-full flex-col overflow-hidden">
<div class="flex items-center space-x-2">
<div class="rounded bg-gray-100 p-1">
<FeatherIcon name="clock" class="h-4 w-4" />
</div>
<div class="text-lg">Recently Viewed</div>
</div>
<div class="mt-3 flex-1 overflow-hidden p-1">
<!-- list of recent records -->
<ul
v-if="recent_records?.length > 0"
class="relative flex flex-1 flex-col overflow-y-auto"
>
<li class="border-b"></li>
<li
v-for="(row, idx) in recent_records"
:key="idx"
class="flex cursor-pointer items-center gap-4 border-b transition-colors hover:bg-gray-50"
@click="openRecord(row)"
>
<div>
<FeatherIcon name="arrow-up-right" class="h-4 w-4 text-gray-600" />
</div>
<div
v-for="(key, idx) in ['title', 'type', 'last_viewed_from_now']"
class="overflow-hidden text-ellipsis whitespace-nowrap py-3"
:class="[idx === 0 ? 'w-[30%] ' : 'flex-1 text-gray-600']"
>
<span>
{{ row[key] }}
</span>
</div>
</li>
</ul>
<!-- empty state -->
<div v-else class="flex h-full w-full items-center justify-center">
<div class="flex flex-col items-center space-y-2">
<div class="text-lg text-gray-600">No recent records</div>
<div class="text-sm text-gray-600">
You can view your recently viewed records here
</div>
</div>
</div>
</div>
</div>
</template>
|
2302_79757062/insights
|
frontend/src/home/HomeRecentRecords.vue
|
Vue
|
agpl-3.0
| 2,465
|
<script setup>
import { computed } from 'vue'
const props = defineProps({
progress: {
type: Number,
default: 0,
},
progressLabel: {
type: String,
default: '',
},
radius: {
type: Number,
default: 26,
},
stroke: {
type: Number,
default: 4,
},
})
const normalizedRadius = computed(() => props.radius - props.stroke * 2)
const circumference = computed(() => normalizedRadius.value * 2 * Math.PI)
const strokeDashoffset = computed(
() => circumference.value - (props.progress / 100) * circumference.value
)
</script>
<template>
<div class="relative flex items-center justify-center rounded-full">
<svg :height="radius * 2" :width="radius * 2">
<circle
class="text-gray-300"
stroke="currentColor"
fill="transparent"
:stroke-width="stroke"
:r="normalizedRadius"
:cx="radius"
:cy="radius"
/>
<circle
class="text-gray-900"
stroke-linecap="round"
stroke="currentColor"
fill="transparent"
:stroke-width="stroke"
:stroke-dasharray="circumference"
:stroke-dashoffset="strokeDashoffset"
:r="normalizedRadius"
:cx="radius"
:cy="radius"
/>
</svg>
<span class="absolute font-bold">
{{ progressLabel }}
</span>
</div>
</template>
<style scoped>
circle {
transition: stroke-dashoffset 0.35s;
transform: rotate(-90deg);
transform-origin: 50% 50%;
}
</style>
|
2302_79757062/insights
|
frontend/src/home/ProgressRing.vue
|
Vue
|
agpl-3.0
| 1,363
|
@import './assets/Inter/inter.css';
@import './assets/FiraCode/fira_code.css';
@import 'frappe-ui/src/style.css';
@import '@vue-flow/core/dist/style.css';
@import '@vue-flow/core/dist/theme-default.css';
.dataframe th {
@apply whitespace-nowrap border-r border-b bg-gray-50 py-2 px-4 text-left text-sm font-medium text-gray-700;
}
.dataframe td {
@apply whitespace-nowrap border-r border-b bg-white py-2 px-4 text-right text-sm text-gray-700;
}
.dataframe tr > th:first-child {
@apply sticky left-0;
}
.font-code {
@apply !font-mono;
}
.tnum {
font-feature-settings: 'tnum';
}
/* Code Control */
.cm-editor {
user-select: text;
padding: 0px !important;
position: relative !important;
}
.cm-gutters {
@apply !border-r !bg-transparent !px-1 !text-center !text-sm !leading-6 !text-gray-600;
}
.cm-gutters {
@apply !border-r !bg-transparent !text-sm !leading-6 !text-gray-600;
}
.cm-foldGutter span {
@apply !hidden !opacity-0;
}
.cm-gutterElement {
@apply !text-center;
}
.cm-activeLine {
@apply !bg-transparent;
}
.cm-activeLineGutter {
@apply !bg-transparent text-gray-600;
}
.cm-editor {
height: 100%;
width: 100%;
border-radius: 0.375rem;
padding: 0.5rem;
user-select: text;
}
.cm-placeholder {
@apply !leading-6 !text-gray-500;
}
.cm-content {
padding: 6px 0px !important;
}
.cm-scroller {
@apply !font-mono !leading-6 !text-gray-600;
}
.cm-matchingBracket {
font-weight: 500 !important;
background: none !important;
border-bottom: 1px solid #000 !important;
outline: none !important;
}
.cm-focused {
outline: none !important;
}
.cm-tooltip-autocomplete {
border: 1px solid #fafafa !important;
padding: 0.25rem;
background-color: #fff !important;
border-radius: 0.375rem;
filter: drop-shadow(0 4px 3px rgb(0 0 0 / 0.07)) drop-shadow(0 2px 2px rgb(0 0 0 / 0.06));
}
.cm-tooltip-autocomplete > ul {
font-family: 'Inter' !important;
}
.cm-tooltip-autocomplete ul li[aria-selected='true'] {
@apply !rounded !bg-gray-200/80;
color: #000 !important;
}
@layer components {
/* Works on Firefox */
* {
scrollbar-width: thin;
scrollbar-color: #c0c6cc #ebeef0;
}
html {
scrollbar-width: auto;
}
/* Works on Chrome, Edge, and Safari */
*::-webkit-scrollbar-thumb {
background: #e2e8f0;
border-radius: 6px;
}
*::-webkit-scrollbar-track,
*::-webkit-scrollbar-corner {
background: #f8fafc;
}
*::-webkit-scrollbar {
width: 0px;
height: 6px;
}
body::-webkit-scrollbar {
width: 0px;
height: 12px;
}
}
.fade-enter-active,
.fade-leave-active {
transition: opacity 0.1s ease;
}
.fade-enter-from,
.fade-leave-to {
opacity: 0;
}
|
2302_79757062/insights
|
frontend/src/index.css
|
CSS
|
agpl-3.0
| 2,593
|
<template>
<div class="flex h-full w-full flex-col bg-gray-50">
<div class="flex items-center justify-between bg-white px-5 py-2.5 shadow-sm">
<slot name="navbar"></slot>
</div>
<div class="flex flex-1 overflow-hidden">
<slot name="content"></slot>
<div v-if="$slots.sidebar" class="flex flex-shrink-0 overflow-hidden">
<slot name="sidebar"></slot>
</div>
</div>
</div>
</template>
|
2302_79757062/insights
|
frontend/src/layouts/BaseLayout.vue
|
Vue
|
agpl-3.0
| 408
|
import { autoAnimatePlugin } from '@formkit/auto-animate/vue'
import { frappeRequest, setConfig } from 'frappe-ui'
import { GridItem, GridLayout } from 'grid-layout-plus'
import { createPinia } from 'pinia'
import { createApp } from 'vue'
import App from './App.vue'
import './index.css'
import router from './router'
import { initSocket } from './socket'
import { createToast } from './utils/toasts'
import { registerControllers, registerGlobalComponents } from './globals'
const app = createApp(App)
const pinia = createPinia()
app.use(pinia)
setConfig('resourceFetcher', (options) => {
return frappeRequest({
...options,
onError(err) {
if (err.messages && err.messages[0]) {
createToast({
title: 'Error',
variant: 'error',
message: err.messages[0],
})
}
},
})
})
app.use(router)
app.use(autoAnimatePlugin)
app.component('grid-layout', GridLayout)
app.component('grid-item', GridItem)
app.provide('$socket', initSocket())
registerGlobalComponents(app)
registerControllers(app)
app.mount('#app')
|
2302_79757062/insights
|
frontend/src/main.js
|
JavaScript
|
agpl-3.0
| 1,039
|
<script setup lang="jsx">
import PageBreadcrumbs from '@/components/PageBreadcrumbs.vue'
import useNotebook from '@/notebook/useNotebook'
import useNotebooks from '@/notebook/useNotebooks'
import { updateDocumentTitle } from '@/utils'
import { ListView } from 'frappe-ui'
import { PlusIcon, SearchIcon } from 'lucide-vue-next'
import { ref } from 'vue'
import { useRouter } from 'vue-router'
const props = defineProps({ notebook: String })
const router = useRouter()
const notebook = useNotebook(props.notebook)
notebook.reload()
const searchQuery = ref('')
async function createNotebookPage() {
const page_name = await notebook.createPage(props.notebook)
router.push({
name: 'NotebookPage',
params: {
notebook: props.notebook,
name: page_name,
},
})
}
const showDeleteDialog = ref(false)
async function handleDelete() {
await notebook.deleteNotebook()
showDeleteDialog.value = false
await useNotebooks().reload()
router.push({ name: 'NotebookList' })
}
const pageMeta = ref({ title: 'Notebook' })
updateDocumentTitle(pageMeta)
</script>
<template>
<header class="sticky top-0 z-10 flex items-center justify-between bg-white px-5 py-2.5">
<PageBreadcrumbs
class="h-7"
:items="[
{ label: 'Notebooks', route: { path: '/notebook' } },
{ label: notebook.doc.title || notebook.doc.name },
]"
/>
<div class="space-x-2.5">
<Button label="New Page" variant="solid" @click="() => createNotebookPage()">
<template #prefix>
<PlusIcon class="w-4" />
</template>
</Button>
</div>
</header>
<div class="mb-4 flex h-full flex-col gap-2 overflow-auto px-4">
<div class="flex gap-2 overflow-visible py-1">
<FormControl placeholder="Search by Title" v-model="searchQuery" :debounce="300">
<template #prefix>
<SearchIcon class="h-4 w-4 text-gray-500" />
</template>
</FormControl>
<Dropdown
placement="left"
:button="{ icon: 'more-horizontal', variant: 'ghost' }"
:options="[
{
label: 'Delete',
icon: 'trash-2',
onClick: () => (showDeleteDialog = true),
},
]"
/>
</div>
<ListView
:columns="[
{ label: 'Title', key: 'title' },
{ label: 'Created', key: 'created_from_now' },
{ label: 'Modified', key: 'modified_from_now' },
]"
:rows="notebook.pages"
:row-key="'name'"
:options="{
showTooltip: false,
getRowRoute: (page) => ({
name: 'NotebookPage',
params: { notebook: notebook.doc.name, name: page.name },
}),
emptyState: {
title: 'No pages.',
description: 'No pages to display.',
button: {
label: 'New Page',
variant: 'solid',
onClick: () => createNotebookPage(),
},
},
}"
>
</ListView>
</div>
<Dialog
:options="{
title: 'Delete Notebook',
icon: { name: 'trash', variant: 'solid', theme: 'red' },
}"
v-model="showDeleteDialog"
:dismissable="true"
>
<template #body-content>
<p class="text-base text-gray-600">Are you sure you want to delete this notebook?</p>
</template>
<template #actions>
<Button variant="outline" @click="showDeleteDialog = false">Cancel</Button>
<Button variant="solid" theme="red" @click="handleDelete" :loading="notebook.deleting">
Yes
</Button>
</template>
</Dialog>
</template>
|
2302_79757062/insights
|
frontend/src/notebook/Notebook.vue
|
Vue
|
agpl-3.0
| 3,276
|
<script setup lang="jsx">
import PageBreadcrumbs from '@/components/PageBreadcrumbs.vue'
import useNotebooks from '@/notebook/useNotebooks'
import { updateDocumentTitle } from '@/utils'
import { ListView } from 'frappe-ui'
import { PlusIcon, SearchIcon } from 'lucide-vue-next'
import { ref } from 'vue'
import { useRouter } from 'vue-router'
const router = useRouter()
const notebooks = useNotebooks()
notebooks.reload()
const searchQuery = ref('')
const TitleWithIcon = (props) => (
<div class="flex items-center">
<FeatherIcon name="folder" class="h-4 w-4 text-gray-600" />
<span class="ml-3">{props.row.title}</span>
</div>
)
const new_notebook_dialog = ref(false)
const new_notebook_title = ref('')
async function createNotebook() {
await notebooks.createNotebook(new_notebook_title.value)
new_notebook_dialog.value = false
new_notebook_title.value = ''
}
async function createNotebookPage() {
const uncategorized = notebooks.list.find((notebook) => notebook.title === 'Uncategorized')
const page_name = await notebooks.createPage(uncategorized.name)
router.push({
name: 'NotebookPage',
params: {
notebook: uncategorized.name,
name: page_name,
},
})
}
const pageMeta = ref({ title: 'Notebooks' })
updateDocumentTitle(pageMeta)
</script>
<template>
<header class="sticky top-0 z-10 flex items-center justify-between bg-white px-5 py-2.5">
<PageBreadcrumbs class="h-7" :items="[{ label: 'Notebooks' }]" />
<div class="space-x-2.5">
<Button label="New Notebook" variant="solid" @click="new_notebook_dialog = true">
<template #prefix>
<PlusIcon class="w-4" />
</template>
</Button>
</div>
</header>
<div class="mb-4 flex h-full flex-col gap-2 overflow-auto px-4">
<div class="flex gap-2 overflow-visible py-1">
<FormControl placeholder="Search by Title" v-model="searchQuery" :debounce="300">
<template #prefix>
<SearchIcon class="h-4 w-4 text-gray-500" />
</template>
</FormControl>
</div>
<ListView
:columns="[
{ label: 'Title', key: 'title' },
{ label: 'Created', key: 'created_from_now' },
{ label: 'Modified', key: 'modified_from_now' },
]"
:rows="notebooks.list"
:row-key="'name'"
:options="{
showTooltip: false,
getRowRoute: (notebook) => ({
name: 'Notebook',
params: { notebook: notebook.name },
}),
emptyState: {
title: 'No notebooks.',
description: 'No notebooks to display.',
button: {
label: 'New Notebook',
variant: 'solid',
onClick: () => (new_notebook_dialog = true),
},
},
}"
>
</ListView>
</div>
<Dialog :options="{ title: 'New Notebook' }" v-model="new_notebook_dialog">
<template #body-content>
<div class="space-y-4">
<Input
type="text"
label="Title"
placeholder="Enter a suitable title..."
v-model="new_notebook_title"
/>
</div>
</template>
<template #actions>
<Button variant="solid" @click="createNotebook" :loading="notebooks.creating">
Create
</Button>
</template>
</Dialog>
</template>
|
2302_79757062/insights
|
frontend/src/notebook/NotebookList.vue
|
Vue
|
agpl-3.0
| 3,056
|
<script setup lang="jsx">
import ContentEditable from '@/components/ContentEditable.vue'
import PageBreadcrumbs from '@/components/PageBreadcrumbs.vue'
import useNotebook from '@/notebook/useNotebook'
import useNotebookPage from '@/notebook/useNotebookPage'
import { updateDocumentTitle } from '@/utils'
import { computed, provide } from 'vue'
import NotebookPageDropdown from './NotebookPageDropdown.vue'
import TipTap from './tiptap/TipTap.vue'
const props = defineProps({ notebook: String, name: String })
const page = useNotebookPage(props.name)
const notebook = useNotebook(props.notebook)
provide('page', page)
const pageMeta = computed(() => ({
title: page.doc?.title,
subtitle: page.doc?.notebook,
}))
updateDocumentTitle(pageMeta)
</script>
<template>
<header class="sticky top-0 z-10 flex items-center justify-between bg-white px-5 py-2.5">
<PageBreadcrumbs
class="h-7"
:items="[
{ label: 'Notebooks', route: { path: '/notebook' } },
{
label: notebook.doc.title || notebook.doc.name,
route: { path: `/notebook/${notebook.doc.name}` },
},
{ label: page.doc.title },
]"
/>
</header>
<div class="flex flex-1 overflow-hidden bg-white px-6 py-2">
<div
v-if="page.doc.name"
class="h-full w-full overflow-y-auto bg-white pb-96 pt-16 text-base scrollbar-hide"
>
<div class="w-full px-[6rem] lg:mx-auto lg:max-w-[62rem]">
<div class="flex items-center">
<ContentEditable
class="flex-1 text-[36px] font-bold"
v-model="page.doc.title"
placeholder="Untitled Analysis"
></ContentEditable>
<NotebookPageDropdown />
</div>
<TipTap class="my-6" v-model:content="page.doc.content" />
</div>
</div>
</div>
</template>
|
2302_79757062/insights
|
frontend/src/notebook/NotebookPage.vue
|
Vue
|
agpl-3.0
| 1,721
|
<script setup>
import { inject, ref } from 'vue'
import { useRouter } from 'vue-router'
const page = inject('page')
const show_delete_dialog = ref(false)
const router = useRouter()
function deletePage() {
const notebook_name = page.doc.notebook
page.delete().then(() => {
router.push(`/notebook/${notebook_name}`)
})
}
</script>
<template>
<Dropdown
:button="{ icon: 'more-horizontal', variant: 'ghost' }"
:options="[
{
label: 'Clear',
icon: 'x-square',
onClick: () => (page.doc.content = {}),
},
{
label: 'Delete',
icon: 'trash',
onClick: () => (show_delete_dialog = true),
},
]"
/>
<Dialog
:options="{
title: 'Delete Page',
icon: { name: 'trash', variant: 'solid', theme: 'red' },
actions: [
{
label: 'Delete',
variant: 'solid',
theme: 'red',
loading: page.delete.loading,
onClick: deletePage,
},
],
}"
v-model="show_delete_dialog"
:dismissable="true"
>
<template #body-content>
<p class="text-base text-gray-600">Are you sure you want to delete this page?</p>
</template>
</Dialog>
</template>
|
2302_79757062/insights
|
frontend/src/notebook/NotebookPageDropdown.vue
|
Vue
|
agpl-3.0
| 1,113
|
<script setup>
import { LoadingIndicator } from 'frappe-ui'
const props = defineProps({
label: String,
icon: String,
iconComponent: Object,
action: Function,
loading: Boolean,
})
</script>
<template>
<div
class="flex h-8 cursor-pointer items-center rounded border border-gray-200 bg-white px-2 hover:bg-gray-50 hover:text-gray-800"
@click.prevent.stop="() => !loading && action && action()"
>
<slot>
<div class="flex items-center space-x-1.5">
<component
v-if="iconComponent"
:is="iconComponent"
class="h-4 w-4 text-gray-500"
></component>
<LoadingIndicator v-if="loading" class="h-4 w-4 text-gray-500" />
<FeatherIcon v-else :name="icon" class="h-4 w-4 text-gray-500"></FeatherIcon>
<span class="text-sm">{{ label }}</span>
</div>
</slot>
</div>
</template>
|
2302_79757062/insights
|
frontend/src/notebook/blocks/BlockAction.vue
|
Vue
|
agpl-3.0
| 818
|
<script setup>
import UsePopover from '@/components/UsePopover.vue'
import { slideRightTransition } from '@/utils/transitions'
const props = defineProps({
blockRef: Object,
actions: {
type: Array,
default: () => [],
},
})
</script>
<template>
<UsePopover
v-if="blockRef"
:targetElement="blockRef"
placement="right-start"
:transition="slideRightTransition"
>
<div class="flex w-[10rem] flex-col space-y-1.5 text-sm transition-all">
<slot />
</div>
</UsePopover>
</template>
|
2302_79757062/insights
|
frontend/src/notebook/blocks/BlockActions.vue
|
Vue
|
agpl-3.0
| 499
|
<script setup lang="jsx">
import useDashboards from '@/dashboard/useDashboards'
import { createChart, default as useChartOld } from '@/query/useChart'
import useQueryStore from '@/stores/queryStore'
import InvalidWidget from '@/widgets/InvalidWidget.vue'
import widgets from '@/widgets/widgets'
import { computed, inject, provide, ref, watch } from 'vue'
import BlockAction from '../BlockAction.vue'
import BlockActions from '../BlockActions.vue'
import ChartOptionsDropdown from './ChartOptionsDropdown.vue'
const emit = defineEmits(['setChartName', 'remove'])
const props = defineProps({ chartName: String })
const blockRef = ref(null)
let chart = null
if (!props.chartName) {
const chartName = await createChart()
emit('setChartName', chartName)
chart = useChartOld(chartName)
} else {
chart = useChartOld(props.chartName)
}
chart.enableAutoSave()
provide('chart', chart)
function removeChart() {
chart.delete().then(() => emit('remove'))
}
const queries = useQueryStore()
const queryOptions = queries.list.map((query) => ({
label: query.title,
value: query.name,
description: query.name,
}))
const selectedQuery = computed(() => {
return queryOptions.find((op) => op.value === chart.doc.query)
})
const QuerySelector = (props) => {
return (
<div class="relative flex w-full items-center text-gray-800 [&>div]:w-full">
<Autocomplete
placeholder="Query"
options={queryOptions}
modelValue={selectedQuery.value}
placement="bottom"
onUpdate:modelValue={(op) => chart.updateQuery(op.value)}
></Autocomplete>
<p class="pointer-events-none absolute right-0 top-0 flex h-full items-center px-2">
<FeatherIcon name="chevron-down" class="h-4 w-4 text-gray-500" />
</p>
</div>
)
}
const showDashboardDialog = ref(false)
const dashboards = useDashboards()
dashboards.reload()
const toDashboard = ref(null)
const addingToDashboard = ref(false)
const dashboardOptions = computed(() => {
// sort alphabetically
return dashboards.list
.sort((a, b) => {
return a.title.toLowerCase() < b.title.toLowerCase() ? -1 : 1
})
.map((d) => ({ label: d.title, value: d.name }))
})
const $notify = inject('$notify')
const addToDashboard = async () => {
if (!toDashboard.value) return
await chart.addToDashboard(toDashboard.value.value)
showDashboardDialog.value = false
$notify({
variant: 'success',
title: 'Success',
message: 'Chart added to dashboard',
})
}
const dashboardInput = ref(null)
watch(
() => showDashboardDialog.value,
(val) => {
if (val) {
setTimeout(() => {
dashboardInput.value.input?.$el?.blur()
dashboardInput.value.input?.$el?.focus()
}, 500)
}
},
{ immediate: true }
)
</script>
<template>
<div
ref="blockRef"
v-if="chart.doc.name"
class="group relative my-6 h-[20rem] overflow-hidden rounded border bg-white"
>
<component
v-if="chart.doc?.chart_type"
ref="widget"
:is="widgets.getComponent(chart.doc.chart_type)"
:data="chart.data"
:options="chart.doc.options"
:key="JSON.stringify([chart.data, chart.doc.options])"
>
<template #placeholder>
<div class="relative h-full w-full">
<InvalidWidget
class="absolute"
title="Insufficient options"
message="Please check the options for this chart"
icon="settings"
icon-class="text-gray-500"
/>
</div>
</template>
</component>
<!-- else -->
<div
v-else
class="absolute right-0 top-0 flex h-full w-full flex-col items-center justify-center"
>
<div class="mb-1 w-[10rem] text-gray-500">Select a query</div>
<div class="w-[10rem] rounded border border-dashed border-gray-300">
<QuerySelector />
</div>
</div>
</div>
<BlockActions :blockRef="blockRef">
<BlockAction class="!px-0">
<QuerySelector />
</BlockAction>
<BlockAction class="!px-0" v-if="chart.doc.query">
<ChartOptionsDropdown />
</BlockAction>
<BlockAction
label="Add to dashboard"
icon="plus"
:action="() => (showDashboardDialog = true)"
/>
<BlockAction icon="trash" label="Delete" :action="removeChart" :loading="chart.deleting" />
</BlockActions>
<Dialog :options="{ title: 'Add to Dashboard' }" v-model="showDashboardDialog">
<template #body-content>
<div class="text-base">
<span class="mb-2 block text-sm leading-4 text-gray-700">Dashboard</span>
<Autocomplete
ref="dashboardInput"
:options="dashboardOptions"
v-model="toDashboard"
/>
</div>
</template>
<template #actions>
<Button variant="solid" @click="addToDashboard" :loading="addingToDashboard">
Add
</Button>
</template>
</Dialog>
</template>
|
2302_79757062/insights
|
frontend/src/notebook/blocks/chart/ChartBlock.vue
|
Vue
|
agpl-3.0
| 4,608
|