Files
timi-tdesign-mobile/src/composables/use-master-detail.ts
T
Timi bdaee75b81 feat(master-detail): add cover sub-mode and providePane
- MasterDetail / MasterDetailPage: add `sub-mode` ("shift" | "cover", default
  "shift", so existing callers are unaffected). `cover` leaves the master pane
  untouched and puts the sub pane over the detail column: the case where the
  list must stay visible while drilling into another module. The detail pane
  fades out in place instead of sliding into the master column, so it stays
  mounted and keeps its scroll position and internal state.
- use-master-detail: export `providePane(context)` and return `close` from
  useMasterDetailPane. A page can now hand a derived pane context to its whole
  subtree, which is how a host rewrites sub view ids (prefixing them with the
  owning record). The alternative - a wrapper component - breaks the
  `.detail > .tui-page-layout` selectors in page-layout.less and sends the
  in-pane navbar back to `position: fixed`.
- docs: cover vs shift, and how to prefix sub view ids without a wrapper.
2026-11-18 15:08:44 +08:00

582 lines
19 KiB
TypeScript
Raw Blame History

This file contains ambiguous Unicode characters
This file contains Unicode characters that might be confused with other characters. If you think that this is intentional, you can safely ignore this warning. Use the Escape button to reveal them.
import { inject, provide, ref, watch, type InjectionKey } from "vue";
import { useRoute, useRouter } from "vue-router";
import { useLayout } from "./use-layout";
/**
* 右栏切换方向。
*
* - forward:进入下一层(详情 → 编辑)
* - back:返回上一层(编辑 → 详情)
* - none:同级内容替换(换一个客户),不做滑动
*/
export type PaneDirection = "forward" | "back" | "none";
/** 右栏内容与列表页之间的约定。 */
export interface PaneContext {
/**
* 关闭当前栏内容,回到上一层。
*
* 分层时关最上面一层:有子页先关子页,其次关编辑,最后关详情。
*
* @param saved 是否有数据变更,上层可据此决定要不要刷新
*/
close: (saved?: boolean) => void;
/**
* 在当前栏之上再压一层子页面(分栏内的第三层)。
*
* 只有分栏形态下接得住。返回 false 表示没接住——窄屏、没有选中项,
* 或者宿主页面没有声明子页槽,调用方应当改走整页路由。
*
* @param view 子页标识,由列表页解析,例如 `recycle-rule:698f`
*/
openSub: (view: string) => boolean;
}
/** useMasterDetail 的配置。 */
export interface UseMasterDetailOptions {
/** 由选中 id 生成详情页路由,窄屏时用于跳转。 */
route?: (id: string) => string;
/** 初始选中项。 */
initial?: string;
/**
* 视口从宽变窄时,把内联的选中项转成整页路由。
*
* 否则用户旋转平板或拖动窗口后,详情栏不再渲染,正在看的内容会凭空消失。
*
* 传 `true` 用 `route(id)` 生成目标;右栏里还有编辑这类子视图时,
* 传函数由业务决定"当前该落到哪个页面",否则正在编辑的内容会被跳成详情。
*/
followViewport?: boolean | ((id: string) => string);
/**
* 右栏内容调用了 `usePane().close()`。
*
* 详情页、编辑页这类内联组件靠它把"返回/取消/保存完成"交回列表页处理,
* 不需要自己判断该跳哪条路由。
*/
onClose?: (saved?: boolean) => void;
/**
* 右栏内容请求压入一个子页面。
*
* 返回 false 表示宿主管不了这个子页,调用方应改走整页跳转。
*/
onOpenSub?: (view: string) => boolean;
}
/** useMasterDetail 的返回值。 */
export interface UseMasterDetailReturn {
/** 当前选中的 id,空字符串表示未选中。 */
selectedId: ReturnType<typeof ref<string>>;
/** 是否处于分栏形态,可直接用于 `master-detail` 的显式控制。 */
isWide: ReturnType<typeof useLayout>["isWide"];
/** 选中某一项:宽屏切换右栏内容,窄屏跳详情路由。 */
open: (id: string) => void;
/** 清空选中。 */
clear: () => void;
}
const PANE_KEY: InjectionKey<PaneContext> = Symbol("tui-pane");
/**
* 读取右栏上下文。
*
* 返回 `null` 说明当前不在 `MasterDetail` 的详情栏里(例如整页路由打开),
* 此时"返回"应该走路由,而不是通知列表页。
*/
export function usePane(): PaneContext | null {
return inject(PANE_KEY, null);
}
/**
* 把一套栏内上下文提供给后代。
*
* 用在"页面要改写子页标识"的场合:列表页在最外层 provide 一套派生上下文,
* 右栏里的页面调 `openSub()` 时标识先经过它,不必在中间塞一层容器组件。
*
* 不要用容器组件代替它:栏内页面的骨架样式(导航栏退化成栏内头部、内容区铺满)
* 挂在 `.detail > .tui-page-layout` 这类直系选择器上,多包一层就全落空。
*
* 注意 provide 只在当前组件的后代里生效,且会遮蔽上层的同一套上下文,
* 所以派生时要把 `close` / `openSub` 转发给宿主,别自己重写一套。
*
* @param context 派生出来的上下文,通常转发 `usePane()` 拿到的宿主上下文
*/
export function providePane(context: PaneContext): void {
provide(PANE_KEY, context);
}
/**
* 主从布局的选中态管理。
*
* 把"宽屏换右栏、窄屏跳路由"的分支收在一处,列表页只需要 `@click="open(item.id)"`。
*/
export function useMasterDetail(options: UseMasterDetailOptions = {}): UseMasterDetailReturn {
const router = useRouter();
const layout = useLayout();
const selectedId = ref(options.initial ?? "");
const isWide = layout.isWide;
// 右栏里的页面通过 usePane().close() 把控制权交回来
providePane({
close: (saved = false) => options.onClose?.(saved),
openSub: view => options.onOpenSub?.(view) ?? false
});
function open(id: string): void {
if (!id) {
return;
}
if (isWide.value) {
selectedId.value = id;
return;
}
if (options.route) {
void router.push(options.route(id));
return;
}
selectedId.value = id;
}
function clear(): void {
selectedId.value = "";
}
if (options.followViewport) {
const toRoute = typeof options.followViewport === "function"
? options.followViewport
: options.route;
if (toRoute) {
watch(isWide, (wide, wasWide) => {
if (wide === wasWide || wide || !selectedId.value) {
return;
}
void router.push(toRoute(selectedId.value));
});
}
}
return { selectedId, isWide, open, clear };
}
/** 写进 `history.state` 的栏内层级。 */
interface PaneHistoryState {
paneLevel?: unknown;
}
/**
* 读取当前 history 条目所处的栏内层级。
*
* 0 表示这一条不是栏内导航推出来的(例如从别的页面 push 进列表页),
* 此时 `router.back()` 会退出列表页,只能降级成 replace。
*/
function readPaneLevel(): number {
if (!("history" in globalThis)) {
return 0;
}
const level = Number((history.state as PaneHistoryState | null)?.paneLevel);
return Number.isInteger(level) && level > 0 ? level : 0;
}
/** useMasterDetailPane 的配置。 */
export interface UseMasterDetailPaneOptions {
/** 列表页路由,转屏回到分栏时的落点。 */
path: string;
/** 详情整页路由。 */
detail: (id: string) => string;
/** 编辑整页路由;不传表示这个模块没有内联编辑视图。 */
edit?: (id: string) => string;
/** 初始选中项;不传则读 query。 */
initial?: string;
/** 初始是否处于编辑视图;不传则读 query。 */
initialEditing?: boolean;
/** 选中项写回 query 的字段名,默认 detail。 */
queryKey?: string;
/** 编辑态写回 query 的字段名,默认 view。 */
viewQueryKey?: string;
/** 子页标识写回 query 的字段名,默认 sub。 */
subQueryKey?: string;
/** 是否把选中项和编辑态同步到 query,默认 true。 */
syncQuery?: boolean;
/**
* 是否让栏内层级进入浏览器历史,默认 true。
*
* 开启后「选中一项」「进入编辑」「打开子页」各推一条 history,手势返回会逐级回退
* (子页 → 详情 → 空栏 → 离开页面),前进手势也能还原右栏。
* 关掉则退回旧行为:层级只改 query,手势返回直接离开列表页。
*/
historyLevels?: boolean;
}
/** useMasterDetailPane 的返回值。 */
export interface UseMasterDetailPaneReturn {
/** 当前选中的 id。 */
selectedId: ReturnType<typeof ref<string>>;
/** 右栏是否处于编辑视图。 */
editing: ReturnType<typeof ref<boolean>>;
/**
* 当前栏内子页标识,空字符串表示没有子页。
*
* 非空时页面处于第三层:列表滑出,详情在主栏,右栏渲染 `#sub` 槽。
*/
subView: ReturnType<typeof ref<string>>;
/** 详情重建计数,保存后自增可让详情重新加载。 */
detailVersion: ReturnType<typeof ref<number>>;
/** 右栏切换方向,直接传给 PaneTransition。 */
paneDirection: ReturnType<typeof ref<PaneDirection>>;
/** 是否处于分栏形态。 */
isWide: ReturnType<typeof useLayout>["isWide"];
/** 选中某一项:宽屏换右栏,窄屏跳详情页。 */
openDetail: (id: string) => void;
/** 右栏切到编辑;没有配置 edit 路由时无效。 */
openEdit: () => void;
/**
* 在右栏压入一层子页面;返回 false 表示当前不是分栏,调用方应改走整页路由。
*
* 调用方通常是详情页:`if (!pane.openSub("recycle-rule:" + id)) router.push(...)`。
*/
openSub: (view: string) => boolean;
/** 关闭子页面,回到详情层。 */
closeSub: () => void;
/**
* 关闭右栏最上面一层:有子页先关子页,其次关编辑,最后关详情。
*
* 和 `usePane().close()` 是同一套逻辑,给"页面要派生一套栏内上下文"时转发用
* (见 `providePane`)。
*/
close: (saved?: boolean) => void;
}
/**
* 主从分栏的完整状态机:选中项、编辑态、子页、切换方向、关闭逻辑、转屏、query 同步。
*
* 列表页只需要 `openDetail(item.id)`、`openEdit()` 和 `subView`,
* 模板里把 `editing` / `selectedId` / `subView` / `paneDirection` 接到
* `MasterDetailPage` 上即可,不用自己写分支。
*
* 编辑视图是可选的:不传 `edit` 时 `openEdit` 什么都不做,`editing` 恒为 false。
*
* 子页是第三层:详情页通过 `usePane().openSub(view)` 压入,列表页用 `#sub` 槽渲染。
* 此时布局从「列表 + 详情」变成「详情 + 子页」,返回再还原。
*
* 栏内层级默认会进浏览器历史(见 `historyLevels`):选中一项、进入编辑、打开子页各推一条,
* 所以浏览器返回手势、物理返回键会先在栏内逐级回退(子页/编辑 → 详情 → 空栏),
* 空栏时再返回才离开列表页。返回手势触发的是 query 变化,
* `PageTransition` 按 path 和 depth 判定,不会把它当成翻页。
*/
export function useMasterDetailPane(options: UseMasterDetailPaneOptions): UseMasterDetailPaneReturn {
const router = useRouter();
const route = useRoute();
const queryKey = options.queryKey ?? "detail";
const viewKey = options.viewQueryKey ?? "view";
const subKey = options.subQueryKey ?? "sub";
const editing = ref(options.initialEditing ?? String(route.query[viewKey] || "") === "edit");
const subView = ref(String(route.query[subKey] || ""));
const detailVersion = ref(0);
const paneDirection = ref<PaneDirection>("forward");
const hasEdit = typeof options.edit === "function";
const useHistory = options.historyLevels !== false && options.syncQuery !== false;
/** 下一次状态变更要推历史还是只改 query。 */
const pendingNav = ref<"push" | "replace">("replace");
/** 由 history 回退触发的降级时,用它把「保存过」交给反向同步去消费。 */
const pendingSaved = ref(false);
/** 从编辑态直接换一项时,先退回详情层,再由反向同步换成这个 id。 */
const pendingSwapId = ref("");
/**
* 栏内层级:有选中项记 1 级,子页或编辑再各加 1 级。
*
* 子页和编辑都从详情发起,互斥,所以最多两级叠加。
*/
function levelOf(id: string | undefined, isEditing: boolean, view: string): number {
return id ? 1 + (view || isEditing ? 1 : 0) : 0;
}
/**
* 往回退一层:能安全回退就交回给 history,让「点关闭」和「手势返回」走同一条路径。
*
* 栈顶不是栏内层级时(直接带 ?detail=x 链接进来)不能 back,否则会退出站点。
*/
function popPane(saved = false): boolean {
if (!useHistory || !isWide.value || readPaneLevel() <= 0) {
return false;
}
pendingSaved.value = saved;
void router.back();
return true;
}
function requestSub(view: string): boolean {
// 窄屏没有右栏可叠;没有选中项也没有"上一层"可以退
if (!view || !isWide.value || !selectedId.value) {
return false;
}
pendingNav.value = "push";
paneDirection.value = "forward";
subView.value = view;
return true;
}
const { selectedId, isWide, open } = useMasterDetail({
route: options.detail,
initial: options.initial ?? String(route.query[queryKey] || ""),
// 宽变窄时按右栏当前视图决定落到哪个整页:正在编辑就进编辑页。
// 子页在这条路径上会被丢掉——它没有对应的整页路由,转屏后退回详情是能接受的最差情况。
followViewport: id => (editing.value && options.edit
? options.edit(id)
: options.detail(id)),
onOpenSub: requestSub,
onClose: saved => closePane(saved)
});
/** 关闭右栏最上面一层;页面派生上下文时原样转发这一个。 */
function closePane(saved = false): void {
if (popPane(saved)) {
return;
}
// 降级:没有可回退的层级,只改 query
pendingNav.value = "replace";
paneDirection.value = "back";
// 有子页先关子页,回到详情
if (subView.value) {
subView.value = "";
return;
}
// 取消/保存编辑:回到详情,保存过就让详情重新加载
if (editing.value) {
editing.value = false;
if (saved) {
detailVersion.value++;
}
return;
}
// 关闭详情:右滑出,回到空栏
selectedId.value = "";
}
function openDetail(id: string): void {
// 正在编辑时直接点列表里另一项:栈顶是编辑层,就地改成新客户的详情的话,
// 下面那条旧客户详情会重新可达,返回时会掉回上一个客户。
// 先退回详情层,再在那层上改写选中项,栈里始终只有一条「当前客户」。
if (useHistory && isWide.value && selectedId.value && editing.value && readPaneLevel() >= 2) {
pendingSwapId.value = id;
void router.back();
return;
}
// 右栏已经有内容时,换一项是同级内容替换,不做滑入;
// 从空到有由外层 v-if 处理(首次挂载不播 enter),方向不影响结果
paneDirection.value = selectedId.value ? "none" : "forward";
// 从空到有才算开新层级;换一项不堆历史,否则连点 N 项要按 N 次返回
pendingNav.value = selectedId.value ? "replace" : "push";
editing.value = false;
// 换订单时子页属于上一单,跟着一起收掉
subView.value = "";
open(id);
}
function openEdit(): void {
if (!hasEdit) {
return;
}
// 详情 → 编辑是加深一层,手势返回应该先退回详情
pendingNav.value = "push";
paneDirection.value = "forward";
subView.value = "";
editing.value = true;
}
function closeSub(): void {
if (!subView.value) {
return;
}
// 子页滑出右侧,栏宽同时收缩
paneDirection.value = "back";
if (popPane()) {
return;
}
pendingNav.value = "replace";
subView.value = "";
}
// 选中项、编辑态、子页一起写回 query:刷新、分享链接、转屏都靠它恢复。
// 合并成一次导航,避免多个 watcher 互相覆盖。
if (options.syncQuery !== false) {
watch([selectedId, editing, subView], ([id, isEditing, view]) => {
// 窄屏走的是整页详情路由,列表页不该再改 query 把它顶掉
if (!isWide.value || route.path !== options.path) {
return;
}
const nextDetail = id || "";
// 子页比编辑深一层,两者互斥:子页在时不再记编辑态
const nextSub = id ? view : "";
const nextView = isEditing && id && !nextSub ? "edit" : "";
if (String(route.query[queryKey] || "") === nextDetail
&& String(route.query[viewKey] || "") === nextView
&& String(route.query[subKey] || "") === nextSub) {
return;
}
const nav = pendingNav.value;
pendingNav.value = "replace";
// paneLevel 跟着 history 条目走:pop 时浏览器自动还原它,前进手势也能对上。
// replace 只继承不抬升,取 min 是为了:直接带 ?detail=x 链接进来时这一条
// 底下没有列表层,标成栏内层级的话再返回就会真的退出站点。
const nextLevel = levelOf(id, isEditing, nextSub);
void router[nav]({
path: options.path,
query: {
...route.query,
[queryKey]: nextDetail || undefined,
[viewKey]: nextView || undefined,
[subKey]: nextSub || undefined
},
state: { paneLevel: nav === "push" ? nextLevel : Math.min(readPaneLevel(), nextLevel) }
});
});
}
// 反向同步:手势返回、前进手势、外部导航落到列表页时,用 query 驱动栏内状态。
// 与上面那个 watcher 都做了幂等比较,两边不会互相触发。
if (options.syncQuery !== false) {
watch(
() => [
route.path,
String(route.query[queryKey] || ""),
String(route.query[viewKey] || ""),
String(route.query[subKey] || "")
] as const,
([path, nextId, nextView, nextSub]) => {
if (!isWide.value || path !== options.path) {
return;
}
const nextEditing = nextView === "edit" && !!nextId && !nextSub;
if (nextId === selectedId.value && nextEditing === editing.value && nextSub === subView.value) {
return;
}
// 上一步退回详情层就是为了换这一项,这里把它落地
const swapId = pendingSwapId.value;
if (swapId) {
pendingSwapId.value = "";
paneDirection.value = "back";
pendingNav.value = "replace";
editing.value = false;
subView.value = "";
selectedId.value = swapId;
return;
}
const nextLevel = levelOf(nextId, nextEditing, nextSub);
const previousLevel = levelOf(selectedId.value, editing.value, subView.value);
paneDirection.value = nextLevel < previousLevel
? "back"
: nextLevel > previousLevel
? "forward"
: "none";
selectedId.value = nextId;
editing.value = nextEditing;
subView.value = nextSub;
// 从保存过的编辑退回详情,让详情重新加载
if (nextLevel < previousLevel && pendingSaved.value) {
detailVersion.value++;
}
pendingSaved.value = false;
}
);
}
return {
selectedId,
editing,
subView,
detailVersion,
paneDirection,
isWide,
openDetail,
openEdit,
openSub: requestSub,
closeSub,
close: closePane
};
}
/** useExpandToMaster 的配置。 */
export interface ExpandToMasterOptions {
/** 列表页路由,通常就是 MasterDetail 所在的页面。 */
path: string;
/** 当前详情 id;返回空值时不动。 */
id: () => string | undefined;
/** 回填选中项用的 query 字段名,默认 detail。 */
queryKey?: string;
/**
* 附加的 query 字段,用来把"右栏当前是哪个子视图"带回列表页。
*
* 例如编辑页传 `{ view: "edit" }`,列表页读出来就能直接把右栏还原成编辑态。
* 只写这里给出的字段,不会带上当前页面的 query——编辑页的 redirect 之类不该带过去。
*/
query?: Record<string, string>;
}
/**
* 整页详情在视口变宽时合并回主从分栏。
*
* 竖屏点进详情是整页路由,转成横屏后如果继续停在整页,用户就看不到列表了——
* 而横屏本来就放得下两栏。这里在变宽时 replace 回列表页,并把选中项写进 query,
* 列表页用 `initial` 读出来即可恢复右栏。
*
* 只在"整页"场景生效:内联在右栏时(`usePane()` 非空)不做任何事。
* 编辑页不要调用——变宽会重建表单,用户填了一半的内容会丢。
*/
export function useExpandToMaster(options: ExpandToMasterOptions): void {
const layout = useLayout();
const router = useRouter();
const pane = usePane();
watch(layout.isWide, wide => {
if (!wide || pane) {
return;
}
const id = options.id();
if (!id) {
return;
}
void router.replace({
path: options.path,
query: {
[options.queryKey ?? "detail"]: id,
...(options.query ?? {})
}
});
});
}