refactor(frontend): 重构前端第二版
This commit is contained in:
1 parent
2631f78b00
commit
4b562cfa82
205 files changed
+15399
-12015
No files matched your search
@@ -0,0 +1,208 @@
|
||||
/**
|
||||
* shared/composables/useAudioTranscription.ts
|
||||
* 语音录制与转写,供聊天输入栏使用。
|
||||
*/
|
||||
import { ref, computed, onBeforeUnmount } from 'vue';
|
||||
import { getAuthHeaders } from '@/shared/utils/auth';
|
||||
|
||||
export type AudioTranscriptionErrorKey =
|
||||
| 'chat.voiceRequiresHttps'
|
||||
| 'chat.voiceNotSupported'
|
||||
| 'chat.voicePermissionDenied'
|
||||
| 'chat.voiceRecordTooShort'
|
||||
| 'chat.voiceTranscriptionFailed';
|
||||
|
||||
const isSecureContextForMic = (): boolean => {
|
||||
if (typeof window === 'undefined') return false;
|
||||
if (window.isSecureContext) return true;
|
||||
const host = window.location.hostname;
|
||||
return host === 'localhost' || host === '127.0.0.1';
|
||||
};
|
||||
|
||||
const canUseMediaRecorder = (): boolean => {
|
||||
if (typeof window === 'undefined') return false;
|
||||
return Boolean(window.MediaRecorder && navigator.mediaDevices?.getUserMedia);
|
||||
};
|
||||
|
||||
export const getVoiceUnavailableErrorKey = (): AudioTranscriptionErrorKey | null => {
|
||||
if (!isSecureContextForMic()) return 'chat.voiceRequiresHttps';
|
||||
if (!canUseMediaRecorder()) return 'chat.voiceNotSupported';
|
||||
return null;
|
||||
};
|
||||
|
||||
const pickMimeType = (): string => {
|
||||
const candidates = [
|
||||
'audio/webm;codecs=opus',
|
||||
'audio/webm',
|
||||
'audio/mp4',
|
||||
'audio/ogg;codecs=opus',
|
||||
];
|
||||
for (const type of candidates) {
|
||||
if (MediaRecorder.isTypeSupported(type)) return type;
|
||||
}
|
||||
return '';
|
||||
};
|
||||
|
||||
export function useAudioTranscription(options: {
|
||||
onResult: (text: string) => void;
|
||||
onError: (key: AudioTranscriptionErrorKey) => void;
|
||||
}) {
|
||||
const isRecording = ref(false);
|
||||
const isTranscribing = ref(false);
|
||||
const isSupported = computed(() => getVoiceUnavailableErrorKey() === null);
|
||||
const isBusy = computed(() => isRecording.value || isTranscribing.value);
|
||||
|
||||
let mediaStream: MediaStream | null = null;
|
||||
let mediaRecorder: MediaRecorder | null = null;
|
||||
let chunks: Blob[] = [];
|
||||
let baseText = '';
|
||||
let skipTranscription = false;
|
||||
|
||||
const cleanupStream = () => {
|
||||
if (mediaStream) {
|
||||
mediaStream.getTracks().forEach((track) => track.stop());
|
||||
mediaStream = null;
|
||||
}
|
||||
mediaRecorder = null;
|
||||
chunks = [];
|
||||
};
|
||||
|
||||
const stopRecording = () => {
|
||||
if (mediaRecorder && mediaRecorder.state !== 'inactive') {
|
||||
mediaRecorder.stop();
|
||||
return;
|
||||
}
|
||||
isRecording.value = false;
|
||||
cleanupStream();
|
||||
};
|
||||
|
||||
const transcribeBlob = async (blob: Blob, mimeType: string) => {
|
||||
if (blob.size < 800) {
|
||||
options.onError('chat.voiceRecordTooShort');
|
||||
return;
|
||||
}
|
||||
|
||||
isTranscribing.value = true;
|
||||
try {
|
||||
const ext = mimeType.includes('mp4') ? 'm4a' : 'webm';
|
||||
const formData = new FormData();
|
||||
formData.append('audio', blob, `recording.${ext}`);
|
||||
|
||||
const response = await fetch('/api/speech/transcribe', {
|
||||
method: 'POST',
|
||||
headers: { ...getAuthHeaders() },
|
||||
body: formData,
|
||||
});
|
||||
|
||||
const payload = await response.json().catch(() => ({}));
|
||||
if (!response.ok) {
|
||||
const errMsg = payload?.error?.message || payload?.message || `Request failed (${response.status})`;
|
||||
throw new Error(errMsg);
|
||||
}
|
||||
|
||||
const text = String(payload.text || '').trim();
|
||||
if (!text) {
|
||||
options.onError('chat.voiceRecordTooShort');
|
||||
return;
|
||||
}
|
||||
|
||||
const prefix = baseText.trim();
|
||||
options.onResult(prefix ? `${prefix} ${text}` : text);
|
||||
} catch {
|
||||
options.onError('chat.voiceTranscriptionFailed');
|
||||
} finally {
|
||||
isTranscribing.value = false;
|
||||
}
|
||||
};
|
||||
|
||||
const startRecording = async (existingText = '') => {
|
||||
if (isBusy.value) return;
|
||||
|
||||
const unavailable = getVoiceUnavailableErrorKey();
|
||||
if (unavailable) {
|
||||
options.onError(unavailable);
|
||||
return;
|
||||
}
|
||||
|
||||
baseText = existingText;
|
||||
|
||||
try {
|
||||
mediaStream = await navigator.mediaDevices.getUserMedia({ audio: true });
|
||||
} catch (err) {
|
||||
const denied = err instanceof DOMException && (
|
||||
err.name === 'NotAllowedError' || err.name === 'PermissionDeniedError'
|
||||
);
|
||||
options.onError(denied ? 'chat.voicePermissionDenied' : 'chat.voiceTranscriptionFailed');
|
||||
return;
|
||||
}
|
||||
|
||||
chunks = [];
|
||||
const mimeType = pickMimeType();
|
||||
try {
|
||||
mediaRecorder = mimeType
|
||||
? new MediaRecorder(mediaStream, { mimeType })
|
||||
: new MediaRecorder(mediaStream);
|
||||
} catch {
|
||||
cleanupStream();
|
||||
options.onError('chat.voiceNotSupported');
|
||||
return;
|
||||
}
|
||||
|
||||
mediaRecorder.ondataavailable = (event) => {
|
||||
if (event.data.size > 0) chunks.push(event.data);
|
||||
};
|
||||
|
||||
mediaRecorder.onstop = async () => {
|
||||
isRecording.value = false;
|
||||
const type = mediaRecorder?.mimeType || mimeType || 'audio/webm';
|
||||
const blob = new Blob(chunks, { type });
|
||||
const shouldSkip = skipTranscription;
|
||||
skipTranscription = false;
|
||||
cleanupStream();
|
||||
if (shouldSkip) return;
|
||||
await transcribeBlob(blob, type);
|
||||
};
|
||||
|
||||
mediaRecorder.onerror = () => {
|
||||
isRecording.value = false;
|
||||
cleanupStream();
|
||||
options.onError('chat.voiceTranscriptionFailed');
|
||||
};
|
||||
|
||||
mediaRecorder.start();
|
||||
isRecording.value = true;
|
||||
};
|
||||
|
||||
const toggle = (existingText = '') => {
|
||||
if (isTranscribing.value) return;
|
||||
if (isRecording.value) {
|
||||
stopRecording();
|
||||
return;
|
||||
}
|
||||
void startRecording(existingText);
|
||||
};
|
||||
|
||||
const cancel = () => {
|
||||
skipTranscription = true;
|
||||
if (mediaRecorder && mediaRecorder.state !== 'inactive') {
|
||||
mediaRecorder.stop();
|
||||
} else {
|
||||
cleanupStream();
|
||||
}
|
||||
isRecording.value = false;
|
||||
isTranscribing.value = false;
|
||||
};
|
||||
|
||||
onBeforeUnmount(cancel);
|
||||
|
||||
return {
|
||||
isRecording,
|
||||
isTranscribing,
|
||||
isSupported,
|
||||
isBusy,
|
||||
startRecording,
|
||||
stopRecording,
|
||||
toggle,
|
||||
cancel,
|
||||
};
|
||||
}
|
||||
@@ -0,0 +1,8 @@
|
||||
/**
|
||||
* shared/composables/useChat.ts
|
||||
* 兼容转发至 chat feature 的 useChat。
|
||||
*/
|
||||
/**
|
||||
* @deprecated 请使用 @/features/chat/composables/useChat
|
||||
*/
|
||||
export { useChat } from '@/features/chat/composables/useChat';
|
||||
@@ -0,0 +1,62 @@
|
||||
/**
|
||||
* shared/composables/useGlobalMessageDialog.ts
|
||||
* 全局消息弹窗单例状态与展示控制。
|
||||
*/
|
||||
import { readonly, ref } from 'vue';
|
||||
|
||||
export type MessageLevel = 'success' | 'info' | 'warning' | 'error';
|
||||
|
||||
// 全局单例状态:整个应用共享一套消息弹框。
|
||||
const visible = ref(false);
|
||||
const level = ref<MessageLevel>('info');
|
||||
const title = ref('');
|
||||
const message = ref('');
|
||||
|
||||
const MAX_DIALOG_MESSAGE_LENGTH = 240;
|
||||
|
||||
const normalizeMessage = (raw: string) => {
|
||||
if (!raw) return '';
|
||||
return raw
|
||||
.replace(/\s+/g, ' ')
|
||||
.replace(/<[^>]*>/g, '')
|
||||
.trim();
|
||||
};
|
||||
|
||||
const formatMessageForDialog = (level: MessageLevel, raw: string) => {
|
||||
const normalized = normalizeMessage(raw);
|
||||
if (!normalized) return '';
|
||||
|
||||
// Error messages often include long backend stack/driver details.
|
||||
if (level === 'error' && normalized.length > MAX_DIALOG_MESSAGE_LENGTH) {
|
||||
return `${normalized.slice(0, MAX_DIALOG_MESSAGE_LENGTH)}...`;
|
||||
}
|
||||
return normalized;
|
||||
};
|
||||
|
||||
export const useGlobalMessageDialog = () => {
|
||||
const showMessageDialog = (
|
||||
nextLevel: MessageLevel,
|
||||
nextMessage: string,
|
||||
nextTitle = ''
|
||||
) => {
|
||||
level.value = nextLevel;
|
||||
title.value = nextTitle;
|
||||
message.value = formatMessageForDialog(nextLevel, nextMessage);
|
||||
visible.value = true;
|
||||
};
|
||||
|
||||
const closeMessageDialog = () => {
|
||||
visible.value = false;
|
||||
title.value = '';
|
||||
message.value = '';
|
||||
};
|
||||
|
||||
return {
|
||||
messageDialogVisible: visible,
|
||||
messageDialogLevel: readonly(level),
|
||||
messageDialogTitle: readonly(title),
|
||||
messageDialogContent: readonly(message),
|
||||
showMessageDialog,
|
||||
closeMessageDialog,
|
||||
};
|
||||
};
|
||||
@@ -0,0 +1,36 @@
|
||||
/**
|
||||
* shared/composables/useIsMobile.ts
|
||||
* 检测竖屏/横屏,供移动端布局切换。
|
||||
*/
|
||||
import { ref, onMounted, onBeforeUnmount, readonly } from 'vue';
|
||||
|
||||
const isMobile = ref(false);
|
||||
|
||||
let listeners = 0;
|
||||
|
||||
const update = () => {
|
||||
isMobile.value = window.innerHeight > window.innerWidth;
|
||||
};
|
||||
|
||||
const startListening = () => {
|
||||
if (listeners === 0) {
|
||||
update();
|
||||
window.addEventListener('resize', update);
|
||||
}
|
||||
listeners++;
|
||||
};
|
||||
|
||||
const stopListening = () => {
|
||||
listeners--;
|
||||
if (listeners <= 0) {
|
||||
listeners = 0;
|
||||
window.removeEventListener('resize', update);
|
||||
}
|
||||
};
|
||||
|
||||
export function useIsMobile() {
|
||||
onMounted(() => startListening());
|
||||
onBeforeUnmount(() => stopListening());
|
||||
|
||||
return { isMobile: readonly(isMobile) };
|
||||
}
|
||||
@@ -0,0 +1,39 @@
|
||||
/**
|
||||
* shared/composables/useMessage.ts
|
||||
* 业务层消息助手,封装全局 LevelMessageDialog 调用。
|
||||
*/
|
||||
import { useGlobalMessageDialog } from './useGlobalMessageDialog';
|
||||
|
||||
type MessageTitle = string | undefined;
|
||||
|
||||
/**
|
||||
* 业务层消息助手:
|
||||
* - 统一复用全局 LevelMessageDialog
|
||||
* - 提供更短的方法名,减少重复传 level 字符串
|
||||
*/
|
||||
export const useMessage = () => {
|
||||
const { showMessageDialog } = useGlobalMessageDialog();
|
||||
|
||||
const info = (message: string, title?: MessageTitle) =>
|
||||
showMessageDialog('info', message, title);
|
||||
|
||||
const success = (message: string, title?: MessageTitle) =>
|
||||
showMessageDialog('success', message, title);
|
||||
|
||||
const warning = (message: string, title?: MessageTitle) =>
|
||||
showMessageDialog('warning', message, title);
|
||||
|
||||
// 兼容常见缩写调用:msg.warn(...)
|
||||
const warn = warning;
|
||||
|
||||
const error = (message: string, title?: MessageTitle) =>
|
||||
showMessageDialog('error', message, title);
|
||||
|
||||
return {
|
||||
info,
|
||||
success,
|
||||
warning,
|
||||
warn,
|
||||
error,
|
||||
};
|
||||
};
|
||||
@@ -0,0 +1,48 @@
|
||||
/**
|
||||
* shared/composables/useReportLayoutStorage.ts
|
||||
* 报表页面布局偏好 localStorage 持久化。
|
||||
*/
|
||||
/**
|
||||
* useReportLayoutStorage.ts
|
||||
* 用途:为报表页面提供统一的布局偏好持久化能力(按用户 + 表名隔离)
|
||||
*/
|
||||
|
||||
const getCurrentAuthUser = () => {
|
||||
let stored = localStorage.getItem('hxops_user');
|
||||
if (!stored) stored = sessionStorage.getItem('hxops_user');
|
||||
if (!stored) return null;
|
||||
try {
|
||||
const data = JSON.parse(stored);
|
||||
return data.user || data;
|
||||
} catch {
|
||||
return null;
|
||||
}
|
||||
};
|
||||
|
||||
const getCurrentIdentity = () => {
|
||||
const user = getCurrentAuthUser();
|
||||
return user?.id ? `id_${user.id}` : `u_${user?.username || 'guest'}`;
|
||||
};
|
||||
|
||||
const getReportLayoutStorageKey = (table: string) => {
|
||||
return `hxops_report_layout_v2_${getCurrentIdentity()}_${table}`;
|
||||
};
|
||||
|
||||
export const loadReportLayoutPref = <T = any>(table: string): T | null => {
|
||||
try {
|
||||
const raw = localStorage.getItem(getReportLayoutStorageKey(table));
|
||||
if (!raw) return null;
|
||||
return JSON.parse(raw) as T;
|
||||
} catch {
|
||||
return null;
|
||||
}
|
||||
};
|
||||
|
||||
export const saveReportLayoutPref = (table: string, payload: unknown) => {
|
||||
try {
|
||||
localStorage.setItem(getReportLayoutStorageKey(table), JSON.stringify(payload));
|
||||
} catch {
|
||||
// Ignore storage write failure to avoid blocking core report flow.
|
||||
}
|
||||
};
|
||||
|
||||
@@ -0,0 +1,93 @@
|
||||
/**
|
||||
* shared/composables/useTheme.ts
|
||||
* 主题 preference 与 dark/light 切换(全局单例)。
|
||||
*/
|
||||
import { computed, ref } from 'vue';
|
||||
|
||||
export type ThemePreference = 'light' | 'dark' | 'system';
|
||||
export type AppliedTheme = 'light' | 'dark';
|
||||
|
||||
const THEME_KEY = 'hxops_theme_preference';
|
||||
const validThemePrefs: ThemePreference[] = ['light', 'dark', 'system'];
|
||||
|
||||
const themePreference = ref<ThemePreference>('system');
|
||||
const systemPrefersDark = ref(false);
|
||||
|
||||
let initialized = false;
|
||||
let mediaListenerCleanup: (() => void) | null = null;
|
||||
|
||||
const appliedTheme = computed<AppliedTheme>(() => {
|
||||
if (themePreference.value === 'system') {
|
||||
return systemPrefersDark.value ? 'dark' : 'light';
|
||||
}
|
||||
return themePreference.value;
|
||||
});
|
||||
|
||||
const applyTheme = () => {
|
||||
const root = document.documentElement;
|
||||
const isDark = appliedTheme.value === 'dark';
|
||||
root.classList.toggle('dark', isDark);
|
||||
root.setAttribute('data-theme', appliedTheme.value);
|
||||
};
|
||||
|
||||
const parseTheme = (value: string | null | undefined): ThemePreference | null => {
|
||||
if (!value) return null;
|
||||
return validThemePrefs.includes(value as ThemePreference) ? (value as ThemePreference) : null;
|
||||
};
|
||||
|
||||
const setThemePreference = (value: ThemePreference, persist = true) => {
|
||||
themePreference.value = value;
|
||||
if (persist) {
|
||||
localStorage.setItem(THEME_KEY, value);
|
||||
}
|
||||
applyTheme();
|
||||
};
|
||||
|
||||
const toggleLightDark = () => {
|
||||
setThemePreference(appliedTheme.value === 'dark' ? 'light' : 'dark');
|
||||
};
|
||||
|
||||
const initTheme = () => {
|
||||
if (initialized) {
|
||||
applyTheme();
|
||||
return;
|
||||
}
|
||||
|
||||
initialized = true;
|
||||
|
||||
const media = window.matchMedia('(prefers-color-scheme: dark)');
|
||||
systemPrefersDark.value = media.matches;
|
||||
|
||||
const onMediaChange = (event: MediaQueryListEvent) => {
|
||||
systemPrefersDark.value = event.matches;
|
||||
if (themePreference.value === 'system') {
|
||||
applyTheme();
|
||||
}
|
||||
};
|
||||
|
||||
media.addEventListener('change', onMediaChange);
|
||||
mediaListenerCleanup = () => media.removeEventListener('change', onMediaChange);
|
||||
|
||||
const stored = parseTheme(localStorage.getItem(THEME_KEY));
|
||||
if (stored) {
|
||||
themePreference.value = stored;
|
||||
}
|
||||
applyTheme();
|
||||
};
|
||||
|
||||
const cleanupTheme = () => {
|
||||
mediaListenerCleanup?.();
|
||||
mediaListenerCleanup = null;
|
||||
initialized = false;
|
||||
};
|
||||
|
||||
export function useTheme() {
|
||||
return {
|
||||
themePreference,
|
||||
appliedTheme,
|
||||
initTheme,
|
||||
cleanupTheme,
|
||||
setThemePreference,
|
||||
toggleLightDark,
|
||||
};
|
||||
}
|
||||
Reference in new issue
Block a user