Skip to content

A self-hosted media server and file management system

7.7 KB
Raw Blame
<script setup lang="ts" generic="T extends TableRow">
import type { TableSortOption, TableProps, TableRow } from '@aminnausin/cedar-ui';
import type { Component } from 'vue';

import { PhSortDescendingLight, PhSortAscendingLight } from '../icons';
import { onMounted, ref, toRef, watch } from 'vue';
import { ButtonCorner, ButtonIcon } from '../button';
import { InputSelect } from '../select';
import { TextInput } from '../input';
import { cn } from '@aminnausin/cedar-ui';

import TableLoadingSpinner from './TableLoadingSpinner.vue';
import TablePagination from './TablePagination.vue';
import useTable from '@/composables/useTable';

const props = withDefaults(
    defineProps<
        TableProps<T> & {
            forceVerticalToolbar?: boolean;
            sticky?: boolean;
            stickyClass?: string;
            loadingPlaceholder?: Component;
            selectedID?: number | null;
            currentIndex?: number;
            defaultSortIndex?: number;
        }
    >(),
    {
        useToolbar: true,
        usePagination: true,
        itemsPerPage: 12,
        selectedID: null,
        startAscending: true,
        usePaginationIcons: false,
        maxVisiblePages: 5,
        noResultsMessage: 'No Results',
        loadingPlaceholder: TableLoadingSpinner,
        currentIndex: -1,
        defaultSortIndex: 0,
    },
);

const { currentPage, itemsPerPage, pageData, setPage } = useTable<T>({
    itemsPerPage: () => props.itemsPerPage,
    data: toRef(props, 'data'),
});

const isFollowingItem = ref(props.selectedID != null);
const sortAscending = ref(props.startAscending);
const lastSortKey = ref('');

// Search Query
const model = defineModel<string | undefined>({
    required: false,
    default: undefined,
});

defineSlots<{
    row(props: { row: T; index: number; selectedID: any }): any;
}>();

const handleSortChange = (sortKey?: TableSortOption) => {
    if (sortKey?.value) lastSortKey.value = sortKey.value;
    if (!lastSortKey.value) return;

    props.sortAction?.(lastSortKey.value as keyof T, sortAscending.value ? 1 : -1);
};

const navigatePage = (page: number) => {
    isFollowingItem.value = false;
    setPage(page);
};

watch(
    () => props.selectedID,
    (id, prevId) => {
        if (id !== prevId) {
            isFollowingItem.value = true;
        }
    },
);

watch(
    () => props.currentIndex,
    (index) => {
        if (!isFollowingItem.value || index === undefined || index < 0 || !props.itemsPerPage) return;
        setPage(Math.floor(index / props.itemsPerPage) + 1);
    },
    { immediate: true },
);

onMounted(() => {
    if (props.useToolbar && props.sortAction) props.sortAction(lastSortKey.value as keyof T, props.startAscending ? 1 : -1);
});
</script>

<template>
    <section class="flex w-full flex-col gap-3">
        <section
            v-if="props.useToolbar"
            :class="[
                'table-toolbar flex flex-col flex-wrap justify-center gap-2',
                { 'sm:flex-row sm:justify-between': !forceVerticalToolbar },
                sticky && cn('sticky top-10 z-1', stickyClass),
            ]"
        >
            <div class="relative">
                <TextInput
                    v-if="model !== undefined"
                    v-model="model"
                    :placeholder="`Search ${props.itemName ? `${props.itemName}...` : ''}`"
                    :class="
                        cn(
                            'ring-r-button hocus:ring-2 dark:bg-surface-2 h-(--table-input-height) w-full pe-8 ring-1',
                            { 'sm:w-70 xl:w-80': !forceVerticalToolbar },
                            { 'button-disabled pointer-events-none': loading },
                        )
                    "
                    title="Search with..."
                    :disabled="loading"
                />
                <div v-show="!!model" class="pointer-events-none absolute inset-0 flex items-center justify-end pe-1">
                    <ButtonCorner
                        :use-default-style="false"
                        class="text-foreground-1 hocus:text-foreground-0 pointer-events-auto p-0.5 *:size-5"
                        :title="'Clear'"
                        @click="model = ''"
                    />
                </div>
            </div>

            <div
                :class="['flex flex-wrap items-end gap-2 sm:flex-nowrap', { 'flex-1': model === undefined || forceVerticalToolbar }, { 'sm:w-48 lg:w-54': !forceVerticalToolbar }]"
            >
                <div :class="['flex w-full flex-1 flex-col gap-2']">
                    <InputSelect
                        title="Sort by..."
                        :name="'sort'"
                        :prefix="'By '"
                        :options="sortingOptions"
                        :disabled="loading"
                        :placeholder="'Sort by...'"
                        :load-default-on-disabled="true"
                        :defaultItem="defaultSortIndex"
                        :class="cn('h-(--table-input-height) w-full')"
                        :menu-margin="{ bottom: 'mb-10', top: 'mt-10' }"
                        @selectItem="handleSortChange"
                    />
                </div>
                <ButtonIcon
                    @click="
                        sortAscending = !sortAscending;
                        handleSortChange();
                    "
                    :title="`Reorder Results...`"
                    :aria-label="`Reorder Results`"
                    class="inline-flex size-(--table-input-height) p-1"
                    :disabled="loading"
                >
                    <template #icon>
                        <!-- Arrow Pointing Down if ascending and then Up otherwise (arrow shows what to change to ?? idk descending points up actually)-->
                        <PhSortDescendingLight v-if="sortAscending" width="24" height="24" />
                        <PhSortAscendingLight v-else width="24" height="24" />
                    </template>
                </ButtonIcon>
            </div>
        </section>
        <section :class="cn(useGrid || 'flex w-full flex-1 flex-col flex-wrap gap-2', tableStyles)">
            <component
                :is="loading ? loadingPlaceholder : TableLoadingSpinner"
                v-if="loading || pageData?.length === 0"
                :is-loading="loading"
                :data-length="pageData?.length"
                :no-results-message="noResultsMessage"
                :class="[{ 'my-auto': !loading || loadingPlaceholder === TableLoadingSpinner }]"
            />
            <template v-else>
                <template v-for="(row, index) in pageData" :key="row.id">
                    <slot name="row" :row="row" :index="index" :selectedID="props.selectedID">
                        <component
                            :is="props.row"
                            :data="row"
                            :index="index"
                            :currentID="props.selectedID ?? null"
                            v-bind="rowAttributes"
                            @clickAction="(...args: any[]) => props.clickAction?.(row.id, ...args)"
                            @otherAction="(...args: any[]) => props.otherAction?.(row.id, ...args)"
                        ></component>
                    </slot>
                </template>
            </template>
        </section>
        <TablePagination
            v-if="usePagination"
            :class="cn({ 'button-disabled pointer-events-none': loading }, paginationClass)"
            :listLength="props.data?.length ?? 0"
            :itemsPerPage="itemsPerPage"
            :currentPage="currentPage"
            :useIcons="props.usePaginationIcons"
            :max-visible-pages="props.maxVisiblePages"
            @setPage="navigatePage"
        />
    </section>
</template>