feat: new-card-design (#196)

* card option 1

* UI updates for item card

* fix test error

* fix pagination issues on backend

* add integer support

* remove date from cards

* implement pagination for search page

* resolve search state problems

* other fixes

* fix broken datetime

* attempt to fix scroll behavior
This commit is contained in:
Hayden 2023-01-01 13:50:48 -08:00 committed by GitHub
parent 58d6f9a28c
commit 891d41b75f
No known key found for this signature in database
GPG key ID: 4AEE18F83AFDEB23
19 changed files with 393 additions and 142 deletions

View file

@ -56,7 +56,6 @@
const calcWidth = ref(0);
function resize() {
console.log("resize", el.value?.offsetHeight, el.value?.offsetWidth);
calcHeight.value = el.value?.offsetHeight || 0;
calcWidth.value = el.value?.offsetWidth || 0;
}

View file

@ -1,22 +1,38 @@
<template>
<NuxtLink
class="group card bg-neutral text-neutral-content hover:bg-primary transition-colors duration-300"
:to="`/item/${item.id}`"
>
<div class="card-body py-4 px-6">
<h2 class="card-title">
<Icon name="mdi-package-variant" />
{{ item.name }}
<Icon v-if="item.archived" class="ml-auto" name="mdi-archive-outline" />
</h2>
<p>{{ description }}</p>
<div class="flex gap-2 flex-wrap justify-end">
<LabelChip
v-for="label in item.labels"
:key="label.id"
:label="label"
class="badge-primary group-hover:badge-secondary"
/>
<NuxtLink class="group card rounded-md" :to="`/item/${item.id}`">
<div class="rounded-t flex flex-col bg-neutral text-neutral-content p-5">
<h2 class="text-base mb-4 last:mb-0 font-bold two-line min-h-[48px]">{{ item.name }}</h2>
<NuxtLink
v-if="item.location"
class="inline-flex text-sm items-center hover:link"
:to="`/location/${item.location.id}`"
>
<Icon name="heroicons-map-pin" class="mr-1 h-4 w-4"></Icon>
<span>
{{ item.location.name }}
</span>
</NuxtLink>
</div>
<div class="rounded-b p-4 pt-2 flex-grow col-span-4 flex flex-col gap-y-2 bg-base-100">
<div class="flex justify-between gap-2">
<div class="mr-auto tooltip tooltip-tip" data-tip="Purchase Price">
<span class="badge badge-sm badge-ghost h-5">
<Currency :amount="item.purchasePrice" />
</span>
</div>
<div v-if="item.insured" class="tooltip z-10" data-tip="Insured">
<Icon class="h-5 w-5 text-primary" name="mdi-shield-check" />
</div>
<div v-if="item.quantity > 1" class="tooltip" data-tip="Quantity">
<span class="badge h-5 w-5 badge-primary badge-sm text-xs">
{{ item.quantity }}
</span>
</div>
</div>
<Markdown class="mb-2 text-clip three-line" :source="item.description" />
<div class="flex gap-2 flex-wrap -mr-1 mt-auto justify-end">
<LabelChip v-for="label in top3" :key="label.id" :label="label" size="sm" />
</div>
</div>
</NuxtLink>
@ -24,7 +40,10 @@
<script setup lang="ts">
import { ItemOut, ItemSummary } from "~~/lib/api/types/data-contracts";
import { truncate } from "~~/lib/strings";
const top3 = computed(() => {
return props.item.labels.slice(0, 3) || [];
});
const props = defineProps({
item: {
@ -32,7 +51,24 @@
required: true,
},
});
const description = computed(() => {
return truncate(props.item.description, 80);
});
</script>
<style lang="css">
.three-line {
overflow: hidden;
text-overflow: ellipsis;
display: -webkit-box;
-webkit-line-clamp: 3;
line-clamp: 3;
-webkit-box-orient: vertical;
}
.two-line {
overflow: hidden;
text-overflow: ellipsis;
display: -webkit-box;
-webkit-line-clamp: 2;
line-clamp: 2;
-webkit-box-orient: vertical;
}
</style>

View file

@ -5,72 +5,21 @@
<script setup lang="ts">
type DateTimeFormat = "relative" | "long" | "short" | "human";
function ordinalIndicator(num: number) {
if (num > 3 && num < 21) return "th";
switch (num % 10) {
case 1:
return "st";
case 2:
return "nd";
case 3:
return "rd";
default:
return "th";
}
}
type Props = {
date?: Date | string;
format?: DateTimeFormat;
};
const months = [
"January",
"February",
"March",
"April",
"May",
"June",
"July",
"August",
"September",
"October",
"November",
"December",
];
const props = withDefaults(defineProps<Props>(), {
date: undefined,
format: "relative",
});
const value = computed(() => {
if (!props.date) {
if (!props.date || !validDate(props.date)) {
return "";
}
const dt = typeof props.date === "string" ? new Date(props.date) : props.date;
if (!dt) {
return "";
}
if (!validDate(dt)) {
return "";
}
switch (props.format) {
case "relative":
return useTimeAgo(dt).value + useDateFormat(dt, " (MM-DD-YYYY)").value;
case "long":
return useDateFormat(dt, "MM-DD-YYYY (dddd)").value;
case "short":
return useDateFormat(dt, "MM-DD-YYYY").value;
case "human":
// January 1st, 2021
return `${months[dt.getMonth()]} ${dt.getDate()}${ordinalIndicator(dt.getDate())}, ${dt.getFullYear()}`;
default:
return "";
}
});
const props = defineProps({
date: {
type: [Date, String],
required: true,
},
format: {
type: String as () => DateTimeFormat,
default: "relative",
},
return fmtDate(props.date, props.format);
});
</script>

View file

@ -2,12 +2,12 @@ const cache = {
currency: "",
};
export function ResetCurrency() {
export function resetCurrency() {
cache.currency = "";
}
export async function useFormatCurrency() {
if (!cache.currency) {
if (cache.currency === "") {
const client = useUserApi();
const { data: group } = await client.group.get();
@ -19,3 +19,59 @@ export async function useFormatCurrency() {
return (value: number | string) => fmtCurrency(value, cache.currency);
}
export type DateTimeFormat = "relative" | "long" | "short" | "human";
function ordinalIndicator(num: number) {
if (num > 3 && num < 21) return "th";
switch (num % 10) {
case 1:
return "st";
case 2:
return "nd";
case 3:
return "rd";
default:
return "th";
}
}
export function fmtDate(value: string | Date, fmt: DateTimeFormat = "human"): string {
const months = [
"January",
"February",
"March",
"April",
"May",
"June",
"July",
"August",
"September",
"October",
"November",
"December",
];
const dt = typeof value === "string" ? new Date(value) : value;
if (!dt) {
return "";
}
if (!validDate(dt)) {
return "";
}
switch (fmt) {
case "relative":
return useTimeAgo(dt).value + useDateFormat(dt, " (MM-DD-YYYY)").value;
case "long":
return useDateFormat(dt, "MM-DD-YYYY (dddd)").value;
case "short":
return useDateFormat(dt, "MM-DD-YYYY").value;
case "human":
// January 1st, 2021
return `${months[dt.getMonth()]} ${dt.getDate()}${ordinalIndicator(dt.getDate())}, ${dt.getFullYear()}`;
default:
return "";
}
}

View file

@ -1,20 +1,35 @@
import { useRouteQuery as useRouteQueryBase } from "@vueuse/router";
/* eslint no-redeclare: 0 */
import { WritableComputedRef } from "vue";
export function useRouteQuery(q: string, def: string[]): WritableComputedRef<string[]>;
export function useRouteQuery(q: string, def: string): WritableComputedRef<string>;
export function useRouteQuery(q: string, def: boolean): WritableComputedRef<boolean>;
export function useRouteQuery(q: string, def: number): WritableComputedRef<number>;
// eslint-disable-next-line @typescript-eslint/no-explicit-any
export function useRouteQuery(q: string, def: any): WritableComputedRef<any> {
const route = useRoute();
const router = useRouter();
const v = useRouteQueryBase(q, def);
const first = computed<string>(() => {
const qv = route.query[q];
if (Array.isArray(qv)) {
return qv[0]?.toString() || def;
}
return qv?.toString() || def;
});
onMounted(() => {
if (route.query[q] === undefined) {
v.value = def;
}
});
switch (typeof def) {
case "string":
if (route.query[q] === undefined) {
router.push({ query: { ...route.query, [q]: def } });
}
return computed({
get: () => {
const qv = route.query[q];
@ -45,16 +60,21 @@ export function useRouteQuery(q: string, def: any): WritableComputedRef<any> {
case "boolean":
return computed({
get: () => {
const qv = route.query[q];
if (Array.isArray(qv)) {
return qv[0] === "true";
}
return qv === "true";
return first.value === "true";
},
set: v => {
const query = { ...route.query, [q]: `${v}` };
router.push({ query });
},
});
case "number":
return computed({
get: () => parseInt(first.value, 10),
set: nv => {
v.value = nv.toString();
},
});
}
throw new Error("Invalid type");
}

View file

@ -102,6 +102,9 @@
const username = computed(() => authStore.self?.name || "User");
// Preload currency format
useFormatCurrency();
const modals = reactive({
item: false,
location: false,

View file

@ -1,5 +1,7 @@
import { Requests } from "../../requests";
const ZERO_DATE = "0001-01-01T00:00:00Z";
type BaseApiType = {
createdAt: string;
updatedAt: string;
@ -16,6 +18,14 @@ export function parseDate<T>(obj: T, keys: Array<keyof T> = []): T {
[...keys, "createdAt", "updatedAt"].forEach(key => {
// @ts-ignore - TS doesn't know that we're checking for the key above
if (hasKey(result, key)) {
if (result[key] === ZERO_DATE) {
const dt = new Date();
dt.setFullYear(1);
result[key] = dt;
return;
}
// Ensure date like format YYYY/MM/DD - otherwise results will be 1 day off
const dateStr: string = result[key].split("T")[0].replace(/-/g, "/");
result[key] = new Date(dateStr);

View file

@ -13,5 +13,4 @@ export default defineNuxtConfig({
},
},
css: ["@/assets/css/main.css"],
plugins: [],
});

View file

@ -35,6 +35,7 @@
"@tailwindcss/forms": "^0.5.2",
"@tailwindcss/typography": "^0.5.4",
"@vueuse/nuxt": "^9.1.1",
"@vueuse/router": "^9.9.0",
"autoprefixer": "^10.4.8",
"chart.js": "^4.0.1",
"daisyui": "^2.24.0",
@ -44,6 +45,7 @@
"postcss": "^8.4.16",
"tailwindcss": "^3.1.8",
"vue": "^3.2.38",
"vue-chartjs": "^4.1.2"
"vue-chartjs": "^4.1.2",
"vue-router": "4"
}
}

View file

@ -13,15 +13,53 @@
});
const searchLocked = ref(false);
const queryParamsInitialized = ref(false);
const initialSearch = ref(true);
const api = useUserApi();
const loading = useMinLoader(2000);
const results = ref<ItemSummary[]>([]);
const items = ref<ItemSummary[]>([]);
const total = ref(0);
const page1 = useRouteQuery("page", 1);
const page = computed({
get: () => page1.value,
set: value => {
page1.value = value;
},
});
const pageSize = useRouteQuery("pageSize", 21);
const query = useRouteQuery("q", "");
const advanced = useRouteQuery("advanced", false);
const includeArchived = useRouteQuery("archived", false);
const totalPages = computed(() => Math.ceil(total.value / pageSize.value));
const hasNext = computed(() => page.value * pageSize.value < total.value);
const hasPrev = computed(() => page.value > 1);
function prev() {
page.value = Math.max(1, page.value - 1);
}
function next() {
page.value = Math.min(Math.ceil(total.value / pageSize.value), page.value + 1);
}
async function resetPageSearch() {
if (searchLocked.value) {
return;
}
if (!initialSearch.value) {
page.value = 1;
}
items.value = [];
await search();
}
async function search() {
if (searchLocked.value) {
return;
@ -29,30 +67,39 @@
loading.value = true;
const locations = selectedLocations.value.map(l => l.id);
const labels = selectedLabels.value.map(l => l.id);
const { data, error } = await api.items.getAll({
q: query.value || "",
locations,
labels,
locations: locIDs.value,
labels: labIDs.value,
includeArchived: includeArchived.value,
page: page.value,
pageSize: pageSize.value,
});
if (error) {
page.value = Math.max(1, page.value - 1);
loading.value = false;
return;
}
results.value = data.items;
if (!data.items || data.items.length === 0) {
page.value = Math.max(1, page.value - 1);
loading.value = false;
return;
}
total.value = data.total;
items.value = data.items;
loading.value = false;
initialSearch.value = false;
}
const route = useRoute();
const router = useRouter();
const queryParamsInitialized = ref(false);
onMounted(async () => {
loading.value = true;
// Wait until locations and labels are loaded
let maxRetry = 10;
while (!labels.value || !locations.value) {
@ -79,6 +126,13 @@
if (!qLab && !qLoc) {
search();
}
loading.value = false;
window.scroll({
top: 0,
left: 0,
behavior: "smooth",
});
});
const locationsStore = useLocationStore();
@ -90,16 +144,18 @@
const selectedLocations = ref<LocationOutCount[]>([]);
const selectedLabels = ref<LabelSummary[]>([]);
const locIDs = computed(() => selectedLocations.value.map(l => l.id));
const labIDs = computed(() => selectedLabels.value.map(l => l.id));
watchPostEffect(() => {
if (!queryParamsInitialized.value) {
return;
}
const labelIds = selectedLabels.value.map(l => l.id);
router.push({
query: {
...router.currentRoute.value.query,
lab: labelIds,
lab: labIDs.value,
},
});
});
@ -109,11 +165,10 @@
return;
}
const locIds = selectedLocations.value.map(l => l.id);
router.push({
query: {
...router.currentRoute.value.query,
loc: locIds,
loc: locIDs.value,
},
});
});
@ -125,8 +180,22 @@
}
});
watchDebounced([selectedLocations, selectedLabels, query], search, { debounce: 250, maxWait: 1000 });
watch(includeArchived, search);
// resetPageHash computes a JSON string that is used to detect if the search
// parameters have changed. If they have changed, the page is reset to 1.
const resetPageHash = computed(() => {
const map = {
q: query.value,
includeArchived: includeArchived.value,
locations: locIDs.value,
labels: labIDs.value,
};
return JSON.stringify(map);
});
watchDebounced(resetPageHash, resetPageSearch, { debounce: 250, maxWait: 1000 });
watchDebounced([page, pageSize], search, { debounce: 250, maxWait: 1000 });
</script>
<template>
@ -157,13 +226,34 @@
</div>
</BaseCard>
<section class="mt-10">
<BaseSectionHeader class="mb-5"> Items </BaseSectionHeader>
<div class="grid grid-cols-1 sm:grid-cols-2 gap-4">
<TransitionGroup name="list">
<ItemCard v-for="item in results" :key="item.id" :item="item" />
</TransitionGroup>
<BaseSectionHeader ref="itemsTitle"> Items </BaseSectionHeader>
<p class="text-base font-medium flex items-center">
{{ total }} Results
<span class="text-base ml-auto"> Page {{ page }} of {{ totalPages }}</span>
</p>
<div ref="cardgrid" class="grid mt-4 grid-cols-1 sm:grid-cols-2 md:grid-cols-3 gap-4">
<ItemCard v-for="item in items" :key="item.id" :item="item" />
<div class="hidden first:inline text-xl">No Items Found</div>
</div>
<div v-if="items.length > 0 && (hasNext || hasPrev)" class="mt-10 flex gap-2 flex-col items-center">
<div class="flex">
<div class="btn-group">
<button :disabled="!hasPrev" class="btn text-no-transform" @click="prev">
<Icon class="mr-1 h-6 w-6" name="mdi-chevron-left" />
Prev
</button>
<button v-if="hasPrev" class="btn text-no-transform" @click="page = 1">First</button>
<button v-if="hasNext" class="btn text-no-transform" @click="page = totalPages">Last</button>
<button :disabled="!hasNext" class="btn text-no-transform" @click="next">
Next
<Icon class="ml-1 h-6 w-6" name="mdi-chevron-right" />
</button>
</div>
</div>
<p class="text-sm font-bold">Page {{ page }} of {{ totalPages }}</p>
</div>
</section>
</BaseContainer>
</template>

View file

@ -157,7 +157,7 @@
<section v-if="label">
<BaseSectionHeader class="mb-5"> Items </BaseSectionHeader>
<div class="grid gap-2 grid-cols-1 sm:grid-cols-2">
<div class="grid grid-cols-1 sm:grid-cols-2 md:grid-cols-3 gap-4">
<ItemCard v-for="item in label.items" :key="item.id" :item="item" />
</div>
</section>

View file

@ -180,7 +180,7 @@
<section v-if="location && location.items.length > 0">
<BaseSectionHeader class="mb-5"> Items </BaseSectionHeader>
<div class="grid gap-2 grid-cols-1 sm:grid-cols-2">
<div class="grid grid-cols-1 sm:grid-cols-2 md:grid-cols-3 gap-4">
<ItemCard v-for="item in location.items" :key="item.id" :item="item" />
</div>
</section>

View file

@ -0,0 +1,7 @@
export default defineNuxtPlugin(nuxtApp => {
nuxtApp.hook("page:finish", () => {
console.log(document.body);
document.body.scrollTo({ top: 0 });
console.log("page:finish");
});
});

View file

@ -12,6 +12,7 @@ specifiers:
'@typescript-eslint/eslint-plugin': ^5.36.2
'@typescript-eslint/parser': ^5.36.2
'@vueuse/nuxt': ^9.1.1
'@vueuse/router': ^9.9.0
autoprefixer: ^10.4.8
chart.js: ^4.0.1
daisyui: ^2.24.0
@ -32,6 +33,7 @@ specifiers:
vitest: ^0.22.1
vue: ^3.2.38
vue-chartjs: ^4.1.2
vue-router: '4'
dependencies:
'@iconify/vue': 3.2.1_vue@3.2.45
@ -41,6 +43,7 @@ dependencies:
'@tailwindcss/forms': 0.5.3_tailwindcss@3.2.4
'@tailwindcss/typography': 0.5.8_tailwindcss@3.2.4
'@vueuse/nuxt': 9.6.0_nuxt@3.0.0+vue@3.2.45
'@vueuse/router': 9.9.0_xsxatmlnmmg5bcuv3xdnj6fj7y
autoprefixer: 10.4.13_postcss@8.4.19
chart.js: 4.0.1
daisyui: 2.43.0_2lwn2upnx27dqeg6hqdu7sq75m
@ -51,6 +54,7 @@ dependencies:
tailwindcss: 3.2.4_postcss@8.4.19
vue: 3.2.45
vue-chartjs: 4.1.2_chart.js@4.0.1+vue@3.2.45
vue-router: 4.1.6_vue@3.2.45
devDependencies:
'@faker-js/faker': 7.6.0
@ -1339,6 +1343,19 @@ packages:
- vue
dev: false
/@vueuse/router/9.9.0_xsxatmlnmmg5bcuv3xdnj6fj7y:
resolution: {integrity: sha512-C6w3HZrU3aLde8t3cjcMfFVnw722Is9FtBNJH2wwUPUv7Fc0bKsqcOEq1yFM0f6K5QktHxlp2vcuV4/nA3xPQw==}
peerDependencies:
vue-router: '>=4.0.0-rc.1'
dependencies:
'@vueuse/shared': 9.9.0_vue@3.2.45
vue-demi: 0.13.11_vue@3.2.45
vue-router: 4.1.6_vue@3.2.45
transitivePeerDependencies:
- '@vue/composition-api'
- vue
dev: false
/@vueuse/shared/9.6.0_vue@3.2.45:
resolution: {integrity: sha512-/eDchxYYhkHnFyrb00t90UfjCx94kRHxc7J1GtBCqCG4HyPMX+krV9XJgVtWIsAMaxKVU4fC8NSUviG1JkwhUQ==}
dependencies:
@ -1348,6 +1365,15 @@ packages:
- vue
dev: false
/@vueuse/shared/9.9.0_vue@3.2.45:
resolution: {integrity: sha512-+D0XFwHG0T+uaIbCSlROBwm1wzs71B7n3KyDOxnvfEMMHDOzl09rYKwaE2AENmYwYPXfHPbSBRDD2gBVHbvTcg==}
dependencies:
vue-demi: 0.13.11_vue@3.2.45
transitivePeerDependencies:
- '@vue/composition-api'
- vue
dev: false
/@zhead/schema/1.0.7:
resolution: {integrity: sha512-jN2ipkz39YrHd8uulgw/Y7x8iOxvR/cTkin/E9zRQVP5JBIrrJMiGyFFj6JBW4Q029xJ5dKtpwy/3RZWpz+dkQ==}