feat: locations tree viewer (#248)

* location tree API

* test fixes

* initial tree location elements

* locations tree page

* update meta-data

* code-gen

* store item display preferences

* introduce basic table/card view elements

* codegen

* set parent location during location creation

* add item support for tree query

* refactor tree view

* wip: location selector improvements

* type gen

* rename items -> search

* remove various log statements

* fix markdown rendering for description

* update location selectors

* fix tests

* fix currency tests

* formatting
This commit is contained in:
Hayden 2023-01-28 11:53:00 -09:00 committed by GitHub
parent 4d220cdd9c
commit 3d295b5132
No known key found for this signature in database
GPG key ID: 4AEE18F83AFDEB23
33 changed files with 1119 additions and 79 deletions

View file

@ -6,7 +6,7 @@
<div class="dropdown dropdown-top sm:dropdown-end">
<div class="relative">
<input
v-model="isearch"
v-model="internalSearch"
tabindex="0"
class="input w-full items-center flex flex-wrap border border-gray-400 rounded-lg"
@keyup.enter="selectFirst"
@ -26,9 +26,11 @@
class="dropdown-content mb-1 menu shadow border border-gray-400 rounded bg-base-100 w-full z-[9999] max-h-60 overflow-y-scroll"
>
<li v-for="(obj, idx) in filtered" :key="idx">
<button type="button" @click="select(obj)">
{{ usingObjects ? obj[itemText] : obj }}
</button>
<div type="button" @click="select(obj)">
<slot name="display" v-bind="{ item: obj }">
{{ usingObjects ? obj[itemText] : obj }}
</slot>
</div>
</li>
<li class="hidden first:flex">
<button disabled>
@ -49,9 +51,10 @@
interface Props {
label: string;
modelValue: string | ItemsObject;
modelValue: string | ItemsObject | null | undefined;
items: ItemsObject[] | string[];
itemText?: keyof ItemsObject;
itemSearch?: keyof ItemsObject | null;
itemValue?: keyof ItemsObject;
search?: string;
noResultsText?: string;
@ -63,21 +66,34 @@
modelValue: "",
items: () => [],
itemText: "text",
itemValue: "value",
search: "",
itemSearch: null,
itemValue: "value",
noResultsText: "No Results Found",
});
const searchKey = computed(() => props.itemSearch || props.itemText);
function clear() {
select(value.value);
}
const isearch = ref("");
watch(isearch, () => {
internalSearch.value = isearch.value;
});
const internalSearch = ref("");
watch(
() => props.search,
val => {
internalSearch.value = val;
}
);
watch(
() => internalSearch.value,
val => {
emit("update:search", val);
}
);
const internalSearch = useVModel(props, "search", emit);
const value = useVModel(props, "modelValue", emit);
const usingObjects = computed(() => {
@ -102,9 +118,9 @@
() => {
if (value.value) {
if (typeof value.value === "string") {
isearch.value = value.value;
internalSearch.value = value.value;
} else {
isearch.value = value.value[props.itemText] as string;
internalSearch.value = value.value[searchKey.value] as string;
}
}
},
@ -113,7 +129,7 @@
}
);
function select(obj: string | ItemsObject) {
function select(obj: Props["modelValue"]) {
if (isStrings(props.items)) {
if (obj === value.value) {
value.value = "";
@ -131,16 +147,16 @@
}
const filtered = computed(() => {
if (!isearch.value || isearch.value === "") {
if (!internalSearch.value || internalSearch.value === "") {
return props.items;
}
if (isStrings(props.items)) {
return props.items.filter(item => item.toLowerCase().includes(isearch.value.toLowerCase()));
return props.items.filter(item => item.toLowerCase().includes(internalSearch.value.toLowerCase()));
} else {
return props.items.filter(item => {
if (props.itemText && props.itemText in item) {
return (item[props.itemText] as string).toLowerCase().includes(isearch.value.toLowerCase());
if (searchKey.value && searchKey.value in item) {
return (item[searchKey.value] as string).toLowerCase().includes(internalSearch.value.toLowerCase());
}
return false;
});

View file

@ -0,0 +1,65 @@
<script setup lang="ts">
import { ViewType } from "~~/composables/use-preferences";
import { ItemSummary } from "~~/lib/api/types/data-contracts";
type Props = {
view?: ViewType;
items: ItemSummary[];
};
const preferences = useViewPreferences();
const props = defineProps<Props>();
const viewSet = computed(() => {
return !!props.view;
});
const itemView = computed(() => {
return props.view ?? preferences.value.itemDisplayView;
});
function setViewPreference(view: ViewType) {
preferences.value.itemDisplayView = view;
}
</script>
<template>
<section>
<BaseSectionHeader class="mb-5 flex justify-between items-center">
Items
<template #description>
<div v-if="!viewSet" class="dropdown dropdown-hover dropdown-left">
<label tabindex="0" class="btn btn-ghost m-1">
<Icon name="mdi-dots-vertical" class="h-7 w-7" />
</label>
<ul tabindex="0" class="dropdown-content menu p-2 shadow bg-base-100 rounded-box w-32">
<li>
<button @click="setViewPreference('card')">
<Icon name="mdi-card-text-outline" class="h-5 w-5" />
Card
</button>
</li>
<li>
<button @click="setViewPreference('table')">
<Icon name="mdi-table" class="h-5 w-5" />
Table
</button>
</li>
</ul>
</div>
</template>
</BaseSectionHeader>
<template v-if="itemView === 'table'">
<ItemViewTable :items="items" />
</template>
<template v-else>
<div class="grid 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>
</template>
</section>
</template>
<style scoped></style>

View file

@ -0,0 +1,10 @@
import { ItemSummary } from "~~/lib/api/types/data-contracts";
export type TableHeader = {
text: string;
value: keyof ItemSummary;
sortable?: boolean;
align?: "left" | "center" | "right";
};
export type TableData = Record<string, any>;

View file

@ -0,0 +1,141 @@
<template>
<BaseCard>
<table class="table w-full">
<thead>
<tr class="bg-primary">
<th
v-for="h in headers"
:key="h.value"
class="text-no-transform text-sm bg-neutral text-neutral-content"
:class="{
'text-center': h.align === 'center',
'text-right': h.align === 'right',
'text-left': h.align === 'left',
}"
>
<template v-if="typeof h === 'string'">{{ h }}</template>
<template v-else>{{ h.text }}</template>
</th>
</tr>
</thead>
<tbody>
<tr v-for="(d, i) in data" :key="i" class="hover cursor-pointer" @click="navigateTo(`/item/${d.id}`)">
<td
v-for="h in headers"
:key="`${h.value}-${i}`"
class="bg-base-100"
:class="{
'text-center': h.align === 'center',
'text-right': h.align === 'right',
'text-left': h.align === 'left',
}"
>
<template v-if="cell(h) === 'cell-name'">
<NuxtLink class="hover" :to="`/item/${d.id}`">
{{ d.name }}
</NuxtLink>
</template>
<template v-else-if="cell(h) === 'cell-purchasePrice'">
<Currency :amount="d.purchasePrice" />
</template>
<template v-else-if="cell(h) === 'cell-insured'">
<Icon v-if="d.insured" name="mdi-check" class="text-green-500 h-5 w-5" />
<Icon v-else name="mdi-close" class="text-red-500 h-5 w-5" />
</template>
<slot v-else :name="cell(h)" v-bind="{ item: d }">
{{ extractValue(d, h.value) }}
</slot>
</td>
</tr>
</tbody>
</table>
<div class="border-t p-3 justify-end flex">
<div class="btn-group">
<button :disabled="!hasPrev" class="btn btn-sm" @click="prev()">«</button>
<button class="btn btn-sm">Page {{ pagination.page }}</button>
<button :disabled="!hasNext" class="btn btn-sm" @click="next()">»</button>
</div>
</div>
</BaseCard>
</template>
<script setup lang="ts">
import { TableData, TableHeader } from "./Table.types";
import { ItemSummary } from "~~/lib/api/types/data-contracts";
type Props = {
items: ItemSummary[];
};
const props = defineProps<Props>();
const sortByProperty = ref<keyof ItemSummary>("name");
const headers = computed<TableHeader[]>(() => {
return [
{ text: "Name", value: "name" },
{ text: "Quantity", value: "quantity", align: "center" },
{ text: "Insured", value: "insured", align: "center" },
{ text: "Price", value: "purchasePrice" },
] as TableHeader[];
});
const pagination = reactive({
sortBy: sortByProperty.value,
descending: false,
page: 1,
rowsPerPage: 10,
rowsNumber: 0,
});
const next = () => pagination.page++;
const hasNext = computed<boolean>(() => {
return pagination.page * pagination.rowsPerPage < props.items.length;
});
const prev = () => pagination.page--;
const hasPrev = computed<boolean>(() => {
return pagination.page > 1;
});
const data = computed<TableData[]>(() => {
// sort by property
let data = [...props.items].sort((a, b) => {
const aLower = a[sortByProperty.value]?.toLowerCase();
const bLower = b[sortByProperty.value]?.toLowerCase();
if (aLower < bLower) {
return -1;
}
if (aLower > bLower) {
return 1;
}
return 0;
});
// sort descending
if (pagination.descending) {
data.reverse();
}
// paginate
const start = (pagination.page - 1) * pagination.rowsPerPage;
const end = start + pagination.rowsPerPage;
data = data.slice(start, end);
return data;
});
function extractValue(data: TableData, value: string) {
const parts = value.split(".");
let current = data;
for (const part of parts) {
current = current[part];
}
return current;
}
function cell(h: TableHeader) {
return `cell-${h.value.replace(".", "_")}`;
}
</script>
<style scoped></style>

View file

@ -10,6 +10,7 @@
label="Location Name"
/>
<FormTextArea v-model="form.description" label="Location Description" />
<LocationSelector v-model="form.parent" />
<div class="modal-action">
<BaseButton type="submit" :loading="loading"> Create </BaseButton>
</div>
@ -18,6 +19,7 @@
</template>
<script setup lang="ts">
import { LocationSummary } from "~~/lib/api/types/data-contracts";
const props = defineProps({
modelValue: {
type: Boolean,
@ -31,6 +33,7 @@
const form = reactive({
name: "",
description: "",
parent: null as LocationSummary | null,
});
whenever(
@ -43,6 +46,7 @@
function reset() {
form.name = "";
form.description = "";
form.parent = null;
focused.value = false;
modal.value = false;
loading.value = false;
@ -54,7 +58,11 @@
async function create() {
loading.value = true;
const { data, error } = await api.locations.create(form);
const { data, error } = await api.locations.create({
name: form.name,
description: form.description,
parentId: form.parent ? form.parent.id : null,
});
if (error) {
toast.error("Couldn't create location");

View file

@ -0,0 +1,49 @@
<template>
<FormAutocomplete
v-model="value"
v-model:search="form.search"
:items="locations"
item-text="display"
item-value="id"
item-search="name"
label="Parent Location"
>
<template #display="{ item }">
<div>
<div>
{{ item.name }}
</div>
<div v-if="item.name != item.display" class="text-xs mt-1">{{ item.display }}</div>
</div>
</template>
</FormAutocomplete>
</template>
<script lang="ts" setup>
import { LocationSummary } from "~~/lib/api/types/data-contracts";
type Props = {
modelValue?: LocationSummary | null;
};
const props = defineProps<Props>();
const value = useVModel(props, "modelValue");
const locations = await useFlatLocations();
const form = ref({
parent: null as LocationSummary | null,
search: "",
});
// Whenever parent goes from value to null reset search
watch(
() => value.value,
() => {
if (!value.value) {
form.value.search = "";
}
}
);
</script>

View file

@ -0,0 +1,73 @@
<script setup lang="ts">
import { useTreeState } from "./tree-state";
import { TreeItem } from "~~/lib/api/types/data-contracts";
type Props = {
treeId: string;
item: TreeItem;
};
const props = withDefaults(defineProps<Props>(), {});
const link = computed(() => {
return props.item.type === "location" ? `/location/${props.item.id}` : `/item/${props.item.id}`;
});
const hasChildren = computed(() => {
return props.item.children.length > 0;
});
const state = useTreeState(props.treeId);
const openRef = computed({
get() {
return state.value[nodeHash.value] ?? false;
},
set(value) {
state.value[nodeHash.value] = value;
},
});
const nodeHash = computed(() => {
// converts a UUID to a short hash
return props.item.id.replace(/-/g, "").substring(0, 8);
});
</script>
<template>
<div>
<div
class="node flex items-center gap-1 rounded p-1"
:class="{
'cursor-pointer hover:bg-base-200': hasChildren,
}"
@click="openRef = !openRef"
>
<div
class="p-1/2 rounded mr-1 flex items-center justify-center"
:class="{
'hover:bg-base-200': hasChildren,
}"
>
<div v-if="!hasChildren" class="h-6 w-6"></div>
<label
v-else
class="swap swap-rotate"
:class="{
'swap-active': openRef,
}"
>
<Icon name="mdi-chevron-right" class="h-6 w-6 swap-off" />
<Icon name="mdi-chevron-down" class="h-6 w-6 swap-on" />
</label>
</div>
<Icon v-if="item.type === 'location'" name="mdi-map-marker" class="h-4 w-4" />
<Icon v-else name="mdi-package-variant" class="h-4 w-4" />
<NuxtLink class="hover:link text-lg" :to="link" @click.stop>{{ item.name }} </NuxtLink>
</div>
<div v-if="openRef" class="ml-4">
<LocationTreeNode v-for="child in item.children" :key="child.id" :item="child" :tree-id="treeId" />
</div>
</div>
</template>
<style scoped></style>

View file

@ -0,0 +1,18 @@
<script setup lang="ts">
import { TreeItem } from "~~/lib/api/types/data-contracts";
type Props = {
locs: TreeItem[];
treeId: string;
};
defineProps<Props>();
</script>
<template>
<div class="p-4 border-2 root">
<LocationTreeNode v-for="item in locs" :key="item.id" :item="item" :tree-id="treeId" />
</div>
</template>
<style></style>

View file

@ -0,0 +1,17 @@
import type { Ref } from "vue";
type TreeState = Record<string, boolean>;
const store: Record<string, Ref<TreeState>> = {};
export function newTreeKey(): string {
return Math.random().toString(36).substring(2);
}
export function useTreeState(key: string): Ref<TreeState> {
if (!store[key]) {
store[key] = ref({});
}
return store[key];
}