Skip to content

A self-hosted media server and file management system

what am I doing

aminnausin1bbd6cffeff1
diff --git a/database/migrations/2024_12_24_064559_create_edits_table.php b/database/migrations/2024_12_24_064559_create_edits_table.php
new file mode 100644
index 00000000..1b4ea21d
--- /dev/null
+++ b/database/migrations/2024_12_24_064559_create_edits_table.php
@@ -0,0 +1,33 @@
+<?php
+
+use Illuminate\Database\Migrations\Migration;
+use Illuminate\Database\Schema\Blueprint;
+use Illuminate\Support\Facades\Schema;
+
+return new class extends Migration {
+ /**
+ * Run the migrations.
+ */
+ public function up(): void {
+ Schema::create('edits', function (Blueprint $table) {
+ $table->id();
+ $table->foreignId('user_id')->constrained()->onDelete('cascade');
+ $table->string('entity_type', 50);
+ $table->unsignedBigInteger('entity_id');
+ $table->json('changes');
+ $table->timestamp('timestamp');
+ $table->timestamps();
+
+ // Indexes
+ $table->index('entity_type');
+ $table->index('entity_id');
+ });
+ }
+
+ /**
+ * Reverse the migrations.
+ */
+ public function down(): void {
+ Schema::dropIfExists('edits');
+ }
+};
diff --git a/database/migrations/2024_12_24_064632_create_activity_table.php b/database/migrations/2024_12_24_064632_create_activity_table.php
new file mode 100644
index 00000000..0a6d53ab
--- /dev/null
+++ b/database/migrations/2024_12_24_064632_create_activity_table.php
@@ -0,0 +1,32 @@
+<?php
+
+use Illuminate\Database\Migrations\Migration;
+use Illuminate\Database\Schema\Blueprint;
+use Illuminate\Support\Facades\Schema;
+
+return new class extends Migration {
+ /**
+ * Run the migrations.
+ */
+ public function up(): void {
+ Schema::create('activity', function (Blueprint $table) {
+ $table->id();
+ $table->foreignId('user_id')->constrained()->onDelete('cascade');
+ $table->string('activity_type', 50);
+ $table->string('ip_address', 45);
+ $table->timestamp('timestamp');
+ $table->unsignedBigInteger('related_id')->nullable();
+ $table->timestamps();
+
+ // Indexes
+ $table->index('activity_type');
+ });
+ }
+
+ /**
+ * Reverse the migrations.
+ */
+ public function down(): void {
+ Schema::dropIfExists('activity');
+ }
+};
diff --git a/database/migrations/2024_12_24_064717_create_server_jobs_and_sub_jobs_table.php b/database/migrations/2024_12_24_064717_create_server_jobs_and_sub_jobs_table.php
new file mode 100644
index 00000000..e0775615
--- /dev/null
+++ b/database/migrations/2024_12_24_064717_create_server_jobs_and_sub_jobs_table.php
@@ -0,0 +1,27 @@
+<?php
+
+use Illuminate\Database\Migrations\Migration;
+use Illuminate\Database\Schema\Blueprint;
+use Illuminate\Support\Facades\Schema;
+
+return new class extends Migration
+{
+ /**
+ * Run the migrations.
+ */
+ public function up(): void
+ {
+ Schema::create('server_jobs_and_sub_jobs', function (Blueprint $table) {
+ $table->id();
+ $table->timestamps();
+ });
+ }
+
+ /**
+ * Reverse the migrations.
+ */
+ public function down(): void
+ {
+ Schema::dropIfExists('server_jobs_and_sub_jobs');
+ }
+};
diff --git a/package-lock.json b/package-lock.json
index 7d54281e..ec24bd9d 100755
--- a/package-lock.json
+++ b/package-lock.json
@@ -21,7 +21,8 @@
"vue": "^3.4.29",
"vue-chartjs": "^5.3.2",
"vue-loader": "^17.4.2",
- "vue-router": "^4.4.0"
+ "vue-router": "^4.4.0",
+ "vue-sonner": "^1.3.0"
},
"devDependencies": {
"@7nohe/laravel-typegen": "^0.6.1",
@@ -5742,6 +5743,12 @@
"vue": "^3.2.0"
}
},
+ "node_modules/vue-sonner": {
+ "version": "1.3.0",
+ "resolved": "https://registry.npmjs.org/vue-sonner/-/vue-sonner-1.3.0.tgz",
+ "integrity": "sha512-jAodBy4Mri8rQjVZGQAPs4ZYymc1ywPiwfa81qU0fFl+Suk7U8NaOxIDdI1oBGLeQJqRZi/oxNIuhCLqsBmOwg==",
+ "license": "MIT"
+ },
"node_modules/vue-tsc": {
"version": "2.1.10",
"resolved": "https://registry.npmjs.org/vue-tsc/-/vue-tsc-2.1.10.tgz",
diff --git a/package.json b/package.json
index 7d5fe579..a5dc7e4e 100755
--- a/package.json
+++ b/package.json
@@ -70,6 +70,7 @@
"vue": "^3.4.29",
"vue-chartjs": "^5.3.2",
"vue-loader": "^17.4.2",
- "vue-router": "^4.4.0"
+ "vue-router": "^4.4.0",
+ "vue-sonner": "^1.3.0"
}
}
diff --git a/resources/js/App.vue b/resources/js/App.vue
index f01d6bf1..79ed03fa 100755
--- a/resources/js/App.vue
+++ b/resources/js/App.vue
@@ -1,12 +1,18 @@
<script setup lang="ts">
-import ToastController from '@/components/pinesUI/ToastController.vue';
+import type { ToastPostion } from './types/pinesTypes';
-import { onMounted, watch } from 'vue';
-import { RouterView } from 'vue-router';
+import { onMounted, ref, watch } from 'vue';
+import { getScreenSize } from './service/util';
import { storeToRefs } from 'pinia';
import { useAppStore } from '@/stores/AppStore';
+import { RouterView } from 'vue-router';
+import { Toaster } from 'vue-sonner';
+
+import ToastController from '@/components/pinesUI/ToastController.vue';
+import { toast } from './service/toaster/state';
const appStore = useAppStore();
+const toastPosition = ref<ToastPostion>();
const { lightMode, ambientMode, playbackHeatmap } = storeToRefs(appStore);
const { toggleDarkMode, initDarkMode, initAmbientMode, setAmbientMode, initPlaybackHeatmap, setPlaybackHeatmap } = appStore;
@@ -14,6 +20,14 @@ onMounted(async () => {
initDarkMode();
initAmbientMode();
initPlaybackHeatmap();
+ toast.add('hi');
+ const screenSize = getScreenSize();
+
+ if (screenSize === 'default') {
+ toastPosition.value = 'top-center';
+ } else {
+ toastPosition.value = 'bottom-left';
+ }
});
watch(ambientMode, setAmbientMode, { immediate: false });
@@ -22,6 +36,7 @@ watch(playbackHeatmap, setPlaybackHeatmap, { immediate: false });
</script>
<template>
- <ToastController />
+ <ToastController v-if="toastPosition" :position="toastPosition" />
+ <Toaster />
<RouterView />
</template>
diff --git a/resources/js/app.ts b/resources/js/app.ts
index 6f186b36..09af4e85 100644
--- a/resources/js/app.ts
+++ b/resources/js/app.ts
@@ -4,15 +4,15 @@ import { VueQueryPlugin } from '@tanstack/vue-query';
import { createPinia } from 'pinia';
import { createApp } from 'vue';
-import ToastService from './service/toastService';
import router from './router';
import App from './App.vue';
+import toastService from './service/toaster/toastService.ts';
const application = createApp(App);
const pinia = createPinia();
application.use(router);
application.use(pinia);
-application.use(ToastService);
+application.use(toastService);
application.use(VueQueryPlugin);
application.mount('#app');
diff --git a/resources/js/components/cards/FolderCard.vue b/resources/js/components/cards/FolderCard.vue
index b2f731a5..1d5e9107 100755
--- a/resources/js/components/cards/FolderCard.vue
+++ b/resources/js/components/cards/FolderCard.vue
@@ -23,8 +23,8 @@ const folderLink = ref(`/${props.categoryName}/${props.folder.name}`);
:to="folderLink"
class="text-left relative flex flex-col gap-4 lg:gap-2 sm:flex-row flex-wrap rounded-lg dark:bg-primary-dark-800/70 bg-primary-800 dark:hover:bg-primary-dark-600 hover:bg-gray-200 dark:text-white shadow p-3 w-full group cursor-pointer divide-gray-300 dark:divide-gray-400"
>
- <section class="flex justify-between gap-4 w-full">
- <h2 class="text-xl w-full truncate" :title="props.folder.name">{{ props.folder.name }}</h2>
+ <section class="flex justify-between gap-4 w-full items-center">
+ <h2 class="w-full truncate" :title="props.folder.name">{{ props.folder.name }}</h2>
<div class="flex justify-end gap-1">
<ButtonCorner
:positionClasses="'w-7 h-7'"
@@ -50,7 +50,7 @@ const folderLink = ref(`/${props.categoryName}/${props.folder.name}`);
</ButtonCorner>
</div>
</section>
- <section class="flex flex-col sm:flex-row sm:justify-between w-full flex-wrap">
+ <section class="flex flex-col sm:flex-row sm:justify-between w-full flex-wrap gap-2 text-sm">
<h3
class="text-neutral-500 w-full text-wrap truncate sm:text-nowrap flex-1"
:title="`${props.folder.file_count} Episode${props.folder.file_count !== 1 ? 's' : ''}`"
diff --git a/resources/js/components/cards/RecordCard.vue b/resources/js/components/cards/RecordCard.vue
index ed4cb895..f705c650 100755
--- a/resources/js/components/cards/RecordCard.vue
+++ b/resources/js/components/cards/RecordCard.vue
@@ -32,7 +32,7 @@ const videoLink = computed(() => {
class="text-left relative flex flex-col gap-4 lg:gap-2 sm:flex-row flex-wrap rounded-lg dark:bg-primary-dark-800/70 bg-primary-800 dark:hover:bg-primary-dark-600 hover:bg-gray-200 dark:text-white shadow p-3 w-full group cursor-pointer divide-gray-300 dark:divide-gray-400"
>
<section class="flex justify-between gap-4 w-full items-center">
- <h2 class="text-xl w-full truncate" :title="props.record.relationships.video_name">
+ <h2 class="w-full truncate" :title="props.record.relationships.video_name">
{{ props.record.relationships.video_name }}
</h2>
<div class="flex justify-end gap-1" v-if="videoLink">
@@ -65,7 +65,7 @@ const videoLink = computed(() => {
<!-- {{ formatFileSize(props.record.relationships.metadata?.attributes?.file_size) }} -->
</div>
</section>
- <section class="flex flex-wrap sm:flex-nowrap sm:justify-between w-full gap-x-2">
+ <section class="flex flex-wrap sm:flex-nowrap sm:justify-between w-full gap-x-2 text-sm">
<h3
class="hidden lg:block text-neutral-500 w-full text-wrap truncate sm:text-nowrap shrink-0 sm:shrink"
:title="props.record.relationships.folder?.name"
diff --git a/resources/js/components/cards/SidebarCard.vue b/resources/js/components/cards/SidebarCard.vue
new file mode 100644
index 00000000..2913eca4
--- /dev/null
+++ b/resources/js/components/cards/SidebarCard.vue
@@ -0,0 +1,67 @@
+<script setup lang="ts">
+import { RouterLink } from 'vue-router';
+
+import ButtonCorner from '@/components/inputs/ButtonCorner.vue';
+
+import CircumFolderOn from '~icons/circum/folder-on';
+import CircumShare1 from '~icons/circum/share-1';
+
+const props = defineProps<{
+ link: string;
+ title?: string;
+ class?: string;
+}>();
+</script>
+
+<template>
+ <RouterLink
+ :to="link"
+ :class="`flex flex-col sm:flex-row flex-wrap gap-4 lg:gap-2 relative
+ w-full group cursor-pointer rounded-lg shadow p-3
+ text-left dark:text-white
+ dark:bg-primary-dark-800/70 bg-primary-800
+ dark:hover:bg-primary-dark-600 hover:bg-gray-200
+ divide-gray-300 dark:divide-gray-400 ${props.class}`"
+ >
+ <section class="flex justify-between gap-4 w-full items-center">
+ <slot name="header">
+ <h2 class="w-full truncate" :title="title">{{ title }}</h2>
+ <div class="flex justify-end gap-1">
+ <ButtonCorner
+ :positionClasses="'w-7 h-7'"
+ :textClasses="'hover:text-violet-600 dark:hover:text-violet-500'"
+ :colourClasses="'dark:hover:bg-neutral-800 hover:bg-gray-300'"
+ :label="'Share'"
+ @click.stop.prevent="$emit('clickAction', link)"
+ >
+ <template #icon>
+ <CircumShare1 width="20" height="20" />
+ </template>
+ </ButtonCorner>
+ <ButtonCorner
+ :positionClasses="'w-7 h-7'"
+ :textClasses="`${true ? 'text-violet-600' : 'hover:text-violet-600'} dark:hover:text-violet-500`"
+ :colourClasses="'dark:hover:bg-neutral-800 hover:bg-gray-300'"
+ :to="''"
+ :label="'Open Folder'"
+ >
+ <template #icon>
+ <CircumFolderOn width="20" height="20" />
+ </template>
+ </ButtonCorner>
+ </div>
+ </slot>
+ </section>
+ <section class="flex flex-col sm:flex-row sm:justify-between w-full flex-wrap gap-2 text-sm">
+ <slot name="body">
+ <h3 class="text-neutral-500 w-full text-wrap truncate sm:text-nowrap flex-1" :title="`${2} Episode${2 > 1 ? 's' : ''}`">
+ <!-- {{ 2 }} Episode{{ 2 > 1 ? 's' : '' }} -->
+ </h3>
+ <h3 class="truncate text-nowrap sm:text-right text-neutral-500 w-fit lg:hidden xl:block">
+ <!-- some other folder statistic or data like number of seasons or if its popular or something -->
+ <!-- {{ '20gb' }} -->
+ </h3>
+ </slot>
+ </section>
+ </RouterLink>
+</template>
diff --git a/resources/js/components/charts/PulseLineChart.vue b/resources/js/components/charts/PulseLineChart.vue
index aec19519..7139ebba 100644
--- a/resources/js/components/charts/PulseLineChart.vue
+++ b/resources/js/components/charts/PulseLineChart.vue
@@ -62,7 +62,7 @@ const defaultChartOptions = {
<template>
<Line
- :class="`${props.class ?? 'w-full ring-1 ring-gray-900/5 bg-white dark:bg-primary-dark-800 rounded-md shadow-sm'}`"
+ :class="`${props.class} w-full ring-1 ring-gray-900/5 bg-white dark:bg-primary-dark-800 rounded-md shadow-sm`"
:data="props.chartData ?? defaultChartData"
:options="props.chartOptions ?? defaultChartOptions"
></Line>
diff --git a/resources/js/components/dashboard/DashboardAnalytics.vue b/resources/js/components/dashboard/DashboardAnalytics.vue
index ee31ab77..7fed6064 100644
--- a/resources/js/components/dashboard/DashboardAnalytics.vue
+++ b/resources/js/components/dashboard/DashboardAnalytics.vue
@@ -2,15 +2,19 @@
import type { PulseResponse } from '@/types/types';
import { useGetPulse, useGetSiteAnalytics } from '@/service/queries';
+import { periodForHumans } from '@/service/util';
import { ref, watch } from 'vue';
+import DashboardCard from '@/components/cards/DashboardCard.vue';
import PulseServers from '@/components/pulseCards/PulseServers.vue';
+import PulseQueues from '@/components/pulseCards/PulseQueues.vue';
+import PulseUsage from '@/components/pulseCards/PulseUsage.vue';
+import ButtonIcon from '@/components/inputs/ButtonIcon.vue';
+import ButtonText from '@/components/inputs/ButtonText.vue';
import LucideChartNoAxesCombined from '~icons/lucide/chart-no-axes-combined';
-import PulseQueues from '../pulseCards/PulseQueues.vue';
-import DashboardCard from '../cards/DashboardCard.vue';
-import { periodForHumans } from '@/service/util';
-import PulseUsage from '../pulseCards/PulseUsage.vue';
+import ProiconsArrowSync from '~icons/proicons/arrow-sync';
+import { useToast } from '@/composables/useToast';
const validPeriods: { key: string; value: string }[] = [
{ key: '1h', value: '1_hour' },
@@ -31,6 +35,8 @@ const setPeriod = (newPeriod: string) => {
period.value = newPeriod;
};
+const toast = useToast();
+
watch(
() => rawPulseData.value,
() => {
@@ -43,8 +49,15 @@ watch(
<template>
<section class="flex flex-wrap gap-4 flex-col">
<section class="flex justify-between flex-wrap gap-2">
- <h4>Website Analytics</h4>
- <div class="flex items-center flex-wrap gap-2">
+ <div class="flex items-center gap-2 flex-wrap [&>*]:h-8">
+ <ButtonText @click="toast.add('Success', { type: 'success', description: 'Submitted Scan Request!', life: 3000 })">
+ <template #text>Run Full Scan</template>
+ <template #icon><ProiconsArrowSync /></template>
+ </ButtonText>
+ <ButtonIcon></ButtonIcon>
+ <ButtonIcon></ButtonIcon>
+ </div>
+ <div class="flex items-center flex-wrap gap-2 ml-auto">
<h5>Time Period</h5>
<button
v-for="(validPeriod, index) in validPeriods"
@@ -75,7 +88,7 @@ watch(
<span>
<h3 class="text-lg">{{ stat.count ?? 0 }}</h3>
</span>
- <h4 :class="`text-sm ${stat.change >= 0 ? 'text-green-600' : 'text-red-500'} ml-auto`">
+ <h4 :class="`text-sm ${stat.change >= 0 ? 'text-green-700 dark:text-green-600' : 'text-red-500'} ml-auto`">
{{ `${stat.change === 0 ? 'no change' : `${stat.change >= 0 ? '+' : '-'}${stat.change}`}` }}
</h4>
</span>
diff --git a/resources/js/components/dashboard/DashboardLibraries.vue b/resources/js/components/dashboard/DashboardLibraries.vue
index 8ad38dba..348e5591 100644
--- a/resources/js/components/dashboard/DashboardLibraries.vue
+++ b/resources/js/components/dashboard/DashboardLibraries.vue
@@ -1,9 +1,6 @@
<script setup lang="ts">
import { computed, onMounted, ref } from 'vue';
-import { useContentStore } from '@/stores/ContentStore';
import { getCategories } from '@/service/mediaAPI';
-import { storeToRefs } from 'pinia';
-import { useAppStore } from '@/stores/AppStore';
import { useToast } from '@/composables/useToast';
import RecordCardDetails from '@/components/cards/RecordCardDetails.vue';
@@ -14,17 +11,11 @@ import TableBase from '@/components/table/TableBase.vue';
import useModal from '@/composables/useModal';
const toast = useToast();
-const appStore = useAppStore();
-const ContentStore = useContentStore();
const loading = ref(false);
const cachedID = ref<null | number>(null);
const confirmModal = useModal({ title: 'Delete Category?', submitText: 'Confim' });
const searchQuery = ref('');
-const { getRecords, deleteRecord, recordsSort } = ContentStore;
-const { pageTitle, selectedSideBar } = storeToRefs(appStore);
-const { stateRecords } = storeToRefs(ContentStore);
-
import type { CategoryResource } from '@/types/resources';
import ProiconsAddCircle from '~icons/proicons/add-circle';
@@ -58,9 +49,9 @@ const handleDelete = (id: number) => {
const submitDelete = async () => {
if (cachedID.value) {
- let request = await deleteRecord(cachedID.value);
- if (request) toast.add({ type: 'success', title: 'Success', description: 'Record Deleted Successfully!', life: 3000 });
- else toast.add({ type: 'warning', title: 'Error', description: 'Unable to delete record. Please try again.', life: 3000 });
+ // let request = await deleteRecord(cachedID.value);
+ // if (request) toast.add({ type: 'success', title: 'Success', description: 'Record Deleted Successfully!', life: 3000 });
+ // else toast.add({ type: 'warning', title: 'Error', description: 'Unable to delete record. Please try again.', life: 3000 });
}
};
diff --git a/resources/js/components/inputs/ButtonText.vue b/resources/js/components/inputs/ButtonText.vue
index 3cc88a2c..6c43c806 100755
--- a/resources/js/components/inputs/ButtonText.vue
+++ b/resources/js/components/inputs/ButtonText.vue
@@ -4,7 +4,7 @@ const props = defineProps(['class', 'type', 'disabled', 'title']);
<template>
<button
- :class="`p-2 flex items-center justify-center h-10 max-h-full
+ :class="`p-2 flex items-center justify-center h-10 max-h-full gap-2
shadow-sm rounded-md cursor-pointer focus:outline-none
ring-1 ring-neutral-200 dark:ring-neutral-700 hocus:ring-[0.125rem]
focus:ring-indigo-400 dark:focus:ring-indigo-500 hover:ring-violet-400 hover:dark:ring-violet-700
@@ -15,5 +15,6 @@ const props = defineProps(['class', 'type', 'disabled', 'title']);
:title="props.title ?? 'Button'"
>
<slot name="text"> </slot>
+ <slot name="icon"> </slot>
</button>
</template>
diff --git a/resources/js/components/inputs/ToggleLightMode.vue b/resources/js/components/inputs/ToggleLightMode.vue
index 5ae5db79..3bdec8f4 100755
--- a/resources/js/components/inputs/ToggleLightMode.vue
+++ b/resources/js/components/inputs/ToggleLightMode.vue
@@ -27,7 +27,8 @@ const { lightMode } = storeToRefs(appStore);
position: relative;
width: 60px;
height: 30px;
- --light: #d8dbe0;
+ --light: #ffffff;
+ /* --light: #d8dbe0; */
--dark: #28292c;
--disabled: #d8dbe0;
--enabled: #28292c;
diff --git a/resources/js/components/pinesUI/Toast.vue b/resources/js/components/pinesUI/Toast.vue
new file mode 100644
index 00000000..e513caaf
--- /dev/null
+++ b/resources/js/components/pinesUI/Toast.vue
@@ -0,0 +1,402 @@
+<script lang="ts" setup>
+import './styles.css';
+
+import { computed, onBeforeUnmount, onMounted, ref, watch, watchEffect } from 'vue';
+import { type HeightT, type ToastProps, type ToastT, isAction } from './types';
+import { useIsDocumentHidden } from '/hooks';
+
+const props = defineProps<ToastProps>();
+
+const emit = defineEmits<{
+ (e: 'update:heights', heights: HeightT[]): void;
+ (e: 'removeToast', toast: ToastT): void;
+}>();
+
+// Default lifetime of a toasts (in ms)
+const TOAST_LIFETIME = 4000;
+
+const SWIPE_THRESHOLD = 20;
+
+const TIME_BEFORE_UNMOUNT = 200;
+
+const mounted = ref(false);
+const removed = ref(false);
+const swiping = ref(false);
+const swipeOut = ref(false);
+const swiped = ref(false);
+const offsetBeforeRemove = ref(0);
+const initialHeight = ref(0);
+const remainingTime = ref(props.toast.duration || props.duration || TOAST_LIFETIME);
+const dragStartTime = ref<Date | null>(null);
+const toastRef = ref<HTMLLIElement | null>(null);
+const isFront = computed(() => props.index === 0);
+const isVisible = computed(() => props.index + 1 <= props.visibleToasts);
+const toastType = computed(() => props.toast.type);
+const dismissible = computed(() => props.toast.dismissible !== false);
+const toastClass = computed(() => props.toast.class || '');
+const toastDescriptionClass = computed(() => props.descriptionClass || '');
+
+const toastStyle = props.toast.style || {};
+
+// Height index is used to calculate the offset as it gets updated before the toast array, which means we can calculate the new layout faster.
+const heightIndex = computed(() => props.heights.findIndex((height) => height.toastId === props.toast.id) || 0);
+const closeButton = computed(() => props.toast.closeButton ?? props.closeButton);
+const duration = computed(() => props.toast.duration || props.duration || TOAST_LIFETIME);
+
+const closeTimerStartTimeRef = ref(0);
+const lastCloseTimerStartTimeRef = ref(0);
+const pointerStartRef = ref<{ x: number; y: number } | null>(null);
+const coords = computed(() => props.position.split('-'));
+const y = computed(() => coords.value[0]);
+const x = computed(() => coords.value[1]);
+const isStringOfTitle = computed(() => typeof props.toast.title !== 'string');
+const isStringOfDescription = computed(() => typeof props.toast.description !== 'string');
+
+const toastsHeightBefore = computed(() => {
+ return props.heights.reduce((prev, curr, reducerIndex) => {
+ // Calculate offset up untill current toast
+ if (reducerIndex >= heightIndex.value) {
+ return prev;
+ }
+
+ return prev + curr.height;
+ }, 0);
+});
+const isDocumentHidden = useIsDocumentHidden();
+const invert = computed(() => props.toast.invert || props.invert);
+const disabled = computed(() => toastType.value === 'loading');
+
+const offset = computed(() => {
+ return heightIndex.value * props.gap! + toastsHeightBefore.value || 0;
+});
+
+onMounted(() => {
+ if (!mounted.value) return;
+
+ const toastNode = toastRef.value;
+ const originalHeight = toastNode?.style.height;
+ toastNode!.style.height = 'auto';
+ const newHeight = toastNode!.getBoundingClientRect().height;
+ toastNode!.style.height = originalHeight as string;
+
+ initialHeight.value = newHeight;
+
+ let newHeightArr;
+
+ const alreadyExists = props.heights.find((height) => height.toastId === props.toast.id);
+
+ if (!alreadyExists) {
+ newHeightArr = [
+ {
+ toastId: props.toast.id,
+ height: newHeight,
+ position: props.toast.position,
+ },
+ ...props.heights,
+ ];
+ } else {
+ newHeightArr = props.heights.map((height) => (height.toastId === props.toast.id ? { ...height, height: newHeight } : height));
+ }
+
+ emit('update:heights', newHeightArr as HeightT[]);
+});
+
+function deleteToast() {
+ // Save the offset for the exit swipe animation
+ removed.value = true;
+ offsetBeforeRemove.value = offset.value;
+ const height = props.heights.filter((height) => height.toastId !== props.toast.id);
+ emit('update:heights', height);
+
+ setTimeout(() => {
+ emit('removeToast', props.toast);
+ }, TIME_BEFORE_UNMOUNT);
+}
+
+function handleCloseToast() {
+ if (disabled.value || !dismissible.value) {
+ return {};
+ }
+
+ deleteToast();
+ props.toast.onDismiss?.(props.toast);
+}
+
+function onPointerDown(event: PointerEvent) {
+ if (disabled.value || !dismissible.value) return;
+ dragStartTime.value = new Date();
+ offsetBeforeRemove.value = offset.value;
+ // Ensure we maintain correct pointer capture even when going outside of the toast (e.g. when swiping)
+ (event.target as HTMLElement).setPointerCapture(event.pointerId);
+ if ((event.target as HTMLElement).tagName === 'BUTTON') return;
+ swiping.value = true;
+ pointerStartRef.value = { x: event.clientX, y: event.clientY };
+}
+
+function onPointerUp() {
+ if (swipeOut.value || !dismissible) return;
+ pointerStartRef.value = null;
+
+ const swipeAmount = Number(toastRef.value?.style.getPropertyValue('--swipe-amount').replace('px', '') || 0);
+
+ const timeTaken = new Date().getTime() - dragStartTime.value?.getTime()!;
+ const velocity = Math.abs(swipeAmount) / timeTaken;
+
+ // Remove only if treshold is met
+ if (Math.abs(swipeAmount) >= SWIPE_THRESHOLD || velocity > 0.11) {
+ offsetBeforeRemove.value = offset.value;
+ props.toast.onDismiss?.(props.toast);
+ deleteToast();
+ swipeOut.value = true;
+ swiped.value = false;
+ return;
+ }
+
+ toastRef.value?.style.setProperty('--swipe-amount', '0px');
+ swiping.value = false;
+}
+
+function onPointerMove(event: PointerEvent) {
+ if (!pointerStartRef.value || !dismissible.value) return;
+
+ const yPosition = event.clientY - pointerStartRef.value.y;
+
+ // @ts-expect-error
+ const isHighlighted = window.getSelection()?.toString().length > 0;
+
+ const swipeAmount = y.value === 'top' ? Math.min(0, yPosition) : Math.max(0, yPosition);
+
+ if (Math.abs(swipeAmount) > 0) {
+ swiped.value = true;
+ }
+
+ if (isHighlighted) return;
+
+ toastRef.value?.style.setProperty('--swipe-amount', `${swipeAmount}px`);
+}
+
+watchEffect((onInvalidate) => {
+ if ((props.toast.promise && toastType.value === 'loading') || props.toast.duration === Infinity || props.toast.type === 'loading') {
+ return;
+ }
+ let timeoutId: ReturnType<typeof setTimeout>;
+
+ // Pause the timer on each hover
+ const pauseTimer = () => {
+ if (lastCloseTimerStartTimeRef.value < closeTimerStartTimeRef.value) {
+ // Get the elapsed time since the timer started
+ const elapsedTime = new Date().getTime() - closeTimerStartTimeRef.value;
+
+ remainingTime.value = remainingTime.value - elapsedTime;
+ }
+
+ lastCloseTimerStartTimeRef.value = new Date().getTime();
+ };
+
+ const startTimer = () => {
+ if (remainingTime.value === Infinity) return;
+ closeTimerStartTimeRef.value = new Date().getTime();
+
+ // Let the toast know it has started
+ timeoutId = setTimeout(() => {
+ props.toast.onAutoClose?.(props.toast);
+ deleteToast();
+ }, remainingTime.value);
+ };
+
+ if (props.expanded || props.interacting || (props.pauseWhenPageIsHidden && isDocumentHidden)) {
+ pauseTimer();
+ } else {
+ startTimer();
+ }
+
+ onInvalidate(() => {
+ clearTimeout(timeoutId);
+ });
+});
+
+watch(
+ () => props.toast.delete,
+ () => {
+ if (props.toast.delete) {
+ deleteToast();
+ }
+ },
+ {
+ deep: true,
+ },
+);
+
+onMounted(() => {
+ mounted.value = true;
+
+ if (toastRef.value) {
+ const height = toastRef.value.getBoundingClientRect().height;
+ // Add toast height tot heights array after the toast is mounted
+ initialHeight.value = height;
+
+ const newHeights = [{ toastId: props.toast.id, height, position: props.toast.position! }, ...props.heights];
+ emit('update:heights', newHeights);
+ }
+});
+
+onBeforeUnmount(() => {
+ if (toastRef.value) {
+ const newHeights = props.heights.filter((height) => height.toastId !== props.toast.id);
+ emit('update:heights', newHeights);
+ }
+});
+</script>
+
+<template>
+ <li
+ ref="toastRef"
+ :aria-live="toast.important ? 'assertive' : 'polite'"
+ aria-atomic="true"
+ role="status"
+ tabindex="0"
+ data-sonner-toast="true"
+ :class="
+ cn(
+ props.class,
+ toastClass,
+ classes?.toast,
+ toast.classes?.toast,
+ // @ts-ignore
+ classes?.[toastType],
+ // @ts-ignore
+ toast?.classes?.[toastType],
+ )
+ "
+ :data-rich-colors="toast.richColors ?? defaultRichColors"
+ :data-styled="!Boolean(toast.component || toast?.unstyled || unstyled)"
+ :data-mounted="mounted"
+ :data-promise="Boolean(toast.promise)"
+ :data-removed="removed"
+ :data-visible="isVisible"
+ :data-y-position="y"
+ :data-x-position="x"
+ :data-index="index"
+ :data-front="isFront"
+ :data-swiping="swiping"
+ :data-dismissible="dismissible"
+ :data-type="toastType"
+ :data-invert="invert"
+ :data-swipe-out="swipeOut"
+ :data-expanded="Boolean(expanded || (expandByDefault && mounted))"
+ :style="{
+ '--index': index,
+ '--toasts-before': index,
+ '--z-index': toasts.length - index,
+ '--offset': `${removed ? offsetBeforeRemove : offset}px`,
+ '--initial-height': expandByDefault ? 'auto' : `${initialHeight}px`,
+ ...style,
+ ...toastStyle,
+ }"
+ @pointerdown="onPointerDown"
+ @pointerup="onPointerUp"
+ @pointermove="onPointerMove"
+ >
+ <template v-if="closeButton && !toast.component">
+ <button
+ :aria-label="closeButtonAriaLabel || 'Close toast'"
+ :data-disabled="disabled"
+ data-close-button="true"
+ :class="cn(classes?.closeButton, toast?.classes?.closeButton)"
+ @click="handleCloseToast"
+ >
+ <template v-if="icons?.close">
+ <component :is="icons?.close" />
+ </template>
+ <template v-else>
+ <slot name="close-icon" />
+ </template>
+ </button>
+ </template>
+
+ <template v-if="toast.component">
+ <component :is="toast.component" v-bind="toast.componentProps" :onCloseToast="handleCloseToast" />
+ </template>
+
+ <template v-else>
+ <template v-if="toastType !== 'default' || toast.icon || toast.promise">
+ <div data-icon="" :class="cn(classes?.icon, toast?.classes?.icon)">
+ <template v-if="(toast.promise || toastType === 'loading') && !toast.icon">
+ <slot name="loading-icon" />
+ </template>
+
+ <component :is="toast.icon" v-if="toast.icon" />
+
+ <template v-else>
+ <slot v-if="toastType === 'success'" name="success-icon" />
+ <slot v-else-if="toastType === 'error'" name="error-icon" />
+ <slot v-else-if="toastType === 'warning'" name="warning-icon" />
+ <slot v-else-if="toastType === 'info'" name="info-icon" />
+ </template>
+ </div>
+ </template>
+
+ <div data-content="" :class="cn(classes?.content, toast?.classes?.content)">
+ <div data-title="" :class="cn(classes?.title, toast.classes?.title)">
+ <template v-if="isStringOfTitle">
+ <component :is="toast.title" v-bind="toast.componentProps" />
+ </template>
+ <template v-else>
+ {{ toast.title }}
+ </template>
+ </div>
+
+ <template v-if="toast.description">
+ <div
+ data-description=""
+ :class="cn(descriptionClass, toastDescriptionClass, classes?.description, toast.classes?.description)"
+ >
+ <template v-if="isStringOfDescription">
+ <component :is="toast.description" v-bind="toast.componentProps" />
+ </template>
+ <template v-else>
+ {{ toast.description }}
+ </template>
+ </div>
+ </template>
+ </div>
+ <template v-if="toast.cancel">
+ <button
+ :style="toast.cancelButtonStyle || cancelButtonStyle"
+ :class="cn(classes?.cancelButton, toast.classes?.cancelButton)"
+ data-button
+ data-cancel
+ @click="
+ (event) => {
+ if (!isAction(toast.cancel!)) return;
+ if (!dismissible) return;
+ toast.cancel.onClick?.(event);
+ deleteToast();
+ }
+ "
+ >
+ {{ isAction(toast.cancel) ? toast.cancel?.label : toast.cancel }}
+ </button>
+ </template>
+ <template v-if="toast.action">
+ <button
+ :style="toast.actionButtonStyle || actionButtonStyle"
+ :class="cn(classes?.actionButton, toast.classes?.actionButton)"
+ data-button
+ data-action
+ @click="
+ (event) => {
+ if (!isAction(toast.action!)) return;
+ if (event.defaultPrevented) return;
+ toast.action.onClick?.(event);
+ if (event.defaultPrevented) return;
+ deleteToast();
+ }
+ "
+ >
+ {{ isAction(toast.action) ? toast.action?.label : toast.action }}
+ </button>
+ </template>
+ </template>
+ </li>
+</template>
diff --git a/resources/js/components/pinesUI/ToastController.vue b/resources/js/components/pinesUI/ToastController.vue
index 368bf94e..99202cb7 100755
--- a/resources/js/components/pinesUI/ToastController.vue
+++ b/resources/js/components/pinesUI/ToastController.vue
@@ -1,284 +1,298 @@
-<script>
+<script lang="ts">
+// Visible toasts amount
+const VISIBLE_TOASTS_AMOUNT = 3;
+
+// Viewport padding
+const VIEWPORT_OFFSET = '24px';
+const MOBILE_VIEWPORT_OFFSET = '16px';
+
+// Default toast width
+const TOAST_WIDTH = 0;
+
+// Default gap between toasts
+const GAP = 16;
+</script>
+
+<script setup lang="ts">
// This is so bad lol pls fix
+import { type ExternalToast, type Message, type ToastControllerProps, type ToastLayout, type ToastPostion } from '@/types/pinesTypes';
+import { onBeforeUnmount, onMounted, ref, watch } from 'vue';
-import ToastEventBus from '@/service/toastEventBus';
import ToastNotification from '@/components/pinesUI/ToastNotification.vue';
+import ToastEventBus from '@/service/toastEventBus';
+
+const props = withDefaults(defineProps<ToastControllerProps>(), {
+ layout: 'default',
+ position: 'bottom-right',
+ defaultLife: 3000,
+ maxVisibleToasts: VISIBLE_TOASTS_AMOUNT,
+ viewportOffset: VIEWPORT_OFFSET,
+ mobileViewportOffset: MOBILE_VIEWPORT_OFFSET,
+ paddingBetweenToasts: GAP,
+});
+
+const container = ref<HTMLElement>();
-var messageIdx = 0;
+const messages = ref<Message[]>([]);
+const layout = ref<ToastLayout>(props.layout);
+const position = ref<ToastPostion>(props.position);
+
+const toastsHovered = ref(false);
+const expanded = ref(props.layout === 'expanded' ? true : false);
+const paddingBetweenToasts = ref(props.paddingBetweenToasts);
+const heightRecalculateTimeout = ref<null | number>(null);
function UniqueComponentId(prefix = 'pv_id_') {
return prefix + Math.random().toString(16).slice(2);
}
-export default {
- name: 'ToastController',
- emits: ['close'],
- data() {
- return {
- messages: [],
- positionRoot: 'bottom-left',
- toastsHovered: false,
- expanded: false,
- layout: 'default',
- paddingBetweenToasts: 16,
- heightRecalculateTimeout: null,
- };
- },
- mounted() {
- ToastEventBus.on('add', this.onAdd);
- ToastEventBus.on('remove', this.onRemove);
- ToastEventBus.on('remove-group', this.onRemoveGroup);
- ToastEventBus.on('remove-all-groups', this.onRemoveAllGroups);
- this.stackToasts();
- },
- beforeUnmount() {
- ToastEventBus.off('add', this.onAdd);
- ToastEventBus.off('remove', this.onRemove);
- ToastEventBus.off('remove-group', this.onRemoveGroup);
- ToastEventBus.off('remove-all-groups', this.onRemoveAllGroups);
- },
- watch: {
- // whenever question changes, this function will run
- toastsHovered(value) {
- if (this.layout == 'default') {
- // if (this.position.includes('bottom')) {
- // this.resetBottom();
- // } else {
- // this.resetTop();
- // }
-
- if (value) {
- // calculate the new positions
- this.expanded = true;
- if (this.layout == 'default') {
- this.stackToasts();
- }
- } else {
- if (this.layout == 'default') {
- this.expanded = false;
- // setTimeout(function(){
- this.stackToasts();
- // }, 10);
- // setTimeout(function () {
- // this.stackToasts();
- // }, 10)
- }
- }
- }
- },
- },
- methods: {
- add(message) {
- if (message.position && this.positionIsValid(message.position)) this.positionRoot = message.position;
- if (message.type && !this.typeIsValid(message.type)) message.type = 'default';
-
- if (message.idx == null) {
- message.idx = messageIdx;
- messageIdx++;
- }
+function onAdd(toast: ExternalToast) {
+ console.log(toast);
- if (message.id == null) {
- message.id = UniqueComponentId('toast_');
- }
+ if (toast.options.position) position.value = toast.options.position;
- this.messages.unshift(message);
- },
- remove(params) {
- if (!params.message.idx) return; // This is slow and causes issues. Every second remove is not called because the last one is blocking the event somehow. Doing it right in the event watcher makes it work correctly.
- // for (let i = 0; i < this.messages.length; i++) {
- // if (this.messages[i].idx === params.message.idx) {
- // console.log('found ' + params.message.idx);
-
- // this.messages.splice(i, 1);
- // break;
- // }
- // }
- // if (this.messages[params.message.idx]) {
- // // delete this.messages[params.message.idx]
- // // this.$emit(params.type, { message: params.message });
- // }
- },
- onAdd(message) {
- if (this.group == message.group) {
- this.add(message);
- }
- },
- onRemove(message) {
- this.remove({ message, type: 'close' });
- },
- onRemoveGroup(group) {
- if (this.group === group) {
- this.messages = [];
- }
- },
- onRemoveAllGroups() {
- this.messages = [];
- },
- stackToasts() {
- this.positionToasts();
- this.calculateHeightOfToastsContainer();
- if (this.heightRecalculateTimeout) clearTimeout(this.heightRecalculateTimeout);
-
- let that = this;
- this.heightRecalculateTimeout = setTimeout(function () {
- that.calculateHeightOfToastsContainer();
- }, 300);
- },
- positionToasts() {
- try {
- let scaleBuffer = 1;
- let yBuffer = -16;
- let zBuffer = 100;
- let bottomFlag = this.positionRoot.includes('bottom');
- let totalHeight = 0;
- let topToast = null;
- for (let i = 0; i < this.messages.length; i++) {
- const toast = document.getElementById(this.messages[i].id);
- toast.style.zIndex = zBuffer;
- if (zBuffer > 0) zBuffer -= 10;
-
- yBuffer += 16;
-
- if (this.expanded) {
- totalHeight = totalHeight + (totalHeight ? this.paddingBetweenToasts : 0);
-
- if (bottomFlag) {
- toast.style.top = 'auto';
- toast.style.bottom = totalHeight + 'px';
- } else toast.style.top = totalHeight + 'px';
-
- totalHeight += toast.getBoundingClientRect().height;
- toast.style.scale = 1;
- continue;
- }
+ if (toast.options.id == null) {
+ toast.options.id = UniqueComponentId('toast_');
+ }
+ messages.value.unshift({
+ ...toast.options,
+ id: toast.options.id ?? UniqueComponentId('toast_'),
+ type: toast.options.type ?? 'default',
+ position: toast.options.position ?? position.value,
+ life: toast.options.life ?? props.defaultLife,
+ title: toast.title,
+ });
+}
+function onRemove(message: Message) {
+ let params = { message, type: 'close' };
+ if (!params.message.id) return; // This is slow and causes issues. Every second remove is not called because the last one is blocking the event somehow. Doing it right in the event watcher makes it work correctly.
+ // for (let i = 0; i < this.messages.length; i++) {
+ // if (this.messages[i].idx === params.message.idx) {
+ // console.log('found ' + params.message.idx);
+
+ // this.messages.splice(i, 1);
+ // break;
+ // }
+ // }
+ // if (this.messages[params.message.idx]) {
+ // // delete this.messages[params.message.idx]
+ // // this.$emit(params.type, { message: params.message });
+ // }
+ deleteToastWithId(params.message.id);
+}
+
+function deleteToastWithId(id: string) {
+ messages.value = messages.value.filter((msg) => msg.id !== id);
+ stackToasts();
+}
+
+function stackToasts() {
+ positionToasts();
+ calculateHeightOfToastsContainer();
+
+ if (heightRecalculateTimeout.value) clearTimeout(heightRecalculateTimeout.value);
+
+ heightRecalculateTimeout.value = setTimeout(() => {
+ calculateHeightOfToastsContainer();
+ }, 300);
+}
+
+function positionToasts() {
+ if (messages.value.length == 0) return;
+
+ try {
+ let scaleBuffer = 1;
+ let yBuffer = 0;
+ let zBuffer = 200;
+ let bottomFlag = position.value.includes('bottom');
+ let totalHeight = 0;
+ let toastElements = [];
+ for (let i = 0; i < messages.value.length; i++) {
+ const toast = document.getElementById(`${messages.value[i].id}`);
+
+ if (!toast) return;
+ toast.style.zIndex = `${zBuffer}`;
+ toastElements.push(toast);
+
+ if (expanded.value) {
+ totalHeight = totalHeight + (totalHeight ? paddingBetweenToasts.value : 0);
+
+ if (bottomFlag) {
toast.style.top = 'auto';
- toast.style.bottom = 'auto';
- toast.style.scale = scaleBuffer;
- toast.style.transform = yBuffer ? `translateY(${bottomFlag ? '-' : ''}${yBuffer}px)` : '';
- if (i === 0) topToast = toast;
- else this.alignBottom(topToast, toast);
- scaleBuffer -= 0.06;
- }
+ toast.style.bottom = totalHeight + 'px';
+ } else toast.style.top = totalHeight + 'px';
+ // console.log('totalHeight', i + 1, totalHeight);
+
+ totalHeight += toast.getBoundingClientRect().height;
+ // console.log(toast.getBoundingClientRect().height);
+
+ toast.style.scale = `100%`;
+ toast.style.transform = `translateY(0px)`;
+ } else if (i > 0) {
+ toast.style.scale = `${scaleBuffer}`;
- if (this.messages[3]) {
- let burnToast = document.getElementById(this.messages[3].id);
- burnToast.classList.remove('opacity-100');
- burnToast.classList.add('opacity-0');
- this.messages.splice(3, 1);
- this.stackToasts();
- // let that = this;
- // // Burn 🔥 (remove) last toast
- // setTimeout(function () {
- // for (let i = 0; i < that.messages.length; i++) {
- // if (that.messages[i].idx === burnToast.idx) {
- // that.messages.splice(i, 1);
- // break;
- // }
- // }
- // }, 300);
-
- // if (bottomFlag && this.messages[1]) {
- // this.messages[1].style.top = "auto";
- // }
+ if (bottomFlag && !(i >= props.maxVisibleToasts)) {
+ toast.style.transform = `translateY(-${yBuffer}px)`;
+ } else {
+ alignBottom(toastElements[0], toast);
+ toast.style.transform = `translateY(${yBuffer}px)`;
}
- } catch (error) {
- console.log(error);
}
- },
- alignBottom(element1, element2) {
- // Get the top position and height of the first element
- let top1 = element1.offsetTop;
- let height1 = element1.offsetHeight;
-
- // Get the height of the second element
- let height2 = element2.offsetHeight;
-
- // Calculate the top position for the second element
- let top2 = top1 + (height1 - height2);
-
- // Apply the calculated top position to the second element
- element2.style.top = top2 + 'px';
- },
- calculateHeightOfToastsContainer() {
- if (this.messages.length == 0) {
- this.$refs.container.style.height = '0px';
- return;
+
+ zBuffer -= 10;
+ scaleBuffer -= 0.06;
+ yBuffer += 16;
+ }
+
+ let burnToast = document.getElementById(`${messages.value[props.maxVisibleToasts]?.id}`);
+
+ if (burnToast) {
+ burnToast.firstElementChild?.classList.remove('opacity-100');
+ burnToast.firstElementChild?.classList.add('opacity-0');
+
+ // Burn 🔥 (remove) last toast
+ setTimeout(function () {
+ messages.value.pop();
+ }, 300);
+
+ if (position.value.includes('bottom')) {
+ toastElements[1].style.top = 'auto';
}
+ }
+ } catch (error) {
+ console.log(error);
+ }
+}
- let lastToast = this.messages[this.messages.length - 1];
- let lastToastRectangle = document.getElementById(lastToast.id).getBoundingClientRect();
+function alignBottom(element1: HTMLElement, element2: HTMLElement) {
+ // Get the top position and height of the first element
+ let top1 = element1.offsetTop;
+ let height1 = element1.offsetHeight;
- let firstToast = this.messages[0];
- let firstToastRectangle = document.getElementById(firstToast.id).getBoundingClientRect();
+ // Get the height of the second element
+ let height2 = element2.offsetHeight;
- if (this.toastsHovered) {
- if (this.positionRoot.includes('bottom')) {
- this.$refs.container.style.height =
- firstToastRectangle.top + firstToastRectangle.height - lastToastRectangle.top + 'px';
- } else {
- this.$refs.container.style.height = lastToastRectangle.top + lastToastRectangle.height - firstToastRectangle.top + 'px';
+ // Calculate the top position for the second element
+ let top2 = top1 + (height1 - height2);
+
+ // Apply the calculated top position to the second element
+ element2.style.top = top2 + 'px';
+}
+
+function calculateHeightOfToastsContainer() {
+ if (!container.value) return;
+
+ if (messages.value.length == 0) {
+ container.value.style.height = '0px';
+ return;
+ }
+
+ let lastToast = messages.value[messages.value.length - 1];
+ let lastToastRectangle = document.getElementById(`${lastToast?.id}`)?.getBoundingClientRect();
+
+ let firstToast = messages.value[0];
+ let firstToastRectangle = document.getElementById(`${firstToast?.id}`)?.getBoundingClientRect();
+
+ if (!firstToastRectangle || !lastToastRectangle) return;
+
+ if (toastsHovered.value) {
+ if (position.value.includes('bottom')) {
+ container.value.style.height = firstToastRectangle.top + firstToastRectangle.height - lastToastRectangle.top + 'px';
+ } else {
+ container.value.style.height = lastToastRectangle.top + lastToastRectangle.height - firstToastRectangle.top + 'px';
+ }
+ } else {
+ container.value.style.height = firstToastRectangle.height + 'px';
+ }
+}
+
+function resetBottom() {
+ for (let i = 0; i < messages.value.length; i++) {
+ let toastElement = document.getElementById(`${messages.value[i]?.id}`);
+ if (toastElement) {
+ toastElement.style.bottom = '0px';
+ }
+ }
+}
+function resetTop() {
+ for (let i = 0; i < messages.value.length; i++) {
+ let toastElement = document.getElementById(`${messages.value[i]?.id}`);
+ if (toastElement) {
+ toastElement.style.top = '0px';
+ }
+ }
+}
+
+onMounted(() => {
+ ToastEventBus.on('add', onAdd);
+ ToastEventBus.on('remove', onRemove);
+ stackToasts();
+});
+
+onBeforeUnmount(() => {
+ ToastEventBus.off('add', onAdd);
+ ToastEventBus.off('remove', onRemove);
+});
+
+watch(
+ () => toastsHovered.value,
+ (value) => {
+ if (layout.value == 'default') {
+ if (position.value.includes('bottom')) {
+ resetBottom();
+ } else {
+ resetTop();
+ }
+
+ if (value) {
+ // calculate the new positions
+ expanded.value = true;
+ if (layout.value == 'default') {
+ stackToasts();
}
} else {
- this.$refs.container.style.height = firstToastRectangle.height + 'px';
+ if (layout.value == 'default') {
+ expanded.value = false;
+ setTimeout(function () {
+ stackToasts();
+ }, 10);
+ setTimeout(function () {
+ stackToasts();
+ }, 10);
+ }
}
- },
- positionIsValid(newPosition) {
- return (
- newPosition == 'top-right' ||
- newPosition == 'top-left' ||
- newPosition == 'top-center' ||
- newPosition == 'bottom-right' ||
- newPosition == 'bottom-left' ||
- newPosition == 'bottom-center'
- );
- },
- typeIsValid(newType) {
- return newType == 'success' || newType == 'info' || newType == 'warning' || newType == 'danger' || newType == 'default';
- },
- },
- components: {
- ToastNotification: ToastNotification,
+ }
},
-};
+);
</script>
<template>
<teleport to="body">
<ul
- class="fixed w-full group z-[99] sm:max-w-xs"
- id="toastRoot"
- :class="{
- 'right-0 top-0 sm:mt-6 sm:mr-6': positionRoot == 'top-right',
- 'left-0 top-0 sm:mt-6 sm:ml-6': positionRoot == 'top-left',
- 'left-1/2 -translate-x-1/2 top-0 sm:mt-6': positionRoot == 'top-center',
- 'right-0 sm:mr-6 top-0 md:top-auto md:bottom-0 sm:mt-6 md:mb-6': positionRoot == 'bottom-right',
- 'left-0 sm:ml-6 top-0 md:top-auto md:bottom-0 sm:mt-6 md:mb-6': positionRoot == 'bottom-left',
- 'left-1/2 -translate-x-1/2 top-0 md:top-auto md:bottom-0 sm:mt-6 md:mb-6': positionRoot == 'bottom-center',
- }"
v-cloak
ref="container"
+ :tabIndex="-1"
+ :class="
+ `fixed w-full ${TOAST_WIDTH ? `sm:w-[${TOAST_WIDTH}px]` : 'sm:max-w-sm'} group z-[99] [&>*]:px-[${mobileViewportOffset ?? viewportOffset}] [&>*]:sm:px-[${viewportOffset}] my-[${mobileViewportOffset ?? viewportOffset}] sm:my-[${viewportOffset}] ` +
+ `${position == 'top-right' ? 'right-0 top-0' : ''} ` +
+ `${position == 'top-left' ? 'left-0 top-0' : ''} ` +
+ `${position == 'top-center' ? 'left-1/2 -translate-x-1/2 top-0' : ''} ` +
+ `${position == 'bottom-right' ? 'right-0 bottom-0' : ''} ` +
+ `${position == 'bottom-left' ? 'left-0 bottom-0' : ''} ` +
+ `${position == 'bottom-center' ? 'left-1/2 -translate-x-1/2 bottom-0' : ''} `
+ "
@mouseenter="toastsHovered = true"
@mouseleave="toastsHovered = false"
>
<ToastNotification
v-for="toast in messages"
- :key="toast.idx"
- :type="toast.type"
v-bind="toast"
+ :key="toast.id"
:stack="stackToasts"
- :count="messages.length"
- @close="
- (event) => {
- for (let i = 0; i < messages.length; i++) {
- if (messages[i].idx === toast.idx) {
- messages.splice(i, 1);
- stackToasts();
- break;
- }
- }
- }
- "
+ :toastCount="messages.length"
+ :position="position"
+ @close="deleteToastWithId"
/>
</ul>
</teleport>
diff --git a/resources/js/components/pinesUI/ToastNotification.vue b/resources/js/components/pinesUI/ToastNotification.vue
index 73035ca0..de87170e 100755
--- a/resources/js/components/pinesUI/ToastNotification.vue
+++ b/resources/js/components/pinesUI/ToastNotification.vue
@@ -1,47 +1,19 @@
<script setup lang="ts">
+import type { ToastProps } from '@/types/pinesTypes';
import { onBeforeUnmount, onMounted, ref } from 'vue';
-const emit = defineEmits(['close']);
-const props = defineProps({
- type: {
- type: String,
- default: 'default',
- },
- position: {
- type: String,
- default: 'bottom-center',
- },
- life: {
- type: Number,
- default: 4000,
- },
- idx: {
- type: Number,
- },
- id: {
- type: String,
- },
- title: {
- type: String,
- default: 'Title',
- },
- description: {
- type: String,
- },
- count: {
- type: Number,
- required: true,
- },
- html: {
- default: '',
- },
- isValid: {
- type: Boolean,
- },
- stack: {
- type: Function,
- default: () => {},
- },
+const emit = defineEmits<{
+ // (e: 'update:heights', heights: HeightT[]): void;
+ (e: 'close', toast: any): void; // removeToast
+}>();
+
+const props = withDefaults(defineProps<ToastProps>(), {
+ type: 'default',
+ position: 'bottom-center',
+ life: 4000,
+ title: 'Title',
+ html: '',
+ style: '',
});
const toastHovered = ref(false);
@@ -49,32 +21,15 @@ const mounted = ref(false);
const animateTimeout = ref<null | number>(null);
const closeTimeout = ref<null | number>(null);
const stackTimeout = ref<null | number>(null);
-onMounted(() => {
- mounted.value = true;
- if (stackTimeout.value) clearTimeout(stackTimeout.value);
+function onClose() {
+ if (closeTimeout.value) return;
- stackTimeout.value = setTimeout(() => {
- props.stack();
- });
-
- if (props.life) {
- animateClose();
- }
-});
-
-onBeforeUnmount(() => {
- clearCloseTimeout();
-});
-
-function close(params: any) {
- emit('close', params);
-}
+ if (animateTimeout.value) clearTimeout(animateTimeout.value);
-function onCloseClick() {
mounted.value = false;
closeTimeout.value = setTimeout(() => {
- close({ message: { idx: props.idx }, type: 'life-end' });
+ emit('close', props.id);
}, 500);
}
function clearCloseTimeout() {
@@ -92,33 +47,46 @@ function clearCloseTimeout() {
}
}
-function animateClose() {
- animateTimeout.value = setTimeout(() => {
- onCloseClick();
- }, props.life);
-}
+onMounted(() => {
+ mounted.value = true;
+
+ if (stackTimeout.value) clearTimeout(stackTimeout.value);
+
+ stackTimeout.value = setTimeout(() => {
+ props.stack();
+ });
+
+ if (props.life) {
+ animateTimeout.value = setTimeout(() => {
+ // onClose();
+ }, props.life);
+ }
+});
+
+onBeforeUnmount(() => {
+ clearCloseTimeout();
+});
</script>
<template>
- <Transition
- enter-active-class="ease-out duration-300"
- :enter-from-class="`opacity-0 ${props.position.includes('bottom') ? '-translate-y-full md:translate-y-full' : '-translate-y-full'}`"
- :enter-to-class="`opacity-100 translate-y-0`"
- leave-active-class="ease-out duration-300"
- :leave-from-class="`opacity-100 translate-y-0`"
- :leave-to-class="`opacity-0 ${props.count == 1 ? (props.position.includes('bottom') ? '-translate-y-full md:translate-y-full' : '-translate-y-full') : 'translate-y-0'}`"
+ <li
+ :id="props.id"
+ @mouseover="toastHovered = true"
+ @mouseout="toastHovered = false"
+ :class="`w-full absolute duration-300 ease-out transition-all select-none ${!description ? 'toast-no-description' : ''} ${style}`"
>
- <li
- v-show="mounted"
- :id="props.id"
- @mouseover="toastHovered = true"
- @mouseout="toastHovered = false"
- class="absolute w-full duration-300 ease-out select-none sm:max-w-xs"
- :class="{ 'toast-no-description': !props.description }"
+ <Transition
+ enter-active-class=""
+ :enter-from-class="`opacity-0 ${props.position.includes('bottom') ? 'translate-y-full' : '-translate-y-full'}`"
+ :enter-to-class="`opacity-100 translate-y-0`"
+ leave-active-class=""
+ :leave-from-class="`opacity-100 translate-y-0`"
+ :leave-to-class="`opacity-0 ${props.toastCount === 1 ? `${props.position.includes('bottom') ? 'translate-y-full' : '-translate-y-full'}` : 'translate-y-0'}`"
>
<span
- class="relative flex flex-col items-start shadow-[0_5px_15px_-3px_rgb(0_0_0_/_0.08)] mx-6 sm:mx-auto transition-all duration-300 ease-out sm:border bg-white dark:bg-primary-dark-700/70 backdrop-blur-lg border-gray-100 dark:border-neutral-800/50 text-gray-800 dark:text-neutral-100 rounded-md sm:max-w-xs group"
+ class="relative flex flex-col items-start shadow-[0_5px_15px_-3px_rgb(0_0_0_/_0.08)] transition-all duration-300 ease-out border bg-white dark:bg-primary-dark-700/70 backdrop-blur-lg border-gray-100 dark:border-neutral-800/50 text-gray-800 dark:text-neutral-100 rounded-md group"
:class="{ 'p-4': !props.html, 'p-0': props.html }"
+ v-show="mounted"
>
<div v-if="!props.html" class="relative">
<div
@@ -198,7 +166,7 @@ function animateClose() {
</p>
</div>
<span
- @click="onCloseClick"
+ @click="onClose"
class="absolute right-0 p-1.5 mr-2.5 text-gray-400 dark:text-rose-700 duration-100 ease-in-out rounded-full opacity-0 cursor-pointer hover:bg-gray-50 dark:bg-gray-800/50 hover:text-gray-500 dark:hover:text-rose-600"
:class="{
'top-1/2 -translate-y-1/2': !props.description && !props.html,
@@ -216,6 +184,6 @@ function animateClose() {
</svg>
</span>
</span>
- </li>
- </Transition>
+ </Transition>
+ </li>
</template>
diff --git a/resources/js/components/pinesUI/Toaster.vue b/resources/js/components/pinesUI/Toaster.vue
new file mode 100644
index 00000000..32f96f9f
--- /dev/null
+++ b/resources/js/components/pinesUI/Toaster.vue
@@ -0,0 +1,372 @@
+<script lang="ts">
+// Visible toasts amount
+const VISIBLE_TOASTS_AMOUNT = 3;
+
+// Viewport padding
+const VIEWPORT_OFFSET = '32px';
+
+// Default toast width
+const TOAST_WIDTH = 356;
+
+// Default gap between toasts
+const GAP = 14;
+
+const isClient = typeof window !== 'undefined' && typeof document !== 'undefined';
+
+function _cn(...classes: (string | undefined)[]) {
+ return classes.filter(Boolean).join(' ');
+}
+</script>
+
+<script lang="ts" setup>
+import { computed, nextTick, ref, toRaw, useAttrs, watch, watchEffect } from 'vue';
+import type { HeightT, Position, ToastT, ToastToDismiss, ToasterProps } from './types';
+import { ToastState } from './state';
+import Toast from './Toast.vue';
+import CloseIcon from './assets/CloseIcon.vue';
+import LoaderIcon from './assets/Loader.vue';
+import SuccessIcon from './assets/SuccessIcon.vue';
+import InfoIcon from './assets/InfoIcon.vue';
+import WarningIcon from './assets/WarningIcon.vue';
+import ErrorIcon from './assets/ErrorIcon.vue';
+
+defineOptions({
+ name: 'Toaster',
+ inheritAttrs: false,
+});
+
+const props = withDefaults(defineProps<ToasterProps>(), {
+ invert: false,
+ position: 'bottom-right',
+ hotkey: () => ['altKey', 'KeyT'],
+ expand: false,
+ closeButton: false,
+ class: '',
+ offset: VIEWPORT_OFFSET,
+ theme: 'light',
+ richColors: false,
+ style: () => ({}),
+ visibleToasts: VISIBLE_TOASTS_AMOUNT,
+ toastOptions: () => ({}),
+ dir: 'auto',
+ gap: GAP,
+ containerAriaLabel: 'Notifications',
+ pauseWhenPageIsHidden: false,
+ cn: _cn,
+});
+
+function getDocumentDirection(): ToasterProps['dir'] {
+ if (typeof window === 'undefined') return 'ltr';
+ if (typeof document === 'undefined') return 'ltr'; // For Fresh purpose
+
+ const dirAttribute = document.documentElement.getAttribute('dir');
+
+ if (dirAttribute === 'auto' || !dirAttribute) {
+ return window.getComputedStyle(document.documentElement).direction as ToasterProps['dir'];
+ }
+
+ return dirAttribute as ToasterProps['dir'];
+}
+
+const attrs = useAttrs();
+const toasts = ref<ToastT[]>([]);
+const filteredToasts = computed(() => {
+ return (pos: string, index: number) => toasts.value.filter((toast) => (!toast.position && index === 0) || toast.position === pos);
+});
+const possiblePositions = computed(() => {
+ const posList = toasts.value.filter((toast) => toast.position).map((toast) => toast.position) as Position[];
+ return posList.length > 0 ? Array.from(new Set([props.position].concat(posList))) : [props.position];
+});
+const heights = ref<HeightT[]>([]);
+const expanded = ref(false);
+const interacting = ref(false);
+const actualTheme = ref(
+ props.theme !== 'system'
+ ? props.theme
+ : typeof window !== 'undefined'
+ ? window.matchMedia && window.matchMedia('(prefers-color-scheme: dark)').matches
+ ? 'dark'
+ : 'light'
+ : 'light',
+);
+
+const listRef = ref<HTMLOListElement[] | HTMLOListElement | null>(null);
+const lastFocusedElementRef = ref<HTMLElement | null>(null);
+const isFocusWithinRef = ref(false);
+
+const hotkeyLabel = props.hotkey.join('+').replace(/Key/g, '').replace(/Digit/g, '');
+
+function removeToast(toastToRemove: ToastT) {
+ if (!toasts.value.find((toast) => toast.id === toastToRemove.id)?.delete) {
+ ToastState.dismiss(toastToRemove.id);
+ }
+
+ toasts.value = toasts.value.filter(({ id }) => id !== toastToRemove.id);
+}
+
+function onBlur(event: FocusEvent | any) {
+ if (isFocusWithinRef.value && !event.currentTarget?.contains?.(event.relatedTarget)) {
+ isFocusWithinRef.value = false;
+ if (lastFocusedElementRef.value) {
+ lastFocusedElementRef.value.focus({ preventScroll: true });
+ lastFocusedElementRef.value = null;
+ }
+ }
+}
+
+function onFocus(event: FocusEvent | any) {
+ const isNotDismissible = event.target instanceof HTMLElement && event.target.dataset.dismissible === 'false';
+
+ if (isNotDismissible) return;
+
+ if (!isFocusWithinRef.value) {
+ isFocusWithinRef.value = true;
+ lastFocusedElementRef.value = event.relatedTarget as HTMLElement;
+ }
+}
+
+function onPointerDown(event: PointerEvent) {
+ if (event.target) {
+ const isNotDismissible = event.target instanceof HTMLElement && event.target.dataset.dismissible === 'false';
+
+ if (isNotDismissible) return;
+ }
+ interacting.value = true;
+}
+
+watchEffect((onInvalidate) => {
+ const unsubscribe = ToastState.subscribe((toast) => {
+ if ((toast as ToastToDismiss).dismiss) {
+ toasts.value = toasts.value.map((t) => (t.id === toast.id ? { ...t, delete: true } : t));
+ return;
+ }
+
+ nextTick(() => {
+ const indexOfExistingToast = toasts.value.findIndex((t) => t.id === toast.id);
+
+ // Update the toast if it already exists
+ if (indexOfExistingToast !== -1) {
+ toasts.value = [
+ ...toasts.value.slice(0, indexOfExistingToast),
+ { ...toasts.value[indexOfExistingToast], ...toast },
+ ...toasts.value.slice(indexOfExistingToast + 1),
+ ];
+ } else {
+ toasts.value = [toast, ...toasts.value];
+ }
+ });
+ });
+
+ onInvalidate(unsubscribe);
+});
+
+watch(
+ () => props.theme,
+ (newTheme) => {
+ if (newTheme !== 'system') {
+ actualTheme.value = newTheme;
+ return;
+ }
+
+ if (newTheme === 'system') {
+ // check if current preference is dark
+ if (window.matchMedia && window.matchMedia('(prefers-color-scheme: dark)').matches) {
+ // it's currently dark
+ actualTheme.value = 'dark';
+ } else {
+ // it's not dark
+ actualTheme.value = 'light';
+ }
+ }
+
+ if (typeof window === 'undefined') return;
+
+ const darkMediaQuery = window.matchMedia('(prefers-color-scheme: dark)');
+
+ try {
+ // Chrome & Firefox
+ darkMediaQuery.addEventListener('change', ({ matches }) => {
+ if (matches) {
+ actualTheme.value = 'dark';
+ } else {
+ actualTheme.value = 'light';
+ }
+ });
+ } catch (error) {
+ darkMediaQuery.addListener(({ matches }) => {
+ try {
+ if (matches) {
+ actualTheme.value = 'dark';
+ } else {
+ actualTheme.value = 'light';
+ }
+ } catch (e) {
+ console.error(e);
+ }
+ });
+ }
+ },
+);
+
+watchEffect(() => {
+ if (listRef.value && lastFocusedElementRef.value) {
+ lastFocusedElementRef.value.focus({ preventScroll: true });
+ lastFocusedElementRef.value = null;
+ isFocusWithinRef.value = false;
+ }
+});
+
+watchEffect(() => {
+ // Ensure expanded is always false when no toasts are present / only one left
+ if (toasts.value.length <= 1) {
+ expanded.value = false;
+ }
+});
+
+watchEffect((onInvalidate) => {
+ function handleKeyDown(event: KeyboardEvent) {
+ const isHotkeyPressed = props.hotkey.every((key) => (event as any)[key] || event.code === key);
+
+ const listRefItem = Array.isArray(listRef.value) ? listRef.value[0] : listRef.value;
+
+ if (isHotkeyPressed) {
+ expanded.value = true;
+ listRefItem?.focus();
+ }
+
+ const isItemActive = document.activeElement === listRef.value || listRefItem?.contains(document.activeElement);
+
+ if (event.code === 'Escape' && isItemActive) {
+ expanded.value = false;
+ }
+ }
+
+ if (!isClient) return;
+
+ document.addEventListener('keydown', handleKeyDown);
+
+ onInvalidate(() => {
+ document.removeEventListener('keydown', handleKeyDown);
+ });
+});
+</script>
+
+<template>
+ <!-- Remove item from normal navigation flow, only available via hotkey -->
+ <section
+ :aria-label="`${containerAriaLabel} ${hotkeyLabel}`"
+ :tabIndex="-1"
+ aria-live="polite"
+ aria-relevant="additions text"
+ aria-atomic="false"
+ >
+ <template v-for="(pos, index) in possiblePositions" :key="pos">
+ <ol
+ ref="listRef"
+ data-sonner-toaster
+ :class="props.class"
+ :dir="dir === 'auto' ? getDocumentDirection() : dir"
+ :tabIndex="-1"
+ :data-theme="theme"
+ :data-rich-colors="richColors"
+ :data-y-position="pos.split('-')[0]"
+ :data-x-position="pos.split('-')[1]"
+ :data-lifted="expanded && toasts.length > 1 && !expand"
+ :style="{
+ '--front-toast-height': `${heights[0]?.height}px`,
+ '--offset': typeof offset === 'number' ? `${offset}px` : offset || VIEWPORT_OFFSET,
+ '--width': `${TOAST_WIDTH}px`,
+ '--gap': `${gap}px`,
+ ...style,
+ ...(attrs as Record<string, Record<string, any>>).style,
+ }"
+ v-bind="$attrs"
+ @blur="onBlur"
+ @focus="onFocus"
+ @mouseenter="() => (expanded = true)"
+ @mousemove="() => (expanded = true)"
+ @mouseleave="
+ () => {
+ // Avoid setting expanded to false when interacting with a toast, e.g. swiping
+ if (!interacting) {
+ expanded = false;
+ }
+ }
+ "
+ @pointerdown="onPointerDown"
+ @pointerup="() => (interacting = false)"
+ >
+ <template v-for="(toast, idx) in filteredToasts(pos, index)" :key="toast.id">
+ <Toast
+ :heights="heights.filter((h) => h.position === toast.position)"
+ :icons="icons"
+ :index="idx"
+ :toast="toast"
+ :defaultRichColors="richColors"
+ :duration="toastOptions?.duration ?? duration"
+ :class="toastOptions?.class ?? ''"
+ :descriptionClass="toastOptions?.descriptionClass"
+ :invert="invert"
+ :visibleToasts="visibleToasts"
+ :closeButton="toastOptions?.closeButton ?? closeButton"
+ :interacting="interacting"
+ :position="pos"
+ :style="toastOptions?.style"
+ :unstyled="toastOptions?.unstyled"
+ :classes="toastOptions?.classes"
+ :cancelButtonStyle="toastOptions?.cancelButtonStyle"
+ :actionButtonStyle="toastOptions?.actionButtonStyle"
+ :toasts="toasts.filter((t) => t.position === toast.position)"
+ :expandByDefault="expand"
+ :gap="gap"
+ :expanded="expanded"
+ :pauseWhenPageIsHidden="pauseWhenPageIsHidden"
+ :cn="cn"
+ @update:heights="
+ (h) => {
+ heights = h;
+ }
+ "
+ @removeToast="removeToast"
+ >
+ <template #close-icon>
+ <slot name="close-icon">
+ <CloseIcon />
+ </slot>
+ </template>
+
+ <template #loading-icon>
+ <slot name="loading-icon">
+ <LoaderIcon :visible="toast.type === 'loading'" />
+ </slot>
+ </template>
+
+ <template #success-icon>
+ <slot name="success-icon">
+ <SuccessIcon />
+ </slot>
+ </template>
+
+ <template #error-icon>
+ <slot name="error-icon">
+ <ErrorIcon />
+ </slot>
+ </template>
+
+ <template #warning-icon>
+ <slot name="warning-icon">
+ <WarningIcon />
+ </slot>
+ </template>
+
+ <template #info-icon>
+ <slot name="info-icon">
+ <InfoIcon />
+ </slot>
+ </template>
+ </Toast>
+ </template>
+ </ol>
+ </template>
+ </section>
+</template>
diff --git a/resources/js/components/pulse/PulseUserCard.vue b/resources/js/components/pulse/PulseUserCard.vue
index fc51bde4..4dfc6238 100644
--- a/resources/js/components/pulse/PulseUserCard.vue
+++ b/resources/js/components/pulse/PulseUserCard.vue
@@ -2,7 +2,9 @@
const props = defineProps<{ user: { name: string; extra?: any; avatar?: string } }>();
</script>
<template>
- <div class="flex items-center justify-between p-4 gap-2 rounded-md dark:bg-primary-dark-800/70 bg-primary-900 ring-1 ring-gray-900/10">
+ <div
+ class="flex items-center justify-between p-4 gap-2 rounded-md dark:bg-primary-dark-800/70 bg-primary-900 ring-1 ring-gray-900/5 shadow-sm ring-inset"
+ >
<div class="flex items-center gap-3 overflow-hidden">
<img
v-if="props.user.avatar ?? false"
diff --git a/resources/js/components/pulseCards/PulseQueues.vue b/resources/js/components/pulseCards/PulseQueues.vue
index 394006a1..64c51e44 100644
--- a/resources/js/components/pulseCards/PulseQueues.vue
+++ b/resources/js/components/pulseCards/PulseQueues.vue
@@ -247,6 +247,7 @@ watch(
<div class="h-14">
<PulseLineChart
+ :class="' !bg-primary-900'"
:chart-data="{
labels: Object.keys(queues[queue].queued).map((v) => pulseFormatDate(v)),
datasets: [
diff --git a/resources/js/composables/useToastController.js b/resources/js/composables/useToastController.js
index 788f8404..a597bbdf 100755
--- a/resources/js/composables/useToastController.js
+++ b/resources/js/composables/useToastController.js
@@ -285,3 +285,139 @@ export default function useToastController($el = document.querySelector('#toastR
);
return toast;
}
+
+function positionToast() {
+ if (messages.value.length == 0 || !messages.value[0].id) return;
+ let topToast = document.getElementById(messages.value[0].id);
+
+ if (!topToast) return;
+
+ topToast.style.zIndex = `${100}`;
+ if (expanded.value) {
+ if (position.value.includes('bottom')) {
+ topToast.style.top = 'auto';
+ topToast.style.bottom = '0px';
+ } else {
+ topToast.style.top = '0px';
+ }
+ }
+ console.log('totalHeight', 1, 0);
+
+ if (messages.value.length == 1 || !messages.value[1].id) return;
+
+ let middleToast = document.getElementById(messages.value[1].id);
+
+ if (!middleToast) return;
+
+ middleToast.style.zIndex = `${90}`;
+
+ if (expanded.value) {
+ console.log(topToast.getBoundingClientRect().height);
+
+ let middleToastPosition = topToast.getBoundingClientRect().height + paddingBetweenToasts.value + 'px';
+
+ if (position.value.includes('bottom')) {
+ middleToast.style.top = 'auto';
+ middleToast.style.bottom = middleToastPosition;
+ } else {
+ middleToast.style.top = middleToastPosition;
+ }
+ console.log('totalHeight', 2, middleToastPosition);
+
+ middleToast.style.scale = '100%';
+ middleToast.style.transform = 'translateY(0px)';
+ } else {
+ middleToast.style.scale = '94%';
+ if (position.value.includes('bottom')) {
+ middleToast.style.transform = 'translateY(-16px)';
+ } else {
+ alignBottom(topToast, middleToast);
+ middleToast.style.transform = 'translateY(16px)';
+ }
+ }
+
+ if (messages.value.length == 2 || !messages.value[2].id) return;
+
+ let bottomToast = document.getElementById(messages.value[2].id);
+
+ if (!bottomToast) return;
+
+ bottomToast.style.zIndex = `${80}`;
+ if (expanded.value) {
+ console.log(middleToast.getBoundingClientRect().height);
+ let bottomToastPosition =
+ topToast.getBoundingClientRect().height +
+ paddingBetweenToasts.value +
+ middleToast.getBoundingClientRect().height +
+ paddingBetweenToasts.value +
+ 'px';
+
+ console.log('totalHeight', 3, bottomToastPosition);
+ if (position.value.includes('bottom')) {
+ bottomToast.style.top = 'auto';
+ bottomToast.style.bottom = bottomToastPosition;
+ } else {
+ bottomToast.style.top = bottomToastPosition;
+ }
+
+ bottomToast.style.scale = '100%';
+ bottomToast.style.transform = 'translateY(0px)';
+ } else {
+ bottomToast.style.scale = '88%';
+ if (position.value.includes('bottom')) {
+ bottomToast.style.transform = 'translateY(-32px)';
+ } else {
+ alignBottom(topToast, bottomToast);
+ bottomToast.style.transform = 'translateY(32px)';
+ }
+ }
+
+ if (messages.value.length == 3 || !messages.value[3].id) return;
+
+ let burnToast = document.getElementById(messages.value[3].id);
+
+ if (!burnToast) return;
+
+ burnToast.style.zIndex = `${70}`;
+ if (expanded.value) {
+ console.log(bottomToast.getBoundingClientRect().height);
+ let burnToastPosition =
+ topToast.getBoundingClientRect().height +
+ paddingBetweenToasts.value +
+ middleToast.getBoundingClientRect().height +
+ paddingBetweenToasts.value +
+ bottomToast.getBoundingClientRect().height +
+ paddingBetweenToasts.value +
+ 'px';
+
+ console.log('totalHeight', 4, burnToastPosition);
+
+ if (position.value.includes('bottom')) {
+ burnToast.style.top = 'auto';
+ burnToast.style.bottom = burnToastPosition;
+ } else {
+ burnToast.style.top = burnToastPosition;
+ }
+
+ burnToast.style.scale = '100%';
+ burnToast.style.transform = 'translateY(0px)';
+ } else {
+ burnToast.style.scale = '82%';
+ alignBottom(topToast, burnToast);
+ burnToast.style.transform = 'translateY(48px)';
+ }
+
+ burnToast.firstElementChild?.classList.remove('opacity-100');
+ burnToast.firstElementChild?.classList.add('opacity-0');
+
+ // Burn 🔥 (remove) last toast
+ setTimeout(function () {
+ messages.value.pop();
+ }, 300);
+
+ if (position.value.includes('bottom')) {
+ middleToast.style.top = 'auto';
+ }
+
+ return;
+}
diff --git a/resources/js/layouts/LayoutBase.vue b/resources/js/layouts/LayoutBase.vue
index 6aace798..e55be175 100755
--- a/resources/js/layouts/LayoutBase.vue
+++ b/resources/js/layouts/LayoutBase.vue
@@ -39,7 +39,7 @@ const scrollBody = ref(null);
</section>
<section
id="list-card"
- :class="`col-span-1 h-fit order-3 bg-primary-900 dark:bg-primary-dark-900 dark:text-[#e2e0e2] shadow-xl rounded-2xl space-y-2 scroll-mt-6 z-20 ring-1 ring-gray-900/5 ${selectedSideBar && sideBarTarget === '#list-card' ? 'ring-1' : 'invisible'}`"
+ :class="`col-span-1 h-fit order-3 bg-primary-900 dark:bg-primary-dark-900 dark:text-[#e2e0e2] shadow-xl rounded-2xl space-y-2 scroll-mt-6 z-20 ring-1 ring-gray-900/5 ${selectedSideBar && sideBarTarget === '#list-card' ? 'ring-1' : 'hidden'}`"
>
<!-- w-full h-fit lg:w-1/6 lg:max-w-72 sm:min-w-32 shrink-0 -->
<!-- class="bg-primary-900 dark:bg-primary-dark-900 dark:text-[#e2e0e2] shadow-xl p-3 rounded-2xl w-full h-fit lg:w-1/6 lg:max-w-72 sm:min-w-32 shrink-0 space-y-2 scroll-mt-6 z-20 ring-1 ring-gray-900/5" -->
diff --git a/resources/js/service/toastService.js b/resources/js/service/toastService.js
deleted file mode 100755
index c4fbde0d..00000000
--- a/resources/js/service/toastService.js
+++ /dev/null
@@ -1,24 +0,0 @@
-import { ToastSymbol } from '../composables/useToast';
-import ToastEventBus from './toastEventBus';
-
-export default {
- install: (app) => {
- const ToastService = {
- add: (message) => {
- ToastEventBus.emit('add', message);
- },
- remove: (message) => {
- ToastEventBus.emit('remove', message);
- },
- removeGroup: (group) => {
- ToastEventBus.emit('remove-group', group);
- },
- removeAllGroups: () => {
- ToastEventBus.emit('remove-all-groups');
- },
- };
-
- app.config.globalProperties.$toast = ToastService;
- app.provide(ToastSymbol, ToastService);
- },
-};
diff --git a/resources/js/service/toaster/component.ts b/resources/js/service/toaster/component.ts
new file mode 100644
index 00000000..ac026a24
--- /dev/null
+++ b/resources/js/service/toaster/component.ts
@@ -0,0 +1 @@
+export { default as ToastController } from '@/components/pinesUI/ToastController.vue';
diff --git a/resources/js/service/toaster/state.ts b/resources/js/service/toaster/state.ts
new file mode 100644
index 00000000..8bf0b417
--- /dev/null
+++ b/resources/js/service/toaster/state.ts
@@ -0,0 +1,107 @@
+import type { ExternalToast, Message, ToastOptions, ToastType } from '@/types/pinesTypes';
+import type { Component } from 'vue';
+
+function UniqueComponentId(prefix = 'pv_id_') {
+ return prefix + Math.random().toString(16).slice(2);
+}
+let toastsCounter = 0;
+
+class Observer {
+ subscribers: Array<(toast: Message | { id: string }) => void>;
+ toasts: Array<Message>;
+
+ constructor() {
+ this.subscribers = [];
+ this.toasts = [];
+ }
+
+ // We use arrow functions to maintain the correct `this` reference
+ subscribe = (subscriber: (toast: Message | { id: string }) => void) => {
+ this.subscribers.push(subscriber as any);
+
+ return () => {
+ const index = this.subscribers.indexOf(subscriber as any);
+ this.subscribers.splice(index, 1);
+ };
+ };
+
+ publish = (data: Message) => {
+ this.subscribers.forEach((subscriber) => subscriber(data));
+ };
+
+ addToast = (data: Message) => {
+ this.publish(data);
+ this.toasts = [...this.toasts, data];
+ };
+
+ create = (
+ data: ExternalToast & {
+ message?: string;
+ type?: ToastType;
+ life?: number;
+ },
+ ) => {
+ const { message, ...rest } = data;
+ const id = data.options.id ?? UniqueComponentId('toast_');
+ const alreadyExists = this.toasts.find((toast) => {
+ return toast.id === id;
+ });
+
+ if (alreadyExists) {
+ this.toasts = this.toasts.map((toast) => {
+ if (toast.id === id) {
+ this.publish({ ...toast, ...data, id, title: message ?? '' });
+ return {
+ ...toast,
+ ...data,
+ id,
+ title: message ?? '',
+ };
+ }
+
+ return toast;
+ });
+ } else {
+ this.addToast({
+ ...rest,
+ title: message ?? '',
+ id,
+ position: 'bottom-right',
+ life: 3000,
+ type: 'success',
+ });
+ }
+
+ return id;
+ };
+ dismiss = (id?: string) => {
+ if (id) {
+ this.subscribers.forEach((subscriber) => subscriber({ id }));
+ }
+ this.toasts.forEach((toast) => {
+ this.subscribers.forEach((subscriber) => subscriber({ id: toast.id }));
+ });
+ return id;
+ };
+
+ add = (message: string, options?: ToastOptions) => {
+ return this.create({ title: message, options: options ?? {} });
+ };
+}
+
+export const ToastState = new Observer();
+
+function toastFunction(message: string, options?: ToastOptions) {
+ const id = UniqueComponentId('toast_');
+
+ ToastState.create({ title: message, options: { type: 'default', ...options, id: id } });
+
+ return id;
+}
+
+const basicToast = toastFunction;
+
+export const toast = Object.assign(basicToast, {
+ add: ToastState.add,
+ dismiss: ToastState.dismiss,
+});
diff --git a/resources/js/service/toaster/toastService.ts b/resources/js/service/toaster/toastService.ts
new file mode 100644
index 00000000..95f88a87
--- /dev/null
+++ b/resources/js/service/toaster/toastService.ts
@@ -0,0 +1,25 @@
+import type { Plugin } from 'vue';
+import { ToastSymbol } from '../../composables/useToast';
+import ToastEventBus from '../toastEventBus';
+import type { ToastOptions } from '@/types/pinesTypes';
+import { ToastController } from './component';
+import { toast } from './state';
+
+export { ToastController, toast };
+
+export default {
+ install: (app: any) => {
+ const ToastService = {
+ add: (title: string, options: ToastOptions) => {
+ ToastEventBus.emit('add', { title, options });
+ },
+ remove: (id: string) => {
+ ToastEventBus.emit('close', id);
+ },
+ };
+
+ app.config.globalProperties.$toast = ToastService;
+ app.provide(ToastSymbol, ToastService);
+ app.component('ToastController');
+ },
+};
diff --git a/resources/js/service/util.ts b/resources/js/service/util.ts
index 0de64e70..e13fc3a4 100644
--- a/resources/js/service/util.ts
+++ b/resources/js/service/util.ts
@@ -89,3 +89,14 @@ export function periodForHumans(period: string) {
export function format_number(value: any) {
return Intl.NumberFormat().format(value);
}
+
+export function getScreenSize(): 'sm' | 'md' | 'lg' | 'xl' | '2xl' | 'default' {
+ const width = window.innerWidth;
+
+ if (width >= 1536) return '2xl';
+ if (width >= 1280) return 'xl';
+ if (width >= 1024) return 'lg';
+ if (width >= 768) return 'md';
+ if (width >= 640) return 'sm';
+ return 'default';
+}
diff --git a/resources/js/types/pinesTypes.ts b/resources/js/types/pinesTypes.ts
new file mode 100644
index 00000000..3e16db15
--- /dev/null
+++ b/resources/js/types/pinesTypes.ts
@@ -0,0 +1,72 @@
+import type { Component } from 'vue';
+
+export type ToastType = 'success' | 'info' | 'warning' | 'danger' | 'default';
+export type ToastPostion = 'top-right' | 'top-left' | 'top-center' | 'bottom-right' | 'bottom-left' | 'bottom-center';
+export type ToastLayout = 'default' | 'expanded';
+
+export interface ToastIcons {
+ success?: Component;
+ info?: Component;
+ warning?: Component;
+ error?: Component;
+ loading?: Component;
+ close?: Component;
+}
+
+export interface ToastControllerProps {
+ layout?: 'default' | 'expanded';
+ position?: ToastPostion;
+ defaultLife?: number;
+ viewportOffset?: string | number;
+ mobileViewportOffset?: string | number;
+ paddingBetweenToasts?: number; // gap
+ maxVisibleToasts?: number;
+ closeButton?: boolean;
+ icons?: ToastIcons;
+}
+
+export interface ToastProps {
+ id: string;
+ stack: Function;
+ position: string;
+ toastCount: number;
+
+ // idx: number;
+
+ title?: string;
+ description?: string;
+ life?: number;
+ type?: string;
+ style?: string;
+ html?: string;
+}
+
+export interface Message<T extends Component = Component> {
+ type: ToastType;
+ position: ToastPostion;
+ life: number;
+ id: string;
+ title: string;
+ description?: string;
+ html?: string;
+ component?: T;
+}
+
+export interface ExternalToast {
+ title: string;
+ options: ToastOptions;
+}
+
+export interface ToastOptions {
+ id?: string;
+ description?: string;
+ type?: ToastType;
+ position?: ToastPostion;
+ life?: number;
+}
+
+export interface ToastT {
+ id: string;
+}
+
+export declare const toast: (title: string, options?: ToastOptions) => string | number;
diff --git a/resources/js/views/DashboardView.vue b/resources/js/views/DashboardView.vue
index 4e5b93c1..346618db 100644
--- a/resources/js/views/DashboardView.vue
+++ b/resources/js/views/DashboardView.vue
@@ -1,61 +1,110 @@
<script setup lang="ts">
-import { onMounted, ref } from 'vue';
+import { onMounted, ref, watch, type Component } from 'vue';
import { useAppStore } from '@/stores/AppStore';
import { storeToRefs } from 'pinia';
+import { useRoute } from 'vue-router';
import DashboardAnalytics from '@/components/dashboard/DashboardAnalytics.vue';
import DashboardLibraries from '@/components/dashboard/DashboardLibraries.vue';
+import SidebarCard from '@/components/cards/SidebarCard.vue';
import LayoutBase from '@/layouts/LayoutBase.vue';
-const dashboardPages = [
- { title: 'overview', timeControls: true },
- { title: 'libraries', timeControls: false },
- { title: 'activity', timeControls: false },
- { title: 'users', timeControls: false },
- { title: 'jobs', timeControls: false },
+import LucideImages from '~icons/lucide/images';
+import LucideChartNoAxesColumnIncreasing from '~icons/lucide/chart-no-axes-column-increasing';
+import CircumDatabase from '~icons/circum/database';
+import CircumServer from '~icons/circum/server';
+import ProiconsLibrary from '~icons/proicons/library';
+import ProiconsBookAdd2 from '~icons/proicons/book-add-2';
+import ProiconsAddSquareMultiple from '~icons/proicons/add-square-multiple';
+import LucideUsers from '~icons/lucide/users';
+import ProiconsHistory from '~icons/proicons/history';
+
+const dashboardTabs: { name: string; title?: string; icon?: Component }[] = [
+ { name: 'overview', title: 'Website Analytics', icon: LucideChartNoAxesColumnIncreasing },
+ { name: 'libraries', icon: ProiconsLibrary },
+ { name: 'activity', icon: ProiconsHistory },
+ { name: 'users', icon: LucideUsers },
+ { name: 'jobs', icon: CircumServer },
];
-const dashboardPage = ref('overview');
+const dashboardTab = ref<{ name: string; title?: string; icon?: any }>();
+const route = useRoute();
const AppStore = useAppStore();
const { cycleSideBar } = AppStore;
-const { pageTitle } = storeToRefs(AppStore);
+const { pageTitle, selectedSideBar } = storeToRefs(AppStore);
onMounted(async () => {
- pageTitle.value = 'Dashboard';
+ const URL_TAB = route.query.tab;
+ let defaultTab = dashboardTabs.find((tab) => (tab.title ?? tab.name) == URL_TAB) ?? dashboardTabs[0];
+
+ pageTitle.value = defaultTab.title ?? defaultTab.name;
+ dashboardTab.value = defaultTab;
cycleSideBar('dashboard', '#left-card');
});
+
+watch(
+ () => dashboardTab.value,
+ () => {
+ if (!dashboardTab.value) return;
+ pageTitle.value = dashboardTab.value.title ?? dashboardTab.value.name;
+ },
+);
</script>
<template>
<LayoutBase>
<template v-slot:content>
<section id="content-dashboard" class="min-h-[80vh]">
- <DashboardAnalytics v-if="dashboardPage == 'overview'" />
- <DashboardLibraries v-if="dashboardPage == 'libraries'" />
+ <DashboardAnalytics v-if="dashboardTab?.name == 'overview'" />
+ <DashboardLibraries v-if="dashboardTab?.name == 'libraries'" />
</section>
</template>
<template v-slot:leftSidebar>
<div class="p-3 flex flex-col gap-3">
<div class="flex py-1 flex-col gap-2">
- <h1 id="sidebar-title" class="text-2xl h-8 w-full capitalize dark:text-white">{{ 'Management' }}</h1>
+ <h1 id="sidebar-title" class="text-2xl h-8 w-full capitalize dark:text-white">{{ selectedSideBar }}</h1>
<hr class="" />
</div>
- <section class="sm:text-lg flex flex-col gap-2">
- <div
- v-for="(page, index) in dashboardPages"
+ <section class="flex flex-col gap-2">
+ <SidebarCard
+ v-for="(tab, index) in dashboardTabs"
:key="index"
+ :link="`/dashboard?tab=${tab.name}`"
:class="`
- flex flex-wrap items-center justify-between gap-2
- rounded-lg shadow p-3 group cursor-pointer
- capitalize dark:text-white overflow-hidden
- dark:bg-primary-dark-800/70 bg-primary-800 dark:hover:bg-primary-dark-600 hover:bg-gray-200
- ring-inset ring-purple-600/50 hover:ring-purple-600 hover:ring-[0.125rem] ${dashboardPage == page.title && 'ring-[0.125rem]'}
+ items-center justify-between !gap-2
+ capitalize overflow-hidden bg-white hover:bg-primary-800
+ ring-inset ring-purple-600 hover:ring-purple-600/50 hover:ring-[0.125rem] ${dashboardTab?.name == tab.name && 'ring-[0.125rem]'}
`"
- @click="dashboardPage = page.title"
+ @click="dashboardTab = tab"
>
- {{ page.title }}
- </div>
+ <template #header>
+ <h2 class="w-full flex-1" :title="tab.title ?? tab.name">{{ tab.title ?? tab.name }}</h2>
+ <component v-if="tab.icon" :is="tab.icon" class="ml-auto w-6 h-6" />
+ <!-- <ButtonCorner
+ :positionClasses="'w-7 h-7'"
+ :textClasses="'hover:text-violet-600 dark:hover:text-violet-500'"
+ :colourClasses="'dark:hover:bg-neutral-800 hover:bg-gray-300'"
+ :label="'Share'"
+ @click.stop.prevent="$emit('clickAction', link)"
+ >
+ <template #icon>
+ <CircumShare1 width="20" height="20" />
+ </template>
+ </ButtonCorner> -->
+ <!-- <ButtonCorner
+ :positionClasses="'w-7 h-7'"
+ :textClasses="`${true ? 'text-violet-600' : 'hover:text-violet-600'} dark:hover:text-violet-500`"
+ :colourClasses="'dark:hover:bg-neutral-800 hover:bg-gray-300'"
+ :to="''"
+ :label="'Open Folder'"
+ >
+ <template #icon>
+ <CircumFolderOn width="20" height="20" />
+ </template>
+ </ButtonCorner> -->
+ </template>
+ </SidebarCard>
</section>
</div>
</template>
diff --git a/resources/js/views/ProfileView.vue b/resources/js/views/ProfileView.vue
index 6cc8dcf7..563e22cc 100755
--- a/resources/js/views/ProfileView.vue
+++ b/resources/js/views/ProfileView.vue
@@ -4,10 +4,12 @@ import { storeToRefs } from 'pinia';
import { onMounted } from 'vue';
import { useToast } from '../composables/useToast';
+import { toast } from 'vue-sonner';
+
import LayoutBase from '../layouts/LayoutBase.vue';
import ButtonText from '../components/inputs/ButtonText.vue';
-const toast = useToast();
+const toastr = useToast();
const appStore = useAppStore();
const { pageTitle, selectedSideBar } = storeToRefs(appStore);
@@ -28,9 +30,8 @@ onMounted(() => {
<div class="relative flex flex-col px-10 space-y-2 sm:space-x-5 sm:space-y-0 sm:flex-row sm:px-0">
<ButtonText
@click="
- toast.add({
+ toastr.add('Default Toast Notification', {
type: 'danger',
- title: 'Default Toast Notification',
description: 'This is an example toast notification',
life: 3000,
})
@@ -40,9 +41,8 @@ onMounted(() => {
</ButtonText>
<ButtonText
@click="
- toast.add({
+ toastr.add('Default Toast Notification', {
type: 'success',
- title: 'Default Toast Notification',
description: 'This is an example toast notification',
life: 3000,
})
@@ -52,9 +52,8 @@ onMounted(() => {
</ButtonText>
<ButtonText
@click="
- toast.add({
+ toastr.add('Default Toast Notification', {
type: 'warning',
- title: 'Default Toast Notification',
description: 'This is an example toast notification',
life: 3000,
})
@@ -64,15 +63,17 @@ onMounted(() => {
</ButtonText>
<ButtonText
@click="
- toast.add({
+ toastr.add('Default Toast Notification', {
type: 'info',
- title: 'Default Toast Notification',
life: 3000,
})
"
>
<template #text> Test </template>
</ButtonText>
+ <ButtonText @click="toast.success('Event has been created')">
+ <template #text> Test </template>
+ </ButtonText>
</div>
</div>
</div>
diff --git a/resources/js/views/VideoView.vue b/resources/js/views/VideoView.vue
index c3fb64b3..153c265c 100755
--- a/resources/js/views/VideoView.vue
+++ b/resources/js/views/VideoView.vue
@@ -2,7 +2,7 @@
import type { FolderResource, VideoResource } from '@/types/resources';
import type { Metadata } from '@/types/model';
-import { nextTick, onMounted, ref, watch, type Ref } from 'vue';
+import { onMounted, ref, watch, type Ref } from 'vue';
import { useContentStore } from '@/stores/ContentStore';
import { useAppStore } from '@/stores/AppStore';
import { storeToRefs } from 'pinia';