|
| 1 | +import { onUnmounted, ref } from 'vue' |
| 2 | +import { getController } from './controller' |
| 3 | +import { getPageAncestors } from '../material-function/page-getter' |
| 4 | + |
| 5 | +export function useRouterPreview() { |
| 6 | + const pageId = ref(getController().getBaseInfo().pageId) |
| 7 | + const previewId = ref(getController().getBaseInfo().previewId) |
| 8 | + const updatePreviewId = getController().updatePreviewId |
| 9 | + const previewFullPath = ref([]) |
| 10 | + const previewPath = ref([]) |
| 11 | + |
| 12 | + async function calcNewPreviewFullPath() { |
| 13 | + if (!pageId.value) { |
| 14 | + if (previewId.value) { |
| 15 | + updatePreviewId(undefined, true) |
| 16 | + return |
| 17 | + } |
| 18 | + previewFullPath.value = [] |
| 19 | + previewPath.value = [] |
| 20 | + return |
| 21 | + } |
| 22 | + if (!previewId.value) { |
| 23 | + previewFullPath.value = await getPageAncestors(pageId.value) |
| 24 | + previewPath.value = [] |
| 25 | + return |
| 26 | + } |
| 27 | + |
| 28 | + if (previewFullPath.value[previewFullPath.value.length - 1] !== previewId.value) { |
| 29 | + // previewId changed |
| 30 | + const fullPath = await getPageAncestors(previewId.value) |
| 31 | + if (fullPath.includes(pageId.value)) { |
| 32 | + previewFullPath.value = fullPath |
| 33 | + } else { |
| 34 | + updatePreviewId(pageId.value, true) |
| 35 | + } |
| 36 | + } |
| 37 | + |
| 38 | + if (previewFullPath.value.includes(pageId.value)) { |
| 39 | + // only pageId changed and fast move |
| 40 | + const fastJumpIndex = previewFullPath.value.indexOf(pageId.value) |
| 41 | + if (fastJumpIndex + 1 < previewFullPath.value.length) { |
| 42 | + previewPath.value = previewFullPath.value.slice(fastJumpIndex + 1) |
| 43 | + } else { |
| 44 | + previewPath.value = [] |
| 45 | + } |
| 46 | + } else { |
| 47 | + previewFullPath.value = await getPageAncestors(pageId.value) |
| 48 | + previewPath.value = [] |
| 49 | + updatePreviewId(pageId.value, true) |
| 50 | + } |
| 51 | + } |
| 52 | + |
| 53 | + const cancel = getController().addHistoryDataChangedCallback(() => { |
| 54 | + const newPageId = getController().getBaseInfo().pageId |
| 55 | + const newPreviewId = getController().getBaseInfo().previewId |
| 56 | + const pageIdChanged = newPageId !== pageId.value |
| 57 | + const previewIdChanged = newPreviewId !== previewId.value |
| 58 | + if (pageIdChanged) { |
| 59 | + pageId.value = newPageId |
| 60 | + } |
| 61 | + if (previewIdChanged) { |
| 62 | + previewId.value = newPreviewId |
| 63 | + } |
| 64 | + if (previewIdChanged || pageIdChanged) { |
| 65 | + calcNewPreviewFullPath() |
| 66 | + } |
| 67 | + }) |
| 68 | + |
| 69 | + onUnmounted(() => { |
| 70 | + cancel() |
| 71 | + }) |
| 72 | + |
| 73 | + calcNewPreviewFullPath() |
| 74 | + |
| 75 | + return { |
| 76 | + previewPath, |
| 77 | + previewFullPath |
| 78 | + } |
| 79 | +} |
0 commit comments