刘光辉
6 小时以前 cf11e63b659afcc9792ab3e395f1b45d844431a8
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
<script lang="ts" setup>
import type { Component } from 'vue';
 
import { computed, defineAsyncComponent, markRaw, nextTick, onMounted, onUnmounted, reactive, shallowRef } from 'vue';
import { useRouter } from 'vue-router';
 
import { useMessage } from '@jnpf/hooks';
import { BasicPopup } from '@jnpf/ui/popup';
 
import { clearCustomViewParams } from '#/utils/custom-view-context';
import { onlineUtils, type OpenCustomViewConfig } from '#/utils/jnpf';
 
interface OpenCustomViewEvent extends OpenCustomViewConfig {
  instanceId: number;
  params: Record<string, any>;
}
 
type ViewLoader = () => Promise<{ default: Component }>;
type ViewCloseDecision = boolean | 'pending';
 
const customViews = import.meta.glob('../../views/x/**/*.vue') as Record<string, ViewLoader>;
const contentTargetSelectors = ['.jnpf-layout-content > .app-main', '.jnpf-layout-content .app-main', '.app-main'];
const emitter = onlineUtils.getEmitter();
const router = useRouter();
const { createMessage } = useMessage();
const viewComponent = shallowRef<Component | null>(null);
const viewRef = shallowRef<null | { requestClose?: () => Promise<ViewCloseDecision> | ViewCloseDecision }>(null);
const teleportTarget = shallowRef<HTMLElement | null>(null);
let closePromise: null | Promise<ViewCloseDecision> = null;
let removeRouteHook: (() => void) | null = null;
let pendingRoutePath: null | string = null;
let pendingRouteTimer: null | ReturnType<typeof setTimeout> = null;
 
const EDITOR_CLOSE_CONFIRM_TIMEOUT_MILLIS = 30_000;
 
const state = reactive({
  config: null as null | OpenCustomViewEvent,
  key: 0,
  loading: false,
  open: false,
  title: '自定义页面',
});
 
const viewParams = computed(() => state.config?.params || {});
 
function normalizePagePath(page: string) {
  const normalized = page
    .trim()
    .replaceAll('\\', '/')
    .replace(/^\/+/, '')
    .replace(/\.vue$/, '')
    .replace(/\/index$/, '');
  const segments = normalized.split('/');
  if (!normalized.startsWith('x/') || segments.some((segment) => !segment || segment === '.' || segment === '..')) return '';
  return normalized;
}
 
function getViewLoader(page: string) {
  const normalized = normalizePagePath(page);
  if (!normalized) return null;
  const basePath = `../../views/${normalized}`;
  return customViews[`${basePath}.vue`] || customViews[`${basePath}/index.vue`] || null;
}
 
function findContentTarget() {
  for (const selector of contentTargetSelectors) {
    const target = document.querySelector<HTMLElement>(selector);
    if (target) return target;
  }
  return null;
}
 
async function ensureTeleportTarget() {
  const currentTarget = findContentTarget();
  if (!currentTarget) return false;
  if (teleportTarget.value !== currentTarget) {
    teleportTarget.value = currentTarget;
    await nextTick();
  }
  return true;
}
 
function resetState() {
  state.config = null;
  state.loading = false;
  state.open = false;
  state.title = '自定义页面';
  viewComponent.value = null;
  viewRef.value = null;
}
 
function clearPendingRouteTimer() {
  if (pendingRouteTimer) clearTimeout(pendingRouteTimer);
  pendingRouteTimer = null;
}
 
function clearPendingRoute() {
  clearPendingRouteTimer();
  pendingRoutePath = null;
}
 
function rememberPendingRoute(routePath: string) {
  clearPendingRoute();
  pendingRoutePath = routePath;
  // ONLYOFFICE requestClose 没有“取消”回调,给确认阶段设置边界,避免以后误跳到已取消的旧目标。
  pendingRouteTimer = setTimeout(clearPendingRoute, EDITOR_CLOSE_CONFIRM_TIMEOUT_MILLIS);
}
 
function finalizeClose(result?: any) {
  const config = state.config;
  resetState();
  if (!config) return Promise.resolve(true);
 
  clearCustomViewParams(config.instanceId);
  try {
    config.onClose?.(result);
  } catch (error) {
    console.error('[onlineUtils.openCustomView] onClose error:', error);
  }
  return Promise.resolve(true);
}
 
function requestViewClose() {
  if (closePromise) return closePromise;
  const config = state.config;
  if (!config) return Promise.resolve(true);
 
  closePromise = (async () => {
    try {
      const accepted = await viewRef.value?.requestClose?.();
      if (accepted === false) return false;
      if (state.config?.instanceId !== config.instanceId) return false;
      return accepted === 'pending' ? 'pending' : true;
    } catch (error: any) {
      createMessage.warning(error?.message || '当前页面暂时无法关闭');
      return false;
    } finally {
      closePromise = null;
    }
  })();
  return closePromise;
}
 
async function requestClose(result?: any) {
  clearPendingRoute();
  if ((await requestViewClose()) !== true) return false;
  return finalizeClose(result);
}
 
async function handleCloseReady(result?: any) {
  const routePath = pendingRoutePath;
  clearPendingRoute();
  await finalizeClose(result);
  if (routePath && router.currentRoute.value.fullPath !== routePath) await router.push(routePath);
}
 
function handleCloseStarted() {
  if (pendingRoutePath) clearPendingRouteTimer();
}
 
async function handleOpen(config: OpenCustomViewEvent) {
  if (state.config && !(await requestClose())) {
    clearCustomViewParams(config.instanceId);
    return;
  }
 
  state.config = config;
  state.loading = true;
  state.title = config.title || '自定义页面';
  viewComponent.value = null;
 
  try {
    if (!(await ensureTeleportTarget())) throw new Error('未找到当前页签内容区域');
    if (state.config?.instanceId !== config.instanceId) return;
    const loader = getViewLoader(config.page);
    if (!loader) throw new Error('未找到 src/views/x 下的自定义页面');
    viewComponent.value = markRaw(defineAsyncComponent(loader));
    state.key = config.instanceId;
    state.open = true;
  } catch (error: any) {
    console.error('[onlineUtils.openCustomView] open custom view failed:', error);
    clearCustomViewParams(config.instanceId);
    resetState();
    createMessage.warning(error?.message || '打开自定义页面失败');
  } finally {
    state.loading = false;
  }
}
 
const popupContext = {
  close: (result?: any) => requestClose(result),
};
 
onMounted(() => {
  teleportTarget.value = findContentTarget();
  emitter.on('OPEN_CUSTOM_VIEW_MODAL', handleOpen as any);
  removeRouteHook = router.beforeEach(async (to, from) => {
    if (to.fullPath === from.fullPath || !state.config) return true;
    const decision = await requestViewClose();
    if (decision === true) {
      clearPendingRoute();
      await finalizeClose();
      return true;
    }
    if (decision === 'pending') rememberPendingRoute(to.fullPath);
    else clearPendingRoute();
    return false;
  });
});
 
onUnmounted(() => {
  emitter.off('OPEN_CUSTOM_VIEW_MODAL', handleOpen as any);
  removeRouteHook?.();
  removeRouteHook = null;
  clearPendingRoute();
  if (state.config) clearCustomViewParams(state.config.instanceId);
});
</script>
 
<template>
  <Teleport v-if="teleportTarget" :to="teleportTarget">
    <BasicPopup
      :open="state.open"
      :loading="state.loading"
      destroy-on-close
      :show-ok-btn="false"
      :close-func="requestClose"
      class="full-popup global-custom-view-popup">
      <template #title>
        <div class="text-[16px] font-medium">{{ state.title }}</div>
      </template>
      <div class="global-custom-view-popup-body">
        <component
          :is="viewComponent"
          v-if="viewComponent"
          :key="state.key"
          ref="viewRef"
          :params="viewParams"
          :popup-context="popupContext"
          @close="requestClose"
          @close-cancelled="clearPendingRoute"
          @close-ready="handleCloseReady"
          @close-started="handleCloseStarted" />
      </div>
    </BasicPopup>
  </Teleport>
</template>
 
<style>
.global-custom-view-popup {
  border-radius: var(--radius);
}
 
.global-custom-view-popup-body {
  height: 100%;
  min-height: 0;
  overflow: hidden;
}
 
.global-custom-view-popup-body > .jnpf-content-wrapper {
  height: 100%;
}
</style>