| 1 | import { computed, ref } from "vue" |
| 2 | |
| 3 | export interface BreadcrumbItem { |
| 4 | name: string |
| 5 | path: string |
| 6 | key: string |
| 7 | } |
| 8 | |
| 9 | const breadcrumbItems = ref<BreadcrumbItem[]>([]) |
| 10 | |
| 11 | export function useBreadcrumb() { |
| 12 | const items = computed(() => breadcrumbItems.value) |
| 13 | |
| 14 | /** |
| 15 | * Adds a new item to the end of the breadcrumb |
| 16 | */ |
| 17 | function push(item: BreadcrumbItem) { |
| 18 | breadcrumbItems.value.push(item) |
| 19 | } |
| 20 | |
| 21 | /** |
| 22 | * Replaces the last breadcrumb item |
| 23 | * If there are no items, adds the new item |
| 24 | */ |
| 25 | function replace(item: BreadcrumbItem) { |
| 26 | if (breadcrumbItems.value.length === 0) { |
| 27 | breadcrumbItems.value.push(item) |
| 28 | } else { |
| 29 | breadcrumbItems.value[breadcrumbItems.value.length - 1] = item |
| 30 | } |
| 31 | } |
| 32 | |
| 33 | /** |
| 34 | * Updates only the name of the last breadcrumb item |
| 35 | * If there are no items, does nothing |
| 36 | */ |
| 37 | function updateLastCrumbName(name: string) { |
| 38 | if (breadcrumbItems.value.length > 0) { |
| 39 | const lastItem = breadcrumbItems.value.at(-1) |
| 40 | if (!lastItem) return |
| 41 | |
| 42 | breadcrumbItems.value[breadcrumbItems.value.length - 1] = { |
| 43 | ...lastItem, |
| 44 | name |
| 45 | } |
| 46 | } |
| 47 | } |
| 48 | |
| 49 | /** |
| 50 | * Removes the last breadcrumb item |
| 51 | */ |
| 52 | function pop() { |
| 53 | return breadcrumbItems.value.pop() |
| 54 | } |
| 55 | |
| 56 | /** |
| 57 | * Clears all breadcrumb items |
| 58 | */ |
| 59 | function clear() { |
| 60 | breadcrumbItems.value = [] |
| 61 | } |
| 62 | |
| 63 | /** |
| 64 | * Sets all breadcrumb items |
| 65 | */ |
| 66 | function setItems(items: BreadcrumbItem[]) { |
| 67 | breadcrumbItems.value = items |
| 68 | } |
| 69 | |
| 70 | /** |
| 71 | * Removes items until reaching the specified index |
| 72 | */ |
| 73 | function truncate(index: number) { |
| 74 | if (index >= 0 && index < breadcrumbItems.value.length) { |
| 75 | breadcrumbItems.value = breadcrumbItems.value.slice(0, index + 1) |
| 76 | } |
| 77 | } |
| 78 | |
| 79 | return { |
| 80 | items, |
| 81 | push, |
| 82 | replace, |
| 83 | updateLastCrumbName, |
| 84 | pop, |
| 85 | clear, |
| 86 | setItems, |
| 87 | truncate |
| 88 | } |
| 89 | } |