fix: 改善移动端布局并完善自动导入配置

处理软键盘弹出时的视口高度,并补充布局测试。
统一 Vite 和 Vitest 的自动导入,整理 Vue 脚本排版。
更新前端依赖、类型检查和格式化配置。
This commit is contained in:
fonghehe 2026-10-22 16:34:59 +08:00
parent a829261c35
commit d1780c1f1b
42 changed files with 2278 additions and 1429 deletions

View File

@ -119,6 +119,7 @@
"sortablejs",
"stylelint",
"tailwindcss",
"tanstack",
"tdesign",
"tinymce",
"unocss",

View File

@ -18,12 +18,13 @@ function createUiResolvers(
export const ConfigAutoImportPlugin = (
framework: ViteEnv['VITE_UI_FRAMEWORK'],
writeDeclarations = true,
) => {
return AutoImport({
dts: 'types/auto-imports.d.ts',
dts: writeDeclarations && 'types/auto-imports.d.ts',
imports: ['vue', 'pinia', 'vue-router'],
eslintrc: {
enabled: true,
enabled: writeDeclarations,
},
resolvers: createUiResolvers(framework),
});

View File

@ -20,12 +20,13 @@ function createUiResolvers(
export const ConfigAutoComponentsPlugin = (
framework: ViteEnv['VITE_UI_FRAMEWORK'],
writeDeclarations = true,
) => {
return Components({
dirs: ['src/components'],
extensions: ['vue', 'md'],
deep: true,
dts: 'types/components.d.ts',
dts: writeDeclarations && 'types/components.d.ts',
directoryAsNamespace: false,
globalNamespaces: [],
directives: true,

View File

@ -195,6 +195,7 @@ test('delivery workspace supports create, view, edit, filter and delete', async
await page.getByLabel('用户名').fill('workspace-tester');
await page.getByLabel('密码').fill('secret');
await page.getByRole('button', { name: '登录', exact: true }).click();
await expect(page).toHaveURL(/\/member$/);
await page.goto('/examples/workspace');
const projectName = `Playwright delivery ${Date.now()}`;

View File

@ -63,6 +63,33 @@ test('chat composer remains visible when the visual viewport shrinks', async ({
);
});
test('the app shell follows the visual viewport without dynamic viewport units', async ({
page,
}) => {
await page.addInitScript(() => {
const supports = CSS.supports.bind(CSS);
CSS.supports = (property: string, value?: string) => {
if (property === 'height' && value === '1dvh') return false;
return value === undefined
? supports(property)
: supports(property, value);
};
});
await page.goto('/home');
const shell = page.locator('.app-shell');
await expect(shell).toBeVisible();
await page.evaluate(() => {
const viewport = window.visualViewport;
if (!viewport) throw new Error('Visual viewport is required');
Object.defineProperty(viewport, 'height', { value: 450 });
viewport.dispatchEvent(new Event('resize'));
});
await expect(shell).toHaveCSS('height', '450px');
await expect(page.getByRole('navigation')).toBeInViewport();
});
test('layout remains restrained on mobile, tablet and desktop', async ({
page,
}) => {
@ -147,6 +174,7 @@ test('mobile routes use consistent page gutters without horizontal overflow', as
await page.getByLabel('用户名').fill('layout-tester');
await page.getByLabel('密码').fill('secret');
await page.getByRole('button', { name: '登录', exact: true }).click();
await expect(page).toHaveURL(/\/member$/);
const routes = [
{ path: '/home', gutter: 16 },
{ path: '/shop', gutter: 16 },

View File

@ -5,8 +5,16 @@ import { defineConfig } from 'oxfmt';
* 详见:https://oxc.rs/docs/guide/usage/formatter/config-file-reference.html
*/
export default defineConfig({
// Vite plugins own these declarations; formatting them is overwritten on build.
ignorePatterns: ['types/auto-imports.d.ts', 'types/components.d.ts'],
// Keep generated output and pnpm's lockfile under their respective tools.
ignorePatterns: [
'coverage',
'dist',
'playwright-report',
'test-results',
'pnpm-lock.yaml',
'types/auto-imports.d.ts',
'types/components.d.ts',
],
/**
* 单行长度,适配 prettier 的 80
* Default:100

View File

@ -8,6 +8,7 @@ import { defineConfig } from 'oxlint';
* + unicorn + import + vue + vitest + node 等插件。
*/
export default defineConfig({
options: { typeAware: true },
// —— plugins:oxlint 支持的插件,将默认开启的也显式配置 ——
// type: eslint | react | unicorn | typescript | oxc |
// import | jsdoc | jest | vitest | jsx-a11y | nextjs |
@ -205,12 +206,12 @@ export default defineConfig({
'typescript/triple-slash-reference': 'error',
'typescript/unified-signatures': 'error',
// typescript 类型感知规则:oxlint 暂不支持,关闭
'typescript/await-thenable': 'off',
// 先启用能发现异步控制流错误的类型感知规则。
'typescript/await-thenable': 'error',
'typescript/consistent-return': 'off',
'typescript/no-base-to-string': 'off',
'typescript/no-duplicate-type-constituents': 'off',
'typescript/no-floating-promises': 'off',
'typescript/no-floating-promises': 'error',
'typescript/no-misused-spread': 'off',
'typescript/no-redundant-type-constituents': 'off',
'typescript/no-unnecessary-boolean-literal-compare': 'off',

View File

@ -30,43 +30,43 @@
},
"dependencies": {
"@nutui/nutui": "^4.3.13",
"@tanstack/vue-query": "^5.102.8",
"@tanstack/vue-query": "^5.107.1",
"@varlet/ui": "^3.20.6",
"axios": "1.20.0",
"dompurify": "^3.4.14",
"markdown-it": "^15.0.0",
"dompurify": "^3.4.17",
"markdown-it": "^15.0.3",
"pinia": "^3.0.4",
"pinia-plugin-persistedstate": "^4.7.1",
"vant": "^4.10.0",
"vue": "^3.5.42",
"vue-i18n": "^11.4.10",
"vant": "^4.10.2",
"vue": "^3.5.45",
"vue-i18n": "^11.4.18",
"vue-router": "^4.6.4"
},
"devDependencies": {
"@commitlint/cli": "^20.5.2",
"@commitlint/config-conventional": "^20.5.0",
"@eslint-community/eslint-plugin-eslint-comments": "^4.7.2",
"@commitlint/cli": "^20.5.3",
"@commitlint/config-conventional": "^20.5.3",
"@eslint-community/eslint-plugin-eslint-comments": "^4.8.1",
"@nutui/auto-import-resolver": "^1.0.0",
"@playwright/test": "^1.62.1",
"@playwright/test": "^1.65.0",
"@stylistic/stylelint-plugin": "^4.0.1",
"@tsconfig/node22": "^22.0.5",
"@types/jsdom": "^21.1.7",
"@types/markdown-it": "^14.2.0",
"@types/node": "^24.12.2",
"@types/node": "^24.19.2",
"@vant/auto-import-resolver": "^1.3.0",
"@varlet/import-resolver": "^3.20.6",
"@varlet/import-resolver": "^3.20.10",
"@vitejs/plugin-basic-ssl": "^2.3.0",
"@vitejs/plugin-vue": "^6.0.8",
"@vitejs/plugin-vue": "^6.0.10",
"@vitejs/plugin-vue-jsx": "^5.1.6",
"@vitest/coverage-v8": "^4.1.11",
"@vue/test-utils": "^2.5.0",
"@vitest/coverage-v8": "^4.1.12",
"@vue/test-utils": "^2.5.1",
"@vue/tsconfig": "^0.8.1",
"@zhaojjiang/vite-plugin-eruda": "^0.0.5",
"autoprefixer": "^10.5.4",
"cz-git": "^1.13.0",
"czg": "^1.13.0",
"autoprefixer": "^10.6.2",
"cz-git": "^1.14.0",
"czg": "^1.14.0",
"eruda": "^3.4.1",
"esbuild": "^0.28.0",
"esbuild": "0.28.2",
"eslint-plugin-command": "^3.5.3",
"git-cz": "^4.9.0",
"husky": "9.1.7",
@ -74,14 +74,16 @@
"lint-staged": "16.2.7",
"openapi-typescript": "^7.13.0",
"oxfmt": "^0.61.0",
"oxlint": "^1.76.0",
"oxlint": "^1.92.0",
"oxlint-tsgolint": "7.0.2005",
"postcss": "8.5.26",
"postcss-html": "1.8.1",
"postcss-scss": "^4.0.9",
"rollup-plugin-visualizer": "^6.0.11",
"sharp": "^0.35.4",
"sass": "1.93.2",
"sharp": "^0.35.5",
"stylelint": "^16.26.1",
"stylelint-config-recess-order": "^7.7.0",
"stylelint-config-recess-order": "^7.10.0",
"stylelint-config-recommended": "^17.0.0",
"stylelint-config-recommended-scss": "^16.0.0",
"stylelint-config-recommended-vue": "^1.5.0",
@ -92,15 +94,15 @@
"typescript": "5.9.3",
"unplugin-auto-import": "^21.1.0",
"unplugin-vue-components": "^32.1.0",
"vite": "^8.2.2",
"vite": "^8.3.6",
"vite-plugin-compression": "^0.5.1",
"vite-plugin-image-optimizer": "^2.0.3",
"vite-plugin-mock": "^3.0.2",
"vite-plugin-progress": "^0.0.7",
"vite-plugin-pwa": "^1.2.0",
"vite-plugin-svg-icons": "^2.0.1",
"vitest": "^4.1.11",
"vue-tsc": "^3.3.11"
"vitest": "^4.1.12",
"vue-tsc": "^3.3.14"
},
"engines": {
"node": ">=22.12.0",

3323
pnpm-lock.yaml generated

File diff suppressed because it is too large Load Diff

View File

@ -1,11 +1,11 @@
<script setup lang="ts">
import { ref, watch } from 'vue';
import { useQueryClient } from '@tanstack/vue-query';
import { useUserStore } from '@/store/modules/user';
const user = useUserStore();
const queryClient = useQueryClient();
const sessionVersion = ref(0);
watch(
() => user.token,
() => {

View File

@ -34,7 +34,6 @@
</template>
<script setup lang="ts">
import { nextTick, ref, useTemplateRef } from 'vue';
import { useI18n } from 'vue-i18n';
const props = defineProps<{ disabled?: boolean; streaming?: boolean }>();
const emit = defineEmits<{ send: [content: string]; stop: [] }>();
@ -42,12 +41,14 @@ const { t } = useI18n();
const input = ref('');
const composing = ref(false);
const textarea = useTemplateRef<HTMLTextAreaElement>('textarea');
const resize = () => {
const element = textarea.value;
if (!element) return;
element.style.height = 'auto';
element.style.height = `${Math.min(element.scrollHeight, 220)}px`;
};
const submit = () => {
if (props.disabled || props.streaming || composing.value) return;
const content = input.value.trim();
@ -56,6 +57,7 @@ const submit = () => {
input.value = '';
void nextTick(resize);
};
const handleKeydown = (event: KeyboardEvent) => {
if (
event.key === 'Enter' &&

View File

@ -4,11 +4,11 @@
</template>
<script setup lang="ts">
import { ref, watch } from 'vue';
import { renderSafeMarkdown } from '@/utils/markdown';
const props = defineProps<{ source: string }>();
const html = ref('');
let renderVersion = 0;
watch(
() => props.source,
async (source) => {

View File

@ -27,7 +27,6 @@
</template>
<script setup lang="ts">
import { computed, ref } from 'vue';
import { useI18n } from 'vue-i18n';
import type { LoginParams } from '@/api/modules/auth';
@ -37,6 +36,7 @@ const { t } = useI18n();
const name = ref('');
const password = ref('');
const canSubmit = computed(() => Boolean(name.value && password.value));
const submit = () => {
if (canSubmit.value && !props.loading)
emit('submit', { name: name.value, password: password.value });

View File

@ -11,15 +11,16 @@
</template>
<script setup lang="ts">
import { onErrorCaptured, ref } from 'vue';
import { useI18n } from 'vue-i18n';
const { t } = useI18n();
const error = ref<Error | null>(null);
onErrorCaptured((captured) => {
error.value = captured;
return false;
});
const recover = () => window.location.reload();
</script>

View File

@ -6,7 +6,6 @@
</template>
<script setup lang="ts">
import { computed } from 'vue';
import type { SvgIconName } from '@/types/icon';
const props = defineProps<{ name: SvgIconName; title?: string }>();

View File

@ -1,7 +1,5 @@
<script setup lang="ts">
import { computed, onScopeDispose, ref, useId, watch } from 'vue';
import { useMutation, useQuery, useQueryClient } from '@tanstack/vue-query';
import { RouterLink } from 'vue-router';
import { useI18n } from 'vue-i18n';
import {
getProductFavorite,
@ -13,9 +11,11 @@ const scope = useId();
const generation = ref(0);
const client = useQueryClient();
let disposed = false;
onScopeDispose(() => {
disposed = true;
});
const key = computed(() => [
'favorite',
scope,
@ -48,6 +48,7 @@ const mutation = useMutation({
client.setQueryData(input.key, data);
},
});
watch(
() => props.session,
() => {
@ -56,10 +57,12 @@ watch(
},
{ flush: 'sync' },
);
watch(
() => props.productId,
() => mutation.reset(),
);
function toggle() {
if (
!favorite.data.value ||

View File

@ -41,7 +41,6 @@
</template>
<script setup lang="ts">
import { computed } from 'vue';
import { useI18n } from 'vue-i18n';
import type { Product } from '@/api/modules/products';
import {

View File

@ -175,7 +175,6 @@
</template>
<script setup lang="ts">
import { reactive, ref, watch } from 'vue';
import { useI18n } from 'vue-i18n';
import type {
LocalizedText,
@ -214,11 +213,13 @@ const locales = localeTabs.map((item) => item.value);
const categories = ['digital', 'lifestyle', 'home', 'outdoor'] as const;
const activeLocale = ref<LocaleKey>('zh-CN');
const validationError = ref('');
const emptyLocalized = (): LocalizedText => ({
'zh-CN': '',
'en-US': '',
'ja-JP': '',
});
const blankForm = (): EditorForm => ({
sku: '',
name: emptyLocalized(),
@ -235,6 +236,7 @@ const blankForm = (): EditorForm => ({
status: 'draft',
featured: false,
});
const form = reactive<EditorForm>(blankForm());
watch(

View File

@ -0,0 +1,26 @@
import { onBeforeUnmount, onMounted, ref } from 'vue';
export function useLayoutViewportHeight() {
const height = ref<string>();
let viewport: VisualViewport | null | undefined;
const update = () => {
height.value = `${Math.round(viewport?.height ?? window.innerHeight)}px`;
};
onMounted(() => {
if (globalThis.CSS?.supports?.('height', '1dvh')) return;
viewport = window.visualViewport;
update();
window.addEventListener('resize', update);
viewport?.addEventListener('resize', update);
});
onBeforeUnmount(() => {
if (height.value === undefined) return;
window.removeEventListener('resize', update);
viewport?.removeEventListener('resize', update);
});
return height;
}

View File

@ -1,5 +1,5 @@
<template>
<div class="app-shell">
<div class="app-shell" :style="{ height: layoutHeight }">
<header
v-if="!route.meta.hideHeader"
class="top-bar"
@ -89,9 +89,8 @@
</template>
<script setup lang="ts">
import { computed } from 'vue';
import { useI18n } from 'vue-i18n';
import { useRoute, useRouter } from 'vue-router';
import { useLayoutViewportHeight } from '@/composables/useLayoutViewportHeight';
import { useNetworkStatus } from '@/composables/useNetworkStatus';
import { setLang } from '@/locales';
import type { SupportedLocale } from '@/locales';
@ -101,6 +100,7 @@ const route = useRoute();
const router = useRouter();
const { locale, t } = useI18n();
const { isOnline } = useNetworkStatus();
const layoutHeight = useLayoutViewportHeight();
const rootNames = new Set(['home', 'shop', 'examples', 'member']);
const isRootPage = computed(() => rootNames.has(String(route.name)));
const pageTitle = computed(() =>
@ -119,6 +119,7 @@ const languageOptions: Array<{ value: SupportedLocale; label: string }> = [
{ value: 'en-US', label: 'common.language.en' },
{ value: 'ja-JP', label: 'common.language.ja' },
];
const changeLanguage = (event: Event) =>
void setLang((event.target as HTMLSelectElement).value);
</script>

View File

@ -1,18 +1,6 @@
<script setup lang="ts">
import {
computed,
nextTick,
onScopeDispose,
shallowRef,
useTemplateRef,
watch,
} from 'vue';
import ChatComposer from '@/components/ai/ChatComposer.vue';
import SafeMarkdown from '@/components/ai/SafeMarkdown.vue';
import SvgIcon from '@/components/common/SvgIcon.vue';
import { useQuery } from '@tanstack/vue-query';
import { getChatSuggestions } from '@/api/modules/ai';
import { useRouter } from 'vue-router';
import { useI18n } from 'vue-i18n';
import { useStreamingChat } from '@/composables/useStreamingChat';
import { useVisualViewport } from '@/composables/useVisualViewport';
@ -28,18 +16,22 @@ const copiedId = shallowRef('');
const copyNotice = shallowRef('');
let copyVersion = 0;
let copyTimer: ReturnType<typeof setTimeout> | undefined;
const resetCopy = () => {
copyVersion += 1;
clearTimeout(copyTimer);
copiedId.value = '';
copyNotice.value = '';
};
onScopeDispose(resetCopy);
const clearChat = () => {
resetCopy();
showScrollButton.value = false;
clear();
};
const suggestionsQuery = useQuery({
queryKey: computed(() => ['ai-suggestions', locale.value]),
queryFn: ({ signal }) =>
@ -59,6 +51,7 @@ const prompts = computed(() =>
const pageStyle = computed(() => ({
height: viewportHeight.value ? `${viewportHeight.value}px` : '100dvh',
}));
const isNearBottom = () => {
const element = messageList.value;
return (
@ -66,6 +59,7 @@ const isNearBottom = () => {
element.scrollHeight - element.scrollTop - element.clientHeight < 160
);
};
const scrollToBottom = (behavior: ScrollBehavior = 'auto') =>
void nextTick(() =>
messageList.value?.scrollTo({
@ -73,13 +67,16 @@ const scrollToBottom = (behavior: ScrollBehavior = 'auto') =>
behavior,
}),
);
const updateScrollState = () => {
showScrollButton.value = !isNearBottom();
};
const send = (content: string) => {
void sendMessage(content);
scrollToBottom();
};
const copyMessage = async (id: string, content: string) => {
resetCopy();
const version = copyVersion;
@ -93,6 +90,7 @@ const copyMessage = async (id: string, content: string) => {
}
copyTimer = setTimeout(resetCopy, 1200);
};
watch(
[
() => messages.value.length,

View File

@ -24,7 +24,6 @@
</template>
<script setup lang="ts">
import { computed } from 'vue';
import { useI18n } from 'vue-i18n';
import type { SvgIconName } from '@/types/icon';
defineOptions({ name: 'ExamplesPage' });

View File

@ -54,7 +54,6 @@
</template>
<script setup lang="ts">
import { computed, ref } from 'vue';
import { useI18n } from 'vue-i18n';
import { useNetworkStatus } from '@/composables/useNetworkStatus';
@ -62,6 +61,7 @@ const { t } = useI18n();
const { isOnline } = useNetworkStatus();
const feedback = ref('');
const canShare = computed(() => typeof navigator.share === 'function');
const copyText = async () => {
feedback.value = '';
try {
@ -71,6 +71,7 @@ const copyText = async () => {
feedback.value = t('common.mobile.copyFailed');
}
};
const sharePage = async () => {
if (!canShare.value) return;
feedback.value = '';

View File

@ -210,7 +210,6 @@
</template>
<script setup lang="ts">
import { computed, reactive, ref } from 'vue';
import { useMutation, useQuery, useQueryClient } from '@tanstack/vue-query';
import { useI18n } from 'vue-i18n';
import {
@ -253,12 +252,15 @@ const dialogTitle = computed(() =>
? t('common.workspace.createTitle')
: (selectedProject.value?.name ?? t('common.workspace.title')),
);
const refresh = () => queryClient.invalidateQueries({ queryKey: ['projects'] });
const showError = (error: unknown) => {
mutationError.value = isApiError(error)
? error.message
: t('common.workspace.unknownError');
};
const saveMutation = useMutation({
mutationFn: ({
id,
@ -278,6 +280,7 @@ const deleteMutation = useMutation({
onSuccess: refresh,
onError: showError,
});
const resetForm = (project?: Project) =>
Object.assign(
form,
@ -289,27 +292,32 @@ const resetForm = (project?: Project) =>
}
: { name: '', description: '', status: 'active' },
);
const openCreate = () => {
selectedProject.value = null;
mutationError.value = '';
resetForm();
dialogMode.value = 'create';
};
const openDetails = (project: Project) => {
selectedProject.value = project;
mutationError.value = '';
dialogMode.value = 'view';
};
const openEdit = (project: Project) => {
selectedProject.value = project;
mutationError.value = '';
resetForm(project);
dialogMode.value = 'edit';
};
const closeDialog = () => {
dialogMode.value = null;
selectedProject.value = null;
};
const saveProject = () => {
mutationError.value = '';
saveMutation.mutate({
@ -321,6 +329,7 @@ const saveProject = () => {
},
});
};
const removeProject = (project: Project) => {
mutationError.value = '';
// 跨 UI 框架的简单删除确认,使用原生 confirm 避免引入框架耦合
@ -330,6 +339,7 @@ const removeProject = (project: Project) => {
)
deleteMutation.mutate(project.id);
};
const formatDate = (value: string) =>
new Intl.DateTimeFormat(locale.value, { dateStyle: 'medium' }).format(
new Date(value),

View File

@ -80,14 +80,6 @@
</template>
<script setup lang="ts">
import {
computed,
onBeforeUnmount,
onMounted,
onScopeDispose,
useTemplateRef,
watch,
} from 'vue';
import {
useInfiniteQuery,
useMutation,
@ -100,9 +92,11 @@ import type { Task } from '@/api/modules/examples';
const queryClient = useQueryClient();
let disposed = false;
onScopeDispose(() => {
disposed = true;
});
const { t } = useI18n();
const tasksQuery = useQuery({
queryKey: ['examples', 'tasks'],
@ -133,14 +127,18 @@ const feedTitleKeys = [
'architectureTitle',
] as const;
const feedCategoryKeys = ['performance', 'ai', 'architecture'] as const;
const getFeedTitle = (id: number) =>
t(`common.query.feedItems.${feedTitleKeys[(id - 1) % feedTitleKeys.length]}`);
const getFeedCategory = (id: number) =>
t(
`common.query.feedItems.${feedCategoryKeys[(id - 1) % feedCategoryKeys.length]}`,
);
const loadMoreTarget = useTemplateRef<HTMLButtonElement>('loadMoreTarget');
let observer: IntersectionObserver | undefined;
onMounted(() => {
observer = new IntersectionObserver(
([entry]) => {
@ -155,10 +153,12 @@ onMounted(() => {
);
if (loadMoreTarget.value) observer.observe(loadMoreTarget.value);
});
watch(loadMoreTarget, (target, previousTarget) => {
if (previousTarget) observer?.unobserve(previousTarget);
if (target) observer?.observe(target);
});
onBeforeUnmount(() => observer?.disconnect());
</script>

View File

@ -64,7 +64,6 @@
</template>
<script setup lang="ts">
import { computed, reactive, ref } from 'vue';
import { useI18n } from 'vue-i18n';
import { triggerRequestError } from '@/api/modules/requestExamples';
import type { RequestErrorScenario } from '@/api/modules/requestExamples';
@ -139,6 +138,7 @@ const scenarios = computed<
description: t('common.request.scenarios.timeoutDescription'),
},
]);
const runScenario = async (scenario: RequestErrorScenario) => {
pending.value = scenario;
results[scenario] = undefined;

View File

@ -80,6 +80,7 @@ const languageOptions: Array<{ value: SupportedLocale; label: string }> = [
{ value: 'en-US', label: 'common.language.en' },
{ value: 'ja-JP', label: 'common.language.ja' },
];
const changeLanguage = (event: Event) =>
void setLang((event.target as HTMLSelectElement).value);
</script>

View File

@ -14,8 +14,6 @@
</template>
<script setup lang="ts">
import { onScopeDispose, ref } from 'vue';
import { useRoute, useRouter } from 'vue-router';
import { useI18n } from 'vue-i18n';
import type { LoginParams } from '@/api/modules/auth';
import { useUserStore } from '@/store/modules/user';
@ -32,7 +30,9 @@ const loginDescriptionKey =
: 'common.login.realDescription';
const loading = ref(false);
const errorMessage = ref('');
onScopeDispose(() => userStore.cancelLogin());
const login = async (params: LoginParams) => {
if (loading.value) return;
loading.value = true;

View File

@ -46,10 +46,8 @@
</template>
<script setup lang="ts">
import { computed } from 'vue';
import { useQuery } from '@tanstack/vue-query';
import { useI18n } from 'vue-i18n';
import { useRouter } from 'vue-router';
import { getUserProfile } from '@/api/modules/user';
import { useUserStore } from '@/store/modules/user';
const router = useRouter();
@ -60,6 +58,7 @@ const profileQuery = useQuery({
queryFn: ({ signal }) => getUserProfile(signal),
enabled: computed(() => Boolean(userStore.token)),
});
const logout = async () => {
userStore.logout();
await router.replace('/home');

View File

@ -104,7 +104,6 @@
</template>
<script setup lang="ts">
import { computed, ref } from 'vue';
import { useMutation, useQuery, useQueryClient } from '@tanstack/vue-query';
import { useI18n } from 'vue-i18n';
import {
@ -156,13 +155,16 @@ const onSaleCount = computed(
const lowStockCount = computed(
() => products.value.filter((item) => item.stock < 20).length,
);
const refresh = () =>
queryClient.invalidateQueries({ queryKey: ['admin-products'] });
const showError = (error: unknown) => {
mutationError.value = isApiError(error)
? error.message
: t('common.shop.admin.operationFailed');
};
const saveMutation = useMutation({
mutationFn: (input: ProductInput) =>
selectedProduct.value
@ -179,24 +181,29 @@ const deleteMutation = useMutation({
onSuccess: () => refresh(),
onError: showError,
});
const openCreate = () => {
selectedProduct.value = null;
mutationError.value = '';
editorOpen.value = true;
};
const openEdit = (product: Product) => {
selectedProduct.value = product;
mutationError.value = '';
editorOpen.value = true;
};
const closeEditor = () => {
editorOpen.value = false;
selectedProduct.value = null;
};
const save = (input: ProductInput) => {
mutationError.value = '';
saveMutation.mutate(input);
};
const remove = (product: Product) => {
// 跨 UI 框架的简单删除确认,使用原生 confirm 避免引入框架耦合
if (

View File

@ -106,7 +106,6 @@
</template>
<script setup lang="ts">
import { ref } from 'vue';
import { useI18n } from 'vue-i18n';
import type { Product } from '@/api/modules/products';
import { useCartStore } from '@/store/modules/cart';
@ -119,8 +118,10 @@ import {
const cart = useCartStore();
const { locale, t } = useI18n();
const checkoutMessage = ref('');
const productName = (product: Product) =>
getLocalizedText(product.name, locale.value);
const checkout = () => {
checkoutMessage.value = t('common.cart.checkoutDemo', {
count: cart.selectedCount,

View File

@ -1,10 +1,7 @@
<script setup lang="ts">
import FavoriteButton from '@/components/shop/FavoriteButton.vue';
import { useUserStore } from '@/store/modules/user';
import { computed, shallowRef, watch } from 'vue';
import { useQuery } from '@tanstack/vue-query';
import { useI18n } from 'vue-i18n';
import { RouterLink, useRoute, useRouter } from 'vue-router';
import { getProduct } from '@/api/modules/products';
import { useCartStore } from '@/store/modules/cart';
import {
@ -42,16 +39,19 @@ const description = computed(() =>
);
const quantity = shallowRef(1);
const actionMessage = shallowRef('');
watch(productId, () => {
quantity.value = 1;
actionMessage.value = '';
});
const available = computed(
() =>
!!product.value &&
product.value.stock > 0 &&
product.value.status === 'on_sale',
);
watch(
() => product.value?.stock,
(stock) => {
@ -59,6 +59,7 @@ watch(
quantity.value = Math.max(1, Math.min(quantity.value, stock));
},
);
const addToCart = () => {
if (!product.value || !available.value) return;
cart.add(product.value, quantity.value);
@ -66,6 +67,7 @@ const addToCart = () => {
count: quantity.value,
});
};
const showBuyAction = () => {
if (!available.value) return;
actionMessage.value = t('common.shop.detail.checkoutDemo', {

View File

@ -150,7 +150,6 @@
</template>
<script setup lang="ts">
import { computed, onBeforeUnmount, ref } from 'vue';
import { useInfiniteQuery } from '@tanstack/vue-query';
import { useI18n } from 'vue-i18n';
import { getProducts } from '@/api/modules/products';
@ -198,9 +197,11 @@ const productsQuery = useInfiniteQuery({
const products = computed(
() => productsQuery.data.value?.pages.flatMap((page) => page.list) ?? [],
);
const applySearch = () => {
keyword.value = searchInput.value;
};
const {
distance,
onTouchEnd,
@ -215,6 +216,7 @@ const {
},
});
let messageTimer: ReturnType<typeof setTimeout> | undefined;
const addToCart = (product: Product) => {
cart.add(product);
cartMessage.value = t('common.shop.addedToCart', { count: cart.itemCount });
@ -223,6 +225,7 @@ const addToCart = (product: Product) => {
cartMessage.value = '';
}, 1800);
};
onBeforeUnmount(() => {
if (messageTimer) clearTimeout(messageTimer);
});

View File

@ -41,7 +41,6 @@
</template>
<script setup lang="ts">
import { ref } from 'vue';
import { useI18n } from 'vue-i18n';
import {
Button as NutButton,

View File

@ -42,7 +42,6 @@
</template>
<script setup lang="ts">
import { ref } from 'vue';
import { useI18n } from 'vue-i18n';
import {
Button as VanButton,

View File

@ -39,7 +39,6 @@
</template>
<script setup lang="ts">
import { ref } from 'vue';
import { useI18n } from 'vue-i18n';
import {
Button as VarButton,

View File

@ -0,0 +1,60 @@
import { mount } from '@vue/test-utils';
import { afterEach, describe, expect, it, vi } from 'vitest';
import { h, nextTick } from 'vue';
import { useLayoutViewportHeight } from '@/composables/useLayoutViewportHeight';
function mountShell() {
return mount({
setup() {
const height = useLayoutViewportHeight();
return () => h('div', { style: { height: height.value } });
},
});
}
afterEach(() => vi.unstubAllGlobals());
describe('useLayoutViewportHeight', () => {
it('leaves height to CSS when dynamic viewport units are supported', () => {
vi.stubGlobal('CSS', { supports: () => true });
const shell = mountShell();
expect(shell.element.style.height).toBe('');
shell.unmount();
});
it('tracks visual viewport height on legacy browsers and removes its listeners', async () => {
vi.stubGlobal('CSS', { supports: () => false });
const viewport = Object.assign(new EventTarget(), { height: 600.2 });
vi.stubGlobal('visualViewport', viewport);
const removeListener = vi.spyOn(viewport, 'removeEventListener');
const shell = mountShell();
await nextTick();
expect(shell.element.style.height).toBe('600px');
viewport.height = 440.6;
viewport.dispatchEvent(new Event('resize'));
await nextTick();
expect(shell.element.style.height).toBe('441px');
shell.unmount();
expect(removeListener).toHaveBeenCalledWith('resize', expect.any(Function));
});
it('falls back to the window height when the visual viewport API is absent', async () => {
vi.stubGlobal('CSS', undefined);
vi.stubGlobal('visualViewport', undefined);
vi.stubGlobal('innerHeight', 640);
const shell = mountShell();
await nextTick();
expect(shell.element.style.height).toBe('640px');
vi.stubGlobal('innerHeight', 500);
window.dispatchEvent(new Event('resize'));
await nextTick();
expect(shell.element.style.height).toBe('500px');
shell.unmount();
});
});

View File

@ -1,29 +1,15 @@
{
"extends": "@vue/tsconfig/tsconfig.dom.json",
"include": [
"tests/**/*.ts",
"src/**/*.ts",
"src/**/*.d.ts",
"src/**/*.tsx",
"src/**/*.vue",
"types/**/*.d.ts",
"types/**/*.ts",
"config/**/*.ts",
"config/**/*.d.ts",
"mock/**/*.ts",
"build/**/*.ts"
],
"exclude": [
"src/**/__tests__/*",
"node_modules",
"tests/server/**/*.ts",
"dist",
"**/*.js"
"mock/**/*.ts"
],
"exclude": ["src/**/__tests__/*", "node_modules", "dist", "**/*.js"],
"compilerOptions": {
"composite": true,
"allowImportingTsExtensions": true,
"baseUrl": ".",
"tsBuildInfoFile": "./node_modules/.tmp/tsconfig.app.tsbuildinfo",
"paths": {
"@/*": ["./src/*"]

View File

@ -3,8 +3,6 @@
"include": [
"vite.config.*",
"vitest.config.*",
"cypress.config.*",
"nightwatch.conf.*",
"playwright.config.*",
"e2e/**/*.ts",
"build/**/*.ts",

View File

@ -1,11 +1,11 @@
{
"extends": "./tsconfig.app.json",
"include": ["tests/**/*.ts", "src/**/*.d.ts", "types/**/*.d.ts"],
"exclude": [],
"compilerOptions": {
"composite": true,
"composite": false,
"incremental": true,
"tsBuildInfoFile": "./node_modules/.tmp/tsconfig.vitest.tsbuildinfo",
"lib": [],
"types": ["node", "jsdom"]
"types": ["node", "jsdom", "pinia-plugin-persistedstate"]
}
}

View File

@ -42,35 +42,13 @@ export default function defineViteConfig({
forwardConsole: true,
},
plugins: createVitePlugins(viteEnv, isProduction),
esbuild: isProduction
? {
drop: ['console', 'debugger'],
}
: undefined,
build: {
target: ['es2019', 'safari15'],
manifest: true,
// 使用 esbuild 压缩:比 terser 快数倍,且原生支持移除 console/debugger
minify: 'esbuild',
rollupOptions: {
rolldownOptions: {
output: {
// 拆分 vendor,避免单个 chunk 过大、改善缓存命中率与并行加载
manualChunks(id) {
if (!id.includes('node_modules')) return undefined;
if (id.includes('@vant')) return 'vendor-vant';
if (id.includes('@nutui')) return 'vendor-nutui';
if (id.includes('@varlet')) return 'vendor-varlet';
if (id.includes('@tanstack')) return 'vendor-query';
if (id.includes('markdown-it') || id.includes('dompurify'))
return 'vendor-markdown';
if (
/[\\/]node_modules[\\/](vue|vue-router|pinia|vue-i18n)[\\/]/.test(
id,
)
) {
return 'vendor-vue';
}
return 'vendor';
minify: {
compress: { dropConsole: true, dropDebugger: true },
},
},
},

View File

@ -1,9 +1,15 @@
import { defineConfig } from 'vitest/config';
import { fileURLToPath, URL } from 'node:url';
import vue from '@vitejs/plugin-vue';
import { ConfigAutoImportPlugin } from './build/vite/plugins/autoImport.ts';
import { ConfigAutoComponentsPlugin } from './build/vite/plugins/component.ts';
export default defineConfig({
plugins: [vue()],
plugins: [
vue(),
ConfigAutoComponentsPlugin('vant', false),
ConfigAutoImportPlugin('vant', false),
],
resolve: {
alias: {
'@': fileURLToPath(new URL('src', import.meta.url)),