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>
<svg
width="16"
height="16"
viewBox="0 0 16 16"
fill="none"
xmlns="http://www.w3.org/2000/svg"
>
<path
fill-rule="evenodd"
clip-rule="evenodd"
d="M2 2.5C1.72386 2.5 1.5 2.72386 1.5 3C1.5 3.27614 1.72386 3.5 2 3.5H3C3.27614 3.5 3.5 3.27614 3.5 3C3.5 2.72386 3.27614 2.5 3 2.5H2ZM5.33301 2.5C5.05687 2.5 4.83301 2.72386 4.83301 3C4.83301 3.27614 5.05687 3.5 5.33301 3.5H14.0002C14.2763 3.5 14.5002 3.27614 14.5002 3C14.5002 2.72386 14.2763 2.5 14.0002 2.5H5.33301ZM5.33301 7.30005C5.05687 7.30005 4.83301 7.52391 4.83301 7.80005C4.83301 8.07619 5.05687 8.30005 5.33301 8.30005H14.0002C14.2763 8.30005 14.5002 8.07619 14.5002 7.80005C14.5002 7.52391 14.2763 7.30005 14.0002 7.30005H5.33301ZM4.83301 12.6001C4.83301 12.324 5.05687 12.1001 5.33301 12.1001H14.0002C14.2763 12.1001 14.5002 12.324 14.5002 12.6001C14.5002 12.8762 14.2763 13.1001 14.0002 13.1001H5.33301C5.05687 13.1001 4.83301 12.8762 4.83301 12.6001ZM1.5 7.80005C1.5 7.52391 1.72386 7.30005 2 7.30005H3C3.27614 7.30005 3.5 7.52391 3.5 7.80005C3.5 8.07619 3.27614 8.30005 3 8.30005H2C1.72386 8.30005 1.5 8.07619 1.5 7.80005ZM2 12.1001C1.72386 12.1001 1.5 12.324 1.5 12.6001C1.5 12.8762 1.72386 13.1001 2 13.1001H3C3.27614 13.1001 3.5 12.8762 3.5 12.6001C3.5 12.324 3.27614 12.1001 3 12.1001H2Z"
fill="currentColor"
/>
</svg>
</template>
|
2302_79757062/drive
|
frontend/src/components/EspressoIcons/ViewList.vue
|
Vue
|
agpl-3.0
| 1,365
|
<template>
<Dialog v-model="open" :options="{ title: 'Open a file', size: '5xl' }">
<template #body>
<h3 class="text-2xl font-semibold leading-6 text-gray-900 px-6 pt-5">
Open a file
</h3>
<div class="px-2 pt-2">
<div class="flex items-center justify-start px-4 my-2">
<Dropdown v-if="dropDownItems.length" :options="dropDownItems">
<button class="flex">
<svg
class="w-4 h-4 m-auto text-gray-600"
xmlns="http://www.w3.org/2000/svg"
width="24"
height="24"
viewBox="0 0 24 24"
fill="none"
stroke="currentColor"
stroke-width="2"
stroke-linecap="round"
stroke-linejoin="round"
>
<circle cx="12" cy="12" r="1" />
<circle cx="19" cy="12" r="1" />
<circle cx="5" cy="12" r="1" />
</svg>
</button>
</Dropdown>
<span v-if="dropDownItems.length" class="text-gray-600 mx-0.5">
{{ "/" }}
</span>
<div v-for="(crumb, index) in lastFourBreadCrumbs" :key="index">
<span
v-if="breadcrumbs.length > 1 && index > 0"
class="text-gray-600 mx-0.5"
>
{{ "/" }}
</span>
<button
class="text-base cursor-pointer"
:class="
breadcrumbs.length - 1 === index
? 'text-gray-900 text-base font-medium p-1'
: 'text-gray-600 text-base rounded-[6px] hover:bg-gray-100 p-1'
"
@click="closeEntity(crumb.name)"
>
{{ crumb.title }}
</button>
</div>
</div>
<div class="flex" :style="{ height: 'calc(100vh - 20rem)' }">
<Tabs v-model="tabIndex" :tabs="tabs">
<div
v-if="tabIndex === 4"
class="flex flex-col h-full items-center justify-center p-4"
>
<Button
size="md"
variant="solid"
@click="emitter.emit('uploadFile')"
>
<template #prefix><Upload class="w-4 stroke-1.5" /></template>
Upload
</Button>
<!-- <span class="text-gray-700 text-base mt-2" >Or drag a file here to upload</span> -->
</div>
<NoFilesSection
v-else-if="isEmpty"
class="my-auto"
primary-message="No Files"
secondary-message=" "
/>
<div v-else class="h-full p-4">
<div class="mt-2">
<div class="flex py-1 justify-between">
<span
v-if="folders.length > 0"
class="text-gray-600 font-medium text-base"
>
Folders
</span>
<span v-else></span>
<Button
v-if="folderStack.length > 1"
variant="ghost"
icon="arrow-up"
class="border"
:class="[
$store.state.view === 'list' ? 'bg-white shadow' : '',
]"
@click="closeEntity()"
/>
</div>
<div class="flex flex-row flex-wrap gap-4 mt-0.5">
<div
v-for="folder in folders"
:id="folder.name"
:key="folder.name"
class="cursor-pointer p-2 w-40 h-26 rounded-lg border group select-none entity border-gray-200 hover:shadow-2xl"
draggable="false"
@click="openEntity(folder)"
@dragenter.prevent
@dragover.prevent
@mousedown.stop
>
<div class="flex items-start">
<svg
:style="{ fill: folder.color }"
:draggable="false"
class="h-6 w-auto"
viewBox="0 0 30 30"
fill="none"
xmlns="http://www.w3.org/2000/svg"
>
<path
d="M14.8341 5.40865H2.375C2.09886 5.40865 1.875 5.63251 1.875 5.90865V25.1875C1.875 26.2921 2.77043 27.1875 3.875 27.1875H26.125C27.2296 27.1875 28.125 26.2921 28.125 25.1875V3.3125C28.125 3.03636 27.9011 2.8125 27.625 2.8125H18.5651C18.5112 2.8125 18.4588 2.82989 18.4156 2.86207L15.133 5.30951C15.0466 5.37388 14.9418 5.40865 14.8341 5.40865Z"
/>
</svg>
</div>
<div class="content-center grid">
<span class="truncate text-sm text-gray-800 mt-2">
{{ folder.title }}
</span>
<p class="truncate text-xs text-gray-600 mt-0">
{{ folder.file_size }}
{{ !!folder.file_size ? "∙" : null }}
{{ folder.relativeModified }}
</p>
</div>
</div>
</div>
</div>
<div
v-if="files.length > 0"
:class="folders.length > 0 ? 'mt-8' : 'mt-2'"
>
<div class="text-gray-600 font-medium text-base">Files</div>
<div class="inline-flex flex-row flex-wrap gap-4 mt-0.5">
<div
v-for="file in files"
:id="file.name"
:key="file.name"
class="w-40 h-40 rounded-lg border group select-none entity cursor-pointer relative group border-gray-200 hover:shadow-2xl"
:draggable="false"
@click="openEntity(file)"
@dragenter.prevent
@dragover.prevent
@mousedown.stop
>
<GridItem
:file_kind="file.file_kind"
:mime_type="file.mime_type"
:file_ext="file.file_ext"
:name="file.name"
:title="file.title"
:modified="file.modified"
:relative-modified="file.relativeModified"
:file_size="file.file_size"
/>
</div>
</div>
</div>
</div>
</Tabs>
</div>
</div>
</template>
</Dialog>
</template>
<script setup>
import NoFilesSection from "./NoFilesSection.vue"
import GridItem from "./GridItem.vue"
import { watch, defineEmits, computed, h, ref } from "vue"
import { useTimeAgo } from "@vueuse/core"
import { createResource, Dialog, Button, Tabs, Dropdown } from "frappe-ui"
import { Plus, Upload } from "lucide-vue-next"
import Home from "./EspressoIcons/Home.vue"
import Recent from "./EspressoIcons/Recent.vue"
import Star from "./EspressoIcons/Star.vue"
import Users from "./EspressoIcons/Users.vue"
import { formatSize, formatDate } from "@/utils/format"
import { useStore } from "vuex"
const props = defineProps({
title: {
type: String,
default: "Open a File",
},
suggestedTabIndex: {
type: Number,
default: 0,
},
})
const store = useStore()
const currentFolder = ref(store.state.homeFolderID)
const emit = defineEmits(["update:modelValue", "success"])
const tabIndex = ref(props.suggestedTabIndex)
const folderContents = ref()
const folderStack = ref([""])
const breadcrumbs = ref([{ name: store.state.homeFolderID, title: "Home" }])
const isEmpty = computed(() => {
return folderContents.value && folderContents.value.length === 0
})
const folders = computed(() => {
return folderContents.value
? folderContents.value.filter((x) => x.is_group === 1)
: []
})
const files = computed(() => {
return folderContents.value
? folderContents.value.filter((x) => x.is_group === 0)
: []
})
const open = computed({
// getter
get() {
return props.modelValue
},
// setter
set(newValue) {
emit("update:modelValue", newValue)
},
})
const tabs = [
{
label: "Home",
icon: h(Home, { class: "w-4 h-4" }),
component: NoFilesSection,
},
{
label: "Recents",
icon: h(Recent, { class: "w-4 h-4" }),
},
{
label: "Favourite",
icon: h(Star, { class: "w-4 h-4" }),
},
{
label: "Shared",
icon: h(Users, { class: "w-4 h-4" }),
},
{
label: "Upload",
icon: h(Plus, { class: "w-4 h-4 stroke-[1.5]" }),
},
]
watch(tabIndex, (newValue) => {
switch (newValue) {
case 0:
breadcrumbs.value = [{ name: store.state.homeFolderID, title: "Home" }]
currentFolder.value = store.state.homeFolderID
fetchFolderContents.fetch({
entity_name: currentFolder.value,
is_active: 1,
recents_only: false,
favourites_only: false,
mime_type_list: JSON.stringify([
"application/vnd.openxmlformats-officedocument.wordprocessingml.document",
]),
})
break
case 1:
breadcrumbs.value = [{ name: "", title: "Recents" }]
currentFolder.value = null
fetchFolderContents.fetch({
entity_name: "",
is_active: 1,
recents_only: true,
favourites_only: false,
mime_type_list: JSON.stringify([
"application/vnd.openxmlformats-officedocument.wordprocessingml.document",
]),
})
break
case 2:
breadcrumbs.value = [{ name: "", title: "Favourites" }]
currentFolder.value = null
fetchFolderContents.fetch({
is_active: 1,
recents_only: false,
favourites_only: true,
mime_type_list: JSON.stringify([
"application/vnd.openxmlformats-officedocument.wordprocessingml.document",
]),
})
break
case 3:
breadcrumbs.value = [{ name: "", title: "Shared" }]
currentFolder.value = null
sharedWithMe.fetch({
is_active: 1,
recents_only: false,
favourites_only: true,
mime_type_list: JSON.stringify([
"application/vnd.openxmlformats-officedocument.wordprocessingml.document",
]),
})
break
default:
breadcrumbs.value = []
folderContents.value = []
break
}
})
const lastFourBreadCrumbs = computed(() => {
if (breadcrumbs.value.length > 4) {
return breadcrumbs.value.slice(-4)
}
return breadcrumbs.value
})
const dropDownItems = computed(() => {
let allExceptLastTwo = breadcrumbs.value.slice(0, -4)
return allExceptLastTwo.map((item) => {
return {
...item,
icon: null,
label: item.title,
onClick: () => closeEntity(item.name),
}
})
})
function openEntity(value) {
if (value.is_group) {
currentFolder.value = value.name
folderPermissions.fetch({
entity_name: value.name,
fields: "title,is_group,allow_comments,allow_download,owner",
})
breadcrumbs.value.push({ name: value.name, title: value.title })
fetchFolderContents.fetch({
entity_name: currentFolder.value,
is_active: 1,
recents_only: false,
favourites_only: false,
mime_type_list: JSON.stringify([
"application/vnd.openxmlformats-officedocument.wordprocessingml.document",
]),
})
} else {
emit("success", value)
}
}
function closeEntity(name) {
const index = breadcrumbs.value.findIndex((obj) => obj.name === name)
if (breadcrumbs.value.length > 1 && index !== breadcrumbs.value.length - 1) {
breadcrumbs.value = breadcrumbs.value.slice(0, index + 1)
currentFolder.value = breadcrumbs.value[breadcrumbs.value.length - 1].name
if (tabIndex.value === 3 && !currentFolder.value.length) {
sharedWithMe.fetch({
is_active: 1,
recents_only: false,
favourites_only: false,
mime_type_list: JSON.stringify([
"application/vnd.openxmlformats-officedocument.wordprocessingml.document",
]),
})
} else {
fetchFolderContents.fetch({
entity_name: currentFolder.value,
is_active: 1,
recents_only: false,
favourites_only: tabIndex.value === 1 ? true : false,
mime_type_list: JSON.stringify([
"application/vnd.openxmlformats-officedocument.wordprocessingml.document",
]),
})
}
}
}
const folderPermissions = createResource({
url: "drive.api.permissions.get_entity_with_permissions",
params: {
entity_name: currentFolder.value,
},
auto: false,
})
const fetchFolderContents = createResource({
method: "GET",
url: "drive.api.list.files",
auto: true,
params: {
entity_name: currentFolder.value,
is_active: 1,
recents_only: false,
favourites_only: false,
mime_type_list: JSON.stringify([
"application/vnd.openxmlformats-officedocument.wordprocessingml.document",
]),
},
onSuccess(data) {
folderContents.value = []
data.forEach((entity) => {
entity.file_size = entity.is_group ? null : formatSize(entity.file_size)
entity.relativeModified = useTimeAgo(entity.modified)
entity.modified = formatDate(entity.modified)
entity.creation = formatDate(entity.creation)
})
folderContents.value = data
},
onError(error) {
if (error && error.exc_type === "PermissionError") {
this.$store.commit("setError", {
primaryMessage: "Forbidden",
secondaryMessage: "Insufficient permissions for this resource",
})
this.$router.replace({ name: "Error" })
}
},
})
let sharedWithMe = createResource({
url: "drive.api.list.shared_with_user",
method: "GET",
auto: false,
onSuccess(data) {
data.forEach((entity) => {
entity.file_size = entity.is_group ? null : formatSize(entity.file_size)
entity.relativeModified = useTimeAgo(entity.modified)
entity.modified = formatDate(entity.modified)
entity.creation = formatDate(entity.creation)
})
folderContents.value = data
},
onError(error) {
console.log(error)
},
})
</script>
|
2302_79757062/drive
|
frontend/src/components/FilePicker.vue
|
Vue
|
agpl-3.0
| 14,424
|
<template>
<Teleport to="#modals">
<div class="fixed inset-0 flex items-center justify-center px-4 py-4 z-10">
<div
class="fixed inset-0 transition-opacity bg-gray-900 opacity-75"
@click="$emit('hide')"
></div>
<FileRender :preview-entity="previewEntity" />
</div>
</Teleport>
</template>
<script>
import FileRender from "@/components/FileRender.vue"
import { Teleport } from "vue"
export default {
name: "FilePreview",
components: {
FileRender,
Teleport,
},
props: {
previewEntity: {
type: Object,
required: true,
},
},
emits: ["hide"],
mounted() {
this.escapeListener = (e) => {
if (e.key === "Escape") {
this.$emit("hide")
}
}
document.addEventListener("keydown", this.escapeListener)
},
unmounted() {
document.removeEventListener("keydown", this.escapeListener)
},
}
</script>
|
2302_79757062/drive
|
frontend/src/components/FilePreview.vue
|
Vue
|
agpl-3.0
| 912
|
<template>
<LoadingIndicator
v-if="loading"
class="w-10 h-full z-10 text-neutral-100 mx-auto"
/>
<div
v-else-if="error"
class="max-w-[450px] px-16 py-8 z-10 bg-white rounded-md text-neutral-100 text-xl text-center font-medium shadow-xl flex flex-col justify-center items-center"
>
<FeatherIcon
class="h-12 mb-4 fill-blue-500 stroke-white"
name="alert-circle"
/>
<span class="mb-4">Cannot open file</span>
<span class="text-base text-center text-gray-700">
{{ error }}
</span>
<Button
v-if="
$store.state.entityInfo[0].allow_download ||
$store.state.entityInfo[0].owner === 'You'
"
class="mt-4 w-full"
variant="solid"
@click="download"
>
Download
</Button>
</div>
<template v-else>
<VideoPreview v-if="isVideo" :preview-entity="previewEntity" />
<AudioPreview v-if="isAudio" :preview-entity="previewEntity" />
<TextPreview v-if="isTxt" :preview-entity="previewEntity" />
<SheetPreview v-if="isXlsx" :preview-entity="previewEntity" />
<ImagePreview v-if="isImage" :preview-entity="previewEntity" />
<DocPreview v-if="isDocx" :preview-entity="previewEntity" />
<PDFPreview v-if="isPdf" :preview-entity="previewEntity" />
</template>
</template>
<script>
import { LoadingIndicator, FeatherIcon } from "frappe-ui"
import SheetPreview from "@/components/FileTypePreview/SheetPreview.vue"
import ImagePreview from "@/components/FileTypePreview/ImagePreview.vue"
import DocPreview from "@/components/FileTypePreview/DocPreview.vue"
import PDFPreview from "./FileTypePreview/PDFPreview.vue"
import VideoPreview from "./FileTypePreview/VideoPreview.vue"
import TextPreview from "./FileTypePreview/TextPreview.vue"
import AudioPreview from "@/components/FileTypePreview/AudioPreview.vue"
export default {
name: "FileRender",
components: {
LoadingIndicator,
SheetPreview,
ImagePreview,
DocPreview,
PDFPreview,
VideoPreview,
TextPreview,
AudioPreview,
FeatherIcon,
},
props: {
previewEntity: {
type: Object,
required: true,
},
modelValue: {
type: Boolean,
required: false,
default: true,
},
},
emits: ["update:modelValue"],
data() {
return {
loading: true,
error: null,
}
},
computed: {
isPdf() {
return this.previewEntity.mime_type === "application/pdf"
},
isImage() {
return this.previewEntity.mime_type?.startsWith("image/")
},
isAudio() {
return this.previewEntity.mime_type?.startsWith("audio/")
},
isVideo() {
return (
this.previewEntity.mime_type === "video/mp4" ||
this.previewEntity.mime_type === "video/webm" ||
this.previewEntity.mime_type === "video/quicktime"
)
},
isFrappeDoc() {
return this.previewEntity.mime_type === "frappe_doc"
},
isDocx() {
return (
this.previewEntity.mime_type ===
"application/vnd.openxmlformats-officedocument.wordprocessingml.document"
)
},
isXlsx() {
return (
this.previewEntity.mime_type ===
"application/vnd.openxmlformats-officedocument.spreadsheetml.sheet"
)
},
isTxt() {
return (
this.previewEntity.mime_type?.startsWith("text/") ||
this.previewEntity.mime_type === "application/json" ||
this.previewEntity.mime_type === "application/javascript" ||
this.previewEntity.mime_type === "text/x-python"
)
},
open: {
get() {
return this.modelValue
},
set(value) {
this.$emit("update:modelValue", value)
if (!value) {
this.folderName = ""
this.errorMessage = ""
}
},
},
},
watch: {
previewEntity: {
handler() {
this.loading = true
this.renderContent()
},
},
},
mounted() {
this.renderContent()
},
beforeUnmount() {
this.loading = true
this.$store.commit("setEntityInfo", [])
},
methods: {
renderContent() {
const isSupportedType =
this.previewEntity.mime_type &&
[
"image",
"video/quicktime",
"video/webm",
"video/mp4",
"audio",
"text",
"text/x-python",
"application/json",
"application/javascript",
"application/pdf",
"application/vnd.openxmlformats-officedocument.wordprocessingml.document",
"application/vnd.openxmlformats-officedocument.spreadsheetml.sheet",
"frappe_doc",
].some((type) => this.previewEntity.mime_type.startsWith(type))
if (!isSupportedType) {
this.error = "Previews are not supported for this file type"
if (
this.$store.state.entityInfo[0].allow_download ||
this.$store.state.entityInfo[0].owner === "You"
) {
this.error =
"Previews are not supported for this file type. Would you like to download it instead?"
}
this.loading = false
} else if (
this.previewEntity.mime_type.startsWith("video") &&
this.previewEntity.size_in_bytes < 2000 * 1024 * 1024
) {
this.loading = false
} else if (this.previewEntity.size_in_bytes > 400 * 1024 * 1024) {
this.error = "File is too large to preview"
this.loading = false
} else {
this.loading = false
this.error = null
}
},
download() {
window.location.href = `/api/method/drive.api.files.get_file_content?entity_name=${this.previewEntity.name}&trigger_download=1`
},
},
}
</script>
|
2302_79757062/drive
|
frontend/src/components/FileRender.vue
|
Vue
|
agpl-3.0
| 5,684
|
<template>
<LoadingIndicator
v-show="loading"
class="w-10 h-full text-neutral-100 mx-auto"
/>
<audio
v-show="!loading"
:key="src"
ref="mediaRef"
class="w-1/4 max-h-full"
autoplay
preload="none"
controls="true"
controlslist="nodownload noremoteplayback noplaybackrate"
@loadedmetadata="handleMediaReady"
>
<source :src="src" :type="type" />
</audio>
</template>
<script setup>
import { LoadingIndicator } from "frappe-ui"
import { ref, onBeforeUnmount, watch, onMounted } from "vue"
const props = defineProps({
previewEntity: {
type: Object,
default: null,
},
})
const loading = ref(true)
const src = ref(
`/api/method/drive.api.files.get_file_content?entity_name=${props.previewEntity.name}`
)
const type = ref("audio/mp3")
const mediaRef = ref("")
const handleMediaReady = (event) => {
mediaRef.value = event.target
if (mediaRef.value.readyState === 1) {
loading.value = false
}
}
watch(
() => props.previewEntity,
(newValue) => {
loading.value = true
src.value = `/api/method/drive.api.files.get_file_content?entity_name=${newValue.name}`
type.value = newValue.mime_type
}
)
/* watch(() => mediaRef.value, (newValue, oldValue) => {
console.log(newValue)
if (newValue) {
if (newValue.readyState === 1) {
loading.value = false;
}
}
}); */
onMounted(() => {
loading.value = false
})
onBeforeUnmount(() => {
loading.value = true
src.value = ""
type.value = ""
})
</script>
|
2302_79757062/drive
|
frontend/src/components/FileTypePreview/AudioPreview.vue
|
Vue
|
agpl-3.0
| 1,506
|
<template>
<div
id="DocxContainer"
class="object-contain h-[85vh] max-w-[65vw] z-10 overflow-y-auto rounded border"
></div>
</template>
<script setup>
import * as docx from "docx-preview"
import { onBeforeUnmount, onMounted, ref, watch } from "vue"
const props = defineProps({
previewEntity: {
type: Object,
default: null,
},
})
const loading = ref(true)
const blob = ref(null)
async function fetchContent() {
loading.value = true
const headers = {
Accept: "application/json",
"Content-Type": "application/json; charset=utf-8",
"X-Frappe-Site-Name": window.location.hostname,
Range: "bytes=0-10000000",
}
const res = await fetch(
`/api/method/drive.api.files.get_file_content?entity_name=${props.previewEntity.name}`,
{
method: "GET",
headers,
}
)
if (res.ok) {
blob.value = await res.blob()
docx.renderAsync(
blob.value,
document.getElementById("DocxContainer"),
document.getElementById("DocxContainer"),
{
ignoreLastRenderedPageBreak: false,
experimental: true,
}
)
//.then((x) => console.log("docx: finished"));
loading.value = false
}
}
onMounted(() => {
fetchContent()
})
watch(
() => props.previewEntity,
() => {
fetchContent()
}
)
onBeforeUnmount(() => {
loading.value = true
blob.value = null
})
</script>
<style>
#DocxContainer {
user-select: text;
}
</style>
|
2302_79757062/drive
|
frontend/src/components/FileTypePreview/DocPreview.vue
|
Vue
|
agpl-3.0
| 1,438
|
<template>
<LoadingIndicator
v-if="loading"
class="w-10 h-full text-neutral-100 mx-auto"
/>
<img v-else draggable="false" class="w-auto max-h-full" :src="previewURL" />
</template>
<script setup>
import { LoadingIndicator } from "frappe-ui"
import { onBeforeUnmount, onMounted, ref, watch } from "vue"
import { useObjectUrl } from "@vueuse/core"
const props = defineProps({
previewEntity: {
type: Object,
default: null,
},
})
const loading = ref(true)
const imgBlob = ref(null)
const previewURL = useObjectUrl(imgBlob)
watch(props.previewEntity, () => {
loading.value = true
imgBlob.value = null
fetchContent()
})
async function fetchContent() {
loading.value = true
const headers = {
Accept: "application/json",
"Content-Type": "application/json; charset=utf-8",
"X-Frappe-Site-Name": window.location.hostname,
}
const res = await fetch(
`/api/method/drive.api.files.get_file_content?entity_name=${props.previewEntity.name}`,
{
method: "GET",
headers,
}
)
if (res.ok) {
imgBlob.value = await res.blob()
loading.value = false
}
}
watch(
() => props.previewEntity,
() => {
fetchContent()
}
)
onMounted(() => {
fetchContent()
})
onBeforeUnmount(() => {
loading.value = true
imgBlob.value = null
})
</script>
<style scoped>
img {
background-image: linear-gradient(45deg, #ccc 25%, transparent 25%),
linear-gradient(135deg, #ccc 25%, transparent 25%),
linear-gradient(45deg, transparent 75%, #ccc 75%),
linear-gradient(135deg, white 75%, #ccc 75%);
background-size: 30px 30px; /* Must be a square */
background-position: 0 0, 15px 0, 15px -15px, 0px 15px; /* Must be half of one side of the square */
}
</style>
|
2302_79757062/drive
|
frontend/src/components/FileTypePreview/ImagePreview.vue
|
Vue
|
agpl-3.0
| 1,741
|
<template>
<LoadingIndicator
v-if="loading"
class="w-10 h-full text-neutral-100 mx-auto"
/>
<div v-else class="flex flex-col items-start justify-start text-base">
<!-- Toolbar -->
<div
v-if="pages > 100"
class="flex w-full items-center justify-center rounded-t bg-gray-50 bg-opacity-50 mt-8 border gap-x-2 p-1"
>
<Button variant="ghost" icon="chevron-left">Prev</Button>
<Input
v-model.number="currentPage"
type="number"
class="min-8 w-auto max-w-15 text-center"
min="1"
max="pages"
/>
<span> / {{ pages }}</span>
<Button
variant="ghost"
icon="chevron-right"
@click="
currentPage = currentPage < pages ? currentPage + 1 : currentPage
"
></Button>
</div>
<div
class="bg-gray-400 overflow-auto max-h-[85vh] max-w-[65vw] min-w-[55vw] p-2 border"
:class="pages > 100 ? 'rounded-b' : 'rounded'"
>
<div v-if="pages > 100" class="m-4">
<!-- Paginate -->
<VuePDF
id="pdf"
:pdf="pdf"
:page="currentPage"
:text-layer="true"
:fit-parent="true"
/>
</div>
<!-- Scroll -->
<div v-for="page in pages" v-else :key="page" class="m-4">
<VuePDF
id="pdf"
:pdf="pdf"
:page="page"
:text-layer="true"
:fit-parent="true"
/>
</div>
</div>
</div>
</template>
<script setup>
import { LoadingIndicator } from "frappe-ui"
import { onMounted, onUnmounted, ref, watch } from "vue"
import { useObjectUrl } from "@vueuse/core"
import { Button, Input } from "frappe-ui"
import { VuePDF, usePDF } from "@tato30/vue-pdf"
import "@tato30/vue-pdf/style.css"
const props = defineProps({
previewEntity: {
type: Object,
default: null,
},
})
const loading = ref(true)
const blob = ref(null)
const previewURL = useObjectUrl(blob)
const currentPage = ref(1)
const { pdf, pages } = usePDF(previewURL)
async function fetchContent() {
loading.value = true
const headers = {
Accept: "application/json",
"Content-Type": "application/json; charset=utf-8",
"X-Frappe-Site-Name": window.location.hostname,
Range: "bytes=0-10000000",
}
const res = await fetch(
`/api/method/drive.api.files.get_file_content?entity_name=${props.previewEntity.name}`,
{
method: "GET",
headers,
}
)
if (res.ok) {
blob.value = await res.blob()
loading.value = false
}
}
watch(
() => props.previewEntity,
() => {
fetchContent()
}
)
onMounted(() => {
fetchContent()
})
onUnmounted(() => {
pdf.value?.destroy()
})
</script>
<style>
#pdf {
user-select: text;
box-shadow: 0 0 10px rgba(0, 0, 0, 0.5);
}
/* Chrome, Safari, Edge, Opera */
input::-webkit-outer-spin-button,
input::-webkit-inner-spin-button {
-webkit-appearance: none;
margin: 0;
}
/* Firefox */
input[type="number"] {
appearance: inherit;
-moz-appearance: textfield;
}
</style>
|
2302_79757062/drive
|
frontend/src/components/FileTypePreview/PDFPreview.vue
|
Vue
|
agpl-3.0
| 3,027
|
<template>
<LoadingIndicator
v-if="loading"
class="w-10 h-full text-neutral-100 mx-auto"
/>
<div>
<div v-if="loading" v-once id="gridctr" />
</div>
</template>
<script setup>
import { LoadingIndicator } from "frappe-ui"
import { ref, onBeforeUnmount, onMounted, watch, computed } from "vue"
import { read, utils } from "xlsx"
import Spreadsheet from "x-data-spreadsheet"
const props = defineProps({
previewEntity: {
type: Object,
default: null,
},
})
const loading = ref(true)
const canWrite = computed(() => {
return props.previewEntity.owner == "You"
? true
: props.previewEntity.write
? true
: false
})
let grid
async function fetchContent() {
loading.value = true
const headers = {
Accept: "application/json",
"Content-Type": "application/json; charset=utf-8",
"X-Frappe-Site-Name": window.location.hostname,
Range: "bytes=0-10000000",
}
const res = await fetch(
`/api/method/drive.api.files.get_file_content?entity_name=${props.previewEntity.name}`,
{
method: "GET",
headers,
}
)
if (res.ok) {
const ab = await res.arrayBuffer()
grid = new Spreadsheet(document.getElementById("gridctr"), {
/* mode: canWrite.value ? "edit" : "read", */
/* showToolbar: canWrite.value, */
mode: "read",
showToolbar: false,
showContextmenu: canWrite.value,
view: {
height: () => document.getElementById("renderContainer").clientHeight,
width: () => 1200,
},
})
grid.loadData(stox(read(ab)))
loading.value = false
}
}
function stox(wb) {
var out = []
wb.SheetNames.forEach(function (name) {
var o = { name: name, rows: {} }
var ws = wb.Sheets[name]
if (!ws || !ws["!ref"]) return
var range = utils.decode_range(ws["!ref"])
// sheet_to_json will lost empty row and col at begin as default
range.s = { r: 0, c: 0 }
var aoa = utils.sheet_to_json(ws, {
raw: false,
header: 1,
range: range,
})
aoa.forEach(function (r, i) {
var cells = {}
r.forEach(function (c, j) {
cells[j] = { text: c || String(c) }
var cellRef = utils.encode_cell({ r: i, c: j })
if (ws[cellRef] != null && ws[cellRef].f != null) {
cells[j].text = "=" + ws[cellRef].f
}
})
o.rows[i] = { cells: cells }
})
o.rows.len = aoa.length
o.merges = []
;(ws["!merges"] || []).forEach(function (merge, i) {
//Needed to support merged cells with empty content
if (o.rows[merge.s.r] == null) {
o.rows[merge.s.r] = { cells: {} }
}
if (o.rows[merge.s.r].cells[merge.s.c] == null) {
o.rows[merge.s.r].cells[merge.s.c] = {}
}
o.rows[merge.s.r].cells[merge.s.c].merge = [
merge.e.r - merge.s.r,
merge.e.c - merge.s.c,
]
o.merges[i] = utils.encode_range(merge)
})
out.push(o)
})
return out
}
/* function xtos(sdata) {
var out = utils.book_new();
sdata.forEach(function (xws) {
var ws = {};
var rowobj = xws.rows;
var minCoord = { r: 0, c: 0 },
maxCoord = { r: 0, c: 0 };
for (var ri = 0; ri < rowobj.len; ++ri) {
var row = rowobj[ri];
if (!row) continue;
Object.keys(row.cells).forEach(function (k) {
var idx = +k;
if (isNaN(idx)) return;
var lastRef = utils.encode_cell({ r: ri, c: idx });
if (ri > maxCoord.r) maxCoord.r = ri;
if (idx > maxCoord.c) maxCoord.c = idx;
var cellText = row.cells[k].text,
type = "s";
if (!cellText) {
cellText = "";
type = "z";
} else if (!isNaN(Number(cellText))) {
cellText = Number(cellText);
type = "n";
} else if (
cellText.toLowerCase() === "true" ||
cellText.toLowerCase() === "false"
) {
cellText = Boolean(cellText);
type = "b";
}
ws[lastRef] = { v: cellText, t: type };
if (type == "s" && cellText[0] == "=") {
ws[lastRef].f = cellText.slice(1);
}
if (row.cells[k].merge != null) {
if (ws["!merges"] == null) ws["!merges"] = [];
ws["!merges"].push({
s: { r: ri, c: idx },
e: {
r: ri + row.cells[k].merge[0],
c: idx + row.cells[k].merge[1],
},
});
}
});
}
ws["!ref"] = minCoord
? utils.encode_range({
s: minCoord,
e: maxCoord,
})
: "A1";
utils.book_append_sheet(out, ws, xws.name);
});
return out;
} */
watch(
() => props.previewEntity,
() => {
document.getElementById("gridctr").innerHTML = ""
fetchContent()
}
)
onMounted(() => {
fetchContent()
})
onBeforeUnmount(() => {
loading.value = true
document.getElementById("gridctr").remove()
})
</script>
<style scoped>
#gridctr {
display: flex;
}
</style>
|
2302_79757062/drive
|
frontend/src/components/FileTypePreview/SheetPreview.vue
|
Vue
|
agpl-3.0
| 4,964
|
<template>
<LoadingIndicator
v-if="loading"
class="w-10 h-full z-10 text-neutral-100 mx-auto"
/>
<div
v-else
id="container"
class="flex items-center justify-center w-full h-full overflow-auto"
>
<pre
class="bg-gray-50 sm:w-full md:w-2/3 h-[85vh] text-gray-800 text-sm border select-text p-3 font-mono overflow-x-auto overflow-y-auto"
>{{ blob }}</pre
>
</div>
</template>
<script setup>
/* Consider adding https://codemirror.net/ and add a mimetype eval list for all possible mimetypes */
import { LoadingIndicator } from "frappe-ui"
import { onMounted, ref, watch } from "vue"
const props = defineProps({
previewEntity: {
type: String,
default: "",
},
})
const loading = ref(true)
const blob = ref(null)
async function fetchContent() {
loading.value = true
const headers = {
Accept: "application/json",
"Content-Type": "application/json; charset=utf-8",
"X-Frappe-Site-Name": window.location.hostname,
Range: "bytes=0-10000000",
}
const res = await fetch(
`/api/method/drive.api.files.get_file_content?entity_name=${props.previewEntity.name}`,
{
method: "GET",
headers,
}
)
if (res.ok) {
let resBlob = await res.blob()
blob.value = await resBlob.text()
loading.value = false
}
}
watch(
() => props.previewEntity,
() => {
fetchContent()
}
)
onMounted(() => {
fetchContent()
})
</script>
<style scoped></style>
|
2302_79757062/drive
|
frontend/src/components/FileTypePreview/TextPreview.vue
|
Vue
|
agpl-3.0
| 1,455
|
<template>
<LoadingIndicator
v-show="loading"
class="w-10 h-full text-neutral-100 mx-auto"
/>
<video
v-show="!loading"
:key="src"
ref="mediaRef"
class="w-auto max-h-full"
autoplay
muted
preload="none"
controlslist="nodownload noremoteplayback noplaybackrate disablepictureinpicture"
controls
draggable="false"
@loadedmetadata="handleMediaReady"
>
<source :src="src" :type="type" />
</video>
</template>
<script setup>
/*
Add codec evaluation currently assumes its a valid H264/5 (MP4/Webm)
Look into the feasibility of client side mp4 moov fragmentation pre processing using
https://github.com/gpac/gpac/wiki/MP4Box
Server side byte is good enough for now
*/
import { LoadingIndicator } from "frappe-ui"
import { ref, onBeforeUnmount, watch } from "vue"
const props = defineProps({
previewEntity: {
type: String,
default: "",
},
})
const loading = ref(true)
const src = ref(
`/api/method/drive.api.files.get_file_content?entity_name=${props.previewEntity.name}`
)
const type = ref(
props.previewEntity.mime_type === "video/quicktime"
? "video/mp4"
: props.previewEntity.mime_type
)
const mediaRef = ref("")
const handleMediaReady = (event) => {
mediaRef.value = event.target
if (mediaRef.value.readyState === 1) {
loading.value = false
}
}
watch(
() => props.previewEntity,
(newValue) => {
loading.value = true
src.value = `/api/method/drive.api.files.get_file_content?entity_name=${newValue.name}`
type.value = newValue.mime_type
}
)
onBeforeUnmount(() => {
loading.value = true
src.value = ""
type.value = ""
})
</script>
|
2302_79757062/drive
|
frontend/src/components/FileTypePreview/VideoPreview.vue
|
Vue
|
agpl-3.0
| 1,664
|
<template>
<div id="fileSelection" class="hidden" />
</template>
<script setup>
import { ref, onMounted, onBeforeUnmount, inject, watch } from "vue"
import { useStore } from "vuex"
import { useRoute } from "vue-router"
import Dropzone from "dropzone"
import { capture } from "@/telemetry"
const store = useStore()
const route = useRoute()
const dropzone = ref()
const computedFullPath = ref("")
const emitter = inject("emitter")
const uploadResponse = ref("")
watch(route, (to) => {
if (to.name === "Document") {
dropzone.value.removeEventListeners()
} else {
dropzone.value.setupEventListeners()
}
})
function doesRootFolderFullPathExist(k, file_parent) {
const url =
window.location.origin +
"/api/method/" +
`drive.api.files.does_entity_exist?name=${k}&parent_entity=${file_parent}`
const xhr = new XMLHttpRequest()
// third parameter false for a synchronous request
xhr.open("GET", url, false)
xhr.send()
if (xhr.status === 200) {
const json = JSON.parse(xhr.responseText)
return json.message
} else {
throw new Error(`Request failed with status ${xhr.status}`)
}
}
function rootFolderFullPathNewName(k, file_parent) {
const url =
window.location.origin +
"/api/method/" +
`drive.utils.files.get_new_title?title=${k}&parent_name=${file_parent}&folder=${true}}`
const xhr = new XMLHttpRequest()
xhr.open("GET", url, false) // Here i am seeting third parameter as false for a synchronous request
xhr.send()
if (xhr.status === 200) {
const json = JSON.parse(xhr.responseText)
return json.message
} else {
throw new Error(`Request failed with status ${xhr.status}`)
}
}
function rootFolderFullPath(full_path) {
let s = full_path
let k = s.substring(0, s.indexOf("/"))
return k
}
function newFullPathName(k, s, x) {
let f = x.replace(k, s)
return f
}
function NonMergeMode(file) {
let a
let s
if (file.webkitRelativePath) {
a = file.webkitRelativePath
} else {
a = file.fullPath
}
let k = rootFolderFullPath(a)
let t = doesRootFolderFullPathExist(k, file.parent)
if (t) {
s = rootFolderFullPathNewName(k, file.parent)
let z = newFullPathName(k, s, a)
file.newFullPath = z
} else {
file.newFullPath = a
s = k
}
return s
}
onMounted(() => {
dropzone.value = new Dropzone("div#dropTarget", {
paramName: "file",
parallelUploads: 1,
autoProcessQueue: false,
clickable: "#fileSelection",
disablePreviews: true,
createImageThumbnails: false,
retryChunksLimit: 5,
previewsContainer: "#dropTarget",
hiddenInputContainer: "#fileSelection",
uploadMultiple: false,
chunking: true,
retryChunks: true,
forceChunking: true,
url: "/api/method/drive.api.files.upload_file",
dictUploadCanceled: "Upload canceled by user",
maxFilesize: 10 * 1024, // 10GB
timeout: 120000, // 2 minutes
chunkSize: 20 * 1024 * 1024, // 20MB
headers: {
"X-Frappe-CSRF-Token": window.csrf_token,
Accept: "application/json",
},
accept: function (file, done) {
if (file.size == 0) {
done("Empty files will not be uploaded.")
} else {
done()
}
},
sending: function (file, xhr, formData) {
if (file.lastModified) {
formData.append("last_modified", file.lastModified)
}
if (file.parent) {
formData.append("parent", file.parent)
}
if (file.newFullPath) {
formData.append("fullpath", file.newFullPath)
} else if (file.webkitRelativePath) {
formData.append("fullpath", file.webkitRelativePath)
} else if (file.fullPath) {
formData.append("fullpath", file.fullPath)
}
},
params: function (files, xhr, chunk) {
if (chunk) {
return {
uuid: chunk.file.upload.uuid,
chunk_index: chunk.index,
total_file_size: chunk.file.size,
chunk_size: dropzone.value.options.chunkSize,
total_chunk_count: chunk.file.upload.totalChunkCount,
chunk_byte_offset: chunk.index * dropzone.value.options.chunkSize,
}
}
},
})
dropzone.value.on("addedfile", function (file) {
file.parent = store.state.currentFolderID
store.commit("pushToUploads", {
uuid: file.upload.uuid,
name: file.name,
progress: 0,
})
if (dropzone.value.files.length === 1) {
if (file.fullPath || file.webkitRelativePath) {
computedFullPath.value = NonMergeMode(file)
}
dropzone.value.options.autoProcessQueue = true
}
if (file.fullPath || file.webkitRelativePath) {
let a
if (file.webkitRelativePath) {
a = file.webkitRelativePath
} else {
a = file.fullPath
}
let k = rootFolderFullPath(a)
file.newFullPath = newFullPathName(k, computedFullPath.value, a)
}
})
dropzone.value.on("queuecomplete", function () {
dropzone.value.files = []
computedFullPath.value = ""
emitter.emit("fetchFolderContents")
})
dropzone.value.on("uploadprogress", function (file, progress) {
store.commit("updateUpload", {
uuid: file.upload.uuid,
progress: progress,
})
})
dropzone.value.on("error", function (file, response) {
let message
if (typeof response === Object) {
message = JSON.parse(JSON.parse(response._server_messages)[0]).message
}
message = message || response || "Upload failed"
store.commit("updateUpload", {
uuid: file.upload.uuid,
error: message,
})
})
dropzone.value.on("success", function (file, response) {
uploadResponse.value = response.message
store.commit("updateUpload", {
uuid: file.upload.uuid,
response: response.message,
})
})
dropzone.value.on("complete", function (file) {
store.commit("updateUpload", {
uuid: file.upload.uuid,
completed: true,
})
capture("new_file_uploaded")
})
/* emitter.on("directUpload", (file) => {
dropzone.value.addFile(file)
return directUplodEntityName.value
}); */
emitter.on("uploadFile", () => {
if (dropzone.value.hiddenFileInput) {
dropzone.value.hiddenFileInput.removeAttribute("webkitdirectory")
dropzone.value.hiddenFileInput.click()
}
})
emitter.on("cancelUpload", (uuid) => {
var files = dropzone.value.files
for (var i = 0; i < files.length; i++) {
if (files[i].upload.uuid === uuid) {
dropzone.value.removeFile(files[i])
}
}
})
emitter.on("cancelAllUploads", () => {
dropzone.value.removeAllFiles(true)
})
emitter.on("uploadFolder", () => {
if (dropzone.value.hiddenFileInput) {
dropzone.value.hiddenFileInput.setAttribute("webkitdirectory", true)
dropzone.value.hiddenFileInput.click()
}
})
})
onBeforeUnmount(() => {
dropzone.value.destroy()
})
</script>
|
2302_79757062/drive
|
frontend/src/components/FileUploader.vue
|
Vue
|
agpl-3.0
| 6,876
|
<template>
<div
class="relative h-full p-5 flex flex-col lg:flex-row justify-center items-center text-center bg-neutral-50 rounded-lg"
>
<div class="w-8 h-8 p-1.5 m-4 rounded-full bg-red-100">
<FeatherIcon name="x" class="text-red-500" />
</div>
<p class="text-2xl font-semibold">
{{ error.messages.join("\n") }}
</p>
<Button
class="absolute left-0 top-0 m-4 focus:ring-0 focus:ring-offset-0 bg-gray-200 hover:bg-gray-300"
icon="chevron-left"
@click="$router.go(-1)"
/>
</div>
</template>
<script>
import { FeatherIcon, Button } from "frappe-ui"
export default {
name: "FolderContentsError",
components: {
FeatherIcon,
Button,
},
props: {
error: {
type: Object,
required: true,
},
},
}
</script>
|
2302_79757062/drive
|
frontend/src/components/FolderContentsError.vue
|
Vue
|
agpl-3.0
| 799
|
<template>
<svg
width="118"
height="118"
viewBox="0 0 118 118"
fill="none"
xmlns="http://www.w3.org/2000/svg"
>
<path
d="M93.9278 0H23.1013C10.3428 0 0 10.3428 0 23.1013V93.9278C0 106.686 10.3428 117.029 23.1013 117.029H93.9278C106.686 117.029 117.029 106.686 117.029 93.9278V23.1013C117.029 10.3428 106.686 0 93.9278 0Z"
fill="#016E7D"
/>
<path
d="M80.1723 35.7545H59.7487L55.7059 28.2466H20.8965V38.7472H49.4056L53.4483 46.2551H82.955C83.9525 46.2551 84.7926 47.0951 84.7926 48.0927V76.4968C84.7926 77.4943 83.9525 78.3344 82.955 78.3344H33.2347C32.2371 78.3344 31.3971 77.4943 31.3971 76.4968V50.5603H20.8965V73.6616C20.8965 82.0096 27.6694 88.835 36.0173 88.835H80.1723C88.5203 88.835 95.2932 82.0621 95.2932 73.6616V50.8754C95.2932 42.5274 88.5203 35.702 80.1723 35.702V35.7545Z"
fill="#EEFBFF"
/>
</svg>
</template>
|
2302_79757062/drive
|
frontend/src/components/FrappeDriveLogo.vue
|
Vue
|
agpl-3.0
| 888
|
<template>
<svg
width="16"
height="16"
viewBox="0 0 16 16"
fill="none"
xmlns="http://www.w3.org/2000/svg"
>
<path
fill-rule="evenodd"
clip-rule="evenodd"
d="M11.9971 14H3.99707C3.16864 14 2.49707 13.3284 2.49707 12.5V3.5C2.49707 2.67157 3.16864 2 3.99707 2H9.5V3.99989C9.5 5.38061 10.6193 6.4999 12 6.49989L13.4971 6.49988V12.5C13.4971 13.3284 12.8255 14 11.9971 14ZM14.4502 5.49987C14.3612 5.04668 14.1476 4.62366 13.8291 4.2806L11.5246 1.79887C11.0516 1.28945 10.3878 1 9.69261 1H3.99707C2.61636 1 1.49707 2.11929 1.49707 3.5V12.5C1.49707 13.8807 2.61636 15 3.99707 15H11.9971C13.3778 15 14.4971 13.8807 14.4971 12.5V5.98173C14.4971 5.9704 14.497 5.95908 14.4968 5.94777L14.4968 5.49987L14.4502 5.49987ZM13.4176 5.49988L12 5.49989C11.1716 5.4999 10.5 4.82832 10.5 3.99989V2.23582C10.6063 2.30368 10.7044 2.38525 10.7918 2.47932L13.0963 4.96105C13.2414 5.11735 13.3502 5.30132 13.4176 5.49988Z"
fill="#000000"
/>
</svg>
</template>
|
2302_79757062/drive
|
frontend/src/components/FrappeFileLine.vue
|
Vue
|
agpl-3.0
| 991
|
<template>
<svg
width="30"
height="30"
viewBox="0 0 30 30"
fill="none"
xmlns="http://www.w3.org/2000/svg"
>
<path
d="M14.8341 5.40865H2.375C2.09886 5.40865 1.875 5.63251 1.875 5.90865V25.1875C1.875 26.2921 2.77043 27.1875 3.875 27.1875H26.125C27.2296 27.1875 28.125 26.2921 28.125 25.1875V3.3125C28.125 3.03636 27.9011 2.8125 27.625 2.8125H18.5651C18.5112 2.8125 18.4588 2.82989 18.4156 2.86207L15.133 5.30951C15.0466 5.37388 14.9418 5.40865 14.8341 5.40865Z"
fill="#525252"
/>
</svg>
</template>
|
2302_79757062/drive
|
frontend/src/components/FrappeFolder.vue
|
Vue
|
agpl-3.0
| 543
|
<template>
<svg
width="16"
height="16"
viewBox="0 0 16 16"
fill="none"
xmlns="http://www.w3.org/2000/svg"
>
<g clip-path="url(#clip0_1811_74212)">
<path
fill-rule="evenodd"
clip-rule="evenodd"
d="M10.023 2.5L8.43184 3.68632C8.25916 3.81507 8.04952 3.88462 7.83412 3.88462H2V12.5C2 13.0523 2.44772 13.5 3 13.5H13C13.5523 13.5 14 13.0523 14 12.5V2.5H10.023ZM9.49179 1.64872C9.6213 1.55216 9.77853 1.5 9.94008 1.5H14.35C14.709 1.5 15 1.79101 15 2.15V12.5C15 13.6046 14.1046 14.5 13 14.5H3C1.89543 14.5 1 13.6046 1 12.5V3.53462C1 3.17563 1.29102 2.88462 1.65 2.88462H7.83412L9.49179 1.64872Z"
fill="#000000"
/>
</g>
<defs>
<clipPath id="clip0_1811_74212">
<rect width="16" height="16" fill="white" />
</clipPath>
</defs>
</svg>
</template>
|
2302_79757062/drive
|
frontend/src/components/FrappeFolderLine.vue
|
Vue
|
agpl-3.0
| 842
|
<template>
<svg
xmlns="http://www.w3.org/2000/svg"
width="13"
height="20"
viewBox="0 0 13 20"
fill="none"
>
<path
fill-rule="evenodd"
clip-rule="evenodd"
d="M0 0.5H13V3.84171H0V0.5ZM0 19.5V9.02556H12.1379V12.3729H4.14943V19.5H0Z"
fill="#2490EF"
/>
</svg>
</template>
|
2302_79757062/drive
|
frontend/src/components/FrappeLogo.vue
|
Vue
|
agpl-3.0
| 325
|
<template>
<div
class="rounded-full relative flex items-center justify-center"
:class="[colorClasses, sizeClasses]"
>
<Globe v-if="props.generalAccess.public" class="h-5 w-5" />
<Organization v-else-if="props.generalAccess.everyone" class="h-5 w-5" />
<Lock v-else class="h-5 w-5" />
</div>
</template>
<script setup>
import Lock from "@/components/EspressoIcons/Lock.vue"
import Organization from "./EspressoIcons/Organization.vue"
import Globe from "./EspressoIcons/Globe.vue"
import { computed } from "vue"
const props = defineProps({
generalAccess: {
type: Object,
default() {
return {
read: 0,
public: 0,
}
},
},
size: {
type: String,
default: "md",
},
})
const colorClasses = computed(() => {
if (props.generalAccess.public) {
return "bg-red-100 text-red-500"
} else if (props.generalAccess.everyone) {
return "bg-blue-100 text-blue-500"
}
return "text-gray-600 bg-gray-100"
})
const sizeClasses = computed(() => {
return {
xs: "w-4 h-4",
sm: "w-5 h-5",
md: "w-6 h-6",
lg: "w-7 h-7",
xl: "w-8 h-8",
"2xl": "w-10 h-10",
"3xl": "w-11.5 h-11.5",
}[props.size]
})
</script>
|
2302_79757062/drive
|
frontend/src/components/GeneralAccess.vue
|
Vue
|
agpl-3.0
| 1,208
|
<template>
<Dialog v-model="open" :options="{ title: dialogData.title, size: 'sm' }">
<template #body-content>
<div class="flex items-center justify-start">
<p class="text-base text-gray-600 leading-5">
{{ dialogData.message }}
</p>
</div>
<ErrorMessage class="my-1" :message="errorMessage" />
<div class="flex mt-5">
<Button
:variant="dialogData.variant"
:icon-left="dialogData.buttonIcon"
:theme="dialogData.theme"
class="w-full"
:loading="$resources.method.loading"
@click="$resources.method.submit()"
>
{{ dialogData.buttonMessage }}
</Button>
</div>
</template>
</Dialog>
</template>
<script>
import { Dialog, ErrorMessage } from "frappe-ui"
import { del } from "idb-keyval"
import { toast } from "../utils/toasts.js"
export default {
name: "GeneralDialog",
components: {
Dialog,
ErrorMessage,
},
props: {
modelValue: {
type: Boolean,
required: true,
},
entities: {
type: [Array, String],
required: true,
},
for: {
type: String,
default: null,
},
},
emits: ["update:modelValue", "success"],
data() {
return {
errorMessage: "",
}
},
computed: {
dialogData() {
const items =
this.entities.length === 1
? `${this.entities.length} item`
: `${this.entities.length} items`
switch (this.for) {
case "unshare":
return {
title: "Unshare",
message:
"Selected items will not be shared with you anymore and you will lose access to them.",
buttonMessage: "Remove",
theme: "red",
buttonIcon: "trash-2",
methodName: "drive.api.files.unshare_entities",
toastMessage: `Unshared ${items}`,
}
case "restore":
return {
title: "Restore Items",
message:
"Selected items will be restored to their original locations.",
buttonMessage: "Restore",
variant: "solid",
buttonIcon: "refresh-ccw",
methodName: "drive.api.files.remove_or_restore",
toastMessage: `Restored ${items}`,
}
case "remove":
return {
title: "Move to Trash",
message:
items +
" will be moved to Trash. Items in trash are deleted forever after 30 days. Other users will lose access to this.",
buttonMessage: "Move to Trash",
theme: "red",
variant: "subtle",
buttonIcon: "trash-2",
methodName: "drive.api.files.remove_or_restore",
toastMessage: `Moved ${items} to Trash`,
}
default:
return {}
}
},
open: {
get() {
return this.modelValue
},
set(value) {
this.$emit("update:modelValue", value)
},
},
},
resources: {
method() {
return {
url: this.dialogData.methodName,
params: {
entity_names:
typeof this.entities === "string"
? JSON.stringify([this.entities])
: JSON.stringify(this.entities.map((entity) => entity.name)),
},
onSuccess(data) {
this.$emit("success", data)
this.$resources.method.reset()
this.entities.map((entity) => del(entity.name))
toast({
title: this.dialogData.toastMessage,
position: "bottom-right",
timeout: 2,
})
},
onError(error) {
if (error.messages) {
this.errorMessage = error.messages.join("\n")
} else {
this.errorMessage = error.message
}
},
}
},
},
}
</script>
|
2302_79757062/drive
|
frontend/src/components/GeneralDialog.vue
|
Vue
|
agpl-3.0
| 3,899
|
<template>
<div v-if="foldersBefore && is_group">
<div class="flex items-start">
<svg
class="h-7.5 w-auto"
:draggable="false"
:style="{ fill: color }"
width="16"
height="16"
viewBox="0 0 16 16"
fill="none"
xmlns="http://www.w3.org/2000/svg"
>
<g clip-path="url(#clip0_1942_59507)">
<path
d="M7.83412 2.88462H1.5C1.22386 2.88462 1 3.10847 1 3.38462V12.5C1 13.6046 1.89543 14.5 3 14.5H13C14.1046 14.5 15 13.6046 15 12.5V2C15 1.72386 14.7761 1.5 14.5 1.5H9.94008C9.88623 1.5 9.83382 1.51739 9.79065 1.54957L8.13298 2.78547C8.04664 2.84984 7.94182 2.88462 7.83412 2.88462Z"
/>
</g>
<defs>
<clipPath id="clip0_1942_59507">
<rect width="16" height="16" fill="white" />
</clipPath>
</defs>
</svg>
</div>
<div class="content-center grid mt-2 sm:mt-3.5">
<span class="truncate text-base font-medium text-gray-800">
{{ title }}
</span>
<p :title="modified" class="truncate text-sm text-gray-600 mt-2">
{{ file_size ? file_size + " ∙ " : "" }}
{{ relativeModified }}
</p>
</div>
</div>
<template v-else>
<div
class="h-2/3 flex items-center justify-center rounded-t-[calc(theme(borderRadius.lg)-1px)] overflow-hidden"
>
<!-- Folder Icon -->
<svg
v-if="is_group"
class="h-8.5 w-auto"
:draggable="false"
:style="{ fill: color }"
width="16"
height="16"
viewBox="0 0 16 16"
fill="none"
xmlns="http://www.w3.org/2000/svg"
>
<g clip-path="url(#clip0_1942_59507)">
<path
d="M7.83412 2.88462H1.5C1.22386 2.88462 1 3.10847 1 3.38462V12.5C1 13.6046 1.89543 14.5 3 14.5H13C14.1046 14.5 15 13.6046 15 12.5V2C15 1.72386 14.7761 1.5 14.5 1.5H9.94008C9.88623 1.5 9.83382 1.51739 9.79065 1.54957L8.13298 2.78547C8.04664 2.84984 7.94182 2.88462 7.83412 2.88462Z"
/>
</g>
<defs>
<clipPath id="clip0_1942_59507">
<rect width="16" height="16" fill="white" />
</clipPath>
</defs>
</svg>
<img
v-else
loading="lazy"
:class="parsedStyled"
:src="link"
:draggable="false"
/>
</div>
<div class="p-2 h-1/3 content-center grid border-t border-gray-100">
<span class="truncate text-base font-medium text-gray-800">
{{ title }}
</span>
<div class="flex items-center justify-start mt-2">
<p :title="modified" class="truncate text-xs text-gray-600">
{{ file_size }} {{ file_size ? "∙" : null }} {{ relativeModified }}
</p>
</div>
</div>
</template>
</template>
<script>
import { formatMimeType } from "@/utils/format"
import { getIconUrl, thumbnail_getIconUrl } from "@/utils/getIconUrl"
export default {
name: "GridItem",
props: {
file_kind: String,
mime_type: String,
file_ext: String,
name: String,
title: String,
relativeModified: String,
modified: String,
file_size: String,
is_group: Number,
color: String,
},
setup() {
return { formatMimeType, getIconUrl, thumbnail_getIconUrl }
},
data: function () {
return {
link: new URL(
`/src/assets/images/icons/${this.mime_type}.svg`,
import.meta.url
),
}
},
computed: {
foldersBefore() {
return this.$store.state.foldersBefore
},
parsedStyled() {
if (typeof this.link === "string") {
return "h-full min-w-full object-cover rounded-t-[calc(theme(borderRadius.lg)-1px)]"
} else {
return "h-10 w-auto"
}
},
},
created() {
this.thumbnailUrl()
},
methods: {
async thumbnailUrl() {
let result = await thumbnail_getIconUrl(
formatMimeType(this.mime_type),
this.name,
this.file_ext
)
this.link = result
},
},
}
</script>
|
2302_79757062/drive
|
frontend/src/components/GridItem.vue
|
Vue
|
agpl-3.0
| 4,016
|
<template>
<div id="main" ref="container">
<div v-for="(entities, i) in folderContents" :key="i">
<span
v-if="entities.length && Object.keys(folderContents).length > 1"
class="text-base text-gray-600 font-medium leading-6 pl-1 my-0"
>
{{ i }}
</span>
<div v-if="entities.length" class="grid-container mt-2 mb-4">
<div
v-for="file in entities"
:id="file.name"
:key="file.name"
class="rounded-lg border group select-none entity cursor-pointer relative group:"
:class="[
file.is_group && foldersBefore
? 'p-3 w-[162px] sm:w-[172px] h-[98px] sm:h-[108px]'
: 'w-[162px] h-[162px] sm:w-[172px] sm:h-[172px]',
selectedEntities.includes(file)
? 'bg-gray-100 border-gray-300'
: 'border-gray-200 hover:shadow-xl',
]"
draggable="false"
@[action]="dblClickEntity(file)"
@click="selectEntity(file, $event, displayOrderedEntities)"
@mousedown.stop
@contextmenu="
handleEntityContext(file, $event, displayOrderedEntities)
"
>
<Button
:variant="'subtle'"
:model-value="selectedEntities.includes(file)"
class="z-10 duration-300 absolute visible group-hover:visible sm:invisible top-2 right-2"
:class="[
selectedEntities.includes(file)
? 'visible '
: 'sm:bg-gray-100 visible sm:invisible',
]"
@click.stop="
handleEntityContext(file, $event, displayOrderedEntities)
"
>
<FeatherIcon class="h-4" name="more-horizontal" />
</Button>
<GridItem
:file_kind="file.file_kind"
:mime_type="file.mime_type"
:file_ext="file.file_ext"
:name="file.name"
:title="file.title"
:modified="file.modified"
:relative-modified="file.relativeModified"
:file_size="file.file_size"
:is_group="file.is_group"
:color="file.color"
/>
</div>
</div>
</div>
<Button
v-if="overrideCanLoadMore"
class="w-full mx-auto text-base pt-8 pb-4"
:loading="true"
:disabled="true"
variant="ghost"
>Loading</Button
>
</div>
</template>
<script>
import GridItem from "@/components/GridItem.vue"
import { FeatherIcon, Button } from "frappe-ui"
import { useInfiniteScroll } from "@vueuse/core"
import { ref } from "vue"
export default {
name: "GridView",
components: {
GridItem,
Button,
FeatherIcon,
},
props: {
folderContents: {
type: Object,
default: null,
},
folders: {
type: Array,
default: null,
},
files: {
type: Array,
default: null,
},
selectedEntities: {
type: Array,
default: null,
},
overrideCanLoadMore: {
type: Boolean,
default: false,
},
},
emits: [
"entitySelected",
"openEntity",
"showEntityContext",
"showEmptyEntityContext",
"fetchFolderContents",
"updateOffset",
],
setup(props, { emit }) {
const container = ref(null)
useInfiniteScroll(
container,
() => {
emit("updateOffset")
},
{
direction: "bottom",
distance: 0,
interval: 100,
canLoadMore: () => props.overrideCanLoadMore,
}
)
return { container, useInfiniteScroll }
},
computed: {
action() {
if (window.innerWidth < 640) return "click"
if (this.$store.state.singleClick) {
return "click"
} else {
return "dblclick"
}
},
isEmpty() {
return !this.$store.state.currentViewEntites?.length
},
foldersBefore() {
return this.$store.state.foldersBefore
},
displayOrderedEntities() {
return this.$store.state.currentViewEntites
},
},
methods: {
selectEntity(entity, event, entities) {
this.$emit("showEntityContext", null)
this.$emit("showEmptyEntityContext", null)
if (event.ctrlKey || event.metaKey) {
this.selectedEntities.indexOf(entity) > -1
? this.selectedEntities.splice(
this.selectedEntities.indexOf(entity),
1
)
: this.selectedEntities.push(entity)
this.$emit("entitySelected", this.selectedEntities)
this.$store.commit("setEntityInfo", this.selectedEntities)
} else if (event.shiftKey) {
if (this.selectedEntities.includes(entity)) {
return null
}
let shiftSelect
this.selectedEntities.push(entity)
const firstIndex = entities.indexOf(this.selectedEntities[0])
const lastIndex = entities.indexOf(
this.selectedEntities[this.selectedEntities.length - 1]
)
shiftSelect = entities.slice(firstIndex, lastIndex)
if (firstIndex > lastIndex) {
shiftSelect = entities.slice(lastIndex, firstIndex)
} else {
shiftSelect = entities.slice(firstIndex, lastIndex)
}
shiftSelect.slice(1).map((file) => {
if (!this.selectedEntities.includes(file)) {
this.selectedEntities.push(file)
}
})
this.$emit("entitySelected", this.selectedEntities)
this.$store.commit("setEntityInfo", this.selectedEntities)
} else {
this.$emit("entitySelected", [entity])
this.$store.commit("setEntityInfo", [entity])
}
},
dblClickEntity(entity) {
this.$store.commit("setEntityInfo", [entity])
this.$emit("openEntity", entity)
},
deselectAll() {
this.$emit("entitySelected", [])
this.$store.commit("setEntityInfo", [])
this.$emit("showEntityContext", null)
this.$emit("showEmptyEntityContext", null)
},
handleEntityContext(entity, event) {
let clientX = event.clientX
let clientY = event.clientY
if (event.changedTouches) {
clientX = event.changedTouches[0].clientX
clientY = event.changedTouches[0].clientY
}
event.preventDefault(event)
if (this.selectedEntities.length <= 1) {
this.$emit("entitySelected", [entity])
this.$store.commit("setEntityInfo", [entity])
}
this.$emit("showEntityContext", { x: clientX, y: clientY })
},
},
}
</script>
<style scoped>
.grid-container {
display: grid;
grid-template-columns: repeat(auto-fill, minmax(162px, 1fr));
gap: 20px;
}
</style>
|
2302_79757062/drive
|
frontend/src/components/GridView.vue
|
Vue
|
agpl-3.0
| 6,643
|
<template>
<div
class="transition-all duration-200 ease-in-out h-full border-l"
:class="
showInfoSidebar
? 'sm:min-w-[352px] sm:max-w-[352px] min-w-full opacity-100'
: 'w-0 min-w-0 max-w-0 overflow-hidden opacity-0'
"
>
<div v-if="typeof entity === 'number'">
<div class="w-full px-5 py-4 border-b overflow-visible">
<div class="flex items-center">
<div class="font-medium truncate text-lg">
{{ store.state.entityInfo.length }} items selected
</div>
</div>
</div>
</div>
<div v-else-if="entity">
<div class="w-full px-5 py-4 border-b">
<div class="flex items-center">
<div class="font-medium truncate text-lg">
{{ entity.title }}
</div>
<Button
icon="x"
variant="ghost"
class="ml-auto sm:hidden"
@click="$store.commit('setShowInfo', false)"
/>
</div>
</div>
<!-- Information -->
<div v-if="tab === 0" class="h-full border-b px-5 pt-4 pb-5 w-full">
<span
class="inline-flex items-center gap-2.5 mb-5 text-gray-800 font-medium text-lg w-full"
>
<Info />
Information
</span>
<div
v-if="
(entity.mime_type?.startsWith('video') ||
(entity.mime_type?.startsWith('image') &&
entity?.mime_type !== 'image/svg+xml')) &&
showInfoSidebar
"
class="h-[210px] w-full mb-4"
>
<img class="object-contain h-full mx-auto" :src="thumbnailLink" />
</div>
<div class="space-y-6.5">
<div v-if="entity.owner === 'You'">
<div class="text-base font-medium mb-4">Access</div>
<div class="flex items-center justify-start">
<Avatar
size="lg"
:label="entity.owner"
:image="entity.user_image"
/>
<div class="border-l h-6 mx-1.5"></div>
<GeneralAccess
v-if="
!generalAccess.loading &&
(!!generalAccess.data?.length || !sharedWithList?.length)
"
size="lg"
class="-mr-[3px] outline outline-white"
:general-access="generalAccess?.data?.[0]"
/>
<div
v-if="sharedWithList?.length && !sharedWithList.loading"
class="flex items-center justify-start"
>
<Avatar
v-for="user in sharedWithList.slice(0, 3)"
:key="user?.user_name"
size="lg"
:label="user?.full_name ? user?.full_name : user?.user_name"
:image="user?.user_image"
class="-mr-[3px] outline outline-white"
/>
<Avatar
v-if="sharedWithList.slice(3).length"
size="lg"
:label="sharedWithList.slice(3).length.toString()"
class="-mr-[3px] outline outline-white"
/>
</div>
<!-- <Button class="ml-auto" @click="showShareDialog = true">
Share
</Button> -->
</div>
</div>
<!-- <div v-if="entityTags.data?.length || entity.owner === 'You'">
<div class="text-base font-medium mb-4">Tags</div>
<div class="flex items-center justify-start flex-wrap gap-y-4">
<div
v-if="entityTags.data?.length"
class="flex flex-wrap gap-2 max-w-full"
>
<Tag
v-for="tag in entityTags?.data"
:key="tag"
:tag="tag"
:entity="entity"
@success="
() => {
userTags.fetch()
entityTags.fetch()
}
"
/>
</div>
<span v-else-if="!addTag" class="text-gray-700 text-base">
This file has no tags
</span>
<Button
v-if="!addTag && entity.owner === 'You'"
class="ml-auto"
@click="addTag = true"
>
Add tag
</Button>
<TagInput
v-if="addTag"
:entity="entity"
:unadded-tags="unaddedTags"
@success="
() => {
userTags.fetch()
entityTags.fetch()
addTag = false
}
"
@close="addTag = false"
/>
</div>
</div> -->
<div>
<div class="text-base font-medium mb-4">Properties</div>
<div class="text-base grid grid-flow-row grid-cols-2 gap-y-3">
<span class="col-span-1 text-gray-600">Type</span>
<span class="col-span-1">{{ formattedMimeType }}</span>
<span v-if="entity.file_size" class="col-span-1 text-gray-600">
Size
</span>
<span v-if="entity.file_size" class="col-span-1">
{{ entity.file_size }}
</span>
<span class="col-span-1 text-gray-600">Modified</span>
<span class="col-span-1">{{ entity.modified }}</span>
<span class="col-span-1 text-gray-600">Created</span>
<span class="col-span-1">{{ entity.creation }}</span>
<span class="col-span-1 text-gray-600">Owner</span>
<span class="col-span-1">{{ entity.full_name }}</span>
</div>
</div>
</div>
</div>
<!-- Comments -->
<div
v-if="tab === 1"
class="max-h-[90vh] pt-4 pb-5 border-b overflow-y-auto overflow-x-hidden"
>
<span
class="inline-flex items-center gap-2.5 px-5 mb-5 text-gray-800 font-medium text-lg w-full"
>
<Comment />
Comments
</span>
<div v-if="entity.allow_comments" class="pb-2 px-5">
<div
v-for="comment in comments.data"
:key="comment"
class="flex flex-col mb-5"
>
<div class="flex items-start justify-start">
<Avatar
:label="comment.comment_by"
:image="comment.user_image"
class="h-7 w-7"
/>
<div class="ml-3">
<div class="flex items-center justify-start text-base gap-x-1">
<span class="font-medium">{{ comment.comment_by }}</span>
<span>{{ "∙" }}</span>
<span class="text-gray-600">{{ comment.creation }}</span>
</div>
<span
class="my-2 text-base text-gray-700 break-word leading-snug"
>
{{ comment.content }}
</span>
</div>
</div>
</div>
<div
v-if="userId != 'Guest'"
class="flex items-center justify-start py-2"
>
<Avatar :label="fullName" :image="imageURL" class="h-7 w-7 mr-3" />
<div
class="flex items-center border w-full bg-transparent rounded mr-1 focus-within:ring-2 ring-gray-400 hover:bg-gray-100 focus-within:bg-gray-100 group"
>
<textarea
v-model="newComment"
class="w-full form-textarea bg-transparent resize-none border-none hover:bg-transparent focus:ring-0 focus:shadow-none focus:bg-transparent"
placeholder="Add a comment"
@input="resize($event)"
@keypress.enter.stop.prevent="postComment"
/>
<Button
class="hover:bg-transparent"
variant="ghost"
icon="arrow-up-circle"
:disabled="!newComment.length"
@click="postComment"
></Button>
</div>
</div>
</div>
<div v-else class="text-gray-600 text-sm px-5">
Comments have been disabled for this
{{ entity.is_group ? "folder" : "file" }} by its owner.
</div>
</div>
</div>
<div
v-else
class="flex h-full w-full flex-col items-center justify-center rounded-lg text-center"
>
<File class="w-auto h-10 text-gray-600 mb-2" />
<p class="text-sm text-gray-600 font-medium">No file selected</p>
</div>
</div>
<div
class="hidden sm:flex flex-col items-center overflow-hidden h-full min-w-[48px] gap-1 pt-3 px-0 border-l z-0 bg-white"
>
<Button
class="text-gray-600"
:class="[
tab === 0 && showInfoSidebar
? 'text-black bg-gray-200'
: ' hover:bg-gray-50',
]"
variant="minimal"
@click="switchTab(0)"
><Info
/></Button>
<Button
v-if="showComments"
class="text-gray-600"
:class="[
tab === 1 && showInfoSidebar
? 'text-black bg-gray-200'
: ' hover:bg-gray-50',
]"
variant="minimal"
@click="switchTab(1)"
><Comment
/></Button>
</div>
</template>
<script setup>
import { ref, computed, watch } from "vue"
import { useStore } from "vuex"
import { Avatar, call, createResource } from "frappe-ui"
import { formatMimeType, formatDate } from "@/utils/format"
import GeneralAccess from "@/components/GeneralAccess.vue"
import { thumbnail_getIconUrl } from "@/utils/getIconUrl"
import Info from "./EspressoIcons/Info.vue"
import File from "./EspressoIcons/File.vue"
import Comment from "./EspressoIcons/Comment.vue"
const store = useStore()
const tab = ref(0)
const newComment = ref("")
const thumbnailLink = ref("")
const userId = computed(() => {
return store.state.auth.user_id
})
const fullName = computed(() => {
return store.state.user.fullName
})
const imageURL = computed(() => {
return store.state.user.imageURL
})
const showInfoSidebar = computed(() => {
return store.state.showInfo
})
const formattedMimeType = computed(() => {
if (entity.value.is_group) return "Folder"
const file = entity.value.file_kind
return file?.charAt(0).toUpperCase() + file?.slice(1)
})
const entity = computed(() => {
if (store.state.entityInfo && store.state.entityInfo.length > 1) {
return store.state.entityInfo.length
} else if (store.state.entityInfo?.length) {
return store.state.entityInfo[0]
} else if (store.state.currentFolder?.length) {
return store.state.currentFolder[0]
} else {
return false
}
})
const sharedWithList = computed(() => {
return userList.data?.users.concat(groupList.data)
})
const showComments = computed(() => {
if (entity.value.owner === "You") {
return true
} else if (entity.value.write) {
return true
} else if (entity.value.allow_comments) {
return true
} else {
return false
}
})
function switchTab(val) {
if (store.state.showInfo == false) {
store.commit("setShowInfo", !store.state.showInfo)
tab.value = val
} else if (tab.value == val) {
store.commit("setShowInfo", !store.state.showInfo)
} else {
tab.value = val
}
}
async function thumbnailUrl() {
let result = await thumbnail_getIconUrl(
formatMimeType(entity.value.mime_type),
entity.value.name,
entity.value.file_ext
)
thumbnailLink.value = result
}
watch([entity, showInfoSidebar], ([newEntity, newShowInfoSidebar]) => {
if (
newEntity &&
typeof newEntity !== "number" &&
typeof newEntity !== "undefined"
) {
if (newShowInfoSidebar == true) {
thumbnailUrl()
comments.fetch({ entity_name: newEntity.name })
entityTags.fetch({ entity: newEntity.name })
generalAccess.fetch({ entity_name: newEntity.name })
userList.fetch({ entity_name: newEntity.name })
groupList.fetch({ entity_name: newEntity.name })
userTags.fetch()
}
}
})
async function postComment() {
if (newComment.value.length) {
try {
await call("frappe.desk.form.utils.add_comment", {
reference_doctype: "Drive Entity",
reference_name: entity.value.name,
content: newComment.value,
comment_email: userId.value,
comment_by: fullName.value,
})
newComment.value = ""
comments.fetch()
} catch (e) {
console.log(e)
}
}
}
let comments = createResource({
url: "drive.api.files.list_entity_comments",
onSuccess(data) {
data.forEach((comment) => {
comment.creation = formatDate(comment.creation)
})
},
onError(error) {
if (error.messages) {
console.log(error.messages)
}
},
auto: false,
})
const generalAccess = createResource({
url: "drive.api.permissions.get_general_access",
auto: false,
})
const userList = createResource({
url: "drive.api.permissions.get_shared_with_list",
auto: false,
})
const groupList = createResource({
url: "drive.api.permissions.get_shared_user_group_list",
auto: false,
})
let userTags = createResource({
url: "drive.api.tags.get_user_tags",
onError(error) {
if (error.messages) {
console.log(error.messages)
}
},
auto: false,
})
let entityTags = createResource({
url: "drive.api.tags.get_entity_tags",
onError(error) {
if (error.messages) {
console.log(error.messages)
}
},
auto: false,
})
function resize(e) {
e.target.style.height = `${e.target.scrollHeight}px`
}
</script>
|
2302_79757062/drive
|
frontend/src/components/InfoSidebar.vue
|
Vue
|
agpl-3.0
| 13,814
|
<template>
<div id="main" ref="container">
<div
class="hidden sm:grid items-center rounded bg-gray-100 min-h-7 p-2 overflow-hidden mb-2"
:style="{ gridTemplateColumns: tableColumnsGridWidth }"
>
<div class="flex w-full items-center text-sm text-gray-600">Name</div>
<div class="flex w-full items-center justify-start text-sm text-gray-600">
Owner
</div>
<div
v-if="$route.name === 'Recents'"
class="flex w-full items-center justify-end text-sm text-gray-600"
>
Last Accessed
</div>
<div
v-else
class="flex w-full items-center justify-end text-sm text-gray-600"
>
Last Modified
</div>
<div class="flex w-full items-center justify-end text-sm text-gray-600">
Size
</div>
<div />
</div>
<div v-for="(entities, i) in folderContents" :key="i">
<div
v-if="Object.keys(folderContents).length > 1 && entities.length"
class="flex items-center w-full py-1.5 pr-2"
>
<span class="text-base text-gray-600 font-medium leading-6 pl-1.5">
{{ i }}
</span>
</div>
<div
v-if="Object.keys(folderContents).length > 1 && entities.length"
class="mx-2 h-px border-t border-gray-200"
></div>
<div v-for="entity in entities" :key="entity.name">
<div
:id="entity.name"
:key="entity.name"
class="entity grid items-center cursor-pointer rounded px-2 py-1.5 hover:bg-gray-50 group"
:style="{
gridTemplateColumns: tableColumnsGridWidth,
}"
:class="
selectedEntities.includes(entity)
? 'bg-gray-100'
: 'hover:bg-gray-100'
"
:draggable="false"
@[action]="dblClickEntity(entity)"
@click="selectEntity(entity, $event, displayOrderedEntities)"
@contextmenu="
handleEntityContext(entity, $event, displayOrderedEntities)
"
@dragstart="dragStart(entity, $event)"
@dragenter.prevent
@dragover.prevent
@mousedown.stop
@drop="isGroupOnDrop(entity)"
>
<div
class="flex items-center text-gray-800 text-base font-medium truncate"
:draggable="false"
>
<svg
v-if="entity.is_group"
class="h-auto w-5 mr-3"
:draggable="false"
:style="{ fill: entity.color }"
width="16"
height="16"
viewBox="0 0 16 16"
fill="none"
xmlns="http://www.w3.org/2000/svg"
>
<g clip-path="url(#clip0_1942_59507)">
<path
d="M7.83412 2.88462H1.5C1.22386 2.88462 1 3.10847 1 3.38462V12.5C1 13.6046 1.89543 14.5 3 14.5H13C14.1046 14.5 15 13.6046 15 12.5V2C15 1.72386 14.7761 1.5 14.5 1.5H9.94008C9.88623 1.5 9.83382 1.51739 9.79065 1.54957L8.13298 2.78547C8.04664 2.84984 7.94182 2.88462 7.83412 2.88462Z"
/>
</g>
<defs>
<clipPath id="clip0_1942_59507">
<rect width="16" height="16" fill="white" />
</clipPath>
</defs>
</svg>
<img
v-else
:src="getIconUrl(formatMimeType(entity.mime_type))"
:draggable="false"
class="h-[20px] mr-3"
/>
{{ entity.title }}
</div>
<div
class="hidden sm:flex items-center justify-start text-gray-700 text-base truncate"
>
<Avatar
:image="entity.user_image"
:label="entity.full_name"
class="-relative mr-2"
size="sm"
/>
{{ entity.owner }}
</div>
<div
:title="entity.modified"
class="hidden sm:flex items-center justify-end text-gray-700 text-base truncate"
>
{{ entity.relativeModified }}
</div>
<div class="flex w-full justify-end text-base text-gray-700">
{{ entity.file_size }}
</div>
<div class="flex w-full justify-end">
<Button
:variant="'ghost'"
:model-value="selectedEntities.includes(entity)"
:class="
selectedEntities.includes(entity)
? 'visible bg-gray-300'
: 'bg-inherit visible'
"
class="border-1 duration-300 relative ml-auto visible group-hover:visible"
@click.stop="
handleEntityContext(entity, $event, displayOrderedEntities)
"
>
<FeatherIcon class="h-4" name="more-horizontal" />
</Button>
</div>
</div>
<div class="mx-2 h-px border-t border-gray-200"></div>
</div>
</div>
<Button
v-if="overrideCanLoadMore"
class="w-full mx-auto text-base pt-8 pb-6"
:loading="true"
:disabled="true"
variant="ghost"
>Loading</Button
>
</div>
</template>
<script>
import { Avatar, Button, FeatherIcon } from "frappe-ui"
import { formatMimeType } from "@/utils/format"
import { getIconUrl } from "@/utils/getIconUrl"
import { useInfiniteScroll } from "@vueuse/core"
import { ref } from "vue"
export default {
name: "ListView",
components: {
Avatar,
Button,
FeatherIcon,
},
props: {
folderContents: {
type: Object,
default: null,
},
selectedEntities: {
type: Array,
default: null,
},
overrideCanLoadMore: {
type: Boolean,
default: false,
},
},
emits: [
"entitySelected",
"openEntity",
"showEntityContext",
"showEmptyEntityContext",
"fetchFolderContents",
"updateOffset",
],
setup(props, { emit }) {
const container = ref(null)
useInfiniteScroll(
container,
() => {
emit("updateOffset")
},
{
direction: "bottom",
distance: 150,
interval: 2000,
canLoadMore: () => props.overrideCanLoadMore,
}
)
return { container, useInfiniteScroll, formatMimeType, getIconUrl }
},
computed: {
action() {
if (window.innerWidth < 640) return "click"
if (this.$store.state.singleClick) {
return "click"
} else {
return "dblclick"
}
},
tableColumnsGridWidth() {
return window.innerWidth < 640
? "2fr 1fr 40px"
: "2fr 1fr 150px 150px 40px"
},
isEmpty() {
return !this.$store.state.currentViewEntites?.length
},
foldersBefore() {
return this.$store.state.foldersBefore
},
displayOrderedEntities() {
return this.$store.state.currentViewEntites
},
},
methods: {
selectEntity(entity, event, entities) {
this.$emit("showEntityContext", null)
this.$emit("showEmptyEntityContext", null)
if (event.ctrlKey || event.metaKey) {
/* this.selectedEntities.indexOf(entity) > -1
? this.selectedEntities.splice(
this.selectedEntities.indexOf(entity),
1
) */
if (this.selectedEntities.includes(entity)) {
this.selectedEntities.pop(entity)
} else {
this.selectedEntities.push(entity)
}
this.$emit("entitySelected", this.selectedEntities)
this.$store.commit("setEntityInfo", this.selectedEntities)
} else if (event.shiftKey) {
if (this.selectedEntities.includes(entity)) {
return null
}
let shiftSelect
this.selectedEntities.push(entity)
const firstIndex = entities.indexOf(this.selectedEntities[0])
const lastIndex = entities.indexOf(
this.selectedEntities[this.selectedEntities.length - 1]
)
shiftSelect = entities.slice(firstIndex, lastIndex)
if (firstIndex > lastIndex) {
shiftSelect = entities.slice(lastIndex, firstIndex)
} else {
shiftSelect = entities.slice(firstIndex, lastIndex)
}
shiftSelect.slice(1).map((file) => {
if (!this.selectedEntities.includes(file)) {
this.selectedEntities.push(file)
}
})
this.$emit("entitySelected", this.selectedEntities)
this.$store.commit("setEntityInfo", this.selectedEntities)
} else {
this.$emit("entitySelected", [entity])
this.$store.commit("setEntityInfo", [entity])
}
},
dblClickEntity(entity) {
this.$store.commit("setEntityInfo", [entity])
this.$emit("openEntity", entity)
},
deselectAll() {
this.$emit("entitySelected", [])
this.$store.commit("setEntityInfo", [])
this.$emit("showEntityContext", null)
this.$emit("showEmptyEntityContext", null)
},
handleEntityContext(entity, event) {
let clientX = event.clientX
let clientY = event.clientY
if (event.changedTouches) {
clientX = event.changedTouches[0].clientX
clientY = event.changedTouches[0].clientY
}
event.preventDefault(event)
if (this.selectedEntities.length <= 1) {
this.$emit("entitySelected", [entity])
this.$store.commit("setEntityInfo", [entity])
}
this.$emit("showEntityContext", { x: clientX, y: clientY })
},
},
}
</script>
|
2302_79757062/drive
|
frontend/src/components/ListView.vue
|
Vue
|
agpl-3.0
| 9,505
|
<template>
<div class="h-full pt-4 sm:pt-16">
<div>
<div class="flex justify-center items-center mx-auto">
<FrappeDriveLogo class="w-auto h-8" />
<span class="pl-2 text-2xl font-semibold">Frappe Drive</span>
</div>
<div
class="px-4 py-8 mx-auto bg-white sm:mt-6 sm:w-0112 sm:w-96 sm:px-10 sm:rounded-lg sm:shadow-xl"
>
<div class="mb-6 text-center">
<span class="text-lg">{{ title }}</span>
</div>
<slot></slot>
</div>
</div>
</div>
</template>
<script>
import FrappeDriveLogo from "@/components/FrappeDriveLogo.vue"
export default {
name: "LoginBox",
components: {
FrappeDriveLogo,
},
props: {
title: {
type: String,
required: true,
},
},
}
</script>
|
2302_79757062/drive
|
frontend/src/components/LoginBox.vue
|
Vue
|
agpl-3.0
| 788
|
<template>
<svg
width="16"
height="16"
viewBox="0 0 16 16"
fill="none"
xmlns="http://www.w3.org/2000/svg"
>
<g clip-path="url(#clip0_315_271)">
<mask
id="mask0_315_271"
style="mask-type: luminance"
maskUnits="userSpaceOnUse"
x="0"
y="0"
width="16"
height="16"
>
<path d="M16 0H0V16H16V0Z" fill="white" />
</mask>
<g mask="url(#mask0_315_271)">
<mask
id="mask1_315_271"
style="mask-type: luminance"
maskUnits="userSpaceOnUse"
x="1"
y="1"
width="14"
height="14"
>
<path d="M15 1H1V15H15V1Z" fill="white" />
</mask>
<g mask="url(#mask1_315_271)">
<path
d="M12 1H4C2.34315 1 1 2.34315 1 4V12C1 13.6569 2.34315 15 4 15H12C13.6569 15 15 13.6569 15 12V4C15 2.34315 13.6569 1 12 1Z"
fill="#C2A88D"
/>
<g filter="url(#filter0_i_315_271)">
<path
fill-rule="evenodd"
clip-rule="evenodd"
d="M6 1H8V2H6V1ZM8 3V2H10V3H8ZM8 4H6V3H8V4ZM8 5V4H10V5H8ZM8 6H6V5H8V6ZM8 7V6H10V7H8ZM8 8H6V7H8V8ZM8 9V8H10V9H8ZM8 9V10H10V11.25C10 12.3546 9.10457 13.25 8 13.25C6.89543 13.25 6 12.3546 6 11.25V9H8ZM8 12.25C8.41421 12.25 8.75 11.9142 8.75 11.5C8.75 11.0858 8.41421 10.75 8 10.75C7.58579 10.75 7.25 11.0858 7.25 11.5C7.25 11.9142 7.58579 12.25 8 12.25Z"
fill="white"
/>
</g>
</g>
</g>
</g>
<defs>
<filter
id="filter0_i_315_271"
x="6"
y="1"
width="4"
height="12.75"
filterUnits="userSpaceOnUse"
color-interpolation-filters="sRGB"
>
<feFlood flood-opacity="0" result="BackgroundImageFix" />
<feBlend
mode="normal"
in="SourceGraphic"
in2="BackgroundImageFix"
result="shape"
/>
<feColorMatrix
in="SourceAlpha"
type="matrix"
values="0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 127 0"
result="hardAlpha"
/>
<feOffset dy="0.5" />
<feGaussianBlur stdDeviation="0.5" />
<feComposite in2="hardAlpha" operator="arithmetic" k2="-1" k3="1" />
<feColorMatrix
type="matrix"
values="0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0.25 0"
/>
<feBlend
mode="normal"
in2="shape"
result="effect1_innerShadow_315_271"
/>
</filter>
<clipPath id="clip0_315_271">
<rect width="16" height="16" fill="white" />
</clipPath>
</defs>
</svg>
</template>
|
2302_79757062/drive
|
frontend/src/components/MimeIcons/Archive.vue
|
Vue
|
agpl-3.0
| 2,699
|
<template>
<svg
width="16"
height="16"
viewBox="0 0 16 16"
fill="none"
xmlns="http://www.w3.org/2000/svg"
>
<path
fill-rule="evenodd"
clip-rule="evenodd"
d="M4 1C2.34315 1 1 2.34315 1 4V12C1 13.6569 2.34315 15 4 15H12C13.6569 15 15 13.6569 15 12V4C15 2.34315 13.6569 1 12 1H4ZM9.99363 3.86769C10.2674 3.82819 10.5444 3.91261 10.7509 4.09842C10.9528 4.28078 11.0669 4.54233 11.0638 4.81589L11.0638 10.3381C11.0638 11.0366 10.3629 11.6024 9.49922 11.6024C8.63555 11.6024 7.93461 11.0366 7.93461 10.3381C7.93461 9.6396 8.63555 9.07384 9.49922 9.07384C9.82973 9.07182 10.1544 9.16147 10.438 9.33302V5.64521L6.68293 6.18569V10.8776C6.68293 11.5761 5.98198 12.1418 5.11832 12.1418C4.25465 12.1418 3.55371 11.5761 3.55371 10.8776C3.55371 10.1791 4.25465 9.61332 5.11832 9.61332C5.44883 9.6113 5.77354 9.70094 6.05708 9.87249V5.26786C6.05244 4.79193 6.39784 4.38627 6.86442 4.31966L9.99363 3.86769Z"
fill="#9C45E3"
/>
</svg>
</template>
|
2302_79757062/drive
|
frontend/src/components/MimeIcons/Audio.vue
|
Vue
|
agpl-3.0
| 987
|
<template>
<svg
width="16"
height="16"
viewBox="0 0 16 16"
fill="none"
xmlns="http://www.w3.org/2000/svg"
>
<path
fill-rule="evenodd"
clip-rule="evenodd"
d="M4 1C2.34315 1 1 2.34315 1 4V12C1 13.6569 2.34315 15 4 15H12C13.6569 15 15 13.6569 15 12V4C15 2.34315 13.6569 1 12 1H4Z"
fill="#0073CA"
/>
<path
fill-rule="evenodd"
clip-rule="evenodd"
d="M7.96195 7.06343L6.8203 11.1015H5.61522L4 5H5.3277L6.27907 9.30021H6.34672L7.45877 5H8.537L9.67019 9.30021H9.73784L10.6808 5H12L10.3806 11.1015H9.18393L8.0296 7.06343H7.96195Z"
fill="white"
/>
</svg>
</template>
|
2302_79757062/drive
|
frontend/src/components/MimeIcons/Document.vue
|
Vue
|
agpl-3.0
| 647
|
<template>
<svg
width="16"
height="16"
viewBox="0 0 16 16"
fill="none"
xmlns="http://www.w3.org/2000/svg"
>
<g clip-path="url(#clip0_1942_59507)">
<path
d="M7.83412 2.88462H1.5C1.22386 2.88462 1 3.10847 1 3.38462V12.5C1 13.6046 1.89543 14.5 3 14.5H13C14.1046 14.5 15 13.6046 15 12.5V2C15 1.72386 14.7761 1.5 14.5 1.5H9.94008C9.88623 1.5 9.83382 1.51739 9.79065 1.54957L8.13298 2.78547C8.04664 2.84984 7.94182 2.88462 7.83412 2.88462Z"
fill="#525252"
/>
</g>
<defs>
<clipPath id="clip0_1942_59507">
<rect width="16" height="16" fill="white" />
</clipPath>
</defs>
</svg>
</template>
|
2302_79757062/drive
|
frontend/src/components/MimeIcons/Folder.vue
|
Vue
|
agpl-3.0
| 672
|
<template>
<svg
width="16"
height="16"
viewBox="0 0 16 16"
fill="none"
xmlns="http://www.w3.org/2000/svg"
>
<g clip-path="url(#clip0_1942_8000)">
<path
fill-rule="evenodd"
clip-rule="evenodd"
d="M4 1C2.34315 1 1 2.34315 1 4V12C1 13.6569 2.34315 15 4 15H12C13.6569 15 15 13.6569 15 12V4C15 2.34315 13.6569 1 12 1H4ZM5.25002 7C6.21652 7 7.00002 6.2165 7.00002 5.25C7.00002 4.2835 6.21652 3.5 5.25002 3.5C4.28352 3.5 3.50002 4.2835 3.50002 5.25C3.50002 6.2165 4.28352 7 5.25002 7ZM3.67581 14C3.44371 14 3.33689 13.7112 3.51312 13.5602L9.7211 8.23906C9.88705 8.09682 10.1262 8.07885 10.3115 8.19469L13.765 10.3531C13.9112 10.4445 14 10.6047 14 10.7771V12C14 13.1046 13.1046 14 12 14H3.67581Z"
fill="#34BAE3"
/>
</g>
<defs>
<clipPath id="clip0_1942_8000">
<rect width="16" height="16" fill="white" />
</clipPath>
</defs>
</svg>
</template>
|
2302_79757062/drive
|
frontend/src/components/MimeIcons/Image.vue
|
Vue
|
agpl-3.0
| 941
|
<template>
<svg
width="16"
height="16"
viewBox="0 0 16 16"
fill="none"
xmlns="http://www.w3.org/2000/svg"
>
<path
fill-rule="evenodd"
clip-rule="evenodd"
d="M4 1C2.34315 1 1 2.34315 1 4V12C1 13.6569 2.34315 15 4 15H12C13.6569 15 15 13.6569 15 12V4C15 2.34315 13.6569 1 12 1H4ZM5.80893 10.6773C4.63445 12.7569 4.02298 13 3.66401 13C3.48964 13 3.32827 12.9308 3.19736 12.7999C3.03677 12.6393 2.97231 12.4388 3.01087 12.22C3.14435 11.4651 4.55054 10.6893 5.4324 10.2721C5.74113 9.71489 6.06198 9.07811 6.3865 8.37778C6.67422 7.757 6.93539 7.12033 7.14466 6.52956C6.69545 5.46922 6.34749 4.03811 6.79536 3.35278C6.94617 3.122 7.17178 3 7.44773 3C7.69489 3 7.89782 3.10178 8.03485 3.29411C8.38115 3.78089 8.27179 4.86178 7.70989 6.50744C7.91738 6.96589 8.16155 7.39778 8.43672 7.79256C8.72956 8.21311 9.15365 8.61222 9.6671 8.95089C10.1745 8.87467 10.6485 8.836 11.0775 8.836C11.9395 8.836 12.5214 8.98744 12.8068 9.28622C12.9413 9.42689 13.0078 9.59978 12.9993 9.78656C12.993 9.92289 12.9118 10.3681 12.1247 10.3681C11.4129 10.3681 10.413 10.03 9.55263 9.50189C9.03074 9.58889 8.49662 9.71311 7.96295 9.87111C7.22857 10.0888 6.48574 10.3669 5.80893 10.6773ZM12.426 9.64967C12.3616 9.58222 12.074 9.36233 11.0774 9.36233C10.879 9.36233 10.6699 9.37122 10.4512 9.38878C11.1161 9.69889 11.7339 9.84167 12.1246 9.84167C12.3747 9.84167 12.4628 9.78422 12.4728 9.76867C12.4747 9.73267 12.4702 9.69578 12.426 9.64967ZM7.44773 3.52633C7.35182 3.52633 7.28847 3.56056 7.23612 3.64067C7.04864 3.92744 7.06575 4.717 7.40427 5.73189C7.77046 4.48589 7.76013 3.81611 7.60576 3.59911C7.57464 3.55544 7.53586 3.52633 7.44773 3.52633ZM7.4485 7.22411C7.27413 7.67544 7.07609 8.14167 6.86415 8.599C6.65 9.06144 6.43706 9.49711 6.22779 9.90133L6.24869 9.89156L6.23213 9.92122C6.74613 9.71222 7.28214 9.524 7.81347 9.36656C8.17722 9.25878 8.54163 9.16611 8.9026 9.08967L8.88004 9.07522L8.93283 9.067C8.56019 8.76833 8.24479 8.43822 8.00463 8.09333C7.81014 7.81411 7.63021 7.51789 7.46662 7.20767L7.45551 7.23978L7.4485 7.22411ZM4.93196 11.1197C4.02443 11.6269 3.57288 12.0651 3.52932 12.3116C3.52209 12.3526 3.52643 12.3846 3.56955 12.4279C3.60989 12.4681 3.63879 12.4737 3.66401 12.4737C3.74059 12.4737 4.11922 12.3991 4.93196 11.1197Z"
fill="#E03636"
/>
</svg>
</template>
|
2302_79757062/drive
|
frontend/src/components/MimeIcons/PDF.vue
|
Vue
|
agpl-3.0
| 2,308
|
<template>
<svg
width="16"
height="16"
viewBox="0 0 16 16"
fill="none"
xmlns="http://www.w3.org/2000/svg"
>
<rect x="1" y="1" width="14" height="14" rx="3" fill="#F5BA14" />
<rect x="3.5" y="4" width="9" height="8" rx="1.5" fill="white" />
<rect x="4.5" y="5.5" width="7" height="5" fill="#F5B90F" />
</svg>
</template>
|
2302_79757062/drive
|
frontend/src/components/MimeIcons/Presentation.vue
|
Vue
|
agpl-3.0
| 358
|
<template>
<svg
width="16"
height="16"
viewBox="0 0 16 16"
fill="none"
xmlns="http://www.w3.org/2000/svg"
>
<g clip-path="url(#clip0_1942_59547)">
<path
fill-rule="evenodd"
clip-rule="evenodd"
d="M4 1C2.34315 1 1 2.34315 1 4V12C1 13.6569 2.34315 15 4 15H12C13.6569 15 15 13.6569 15 12V4C15 2.34315 13.6569 1 12 1H4ZM4 2H5.5V4H14V5.5H5.5V14H4V5.5H2V4H4V2Z"
fill="#30A66D"
/>
</g>
<defs>
<clipPath id="clip0_1942_59547">
<rect width="16" height="16" fill="white" />
</clipPath>
</defs>
</svg>
</template>
|
2302_79757062/drive
|
frontend/src/components/MimeIcons/Spreadsheet.vue
|
Vue
|
agpl-3.0
| 609
|
<template>
<svg
width="16"
height="16"
viewBox="0 0 16 16"
fill="none"
xmlns="http://www.w3.org/2000/svg"
>
<g clip-path="url(#clip0_316_313)">
<path
fill-rule="evenodd"
clip-rule="evenodd"
d="M4 1C2.34315 1 1 2.34315 1 4V12C1 13.6569 2.34315 15 4 15H12C13.6569 15 15 13.6569 15 12V4C15 2.34315 13.6569 1 12 1H4Z"
fill="#E2E2E2"
/>
<path
d="M10 5H4"
stroke="#6F6F6F"
stroke-linecap="round"
stroke-linejoin="round"
/>
<path
d="M12 8H4"
stroke="#6F6F6F"
stroke-linecap="round"
stroke-linejoin="round"
/>
<path
d="M9 11H4"
stroke="#6F6F6F"
stroke-linecap="round"
stroke-linejoin="round"
/>
</g>
<defs>
<clipPath id="clip0_316_313">
<rect width="16" height="16" fill="white" />
</clipPath>
</defs>
</svg>
</template>
|
2302_79757062/drive
|
frontend/src/components/MimeIcons/Unknown.vue
|
Vue
|
agpl-3.0
| 951
|
<template>
<svg
width="16"
height="16"
viewBox="0 0 16 16"
fill="none"
xmlns="http://www.w3.org/2000/svg"
>
<g clip-path="url(#clip0_1942_1105)">
<path
fill-rule="evenodd"
clip-rule="evenodd"
d="M4 1C2.34315 1 1 2.34315 1 4V12C1 13.6569 2.34315 15 4 15H12C13.6569 15 15 13.6569 15 12V4C15 2.34315 13.6569 1 12 1H4ZM7.09287 10.8763L10.7212 8.47937C10.8945 8.37679 11 8.19537 11 8C11 7.80463 10.8945 7.62321 10.7212 7.52063L7.09287 5.12375C6.891 4.9855 6.62753 4.96127 6.40197 5.06021C6.17641 5.15916 6.02312 5.36619 6 5.60313V10.3969C6.02312 10.6338 6.17641 10.8408 6.40197 10.9398C6.62753 11.0387 6.891 11.0145 7.09287 10.8763Z"
fill="#E86C13"
/>
</g>
<defs>
<clipPath id="clip0_1942_1105">
<rect width="16" height="16" fill="white" />
</clipPath>
</defs>
</svg>
</template>
|
2302_79757062/drive
|
frontend/src/components/MimeIcons/Video.vue
|
Vue
|
agpl-3.0
| 881
|
<template>
<div v-if="open" class="fixed inset-0 z-20 flex md:hidden">
<div class="flex w-auto flex-col bg-white">
<!-- <div class="flex h-16 items-center border-b p-4">
<FrappeDriveLogo />
</div> -->
<div class="grow p-4">
<Sidebar @toggle-mobile-sidebar="open = !open" />
</div>
</div>
<div class="grow bg-black opacity-25" @click="open = !open"></div>
</div>
</template>
<script>
import Sidebar from "@/components/Sidebar.vue"
export default {
name: "MobileSidebar",
components: {
Sidebar,
},
props: {
modelValue: {
type: Boolean,
required: true,
},
},
emits: ["update:modelValue"],
computed: {
open: {
get() {
return this.modelValue
},
set(value) {
this.$emit("update:modelValue", value)
},
},
},
}
</script>
|
2302_79757062/drive
|
frontend/src/components/MobileSidebar.vue
|
Vue
|
agpl-3.0
| 865
|
<template>
<Dialog v-model="open" :options="{ title: DialogTitle, size: 'xl' }">
<template #body>
<div class="p-6">
<div class="mb-4">
<span class="text-2xl font-semibold leading-6 text-gray-900">{{
DialogTitle
}}</span>
</div>
<Tabs v-model="tabIndex" :tabs="tabs" tablist-class="!pl-0">
<div
v-if="folderContents?.length"
class="flex flex-col justify-items-start h-[50vh] overflow-y-auto justify-start my-2"
>
<div
v-for="item in folderContents"
:id="item.name"
:key="item.name"
>
<div
class="px-3 grid items-center cursor-pointer rounded h-9 group hover:bg-gray-100"
:draggable="false"
@click="openEntity(item)"
@dragenter.prevent
@dragover.prevent
@mousedown.stop
>
<div
class="flex items-center text-gray-800 text-base font-medium truncate"
:draggable="false"
>
<svg
v-if="item.is_group"
:style="{ fill: item.color }"
:draggable="false"
class="h-4.5 mr-2"
viewBox="0 0 30 30"
xmlns="http://www.w3.org/2000/svg"
>
<path
d="M14.8341 5.40865H2.375C2.09886 5.40865 1.875 5.63251 1.875 5.90865V25.1875C1.875 26.2921 2.77043 27.1875 3.875 27.1875H26.125C27.2296 27.1875 28.125 26.2921 28.125 25.1875V3.3125C28.125 3.03636 27.9011 2.8125 27.625 2.8125H18.5651C18.5112 2.8125 18.4588 2.82989 18.4156 2.86207L15.133 5.30951C15.0466 5.37388 14.9418 5.40865 14.8341 5.40865Z"
/>
</svg>
<img
v-else
:src="getIconUrl(formatMimeType(item.mime_type))"
:draggable="false"
class="h-[20px] mr-3"
/>
{{ item.title }}
</div>
</div>
<div class="border-t w-full mx-auto max-w-[95%]"></div>
</div>
</div>
<div
v-else
class="flex flex-col items-center justify-center h-[52vh]"
>
<Folder class="text-gray-600 h-10 w-auto" />
<span class="text-gray-600 text-base mt-2">Folder is Empty</span>
</div>
<div
v-if="breadcrumbs.length > 1"
class="flex items-center my-2"
:class="breadcrumbs.length > 1 ? 'visible' : 'invisible'"
>
<Dropdown
v-if="dropDownItems.length"
class="h-7"
:options="dropDownItems"
>
<Button variant="ghost">
<template #icon>
<svg
class="w-4 text-gray-600"
xmlns="http://www.w3.org/2000/svg"
width="24"
height="24"
viewBox="0 0 24 24"
fill="none"
stroke="currentColor"
stroke-width="2"
stroke-linecap="round"
stroke-linejoin="round"
>
<circle cx="12" cy="12" r="1" />
<circle cx="19" cy="12" r="1" />
<circle cx="5" cy="12" r="1" />
</svg>
</template>
</Button>
</Dropdown>
<span v-if="dropDownItems.length" class="text-gray-600 mx-0.5">
{{ "/" }}
</span>
<div v-for="(crumb, index) in lastTwoBreadCrumbs" :key="index">
<span
v-if="breadcrumbs.length > 1 && index > 0"
class="text-gray-600 mx-0.5"
>
{{ "/" }}
</span>
<button
class="text-base cursor-pointer"
:class="
breadcrumbs.length - 1 === index
? 'text-gray-900 text-base font-medium p-1'
: 'text-gray-600 text-base rounded-[6px] hover:bg-gray-100 p-1'
"
@click="closeEntity(crumb.name)"
>
{{ crumb.title }}
</button>
</div>
</div>
</Tabs>
<Button
variant="solid"
class="w-full"
:loading="move.loading"
:disabled="!evalPermission"
@click="
move.submit({
entity_names: store.state.entityInfo.map((obj) => obj.name),
new_parent: currentFolder,
})
"
>
<template #prefix>
<Move />
</template>
Move
</Button>
</div>
</template>
</Dialog>
</template>
<script setup>
import { watch, defineEmits, computed, h, ref } from "vue"
import { createResource, Dialog, Button, Tabs, Dropdown } from "frappe-ui"
import { formatSize, formatDate, formatMimeType } from "@/utils/format"
import { useStore } from "vuex"
import Home from "./EspressoIcons/Home.vue"
import Star from "./EspressoIcons/Star.vue"
import Users from "./EspressoIcons/Users.vue"
import Move from "./EspressoIcons/Move.vue"
import Folder from "./EspressoIcons/Folder.vue"
const store = useStore()
const currentFolder = ref(store.state.homeFolderID)
const emit = defineEmits(["update:modelValue", "success"])
const props = defineProps({
entity: {
type: Object,
required: false,
default: null,
},
})
const open = computed({
get() {
return props.modelValue
},
set(newValue) {
emit("update:modelValue", newValue)
},
})
const evalPermission = computed(() => {
if (currentFolder.value) {
if (
folderPermissions.data?.owner === currentUserEmail.value ||
folderPermissions.data?.write === 1
) {
return true
}
if (currentFolder.value === store.state.homeFolderID) {
return true
}
}
return false
})
const DialogTitle = computed(() => {
if (store.state.entityInfo.length > 1) {
return `Moving ${store.state.entityInfo.length} items`
} else {
return `Moving "${store.state.entityInfo[0].title}"`
}
})
const currentUserEmail = computed(() => {
return store.state.auth.user_id
})
const lastTwoBreadCrumbs = computed(() => {
if (breadcrumbs.value.length > 2) {
return breadcrumbs.value.slice(-2)
}
return breadcrumbs.value
})
const dropDownItems = computed(() => {
let allExceptLastTwo = breadcrumbs.value.slice(0, -2)
return allExceptLastTwo.map((item) => {
return {
...item,
icon: null,
label: item.title,
onClick: () => closeEntity(item.name),
}
})
})
const tabs = [
{
label: "Home",
icon: h(Home, { class: "w-4 h-4" }),
},
{
label: "Favourites",
icon: h(Star, { class: "w-4 h-4" }),
},
{
label: "Shared",
icon: h(Users, { class: "w-4 h-4" }),
},
]
const tabIndex = ref(0)
const folderContents = ref()
const breadcrumbs = ref([{ name: store.state.homeFolderID, title: "Home" }])
const folderPermissions = createResource({
url: "drive.api.permissions.get_entity_with_permissions",
params: {
entity_name: currentFolder.value,
},
auto: false,
})
watch(tabIndex, (newValue) => {
switch (newValue) {
case 0:
breadcrumbs.value = [{ name: store.state.homeFolderID, title: "Home" }]
currentFolder.value = store.state.homeFolderID
fetchFolderContents.fetch({
entity_name: currentFolder.value,
is_active: 1,
recents_only: false,
favourites_only: false,
file_kind_list: JSON.stringify(["Folder"]),
})
break
case 1:
breadcrumbs.value = [{ name: "", title: "Favourites" }]
currentFolder.value = null
fetchFolderContents.fetch({
entity_name: "",
is_active: 1,
recents_only: false,
favourites_only: true,
file_kind_list: JSON.stringify(["Folder"]),
})
break
case 2:
breadcrumbs.value = [{ name: "", title: "Shared" }]
currentFolder.value = null
sharedWithMe.fetch({
is_active: 1,
recents_only: false,
favourites_only: false,
file_kind_list: JSON.stringify(["Folder"]),
})
break
default:
breadcrumbs.value = []
folderContents.value = []
break
}
})
function openEntity(value) {
currentFolder.value = value.name
folderPermissions.fetch({
entity_name: value.name,
fields: "title,is_group,allow_comments,allow_download,owner",
})
breadcrumbs.value.push({ name: value.name, title: value.title })
fetchFolderContents.fetch({
entity_name: currentFolder.value,
is_active: 1,
recents_only: false,
favourites_only: false,
file_kind_list: JSON.stringify(["Folder"]),
})
}
function closeEntity(name) {
const index = breadcrumbs.value.findIndex((obj) => obj.name === name)
if (breadcrumbs.value.length > 1 && index !== breadcrumbs.value.length - 1) {
breadcrumbs.value = breadcrumbs.value.slice(0, index + 1)
currentFolder.value = breadcrumbs.value[breadcrumbs.value.length - 1].name
if (tabIndex.value === 2 && !currentFolder.value.length) {
sharedWithMe.fetch({
is_active: 1,
recents_only: false,
favourites_only: false,
file_kind_list: JSON.stringify(["Folder"]),
})
} else {
fetchFolderContents.fetch({
entity_name: currentFolder.value,
is_active: 1,
recents_only: false,
favourites_only: tabIndex.value === 1 ? true : false,
file_kind_list: JSON.stringify(["Folder"]),
})
}
}
}
const fetchFolderContents = createResource({
method: "GET",
url: "drive.api.list.files",
auto: true,
params: {
entity_name: currentFolder.value,
is_active: 1,
recents_only: false,
favourites_only: false,
file_kind_list: JSON.stringify(["Folder"]),
},
onSuccess(data) {
folderContents.value = []
folderContents.value = data
},
onError(error) {
if (error && error.exc_type === "PermissionError") {
this.$store.commit("setError", {
primaryMessage: "Forbidden",
secondaryMessage: "Insufficient permissions for this resource",
})
this.$router.replace({ name: "Error" })
}
},
})
let sharedWithMe = createResource({
url: "drive.api.list.shared_with_user",
method: "GET",
auto: false,
onSuccess(data) {
data.forEach((entity) => {
entity.size_in_bytes = entity.file_size
entity.file_size = entity.is_group
? entity.item_count + " items"
: formatSize(entity.file_size)
entity.modified = formatDate(entity.modified)
entity.creation = formatDate(entity.creation)
})
folderContents.value = data
},
onError(error) {
console.log(error)
},
})
const move = createResource({
url: "drive.api.files.move",
method: "POST",
auto: false,
onSuccess() {
emit(
"success",
store.state.entityInfo[0].name,
store.state.entityInfo[store.state.entityInfo.length - 1].name
)
},
})
</script>
|
2302_79757062/drive
|
frontend/src/components/MoveDialog.vue
|
Vue
|
agpl-3.0
| 11,345
|
<template>
<nav
ondragstart="return false;"
ondrop="return false;"
class="bg-white top-0 border-b min-w-full"
>
<div
class="mx-auto pl-4 py-2.5 pr-2 h-12 z-10 flex items-center justify-between"
>
<Breadcrumbs />
<div class="flex gap-1">
<div
v-if="connectedUsers.length > 1 && isLoggedIn"
class="hidden sm:flex bg-gray-200 rounded justify-center items-center px-1"
>
<UsersBar />
</div>
<Dropdown
v-if="$store.state.entityInfo"
:options="actionItems"
placement="right"
class="basis-5/12 lg:basis-auto"
>
<Button
v-if="
$route.meta.documentPage ||
$route.name === 'File' ||
$route.name === 'Folder'
"
variant="ghost"
@click="handleSelectedEntity"
>
<FeatherIcon class="h-4" name="more-horizontal" />
</Button>
</Dropdown>
<div v-if="isLoggedIn" class="block sm:flex">
<Button
v-if="$route.name === 'Document' || $route.name === 'File'"
:variant="'solid'"
:disabled="$store.state.entityInfo[0]?.owner !== 'You'"
class="bg-gray-200 rounded flex justify-center items-center px-1"
@click="emitter.emit('showShareDialog')"
>
<template #prefix>
<Share class="w-4" />
</template>
Share
</Button>
<Button
v-else-if="$route.name === 'Recents'"
class="line-clamp-1 truncate w-full"
:disabled="!currentViewEntites?.length"
theme="red"
:variant="'subtle'"
@click="emitter.emit('showCTADelete')"
>
<template #prefix>
<FeatherIcon name="trash-2" class="w-4" />
</template>
Clear Recents
</Button>
<Button
v-else-if="$route.name === 'Favourites'"
class="line-clamp-1 truncate"
:disabled="!currentViewEntites?.length"
theme="red"
:variant="'subtle'"
@click="emitter.emit('showCTADelete')"
>
<template #prefix>
<FeatherIcon name="trash-2" class="w-4" />
</template>
Clear Favourites
</Button>
<Button
v-else-if="$route.name === 'Trash'"
class="line-clamp-1 truncate"
:disabled="!currentViewEntites?.length"
theme="red"
:variant="'subtle'"
@click="emitter.emit('showCTADelete')"
>
<template #prefix>
<FeatherIcon name="trash-2" class="w-4" />
</template>
Empty Trash
</Button>
<Dropdown
v-else
:options="newEntityOptions"
placement="left"
class="basis-5/12 lg:basis-auto"
>
<Button variant="solid" :disabled="canUpload">
<template #prefix>
<FeatherIcon name="upload" class="w-4" />
</template>
New
<template #suffix>
<FeatherIcon name="chevron-down" class="w-4" />
</template>
</Button>
</Dropdown>
</div>
<div v-if="!isLoggedIn" class="ml-auto">
<Button variant="solid" @click="$router.push({ name: 'Login' })">
Sign In
</Button>
</div>
</div>
</div>
</nav>
<NewFolderDialog
v-model="showNewFolderDialog"
:parent="$route.params.entityName"
@success="
() => {
emitter.emit('fetchFolderContents')
showNewFolderDialog = false
}
"
/>
<RenameDialog
v-if="showRenameDialog"
v-model="showRenameDialog"
:parent="$route.params.entityName"
:entity="selectedEntities[0] ? selectedEntities[0] : currentFolder[0]"
@success="
() => {
showRenameDialog = false
}
"
/>
</template>
<script>
import UsersBar from "./UsersBar.vue"
import { Dropdown, FeatherIcon, Button } from "frappe-ui"
import NewFolderDialog from "@/components/NewFolderDialog.vue"
import RenameDialog from "@/components/RenameDialog.vue"
import Breadcrumbs from "@/components/Breadcrumbs.vue"
import { formatDate } from "@/utils/format"
import { getLink } from "@/utils/getLink"
import {
folderDownload,
selectedEntitiesDownload,
} from "@/utils/folderDownload"
import Share from "./EspressoIcons/Share.vue"
import Star from "./EspressoIcons/Star.vue"
import Rename from "./EspressoIcons/Rename.vue"
import Link from "./EspressoIcons/Link.vue"
import Download from "./EspressoIcons/Download.vue"
import NewFolder from "./EspressoIcons/NewFolder.vue"
import FileUpload from "./EspressoIcons/File-upload.vue"
import FolderUpload from "./EspressoIcons/Folder-upload.vue"
import NewFile from "./EspressoIcons/NewFile.vue"
import { capture } from "@/telemetry"
export default {
name: "Navbar",
components: {
RenameDialog,
NewFolderDialog,
Dropdown,
FeatherIcon,
Button,
Breadcrumbs,
UsersBar,
Share,
},
props: {
breadcrumbs: {
type: Array,
default: null,
},
mobileSidebarIsOpen: {
type: Boolean,
required: true,
},
},
emits: ["toggleMobileSidebar", "fetchRecents"],
data() {
return {
previewEntity: null,
showPreview: false,
showNewFolderDialog: false,
showRenameDialog: false,
newEntityOptions: [
{
group: "Upload",
items: [
{
label: "Upload File",
icon: FileUpload,
onClick: () => this.emitter.emit("uploadFile"),
},
{
label: "Upload Folder",
icon: FolderUpload,
onClick: () => this.emitter.emit("uploadFolder"),
isEnabled: () => this.selectedEntities.length === 0,
},
],
},
{
group: "New",
items: [
{
label: "New Folder",
icon: NewFolder,
onClick: () => (this.showNewFolderDialog = true),
},
{
label: "New Document",
icon: NewFile,
onClick: async () => {
await this.$resources.createDocument.submit({
title: "Untitled Document",
content: null,
parent: this.$store.state.currentFolderID,
})
capture("new_document_created")
if (this.$store.state.editorNewTab) {
window.open(
this.$router.resolve({
name: "Document",
params: { entityName: this.previewEntity.name },
}).href,
"_blank"
)
} else {
this.$router.push({
name: "Document",
params: { entityName: this.previewEntity.name },
})
}
},
isEnabled: () => this.selectedEntities?.length === 0,
},
],
},
],
}
},
computed: {
selectedEntities() {
if (this.$route.name === "Folder") {
return this.$store.state.currentFolder
}
return this.$store.state.entityInfo
},
actionItems() {
return [
{
label: "Download",
icon: Download,
onClick: () => {
window.location.href = `/api/method/drive.api.files.get_file_content?entity_name=${this.selectedEntities[0].name}&trigger_download=1`
},
isEnabled: () => {
if (this.selectedEntities?.length === 1) {
if (
this.selectedEntities?.length === 1 &&
!this.selectedEntities[0]?.is_group &&
!this.selectedEntities[0]?.document
) {
return (
this.selectedEntities[0]?.allow_download ||
this.selectedEntities[0]?.owner === "You"
)
}
}
},
},
{
label: "Download",
icon: Download,
onClick: () => {
if (this.selectedEntities.length > 1) {
let selected_entities = this.selectedEntities
selectedEntitiesDownload(selected_entities)
} else if (this.selectedEntities[0].is_group === 1) {
folderDownload(this.selectedEntities[0])
}
},
isEnabled: () => {
if (
this.selectedEntities?.length === 1 &&
!this.selectedEntities[0]?.is_group
) {
return false
}
if (this.selectedEntities?.length) {
const allEntitiesSatisfyCondition = this.selectedEntities?.every(
(entity) => {
return entity.allow_download || entity.owner === "You"
}
)
return allEntitiesSatisfyCondition
}
},
},
{
label: "Share",
icon: Share,
onClick: () => {
this.emitter.emit("showShareDialog")
},
isEnabled: () => {
return (
this.$route.name === "Folder" &&
this.$store.state.currentFolder[0]?.owner === "You"
)
},
},
{
label: "Get Link",
icon: Link,
onClick: () => {
getLink(this.selectedEntities[0])
},
isEnabled: () => {
return this.selectedEntities?.length === 1
},
},
{
label: "Rename",
icon: Rename,
onClick: () => {
this.showRenameDialog = true
},
isEnabled: () => {
return (
this.selectedEntities?.length === 1 &&
(this.selectedEntities[0]?.write ||
this.selectedEntities[0]?.owner === "You")
)
},
},
{
label: "Favourite",
icon: Star,
onClick: () => {
this.$resources.toggleFavourite.submit()
},
isEnabled: () => {
return (
this.selectedEntities?.length > 0 &&
this.isLoggedIn &&
this.selectedEntities?.every((x) => !x.is_favourite)
)
},
},
{
label: "Unfavourite",
icon: Star,
onClick: () => {
this.$resources.toggleFavourite.submit()
},
isEnabled: () => {
return (
this.selectedEntities?.length > 0 &&
this.selectedEntities?.every((x) => x.is_favourite)
)
},
},
].filter((item) => item.isEnabled())
},
fullName() {
return this.$store.state.user.fullName
},
imageURL() {
return this.$store.state.user.imageURL
},
isLoggedIn() {
return this.$store.getters.isLoggedIn
},
connectedUsers() {
return this.$store.state.connectedUsers
},
currentViewEntites() {
return this.$store.state.currentViewEntites
},
canUpload() {
if (
(this.$route.name === "Home" || this.$route.name === "Notifications") &&
this.$store.state.currentFolderID === this.$store.state.homeFolderID
) {
return false
}
if (
this.$store.state.currentFolder[0]?.owner === "You" ||
this.$store.state.currentFolder[0]?.write === 1
) {
return false
}
return true
},
},
methods: {
handleSelectedEntity() {
if (this.$route.name === "Folder") {
return this.$store.commit(
"setEntityInfo",
this.$store.state.currentFolder
)
}
},
},
resources: {
createDocument() {
return {
url: "drive.api.files.create_document_entity",
onSuccess(data) {
data.modified = formatDate(data.modified)
data.creation = formatDate(data.creation)
this.$store.commit("setEntityInfo", [data])
this.previewEntity = data
data.owner = "You"
},
onError(data) {
console.log(data)
},
auto: false,
}
},
toggleFavourite() {
return {
method: "POST",
auto: false,
url: "drive.api.files.add_or_remove_favourites",
params: {
entity_names: JSON.stringify(
this.selectedEntities?.map((entity) => entity.name)
),
},
onSuccess() {
this.$store.state.entityInfo[0].is_favourite =
!this.$store.state.entityInfo[0].is_favourite
},
}
},
},
}
</script>
|
2302_79757062/drive
|
frontend/src/components/Navbar.vue
|
Vue
|
agpl-3.0
| 13,046
|
<template>
<Dialog v-model="open" :options="{ title: 'New Folder', size: 'xs' }">
<template #body-content>
<Input
ref="input"
v-model="folderName"
placeholder="Untitled Folder"
type="text"
@keyup.enter="
(e) =>
$resources.createFolder.submit({
title: e.target.value.trim(),
parent,
})
"
/>
<ErrorMessage class="mt-2" :message="errorMessage" />
<div class="flex mt-8">
<Button
variant="solid"
class="w-full"
:loading="$resources.createFolder.loading"
@click="$resources.createFolder.submit()"
>
Create
</Button>
</div>
</template>
</Dialog>
</template>
<script>
import { ref } from "vue"
import { useFocus } from "@vueuse/core"
import { Dialog, Input, ErrorMessage } from "frappe-ui"
export default {
name: "NewFolderDialog",
components: {
Dialog,
Input,
ErrorMessage,
},
props: {
modelValue: {
type: Boolean,
required: true,
},
parent: {
type: String,
default: "",
},
},
emits: ["update:modelValue", "success"],
setup() {
const input = ref()
const { focused } = useFocus(input, { initialValue: true })
return {
input,
focused,
}
},
data() {
return {
folderName: "",
errorMessage: "",
}
},
computed: {
open: {
get() {
return this.modelValue
},
set(value) {
this.$emit("update:modelValue", value)
if (!value) {
this.folderName = ""
this.errorMessage = ""
}
},
},
},
resources: {
createFolder() {
return {
url: "drive.api.files.create_folder",
params: {
title: this.folderName,
parent: this.parent,
},
/* validate(params) {
if (!params?.title) {
return "Folder name is required";
}
}, */
onSuccess(data) {
this.folderName = ""
this.$emit("success", data)
},
onError(error) {
if (error.messages) {
this.errorMessage = error.messages.join("\n")
} else {
this.errorMessage = error.message
}
},
}
},
},
}
</script>
|
2302_79757062/drive
|
frontend/src/components/NewFolderDialog.vue
|
Vue
|
agpl-3.0
| 2,366
|
<template>
<div class="flex flex-col items-center justify-center">
<div v-if="icon">
<component :is="icon" class="w-14 stroke-[0] h-auto text-gray-500 pb-4" />
</div>
<svg
v-else
viewBox="0 0 78 85"
class="w-[8%] fill-transparent stroke-2 pb-6"
>
<path
d="M42 31H66 M42 51H66 M42 25H55 M42 45H55 M65 9V8C65 4.13401 61.866 1 58 1H8C4.13401 1 1 4.13401 1 8V66C1 69.866 4.13401 73 8 73H10 M70 12H20C16.134 12 13 15.134 13 19V77C13 80.866 16.134 84 20 84H70C73.866 84 77 80.866 77 77V19C77 15.134 73.866 12 70 12Z"
stroke="#454545"
/>
<path
d="M32 43H26C24.8954 43 24 43.8954 24 45V51C24 52.1046 24.8954 53 26 53H32C33.1046 53 34 52.1046 34 51V45C34 43.8954 33.1046 43 32 43Z M32 23H26C24.8954 23 24 23.8954 24 25V31C24 32.1046 24.8954 33 26 33H32C33.1046 33 34 32.1046 34 31V25C34 23.8954 33.1046 23 32 23Z"
stroke="#454545"
/>
</svg>
<p class="text-base text-gray-600 font-medium">{{ primaryMessage }}</p>
<p class="text-sm text-gray-600">{{ secondaryMessage }}</p>
</div>
</template>
<script>
export default {
name: "NoFilesSection",
props: {
icon: {
type: Object,
default: null,
},
primaryMessage: {
type: String,
default: "You don't have any files yet",
},
secondaryMessage: {
type: String,
default: "Drop files here",
},
},
}
</script>
|
2302_79757062/drive
|
frontend/src/components/NoFilesSection.vue
|
Vue
|
agpl-3.0
| 1,416
|
<template>
<div
ref="container"
class="h-full w-full pt-3.5 px-4 pb-5 overflow-y-auto"
@mousedown.prevent="
(event) => {
dragSelectStart(event)
}
"
@contextmenu="toggleEmptyContext"
>
<DriveToolBar
:action-items="actionItems"
:column-headers="showSort ? columnHeaders : null"
/>
<FolderContentsError
v-if="$resources.folderContents.error"
:error="$resources.folderContents.error"
/>
<NoFilesSection
v-else-if="folderItems && folderItems.length === 0"
class="absolute top-1/2 left-1/2 -translate-x-1/2 -translate-y-1/2"
:icon="icon"
:primary-message="primaryMessage"
:secondary-message="secondaryMessage"
/>
<GridView
v-else-if="folderItems && $store.state.view === 'grid'"
:folder-contents="
foldersBefore ? groupedByFolder : { 'All Files': folderItems }
"
:selected-entities="selectedEntities"
:override-can-load-more="overrideCanLoadMore"
@entity-selected="(selected) => (selectedEntities = selected)"
@open-entity="(entity) => openEntity(entity)"
@fetch-folder-contents="() => $resources.folderContents.fetch()"
@update-offset="fetchNextPage"
/>
<ListView
v-else-if="folderItems && $store.state.view === 'list'"
:folder-contents="
foldersBefore ? groupedByFolder : { 'All Files': folderItems }
"
:selected-entities="selectedEntities"
:override-can-load-more="overrideCanLoadMore"
@entity-selected="(selected) => (selectedEntities = selected)"
@open-entity="(entity) => openEntity(entity)"
@fetch-folder-contents="() => $resources.folderContents.fetch()"
@update-offset="fetchNextPage"
/>
<EntityContextMenu
v-if="showEntityContext"
v-on-outside-click="closeContextMenu"
:entity-name="selectedEntities[0].name"
:action-items="actionItems"
:entity-context="entityContext"
:close="closeContextMenu"
/>
<EmptyEntityContextMenu
v-if="showEmptyEntityContextMenu && allowEmptyContextMenu"
v-on-outside-click="closeContextMenu"
:action-items="emptyActionItems"
:entity-context="entityContext"
:close="closeContextMenu"
/>
<NewFolderDialog
v-if="showNewFolderDialog"
v-model="showNewFolderDialog"
:parent="$route.params.entityName"
@success="
(data) => {
// Will break if more folders exist than the pagelength
// Need to check the sort and see where the newly created folder fits
// And re-fetch that offset
handleListMutation()
showNewFolderDialog = false
}
"
/>
<RenameDialog
v-if="showRenameDialog"
v-model="showRenameDialog"
:entity="selectedEntities[0]"
@success="
(data) => {
handleListMutation(data.name)
showRenameDialog = false
selectedEntities = []
}
"
/>
<GeneralDialog
v-if="showRemoveDialog"
v-model="showRemoveDialog"
:entities="selectedEntities"
:for="'remove'"
@success="
() => {
handleListMutation()
showRemoveDialog = false
selectedEntities = []
}
"
/>
<GeneralDialog
v-model="showUnshareDialog"
:entities="selectedEntities"
:for="'unshare'"
@success="
() => {
handleListMutation()
showUnshareDialog = false
selectedEntities = []
}
"
/>
<GeneralDialog
v-model="showRestoreDialog"
:entities="selectedEntities"
:for="'restore'"
@success="
() => {
handleListMutation()
showRestoreDialog = false
selectedEntities = []
}
"
/>
<ShareDialog
v-if="showShareDialog"
v-model="showShareDialog"
:entity-name="$store.state.entityInfo[0].name"
/>
<MoveDialog
v-if="showMoveDialog"
v-model="showMoveDialog"
:entity-name="selectedEntities[0].name"
@success="
() => {
handleListMutation(selectedEntities[0].name)
showMoveDialog = false
selectedEntities = []
}
"
/>
<DeleteDialog
v-model="showDeleteDialog"
:entities="
selectedEntities.length > 0
? selectedEntities
: $resources.folderContents.data
"
@success="
() => {
offset = 0
folderItems = null
selectedEntities = []
fetchNextPage()
showDeleteDialog = false
}
"
/>
<CTADeleteDialog
v-model="showCTADelete"
:clear-all="clearAll"
@success="
() => {
offset = 0
folderItems = null
selectedEntities = []
fetchNextPage()
showCTADelete = false
}
"
/>
<div
id="selectionElement"
class="absolute border-1 bg-gray-300 border-gray-400 opacity-50 mix-blend-multiply rounded"
:style="selectionElementStyle"
:hidden="!selectionCoordinates.x1"
/>
</div>
</template>
<script>
import ListView from "@/components/ListView.vue"
import GridView from "@/components/GridView.vue"
import DriveToolBar from "@/components/DriveToolBar.vue"
import NoFilesSection from "@/components/NoFilesSection.vue"
import NewFolderDialog from "@/components/NewFolderDialog.vue"
import RenameDialog from "@/components/RenameDialog.vue"
import ShareDialog from "@/components/ShareDialog/ShareDialog.vue"
import GeneralDialog from "@/components/GeneralDialog.vue"
import DeleteDialog from "@/components/DeleteDialog.vue"
import CTADeleteDialog from "@/components/CTADeleteDialog.vue"
import MoveDialog from "../components/MoveDialog.vue"
import FolderContentsError from "@/components/FolderContentsError.vue"
import EntityContextMenu from "@/components/EntityContextMenu.vue"
import EmptyEntityContextMenu from "@/components/EmptyEntityContextMenu.vue"
import { formatSize, formatDate } from "@/utils/format"
import { getLink } from "@/utils/getLink"
import { useTimeAgo } from "@vueuse/core"
import {
folderDownload,
selectedEntitiesDownload,
} from "@/utils/folderDownload"
import { RotateCcw, X } from "lucide-vue-next"
import NewFolder from "./EspressoIcons/NewFolder.vue"
import FileUpload from "./EspressoIcons/File-upload.vue"
import FolderUpload from "./EspressoIcons/Folder-upload.vue"
import Share from "./EspressoIcons/Share.vue"
import Download from "./EspressoIcons/Download.vue"
import Link from "./EspressoIcons/Link.vue"
import Rename from "./EspressoIcons/Rename.vue"
import Move from "./EspressoIcons/Move.vue"
import Info from "./EspressoIcons/Info.vue"
import Star from "./EspressoIcons/Star.vue"
import Preview from "./EspressoIcons/Preview.vue"
import Trash from "./EspressoIcons/Trash.vue"
import NewFile from "./EspressoIcons/NewFile.vue"
import { toast } from "../utils/toasts.js"
import { capture } from "@/telemetry"
import { calculateRectangle, handleDragSelect } from "@/utils/dragSelect"
export default {
name: "PageGeneric",
components: {
ListView,
GridView,
DriveToolBar,
NoFilesSection,
NewFolderDialog,
RenameDialog,
MoveDialog,
DeleteDialog,
ShareDialog,
GeneralDialog,
FolderContentsError,
EntityContextMenu,
EmptyEntityContextMenu,
CTADeleteDialog,
},
props: {
url: {
type: String,
default: "",
required: false,
},
parent: {
type: String,
default: null,
required: false,
},
allowEmptyContextMenu: {
type: Boolean,
default: false,
required: false,
},
isSharedFolder: {
type: Boolean,
default: false,
required: false,
},
isActive: {
type: Number,
default: 1,
required: false,
},
showSort: {
type: Boolean,
default: false,
required: false,
},
entityName: {
type: String,
required: false,
default: "",
},
icon: {
type: Object,
default: null,
},
primaryMessage: {
type: String,
required: false,
default: "No Files here",
},
secondaryMessage: {
type: String,
required: false,
default: "Add files",
},
recents: {
type: Boolean,
required: false,
default: false,
},
favourites: {
type: Boolean,
required: false,
default: false,
},
},
data: () => ({
folderItems: null,
previewEntity: null,
showPreview: false,
showNewFolderDialog: false,
showRenameDialog: false,
showShareDialog: false,
showRemoveDialog: false,
showDeleteDialog: false,
showUnshareDialog: false,
showRestoreDialog: false,
showMoveDialog: false,
showEntityContext: false,
showEmptyEntityContextMenu: false,
entityContext: {},
pageLength: 60,
pageOffset: 0,
overrideCanLoadMore: false,
clearAll: false,
showCTADelete: false,
selectionElementStyle: {},
selectionCoordinates: { x1: 0, x2: 0, y1: 0, y2: 0 },
containerRect: null,
selectedIDs: null,
}),
computed: {
groupedByFolder() {
const output = {}
if (this.recents && this.folderItems) {
return this.groupByAccessed(this.folderItems)
}
if (this.folderItems) {
const folders = this.folderItems.filter((x) => x.is_group === 1)
const files = this.folderItems.filter((x) => x.is_group === 0)
if (folders.length > 0) {
output.Folders = folders
}
if (files.length > 0) {
output.Files = files
}
}
return output
},
selectedEntities: {
get() {
return this.$store.state.entityInfo
},
set(val) {
this.$store.commit("setEntityInfo", val)
},
},
filters() {
return this.$store.state.activeFilters
},
orderBy() {
return this.$store.state.sortOrder.ascending
? this.$store.state.sortOrder.field
: `${this.$store.state.sortOrder.field} desc`
},
userId() {
return this.$store.state.auth.user_id
},
columnHeaders() {
return [
{
label: "Name",
field: "title",
sortable: true,
},
{
label: "Owner",
field: "owner",
sortable: true,
},
{
label: "Modified",
field: "modified",
sortable: true,
},
{
label: "Size",
field: "file_size",
sortable: true,
},
{
label: "Type",
field: "mime_type",
sortable: true,
},
].filter((item) => item.sortable)
},
emptyActionItems() {
return [
{
label: "Upload File",
icon: FileUpload,
handler: () => this.emitter.emit("uploadFile"),
isEnabled: () => this.selectedEntities.length === 0,
},
{
label: "Upload Folder",
icon: FolderUpload,
handler: () => this.emitter.emit("uploadFolder"),
isEnabled: () => this.selectedEntities.length === 0,
},
{
label: "New Folder",
icon: NewFolder,
handler: () => (this.showNewFolderDialog = true),
isEnabled: () => this.selectedEntities.length === 0,
},
{
label: "New Document",
icon: NewFile,
handler: () => this.newDocument(),
isEnabled: () => this.selectedEntities.length === 0,
},
/*{
label: "Paste",
icon: "clipboard",
handler: async () => {
this.pasteEntities()
},
isEnabled: () => this.$store.state.pasteData.entities.length,
},*/
].filter((item) => item.isEnabled())
},
actionItems() {
if (this.$route.name === "Trash") {
return [
{
label: "Restore",
icon: RotateCcw,
onClick: () => {
this.showRestoreDialog = true
},
isEnabled: () => {
return this.selectedEntities.length > 0
},
},
{
label: "Delete forever",
icon: Trash,
danger: true,
onClick: () => {
this.showDeleteDialog = true
},
isEnabled: () => {
if (this.$route.name === "Trash") {
return this.selectedEntities.length > 0
}
},
},
].filter((item) => item.isEnabled())
} else {
return [
{
label: "Preview",
icon: Preview,
onClick: () => {
console.log(this.selectedEntities[0].is_group)
this.openEntity(this.selectedEntities[0])
},
isEnabled: () => {
if (this.selectedEntities.length === 1) {
return true
}
},
},
{
label: "Download",
icon: Download,
onClick: () => {
window.location.href = `/api/method/drive.api.files.get_file_content?entity_name=${this.selectedEntities[0].name}&trigger_download=1`
},
isEnabled: () => {
if (this.selectedEntities.length === 1) {
if (
this.selectedEntities.length === 1 &&
!this.selectedEntities[0].is_group &&
!this.selectedEntities[0].document
) {
return (
this.selectedEntities[0].allow_download ||
this.selectedEntities[0].owner === "You"
)
}
}
},
},
/* Folder Download */
{
label: "Download",
icon: Download,
onClick: () => {
if (this.selectedEntities.length > 1) {
let selected_entities = this.selectedEntities
selectedEntitiesDownload(selected_entities)
} else if (this.selectedEntities[0].is_group === 1) {
folderDownload(this.selectedEntities[0])
}
},
isEnabled: () => {
if (
this.selectedEntities.length === 1 &&
!this.selectedEntities[0].is_group
) {
return false
}
if (this.selectedEntities.length) {
const allEntitiesSatisfyCondition = this.selectedEntities.every(
(entity) => {
return entity.allow_download || entity.owner === "You"
}
)
return allEntitiesSatisfyCondition
}
},
},
{
label: "Share",
icon: Share,
onClick: () => {
this.showShareDialog = true
},
isEnabled: () => {
return (
this.selectedEntities.length === 1 &&
this.selectedEntities[0].owner === "You"
)
},
},
{
label: "Get Link",
icon: Link,
onClick: () => {
getLink(this.selectedEntities[0])
},
isEnabled: () => {
return this.selectedEntities.length === 1
},
},
{
label: "Rename",
icon: Rename,
onClick: () => {
this.showRenameDialog = true
},
isEnabled: () => {
return (
this.selectedEntities.length === 1 &&
(this.selectedEntities[0].write ||
this.selectedEntities[0].owner === "You")
)
},
},
{
label: "Move",
icon: Move,
onClick: () => {
this.showMoveDialog = true
},
isEnabled: () => {
const allOwned = this.selectedEntities.every((entity) => {
return entity.owner === "You"
})
return this.selectedEntities.length > 0 && allOwned
},
},
/* {
label: "Duplicate",
icon: Copy,
onClick: () => {
this.$store.commit("setPasteData", {
entities: this.selectedEntities.map((x) => x.name),
action: "copy",
})
},
isEnabled: () => {
return (
this.selectedEntities.length > 0 &&
(this.selectedEntities[0].write ||
this.selectedEntities[0].owner === "You")
)
},
}, */
{
label: "Show Info",
icon: Info,
onClick: () => {
this.$store.commit("setShowInfo", true)
},
isEnabled: () => {
return (
!this.$store.state.showInfo &&
this.selectedEntities.length === 1
)
},
},
{
label: "Hide Info",
icon: Info,
onClick: () => {
this.$store.commit("setShowInfo", false)
},
isEnabled: () => {
return (
this.$store.state.showInfo && this.selectedEntities.length === 1
)
},
},
/*{
label: "Paste",
icon: "clipboard",
onClick: async () => {
this.pasteEntities(this.selectedEntities[0].name)
},
isEnabled: () => {
return (
this.$store.state.pasteData.entities.length &&
this.selectedEntities.length === 1 &&
this.selectedEntities[0].is_group
)
},
},*/
{
label: "Favourite",
icon: Star,
onClick: () => {
this.$resources.toggleFavourite.submit()
},
isEnabled: () => {
return (
this.selectedEntities.length > 0 &&
this.selectedEntities.every((x) => !x.is_favourite)
)
},
},
{
label: "Unfavourite",
icon: Star,
onClick: () => {
this.$resources.toggleFavourite.submit()
},
isEnabled: () => {
return (
this.selectedEntities.length > 0 &&
this.selectedEntities.every((x) => x.is_favourite)
)
},
},
{
label: "Color",
isEnabled: () => {
return (
this.selectedEntities.length === 1 &&
this.selectedEntities[0].is_group &&
(this.selectedEntities[0].write === 1 ||
this.selectedEntities[0].owner === "You")
)
},
},
{
label: "Remove from Recents",
icon: Trash,
danger: true,
onClick: () => {
this.$resources.clearRecent.submit()
},
isEnabled: () => {
if (this.$route.name === "Recents") {
return this.selectedEntities.length > 0
}
},
},
{
label: "Unshare",
danger: true,
icon: "trash-2",
onClick: () => {
this.showUnshareDialog = true
},
isEnabled: () => {
if (this.selectedEntities.length) {
return (
this.selectedEntities.every(
(x) =>
x.owner != "You" &&
x.user_doctype === "User" &&
x.everyone !== 1
) && !this.isSharedFolder
)
}
},
},
{
label: "Move to Trash",
icon: Trash,
danger: true,
onClick: () => {
this.showRemoveDialog = true
},
isEnabled: () => {
const allOwned = this.selectedEntities.every((entity) => {
return entity.owner === "You"
})
return this.selectedEntities.length > 0 && allOwned
},
},
].filter((item) => item.isEnabled())
}
},
foldersBefore() {
return this.$store.state.foldersBefore
},
},
watch: {
filters: {
handler() {
this.pageOffset = 0
this.resetAndFetch()
},
deep: true,
},
folderItems: {
handler(newVal) {
this.$store.commit("setCurrentViewEntites", newVal)
},
},
orderBy: {
handler() {
this.pageOffset = 0
this.resetAndFetch()
},
},
},
mounted() {
this.fetchNextPage()
this.emitter.on("fetchFolderContents", () => {
this.handleListMutation()
})
this.emitter.on("showCTADelete", () => {
this.clearAll = true
this.showCTADelete = true
})
this.emitter.on("showShareDialog", () => {
this.showShareDialog = true
})
this.emitter.on("selectAll", () => {
this.clearAll()
})
this.emitter.on("createNewDocument", () => {
this.newDocument()
})
this.pasteListener = (e) => {
if (
(e.ctrlKey || e.metaKey) &&
(e.key === "v" || e.key === "V") &&
this.$store.state.pasteData.entities.length
)
this.pasteEntities()
}
window.addEventListener("keydown", this.pasteListener)
this.deleteListener = (e) => {
if (e.key === "Delete" && this.selectedEntities.length)
this.showRemoveDialog = true
}
window.addEventListener("keydown", this.deleteListener)
window.addEventListener(
"dragover",
function (e) {
e = e || event
e.preventDefault()
},
false
)
window.addEventListener(
"drop",
function (e) {
e = e || event
e.preventDefault()
},
false
)
this.$store.commit("setHasWriteAccess", true)
window.addEventListener("scroll", this.onScroll)
if (this.isEmpty) return
this.updateContainerRect()
visualViewport.addEventListener("resize", this.updateContainerRect)
},
unmounted() {
this.folderItems = []
this.pageOffset = 0
this.emitter.off("fetchFolderContents")
this.$store.commit("setHasWriteAccess", false)
window.removeEventListener("keydown", this.pasteListener)
window.removeEventListener("keydown", this.deleteListener)
window.removeEventListener("scroll", this.onScroll)
document.removeEventListener("keydown", this.selectAllListener)
document.removeEventListener("keydown", this.copyListener)
document.removeEventListener("keydown", this.cutListener)
},
methods: {
dragSelectStart(event) {
if (this.showEntityContext) return
this.selectedIDs = null
this.selectedEntities = []
document.addEventListener("mousemove", this.dragSelectMove)
document.addEventListener("mouseup", this.dragSelectStop)
this.selectionCoordinates.x1 = event.clientX
this.selectionCoordinates.y1 = event.clientY
this.selectionCoordinates.x2 = event.clientX
this.selectionCoordinates.y2 = event.clientY
this.selectionElementStyle = calculateRectangle(this.selectionCoordinates)
},
dragSelectMove(event) {
if (this.isEmpty) return
if (event.which != 1 || !this.selectionCoordinates.x1) return
this.selectionCoordinates.x2 = Math.max(
this.containerRect.left,
Math.min(this.containerRect.right, event.clientX)
)
this.selectionCoordinates.y2 = Math.max(
this.containerRect.top,
Math.min(this.containerRect.bottom, event.clientY)
)
this.selectionElementStyle = calculateRectangle(this.selectionCoordinates)
const entityElements = this.$el.querySelectorAll(".entity")
const selectedEntities = handleDragSelect(
entityElements,
this.selectionCoordinates,
this.folderContents
)
this.selectedIDs = selectedEntities
},
dragSelectStop() {
if (this.selectedIDs) {
this.selectedEntities = this.folderItems.filter((item) =>
this.selectedIDs.has(item.name)
)
}
this.selectionCoordinates = { x1: 0, x2: 0, y1: 0, y2: 0 }
document.removeEventListener("mousemove", this.dragSelectMove)
document.removeEventListener("mouseup", this.dragSelectStop)
},
updateContainerRect() {
this.containerRect = this.$refs["container"]?.getBoundingClientRect()
},
onScroll() {
const position = window.pageYOffset
this.$store.dispatch("saveScrollPosition", {
route: this.$route.fullPath,
position,
})
},
fetchNextPage() {
this.pageOffset = this.pageOffset + this.pageLength
this.$resources.folderContents.fetch().then((data) => {
this.overrideCanLoadMore = data.length < 60 ? false : true
this.folderItems = this.folderItems
? this.folderItems.concat(data)
: data
})
},
resetAndFetch() {
this.folderItems = null
this.$resources.folderContents
.fetch({
entity_name: this.entityName,
order_by: this.orderBy,
offset: 0,
limit: this.pageLength,
is_active: this.isActive,
folders_first: this.foldersBefore,
recents_only: this.recents,
favourites_only: this.favourites,
file_kind_list: JSON.stringify(this.filters),
})
.then((data) => {
this.pageOffset = data.length
this.folderItems = data
this.overrideCanLoadMore = data.length < 60 ? false : true
})
},
handleListMutation(entityID) {
let index = this.folderItems.findIndex((obj) => obj.name === entityID)
let entityPage = Math.ceil(index / this.pageLength)
let entityOriginalOffset = Math.max(
0,
entityPage * this.pageLength - this.pageLength
)
let endIndex = this.folderItems.findIndex(
(obj) =>
obj.name ===
this.$store.state.entityInfo[this.$store.state.entityInfo.length - 1]
)
let endPage = Math.ceil(endIndex / this.pageLength)
let endtityOgOffset = Math.max(
0,
endPage * this.pageLength - this.pageLength
)
let totalPages = endtityOgOffset - 0
this.$resources.folderContents
.fetch({
entity_name: this.entityName,
order_by: this.orderBy,
offset: entityOriginalOffset,
limit: this.pageLength,
folders_first: this.foldersBefore,
is_active: this.isActive,
recents_only: this.recents,
favourites_only: this.favourites,
file_kind_list: JSON.stringify(this.filters),
})
.then((data) => {
this.folderItems.splice(
entityOriginalOffset,
entityOriginalOffset + this.pageLength,
...data
)
})
},
openEntity(entity) {
if (this.$route.name === "Trash") {
return
}
if (entity.is_group) {
this.selectedEntities = []
this.$router.push({
name: "Folder",
params: { entityName: entity.name },
})
} else if (entity.document) {
if (this.$store.state.editorNewTab) {
window.open(
this.$router.resolve({
name: "Document",
params: { entityName: entity.name },
}).href,
"_blank"
)
} else {
this.$router.push({
name: "Document",
params: { entityName: entity.name },
})
}
} else {
this.$router.push({
name: "File",
params: { entityName: entity.name },
})
this.previewEntity = entity
this.showPreview = true
}
},
async pasteEntities(newParent = this.$store.state.currentFolderID) {
const method =
this.$store.state.pasteData.action === "cut" ? "move" : "copy"
for (let i = 0; i < this.$store.state.pasteData.entities.length; i++) {
await this.$resources.pasteEntity.submit({
method,
entity_name: this.$store.state.pasteData.entities[i],
new_parent: newParent,
})
}
this.selectedEntities = []
this.$store.commit("setPasteData", { entities: [], action: null })
this.$resources.folderContents.fetch()
},
toggleEntityContext(event) {
if (!event) this.showEntityContext = false
else {
this.showEntityContext = true
this.showEmptyEntityContextMenu = false
this.entityContext = event
}
},
toggleEmptyContext(event) {
if (!event) {
this.showEntityContext = false
this.showEmptyEntityContextMenu = false
} else if (this.selectedEntities.length === 0) {
this.selectedEntities = []
this.showEntityContext = false
this.showEmptyEntityContextMenu = true
this.entityContext = event
} else if (this.selectedEntities.length > 0) {
this.showEntityContext = true
this.showEmptyEntityContextMenu = false
this.entityContext = event
}
},
closeContextMenu() {
this.showEntityContext = false
this.showEmptyEntityContextMenu = false
this.entityContext = undefined
},
async newDocument() {
await this.$resources.createDocument.submit({
title: "Untitled Document",
content: null,
parent: this.$store.state.currentFolderID,
})
capture("new_document_created")
if (this.$store.state.editorNewTab) {
window.open(
this.$router.resolve({
name: "Document",
params: { entityName: this.previewEntity.name },
}).href,
"_blank"
)
} else {
this.$router.push({
name: "Document",
params: { entityName: this.previewEntity.name },
})
}
},
groupByAccessed(entities) {
const today = new Date()
const grouped = {
Today: [],
"Earlier this week": [],
"Earlier this month": [],
"Earlier this year": [],
"Older than a year": [],
}
entities.forEach((file) => {
const modifiedDate = new Date(file.modified)
const yearDiff = today.getFullYear() - modifiedDate.getFullYear()
const monthDiff =
today.getMonth() - modifiedDate.getMonth() + yearDiff * 12 // Adjust for year difference
const dayDiff = Math.floor(
(today - modifiedDate) / (1000 * 60 * 60 * 24)
)
if (dayDiff === 0) {
grouped["Today"].push(file)
} else if (dayDiff <= 7) {
grouped["Earlier this week"].push(file)
} else if (monthDiff === 0) {
grouped["Earlier this month"].push(file)
} else if (yearDiff === 0) {
grouped["Earlier this year"].push(file)
} else {
grouped["Older than a year"].push(file)
}
})
return grouped
},
},
resources: {
pasteEntity() {
return {
url: "drive.api.files.call_controller_method",
method: "POST",
auto: false,
}
},
folderContents() {
return {
method: "GET",
url: this.url,
auto: false,
params: {
entity_name: this.entityName,
order_by: this.orderBy,
offset: this.pageOffset,
limit: this.pageLength,
folders_first: this.foldersBefore,
is_active: this.isActive,
recents_only: this.recents,
favourites_only: this.favourites,
file_kind_list: JSON.stringify(this.filters),
},
transform(data) {
this.$resources.folderContents.error = null
data.forEach((entity) => {
entity.size_in_bytes = entity.file_size
if (entity.is_group) {
if (entity.item_count === 0 || entity.item_count > 0) {
entity.file_size = entity.item_count + " item"
if (entity.item_count > 1) {
entity.file_size = entity.item_count + " items"
}
} else {
entity.file_size = ""
}
} else {
entity.file_size = formatSize(entity.file_size)
}
entity.relativeModified = useTimeAgo(entity.modified)
entity.modified = formatDate(entity.modified)
entity.creation = formatDate(entity.creation)
entity.owner =
entity.owner === this.userId ? "You" : entity.full_name
})
},
onError(error) {
if (error && error.exc_type === "PermissionError") {
this.$store.commit("setError", {
primaryMessage: "Forbidden",
secondaryMessage: "Insufficient permissions for this resource",
})
this.$router.replace({ name: "Error" })
}
},
}
},
toggleFavourite() {
return {
method: "POST",
auto: false,
url: "drive.api.files.add_or_remove_favourites",
params: {
entity_names: JSON.stringify(
this.selectedEntities?.map((entity) => entity.name)
),
},
onSuccess() {
// Toggled OFF
if (this.selectedEntities[0].is_favourite) {
toast({
title: `${this.selectedEntities.length} ${
this.selectedEntities.length > 1 ? " items" : " item"
} removed from Favourites`,
position: "bottom-right",
timeout: 2,
})
} else {
toast({
title: `${this.selectedEntities.length} ${
this.selectedEntities.length > 1 ? " items" : " item"
} added to Favourites`,
position: "bottom-right",
timeout: 2,
})
}
this.handleListMutation(this.selectedEntities[0].name)
this.selectedEntities = []
},
}
},
clearRecent() {
return {
method: "POST",
auto: false,
url: "drive.api.files.remove_recents",
params: {
entity_names: JSON.stringify(
this.selectedEntities?.map((entity) => entity.name)
),
},
onSuccess() {
toast({
title: `Cleared ${this.selectedEntities.length} ${
this.selectedEntities.length > 1 ? " items" : " item"
} from Recents`,
position: "bottom-right",
timeout: 2,
})
this.handleListMutation(this.selectedEntities[0].name)
this.selectedEntities = []
},
onError(error) {
if (error.messages) {
console.log(error.messages)
}
},
}
},
createDocument() {
return {
method: "POST",
url: "drive.api.files.create_document_entity",
onSuccess(data) {
data.modified = formatDate(data.modified)
data.creation = formatDate(data.creation)
this.$store.commit("setEntityInfo", [data])
this.previewEntity = data
data.owner = "You"
},
onError(error) {
console.log(error.messages)
},
auto: false,
}
},
},
}
</script>
<style>
html {
-webkit-user-select: none;
-ms-user-select: none;
user-select: none;
}
</style>
|
2302_79757062/drive
|
frontend/src/components/PageGeneric.vue
|
Vue
|
agpl-3.0
| 36,063
|
<template>
<Dropdown :options="settingsItems">
<template #default="{ open }">
<button
class="flex items-center justify-start rounded-md text-left transition-all duration-300 ease-in-out"
:class="[
isExpanded ? 'p-2' : 'py-2',
open && isExpanded
? 'bg-white shadow-sm'
: isExpanded
? 'hover:bg-gray-200'
: 'bg-transparent hover:bg-transparent shadow-none',
//open && isExpanded ? 'hover:bg-transparent' : 'bg-transparent hover:bg-transparent',
]"
:style="{
width: isExpanded ? '204px' : 'auto',
}"
>
<FrappeDriveLogo class="w-8 h-8 rounded" />
<div
class="flex flex-1 flex-col text-left duration-300 ease-in-out"
:class="isExpanded ? 'ml-2 w-auto opacity-100' : 'ml-0 w-0 opacity-0'"
>
<div class="text-base font-medium leading-none text-gray-900">
Drive
</div>
<div
class="line-clamp-1 overflow-hidden mt-1 text-sm leading-none text-gray-700"
>
{{ fullName }}
</div>
</div>
<div
class="duration-300 ease-in-out"
:class="
isExpanded
? 'mr-auto w-auto opacity-100'
: 'ml-0 w-0 overflow-hidden opacity-0'
"
>
<FeatherIcon
:name="open ? 'chevron-up' : 'chevron-down'"
class="h-5 w-5 sm:inline text-gray-700"
/>
</div>
</button>
</template>
</Dropdown>
<SettingsDialog
v-if="showSettings"
v-model="showSettings"
:suggested-tab="suggestedTab"
/>
</template>
<script>
import { markRaw } from "vue"
import { Dropdown, FeatherIcon } from "frappe-ui"
import SettingsDialog from "@/components/Settings/SettingsDialog.vue"
import FrappeDriveLogo from "@/components/FrappeDriveLogo.vue"
import Docs from "@/components/EspressoIcons/Docs.vue"
import AppSwitcher from "@/components/AppSwitcher.vue"
export default {
name: "PrimaryDropdown",
components: {
Dropdown,
FeatherIcon,
SettingsDialog,
FrappeDriveLogo,
AppSwitcher,
},
props: {
isExpanded: Boolean,
},
data: () => ({
showSettings: false,
suggestedTab: 0,
}),
computed: {
firstName() {
return this.$store.state.user.fullName.split(" ")
},
fullName() {
return this.$store.state.user.fullName
},
userEmail() {
return this.$store.state.auth.user_id
},
settingsItems() {
return [
{
group: "Manage",
hideLabel: true,
items: [
{
component: markRaw(AppSwitcher),
},
{
icon: Docs,
label: "Documentation",
onClick: () =>
window.open("https://docs.frappe.io/drive", "_blank"),
},
{
icon: "life-buoy",
label: "Support",
onClick: () => window.open("https://t.me/frappedrive", "_blank"),
},
],
},
{
group: "Others",
hideLabel: true,
items: [
{
icon: "settings",
label: "Settings",
onClick: () => (this.showSettings = true),
},
{
icon: "log-out",
label: "Log out",
onClick: () => this.logout(),
},
],
},
]
},
},
mounted() {
this.emitter.on("showSettings", (val) => {
this.showSettings = true
this.suggestedTab = val
})
},
methods: {
logout() {
this.$store.dispatch("logout")
this.$router.redirect("/")
},
},
}
</script>
|
2302_79757062/drive
|
frontend/src/components/PrimaryDropdown.vue
|
Vue
|
agpl-3.0
| 3,789
|
<template>
<svg :height="radius * 2" :width="radius * 2">
<circle
class="fill-transparent stroke-current"
:class="secondaryClass"
:cx="radius"
:cy="radius"
:r="normalizedRadius"
:stroke-width="stroke"
:stroke-dasharray="circumference"
/>
<circle
class="fill-transparent stroke-current origin-center -rotate-90 transition-all"
:class="primaryClass"
:cx="radius"
:cy="radius"
:r="normalizedRadius"
:stroke-width="stroke"
:stroke-dasharray="circumference"
:stroke-dashoffset="strokeDashoffset"
/>
</svg>
</template>
<script>
export default {
name: "ProgressRing",
props: {
progress: {
type: Number,
required: true,
},
radius: {
type: Number,
default: 24,
},
stroke: {
type: Number,
default: 4,
},
primaryClass: {
type: String,
default: "text-black",
},
secondaryClass: {
type: String,
default: "text-gray-200",
},
},
computed: {
normalizedRadius() {
return this.radius - this.stroke
},
circumference() {
return this.normalizedRadius * 2 * Math.PI
},
strokeDashoffset() {
return this.circumference - (this.progress / 100) * this.circumference
},
},
}
</script>
|
2302_79757062/drive
|
frontend/src/components/ProgressRing.vue
|
Vue
|
agpl-3.0
| 1,319
|
<template>
<Dialog v-model="open" :options="{ title: 'Rename', size: 'xs' }">
<template #body-content>
<div class="flex items-center justify-center">
<Input
ref="input"
v-model="newName"
class="w-full"
type="text"
@keyup.enter="$resources.rename.submit"
/>
<span
v-if="entity.file_ext"
:variant="'subtle'"
theme="gray"
size="sm"
class="form-input font-medium ml-2 text-gray-700 border-gray-100"
>
{{ entity.file_ext.toUpperCase().slice(1) }}
</span>
</div>
<ErrorMessage class="mt-2" :message="errorMessage" />
<div class="flex mt-8">
<Button
variant="solid"
class="w-full"
:loading="$resources.rename.loading"
@click="$resources.rename.submit"
>
Rename
</Button>
</div>
</template>
</Dialog>
</template>
<script>
import { ref } from "vue"
import { Dialog, Input, ErrorMessage, Badge } from "frappe-ui"
import { useFocus } from "@vueuse/core"
import { useRoute } from "vue-router"
import { useStore } from "vuex"
import { toast } from "../utils/toasts.js"
export default {
name: "RenameDialog",
components: {
Dialog,
Input,
ErrorMessage,
Badge,
},
props: {
modelValue: {
type: Boolean,
required: true,
},
entity: {
type: Object,
required: false,
default: null,
},
},
emits: ["update:modelValue", "success"],
setup(props) {
const newName = ref("")
const route = useRoute()
const store = useStore()
let parsedName = ""
if (props.entity?.is_group || props.entity?.document) {
newName.value = props.entity.title
if (route.meta.documentPage) {
store.state.entityInfo[0].title = newName.value
}
} else {
parsedName = props.entity?.title.split(".").slice(0, -1).join(".")
}
newName.value = parsedName?.length > 1 ? parsedName : props.entity?.title
const input = ref()
const { focused } = useFocus(input, { initialValue: true })
return {
input,
focused,
newName,
}
},
data() {
return {
errorMessage: "",
extension: "",
}
},
computed: {
entityName() {
return this.entity?.name
},
fullName() {
let trimmed_name = this.newName.trim()
if (this.entity?.file_ext) {
return trimmed_name + this.entity.file_ext
} else {
return trimmed_name
}
},
open: {
get() {
return this.modelValue
},
set(value) {
this.$emit("update:modelValue", value)
if (!value) {
this.newName = ""
this.errorMessage = ""
}
},
},
},
resources: {
rename() {
return {
url: "drive.api.files.call_controller_method",
method: "POST",
params: {
method: "rename",
entity_name: this.entityName,
new_title: this.fullName,
},
onSuccess(data) {
toast({
title: `Renamed ${this.$store.state.entityInfo[0].title} to ${this.newName}`,
position: "bottom-right",
timeout: 2,
})
this.$store.state.entityInfo[0].title = data.title
this.$store.state.passiveRename = false
this.$emit("success", data)
this.newName = ""
this.extension = ""
this.errorMessage = ""
},
onError(error) {
if (error.messages) {
this.errorMessage = error.messages.join("\n")
} else {
this.errorMessage = error.message
}
},
}
},
},
}
</script>
|
2302_79757062/drive
|
frontend/src/components/RenameDialog.vue
|
Vue
|
agpl-3.0
| 3,759
|
<template>
<Dialog v-model="open" :options="{ title: roleName, size: 'lg' }">
<template #body-content>
<label class="block text-base text-gray-600 my-2">Add User</label>
<UserSearch
:button-variant="'solid'"
:search-groups="false"
:active-users="uniqueUsers"
:active-groups="[]"
@add-new-users="(data) => addUser(data.users)"
/>
<label
v-if="UsersInRole.length"
class="block text-base text-gray-600 mt-6 mb-2"
>
Users in this Group
</label>
<div
v-for="(user, index) in uniqueUsers"
:key="user.user_name"
class="flex flex-row w-full gap-2 items-center rounded py-2 px-1"
>
<Avatar :image="user.user_image" :label="user.full_name" size="xl" />
<div>
<p class="text-gray-900 text-base font-medium">
{{ user.full_name }}
</p>
<p class="text-gray-600 text-base">
{{ user.user_name }}
</p>
</div>
<Button class="ml-auto" @click="removeUser(user)">Remove</Button>
</div>
<ErrorMessage class="mt-2" :message="errorMessage" />
</template>
</Dialog>
</template>
<script>
import {
Input,
Avatar,
Dialog,
ErrorMessage,
Button,
Tooltip,
FeatherIcon,
} from "frappe-ui"
import UserSearch from "./ShareDialog/UserSearch.vue"
export default {
name: "RoleDetailsDialog",
components: {
Avatar,
Dialog,
UserSearch,
ErrorMessage,
Button,
Input,
Tooltip,
FeatherIcon,
},
props: {
modelValue: {
type: Boolean,
required: true,
},
roleName: {
type: String,
default: null,
required: true,
},
},
emits: ["update:modelValue", "success"],
data() {
return {
NewRoleName: "",
UsersInRole: [],
NewUsersInRole: [],
errorMessage: "",
}
},
computed: {
uniqueUsers() {
return this.removeDuplicateObjects(this.UsersInRole, "user_name")
},
uniqueEmails() {
const uniqueUsernames = new Set()
this.NewUsersInRole.forEach((user) => {
uniqueUsernames.add(user)
})
this.UsersInRole.forEach((user) => {
uniqueUsernames.add(user.user_name)
})
return Array.from(uniqueUsernames)
},
open: {
get() {
return this.modelValue
},
set(value) {
this.$emit("update:modelValue", value)
if (!value) {
this.newName = ""
this.errorMessage = ""
}
},
},
},
methods: {
addUser(value) {
value.forEach((user) => {
this.UsersInRole.push(user)
this.NewUsersInRole.push(user.user_name)
})
this.$resources.addUsersToGroup.submit()
},
removeDuplicateObjects(arr, property) {
return [...new Map(arr.map((obj) => [obj[property], obj])).values()]
},
removeUser(user, index) {
this.$resources.RemoveUsersFromGroup.submit({
group_name: this.roleName,
user_emails: [user.user_name],
})
},
},
resources: {
getUsersInGroup() {
return {
url: "drive.utils.user_group.get_users_in_group",
params: {
group_name: this.roleName,
},
onSuccess(data) {
this.UsersInRole = data
data.forEach((user) => {
user.user_name = user.email
user.user_type = "User"
delete user.name
})
},
onError(data) {
console.log(data)
},
auto: true,
}
},
addUsersToGroup() {
return {
url: "drive.utils.user_group.add_users_to_group",
params: {
group_name: this.roleName,
user_emails: this.NewUsersInRole,
},
validate: () => {
if (!this.uniqueEmails.length) {
this.errorMessage = "Group needs atleast one member"
}
},
onSuccess(data) {
this.errorMessage = ""
this.$emit("success", data)
},
onError(data) {
console.log(data)
this.errorMessage = data
},
auto: false,
}
},
RemoveUsersFromGroup() {
return {
url: "drive.utils.user_group.remove_users_from_group",
params: {
group_name: this.roleName,
user_emails: null,
},
validate: () => {
if (this.uniqueEmails.length === 1) {
this.errorMessage = "Group needs atleast one active member"
}
},
onSuccess() {
this.errorMessage = ""
this.$resources.getUsersInGroup.fetch()
},
onError(data) {
if (data.messages === "Data missing in table: User Group Members'") {
this.errorMessage = "Group needs atleast one active member"
}
},
auto: false,
}
},
},
}
</script>
|
2302_79757062/drive
|
frontend/src/components/RoleDetailsDialog.vue
|
Vue
|
agpl-3.0
| 4,919
|
<template>
<Dialog v-model:open="open" :options="{ size: '2xl', position: 'top' }">
<template #body>
<div class="flex px-4 py-3 gap-1 items-center border-b">
<Search class="w-4 mr-1 h-auto" name="search" />
<input
v-model="search"
icon-left="search"
type="text"
class="appearance-none forced-colors:hidden w-full border-none bg-transparent py-3 pl-11.5 pr-4.5 text-base text-gray-800 placeholder-gray-500 focus:ring-0"
placeholder="Search"
/>
</div>
<div
v-if="$resources.entities.data?.length"
class="flex flex-col py-4 px-2.5 overflow-y-auto overflow-x-auto max-h-[50vh]"
>
<span class="mb-1 pl-2 text-base text-gray-600"
>Search results for <strong>"{{ search }}"</strong></span
>
<div
v-for="entity in $resources.entities.data"
:key="entity.name"
class="grid grid-flow-col grid-cols-8 gap-2 w-full items-center rounded px-2 py-2 text-base cursor-pointer hover:bg-gray-100"
@click="openEntity(entity)"
>
<div class="flex items-center gap-2 w-full col-span-6">
<svg
v-if="entity.is_group"
class="h-4 w-4"
:draggable="false"
:style="{ fill: entity.color }"
width="16"
height="16"
viewBox="0 0 16 16"
fill="none"
xmlns="http://www.w3.org/2000/svg"
>
<g clip-path="url(#clip0_1942_59507)">
<path
d="M7.83412 2.88462H1.5C1.22386 2.88462 1 3.10847 1 3.38462V12.5C1 13.6046 1.89543 14.5 3 14.5H13C14.1046 14.5 15 13.6046 15 12.5V2C15 1.72386 14.7761 1.5 14.5 1.5H9.94008C9.88623 1.5 9.83382 1.51739 9.79065 1.54957L8.13298 2.78547C8.04664 2.84984 7.94182 2.88462 7.83412 2.88462Z"
/>
</g>
<defs>
<clipPath id="clip0_1942_59507">
<rect width="16" height="16" fill="white" />
</clipPath>
</defs>
</svg>
<img
v-else
class="w-4 h-4"
:src="getIconUrl(formatMimeType(entity.mime_type))"
/>
<span class="truncate">{{ entity.title }}</span>
</div>
<div
class="col-span-2 grid grid-flow-col justify-start items-center truncate"
>
<Avatar
:image="entity.user_image"
:label="entity.full_name"
class="relative mr-2"
size="xs"
/>
<span class="text-base text-gray-800">{{ entity.full_name }}</span>
</div>
</div>
</div>
<div
v-if="search.length > 3 && !$resources.entities.data?.length"
class="flex flex-col py-4 px-2.5"
>
<span class="mb-1 pl-2 text-base text-gray-600"
>No results for <strong>"{{ search }}"</strong></span
>
</div>
<div
v-if="!$resources.entities.data?.length && !search.length"
class="flex flex-col mb-2 mt-4 first:mt-3"
>
<span class="mb-1 px-4.5 text-base text-gray-600">Jump to</span>
<div class="px-2.5">
<div
class="flex w-full min-w-0 items-center rounded px-2 py-2 text-base font-medium text-gray-700 hover:bg-gray-100"
@click="
$router.push({ name: 'Home' }),
emitter.emit('showSearchPopup', false)
"
>
<Home class="mr-2 h-4 w-4 text-gray-700" />
Home
</div>
<div
class="flex w-full min-w-0 items-center rounded px-2 py-2 text-base font-medium text-gray-700 hover:bg-gray-100"
@click="
$router.push({ name: 'Recents' }),
emitter.emit('showSearchPopup', false)
"
>
<Recent class="mr-2 h-4 w-4 text-gray-700" />
Recents
</div>
<div
class="flex w-full min-w-0 items-center rounded px-2 py-2 text-base font-medium text-gray-700 hover:bg-gray-100"
@click="
$router.push({ name: 'Favourites' }),
emitter.emit('showSearchPopup', false)
"
>
<Star class="mr-2 h-4 w-4 text-gray-700" />
Favourites
</div>
</div>
<span class="mt-3 mb-1 px-4.5 text-base text-gray-600">Actions</span>
<div class="px-2.5">
<div
class="flex w-full min-w-0 items-center rounded px-2 py-2 text-base font-medium text-gray-700 hover:bg-gray-100"
@click="
emitter.emit('uploadFile'), emitter.emit('showSearchPopup', false)
"
>
<FileUpload class="stroke-[1.35] mr-2 h-4 w-4 text-gray-700" />
Upload File
</div>
<div
class="flex w-full min-w-0 items-center rounded px-2 py-2 text-base font-medium text-gray-700 hover:bg-gray-100"
@click="
emitter.emit('uploadFolder'),
emitter.emit('showSearchPopup', false)
"
>
<FolderUpload class="stroke-[1.35] mr-2 h-4 w-4 text-gray-700" />
Upload Folder
</div>
<!-- <div class="flex w-full min-w-0 items-center rounded px-2 py-2 text-base font-medium text-gray-700 hover:bg-gray-100">
<FeatherIcon name="folder-plus" class="mr-2 h-4 w-4 text-gray-700"/>
New Folder
</div>
<div class="flex w-full min-w-0 items-center rounded px-2 py-2 text-base font-medium text-gray-700 hover:bg-gray-100">
<FeatherIcon name="file-text" class="mr-2 h-4 w-4 text-gray-700"/>
New Document
</div> -->
</div>
</div>
</template>
</Dialog>
</template>
<script>
import Home from "./EspressoIcons/Home.vue"
import Recent from "./EspressoIcons/Recent.vue"
import Search from "./EspressoIcons/Search.vue"
import FileUpload from "./EspressoIcons/File-upload.vue"
import FolderUpload from "./EspressoIcons/Folder-upload.vue"
import { Dialog, Avatar } from "frappe-ui"
import { formatMimeType } from "@/utils/format"
import { getIconUrl } from "@/utils/getIconUrl"
import Star from "./EspressoIcons/Star.vue"
export default {
name: "SearchPopup",
components: {
Dialog,
Avatar,
Home,
Recent,
Search,
Star,
FileUpload,
FolderUpload,
},
emits: ["openEntity", "update:open"],
setup() {
return { formatMimeType, getIconUrl }
},
data() {
return {
isOpen: false,
search: "",
selectedEntity: "",
}
},
computed: {
fullName() {
return this.$store.state.user.fullName
},
open: {
get() {
return this.open
},
set(value) {
this.$emit("update:open", value)
},
},
},
watch: {
search: {
handler(value) {
if (value.length >= 3) {
this.search = value
this.$resources.entities.submit({
query: value,
home_dir: this.$store.state.homeFolderID,
})
} else {
this.$resources.entities.reset()
}
},
},
},
methods: {
openEntity(entity) {
this.$resources.upwardPath
.fetch({ entity_name: entity.name })
.then(() => {
if (entity.is_group) {
this.selectedEntities = []
this.$router.push({
name: "Folder",
params: { entityName: entity.name },
})
} else if (entity.document) {
this.$router.push({
name: "Document",
params: { entityName: entity.name },
})
} else {
this.$router.push({
name: "File",
params: { entityName: entity.name },
})
}
})
this.emitter.emit("showSearchPopup", false)
},
},
resources: {
entities() {
return {
auto: false,
method: "POST",
url: "drive.api.files.search",
}
},
upwardPath() {
return {
auto: false,
method: "POST",
url: "drive.api.files.generate_upward_path",
}
},
},
}
</script>
<style scoped>
input {
all: unset;
}
input:focus {
all: unset;
outline: none;
border: none;
}
</style>
|
2302_79757062/drive
|
frontend/src/components/SearchPopup.vue
|
Vue
|
agpl-3.0
| 8,440
|
<template>
<Dialog v-model="open" :options="{ title: 'New Group', size: 'lg' }">
<template #body-content>
<label class="block text-sm text-gray-600 mb-2">Group Name</label>
<Input v-model="roleName" placeholder="Group Name" type="text" />
<ErrorMessage class="text-sm mt-2" :message="groupNameError" />
<label class="block text-sm text-gray-600 mt-4 mb-1">Add User</label>
<UserSearch
button-text="Add"
:search-groups="false"
:active-users="uniqueUsers"
:active-groups="[]"
@add-new-users="(data) => addUser(data.users)"
/>
<ErrorMessage class="text-sm mt-2" :message="memberError" />
<label v-if="UsersInRole.length" class="block text-sm text-gray-600 mt-6">
Users in this Group
</label>
<div
v-for="(user, index) in uniqueUsers"
:key="user.user_name"
class="mt-1 flex flex-row w-full gap-2 items-center hover:bg-gray-50 rounded py-2 px-1 cursor-pointer group"
>
<Avatar :image="user.user_image" :label="user.full_name" size="xl" />
<div>
<p class="text-gray-900 text-sm font-medium">
{{ user.full_name }}
</p>
<p class="text-gray-600 text-sm">
{{ user.user_name }}
</p>
</div>
<Button class="ml-auto" @click="UsersInRole.splice(index, 1)"
>Remove</Button
>
</div>
<div class="flex mt-6">
<Button
variant="solid"
class="w-full"
@click="$resources.createUserGroup.submit"
>
Create
</Button>
</div>
</template>
</Dialog>
</template>
<script>
import {
Avatar,
Dialog,
ErrorMessage,
Input,
Button,
Tooltip,
FeatherIcon,
} from "frappe-ui"
import UserSearch from "@/components/ShareDialog/UserSearch.vue"
export default {
name: "RoleDetailsDialog",
components: {
Avatar,
Dialog,
UserSearch,
ErrorMessage,
Button,
Input,
FeatherIcon,
Tooltip,
},
props: {
modelValue: {
type: Boolean,
required: true,
},
},
emits: ["update:modelValue", "success"],
data() {
return {
roleName: "",
UsersInRole: [],
groupNameError: [],
memberError: [],
errorMessage: "",
}
},
computed: {
uniqueEmails() {
const uniqueUsernames = new Set()
this.UsersInRole.forEach((user) => {
uniqueUsernames.add(user.user_name)
})
return Array.from(uniqueUsernames)
},
uniqueUsers() {
return this.removeDuplicateObjects(this.UsersInRole, "user_name")
},
open: {
get() {
return this.modelValue
},
set(value) {
this.$emit("update:modelValue", value)
if (!value) {
this.newName = ""
this.errorMessage = ""
}
},
},
},
methods: {
addUser(data) {
data.forEach((user) => {
this.memberError = ""
this.UsersInRole.push(user)
})
},
removeDuplicateObjects(arr, property) {
return [...new Map(arr.map((obj) => [obj[property], obj])).values()]
},
},
resources: {
createUserGroup() {
return {
url: "drive.utils.user_group.create_user_group",
params: {
group_name: this.roleName,
members: this.uniqueEmails,
},
validate: () => {
if (!this.roleName.length) {
this.groupNameError = "Group name is required"
}
if (!this.uniqueEmails.length) {
this.memberError = "Group needs atleast one member"
}
},
onSuccess(data) {
if (data.error) {
this.groupNameError = data.message
}
this.$emit("success", data)
},
onError(data) {
console.log(data.messages)
if (data.messages === "Please set the document name") {
this.groupNameError = "Group name is required"
}
},
auto: false,
}
},
},
}
</script>
|
2302_79757062/drive
|
frontend/src/components/Settings/NewRoleDialog.vue
|
Vue
|
agpl-3.0
| 4,064
|
<template>
<h1 class="font-semibold mb-8">Profile</h1>
<div class="flex justify-start w-full items-center gap-x-4">
<Avatar :image="imageURL" size="3xl" :label="fullName" class="w-20 h-20" />
<div class="flex flex-col">
<span class="text-xl font-semibold">{{ fullName }}</span>
<span class="text-base text-gray-700">{{ currentUserEmail }}</span>
</div>
<Button class="ml-auto" @click="editProfileDialog = true"
>Edit profile</Button
>
</div>
<Dialog
v-model="editProfileDialog"
:options="{
title: 'Edit Profile',
size: 'md',
actions: [
{
label: 'Confirm',
variant: 'solid',
onClick: submit,
},
],
}"
>
<template #body-content>
<div class="flex flex-col items-start justify-start gap-y-2">
<span class="text-base text-gray-600">Profile Photo</span>
<div class="flex items-center justify-between w-full">
<Avatar
:image="newImageUrl"
size="3xl"
:label="newFullName"
class="w-20 h-20"
/>
<div
v-if="newImageUrl"
class="flex items-center justify-between bg-gray-100 h-7 pl-2 text-base rounded"
>
<Link class="mr-2" />
<a :href="newImageUrl" class="truncate max-w-56 underline">{{
newImageUrl
}}</a>
<Button @click="newImageUrl = null"
><template #icon> <X class="stroke-1 h-4" /> </template
></Button>
</div>
<FileUploader
v-else
:file-types="'image/png, image/jpeg, image/jpg'"
:validate-file="validateFile"
@success="
(file) => {
newImageUrl = file.file_url
}
"
>
<template
#default="{ file, progress, uploading, openFileSelector }"
>
<Button @click="openFileSelector"> Add Image </Button>
</template>
</FileUploader>
</div>
<div class="w-full flex flex-col gap-y-2 my-2">
<span class="text-base text-gray-600">First Name</span>
<Input v-model="newFirstName"></Input>
<span class="text-base text-gray-600">Last Name</span>
<Input v-model="newLastName"></Input>
</div>
</div>
<ErrorMessage
v-if="errorMessage"
class="text-sm mt-2"
:message="errorMessage"
/>
</template>
</Dialog>
<h1 class="font-semibold mt-12 mb-4">Preferences</h1>
<Switch v-model="foldersBefore" label="Group folders before files"></Switch>
<Switch
v-model="singleClick"
label="Single click to open files and folders"
></Switch>
</template>
<script>
import { Button, Input, Avatar, Dialog, FileUploader, Switch } from "frappe-ui"
import Link from "../EspressoIcons/Link.vue"
import { X } from "lucide-vue-next"
import ErrorMessage from "frappe-ui/src/components/ErrorMessage.vue"
export default {
name: "NoFilesSection",
components: {
Avatar,
Button,
Input,
Dialog,
Link,
X,
FileUploader,
ErrorMessage,
Switch,
},
data() {
return {
newImageUrl: this.$store.state.user.imageURL,
newFirstName: this.$store.state.user.fullName.split(" ")[0],
newLastName: this.$store.state.user.fullName.split(" ")[1],
editProfileDialog: false,
addImageDialog: true,
errorMessage: null,
routeOptions: [
{
group: "Routes",
hideLabel: true,
items: [
{
icon: "home",
label: "Home",
},
{
icon: "clock",
label: "Recents",
},
{
icon: "star",
label: "Favourites",
},
{
icon: "users",
label: "Shared",
},
{
icon: "trash-2",
label: "Trash",
},
],
},
],
}
},
computed: {
newFullName() {
return this.newFirstName + " " + this.newLastName
},
isExpanded() {
return this.$store.state.IsSidebarExpanded
},
firstName() {
return this.$store.state.user.fullName.split(" ")[0]
},
lastName() {
return this.$store.state.user.fullName.split(" ")[1]
},
currentUserEmail() {
return this.$store.state.auth.user_id
},
fullName() {
return this.$store.state.user.fullName
},
imageURL() {
return this.$store.state.user.imageURL
},
foldersBefore: {
get() {
return this.$store.state.foldersBefore
},
set() {
//toggled in mutation
this.$store.commit("toggleFoldersBefore")
},
},
singleClick: {
get() {
return this.$store.state.singleClick
},
set() {
this.$store.commit("toggleSingleClick")
},
},
editorNewTab: {
get() {
return this.$store.state.editorNewTab
},
set() {
this.$store.commit("toggleEditorNewTab")
},
},
},
methods: {
submit() {
this.$resources.profile.setValue
.submit({
first_name: this.newFirstName,
last_name: this.newLastName,
user_image: this.newImageUrl,
})
.then((data) => {
this.$store.state.user.fullName = data.full_name
this.$store.state.user.imageURL = data.user_image
this.editProfileDialog = false
})
},
validateFile(file) {
let extension = file.name.split(".").pop().toLowerCase()
if (!["jpg", "jpeg", "png"].includes(extension)) {
this.errorMessage = "Not a valid Image file"
} else {
this.errorMessage = null
}
},
},
resources: {
profile() {
return {
type: "document",
doctype: "User",
name: this.currentUserEmail,
auto: true,
realtime: true,
}
},
},
}
</script>
|
2302_79757062/drive
|
frontend/src/components/Settings/ProfileSettings.vue
|
Vue
|
agpl-3.0
| 6,098
|
<template>
<Dialog v-model="open" :options="{ title: 'Settings', size: '5xl' }">
<template #body>
<div class="flex" :style="{ height: 'calc(100vh - 9rem)' }">
<div class="flex w-52 shrink-0 flex-col bg-gray-50 py-3 p-4 border-r">
<h1 class="text-xl font-semibold leading-6 text-gray-900 px-2">
Settings
</h1>
<div class="mt-3 space-y-1">
<button
v-for="tab in tabs"
:key="tab.label"
class="flex h-7 w-full items-center gap-2 rounded px-2 py-1"
:class="[
activeTab?.label == tab.label
? 'bg-gray-200'
: 'hover:bg-gray-100',
]"
@click="activeTab = tab"
>
<component :is="tab.icon" class="h-4 w-4 text-gray-700" />
<span class="text-base text-gray-800">
{{ tab.label }}
</span>
</button>
</div>
</div>
<div class="flex flex-1 flex-col p-12 overflow-y-auto">
<component :is="activeTab.component" v-if="activeTab" />
</div>
<Button
class="my-3 mr-4 absolute right-0"
variant="ghost"
@click="$emit('update:modelValue', false)"
>
<FeatherIcon name="x" class="stroke-2 ml-auto h-4" />
</Button>
</div>
</template>
</Dialog>
</template>
<script setup>
import { ref, defineProps, markRaw, computed } from "vue"
import { Dialog, FeatherIcon, Button, createResource } from "frappe-ui"
import ProfileSettings from "@/components/Settings/ProfileSettings.vue"
import StorageSettings from "./StorageSettings.vue"
import User from "@/components/EspressoIcons/User.vue"
import AddUser from "@/components/EspressoIcons/AddUser.vue"
import Users from "@/components/EspressoIcons/Users.vue"
import Cloud from "@/components/EspressoIcons/Cloud.vue"
import UserRoleSettings from "./UserRoleSettings.vue"
import UserListSettings from "./UserListSettings.vue"
import { useStore } from "vuex"
const store = useStore()
let tabs = [
{
label: "Profile",
icon: User,
component: markRaw(ProfileSettings),
},
{
label: "Users",
icon: AddUser,
component: markRaw(UserListSettings),
},
{
label: "Groups",
icon: Users,
component: markRaw(UserRoleSettings),
},
{
label: "Storage",
icon: Cloud,
component: markRaw(StorageSettings),
},
]
const emit = defineEmits(["update:modelValue"])
const props = defineProps({
modelValue: {
type: Boolean,
required: true,
},
suggestedTab: {
type: Number,
default: 0,
required: false,
},
})
let activeTab = ref(tabs[props.suggestedTab])
const open = computed({
get() {
return props.modelValue
},
set(newValue) {
emit("update:modelValue", newValue)
},
})
createResource({
url: "drive.utils.users.is_drive_admin",
method: "POST",
auto: true,
onSuccess(data) {
store.state.user.driveAdmin = data
},
})
</script>
|
2302_79757062/drive
|
frontend/src/components/Settings/SettingsDialog.vue
|
Vue
|
agpl-3.0
| 3,045
|
<template>
<h1 class="font-semibold mb-8">Storage</h1>
<div
v-if="!usedSpace"
class="h-full w-full flex flex-col items-center justify-center my-auto"
>
<Cloud class="h-7 stroke-1 text-gray-600" />
<span class="text-gray-800 text-sm mt-2">No Storage Used</span>
</div>
<div v-else>
<div class="flex flex-col items-start justify-start w-full mb-4">
<span class="text-lg font-semibold text-gray-800 mb-3"
>You have used {{ formatSize(usedSpace) }} out of
{{ base2BlockSize(planSizeLimit) }}</span
>
<div
class="w-full flex justify-start items-start bg-gray-50 border rounded overflow-clip h-7 pl-0"
>
<div
v-for="i in $resources.getDataByMimeType.data"
:key="i.file_kind"
class="h-7"
:style="{
backgroundColor: i.color,
width: i.percentageFormat,
paddingRight: `${5 + i.percentageRaw}px`,
}"
></div>
</div>
</div>
<div
class="flex flex-col items-start justify-start w-full rounded full px-1.5 overflow-y-auto"
>
<div
v-for="i in $resources.getDataByMimeType.data"
:key="i.file_kind"
class="w-full border-b flex items-center justify-start py-4 gap-x-2"
>
<div
class="h-2 w-2 rounded-full"
:style="{
backgroundColor: i.color,
}"
></div>
<span class="text-gray-800 text-base">{{ i.file_kind }}</span>
<span class="text-gray-800 text-base ml-auto">{{ i.h_size }}</span>
</div>
</div>
</div>
</template>
<script>
import { formatSize, base2BlockSize } from "../../utils/format"
import Cloud from "@/components/EspressoIcons/Cloud.vue"
export default {
name: "StorageSettings",
components: {
Cloud,
},
data() {
return {
fullName: this.$store.state.user.fullName,
planSizeLimit: 50000000000,
usedSpace: 0,
fileKindColorMap: {
Archive: "#C2A88D",
Application: "#f472b6",
Image: "#34BAE3",
Video: "#E86C13",
Audio: "#9C45E3",
Document: "#0073CA",
Spreadsheet: "#30A66D",
Presentation: "#F5BA14",
Text: "#E2E2E2",
PDF: "#E03636",
Book: "#E2E2E2",
Unknown: "#3f3f46",
},
}
},
computed: {
isExpanded() {
return this.$store.state.IsSidebarExpanded
},
firstName() {
return this.$store.state.user.fullName.split(" ")
},
/* fullName() {
return this.$store.state.user.fullName;
}, */
imageURL() {
return this.$store.state.user.imageURL
},
},
resources: {
storageLimit() {
return {
url: "drive.api.storage.get_max_storage",
method: "GET",
auto: true,
onSuccess(data) {
this.planSizeLimit = data
this.$resources.getDataByMimeType.fetch()
},
onError(error) {
if (error.messages) {
this.errorMessage = error.messages.join("\n")
} else {
this.errorMessage = error.message
}
},
}
},
getDataByMimeType() {
return {
url: "drive.api.storage.total_storage_used_by_file_kind",
onError(error) {
console.log(error)
},
onSuccess(data) {
data.forEach((item) => {
item.color = this.fileKindColorMap[item.file_kind]
item.percentageRaw = (100 * item.total_size) / this.planSizeLimit
item.percentageFormat = this.formatPercent(item.percentageRaw)
item.h_size = formatSize(item.total_size)
this.usedSpace = this.usedSpace + item.total_size
})
data.sort((a, b) => b.total_size - a.total_size)
},
auto: false,
}
},
},
methods: {
formatSize,
base2BlockSize,
formatPercent(num) {
return new Intl.NumberFormat("default", {
style: "percent",
minimumFractionDigits: 1,
maximumFractionDigits: 1,
}).format(num / 100)
},
},
}
</script>
|
2302_79757062/drive
|
frontend/src/components/Settings/StorageSettings.vue
|
Vue
|
agpl-3.0
| 4,103
|
<template>
<h1 class="font-semibold mb-4">Users</h1>
<div class="flex flex-col items-stretch justify-start overflow-y-auto">
<div class="flex items-center justify-between">
<!-- <Button
variant="subtle"
icon-left="plus"
@click="CreateRoleDialog = !CreateRoleDialog"
>
Invite
</Button> -->
</div>
<div
v-for="(user, index) in $resources.fetchAllUsers?.data"
:key="user.user_name"
>
<div
v-if="index > 0"
class="w-[95%] mx-auto h-px border-t border-gray-200"
></div>
<div class="flex items-center justify-start py-2 pl-2 pr-4 gap-x-2">
<Avatar :image="user.user_image" :label="user.full_name" size="lg" />
<div class="flex flex-col">
<span class="text-base">{{ user.full_name }}</span>
<span class="text-base text-gray-700">{{ user.user_name }}</span>
</div>
<span class="ml-auto text-base text-gray-600">{{ user.role }}</span>
</div>
</div>
</div>
<div
v-if="!$resources.fetchAllUsers?.data?.length"
class="h-1/2 w-full flex flex-col items-center justify-center my-auto"
>
<FeatherIcon class="h-8 stroke-1 text-gray-600" name="users" />
<span class="text-gray-800 text-sm mt-2">No Users</span>
</div>
</template>
<script>
import { Avatar, FeatherIcon, Dropdown, Dialog } from "frappe-ui"
import RoleDetailsDialog from "@/components/RoleDetailsDialog.vue"
import NewRoleDialog from "./NewRoleDialog.vue"
export default {
name: "UserRoleSettings",
components: {
Avatar,
RoleDetailsDialog,
NewRoleDialog,
FeatherIcon,
Dropdown,
Dialog,
},
data() {
return {
RoleName: "",
UsersInRole: [],
CreateRoleDialog: false,
EditRoleDialog: false,
AllRoles: null,
errorMessage: "",
activeGroup: null,
showDeleteDialog: false,
}
},
computed: {
memberEmails() {
let x = []
this.UsersInRole.forEach((user) => x.push(user.email))
return x
},
},
methods: {
viewGroupDetails(value) {
this.activeGroup = value
this.RoleName = value
this.EditRoleDialog = !this.EditRoleDialog
},
},
resources: {
fetchAllUsers: {
url: "drive.utils.users.get_users_with_drive_user_role",
params: {
get_roles: true,
},
method: "GET",
auto: true,
onSuccess(data) {
// Update group key to filter
data.forEach(function (item) {
if (item.email) {
item.user_name = item.email
item.user_type = "User"
delete item.email
}
})
},
onError(error) {
if (error.messages) {
this.errorMessage = error.messages.join("\n")
} else {
this.errorMessage = error.message
}
},
},
},
}
</script>
|
2302_79757062/drive
|
frontend/src/components/Settings/UserListSettings.vue
|
Vue
|
agpl-3.0
| 2,880
|
<template>
<div class="flex items-center mb-2">
<h1 class="font-semibold">Groups</h1>
<Button
variant="subtle"
icon-left="plus"
class="ml-auto"
@click="CreateRoleDialog = !CreateRoleDialog"
>
Create
</Button>
</div>
<div
class="w-full h-full flex flex-col items-stretch justify-start overflow-y-auto"
>
<div v-for="(group, index) in AllRoles" :key="group.name">
<div
v-if="index > 0"
class="w-[95%] mx-auto h-px border-t border-gray-200"
></div>
<div
class="flex text-base items-center justify-start p-2 cursor-pointer hover:bg-gray-50 rounded w-full"
@click.self="viewGroupDetails(group.name)"
>
<Avatar size="lg" :label="group.name" />
<span class="ml-2">{{ group.name }}</span>
<Dropdown
v-if="isDriveadmin"
:button="{
icon: 'more-horizontal',
label: 'Page Options',
variant: 'ghost',
}"
class="ml-auto"
placement="right"
:options="[
{
label: 'Delete',
icon: 'trash-2',
onClick: () => {
activeGroup = group.name
showDeleteDialog = true
},
},
]"
>
<Button>
<template #icon>
<FeatherIcon name="more-horizontal" class="h-4 w-4" />
</template> </Button
></Dropdown>
</div>
</div>
<div
v-if="!AllRoles?.length"
class="h-1/2 w-full flex flex-col items-center justify-center my-auto"
>
<FeatherIcon class="h-8 stroke-1 text-gray-600" name="users" />
<span class="text-gray-800 text-sm mt-2">No groups</span>
</div>
<NewRoleDialog
v-if="CreateRoleDialog"
v-model="CreateRoleDialog"
@success="
() => {
CreateRoleDialog = false
$resources.getUserGroups.fetch()
}
"
/>
<RoleDetailsDialog
v-if="EditRoleDialog"
v-model="EditRoleDialog"
:role-name="RoleName"
@success="
() => {
$resources.getUserGroups.fetch()
}
"
/>
<Dialog
v-model="showDeleteDialog"
:options="{
title: 'Delete ' + activeGroup,
message:
'This will delete the group. Members will lose access to files shared with this group.',
size: 'sm',
actions: [
{
label: 'Confirm',
variant: 'solid',
theme: 'red',
onClick: () => {
$resources.deleteUserGroup.submit({
group_name: activeGroup,
})
},
},
],
}"
/>
</div>
</template>
<script>
import { Avatar, FeatherIcon, Dropdown, Dialog } from "frappe-ui"
import RoleDetailsDialog from "@/components/RoleDetailsDialog.vue"
import NewRoleDialog from "./NewRoleDialog.vue"
export default {
name: "UserRoleSettings",
components: {
Avatar,
RoleDetailsDialog,
NewRoleDialog,
FeatherIcon,
Dropdown,
Dialog,
},
data() {
return {
RoleName: "",
UsersInRole: [],
CreateRoleDialog: false,
EditRoleDialog: false,
AllRoles: null,
errorMessage: "",
activeGroup: null,
showDeleteDialog: false,
}
},
computed: {
memberEmails() {
let x = []
this.UsersInRole.forEach((user) => x.push(user.email))
return x
},
isDriveadmin() {
return this.$store.state.user.driveAdmin
},
},
methods: {
viewGroupDetails(value) {
this.activeGroup = value
this.RoleName = value
this.EditRoleDialog = !this.EditRoleDialog
},
},
resources: {
deleteUserGroup() {
return {
url: "drive.utils.user_group.delete_user_group",
params: {
group_name: null,
},
onSuccess() {
this.errorMessage = ""
this.activeGroup = ""
this.showDeleteDialog = false
this.$resources.getUserGroups.fetch()
},
onError(data) {
console.log(data)
this.errorMessage = data
},
auto: false,
}
},
getUserGroups() {
return {
url: "drive.utils.user_group.get_name_of_all_user_groups",
onSuccess(data) {
this.AllRoles = data
},
onError(data) {
console.log(data)
},
auto: true,
}
},
},
}
</script>
|
2302_79757062/drive
|
frontend/src/components/Settings/UserRoleSettings.vue
|
Vue
|
agpl-3.0
| 4,528
|
<template>
<Popover v-slot="{ open, close }">
<Float
placement="bottom"
:offset="2"
portal
as="div"
class="relative w-full"
>
<PopoverButton
class="flex gap-1 px-2 focus:outline-none bg-gray-100 rounded h-7 items-center text-base"
>
{{ accessObj.write ? "Can Edit" : "Can View" }}
<span class="hidden">{{
open ? disableScroll.on() : disableScroll.off()
}}</span>
<ChevronDown
:class="{ '[transform:rotateX(180deg)]': open }"
class="w-4"
/>
</PopoverButton>
<PopoverPanel class="z-10 bg-white p-1 shadow-2xl rounded w-full">
<div v-if="open">
<ul>
<li
class="flex items-center justify-between px-1 text-base line-clamp-1 py-1 gap-1 hover:bg-gray-100 w-full rounded-[6px] cursor-pointer"
@click="
;(accessObj.read = 1),
(accessObj.write = 0),
$emit('updateAccess'),
close()
"
>
Can View
<Check
v-if="accessObj.read === 1 && accessObj.write === 0"
class="h-3"
/>
</li>
<li
class="flex items-center justify-between px-1 text-base line-clamp-1 py-1 gap-1 hover:bg-gray-100 w-full rounded-[6px] cursor-pointer"
@click="
;(accessObj.read = 1),
(accessObj.write = 1),
$emit('updateAccess'),
close()
"
>
Can Edit
<Check v-if="accessObj.write === 1" class="h-3" />
</li>
<hr class="my-0.5" />
<li
class="flex items-center justify-between px-1 text-base line-clamp-1 py-1 gap-1 hover:bg-gray-100 w-full rounded-[6px] cursor-pointer text-red-500"
@click="$emit('removeAccess'), close()"
>
Remove
</li>
</ul>
</div>
</PopoverPanel>
</Float>
</Popover>
</template>
<script setup>
import { ref } from "vue"
import { Float } from "@headlessui-float/vue"
import ChevronDown from "@/components/EspressoIcons/ChevronDown.vue"
import Check from "@/components/EspressoIcons/Check.vue"
import { Popover, PopoverButton, PopoverPanel } from "@headlessui/vue"
import disableScroll from "../../utils/disable-scroll"
const props = defineProps(["accessObj"])
const accessObj = ref(props.accessObj)
defineEmits(["updateAccess", "removeAccess"])
</script>
|
2302_79757062/drive
|
frontend/src/components/ShareDialog/AccessButton.vue
|
Vue
|
agpl-3.0
| 2,606
|
<template>
<Dialog v-model="openDialog" :options="{ size: 'lg' }">
<template #body-main>
<div class="pb-6 pt-5 max-h-[85vh]">
<div
class="flex items-start w-full justify-between gap-x-15 mb-8 px-4 sm:px-6"
>
<span class="font-semibold text-2xl truncate"
>Sharing "{{ entity?.title }}"</span
>
<Button
class="ml-auto"
variant="ghost"
@click="$emit('update:modelValue', false)"
>
<FeatherIcon name="x" class="stroke-2 h-4" />
</Button>
</div>
<div
v-if="showSettings"
class="px-4 sm:px-6"
:style="{
minHeight: $refs.shareMain?.clientHeight + 'px',
}"
>
<div class="flex flex-col space-y-4">
<div>
<span class="mb-0.5 block text-sm leading-4 text-gray-700"
>Preferences</span
>
<Switch v-model="allowComments" label="Allow Comments" />
<Switch v-model="allowDownload" label="Allow Downloading" />
</div>
<div>
<DatePicker
v-model="invalidAfter"
variant="subtle"
label="Invalidate after"
></DatePicker>
<span
v-if="invalidateAfterError"
class="block text-xs leading-4 text-red-500 px-0.5 py-1.5"
>
{{ invalidateAfterError }}
</span>
<span
v-else-if="invalidAfter"
class="block text-xs leading-4 text-gray-700 px-0.5 py-1.5"
>
Selected documents will remain shared until
{{ useDateFormat(invalidAfter, "YY-MM-DD") }}
</span>
<span
v-else
class="block text-xs leading-4 text-gray-700 px-0.5 py-1.5"
>
Selected documents will remain shared indefinitely
</span>
</div>
</div>
</div>
<div
v-else-if="
!$resources.sharedWith.loading &&
!$resources.sharedWithUserGroup.loading
"
ref="shareMain"
>
<div
class="grid grid-flow-col-dense grid-cols-10 items-start justify-start mb-8 px-4 sm:px-6"
>
<GeneralAccess
size="xl"
class="col-span-1 justify-self-start row-start-1 row-end-1"
:general-access="generalAccess"
/>
<Popover
v-slot="{ open, close }"
class="text-gray-700 relative flex-shrink-0 justify-self-start col-span-6"
>
<PopoverButton
class="flex gap-1 px-2 focus:outline-none bg-gray-100 rounded h-7 items-center text-base w-auto justify-between"
>
{{
generalAccess.public
? "Public"
: generalAccess.everyone
? "Organization"
: "Restricted"
}}
<FeatherIcon
:class="{ '[transform:rotateX(180deg)]': open }"
name="chevron-down"
class="w-4"
/>
</PopoverButton>
<PopoverPanel
class="z-10 bg-white p-1 shadow-2xl rounded mt-1 absolute min-w-28 w-full"
><ul>
<li
class="flex items-center justify-between px-1 text-base line-clamp-1 py-1 gap-1 hover:bg-gray-100 w-full rounded-[6px] cursor-pointer"
@click="
;(generalAccess.public = 0),
(generalAccess.everyone = 1),
close()
"
>
Organization
<Check v-if="generalAccess.everyone" class="h-3" />
</li>
<li
class="flex items-center justify-between px-1 text-base line-clamp-1 py-1 gap-1 hover:bg-gray-100 w-full rounded-[6px] cursor-pointer"
@click="
;(generalAccess.public = 1),
(generalAccess.everyone = 0),
close()
"
>
Public
<Check v-if="generalAccess.public" class="h-3" />
</li>
<li
class="flex items-center justify-between px-1 text-base line-clamp-1 py-1 gap-1 hover:bg-gray-100 w-full rounded-[6px] cursor-pointer"
@click="
;(generalAccess.public = 0),
(generalAccess.read = 0),
(generalAccess.write = 0),
(generalAccess.everyone = 0),
close()
"
>
Restricted
<Check
v-if="!generalAccess.public && !generalAccess.everyone"
class="h-3"
/>
</li></ul
></PopoverPanel>
</Popover>
<Popover
v-if="generalAccess.public || generalAccess.everyone"
v-slot="{ open, close }"
class="text-gray-700 relative flex-shrink-0 col-span-3 justify-self-end row-start-1 row-end-1"
>
<PopoverButton
class="flex gap-1 px-2 focus:outline-none bg-gray-100 rounded h-7 items-center text-base justify-self-end"
>
{{ generalAccess.write ? "Can Edit" : "Can View" }}
<FeatherIcon
:class="{ '[transform:rotateX(180deg)]': open }"
name="chevron-down"
class="w-4"
/>
</PopoverButton>
<PopoverPanel
class="z-10 bg-white p-1 shadow-2xl rounded mt-1 absolute w-full"
><ul>
<li
class="flex items-center justify-between px-1 text-base line-clamp-1 py-1 gap-1 hover:bg-gray-100 w-full rounded-[6px] cursor-pointer"
@click="
generalAccess.read === 1,
(generalAccess.write = 0),
close()
"
>
Can View
<Check
v-if="
generalAccess.read === 1 && generalAccess.write === 0
"
class="h-3"
/>
</li>
<li
class="flex items-center justify-between px-1 text-base line-clamp-1 py-1 gap-1 hover:bg-gray-100 w-full rounded-[6px] cursor-pointer"
@click="
generalAccess.read === 1,
(generalAccess.write = 1),
close()
"
>
Can Edit
<Check
v-if="
generalAccess.read === 1 && generalAccess.write === 1
"
class="h-3"
/>
</li></ul
></PopoverPanel>
</Popover>
<span
class="text-xs text-gray-700 row-start-2 row-end-2 col-span-6 col-start-2"
>
{{ accessMessage }}
</span>
</div>
<UserSearch
button-variant="solid"
class="mb-4 px-4 sm:px-6"
:owner="$resources.sharedWith.data.owner"
:active-users="$resources.sharedWith.data.users"
:active-groups="$resources.sharedWithUserGroup.data"
@add-new-users="addNewUsers"
/>
<div class="overflow-y-auto max-h-96 px-4 sm:px-6">
<div
v-if="!$resources.sharedWith.loading"
class="text-base space-y-4 mb-5"
>
<span class="text-gray-600 font-medium text-base">Users</span>
<!-- Owner -->
<div class="flex items-center gap-x-3">
<Avatar
size="xl"
:label="$resources.sharedWith.data.owner.full_name"
:image="$resources.sharedWith.data.owner.user_image"
/>
<div class="flex items-start flex-col justify-start">
<span class="text-gray-900">{{
$resources.sharedWith.data.owner.full_name
}}</span>
<span class="text-gray-700">{{
$resources.sharedWith.data.owner.email
}}</span>
</div>
<span class="ml-auto flex items-center gap-1 text-gray-600">
Owner
<Diamond class="h-3.5" />
</span>
</div>
<!-- Users -->
<div
v-for="(user, index) in $resources.sharedWith.data.users"
:key="user.name"
class="flex items-center gap-x-3"
>
<Avatar
size="xl"
:label="user.user_name"
:image="user.user_image"
/>
<div class="flex items-start flex-col justify-start">
<span class="text-gray-900">{{
user.full_name ? user.full_name : user.user_name
}}</span>
<span class="text-gray-700">{{
user.full_name ? user.user_name : ""
}}</span>
</div>
<AccessButton
class="text-gray-700 relative flex-shrink-0 ml-auto"
:access-obj="user"
@update-access="
$resources.share.submit({
entity_name: entityName,
method: 'share',
user: user.user_name,
read: user.read,
write: user.write,
share: 0,
user_type: 'User',
})
"
@remove-access="
$resources.sharedWith.data.users.splice(index, 1),
$resources.share.submit({
entity_name: entityName,
method: 'unshare',
user: user.user_name,
user_type: 'User',
})
"
/>
</div>
</div>
<!-- Groups -->
<div
v-if="$resources.sharedWithUserGroup.data?.length"
class="text-base space-y-4 mb-5"
>
<span
v-if="$resources.sharedWithUserGroup.data?.length"
class="text-gray-600 font-medium text-base"
>Groups</span
>
<div
v-for="(group, index) in $resources.sharedWithUserGroup.data"
:key="group.user_name"
class="flex items-center gap-x-3"
>
<Avatar size="xl" :label="group.user_name" />
<div class="flex items-start flex-col justify-start">
<span class="text-gray-900">{{ group.user_name }}</span>
</div>
<AccessButton
class="text-gray-700 relative flex-shrink-0 ml-auto"
:access-obj="group"
@update-access="
$resources.share.submit({
entity_name: entityName,
method: 'share',
user: group.user_name,
read: group.read,
write: group.write,
share: 0,
user_type: 'User Group',
})
"
@remove-access="
$resources.sharedWithUserGroup.data.splice(index, 1),
$resources.share.submit({
entity_name: entityName,
method: 'unshare',
user: group.user_name,
user_type: 'User Group',
})
"
/>
</div>
</div>
</div>
</div>
<div
class="w-full flex items-center justify-between mt-2 px-4 sm:px-6 gap-x-2"
>
<Button
v-if="!showSettings"
:variant="'outline'"
@click="getLink(entity)"
>
<template #prefix>
<Link />
</template>
Copy Link
</Button>
<Button
class="ml-auto"
:variant="'outline'"
:icon-left="showSettings ? 'arrow-left' : 'settings'"
@click="showSettings = !showSettings"
>
{{ showSettings ? "Back" : "Settings" }}
</Button>
</div>
</div>
</template>
</Dialog>
</template>
<script>
import { ref } from "vue"
import { Popover, PopoverButton, PopoverPanel } from "@headlessui/vue"
import { Avatar, Dialog, FeatherIcon, Switch } from "frappe-ui"
import AccessButton from "@/components/ShareDialog/AccessButton.vue"
import { getLink } from "@/utils/getLink"
import GeneralAccess from "@/components/GeneralAccess.vue"
import UserSearch from "@/components/ShareDialog/UserSearch.vue"
import Link from "@/components/EspressoIcons/Link.vue"
import Diamond from "@/components/EspressoIcons/Diamond.vue"
import Check from "@/components/EspressoIcons/Check.vue"
import { capture } from "@/telemetry"
import DatePicker from "frappe-ui/src/components/DatePicker.vue"
import { formatDate } from "@/utils/format"
import { useDateFormat } from "@vueuse/core"
export default {
name: "ShareDialog",
components: {
Dialog,
UserSearch,
Avatar,
FeatherIcon,
Popover,
PopoverButton,
PopoverPanel,
Diamond,
Check,
GeneralAccess,
AccessButton,
Link,
Switch,
DatePicker,
},
props: {
modelValue: {
type: Boolean,
required: true,
},
entityName: {
type: String,
required: true,
},
},
emits: ["update:modelValue", "success"],
setup() {
const shareMain = ref(null)
return { shareMain }
},
data() {
return {
generalAccess: {
name: this.entityName,
read: true,
write: false,
share: false,
everyone: false,
public: false,
},
invalidAfter: null,
invalidateAfterError: null,
allowComments: true,
allowDownload: true,
saveLoading: false,
errorMessage: "",
showAlert: false,
alertMessage: "",
entity: null,
showSettings: false,
searchUserText: "",
}
},
computed: {
accessMessage() {
if (this.generalAccess.public) {
return this.generalAccess.write
? "Anyone with a link to this file can edit"
: "Anyone with a link to this file can view"
}
if (this.generalAccess.everyone) {
return this.generalAccess.write
? `Members of ${this.$resources.getOrgName.data?.org_name} can edit`
: `Members of ${this.$resources.getOrgName.data?.org_name} can view`
} else {
return "Only users with access can view or edit"
}
},
openDialog: {
get() {
return this.modelValue
},
set(value) {
this.$emit("update:modelValue", value)
if (!value) {
this.errorMessage = ""
}
},
},
},
watch: {
generalAccess: {
handler() {
this.$resources.updateAccess.submit({
method: "set_general_access",
entity_name: this.entityName,
read: this.generalAccess.read,
write: this.generalAccess.write,
share_name: this.generalAccess.name,
share: this.generalAccess.share,
public: this.generalAccess.public,
everyone: this.generalAccess.everyone,
})
},
deep: true,
},
invalidAfter: {
handler(newVal) {
const date = new Date(newVal + " UTC")
const unix = Math.floor(date.getTime() / 1000)
const now = Math.floor(Date.now() / 1000)
if (unix < now) {
this.invalidAfter = null
this.invalidateAfterError = "Cannot select an earlier date"
} else {
this.invalidateAfterError = null
this.$resources.updateInvalidAfter.submit({
entity_name: this.entityName,
invalidation_date: newVal,
})
}
},
},
allowComments: {
handler() {
this.$resources.toggleAllowComments.submit()
},
},
allowDownload: {
handler() {
this.$resources.toggleAllowDownload.submit()
},
},
},
methods: {
formatDate,
useDateFormat,
addNewUsers(data) {
for (let i in data.users) {
this.$resources.share.submit({
entity_name: this.entityName,
method: "share",
user: data.users[i].user_name,
user_type: data.users[i].user_type,
read: data.access.read,
write: data.access.write,
share: 0,
})
if (data.users[i].user_type === "User") {
this.$resources.sharedWith.data.users.push({
user_name: data.users[i].user_name,
read: data.access.read,
write: data.access.write,
share: 0,
user_image: data.users[i].user_image,
full_name: data.users[i].full_name,
})
} else {
this.$resources.sharedWithUserGroup.data.push({
user_name: data.users[i].user_name,
read: data.access.read,
write: data.access.write,
share: 0,
})
}
}
},
getLink,
},
resources: {
sharedWith() {
return {
url: "drive.api.permissions.get_shared_with_list",
params: {
entity_name: this.entityName,
},
auto: true,
}
},
sharedWithUserGroup() {
return {
url: "drive.api.permissions.get_shared_user_group_list",
params: {
entity_name: this.entityName,
},
auto: true,
}
},
entity() {
return {
url: "drive.api.permissions.get_entity_with_permissions",
params: {
entity_name: this.entityName,
fields: "title,is_group,allow_comments,allow_download,owner",
},
onSuccess(data) {
this.entity = data
if (data.valid_until) {
this.invalidAfter = data.valid_until
}
this.allowComments = !!data.allow_comments
this.allowDownload = !!data.allow_download
},
auto: true,
}
},
generalAccess() {
return {
url: "drive.api.permissions.get_general_access",
params: { entity_name: this.entityName },
onSuccess(data) {
if (data[0]) {
this.generalAccess = data[0]
}
},
auto: true,
}
},
share() {
return {
url: "drive.api.files.call_controller_method",
params: {
method: "share",
entity_name: this.entityName,
},
onSuccess() {
this.$resources.share.error = null
capture("sharing_status_updated")
},
onError(error) {
if (error.messages) {
this.errorMessage = error.messages.join("\n")
} else {
this.errorMessage = error.message
}
},
}
},
toggleAllowComments() {
return {
url: "drive.api.files.call_controller_method",
params: {
entity_name: this.entityName,
method: "toggle_allow_comments",
new_value: !this.allowComments,
},
onSuccess() {
this.$emit("success")
},
onError(error) {
if (error.messages) {
console.log(error.messages)
}
},
}
},
updateInvalidAfter() {
return {
url: "drive.api.permissions.update_document_invalidation",
debounce: 500,
params: {
entity_name: this.entityName,
invalidation_date: this.invalidAfter,
},
onSuccess() {
this.$emit("success")
},
onError(error) {
if (error.messages) {
console.log(error.messages)
}
},
}
},
toggleAllowDownload() {
return {
url: "drive.api.files.call_controller_method",
params: {
entity_name: this.entityName,
method: "toggle_allow_download",
new_value: !this.allowDownload,
},
onSuccess() {
this.$emit("success")
},
onError(error) {
if (error.messages) {
console.log(error.messages)
}
},
}
},
updateAccess() {
return {
url: "drive.api.files.call_controller_method",
onSuccess() {
capture("sharing_status_updated")
},
onError(error) {
if (error.messages) {
console.log(error.messages)
}
},
}
},
getOrgName() {
return {
url: "frappe.client.get",
method: "GET",
cache: "org_info",
params: {
doctype: "Drive Instance Settings",
},
onError(error) {
if (error.messages) {
this.errorMessage = error.messages.join("\n")
} else {
this.errorMessage = error.message
}
},
auto: true,
}
},
},
}
</script>
|
2302_79757062/drive
|
frontend/src/components/ShareDialog/ShareDialog.vue
|
Vue
|
agpl-3.0
| 22,179
|
<template>
<div class="grid grid-flow-col grid-cols-12 gap-x-2">
<div
class="flex items-center justify-start col-span-10 bg-gray-100 rounded text-base"
>
<Popover v-slot="{ open }" class="min-w-full">
<Float
placement="bottom"
:auto-update="true"
as="div"
class="relative"
:offset="10"
floating-as="template"
portal
adaptive-width
>
<PopoverButton
class="text-left w-full max-w-full focus:outline-none pl-2 text-gray-600 truncate overflow-hidden"
>
<span
v-for="(user, index) in newUsers"
:key="user.user_name"
class="text-gray-800"
>
<template v-if="index > 0">, </template>
{{ user.full_name }}
</span>
<span v-if="!newUsers.length" class="">Add users</span>
</PopoverButton>
<PopoverPanel
class="z-10 bg-white px-1.5 pt-1.5 shadow-2xl rounded-lg max-w-96 w-full"
>
<Input
v-model="searchUserText"
class="bg-white pb-1.5"
placeholder="Search users"
type="text"
@input="searchUserText = $event"
/>
<ul
v-if="searchFilterUsers?.length"
class="flex flex-col items-start justify-start max-h-[10rem] overflow-y-auto"
>
<li
v-for="user in searchFilterUsers"
:key="user.email"
class="flex items-center justify-start px-1.5 py-1 hover:bg-gray-100 w-full rounded cursor-pointer"
@click="addNewUser(user)"
>
<Avatar
size="sm"
:label="user.full_name"
:image="user.user_image"
class="mr-2"
/>
<span class="text-base text-gray-700">{{
user.full_name
}}</span>
</li>
</ul>
<span
v-else
class="rounded-md px-2.5 py-1.5 text-base text-gray-600"
>No users found</span
>
<div class="flex items-center justify-end border-t py-1 mt-1">
<Button
class="px-2 py-1.5 hover:bg-gray-100 rounded cursor-pointer"
@click="resetAll"
>
Clear all
</Button>
</div>
</PopoverPanel>
</Float>
</Popover>
<!-- <div class="border-l border-gray-300 h-5"></div>
<Popover v-slot="{ open }" class="text-gray-700 relative flex-shrink-0">
<PopoverButton class="flex gap-1 px-2 focus:outline-none">
{{ newUserAccess.write ? "Can Edit" : "Can View" }}
<FeatherIcon name="chevron-down" class="w-4" />
</PopoverButton>
<PopoverPanel
class="z-10 bg-white p-1.5 shadow-2xl rounded mt-3 absolute w-full"
><ul>
<li
class="line-clamp-1 p-1 pl-1.5 hover:bg-gray-100 w-full rounded-[6px] cursor-pointer"
@click="newUserAccess = { read: 1, write: 0 }"
>
Can View
</li>
<li
class="line-clamp-1 p-1 pl-1.5 hover:bg-gray-100 w-full rounded-[6px] cursor-pointer"
@click="newUserAccess = { read: 1, write: 1 }"
>
Can Edit
</li>
</ul></PopoverPanel
>
</Popover> -->
</div>
<Button
class="col-span-2"
:variant="buttonVariant"
@click="
emit('addNewUsers', { users: newUsers, access: newUserAccess }),
(newUsers = [])
"
>
{{ buttonText }}
</Button>
</div>
</template>
<script setup>
import { Float } from "@headlessui-float/vue"
import { Popover, PopoverButton, PopoverPanel } from "@headlessui/vue"
import { defineEmits, computed, ref, watch } from "vue"
import { createResource, Avatar, Input } from "frappe-ui"
const searchUserText = ref("")
const allUsers = ref([])
const newUserAccess = ref({ read: 1, write: 0 })
const newUsers = ref([])
const props = defineProps({
buttonText: {
type: String,
default: "Invite",
},
buttonVariant: {
type: String,
default: "subtle",
},
searchGroups: {
type: Boolean,
default: true,
},
activeUsers: {
type: Object,
required: true,
},
activeGroups: {
type: Object,
required: true,
},
owner: {
type: Object,
default() {
return {
user_name: "",
}
},
},
})
const activeUsers = ref(props.activeUsers)
const activeGroups = ref(props.activeGroups)
const emit = defineEmits(["addNewUsers"])
watch([activeUsers.value, activeGroups.value], () => {
allUsers.value = [...fetchAllUsers.data]
})
const searchFilterUsers = computed(() => {
if (!searchUserText.value.length) return availableUsers.value
return availableUsers.value?.filter((x) =>
x.full_name.toLowerCase().includes(searchUserText.value.toLowerCase())
)
})
const availableUsers = computed(() => {
return allUsers.value.filter((item) => !filterActiveUsers(item.user_name))
})
function addNewUser(user) {
const index = allUsers.value.indexOf(user)
newUsers.value.push(allUsers.value[index])
if (index > -1) {
allUsers.value.splice(index, 1)
}
}
function filterActiveUsers(val) {
return (
props.owner.email === val ||
props.activeGroups.some((group) => group.user_name === val) ||
props.activeUsers.some((user) => user.user_name === val)
)
}
function resetAll() {
newUsers.value = []
allUsers.value = fetchAllUsers.fetch().then(() => {})
}
let fetchAllUsers = createResource({
url: props.searchGroups
? "drive.utils.users.get_users_with_drive_user_role_and_groups"
: "drive.utils.users.get_users_with_drive_user_role",
method: "GET",
auto: true,
onSuccess(data) {
// Update group key to filter
data.forEach(function (item) {
if (item.email) {
item.user_name = item.email
item.user_type = "User"
delete item.email
} else {
item.full_name = item.name
item.user_name = item.name
item.user_type = "User Group"
delete item.name
}
})
allUsers.value = [...data]
},
onError(error) {
if (error.messages) {
this.errorMessage = error.messages.join("\n")
} else {
this.errorMessage = error.message
}
},
})
</script>
|
2302_79757062/drive
|
frontend/src/components/ShareDialog/UserSearch.vue
|
Vue
|
agpl-3.0
| 6,574
|
<template>
<div
:class="isExpanded ? 'w-[220px]' : 'w-[50px]'"
class="border-r bg-gray-50 relative hidden sm:flex h-screen flex-col justify-start duration-300 ease-in-out p-2"
>
<PrimaryDropDown :is-expanded="isExpanded" />
<div
class="mt-2.5"
:class="!isExpanded ? 'flex flex-col items-start' : ''"
ondragstart="return false;"
ondrop="return false;"
>
<SidebarItem
:label="'Search'"
class="mb-0.5"
:is-collapsed="!isExpanded"
@click="() => emitter.emit('showSearchPopup', true)"
>
<template #icon>
<Search
class="stroke-[1.5] h-4 w-4 text-gray-700 focus:outline-none"
/>
</template>
<template #right>
<div
class="flex items-center justify-start w-full duration-300 ease-in-out"
:class="
isExpanded ? 'ml-2 opacity-100' : 'ml-0 overflow-hidden opacity-0'
"
>
<span
class="text-sm text-gray-500 ease-in"
:class="
isExpanded
? 'opacity-100 ml-auto'
: 'ml-0 overflow-hidden opacity-0'
"
>
{{ currentPlatform === "mac" ? "⌘K" : " Ctrl+K" }}
</span>
</div>
</template>
</SidebarItem>
<SidebarItem
:label="'Notifications'"
icon="inbox"
class="mb-0.5"
:is-collapsed="!isExpanded"
to="/notifications"
>
<template #right>
<div
class="flex items-center justify-start w-full duration-300 ease-in-out"
:class="
isExpanded
? 'ml-2 opacity-100'
: 'ml-0 overflow-hidden relative min-w-5 min-h-5'
"
>
<span
v-if="$store.state.notifCount > 0"
class="text-sm text-gray-500 ease-in"
:class="
isExpanded
? 'opacity-100 ml-auto'
: 'absolute top-0 left-0 bg-[#015a66] rounded w-1 h-1'
"
>
{{ isExpanded ? $store.state.notifCount : "" }}
</span>
</div>
</template>
</SidebarItem>
<SidebarItem
v-for="item in sidebarItems"
:key="item.label"
:icon="item.icon"
:label="item.label"
:to="item.route"
:is-collapsed="!isExpanded"
class="mb-0.5"
/>
</div>
<div class="mt-auto">
<StorageBar />
<!-- <span>{{ $resources.getRootFolderSize.data }}</span> -->
<SidebarItem
:label="!isExpanded ? 'Expand' : 'Collapse'"
:is-collapsed="!isExpanded"
class="mt-auto"
@click="toggleExpanded"
>
<template #icon>
<span class="grid h-4.5 w-4.5 flex-shrink-0 place-items-center">
<ArrowLeftFromLine
class="stroke-[1.5] h-4 w-4 text-gray-700 duration-300 ease-in-out"
:class="{ '[transform:rotateY(180deg)]': !isExpanded }"
/>
</span>
</template>
</SidebarItem>
</div>
</div>
</template>
<script>
import { formatSize } from "../utils/format"
import PrimaryDropDown from "./PrimaryDropdown.vue"
import { ArrowLeftFromLine } from "lucide-vue-next"
import Search from "./EspressoIcons/Search.vue"
import Recent from "./EspressoIcons/Recent.vue"
import Star from "./EspressoIcons/Star.vue"
import Users from "./EspressoIcons/Users.vue"
import Trash from "./EspressoIcons/Trash.vue"
import SidebarItem from "@/components/SidebarItem.vue"
import Home from "./EspressoIcons/Home.vue"
import StorageBar from "./StorageBar.vue"
export default {
name: "Sidebar",
components: {
PrimaryDropDown,
ArrowLeftFromLine,
SidebarItem,
Search,
StorageBar,
},
emits: ["toggleMobileSidebar", "showSearchPopUp"],
data() {
return {
sidebarResizing: false,
}
},
computed: {
isExpanded() {
return this.$store.state.IsSidebarExpanded
},
currentPlatform() {
let ua = navigator.userAgent.toLowerCase()
if (ua.indexOf("win") > -1) {
return "win"
} else if (ua.indexOf("mac") > -1) {
return "mac"
} else if (ua.indexOf("x11") > -1 || ua.indexOf("linux") > -1) {
return "linux"
}
return ""
},
sidebarItems() {
return [
{
label: "Home",
route: "/home",
icon: Home,
highlight: this.$store.state.currentBreadcrumbs[0].label === "Home",
},
{
label: "Recents",
route: "/recents",
icon: Recent,
highlight:
this.$store.state.currentBreadcrumbs[0].label === "Recents",
},
{
label: "Favourites",
route: "/favourites",
icon: Star,
highlight:
this.$store.state.currentBreadcrumbs[0].label === "Favourites",
},
{
label: "Shared",
route: "/shared",
icon: Users,
highlight: this.$store.state.currentBreadcrumbs[0].label === "Shared",
},
{
label: "Trash",
route: "/trash",
icon: Trash,
highlight: this.$store.state.currentBreadcrumbs[0].label === "Trash",
},
]
},
},
methods: {
formatSize,
toggleExpanded() {
return this.$store.commit(
"setIsSidebarExpanded",
this.isExpanded ? false : true
)
},
},
resources: {
getUnreadCount: {
url: "drive.api.notifications.get_unread_count",
auto: true,
method: "GET",
onSuccess(data) {
this.$store.state.notifCount = data
},
},
},
}
</script>
|
2302_79757062/drive
|
frontend/src/components/Sidebar.vue
|
Vue
|
agpl-3.0
| 5,803
|
<template>
<button
class="flex h-7 w-full cursor-pointer items-center rounded text-gray-700 duration-300 ease-in-out focus:outline-none focus:transition-none focus-visible:rounded focus-visible:ring-2 focus-visible:ring-gray-400"
:class="isActive ? 'bg-white shadow-sm' : 'hover:bg-gray-100'"
@click="handleClick"
>
<div
class="flex w-full items-center justify-between duration-300 ease-in-out p-2"
>
<div class="flex items-center">
<Tooltip
:text="label"
placement="right"
arrow-class="fill-gray-900"
:disabled="!isCollapsed"
>
<slot name="icon">
<span class="grid h-4.5 w-4.5 flex-shrink-0 place-items-center">
<FeatherIcon
v-if="typeof icon == 'string'"
:name="icon"
class="h-4.5 w-4.5 text-gray-700"
/>
<component :is="icon" v-else class="h-4.5 w-4.5 text-gray-700" />
</span>
</slot>
</Tooltip>
<span
class="flex-1 flex-shrink-0 text-sm duration-300 ease-in-out"
:class="
isCollapsed
? 'ml-0 w-0 overflow-hidden opacity-0'
: 'ml-2 w-auto opacity-100'
"
>
{{ label }}
</span>
</div>
<slot name="right" />
</div>
</button>
</template>
<script setup>
import { Tooltip, FeatherIcon } from "frappe-ui"
import { computed } from "vue"
import { useStore } from "vuex"
import { useRouter } from "vue-router"
const router = useRouter()
const store = useStore()
const props = defineProps({
icon: {
type: [String, Object],
default: null,
},
label: {
type: String,
default: "",
},
to: {
type: [Object, String],
default: "",
},
isCollapsed: {
type: Boolean,
default: false,
},
})
function handleClick() {
router.push({ path: props.to })
}
let isActive = computed(() => {
return store.state.currentBreadcrumbs[0].label === props.label
})
</script>
|
2302_79757062/drive
|
frontend/src/components/SidebarItem.vue
|
Vue
|
agpl-3.0
| 2,052
|
<template>
<div
v-if="!maxStorage.loading && !storageUsed.loading"
class="flex flex-col hover:bg-gray-100 rounded cursor-pointer mb-0.5"
@click="emitter.emit('showSettings', 3)"
>
<SidebarItem
:label="isExpanded ? 'Storage' : '3.5GB used out of 50GB'"
:is-collapsed="!isExpanded"
>
<template #icon>
<Cloud class="w-4" />
</template>
</SidebarItem>
<div class="w-auto mx-2 bg-gray-300 rounded-full h-1 my-2">
<div
class="bg-black h-1 rounded-full"
:style="{
width: calculatePercent,
maxWidth: '100%',
}"
></div>
</div>
<span
class="mx-2 text-xs text-gray-600 transition-all duration-500 ease-in-out line-clamp-1"
:class="
isExpanded
? 'ml-2 w-auto opacity-100 h-auto'
: 'ml-0 w-0 overflow-hidden opacity-0 h-0'
"
>{{ formatedString }}</span
>
</div>
</template>
<script setup>
import { ref, computed, inject } from "vue"
import { useStore } from "vuex"
import { createResource } from "frappe-ui"
import SidebarItem from "./SidebarItem.vue"
import Cloud from "./EspressoIcons/Cloud.vue"
import { formatSize, base2BlockSize } from "@/utils/format"
const emitter = inject("emitter")
const usedStorage = ref(0)
const storageMax = ref(5368709120)
const store = useStore()
const isExpanded = computed(() => {
return store.state.IsSidebarExpanded
})
const formatedString = computed(() => {
return (
formatSize(usedStorage.value) +
" used out of " +
base2BlockSize(storageMax.value)
)
})
const calculatePercent = computed(() => {
let num = (100 * usedStorage.value) / storageMax.value
return new Intl.NumberFormat("default", {
style: "percent",
minimumFractionDigits: 1,
maximumFractionDigits: 1,
}).format(num / 100)
})
let maxStorage = createResource({
url: "drive.api.storage.get_max_storage",
method: "GET",
cache: "max_storage",
onSuccess(data) {
if (!data) data = 0
storageMax.value = data
},
onError(error) {
if (error.messages) {
console.log(error.messages)
}
},
auto: true,
})
let storageUsed = createResource({
url: "drive.api.storage.total_storage_used",
onSuccess(data) {
data = data[0].total_size
if (!data) data = 0
usedStorage.value = data
},
onError(error) {
if (error.messages) {
console.log(error.messages)
}
},
auto: true,
})
</script>
|
2302_79757062/drive
|
frontend/src/components/StorageBar.vue
|
Vue
|
agpl-3.0
| 2,449
|
<template>
<div
class="inline-flex gap-1 items-center justify-center text-gray-800 border hover:bg-gray-200 h-7 text-base px-2 rounded group"
>
<button
v-if="entity.owner === 'You'"
class="hidden group-hover:block"
icon="x"
@click="$resources.removeTag.submit()"
>
<FeatherIcon
class="my-auto h-4 w-4 stroke-2"
name="x"
@click="$resources.removeTag.submit()"
/>
</button>
<svg
:class="entity.owner === 'You' ? 'block group-hover:hidden' : 'block'"
width="16"
height="16"
viewBox="0 0 16 16"
fill="none"
xmlns="http://www.w3.org/2000/svg"
>
<circle
cx="8"
cy="8"
r="4.5"
fill="transparent"
:stroke="tag.color"
stroke-width="3"
/>
</svg>
<span class="text-base text-gray-800">
{{ tag.title }}
</span>
</div>
</template>
<!-- <Popover transition="default">
<template #target="{ togglePopover }">
<Badge
class="text-base font-medium px-2"
variant="subtle"
:theme="`${tag.color}`"
:style="{
cursor: entity.owner === 'You' ? 'pointer' : 'default',
}"
@click="
if (entity.owner === 'You');
togglePopover()
"
>
<span class="text-sm">{{ `${tag.title}` }}</span>
<FeatherIcon
v-if="entity.owner === 'You'"
class="my-auto h-3 stroke-2"
name="x"
@click="$resources.removeTag.submit()"
/>
</Badge>
</template>
<template #body-main="{ togglePopover }">
<div class="bg-white rounded shadow-md p-1 z-10 space-y-0.5 absolute">
<Popover
placement="right"
trigger="hover"
:hover-delay="0.5"
:leave-delay="0.6"
>
<template #target>
<div
class="hover:bg-gray-100 cursor-pointer rounded flex items-center px-1.5 py-1 w-24"
>
<FeatherIcon name="droplet" class="w-4 h-4 text-gray-700 mr-1" />
<div class="text-gray-800 text-base">Color</div>
<FeatherIcon
name="chevron-right"
class="w-4 h-4 text-gray-700 ml-auto"
/>
</div>
</template>
<template #body-main="{ togglePopover: toggleColors }">
<div class="p-1 space-x-1 flex">
<button
v-for="color in colors"
:key="color"
:class="`h-5 w-5 rounded-full bg-${
color === 'orange' ? 'amber' : color
}-600`"
@click="
$resources.updateColor.submit({
tag: tag.name,
color: color,
}),
toggleColors()
"
/>
</div>
</template>
</Popover>
<div
v-for="item in tagActions"
:key="item"
class="hover:bg-gray-100 cursor-pointer rounded flex items-center px-1.5 py-1 w-24"
@click="item.handler(), togglePopover()"
>
<FeatherIcon :name="item.icon" class="w-4 h-4 text-gray-700 mr-1" />
<div class="text-gray-800 text-base">{{ item.label }}</div>
</div>
</div>
</template>
</Popover> -->
<script>
import { Badge, Popover, FeatherIcon } from "frappe-ui"
export default {
name: "Tag",
components: {
Popover,
Badge,
FeatherIcon,
},
props: {
entity: {
type: Object,
required: true,
default: null,
},
tag: {
type: Object,
required: true,
default: null,
},
},
emits: ["success"],
data() {
return {
colors: ["gray", "blue", "green", "orange", "red"],
tagActions: [
{
label: "Delete",
icon: "trash-2",
handler: () => {
this.$resources.deleteTag.submit()
},
},
],
}
},
resources: {
updateColor() {
return {
url: "drive.api.tags.update_tag_color",
onSuccess() {
this.$emit("success")
},
}
},
removeTag() {
return {
url: "drive.api.tags.remove_tag",
params: {
entity: this.entity.name,
tag: this.tag.name,
},
onSuccess() {
this.$emit("success")
},
}
},
deleteTag() {
return {
url: "drive.api.tags.delete_tag",
params: {
tag: this.tag.name,
},
onSuccess() {
this.$emit("success")
},
}
},
},
}
</script>
|
2302_79757062/drive
|
frontend/src/components/Tag.vue
|
Vue
|
agpl-3.0
| 4,699
|
<template>
<div class="w-full">
<Popover>
<template #target="{ open: openPopover, togglePopover }">
<slot name="target" v-bind="{ open: openPopover, togglePopover }">
<div
v-on-outside-click="closePopover()"
class="flex items-center justify-start w-full flex-wrap gap-y-4 gap-x-2"
>
<Tag
v-for="tag in $resources.entityTags.data"
:key="tag.name"
:tag="tag"
:entity="entity"
>
</Tag>
<span
v-if="!$resources.entityTags.data?.length"
class="text-gray-700 text-base"
>
This file has no tags
</span>
<Button class="ml-auto" @click="togglePopover()">Add Tag</Button>
</div>
</slot>
</template>
<template #body="{ isOpen, togglePopover }">
<div
v-show="isOpen"
class="relative mt-1 rounded-lg bg-white text-base shadow-2xl min-h-auto"
>
<div class="px-1.5 pb-1.5">
<Input
class="bg-white py-1.5"
placeholder="Search"
v-model="tagInputText"
v-focus
v-on-outside-click="closeInput"
type="text"
@input="tagInputText = $event"
@keydown.enter="
(e) =>
$resources.createTag.submit({
title: tagInputText.trim(),
color: randomColor(),
})
"
/>
<ul
v-if="filteredTags?.length"
class="flex flex-col items-start justify-start max-h-[8rem] overflow-y-auto"
>
<li
v-for="item in filteredTags"
:key="item"
class="flex items-center justify-start px-1.5 py-1 hover:bg-gray-100 w-full rounded cursor-pointer"
@click="
$resources.addTag.submit({
entity: entity.name,
tag: item.name,
})
"
>
<div
class="flex items-center-justify-start rounded-[7px] px-1.5 py-1 gap-1"
:class="`bg-${item.color}-500 bg-opacity-10`"
>
<svg
class="ml-auto"
width="16"
height="16"
viewBox="0 0 16 16"
fill="none"
xmlns="http://www.w3.org/2000/svg"
>
<circle
cx="8"
cy="8"
r="4.5"
fill="transparent"
:stroke="item.color"
stroke-width="3"
/>
</svg>
<span class="text-base" :class="`text-${item.color}-700`">
{{ item.title }}
</span>
</div>
</li>
</ul>
<span
class="rounded-md px-2.5 py-1.5 text-base text-gray-600"
v-else
>No tags found</span
>
</div>
<div class="flex items-center justify-end border-t p-1">
<Button
@click="
(e) =>
$resources.createTag.submit({
title: tagInputText.trim(),
color: randomColor(),
})
"
v-if="tagInputText"
class="mr-auto px-2 py-1.5 hover:bg-gray-100 rounded cursor-pointer"
>
Create tag "{{ tagInputText }}"
</Button>
<Button
@click="$resources.removeTag.submit()"
class="px-2 py-1.5 hover:bg-gray-100 rounded cursor-pointer"
>
Clear all
</Button>
</div>
</div>
</template>
</Popover>
</div>
</template>
<!-- <Popover transition="default" :show="hackyFlag && filteredTags.length">
<template #target>
<Input
v-model="tagInputText"
v-focus
v-on-outside-click="closeInput"
type="text"
class="w-full"
@input="tagInputText = $event"
@keydown.enter="
(e) =>
$resources.createTag.submit({
title: e.target.value.trim(),
})
"
/>
</template>
<template #body-main>
<div class="p-1" @click.stop>
<div v-for="tag in filteredTags" :key="tag.name">
<div
:class="`hover:bg-gray-100 cursor-pointer rounded-md py-1.5 px-2 text-gray-800 text-base`"
@click="
$resources.addTag.submit({
entity: entity.name,
tag: tag.name,
})
"
>
{{ tag.title }}
</div>
</div>
</div>
</template>
</Popover> -->
<!-- <div class="flex items-center justify-start flex-wrap gap-y-4">
<div
v-if="$resources.entityTags.data?.length"
class="flex flex-wrap gap-2 max-w-full"
>
<Tag
v-for="tag in $resources.entityTags?.data"
:key="tag"
:tag="tag"
:entity="entity"
@success="
() => {
$resources.userTags.fetch()
$resources.entityTags.fetch()
}
"
/>
</div>
<span v-else-if="!showTagInput" class="text-gray-700 text-base">
This file has no tags
</span>
<Button
v-if="!showTagInput && entity.owner === 'You'"
class="ml-auto"
@click="showTagInput = true"
>
Add tag
</Button>
<Input
v-if="showTagInput"
:entity="entity"
:unadded-tags="unaddedTags"
@success="
() => {
$resources.userTags.fetch()
$resources.entityTags.fetch()
showTagInput = false
}
"
@close="showTagInput = false"
/>
</div> -->
<script>
import { getRandomColor } from "@/utils/random-color"
import { Input, Popover, FeatherIcon } from "frappe-ui"
import Tag from "./Tag.vue"
export default {
name: "TagInput",
components: {
Input,
Popover,
FeatherIcon,
Tag,
},
props: {
entity: {
type: Object,
required: true,
default: null,
},
},
emits: ["success", "close"],
expose: ["togglePopover"],
data() {
return {
showTagInput: false,
tagInputText: "",
hackyFlag: false, // temporary hacky flag to circumvent v-on-outside-click from running on mounting
}
},
computed: {
unaddedTags() {
return this.$resources.userTags?.data?.filter(
({ name: id1 }) =>
!this.$resources.entityTags?.data?.some(
({ name: id2 }) => id2 === id1
)
)
},
filteredTags() {
return this.unaddedTags?.filter((x) =>
x.title.toLowerCase().startsWith(this.tagInputText.toLowerCase())
)
},
},
methods: {
togglePopover(val) {
this.showTagInput = val ?? !this.showTagInput
},
randomColor() {
return getRandomColor()
},
closeInput() {
if (this.hackyFlag) this.$emit("close")
this.hackyFlag = !this.hackyFlag
},
},
resources: {
userTags() {
return {
url: "drive.api.tags.get_user_tags",
onError(error) {
if (error.messages) {
console.log(error.messages)
}
},
auto: true,
}
},
entityTags() {
return {
url: "drive.api.tags.get_entity_tags",
params: { entity: this.entity.name },
onError(error) {
if (error.messages) {
console.log(error.messages)
}
},
auto: true,
}
},
createTag() {
return {
url: "drive.api.tags.create_tag",
onSuccess(data) {
this.$resources.addTag.submit({
entity: this.entity.name,
tag: data,
})
},
onError(error) {
if (error.messages) {
console.log(error.messages)
}
},
}
},
removeTag() {
return {
url: "drive.api.tags.remove_tag",
params: {
entity: this.entity.name,
all: true,
},
onSuccess() {
this.$resources.entityTags.fetch()
this.$emit("success")
},
}
},
addTag() {
return {
url: "drive.api.tags.add_tag",
onSuccess() {
this.$emit("success")
this.$resources.entityTags.fetch()
this.$resources.userTags.fetch()
},
onError(error) {
if (error.messages) {
console.log(error.messages)
}
},
}
},
},
}
</script>
|
2302_79757062/drive
|
frontend/src/components/TagInput.vue
|
Vue
|
agpl-3.0
| 9,092
|
<template>
<div
class="flex items-center min-h-7 justify-start border border-gray-200 rounded pl-2 pr-1 py-0.5 hover:border-gray-200 focus-within:bg-white focus-within:border-gray-500 focus-within:shadow-sm focus-within:ring-2 focus-within:ring-gray-400 text-gray-800 transition-colors w-full"
>
<editor-content class="w-full" :editor="editor" />
<!-- Take this out later -->
<Button
v-if="showInlineButton"
class="mt-auto ml-auto hover:bg-gray-300 min-w-7 aspect-square cursor-pointer"
:variant="'ghost'"
icon="arrow-up-circle"
:disabled="!modelValue.length"
@click="$emit('success', modelValue)"
></Button>
</div>
</template>
<script>
import { Button } from "frappe-ui"
import { normalizeClass } from "vue"
import { Document } from "@/components/DocEditor/extensions/document"
import { Paragraph } from "@/components/DocEditor/extensions/paragraph"
import { Text } from "@/components/DocEditor/extensions/text"
import { Editor, EditorContent } from "@tiptap/vue-3"
import { Placeholder } from "./DocEditor/extensions/placeholder"
export default {
components: {
EditorContent,
Button,
},
props: {
modelValue: {
type: String,
default: "",
},
showInlineButton: {
type: Boolean,
default: true,
required: false,
},
},
emits: ["update:modelValue", "success"],
data() {
return {
editor: null,
}
},
watch: {
modelValue(value) {
const isSame = this.editor.getHTML() === value
if (isSame) {
return
}
this.editor.commands.setContent(value, false)
},
},
mounted() {
this.editor = new Editor({
autofocus: true,
extensions: [
Document,
Paragraph,
Text,
Placeholder.configure({
placeholder: "Ctrl + Enter to post",
}),
],
editorProps: {
attributes: {
class: normalizeClass([
`text-sm !p-0 min-w-full placeholder-gray-500 bg-gray-100 !bg-transparent border-0 resize-none focus:outline-0 focus:border-0 active:outline-0 hover:bg-transparent`,
]),
},
},
content: this.modelValue,
onUpdate: () => {
this.$emit("update:modelValue", this.editor.getHTML())
},
})
},
beforeUnmount() {
this.editor.destroy()
},
}
</script>
|
2302_79757062/drive
|
frontend/src/components/TiptapInput.vue
|
Vue
|
agpl-3.0
| 2,367
|
<template>
<div
class="my-2 min-w-[15rem] max-w-[45rem] rounded-md border bg-white p-3 shadow-[0_4px_12px_#0000001a]"
>
<div class="flex place-items-center">
<FeatherIcon
v-if="icon"
:name="icon"
:class="['h-4.5 w-4.5 mr-2', iconClasses]"
/>
<Avatar
v-else-if="avatarURL"
:label="avatarLabel"
:image="avatarURL"
size="sm"
:class="['mr-2']"
>
</Avatar>
<div>
<slot>
<p
v-if="title"
class="text-base font-medium text-gray-900"
:class="{ 'mb-1': text }"
>
{{ title }}
</p>
<p v-if="text" class="text-sm text-gray-600">
{{ text }}
</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"
@click="$emit('close')"
>
<FeatherIcon name="x" class="h-4 w-4 text-gray-700" />
</button>
</slot>
</div>
</div>
</div>
</template>
<script>
import { FeatherIcon } from "frappe-ui"
import Avatar from "frappe-ui/src/components/Avatar.vue"
export default {
name: "Toast",
components: {
FeatherIcon,
Avatar,
},
props: {
position: {
type: String,
default: "top-center",
},
icon: {
type: String,
default: "",
},
iconClasses: {
type: String,
default: "",
},
avatarURL: {
type: String,
default: "",
},
avatarLabel: {
type: String,
default: "",
},
title: {
type: String,
default: "",
},
text: {
type: String,
default: "",
},
timeout: {
type: Number,
default: 5,
},
},
emits: ["close"],
mounted() {
if (this.timeout > 0) {
setTimeout(() => {
this.$emit("close")
}, this.timeout * 1000)
}
},
}
</script>
|
2302_79757062/drive
|
frontend/src/components/Toast.vue
|
Vue
|
agpl-3.0
| 2,021
|
<template>
<div
class="flex flex-col items-start fixed bottom-0 right-0 w-full m-5 sm:w-96 z-10 rounded-2xl overflow-hidden shadow-2xl 500 bg-white p-4"
>
<div
class="flex items-center justify-between w-full mb-4 pr-1.5"
:class="[collapsed ? 'cursor-pointer' : '']"
@click="collapsed = false"
>
<div
v-if="uploadsInProgress.length > 0"
class="font-medium truncate text-lg"
>
Uploading {{ uploadsInProgress.length }}
{{ uploadsInProgress.length == 1 ? "file" : "files" }}
</div>
<div
v-else-if="uploadsCompleted.length > 0"
class="font-medium truncate text-lg"
>
{{ uploadsCompleted.length }}
{{ uploadsCompleted.length == 1 ? "upload" : "uploads" }} complete
</div>
<div
v-else-if="uploadsFailed.length > 0"
class="font-medium truncate text-lg"
>
{{ uploadsFailed.length }}
{{ uploadsFailed.length == 1 ? "upload" : "uploads" }} failed
</div>
<div class="ml-auto flex items-center gap-4">
<button
v-if="!collapsed"
class="focus:outline-none"
@click.stop="toggleCollapsed"
>
<FeatherIcon name="minus" class="h-4 w-4 text-gray-800" />
</button>
<button class="focus:outline-none" @click="close">
<FeatherIcon name="x" class="h-4 w-4 text-gray-800" />
</button>
</div>
</div>
<div
class="bg-gray-100 rounded-[10px] space-x-0.5 h-7 flex items-center px-0.5 py-1 mb-2"
>
<Button
variant="ghost"
class="max-h-6 leading-none transition-colors focus:outline-none"
:class="[
currentTab === 1
? 'bg-white shadow-sm hover:bg-white active:bg-white'
: '',
]"
@click="currentTab = 1"
>
In Progress
</Button>
<Button
variant="ghost"
class="max-h-6 leading-none transition-colors focus:outline-none"
:class="[
currentTab === 2
? 'bg-white shadow-sm hover:bg-white active:bg-white'
: '',
]"
@click="currentTab = 2"
>
Completed
</Button>
<Button
v-show="uploadsFailed.length > 0"
variant="ghost"
class="max-h-6 leading-none transition-colors focus:outline-none"
:class="[
currentTab === 3
? 'bg-white shadow-sm hover:bg-white active:bg-white'
: '',
]"
@click="currentTab = 3"
>
Failed
</Button>
</div>
<div v-if="!collapsed" class="max-h-64 overflow-y-auto bg-white w-full">
<span
v-if="!currentTabGetter().length"
class="px-1.5 text-base font-medium text-gray-800"
>{{ emptyMessage }}</span
>
<div
v-for="(upload, index) in currentTabGetter()"
:key="upload.uuid"
class="cursor-pointer truncate hover:bg-gray-50 rounded px-1 group"
@mouseover="hoverIndex = index"
@mouseout="hoverIndex = null"
>
<div
class="flex items-center gap-3 py-2 pr-[3px]"
@click="openFile(upload)"
>
<div class="flex items-center justify-between w-full">
<div class="flex justify-start items-center w-full max-w-[80%]">
<File class="w-5 mr-2" />
<p class="truncate text-sm leading-6 col-span-1 row-span-1">
{{ upload.name }}
</p>
</div>
<div
v-if="upload.completed && hoverIndex !== index"
class="grid h-5 w-5 place-items-center rounded-full text-white bg-black"
:class="upload.error ? 'bg-red-500' : 'bg-black'"
>
<FeatherIcon
:name="upload.error ? 'x' : 'check'"
class="h-3 w-3"
:stroke-width="3"
/>
</div>
<FeatherIcon
v-if="upload.completed && hoverIndex === index"
class="h-4.5 w-4.5 place-items-center"
name="external-link"
:stroke-width="1.5"
/>
<button
v-if="hoverIndex === index"
v-show="!upload.completed && hoverIndex === index"
class="rounded-full hover:bg-red-300"
variant="'ghost'"
@click="emitter.emit('cancelUpload', upload.uuid)"
>
<FeatherIcon name="x" class="h-6 w-6 p-1" />
</button>
<div
v-if="hoverIndex !== index"
v-show="!upload.completed && !upload.error"
class="h-6 w-6"
>
<ProgressRing :radius="14" :progress="upload.progress" />
</div>
</div>
</div>
</div>
</div>
<Dialog
v-if="showErrorDialog"
v-model="showErrorDialog"
:options="{
title: 'Upload Failed',
message: selectedUpload.error,
size: 'sm',
actions: [
{
label: 'Confirm',
onClick: () => {
showErrorDialog = false
},
},
],
}"
/>
<Dialog
v-if="showCancelDialog"
v-model="showCancelDialog"
:options="{
title: 'Cancel uploads',
message: 'Are you sure you want to cancel all ongoing uploads?',
size: 'sm',
actions: [
{
label: 'Confirm',
variant: 'subtle',
theme: 'red',
onClick: () => {
emitter.emit('cancelAllUploads')
showCancelDialog = false
$store.dispatch('clearUploads')
},
},
],
}"
/>
</div>
</template>
<script>
import { mapGetters } from "vuex"
import { FeatherIcon } from "frappe-ui"
import ProgressRing from "@/components/ProgressRing.vue"
import Dialog from "frappe-ui/src/components/Dialog.vue"
import File from "./EspressoIcons/File.vue"
export default {
name: "UploadTracker",
components: {
FeatherIcon,
ProgressRing,
Dialog,
File,
},
data() {
return {
collapsed: false,
hoverIndex: null,
showCancelDialog: false,
showErrorDialog: false,
selectedUpload: null,
currentTab: 1,
emptyMessage: "No uploads in progress",
}
},
computed: {
uploads() {
return this.$store.state.uploads
},
...mapGetters(["uploadsInProgress", "uploadsCompleted", "uploadsFailed"]),
},
methods: {
currentTabGetter() {
switch (this.currentTab) {
case 1:
this.emptyMessage = "No uploads in progress"
return this.uploadsInProgress
case 2:
this.emptyMessage = "No uploads completed"
return this.uploadsCompleted
case 3:
this.emptyMessage = "No failed uploads"
return this.uploadsFailed
default:
this.emptyMessage = "No uploads completed"
return this.uploadsCompleted
}
},
openFile(upload) {
this.selectedUpload = upload
if (upload.error) {
console.log(upload.response)
this.showErrorDialog = true
}
if (upload.completed && upload.response) {
this.$router.push({
name: "File",
params: { entityName: upload.response.name },
})
}
},
toggleCollapsed() {
this.collapsed = !this.collapsed
},
close() {
if (this.uploads.length === this.uploadsCompleted.length) {
this.$store.dispatch("clearUploads")
} else {
this.showCancelDialog = true
}
},
},
}
</script>
|
2302_79757062/drive
|
frontend/src/components/UploadTracker.vue
|
Vue
|
agpl-3.0
| 7,702
|
<template>
<button
class="flex items-center rounded-md text-left m-2"
:style="{
width: isExpanded ? '200px' : 'auto',
}"
@click="() => $router.push({ name: 'Home' })"
>
<FrappeDriveLogo class="w-8 h-8 rounded" />
<div v-if="isExpanded" class="ml-2 flex flex-col">
<div class="text-base font-medium text-gray-900 leading-none">
Frappe Drive
</div>
</div>
</button>
<Settings v-if="showSettings" v-model="showSettings" />
</template>
<script>
import Settings from "@/components/Settings.vue"
import FrappeDriveLogo from "@/components/FrappeDriveLogo.vue"
export default {
name: "UserDropdown",
components: {
Settings,
FrappeDriveLogo,
},
data: () => ({
showSettings: false,
}),
computed: {
isExpanded() {
return this.$store.state.IsSidebarExpanded
},
firstName() {
return this.$store.state.user.fullName.split(" ")
},
fullName() {
return this.$store.state.user.fullName
},
imageURL() {
return this.$store.state.user.imageURL
},
settingsItems() {
if (this.$resources.isAdmin?.data) {
return [
{
icon: "settings",
label: "Settings",
onClick: () => (this.showSettings = true),
},
{
icon: "log-out",
label: "Log out",
onClick: () => this.logout(),
},
]
}
return [
{
icon: "log-out",
label: "Log out",
onClick: () => this.logout(),
},
]
},
},
methods: {
logout() {
this.$store.dispatch("logout")
},
},
resources: {
isAdmin() {
return {
url: "drive.utils.users.is_drive_admin",
cache: "is_admin",
params: {
doctype: "Drive Instance Settings",
},
onError(error) {
if (error.messages) {
this.errorMessage = error.messages.join("\n")
} else {
this.errorMessage = error.message
}
},
auto: true,
}
},
},
}
</script>
|
2302_79757062/drive
|
frontend/src/components/UserDropdown.vue
|
Vue
|
agpl-3.0
| 2,116
|
<template>
<Popover
transition="default"
placement="bottom-end"
popover-class="border-t-8 border-transparent"
>
<template #target="{ togglePopover }">
<div
class="ml-2.5 flex items-center rounded-md cursor-pointer"
@click="togglePopover()"
>
<div
v-for="user in connectedUsers"
:key="user.name"
class="-ml-2.5 -py-0.5 flex items-center rounded-full"
>
<Avatar
class="-"
:size="'md'"
:style="{
border: '2px solid',
borderRadius: '100%',
borderColor: user.color,
}"
:image="user.avatar"
:label="user.name"
:title="user.name"
/>
</div>
</div>
</template>
<template #body-main>
<div class="px-3 py-1">
<div
v-for="user in connectedUsers"
:key="user.name"
class="flex justifty items-center gap-2 py-1"
>
<Avatar
:size="'md'"
:image="user.avatar"
:label="user.name"
:title="user.name"
/>
<span class="text-sm text-gray-800 mr-4">{{ user.name }}</span>
<svg
class="ml-auto"
width="16"
height="16"
viewBox="0 0 16 16"
fill="none"
xmlns="http://www.w3.org/2000/svg"
>
<circle
cx="8"
cy="8"
r="4.5"
fill="transparent"
:stroke="user.color"
stroke-width="3"
/>
</svg>
</div>
</div>
</template>
</Popover>
</template>
<script>
import { Avatar, Popover } from "frappe-ui"
import { mapState } from "vuex"
export default {
name: "UsersBar",
components: {
Avatar,
Popover,
},
computed: mapState(["connectedUsers"]),
}
</script>
|
2302_79757062/drive
|
frontend/src/components/UsersBar.vue
|
Vue
|
agpl-3.0
| 1,950
|
<template>
<div>
<video ref="videoPlayer" preload="auto"></video>
</div>
</template>
<script>
import videojs from "video.js"
import "video.js/dist/video-js.min.css"
export default {
name: "VideoPlayer",
props: {
options: {
type: Object,
default() {
return {}
},
},
},
data() {
return {
player: null,
}
},
mounted() {
this.player = videojs(this.$refs.videoPlayer, this.options, () => {
this.player.log("onPlayerReady", this)
this.player.fluid(true)
})
},
beforeUnmount() {
if (this.player) {
this.player.dispose()
}
},
}
</script>
|
2302_79757062/drive
|
frontend/src/components/VideoPlayer.vue
|
Vue
|
agpl-3.0
| 640
|
<template>
<svg
width="24"
height="24"
viewBox="0 0 24 24"
fill="none"
xmlns="http://www.w3.org/2000/svg"
>
<path
d="M12 17V3"
stroke="black"
stroke-width="1.5"
stroke-linecap="round"
stroke-linejoin="round"
/>
<path
d="M6 11L12 17L18 11"
stroke="black"
stroke-width="1.5"
stroke-linecap="round"
stroke-linejoin="round"
/>
<path
d="M19 21H5"
stroke="black"
stroke-width="1.5"
stroke-linecap="round"
stroke-linejoin="round"
/>
<path
d="M2 2L22 22"
stroke="black"
stroke-width="1.5"
stroke-linecap="round"
stroke-linejoin="round"
/>
</svg>
</template>
|
2302_79757062/drive
|
frontend/src/components/arrow-down-to-line-off.vue
|
Vue
|
agpl-3.0
| 728
|
<template>
<svg
width="24"
height="24"
viewBox="0 0 24 24"
fill="none"
xmlns="http://www.w3.org/2000/svg"
>
<path
d="M3 21L4.9 15.3C3.99713 13.4948 3.76612 11.4272 4.2483 9.46721C4.73049 7.50724 5.8944 5.78282 7.53176 4.60254C9.16911 3.42225 11.173 2.86315 13.1849 3.02527C15.1968 3.18739 17.0854 4.06017 18.5126 5.4874C19.9398 6.91463 20.8126 8.80318 20.9747 10.8151C21.1369 12.827 20.5777 14.8309 19.3975 16.4682C18.2172 18.1056 16.4928 19.2695 14.5328 19.7517C12.5728 20.2339 10.5052 20.0029 8.7 19.1L3 21Z"
stroke="black"
stroke-width="1.5"
stroke-linecap="round"
stroke-linejoin="round"
/>
<path
d="M2 2L22 22"
stroke="black"
stroke-width="1.5"
stroke-linecap="round"
stroke-linejoin="round"
/>
</svg>
</template>
|
2302_79757062/drive
|
frontend/src/components/message-circle-off.vue
|
Vue
|
agpl-3.0
| 821
|
import mitt from "mitt"
const emitter = mitt()
export default emitter
|
2302_79757062/drive
|
frontend/src/event-bus.js
|
JavaScript
|
agpl-3.0
| 71
|
/* frappe ui includes Inter*/
@import "frappe-ui/src/style.css";
* {
scrollbar-width: thin;
scrollbar-color: #c0c6cc #ebeef0;
}
html {
scrollbar-width: auto;
}
*::-webkit-scrollbar-thumb {
background: #c0c6cc;
border-radius: 6px;
}
*::-webkit-scrollbar-track,
*::-webkit-scrollbar-corner {
background: #ebeef0;
}
*::-webkit-scrollbar {
width: 6px;
height: 6px;
}
body::-webkit-scrollbar {
width: 12px;
height: 12px;
}
body {
overflow: hidden;
}
|
2302_79757062/drive
|
frontend/src/index.css
|
CSS
|
agpl-3.0
| 474
|
import { createApp } from "vue"
import {
FrappeUI,
Button,
onOutsideClickDirective,
setConfig,
frappeRequest,
resourcesPlugin,
} from "frappe-ui"
import store from "./store"
import router from "./router"
import App from "./App.vue"
import emitter from "./event-bus"
import "./index.css"
import VueTippy from "vue-tippy"
import { initSocket, RealTimeHandler } from "./socket"
setConfig("resourceFetcher", frappeRequest)
const app = createApp(App)
app.config.unwrapInjectedRef = true
app.config.globalProperties.emitter = emitter
app.provide("emitter", emitter)
app.use(router)
app.use(store)
app.use(FrappeUI, { socketio: false })
const socket = initSocket()
const realtime = new RealTimeHandler(socket)
app.provide("realtime", realtime)
app.config.globalProperties.$realtime = realtime
app.directive("on-outside-click", onOutsideClickDirective)
app.use(
VueTippy,
// optional
{
directive: "tippy", // => v-tippy
component: "tippy", // => <tippy/>
}
)
app.directive("focus", {
mounted: (el) => el.focus(),
})
setConfig("resourceFetcher", (options) => {
return frappeRequest({
...options,
onError(err) {
if (err.messages && err.messages[0]) {
return
}
},
})
})
app.component("Button", Button)
app.mount("#app")
|
2302_79757062/drive
|
frontend/src/main.js
|
JavaScript
|
agpl-3.0
| 1,278
|
<template>
<div class="flex w-full">
<TextEditor
v-if="contentLoaded"
v-model:yjsContent="yjsContent"
v-model:rawContent="rawContent"
v-model:lastSaved="lastSaved"
v-model:settings="settings"
:user-list="allUsers"
:fixed-menu="true"
:bubble-menu="true"
:timeout="timeout"
:is-writable="isWritable"
:entity-name="entityName"
:entity="entity"
@mentioned-users="(val) => (mentionedUsers = val)"
@save-document="saveDocument"
/>
<ShareDialog
v-if="showShareDialog"
v-model="showShareDialog"
:entity-name="entityName"
/>
</div>
</template>
<script setup>
import { fromUint8Array, toUint8Array } from "js-base64"
import {
ref,
computed,
inject,
onMounted,
defineAsyncComponent,
onBeforeUnmount,
} from "vue"
import { useRouter } from "vue-router"
import { useStore } from "vuex"
import { formatSize, formatDate } from "@/utils/format"
import { createResource } from "frappe-ui"
import { watchDebounced } from "@vueuse/core"
const TextEditor = defineAsyncComponent(() =>
import("@/components/DocEditor/TextEditor.vue")
)
const ShareDialog = defineAsyncComponent(() =>
import("@/components/ShareDialog/ShareDialog.vue")
)
const store = useStore()
const router = useRouter()
const emitter = inject("emitter")
const props = defineProps({
entityName: {
type: String,
required: false,
default: "",
},
})
// Reactive data properties
const oldTitle = ref(null)
const title = ref(null)
const yjsContent = ref(null)
const settings = ref(null)
const rawContent = ref(null)
const contentLoaded = ref(false)
const isWritable = ref(false)
const entity = ref(null)
const allUsers = ref([])
const mentionedUsers = ref()
const showShareDialog = ref(false)
const timeout = ref(1000 + Math.floor(Math.random() * 5000))
const saveCount = ref(0)
const lastSaved = ref(0)
const titleVal = computed(() => title.value || oldTitle.value)
const comments = computed(() => store.state.allComments)
const userId = computed(() => store.state.auth.user_id)
let intervalId = ref(null)
setTimeout(() => {
watchDebounced(
rawContent,
() => {
const now = Date.now()
if (now - lastSaved.value >= timeout.value) {
saveDocument()
}
},
{ debounce: timeout.value, maxWait: 30000 }
)
}, 1500)
const saveDocument = () => {
if (isWritable.value) {
updateDocument.submit({
entity_name: props.entityName,
doc_name: entity.value.document,
title: titleVal.value,
content: fromUint8Array(yjsContent.value),
raw_content: rawContent.value,
settings: settings.value,
comments: comments.value,
mentions: mentionedUsers.value,
file_size: fromUint8Array(yjsContent.value).length,
})
}
}
const getDocument = createResource({
url: "drive.api.permissions.get_entity_with_permissions",
method: "GET",
auto: true,
params: {
entity_name: props.entityName,
},
onSuccess(data) {
data.size_in_bytes = data.file_size
data.file_size = formatSize(data.file_size)
data.modified = formatDate(data.modified)
data.creation = formatDate(data.creation)
store.commit("setEntityInfo", [data])
if (!data.settings) {
data.settings =
'{ "docWidth": false, "docSize": true, "docFont": "font-fd-sans", "docHeader": false, "docHighlightAnnotations": false, "docSpellcheck": false}'
}
settings.value = JSON.parse(data.settings)
if (!("docSpellcheck" in settings.value)) {
settings.value.docSpellcheck = 1
}
title.value = data.title
oldTitle.value = data.title
yjsContent.value = toUint8Array(data.content)
rawContent.value = data.raw_content
isWritable.value = data.owner === userId.value || !!data.write
store.commit("setHasWriteAccess", isWritable)
data.owner = data.owner === userId.value ? "You" : data.owner
entity.value = data
lastSaved.value = Date.now()
contentLoaded.value = true
let currentBreadcrumbs = [
{
label: "Shared",
route: "/shared",
},
]
const root_item = data.breadcrumbs[0]
if (root_item.name === store.state.homeFolderID) {
currentBreadcrumbs = [
{
label: "Home",
route: "/home",
},
]
data.breadcrumbs.shift()
}
data.breadcrumbs.forEach((item, idx) => {
if (idx === data.breadcrumbs.length - 1) {
currentBreadcrumbs.push({
label: item.title,
route: "/document/" + item.name,
})
} else {
currentBreadcrumbs.push({
label: item.title,
route: "/folder/" + item.name,
})
}
})
store.commit("setCurrentBreadcrumbs", currentBreadcrumbs)
},
onError(error) {
if (error && error.exc_type === "PermissionError") {
store.commit("setError", {
iconName: "alert-triangle",
iconClass: "fill-amber-500 stroke-white",
primaryMessage: "Forbidden",
secondaryMessage: "Insufficient permissions for this resource",
})
}
router.replace({ name: "Error" })
},
})
const updateDocument = createResource({
url: "drive.api.files.save_doc",
debounce: 0,
auto: false,
onSuccess() {
lastSaved.value = Date.now()
saveCount.value++
},
onError(data) {
console.log(data)
},
})
onMounted(() => {
emitter.on("showShareDialog", () => {
showShareDialog.value = true
})
if (saveCount.value > 0) {
intervalId.value = setInterval(() => {
emitter.emit("triggerAutoSnapshot")
}, 120000 + timeout.value)
}
})
onBeforeUnmount(() => {
if (saveCount.value) {
saveDocument()
}
if (intervalId.value !== null) {
clearInterval(intervalId.value)
}
})
let fetchAllUsers = createResource({
url: "drive.utils.users.get_users_with_drive_user_role_and_groups",
method: "GET",
auto: true,
onSuccess(data) {
data.forEach(function (item) {
if (item.name) {
item.value = item.name
item.label = item.name
item.type = "User Group"
delete item.name
return
}
item.value = item.email
item.label = item.full_name.trimEnd()
item.type = "User"
delete item.email
delete item.full_name
})
allUsers.value = data
},
onError(error) {
if (error.messages) {
this.errorMessage = error.messages.join("\n")
} else {
this.errorMessage = error.message
}
},
})
</script>
|
2302_79757062/drive
|
frontend/src/pages/Document.vue
|
Vue
|
agpl-3.0
| 6,484
|
<template>
<div
class="m-auto max-w-[450px] px-16 py-8 z-10 bg-white rounded-md text-neutral-100 text-xl text-center font-medium shadow-xl flex flex-col justify-center items-center"
>
<FeatherIcon
class="h-12 mb-4"
:class="store.state.error.iconClass"
:name="store.state.error.iconName"
/>
<p class="text-xl mb-2 text-black font-medium">
{{ store.state.error.primaryMessage }}
</p>
<p class="text-lg text-gray-700">
{{ store.state.error.secondaryMessage }}
</p>
<Button
variant="solid"
class="px-3 mt-2"
@click="
router.push({
name: 'Home',
})
"
>
Back to Home
</Button>
</div>
</template>
<script setup>
import { useRouter } from "vue-router"
import { useStore } from "vuex"
import { FeatherIcon, Button } from "frappe-ui"
const store = useStore()
const router = useRouter()
</script>
|
2302_79757062/drive
|
frontend/src/pages/Error.vue
|
Vue
|
agpl-3.0
| 919
|
<template>
<PageGeneric
url="drive.api.list.files"
:favourites="true"
:allow-empty-context-menu="false"
:show-sort="true"
:icon="Star"
:primaryMessage="'No Favourite Files'"
:secondaryMessage="''"
/>
</template>
<script setup>
import PageGeneric from "@/components/PageGeneric.vue"
import Star from "../components/EspressoIcons/Star.vue"
</script>
|
2302_79757062/drive
|
frontend/src/pages/Favourites.vue
|
Vue
|
agpl-3.0
| 381
|
<template>
<div
class="h-full w-full overflow-hidden flex flex-col items-center justify-start"
>
<div
id="renderContainer"
:draggable="false"
class="flex items-center justify-center h-full w-full min-h-[85vh] max-h-[85vh] mt-3"
>
<FileRender v-if="file.data" :preview-entity="file.data" />
</div>
<div
class="hidden sm:flex absolute bottom-[-1%] left-[50%] center-transform items-center justify-center p-1 gap-1 h-10 rounded-lg shadow-xl bg-white"
>
<Button
:disabled="!prevEntity?.name"
:variant="'ghost'"
icon="arrow-left"
@click="scrollEntity(true)"
></Button>
<Button :variant="'ghost'" @click="enterFullScreen">
<Scan class="w-4" />
</Button>
<!-- <Button :variant="'ghost'">
<FileSignature class="w-4"/>
</Button> -->
<Button
:disabled="!nextEntity?.name"
:variant="'ghost'"
icon="arrow-right"
@click="scrollEntity()"
></Button>
</div>
<ShareDialog
v-if="showShareDialog"
v-model="showShareDialog"
:entity-name="props.entityName"
/>
</div>
</template>
<script setup>
import { useStore } from "vuex"
import {
ref,
computed,
onMounted,
defineProps,
onBeforeUnmount,
inject,
} from "vue"
import { Button } from "frappe-ui"
import FileRender from "@/components/FileRender.vue"
import { createResource } from "frappe-ui"
import { formatSize, formatDate } from "@/utils/format"
import { useRouter } from "vue-router"
import { Scan } from "lucide-vue-next"
import { onKeyStroke } from "@vueuse/core"
import ShareDialog from "@/components/ShareDialog/ShareDialog.vue"
const router = useRouter()
const store = useStore()
const emitter = inject("emitter")
const realtime = inject("realtime")
const props = defineProps({
entityName: {
type: String,
default: null,
},
})
const entity = ref(null)
const showShareDialog = ref(false)
const currentEntity = ref(props.entityName)
const userId = computed(() => {
return store.state.auth.user_id
})
const filteredEntities = computed(() => {
if (store.state.currentViewEntites.length) {
return store.state.currentViewEntites.filter(
(item) => item.is_group === 0 && item.mime_type !== "frappe_doc"
)
} else {
return []
}
})
const currentEntityIndex = computed(() => {
return filteredEntities.value.findIndex(
(item) => item.name === props.entityName
)
})
const prevEntity = computed(() => {
return filteredEntities.value[currentEntityIndex.value - 1]
})
const nextEntity = computed(() => {
return filteredEntities.value[currentEntityIndex.value + 1]
})
function fetchFile(currentEntity) {
file.fetch({ entity_name: currentEntity }).then(() => {
router.replace({
name: "File",
params: { entityName: currentEntity },
})
})
}
function enterFullScreen() {
let elem = document.getElementById("renderContainer")
if (elem.requestFullscreen) {
elem.requestFullscreen()
} else if (elem.mozRequestFullScreen) {
/* Firefox */
elem.mozRequestFullScreen()
} else if (elem.webkitRequestFullscreen) {
/* Chrome, Safari & Opera */
elem.webkitRequestFullscreen()
} else if (elem.msRequestFullscreen) {
/* IE/Edge */
elem.msRequestFullscreen()
}
}
onKeyStroke("ArrowLeft", (e) => {
e.preventDefault()
scrollEntity(true)
})
onKeyStroke("ArrowRight", (e) => {
e.preventDefault()
scrollEntity()
})
let file = createResource({
url: "drive.api.permissions.get_entity_with_permissions",
params: { entity_name: props.entityName },
transform(data) {
entity.value = data
data.size_in_bytes = data.file_size
data.file_size = formatSize(data.file_size)
data.modified = formatDate(data.modified)
data.creation = formatDate(data.creation)
data.owner = data.owner === userId.value ? "You" : data.owner
store.commit("setEntityInfo", [data])
},
onSuccess(data) {
let currentBreadcrumbs = [
{
label: "Shared",
route: "/shared",
},
]
const root_item = data.breadcrumbs[0]
if (root_item.name === store.state.homeFolderID) {
currentBreadcrumbs = [
{
label: "Home",
route: "/home",
},
]
data.breadcrumbs.shift()
}
data.breadcrumbs.forEach((item, idx) => {
if (idx === data.breadcrumbs.length - 1) {
currentBreadcrumbs.push({
label: item.title,
route: "/file/" + item.name,
})
} else {
currentBreadcrumbs.push({
label: item.title,
route: "/folder/" + item.name,
})
}
})
store.commit("setCurrentBreadcrumbs", currentBreadcrumbs)
},
onError(error) {
if (error && error.exc_type === "PermissionError") {
store.commit("setError", {
iconName: "alert-triangle",
iconClass: "fill-amber-500 stroke-white",
primaryMessage: "Forbidden",
secondaryMessage: "Insufficient permissions for this resource",
})
}
router.replace({ name: "Error" })
},
})
function scrollEntity(negative = false) {
currentEntity.value = negative ? prevEntity.value : nextEntity.value
fetchFile(currentEntity.value.name)
}
onMounted(() => {
fetchFile(props.entityName)
realtime.doc_subscribe("Drive Entity", props.entityName)
realtime.doc_open("Drive Entity", props.entityName)
realtime.on("doc_viewers", (data) => {
store.state.connectedUsers = data.users
userInfo.submit({ users: JSON.stringify(data.users) })
})
if (window.matchMedia("(max-width: 1500px)").matches) {
store.commit("setIsSidebarExpanded", false)
}
emitter.on("showShareDialog", () => {
showShareDialog.value = true
})
})
onBeforeUnmount(() => {
realtime.off("doc_viewers")
store.state.connectedUsers = []
realtime.doc_close("Drive Entity", file.data.name)
realtime.doc_unsubscribe("Drive Entity", file.data.name)
store.commit("setEntityInfo", [])
})
let userInfo = createResource({
url: "frappe.desk.form.load.get_user_info_for_viewers",
// compatibility with document awareness
onSuccess(data) {
data = Object.values(data)
data.forEach((item) => {
if (item.fullname) {
item.avatar = item.image
item.name = item.fullname
delete item.image
delete item.fullname
}
})
store.state.connectedUsers = data
},
auto: false,
})
</script>
<style scoped>
.center-transform {
transform: translate(-50%, -50%);
}
#renderContainer::backdrop {
background-color: rgb(0, 0, 0);
min-width: 100vw;
min-height: 100vh;
position: fixed;
width: 100%;
height: 100%;
left: 0;
top: 0;
}
</style>
|
2302_79757062/drive
|
frontend/src/pages/File.vue
|
Vue
|
agpl-3.0
| 6,703
|
<template>
<PageGeneric
v-if="currentFolder.fetched"
url="drive.api.list.files"
:allow-empty-context-menu="allowEmptyContextMenu"
:show-sort="true"
:is-shared-folder="isSharedFolder"
:entity-name="entityName"
:icon="Folder"
:primaryMessage="'Folder is Empty'"
:secondaryMessage="''"
/>
</template>
<script setup>
import Folder from "../components/EspressoIcons/Folder.vue"
import PageGeneric from "@/components/PageGeneric.vue"
import { ref, inject, onMounted, onBeforeUnmount } from "vue"
import { useStore } from "vuex"
import { createResource } from "frappe-ui"
import { useRouter } from "vue-router"
import { formatDate } from "@/utils/format"
const store = useStore()
const router = useRouter()
const realtime = inject("realtime")
const isSharedFolder = ref(false)
const allowEmptyContextMenu = ref(false)
const props = defineProps({
entityName: {
type: String,
required: false,
default: "",
},
})
onMounted(() => {
realtime.doc_subscribe("Drive Entity", props.entityName)
realtime.doc_open("Drive Entity", props.entityName)
realtime.on("doc_viewers", (data) => {
store.state.connectedUsers = data.users
userInfo.submit({ users: JSON.stringify(data.users) })
})
if (window.matchMedia("(max-width: 1500px)").matches) {
store.commit("setIsSidebarExpanded", false)
}
})
onBeforeUnmount(() => {
realtime.off("doc_viewers")
store.state.connectedUsers = []
realtime.doc_close("Drive Entity", currentFolder.data.name)
realtime.doc_unsubscribe("Drive Entity", currentFolder.data.name)
store.commit("setEntityInfo", [])
})
let currentFolder = createResource({
url: "drive.api.permissions.get_entity_with_permissions",
params: { entity_name: props.entityName },
transform(data) {
if (data.owner !== store.state.auth.user_id) {
isSharedFolder.value = true
store.commit("setHasWriteAccess", data.write)
allowEmptyContextMenu.value = !!data.write
} else {
isSharedFolder.value = false
store.commit("setHasWriteAccess", true)
allowEmptyContextMenu.value = true
}
},
onSuccess(data) {
store.commit("setCurrentFolder", [data])
store.commit("setCurrentFolderID", props.entityName)
data.modified = formatDate(data.modified)
data.creation = formatDate(data.creation)
let currentBreadcrumbs = [
{
label: "Shared",
route: "/shared",
},
]
const root_item = data.breadcrumbs[0]
if (root_item.name === store.state.homeFolderID) {
currentBreadcrumbs = [
{
label: "Home",
route: "/home",
},
]
data.breadcrumbs.shift()
}
data.breadcrumbs.forEach((item, idx) => {
currentBreadcrumbs.push({
label: item.title,
route: "/folder/" + item.name,
})
})
store.commit("setCurrentBreadcrumbs", currentBreadcrumbs)
},
onError(error) {
if (error && error.exc_type === "PermissionError") {
store.commit("setError", {
iconName: "alert-triangle",
iconClass: "fill-amber-500 stroke-white",
primaryMessage: "Forbidden",
secondaryMessage: "Insufficient permissions for this resource",
})
}
router.replace({ name: "Error" })
},
auto: true,
})
let userInfo = createResource({
url: "frappe.desk.form.load.get_user_info_for_viewers",
onSuccess(data) {
data = Object.values(data)
data.forEach((item) => {
// compatibility with document awareness
if (item.fullname) {
item.avatar = item.image
item.name = item.fullname
delete item.image
delete item.fullname
}
})
store.state.connectedUsers = data
},
auto: false,
})
</script>
|
2302_79757062/drive
|
frontend/src/pages/Folder.vue
|
Vue
|
agpl-3.0
| 3,730
|
<template>
<PageGeneric
v-if="!homeID.loading"
url="drive.api.list.files"
:allow-empty-context-menu="true"
:entity-name="homeID.data"
:show-sort="true"
:icon="Home"
:primary-message="'Home is empty'"
:secondary-message="'Add files by dropping them here'"
/>
</template>
<script setup>
import Home from "../components/EspressoIcons/Home.vue"
import PageGeneric from "@/components/PageGeneric.vue"
import { createResource } from "frappe-ui"
import { useStore } from "vuex"
const store = useStore()
let homeID = createResource({
url: "drive.api.files.get_home_folder_id",
auto: true,
onSuccess(data) {
store.commit("setCurrentFolderID", data)
store.commit("setHomeFolderID", data)
},
})
</script>
|
2302_79757062/drive
|
frontend/src/pages/Home.vue
|
Vue
|
agpl-3.0
| 749
|
<template>
<LoginBox
title="Log in to your account"
:class="{ 'pointer-events-none': loading }"
>
<form class="flex flex-col" @submit.prevent="">
<Input
v-model="email"
class="mb-4"
label="Email"
placeholder="johndoe@mail.com"
name="email"
autocomplete="email"
:type="email !== 'Administrator' ? 'email' : 'text'"
/>
<Input
v-model="password"
label="Password"
type="password"
placeholder="••••••••"
name="password"
autocomplete="current-password"
/>
<ErrorMessage :message="errorMessage" class="mt-4" />
<Button
class="mt-4 focus:ring-0 focus:ring-offset-0"
:loading="loading"
variant="solid"
@click="login"
>
Submit
</Button>
<div class="mt-10 text-center border-t">
<div class="transform -translate-y-1/2">
<span
class="px-2 text-xs leading-8 tracking-wider text-gray-800 bg-white"
>
OR
</span>
</div>
</div>
<Button
v-for="provider in $resources.authProviders.data"
:key="provider.name"
class="mb-4 focus:ring-0 focus:ring-offset-0"
variant="solid"
@click="redirect(provider.auth_url)"
>
<template v-if="provider.name == 'frappe'" #prefix>
<svg
class="h-4.5"
style="fill: white"
width="24"
height="24"
viewBox="0 0 24 24"
xmlns="http://www.w3.org/2000/svg"
>
<path d="M5 3.68891V5.37783H11.5H18V3.68891V2H11.5H5V3.68891Z" />
<path
d="M5 15.9374V21.2443H7.07628H9.15256V17.6341V14.0238H13.1502H17.1478V12.3272V10.6305H11.0739H5V15.9374Z"
/>
</svg>
</template>
Login via {{ provider.provider_name }}
</Button>
<router-link class="text-base text-center" to="/signup">
Sign up for a new account
</router-link>
</form>
</LoginBox>
</template>
<script>
import { Input, ErrorMessage } from "frappe-ui"
import LoginBox from "@/components/LoginBox.vue"
export default {
name: "Login",
components: {
LoginBox,
Input,
ErrorMessage,
},
data() {
return {
loading: false,
email: null,
password: null,
errorMessage: null,
successMessage: null,
redirect_route: null,
}
},
methods: {
redirect(link) {
window.location.href = link
},
async login() {
try {
this.errorMessage = null
this.loading = true
if (this.email && this.password) {
let res = await this.$store.dispatch("login", {
email: this.email,
password: this.password,
})
if (res) {
this.$router.push("/home")
}
}
} catch (error) {
this.errorMessage = error.messages.join("\n")
} finally {
this.loading = false
}
},
},
resources: {
authProviders() {
return {
url: "drive.api.api.oauth_providers",
onError(error) {
if (error.messages) {
console.log(error.messages)
}
},
auto: true,
}
},
},
}
</script>
<style>
html {
-webkit-user-select: none;
/* Safari */
-ms-user-select: none;
/* IE 10 and IE 11 */
user-select: none;
/* Standard syntax */
}
</style>
|
2302_79757062/drive
|
frontend/src/pages/Login.vue
|
Vue
|
agpl-3.0
| 3,504
|
<template>
<div class="h-full overflow-y-auto mt-3.5 px-4 pb-5 w-full">
<div class="w-full h-7 mb-6 flex items-start justify-between">
<div
class="bg-gray-100 rounded-[10px] space-x-0.5 h-7 flex items-center px-0.5 py-1"
>
<Button
class="max-h-6"
:class="
onlyUnread
? 'bg-white shadow-sm hover:bg-white active:bg-white'
: ''
"
@click="onlyUnread = true"
>Unread</Button
>
<Button
class="max-h-6"
:class="
onlyUnread
? ''
: 'bg-white shadow-sm hover:bg-white active:bg-white'
"
@click="onlyUnread = false"
>All</Button
>
</div>
<div>
<Button
:loading="notifications.loading"
icon="refresh-ccw"
class="mr-2"
@click="notifications.reload()"
></Button>
<Button
icon-left="check-circle"
@click="
markAsRead.submit({ all: true }), (store.state.notifCount = 0)
"
>Mark all as Read</Button
>
</div>
</div>
<ListView
v-if="!notifications.loading && notifications.data.length"
:columns="columns"
:options="options"
:rows="notifications.data"
row-key="name"
></ListView>
<div
v-else
class="absolute top-1/2 left-1/2 -translate-x-1/2 -translate-y-1/2 flex flex-col items-center justify-center"
>
<FeatherIcon name="inbox" class="w-14 h-auto text-gray-500 pb-4" />
<span class="text-base text-gray-600 font-medium">No Notifications</span>
</div>
</div>
</template>
<script setup>
import { ref, h, watch } from "vue"
import { formatTimeAgo } from "@vueuse/core"
import { createResource, Avatar, ListView, FeatherIcon } from "frappe-ui"
import { useStore } from "vuex"
import { formatDate } from "../utils/format"
const store = useStore()
const onlyUnread = ref(true)
const options = {
getRowRoute: (row) => ({
name: row.entity_type,
params: { entityName: row.notif_doctype_name },
}),
onRowClick: (row) => {
if (onlyUnread.value) {
markAsRead.submit({ name: row.name })
store.state.notifCount = store.state.notifCount - 1
}
},
selectable: false,
showTooltip: true,
resizeColumn: false,
}
const columns = [
{
label: "Subject",
key: "subject",
width: "80px",
getLabel: ({ row }) => row.type,
},
{
label: "Message",
key: "message",
width: 4,
getLabel: ({ row }) => row.message,
prefix: ({ row }) => {
return h(Avatar, {
shape: "circle",
label: row.from_user,
image: row.user_image,
size: "sm",
})
},
},
{
key: "creation",
align: "end",
getLabel: ({ row }) => row.relativeTime,
},
]
watch(onlyUnread, (newValue) => {
notifications.fetch({
only_unread: newValue,
})
})
const notifications = createResource({
url: "drive.api.notifications.get_notifications",
auto: true,
params: {
only_unread: onlyUnread.value,
},
onSuccess(data) {
data.forEach((item) => {
item.relativeTime = formatTimeAgo(new Date(item.creation))
item.creation = formatDate(item.creation)
})
},
})
const markAsRead = createResource({
url: "drive.api.notifications.mark_as_read",
auto: false,
method: "POST",
params: {
name: "",
all: false,
},
onSuccess() {
notifications.reload()
},
})
</script>
|
2302_79757062/drive
|
frontend/src/pages/Notifications.vue
|
Vue
|
agpl-3.0
| 3,533
|
<template>
<PageGeneric
url="drive.api.list.files"
:recents="true"
:allow-empty-context-menu="false"
:show-sort="false"
:icon="Recent"
primary-message="No Recent Files"
:secondary-message="''"
/>
</template>
<script setup>
import PageGeneric from "@/components/PageGeneric.vue"
import Recent from "../components/EspressoIcons/Recent.vue"
</script>
|
2302_79757062/drive
|
frontend/src/pages/Recents.vue
|
Vue
|
agpl-3.0
| 381
|
<template>
<PageGeneric
:key="sharedUrl"
:url="sharedUrl"
:allow-empty-context-menu="allowEmptyContextMenu"
:show-sort="true"
:icon="Users"
:primaryMessage="'No Shared Files'"
:secondaryMessage="''"
/>
</template>
<script setup>
import PageGeneric from "@/components/PageGeneric.vue"
import { ref, computed } from "vue"
import { useStore } from "vuex"
import Users from "../components/EspressoIcons/Users.vue"
const store = useStore()
const allowEmptyContextMenu = ref(false)
const sharedUrl = computed(() => {
return store.state.shareView === "with"
? "drive.api.list.shared_with_user"
: "drive.api.list.shared_by_user"
})
</script>
|
2302_79757062/drive
|
frontend/src/pages/Shared.vue
|
Vue
|
agpl-3.0
| 679
|
<template>
<LoginBox
v-if="!request_status_ok"
title="Create your account"
:class="{ 'pointer-events-none': loading }"
>
<form class="flex flex-col" @submit.prevent="signup()">
<Input
v-model="fullName"
class="mb-4"
label="Name"
type="text"
placeholder="John Doe"
autocomplete="name"
required
/>
<Input
v-model="email"
label="Email"
type="email"
placeholder="johndoe@mail.com"
autocomplete="email"
required
/>
<ErrorMessage class="mt-4" :message="errorMessage" />
<Button
class="mt-4 focus:ring-0 focus:ring-offset-0"
:loading="loading"
variant="solid"
>
Submit
</Button>
<div class="mt-10 text-center border-t">
<div class="transform -translate-y-1/2">
<span
class="px-2 text-xs leading-8 tracking-wider text-gray-800 bg-white"
>
OR
</span>
</div>
</div>
<router-link class="text-base text-center" to="/login">
Already have an account? Log in.
</router-link>
</form>
</LoginBox>
<div v-else class="p-5 sm:p-20">
<div
class="flex flex-col flex-1 items-center p-10 text-base bg-white rounded-lg mx-auto shadow-lg w-full sm:w-96"
>
<div class="w-8 h-8 p-1 rounded-full" :class="iconContainerClass">
<FeatherIcon :name="icon" :class="iconClass" />
</div>
<h2 class="mt-4 text-lg font-medium text-center text-gray-900">
{{ response.title }}
</h2>
<p class="text-base text-center text-gray-700 mt-1.5">
<!-- eslint-disable-next-line vue/no-v-html -->
<span v-html="response.message" />
</p>
</div>
</div>
</template>
<script>
import { Input, ErrorMessage, FeatherIcon } from "frappe-ui"
import LoginBox from "@/components/LoginBox.vue"
export default {
name: "Signup",
components: {
Input,
ErrorMessage,
FeatherIcon,
LoginBox,
},
data() {
return {
email: null,
fullName: null,
errorMessage: null,
loading: false,
request_status_ok: false,
response: {
title: null,
message: null,
color: null,
},
}
},
computed: {
iconClass() {
return {
red: "text-red-500",
green: "text-green-500",
}[this.response.color]
},
iconContainerClass() {
return {
red: "bg-red-100",
green: "bg-green-100",
}[this.response.color]
},
icon() {
return {
red: "x",
green: "check",
}[this.response.color]
},
},
methods: {
async signup() {
try {
this.errorMessage = null
this.loading = true
if (this.email && this.fullName) {
let res = await this.$call("frappe.core.doctype.user.user.sign_up", {
full_name: this.fullName,
email: this.email,
redirect_to: "",
})
if (res) {
let [code] = res
if (code > 0) this.request_status_ok = true
if (code === 0) {
this.errorMessage = "This account already exists"
} else if (code === 1) {
this.response = {
title: "Verification Email Sent",
message: `We have sent an email to
<span class="font-semibold">${this.email}</span>. Please check your email for verification.`,
color: "green",
}
} else {
this.request_status_ok = true
this.response = {
title: "Verification Needed",
message: `Verification email was not sent. Please ask your administrator to
verify your sign-up`,
color: "red",
}
}
}
}
} catch (error) {
this.errorMessage = error.messages.join("\n")
} finally {
this.loading = false
}
},
},
}
</script>
|
2302_79757062/drive
|
frontend/src/pages/Signup.vue
|
Vue
|
agpl-3.0
| 4,072
|
<template>
<div>
<Dropdown
placement="center"
:options="[
{
icon: 'user',
label: 'My Profile',
},
{
icon: 'folder-minus',
label: 'Archived Teams',
},
{
icon: 'log-out',
label: 'Log out',
},
]"
>
<template #default="{ open }">
<Button :class="open ? 'bg-gray-300' : 'hover:bg-gray-200'">
Drop
</Button>
</template>
</Dropdown>
<Popover>
<template #target="{ togglePopover }">
<Button @click="togglePopover()">Pop</Button>
</template>
<template #body-main="{ togglePopover }">
<div v-for="item in ['yes', 'no']" :key="item">
<div
@click="
() => {
togglePopover()
}
"
>
{{ item }}
</div>
</div>
</template>
</Popover>
</div>
</template>
<script>
import { Popover, Button, Dropdown } from "frappe-ui"
export default {
name: "Test",
components: { Popover, Button, Dropdown },
}
</script>
|
2302_79757062/drive
|
frontend/src/pages/Test.vue
|
Vue
|
agpl-3.0
| 1,136
|
<template>
<PageGeneric
url="drive.api.list.files"
:allow-empty-context-menu="false"
:is-active="0"
:show-sort="true"
:icon="Trash"
:primaryMessage="'Trash is Empty'"
:secondaryMessage="''"
/>
</template>
<script setup>
import PageGeneric from "@/components/PageGeneric.vue"
import Trash from "../components/EspressoIcons/Trash.vue"
</script>
|
2302_79757062/drive
|
frontend/src/pages/Trash.vue
|
Vue
|
agpl-3.0
| 376
|
import { createRouter, createWebHistory } from "vue-router"
import store from "./store"
function redir404(to, from) {
if (to.name === "Error" && from.name) {
return
}
if (store.getters.isLoggedIn && to.fullPath === "/") {
return { name: "Home" }
} else if (!store.getters.isLoggedIn && to.fullPath === "/") {
return { name: "Login" }
} else {
return { name: "Login" }
}
}
function clearStore(to, from) {
if (from.name === "Document" || to.name === "Document") {
store.commit("setShowInfo", false)
return
} else {
store.commit("setEntityInfo", [])
store.commit("setCurrentFolder", [])
store.commit("setCurrentViewEntites", [])
}
}
function setRootBreadCrumb(to) {
if (store.getters.isLoggedIn) {
document.title = to.name
store.commit("setCurrentBreadcrumbs", [{ label: to.name, route: to.path }])
}
}
const routes = [
{
path: "/notifications",
name: "Notifications",
component: () => import("@/pages/Notifications.vue"),
beforeEnter: [setRootBreadCrumb, clearStore],
},
{
path: "/home",
name: "Home",
component: () => import("@/pages/Home.vue"),
beforeEnter: [setRootBreadCrumb, clearStore],
},
{
path: "/file/:entityName",
name: "File",
component: () => import("@/pages/File.vue"),
meta: { sidebar: true, isHybridRoute: true, filePage: true },
props: true,
},
{
path: "/folder/:entityName",
name: "Folder",
component: () => import("@/pages/Folder.vue"),
meta: { sidebar: true, isHybridRoute: true },
props: true,
},
{
path: "/document/:entityName",
name: "Document",
meta: { sidebar: false, documentPage: true, isHybridRoute: true },
component: () => import("@/pages/Document.vue"),
props: true,
beforeEnter: [clearStore],
},
{
path: "/recents",
name: "Recents",
component: () => import("@/pages/Recents.vue"),
beforeEnter: [setRootBreadCrumb, clearStore],
},
{
path: "/shared",
name: "Shared",
component: () => import("@/pages/Shared.vue"),
beforeEnter: [setRootBreadCrumb, clearStore],
},
{
path: "/favourites",
name: "Favourites",
component: () => import("@/pages/Favourites.vue"),
beforeEnter: [setRootBreadCrumb],
},
{
path: "/trash",
name: "Trash",
component: () => import("@/pages/Trash.vue"),
beforeEnter: [setRootBreadCrumb, clearStore],
},
{
path: "/signup",
name: "Signup",
component: () => import("@/pages/Signup.vue"),
meta: {
isPublicRoute: true,
},
},
{
path: "/test",
name: "Test",
component: () => import("@/pages/Test.vue"),
},
{
path: "/login",
name: "Login",
redirect: () => {
window.location.href = "/login"
},
},
{
path: "/:pathMatch(.*)*/",
name: "Error",
component: () => import("@/pages/Error.vue"),
beforeEnter: [redir404, clearStore],
props: true,
},
]
let router = createRouter({
history: createWebHistory("/drive"),
routes,
/* scrollBehavior(to, from) {
return new Promise((resolve) => {
// Set a delay of 1000ms before scrolling
setTimeout(() => {
const element = document.getElementById('main');
console.log(element)
const { top } = element.getBoundingClientRect();
const scrollY = window.scrollY + top + 100;
console.log('Scroll position:', scrollY);
element.scrollTo({
top: element.scrollTop + 8000, // Scroll down by the specified amount
behavior: 'instant',
// Enable smooth scrolling
});
// Always scroll to the element with ID 'main', 10 pixels above
resolve();
}, 1000); // 1000ms delay
});
}, */
})
const HybridRouteArray = ["File", "Folder", "Document"]
router.beforeEach((to, from, next) => {
// If they hit a public page log them in
if (to.matched.some((record) => record.meta.isPublicRoute)) {
if (store.getters.isLoggedIn) {
next({ name: "Home" })
} else {
next()
}
} else {
// Prepend "Shared/" to the breadcrumbs if an authenticated user navigated to a file by pasting a link
if (
store.getters.isLoggedIn ||
to.matched.some((record) => record.meta.isHybridRoute)
) {
if (to.href !== sessionStorage.getItem("currentRoute")) {
if (from.fullPath === "/" && HybridRouteArray.includes(to.name)) {
store.commit("setCurrentBreadcrumbs", [
{ label: "Shared", route: "/shared" },
])
}
}
next()
} else {
if (to.name === "Error") {
next()
} else {
next("/login")
}
//import.meta.env.DEV ? next("/login") : (window.location.href = "/login");
}
}
})
router.afterEach((to) => {
sessionStorage.setItem("currentRoute", to.href)
})
export default router
|
2302_79757062/drive
|
frontend/src/router.js
|
JavaScript
|
agpl-3.0
| 4,853
|
import { io } from "socket.io-client"
import { socketio_port } from "../../../../sites/common_site_config.json"
export function initSocket(options = {}) {
let host = window.location.hostname
let siteName = import.meta.env.DEV ? host : window.site_name
let port = window.location.port ? `:${socketio_port}` : ""
let protocol = port ? "http" : "https"
let url = `${protocol}://${host}${port}/${siteName}`
// add exponential backoff
let socket = io(url, {
withCredentials: true,
reconnectionAttempts: 5,
transports: ["websocket", "polling"],
})
socket.on("connect_error", (data) => {
console.log(data)
})
return socket
}
// global socket conn state
export class RealTimeHandler {
open_docs: Set<string>
socket: Socket
subscribing: boolean
constructor(socket) {
this.open_docs = new Set()
this.socket = socket
this.subscribing = false
}
on(event: string, callback: (...args: any[]) => void) {
if (this.socket) {
this.socket.on(event, callback)
}
}
off(event: string, callback: (...args: any[]) => void) {
if (this.socket) {
this.socket.off(event, callback)
}
}
emit(event: string, ...args: any[]) {
this.socket.emit(event, ...args)
}
doc_subscribe(doctype: string, docname: string) {
if (this.subscribing) {
console.log("throttled")
return
}
if (this.open_docs.has(`${doctype}:${docname}`)) {
return
}
this.subscribing = true
// throttle to 1 per sec
setTimeout(() => {
this.subscribing = false
}, 1000)
this.emit("doc_subscribe", doctype, docname)
this.open_docs.add(`${doctype}:${docname}`)
}
doc_unsubscribe(doctype: string, docname: string) {
this.emit("doc_unsubscribe", doctype, docname)
return this.open_docs.delete(`${doctype}:${docname}`)
}
doc_open(doctype: string, docname: string) {
this.emit("doc_open", doctype, docname)
}
doc_close(doctype: string, docname: string) {
this.emit("doc_close", doctype, docname)
}
publish(event: string, message: any) {
if (this.socket) {
this.emit(event, message)
}
}
}
|
2302_79757062/drive
|
frontend/src/socket.ts
|
TypeScript
|
agpl-3.0
| 2,141
|
import { createStore } from "vuex"
import { call } from "frappe-ui"
import { clear } from "idb-keyval"
import { get, set } from "idb-keyval"
let getCookies = () => {
return Object.fromEntries(
document.cookie
.split("; ")
.map((cookie) => cookie.split("="))
.map((entry) => [entry[0], decodeURIComponent(entry[1])])
)
}
const store = createStore({
state: {
auth: {
loading: false,
user_id: getCookies().user_id,
},
user: {
systemUser: getCookies().system_user === "yes",
fullName: getCookies().full_name,
imageURL: getCookies().user_image,
driveAdmin: false,
},
error: {
iconName: "x-circle",
iconClass: "fill-red-500 stroke-white",
primaryMessage: "404 Not Found",
secondaryMessage: "The resource you're looking for does not exist",
},
uploads: [],
connectedUsers: [],
sortOrder: JSON.parse(localStorage.getItem("sortOrder")) || {
label: "Modified",
field: "modified",
ascending: false,
},
view: JSON.parse(localStorage.getItem("view")) || "grid",
shareView: JSON.parse(localStorage.getItem("shareView")) || "with",
activeFilters: [],
notifCount: 0,
entityInfo:
JSON.parse(localStorage.getItem("selectedEntities")) ||
JSON.parse(localStorage.getItem("currentFolder")) ||
[],
serverTZ: null,
currentFolder: JSON.parse(localStorage.getItem("currentFolder")) || [],
currentViewEntites: get("currentViewEntites") || [],
pasteData: { entities: [], action: null },
showInfo: JSON.parse(localStorage.getItem("showInfo")) || false,
hasWriteAccess: false,
// Default to empty string to upload to user Home folder
currentFolderID: "",
homeFolderID: localStorage.getItem("homeFolderID"),
currentBreadcrumbs: JSON.parse(
localStorage.getItem("currentBreadcrumbs")
) || [{ label: "Home", route: "/home" }],
allComments: "",
activeCommentsInstance: "",
IsSidebarExpanded: JSON.parse(
localStorage.getItem("IsSidebarExpanded") || true
),
passiveRename: false,
foldersBefore: localStorage.getItem("foldersBefore")
? JSON.parse(localStorage.getItem("foldersBefore"))
: true,
singleClick: localStorage.getItem("singleClick")
? JSON.parse(localStorage.getItem("singleClick"))
: false,
editorNewTab: localStorage.getItem("editorNewTab")
? JSON.parse(localStorage.getItem("editorNewTab"))
: false,
},
getters: {
isLoggedIn: (state) => {
return state.auth.user_id && state.auth.user_id !== "Guest"
},
uploadsInProgress: (state) => {
return state.uploads.filter((upload) => !upload.completed)
},
uploadsFailed: (state) => {
return state.uploads.filter((upload) => upload.error)
},
uploadsCompleted: (state) => {
return state.uploads.filter((upload) => upload.completed && !upload.error)
},
},
mutations: {
toggleFoldersBefore(state) {
state.foldersBefore = !state.foldersBefore
localStorage.setItem("foldersBefore", JSON.stringify(state.foldersBefore))
},
toggleSingleClick(state) {
state.singleClick = !state.singleClick
localStorage.setItem("singleClick", JSON.stringify(state.singleClick))
},
toggleEditorNewTab(state) {
state.editorNewTab = !state.editorNewTab
localStorage.setItem("editorNewTab", JSON.stringify(state.editorNewTab))
},
setAuth(state, auth) {
Object.assign(state.auth, auth)
},
setError(state, error) {
Object.assign(state.error, error)
},
setUser(state, user) {
Object.assign(state.user, user)
},
setUploads(state, uploads) {
state.uploads = uploads
},
setConnectedUsers(state, connectedUsers) {
state.connectedUsers = connectedUsers
},
pushToUploads(state, upload) {
state.uploads.push(upload)
},
updateUpload(state, payload) {
let index = state.uploads.findIndex(
(upload) => upload.uuid == payload.uuid
)
Object.assign(state.uploads[index], payload)
},
setSortOrder(state, payload) {
localStorage.setItem("sortOrder", JSON.stringify(payload))
state.sortOrder = payload
},
toggleView(state, payload) {
localStorage.setItem("view", JSON.stringify(payload))
state.view = payload
},
toggleShareView(state, payload) {
localStorage.setItem("shareView", JSON.stringify(payload))
state.shareView = payload
},
setEntityInfo(state, payload) {
localStorage.setItem("selectedEntities", JSON.stringify(payload))
state.entityInfo = payload
},
setCurrentFolder(state, payload) {
localStorage.setItem("currentFolder", JSON.stringify(payload))
state.currentFolder = payload
},
setCurrentViewEntites(state, payload) {
state.currentViewEntites = payload
set("currentViewEntites", JSON.stringify(payload))
},
setPasteData(state, payload) {
state.pasteData = payload
},
setShowInfo(state, payload) {
localStorage.setItem("showInfo", payload)
state.showInfo = payload
},
setAllComments(state, payload) {
/* localStorage.setItem("allDocComments",payload); */
state.allComments = payload
},
setActiveCommentsInstance(state, payload) {
state.activeCommentsInstance = payload
},
setHasWriteAccess(state, payload) {
state.hasWriteAccess = payload
},
setCurrentFolderID(state, payload) {
state.currentFolderID = payload
},
setHomeFolderID(state, payload) {
state.homeFolderID = payload
localStorage.setItem("homeFolderID", payload)
},
setCurrentBreadcrumbs(state, payload) {
localStorage.setItem("currentBreadcrumbs", JSON.stringify(payload))
state.currentBreadcrumbs = payload
},
setIsSidebarExpanded(state, payload) {
localStorage.setItem("IsSidebarExpanded", JSON.stringify(payload))
state.IsSidebarExpanded = payload
},
},
actions: {
async login({ commit }, payload) {
localStorage.removeItem("is_drive_admin")
commit("setAuth", { loading: true })
clear()
let res = await call("login", {
usr: payload.email,
pwd: payload.password,
})
if (res) {
commit("setAuth", {
loading: false,
user_id: getCookies().user_id,
})
commit("setUser", {
fullName: getCookies().full_name,
imageURL: getCookies().user_image
? window.location.origin + getCookies().user_image
: null,
})
return res
}
},
async logout({ commit }) {
commit("setAuth", { loading: true })
await call("logout")
clear()
window.location.reload()
},
clearUploads({ commit }) {
commit("setUploads", [])
},
},
})
export default store
|
2302_79757062/drive
|
frontend/src/store.js
|
JavaScript
|
agpl-3.0
| 6,914
|
import { useStorage } from "@vueuse/core"
import { call } from "frappe-ui"
import "../../../frappe/frappe/public/js/lib/posthog.js"
const APP = "drive"
const SITENAME = window.location.hostname
// extend window object to add posthog
// eslint-disable-next-line @typescript-eslint/no-explicit-any
declare global {
interface Window {
posthog: any
}
}
const telemetry = useStorage("telemetry", {
enabled: false,
project_id: "",
host: "",
})
export async function init() {
await set_enabled()
if (!telemetry.value.enabled) return
try {
await set_credentials()
window.posthog.init(telemetry.value.project_id, {
api_host: telemetry.value.host,
autocapture: false,
person_profiles: "always",
capture_pageview: true,
capture_pageleave: true,
disable_session_recording: false,
session_recording: {
maskAllInputs: false,
maskInputOptions: {
password: true,
},
},
loaded: (posthog) => {
window.posthog = posthog
window.posthog.identify(SITENAME)
},
})
} catch (e) {
console.trace("Failed to initialize telemetry", e)
telemetry.value.enabled = false
}
}
async function set_enabled() {
if (telemetry.value.enabled) return
await call("drive.api.telemetry.is_enabled").then((res) => {
telemetry.value.enabled = true
})
}
async function set_credentials() {
if (!telemetry.value.enabled) return
if (telemetry.value.project_id && telemetry.value.host) return
await call("drive.api.telemetry.get_credentials").then((res) => {
telemetry.value.project_id = res.project_id
telemetry.value.host = res.telemetry_host
})
}
interface CaptureOptions {
data: {
user: string
[key: string]: string | number | boolean | object
}
}
export function capture(
event: string,
options: CaptureOptions = { data: { user: "" } }
) {
if (!telemetry.value.enabled) return
window.posthog.capture(`${APP}_${event}`, options)
}
export function recordSession() {
if (!telemetry.value.enabled) return
if (window.posthog && window.posthog.__loaded) {
window.posthog.startSessionRecording()
}
}
export function stopSession() {
if (!telemetry.value.enabled) return
if (
window.posthog &&
window.posthog.__loaded &&
window.posthog.sessionRecordingStarted()
) {
window.posthog.stopSessionRecording()
}
}
|
2302_79757062/drive
|
frontend/src/telemetry.ts
|
TypeScript
|
agpl-3.0
| 2,398
|
import { v4 as uuidv4 } from "uuid"
/* Simple function to chunk upload a file instead of dropzone JS
Currently only used in documents
*/
export async function uploadDriveEntity(file, parent_entity_name) {
const fileUuid = uuidv4()
const chunkSize = 5 * 1024 * 1024 // size of each chunk (5MB)
let chunkByteOffset = 0
let chunkIndex = 0
const totalChunks = Math.ceil(file.size / chunkSize)
while (chunkByteOffset < file.size) {
let CurrentChunk = file.slice(chunkByteOffset, chunkByteOffset + chunkSize)
const response = await uploadChunk(
file.name,
CurrentChunk,
fileUuid,
file.size,
file.type,
chunkIndex,
chunkSize,
totalChunks,
chunkByteOffset,
parent_entity_name
)
if (chunkIndex === totalChunks - 1) {
// This is the last chunk, handle the response here
if (!response.ok) {
throw new Error(`Upload failed: ${response.statusText}`)
}
const data = await response.json()
return `/api/method/drive.api.embed.get_file_content?embed_name=${data.message}&parent_entity_name=${parent_entity_name}`
}
chunkByteOffset += chunkSize
chunkIndex++
}
}
async function uploadChunk(
fileName,
CurrentChunk,
fileUuid,
fileSize,
fileType,
chunkIndex,
chunkSize,
totalChunks,
chunkByteOffset,
parent_entity_name
) {
const formData = new FormData()
formData.append("file_name", fileName)
formData.append("total_file_size", fileSize)
formData.append("mime_type", fileType)
formData.append("total_chunk_count", totalChunks)
formData.append("chunk_byte_offset", chunkByteOffset)
formData.append("chunk_index", chunkIndex)
formData.append("chunk_size", chunkSize)
formData.append("file", CurrentChunk)
formData.append("parent", parent_entity_name)
formData.append("uuid", fileUuid)
const response = await fetch(
window.location.origin + "/api/method/drive.api.embed.upload_chunked_file",
{
method: "POST",
body: formData,
headers: {
"X-Frappe-CSRF-Token": window.csrf_token,
Accept: "application/json",
},
}
)
return response
}
|
2302_79757062/drive
|
frontend/src/utils/chunkFileUpload.js
|
JavaScript
|
agpl-3.0
| 2,158
|
const canUseDOM = () =>
typeof window !== "undefined" &&
!!window.document &&
!!window.document.createElement
interface Options {
authorizedInInputs: number[]
disableKeys: boolean
disableScroll: boolean
disableWheel: boolean
keyboardKeys: number[]
}
class DisableScroll {
element: Element | null
lockToScrollPos: [number, number]
options: Options
constructor() {
this.element = null
this.lockToScrollPos = [0, 0]
this.options = {
authorizedInInputs: [32, 37, 38, 39, 40],
disableKeys: true,
disableScroll: true,
disableWheel: true,
keyboardKeys: [32, 33, 34, 35, 36, 37, 38, 39, 40],
// space: 32, page up: 33, page down: 34, end: 35, home: 36
// left: 37, up: 38, right: 39, down: 40
}
/* istanbul ignore else */
if (canUseDOM()) {
this.element = document.scrollingElement
}
}
/**
* Disable Page Scroll
*/
on(element?: Element, options?: Partial<Options>) {
if (!canUseDOM()) return
this.element = element || this.element
this.options = {
...this.options,
...options,
}
const { disableKeys, disableScroll, disableWheel } = this.options
/* istanbul ignore else */
if (disableWheel) {
document.addEventListener("wheel", this.handleWheel, { passive: false })
document.addEventListener("touchmove", this.handleWheel, {
passive: false,
})
}
/* istanbul ignore else */
if (disableScroll) {
this.lockToScrollPos = [
this.element?.scrollLeft ?? 0,
this.element?.scrollTop ?? 0,
]
document.addEventListener("scroll", this.handleScroll, {
passive: false,
})
}
/* istanbul ignore else */
if (disableKeys) {
document.addEventListener("keydown", this.handleKeydown, {
passive: false,
})
}
}
/**
* Re-enable page scrolls
*/
off() {
if (!canUseDOM()) return
document.removeEventListener("wheel", this.handleWheel)
document.removeEventListener("touchmove", this.handleWheel)
document.removeEventListener("scroll", this.handleScroll)
document.removeEventListener("keydown", this.handleKeydown)
}
handleWheel = (e: WheelEvent | TouchEvent) => {
e.preventDefault()
}
handleScroll = () => {
window.scrollTo(...this.lockToScrollPos)
}
handleKeydown = (e: KeyboardEvent) => {
let keys = this.options.keyboardKeys
/* istanbul ignore else */
if (
["INPUT", "TEXTAREA"].includes(
(e.target as HTMLInputElement | HTMLTextAreaElement).tagName
)
) {
keys = keys.filter(
(key) => !this.options.authorizedInInputs.includes(key)
)
}
/* istanbul ignore else */
if (keys.includes(e.keyCode)) {
e.preventDefault()
}
}
}
export default new DisableScroll()
|
2302_79757062/drive
|
frontend/src/utils/disable-scroll.ts
|
TypeScript
|
agpl-3.0
| 2,846
|
export function calculateRectangle(coordinates) {
const x3 = Math.min(coordinates.x1, coordinates.x2)
const x4 = Math.max(coordinates.x1, coordinates.x2)
const y3 = Math.min(coordinates.y1, coordinates.y2)
const y4 = Math.max(coordinates.y1, coordinates.y2)
return {
left: x3 + "px",
top: y3 + "px",
width: x4 - x3 + "px",
height: y4 - y3 + "px",
}
}
export function handleDragSelect(entityElements, coordinates) {
const selectedEntities = new Set()
entityElements.forEach((element) => {
const elementRect = element.getBoundingClientRect()
const maxX = Math.max(coordinates.x1, coordinates.x2)
const minX = Math.min(coordinates.x1, coordinates.x2)
const maxY = Math.max(coordinates.y1, coordinates.y2)
const minY = Math.min(coordinates.y1, coordinates.y2)
if (
((elementRect.top >= minY && elementRect.top <= maxY) ||
(elementRect.bottom >= minY && elementRect.bottom <= maxY) ||
(minY >= elementRect.top && minY <= elementRect.bottom)) &&
((elementRect.left >= minX && elementRect.left <= maxX) ||
(elementRect.right >= minX && elementRect.right <= maxX) ||
(minX >= elementRect.left && minX <= elementRect.right))
) {
//element.classList.add("bg-gray-100", "border-gray-300");
selectedEntities.add(element.id)
} else {
// element.classList.remove("bg-gray-100", "border-gray-300");
}
})
return selectedEntities
}
|
2302_79757062/drive
|
frontend/src/utils/dragSelect.js
|
JavaScript
|
agpl-3.0
| 1,450
|
export default (file) => {
return new Promise((resolve) => {
let reader = new FileReader()
reader.onloadend = () => {
resolve(reader.result)
}
reader.readAsDataURL(file)
})
}
|
2302_79757062/drive
|
frontend/src/utils/file-to-base64.js
|
JavaScript
|
agpl-3.0
| 201
|
import JSZip from "jszip"
export function selectedEntitiesDownload(selected_entities) {
const generateRandomString = () =>
[...Array(5)].map(() => Math.random().toString(36)[2]).join("")
const randomString = generateRandomString()
const folderName = "FDrive_" + randomString
const zip = new JSZip()
const processEntity = (entity, parentFolder) => {
if (entity.is_group) {
const folder = parentFolder.folder(entity.title)
return get_children(entity.name).then((children) => {
const promises = children.map((childEntity) =>
processEntity(childEntity, folder)
)
return Promise.all(promises)
})
} else if (entity.document) {
return
} else {
return get_file_content(entity.name).then((fileContent) => {
parentFolder.file(entity.title, fileContent)
})
}
}
const promises = selected_entities.map((entity) => processEntity(entity, zip))
Promise.all(promises)
.then(() => {
return zip.generateAsync({ type: "blob", streamFiles: true })
})
.then(function (content) {
var downloadLink = document.createElement("a")
downloadLink.href = URL.createObjectURL(content)
downloadLink.download = folderName + ".zip"
document.body.appendChild(downloadLink)
downloadLink.click()
document.body.removeChild(downloadLink)
})
.catch((error) => {
console.error(error)
})
}
export function folderDownload(root_entity) {
const folderName = root_entity.title
const zip = new JSZip()
temp(root_entity.name, zip)
.then(() => {
return zip.generateAsync({ type: "blob", streamFiles: true })
})
.then((content) => {
const downloadLink = document.createElement("a")
downloadLink.href = URL.createObjectURL(content)
downloadLink.download = folderName + ".zip"
document.body.appendChild(downloadLink)
downloadLink.click()
document.body.removeChild(downloadLink)
})
.catch((error) => {
console.error(error)
})
}
function temp(entity_name, parentZip) {
return new Promise((resolve, reject) => {
get_children(entity_name)
.then((result) => {
const promises = result.map((entity) => {
if (entity.is_group) {
const folder = parentZip.folder(entity.title)
return temp(entity.name, folder)
} else {
return get_file_content(entity.name).then((fileContent) => {
parentZip.file(entity.title, fileContent)
})
}
})
Promise.all(promises)
.then(() => {
resolve()
})
.catch((error) => {
reject(error)
})
})
.catch((error) => {
reject(error)
})
})
}
function get_file_content(entity_name) {
const fileUrl =
"/api/method/" +
`drive.api.files.get_file_content?entity_name=${entity_name}`
return fetch(fileUrl).then((response) => {
if (response.ok) {
return response.blob()
} else if (response.status === 204) {
console.log(response)
} else {
throw new Error(`Request failed with status ${response.status}`)
}
})
}
function get_children(entity_name) {
const url =
"/api/method/" +
`drive.api.files.list_folder_contents?entity_name=${entity_name}`
return fetch(url, {
method: "GET",
headers: {
"X-Frappe-CSRF-Token": window.csrf_token,
"Content-Type": "application/json",
Accept: "application/json",
},
})
.then((response) => {
if (!response.ok) {
throw new Error(`Request failed with status ${response.status}`)
}
return response.json()
})
.then((json) => json.message)
}
|
2302_79757062/drive
|
frontend/src/utils/folderDownload.js
|
JavaScript
|
agpl-3.0
| 3,744
|
import { format } from "date-fns"
import { fromZonedTime } from "date-fns-tz"
import store from "../store"
export function formatSize(size, nDigits = 1) {
if (size === 0) return "0 B"
const k = 1000 // Change base to 1000 for decimal prefixes
const digits = nDigits < 0 ? 0 : nDigits
const sizes = [" B", " KB", " MB", " GB", " TB", " PB"] // Adjusted for decimal prefixes
const i = Math.floor(Math.log(size) / Math.log(k))
let decSize = parseFloat((size / Math.pow(k, i)).toFixed(digits)) + sizes[i]
if (i === 0 || i === 1) {
decSize = Math.round(size / Math.pow(k, i))
} else {
decSize = parseFloat((size / Math.pow(k, i)).toFixed(digits))
}
return decSize + sizes[i]
}
export function base2BlockSize(bytes, decimals = 2, current = 0) {
if (bytes === 0) return "0 Bytes"
const k = 1024
const dm = decimals < 0 ? 0 : decimals
const sizes = ["Bytes", "KB", "MB", "GB", "TB", "PB", "EB", "ZB", "YB"]
const i = Math.floor(Math.log(Math.abs(bytes)) / Math.log(k))
return (
parseFloat((bytes / Math.pow(k, i)).toFixed(dm)) + " " + sizes[i + current]
)
}
export function formatDate(date) {
const serverTimeZone = store.state.serverTZ
const dateObj = new Date(date)
const timeZone = Intl.DateTimeFormat().resolvedOptions().timeZone
const zonedDate = fromZonedTime(dateObj, serverTimeZone)
const hourCycle = navigator.language || "en-US"
const formattedDate = format(zonedDate, "MM/dd/yy", { timeZone })
let formattedTime
if (hourCycle === "en-US") {
formattedTime = format(zonedDate, "hh:mm a", { timeZone })
} else {
formattedTime = format(zonedDate, "HH:mm", { timeZone })
}
return `${formattedDate}, ${formattedTime}`
}
export function formatMimeType(mimeType) {
let icon = "unknown"
if (!mimeType) return icon
const generic = mimeType.split("/")[0]
const specific = mimeType.split("/")[1]
if (["image", "video", "audio"].includes(generic)) icon = generic
else if (generic === "frappe_doc") icon = "Frappe Doc"
else
switch (specific) {
case "pdf":
icon = "pdf"
break
case "vnd.openxmlformats-officedocument.spreadsheetml.sheet":
icon = "spreadsheet"
break
case "vnd.openxmlformats-officedocument.presentationml.presentation":
icon = "presentation"
break
case "vnd.openxmlformats-officedocument.wordprocessingml.document":
icon = "word"
break
case "msword":
icon = "word"
break
case "zip":
icon = "zip"
break
case "x-tar":
icon = "zip"
break
case "x-7z-compressed":
icon = "zip"
break
}
return icon
}
export function getDateDiffInDays(date1, date2) {
const msPerDay = 1000 * 60 * 60 * 24
const date1UTC = Date.UTC(
date1.getFullYear(),
date1.getMonth(),
date1.getDate()
)
const date2UTC = Date.UTC(
date2.getFullYear(),
date2.getMonth(),
date2.getDate()
)
return Math.floor((date1UTC - date2UTC) / msPerDay)
}
|
2302_79757062/drive
|
frontend/src/utils/format.js
|
JavaScript
|
agpl-3.0
| 3,027
|
import fuzzysort from "fuzzysort"
export default function getFilteredEntities(search, entities) {
return fuzzysort
.go(search, entities, {
limit: 5,
threshold: -100000,
key: "title",
all: true,
})
.map((result) => result.obj)
}
|
2302_79757062/drive
|
frontend/src/utils/fuzzySearcher.js
|
JavaScript
|
agpl-3.0
| 267
|
export function getIconUrl(mime_type) {
return new URL(`/src/assets/images/icons/${mime_type}.svg`, import.meta.url)
}
export async function thumbnail_getIconUrl(mime_type, name, file_ext) {
if (mime_type === "image" && file_ext !== ".svg") {
return get_thumbnail_content(name)
.then((fileContent) => {
return URL.createObjectURL(fileContent)
})
.catch(() => {
return getIconUrl(mime_type) // Return the default icon URL on failure
})
} else if (mime_type === "video") {
return get_thumbnail_video_content(name)
.then((fileContent) => {
return URL.createObjectURL(fileContent)
})
.catch(() => {
return getIconUrl(mime_type) // Return the default icon URL on failure
})
} else {
return Promise.resolve(
new URL(`/src/assets/images/icons/${mime_type}.svg`, import.meta.url)
)
}
}
function get_thumbnail_content(entity_name) {
const fileUrl =
"/api/method/" +
`drive.api.thumbnail_generator.create_image_thumbnail?entity_name=${entity_name}`
return fetch(fileUrl).then((response) => {
if (response.ok) {
return response.blob()
} else {
throw new Error(`Request failed with status ${response.status}`)
}
})
}
function get_thumbnail_video_content(entity_name) {
const fileUrl =
"/api/method/" +
`drive.api.thumbnail_generator.create_video_thumbnail?entity_name=${entity_name}`
return fetch(fileUrl).then((response) => {
if (response.ok) {
return response.blob()
} else {
throw new Error(`Request failed with status ${response.status}`)
}
})
}
|
2302_79757062/drive
|
frontend/src/utils/getIconUrl.js
|
JavaScript
|
agpl-3.0
| 1,631
|
import { toast } from "../utils/toasts.js"
export async function getLink(entity) {
const link = entity.is_group
? `${window.location.origin}/drive/folder/${entity.name}`
: entity.document
? `${window.location.origin}/drive/document/${entity.name}`
: `${window.location.origin}/drive/file/${entity.name}`
try {
await copyToClipboard(link)
toast({
title: "Copied link",
position: "bottom-right",
timeout: 2,
})
} catch (err) {
if (err.name === "NotAllowedError") {
toast({
icon: "alert-triangle",
iconClasses: "text-red-700",
title: "Clipboard permission denied",
position: "bottom-right",
})
} else {
console.error("Failed to copy link:", err)
}
}
}
const copyToClipboard = (str) => {
if (navigator && navigator.clipboard && navigator.clipboard.writeText) {
return navigator.clipboard.writeText(str)
} else {
// Fallback to the legacy clipboard API
const textArea = document.createElement("textarea")
textArea.value = str
document.body.appendChild(textArea)
textArea.select()
document.execCommand("copy")
document.body.removeChild(textArea)
return Promise.resolve()
}
}
|
2302_79757062/drive
|
frontend/src/utils/getLink.js
|
JavaScript
|
agpl-3.0
| 1,230
|
function getNumberFromPx(px: string | number | null | undefined): number {
if (!px) {
return 0
}
if (typeof px === "number") {
return px
}
return Number(px.replace("px", ""))
}
function addPxToNumber(number: number, round: boolean = true): string {
number = round ? Math.round(number) : number
return `${number}px`
}
function HexToHSV(color: HashString): { h: number; s: number; v: number } {
const [r, g, b] = color
.replace("#", "")
.match(/.{1,2}/g)
?.map((x) => parseInt(x, 16)) || [0, 0, 0]
const max = Math.max(r, g, b)
const min = Math.min(r, g, b)
const v = max / 255
const d = max - min
const s = max === 0 ? 0 : d / max
const h =
max === min
? 0
: max === r
? (g - b) / d + (g < b ? 6 : 0)
: max === g
? (b - r) / d + 2
: (r - g) / d + 4
return { h: h * 60, s, v }
}
function HSVToHex(h: number, s: number, v: number): HashString {
s /= 100
v /= 100
h /= 360
let r = 0,
g = 0,
b = 0
let i = Math.floor(h * 6)
let f = h * 6 - i
let p = v * (1 - s)
let q = v * (1 - f * s)
let t = v * (1 - (1 - f) * s)
switch (i % 6) {
case 0:
;(r = v), (g = t), (b = p)
break
case 1:
;(r = q), (g = v), (b = p)
break
case 2:
;(r = p), (g = v), (b = t)
break
case 3:
;(r = p), (g = q), (b = v)
break
case 4:
;(r = t), (g = p), (b = v)
break
case 5:
;(r = v), (g = p), (b = q)
break
}
r = Math.round(r * 255)
g = Math.round(g * 255)
b = Math.round(b * 255)
return `#${[r, g, b].map((x) => x.toString(16).padStart(2, "0")).join("")}`
}
function getRandomColor() {
return HSVToHex(Math.random() * 360, 25, 100)
}
async function confirm(message: string): Promise<boolean> {
return new Promise((resolve) => {
const confirmed = window.confirm(message)
resolve(confirmed)
})
}
function getTextContent(html: string | null) {
if (!html || !isHTMLString(html)) {
return html || ""
}
const tmp = document.createElement("div")
tmp.innerHTML = html || ""
const textContent = tmp.textContent || tmp.innerText || ""
tmp.remove()
return textContent
}
function RGBToHex(rgb: RGBString): HashString {
const [r, g, b] = rgb
.replace("rgb(", "")
.replace(")", "")
.split(",")
.map((x) => parseInt(x))
return `#${[r, g, b].map((x) => x.toString(16).padStart(2, "0")).join("")}`
}
function getRGB(color: HashString | RGBString | string | null): HashString {
if (!color) {
return "#ffffff"
}
if (color.startsWith("rgb")) {
return RGBToHex(color as RGBString)
} else if (!color.startsWith("#") && color.match(/\b[a-fA-F0-9]{3,6}\b/g)) {
return `#${color}` as HashString
}
return color as HashString
}
function isHTMLString(str: string) {
return /<[a-z][\s\S]*>/i.test(str)
}
function copyToClipboard(
text: string | object,
e: ClipboardEvent,
copyFormat = "text/plain"
) {
if (typeof text !== "string") {
text = JSON.stringify(text)
}
e.clipboardData?.setData(copyFormat, text)
}
function stripExtension(string: string) {
const lastDotPosition = string.lastIndexOf(".")
if (lastDotPosition === -1) {
return string
}
return string.substr(0, lastDotPosition)
}
function findNearestSiblingIndex(e: MouseEvent) {
let nearestElementIndex = 0
let minDistance = Number.MAX_VALUE
let parent = e.target as HTMLElement
const elements = Array.from(parent.children)
elements.forEach(function (element, index) {
const rect = element.getBoundingClientRect()
const centerX = rect.left + rect.width / 2
const centerY = rect.top + rect.height / 2
const distance = Math.sqrt(
Math.pow(centerX - e.clientX, 2) + Math.pow(centerY - e.clientY, 2)
)
if (distance < minDistance) {
minDistance = distance
nearestElementIndex = index
const positionBitmask = element.compareDocumentPosition(e.target as Node)
// sourcery skip: possible-incorrect-bitwise-operator
if (positionBitmask & Node.DOCUMENT_POSITION_PRECEDING) {
// before
} else {
nearestElementIndex += 1
}
}
})
return nearestElementIndex
}
// converts border-color to borderColor
function kebabToCamelCase(str: string) {
return str.replace(/-([a-z])/g, function (g) {
return g[1].toUpperCase()
})
}
function isJSONString(str: string) {
try {
JSON.parse(str)
} catch (e) {
return false
}
return true
}
function isTargetEditable(e: Event) {
const target = e.target as HTMLElement
const isEditable = target.isContentEditable
const isInput = target.tagName === "INPUT" || target.tagName === "TEXTAREA"
return isEditable || isInput
}
function getDataForKey(datum: Object, key: string) {
const data = Object.assign({}, datum)
return key.split(".").reduce((d, key) => (d ? d[key] : null), data) as string
}
export {
HSVToHex,
HexToHSV,
RGBToHex,
addPxToNumber,
confirm,
copyToClipboard,
findNearestSiblingIndex,
getDataForKey,
getNumberFromPx,
getRGB,
getRandomColor,
getTextContent,
isHTMLString,
isJSONString,
isTargetEditable,
kebabToCamelCase,
stripExtension,
}
|
2302_79757062/drive
|
frontend/src/utils/helpers.ts
|
TypeScript
|
agpl-3.0
| 5,190
|
import showdown from "showdown"
export function markdownToHTML(text) {
const converter = new showdown.Converter()
return converter.makeHtml(text)
}
export function htmlToMarkdown(text) {
const converter = new showdown.Converter()
return converter.makeMarkdown(text)
}
export function detectMarkdown(text) {
const lines = text.split("\n")
const markdown = lines.filter(
(line) =>
line.startsWith("![") ||
line.startsWith("#") ||
line.startsWith("> ") ||
line.startsWith("*") ||
line.startsWith("- ") ||
line.startsWith("1. ") ||
line.startsWith("```") ||
line.startsWith("`") ||
line.startsWith("[") ||
line.startsWith("---")
)
return markdown.length > 0
}
|
2302_79757062/drive
|
frontend/src/utils/markdown.js
|
JavaScript
|
agpl-3.0
| 739
|
const colors = {
blue: "#0000ff",
cyan: "#00ffff",
darkblue: "#00008b",
darkcyan: "#008b8b",
darkgrey: "#a9a9a9",
darkkhaki: "#bdb76b",
darksalmon: "#e9967a",
darkviolet: "#9400d3",
gold: "#ffd700",
green: "#008000",
lightblue: "#add8e6",
lightgreen: "#90ee90",
magenta: "#ff00ff",
maroon: "#800000",
navy: "#000080",
orange: "#ffa500",
pink: "#ffc0cb",
purple: "#800080",
red: "#ff0000",
yellow: "#ffff00",
}
const colorArray = Object.values(colors)
export function getRandomColor() {
const randomIndex = Math.floor(Math.random() * colorArray.length)
return colorArray[randomIndex].trim()
}
|
2302_79757062/drive
|
frontend/src/utils/random-color.js
|
JavaScript
|
agpl-3.0
| 637
|