Compare commits

..
4 Commits
Author SHA1 Message Date
wc24 2ce6fd6d2f 0.8.1: 布局不再依赖消费侧给挂载点加 class="aminui"
.aminui-wrapper 补 height:100%。#app 本来就有 height:100%(app.scss 开头),
但它是块级容器,wrapper 的 flex:1 在块级父容器里空转,布局塌成内容高度——
侧边栏比页面矮一截,还跟着表格异步加载忽长忽短。不报错、页面照常打开,
所以接入方发现不了,只会当成 CSS 小毛病。

父级确实是 .aminui 时 flex:1 1 0% 接管尺寸,这行等价不冲突,存量消费侧不受影响。

已验证:atf-admin 删掉 index.html 上的 class="aminui" 后,
project / point / requirement 三个页面侧边栏高度均为 851(此前缺类时 634)。
2026-08-10 19:55:52 +08:00
wc24 603e33d17f 0.8.0: 契约副本刷齐并改为自动同步;未注册字段类型不再静默回落
契约副本(src/IShrimpType.ts)此前漂了一整代:停在旧的 json 类型,
缺 object / array / IFieldConfig.fields / IFieldConfig.item / parse / IPageResult.refs。
而本包自己的组件早就在读这些字段——FieldArray 读 field.item、FieldObject 读 fields、
FieldRelation 与 ShrimpTable 读 refs。等于组件在用、类型说没有。
接入方照这份副本理解 shrimp 能渲染什么,只会得出"结构化数据只有 json"的结论。

现在由 shrimp-server 的 postbuild 单向覆盖过来(它是契约真身),
本仓库另提供 npm run check:contract / sync:contract 手动比对与同步。
注释头不参与同步,它声明的是"我是副本",与契约正文是两回事。

VueAdmin.getFieldComponent:未注册类型仍回落成 string(类型词汇表是开放的,
消费侧放个 Field<X>.vue 就能扩,改成严格校验会当场打死 theseus 的 gesture/goodsList
和 hand 的 dropList/matterPointDropList),但按类型去重告警一次,
打印出现位置、已注册类型和两条修法。上面那个 json 就是这么静默活下来的。

resolveVue:内置组件表为空时报"本包没被 vite 正常转换、消费侧缺 optimizeDeps.exclude",
不再报"找不到 layout.vue"把人引去查文件路径。

README 重写成可照抄的接入模板 + 出错对照表 + "那几行为什么不能删"。
版本与 shrimp-server 归一到 0.8.0,删掉 @syncedFrom 这条手维护的版本标记。
2026-08-10 19:48:57 +08:00
lbin b7042c8387 操作栏 宽度 2026-07-23 19:11:08 +08:00
lbin bed4d4dc4a add: bar components 2026-07-10 15:11:42 +08:00
9 changed files with 257 additions and 22 deletions
+126 -10
View File
@@ -4,37 +4,153 @@ Shrimp 框架前端 —— 一种**经典解决方案**(不是框架本身),消
如果你想换 UI 库或者换前端技术栈,直接照 shrimp-server 的约定再写一份就行,不依赖本包。
## 安装
shrimp-admin 是**源码 ship**(.ts + .vue 直接发),不带构建产物,由消费侧 Vite 编译。这省掉了框架的构建步骤,代价是**有几件事 npm 装完不会自动生效**,必须消费侧显式配 —— 下面的接入模板已经把它们全写进去了。
```bash
npm i git+http://git.zeromvc.com/wc24/shrimp-admin.git#v0.3.0
---
# 接入模板
> **整段抄,不要自己攒。** 标了「⚠️ 不能删」的行看起来多余,删掉的后果写在每行旁边;
> 现存的 theseus-admin / hand-admin / bug-book 三个项目里,这些行一行不差全都在。
## 1. package.json
```jsonc
{
"type": "module",
"scripts": { "dev": "vite", "build": "vite build" },
"dependencies": {
"shrimp-admin": "git+http://git.zeromvc.com/wc24/shrimp-admin.git#v0.7.10",
// ⚠️ 不能删 —— 下面 6 个是 shrimp-admin 的 peerDependencies,
// 必须由消费侧显式装进自己的 dependencies,不能指望 npm 提升碰巧能 import 到
"vue": "^3.5.0",
"vue-router": "^4.5.0",
"vue-i18n": "^9.14.0",
"axios": "^1.7.0",
"element-plus": "^2.10.0",
"@element-plus/icons-vue": "^2.3.0"
},
"devDependencies": {
"@vitejs/plugin-vue": "^5.2.0",
"sass-embedded": "^1.80.0", // ⚠️ 不能删 —— shrimp-admin/style 是 .scss
"typescript": "^5.6.0",
"vite": "^6.0.0"
}
}
```
shrimp-admin 是**源码 ship**(.ts + .vue 直接发),由消费侧 Vite 编译。
服务端那侧另有一条硬约束:**shrimp-server 要求 Express 5**(它的兜底路由用了 `/*path` 具名通配,Express 4 只会当字面路径)。装成 4 的症状是能登录、能出菜单,但**所有** `POST /<moduleKey>/list` 都 404。
## 使用
## 2. vite.config.ts
```ts
import { defineConfig } from 'vite'
import vue from '@vitejs/plugin-vue'
export default defineConfig({
plugins: [vue()],
optimizeDeps: {
// ⚠️ 不能删 —— 删了整页白屏,报 resolveVue: components/layout.vue not found in sources
exclude: ['shrimp-admin'],
},
resolve: {
// ⚠️ 不能删 —— 删了 element-plus 与 shrimp-admin 各带一份 vue/dayjs,互操作错位
dedupe: ['vue', 'vue-i18n', 'vue-router', 'element-plus', 'dayjs'],
},
server: {
// 开发期后台接口由 vite 转发,前端一律走相对路径,不注入任何后端地址
proxy: { '/admin-api': { target: 'http://127.0.0.1:8080', changeOrigin: true } },
},
})
```
## 3. src/main.ts
```ts
// main.ts
import { createApp } from 'vue'
import { createShrimpAdmin, App } from 'shrimp-admin'
// ⚠️ 不能删,且必须在 shrimp-admin/style 之前 ——
// 删了页面能出来但整个掉样式,最显眼的症状是图标被撑到巨大
import 'element-plus/dist/index.css'
import 'element-plus/theme-chalk/display.css'
import 'shrimp-admin/style'
import { createShrimpAdmin, App } from 'shrimp-admin'
import zhCn from './locales/zh-cn.json'
import en from './locales/en.json'
const app = createApp(App)
app.use(createShrimpAdmin({
config: {
API_URL: '/admin-api',
API_URL: '/admin-api', // 相对路径,由 vite proxy 转发
TIMEOUT: 10000,
},
locales: { 'zh-cn': zhCn, en },
// ⚠️ import.meta.glob 必须写在消费侧的文件里(vite 静态扫描相对本文件),
// 不能封装成函数从别处调
sources: import.meta.glob('./shrimp/**/*.vue'),
}))
app.mount('#app')
```
## 唯一约定: `sources` 路径后缀覆盖
## 4. 每个业务模块一个薄壳 `src/shrimp/module/<key>.vue`
⚠️ **不能省。**后端有几个 moduleKey,这里就得有几个文件 —— 这**不是「覆盖」,是「注册」**:框架的内置兜底只兜自己的 login/layout/404,不认识你的业务模块,少一个那个菜单就点不开。
```vue
<!-- src/shrimp/module/product.vue —— 后端 moduleKey === 'product' -->
<template>
<ShrimpTable moduleKey="product" />
</template>
<script setup lang="ts">
// 字段、筛选、编辑全由后端 moduleInfo 声明,ShrimpTable 自动渲染,这里不写业务代码
import { ShrimpTable } from 'shrimp-admin'
</script>
```
反过来,内置的 `login.vue` / `layout.vue` / `404.vue` **一个都不用写** —— 框架内置兜底,只在你真有增量时才覆盖(见下面「唯一约定」)。
---
# 出错对照表
接入时按症状反查,不必先懂原理。
| 你看到的 | 病因 | 改哪 |
| --- | --- | --- |
| `resolveVue: components/layout.vue not found in sources`,整页白屏 | shrimp-admin 被 vite 预打包了 | vite.config `optimizeDeps.exclude: ['shrimp-admin']` |
| `module component not found: module/<key>.vue`,菜单点不开 | 少了业务模块薄壳 | 补 `src/shrimp/module/<key>.vue`,模板第 4 节 |
| 页面出来了但没样式,**图标巨大** | 没引 element-plus 基础样式 | main.ts 加两行 css,模板第 3 节 |
| 能登录、菜单也有,但**所有列表都 404** | 服务端装的是 Express 4 | 服务端升到 `express@^5` |
| `does not provide an export named 'default'`(dayjs / element-plus) | 依赖被装了两份 | vite.config `resolve.dedupe`,模板第 2 节 |
## 验收: 必须在浏览器里打开页面
`vite build` 通过、`curl` 打接口通,**都不算接入完成**。上表前三行全部逃得过构建和接口测试:
- dev 用 esbuild 预打包、build 用 rollup,是**两套转换管线**。rollup 正确处理 node_modules 里的 `import.meta.glob`,所以第 1 行的问题在 `vite build` 下一路绿灯,只在 dev 复现。
- 样式和路由注册只在浏览器运行时才成立,接口测试根本不经过它们。
# 那几行为什么不能删
## `optimizeDeps.exclude: ['shrimp-admin']`
Vite dev 默认用 **esbuild** 把 node_modules 里的裸导入预打包成 `node_modules/.vite/deps/shrimp-admin.js`。两个后果:
- 框架的内置组件表靠 `import.meta.glob('./{components,module}/**/*.vue')` 收集,这是 **Vite 编译期宏**,esbuild 不认识,会原样抄进产物;等它在 `.vite/deps/` 目录下才被展开时,那个目录里一个 `.vue` 都没有 → 内置表变成空对象 `{}` → 内置兜底全部落空。
- 预打包等于复制出第二份模块实例,`vueAdmin` 单例会分裂成两个,消费侧拿到的和框架内部用的不是同一个。
## element-plus 的两行 css
`shrimp-admin/style` 只包含框架自己的覆盖样式与暗色变量(`fix.scss` / `dark.scss` 等),**不含** element-plus 本体的样式表。element-plus 是 peerDependency、由消费侧安装,它的基础样式自然也该由消费侧引 —— 框架替你引会锁死版本、也挡住你换主题。顺序不能反:覆盖必须在基础之后。
## 业务模块薄壳
框架靠 `sources` 里扫到的 `module/<key>.vue` 去 `registerRoute`。它没有别的途径知道你有哪些业务模块 —— 后端 moduleInfo 只告诉它「有个 key 叫 product」,渲染成哪个组件得你指定。壳里只有一行 `<ShrimpTable>`,但这一行就是那次指定。
# 唯一约定: `sources` 路径后缀覆盖
消费侧把所有要交给框架的 .vue 通过单个 `sources` 入口注入(`import.meta.glob` 必须由消费侧自己调用,vite 静态扫描相对调用文件)。框架按**文件路径后缀**匹配,同后缀消费侧优先,内置兜底。
@@ -130,7 +246,7 @@ function login() {
只要文件落在 `src/shrimp/components/login.vue`,被 `sources` 的 glob 扫到,框架的 `/login` 路由就会用你这份替换内置版本。
## 消费的契约
# 消费的契约
参见 shrimp-server README `## 约定` 章节。本包消费以下条件契约:
+5 -1
View File
@@ -1,6 +1,6 @@
{
"name": "shrimp-admin",
"version": "0.7.10",
"version": "0.8.1",
"private": true,
"description": "Shrimp 框架前端 — 消费 ShrimpServer + ShrimpTable 契约的经典 Vue3 + Element Plus 实现",
"main": "src/index.ts",
@@ -17,6 +17,10 @@
"src",
"README.md"
],
"scripts": {
"check:contract": "node scripts/check-contract.mjs",
"sync:contract": "node scripts/check-contract.mjs --fix"
},
"peerDependencies": {
"vue": "^3.3.0",
"vue-router": "^4.0.0",
+61
View File
@@ -0,0 +1,61 @@
/**
* 契约副本工具:比对 / 同步 src/IShrimpType.ts 与 shrimp-server 那份。
*
* node scripts/check-contract.mjs 比对,漂了就非零退出
* node scripts/check-contract.mjs --fix 从 shrimp-server 复制过来(自动保留前端副本的注释头)
*
* 为什么需要它:副本靠人工同步,漂了一整代都没被发现——
* 副本停在旧的 json 类型、缺 object/array/fields/item/parse/refs。
* 前端对未注册的字段类型静默回落到 string,所以漂移不报错、只悄悄渲染错。
* (同样是"改了就复制过去"的约定,goby 的 GobyClient.ts 四份拷贝已经全漂了,
* 区别只在于那份复制后归消费侧拥有、漂了无所谓,而这份两边必须字节一致。)
*
* 只比对注释块之后的正文:两边的头部本来就该不同,一份是契约、一份声明自己是副本。
*/
import { readFileSync, writeFileSync, existsSync } from "node:fs"
import { fileURLToPath } from "node:url"
import { dirname, resolve } from "node:path"
const here = dirname(fileURLToPath(import.meta.url))
const mine = resolve(here, "../src/IShrimpType.ts")
const fix = process.argv.includes("--fix")
const argPath = process.argv.find(a => !a.startsWith("--") && a !== process.argv[0] && a !== process.argv[1])
const theirs = [
argPath && resolve(argPath, "src/IShrimpType.ts"),
resolve(here, "../node_modules/shrimp-server/src/IShrimpType.ts"),
resolve(here, "../../shrimp-server/src/IShrimpType.ts"),
].filter(Boolean).find(existsSync)
if (!theirs) {
// 消费侧的前端项目不装后端包,找不到是正常的,不该让它们的构建挂掉
console.log("skip: 找不到 shrimp-server 源码,无从比对")
process.exit(0)
}
const split = f => {
const s = readFileSync(f, "utf8")
const i = s.indexOf("*/") + 2
return { head: s.slice(0, i), body: s.slice(i) }
}
const a = split(mine)
const b = split(theirs)
if (a.body === b.body) {
console.log("✅ 契约副本与 shrimp-server 一致")
process.exit(0)
}
if (fix) {
writeFileSync(mine, a.head + b.body)
console.log("✅ 已从 shrimp-server 同步契约副本(保留原注释头)")
console.log(" " + theirs + "\n → " + mine)
process.exit(0)
}
console.error("❌ 契约副本已漂移")
console.error(" 副本: " + mine)
console.error(" 契约: " + theirs)
console.error(" 修法: npm run sync:contract")
process.exit(1)
+18 -7
View File
@@ -1,15 +1,18 @@
/**
* Shrimp 类型契约 — 前后端 wire protocol 定义(前端副本)
*
* @syncedFrom shrimp-server contract 1.0.0
* 这是 shrimp-server/src/IShrimpType.ts 的逐字副本(除本注释块外)。
* 不要在这里改 wire protocol,先改 shrimp-server 那份升版本,再整份 cp 过来。
*
* 这是 shrimp-server/src/IShrimpType.ts 的逐字副本。
* 不要在这里改 wire protocol,先改 shrimp-server 那份升版本,再 copy 过来更新 @syncedFrom。
* 本文件由 shrimp-server 的 postbuild 自动同步过来,手改会被下次 build 覆盖。
* 手动同步: npm run sync:contract 只想看漂没漂: npm run check:contract
* 自动同步这件事存在的原因是:曾经靠人工复制,漂了一整代都没人发现——
* 副本停在旧的 json 类型、缺 object/array/fields/item/parse/refs,
* 而前端对未注册类型静默回落到 string,所以漂移不会报错、只会悄悄渲染错。
*
* 故意保留副本而不 import 'shrimp-server' 的原因:
* - shrimp-server 入口会把 mongoose / express 牵进前端 bundle
* - 拆 './types' 子入口会绕开 vite optimize、可读性也差
* - 类型契约低频改动,版本号对照即可
* - shrimp-server 默认入口会把 mongoose / express 牵进前端 bundle
* - 前端项目不该为一份纯类型去装后端包
*/
/** 业务错误码 */
@@ -238,8 +241,9 @@ export const ShrimpFieldTypes = {
Textarea: "textarea" as ShrimpFieldType,
Password: "password" as ShrimpFieldType,
Relation: "relation" as ShrimpFieldType,
Json: "json" as ShrimpFieldType,
Tab: "tab" as ShrimpFieldType,
Object: "object" as ShrimpFieldType,
Array: "array" as ShrimpFieldType,
}
/** 字段可编辑状态 */
@@ -279,6 +283,12 @@ export interface IFieldConfig {
rules?: IFieldRule[] // 通用验证规则(前后端共用)
/** tab 类型专用:每个 type 对应的子字段配置 */
tabs?: { key: any; label: ILabel; fields: IFieldConfig[] }[]
/** object 类型专用:嵌套字段组 */
fields?: IFieldConfig[]
/** array 类型专用:每个元素的字段配置(递归 IFieldConfig;元素无需 key,label 用作每项标题) */
item?: IFieldConfig
/** tab 类型专用:import 反序列化(把字符串还原成对象,如 xlsx 导入),默认 JSON.parse */
parse?: (text: string) => any
}
/** 通用验证规则(前后端共用) */
@@ -315,6 +325,7 @@ export interface IPageResult<T> {
page: number // 当前页码
pageSize: number // 每页数量
totalPages: number // 总页数
refs?: Record<string, Record<string, any>> // relation 显示名字典: { moduleKey: { id: 显示名 } },前端显示时查名,替代逐行 _label
}
// ============== 数据源查询协议 ==============
+34 -1
View File
@@ -53,6 +53,8 @@ export interface ShrimpAdminOptions {
locales?: Record<string, any>
/** 语言列表,默认 [{ lang: 'zh-cn', name: '简体中文' }] */
langList?: { lang: string; name: string }[]
/** 顶栏(userbar)自定义组件,按序渲染在语言切换左侧。业务侧注入全局头部小部件(如终端商户选择器) */
headerWidgets?: Component[]
}
// ============== 源注册表 ==============
@@ -78,6 +80,15 @@ export function resolveVue(suffix: string): VueLoader {
for (const key in internalSources) {
if (key.endsWith(tail)) return internalSources[key] as any
}
// 内置表整个是空的,说明本包被 esbuild 预打包了——import.meta.glob 是 vite 编译期宏,
// 预打包不认它,内置组件一个都收不到。报"找不到 layout.vue"会把人引向错误的方向。
if (Object.keys(internalSources).length === 0) {
throw new Error(
`[shrimp-admin] 内置组件表为空,本包没有被 vite 正常转换。\n` +
` 消费侧 vite.config 需要: optimizeDeps: { exclude: ["shrimp-admin"] }\n` +
` (或直接用 shrimp-admin/vite 提供的插件,它会自动加上)`
)
}
throw new Error(`[shrimp-admin] resolveVue: ${suffix} not found in sources`)
}
@@ -88,6 +99,19 @@ export function resolveVue(suffix: string): VueLoader {
const fieldRegistry = new Map<string, Component>()
/** 未注册类型每种只喊一次——表格逐格调 getFieldComponent,不去重会刷屏 */
const warnedTypes = new Set<string>()
function warnOnce(type: string, moduleKey?: string, fieldKey?: string) {
if (warnedTypes.has(type)) return
warnedTypes.add(type)
console.warn(
`[shrimp-admin] 字段类型 "${type}" 没有对应组件,已按 string 渲染` +
(moduleKey || fieldKey ? `(出现在 ${moduleKey ?? '?'}.${fieldKey ?? '?'})` : '') +
`\n 已注册: ${[...fieldRegistry.keys()].sort().join(', ')}` +
`\n 要么后端把 type 改成上面之一,要么消费侧补一个 shrimp/components/fields/Field${type.charAt(0).toUpperCase() + type.slice(1)}.vue`
)
}
function deriveFieldType(path: string): string | null {
const m = path.match(/\/components\/fields\/Field([A-Z][A-Za-z0-9]*)\.vue$/)
if (!m) return null
@@ -127,7 +151,12 @@ export class VueAdmin extends ShrimpClient {
moduleRoutes = new Map<string, IRouteInfo>()
getFieldComponent(_moduleKey: string, type: string, _fieldKey?: string): Component {
return fieldRegistry.get(type) || fieldRegistry.get('string')!
const hit = fieldRegistry.get(type)
if (hit) return hit
// 类型词汇表是开放的(消费侧放个 Field<X>.vue 就能扩),所以这里不能报错、只能回落。
// 但静默回落等于打错字永远发现不了——曾经有个 json 类型这么活了一整代。
warnOnce(type, _moduleKey, _fieldKey)
return fieldRegistry.get('string')!
}
/** 目标模块能否作为「单项查看」跳转目标:已按权限注册路由 且 非子模块。返回其路由信息或 undefined(不可跳) */
@@ -138,6 +167,9 @@ export class VueAdmin extends ShrimpClient {
state = reactive({ isMobile: false })
/** 顶栏自定义组件(由 createShrimpAdmin 的 headerWidgets 注入),userbar 按序渲染 */
headerWidgets: Component[] = []
private _token: string | null = null
get token() { return this._token }
set token(value: string | null) {
@@ -170,6 +202,7 @@ export class VueAdmin extends ShrimpClient {
super()
this.config = opts.config
this.langList = opts.langList || [{ lang: 'zh-cn', name: '简体中文' }]
this.headerWidgets = opts.headerWidgets || []
if (opts.sources) {
Object.assign(externalSources, opts.sources)
+5 -2
View File
@@ -35,7 +35,7 @@
</el-table-column>
</template>
<el-table-column :label="$t('base.operation')" :width="rowActionsWidth" v-if="hasRowActions">
<el-table-column :label="$t('base.operation')" :width="resolvedRowActionsWidth" v-if="hasRowActions">
<template #default="{ row }">
<el-button v-if="hasActiveField && can('edit')" link :type="row.active ? 'warning' : 'success'" :icon="row.active ? VideoPause : VideoPlay" size="large" @click="handleToggleActive(row)" />
<el-button v-if="can('edit')" link type="primary" :icon="Edit" size="large" @click="handleEdit(row)" />
@@ -100,6 +100,8 @@ interface Props {
pageSize?: number
/** 显式锁定的筛选条件(覆盖自动 ownerKey 推断);用户无法修改,会合并进 filter 并在筛选抽屉中隐藏 */
baseFilter?: Record<string, any>
/** 显式指定操作列宽度;传入后覆盖按内置按钮数量自动计算的宽度,适用于 row-actions 插槽塞了多个按钮的场景 */
rowActionsWidth?: number | string
}
const props = withDefaults(defineProps<Props>(), {
@@ -287,7 +289,8 @@ function handleSubJump(sub: IModuleInfo, row: any) {
const hasRowActions = computed(() => can('edit') || can('delete') || hasActiveField.value || subModules.value.length > 0 || !!slots['row-actions'])
const rowActionsWidth = computed(() => {
const resolvedRowActionsWidth = computed(() => {
if (props.rowActionsWidth != null && props.rowActionsWidth !== '') return props.rowActionsWidth
let n = 0
if (hasActiveField.value && can('edit')) n++
if (can('edit')) n++
+2
View File
@@ -1,5 +1,7 @@
<template>
<div class="user-bar">
<!-- 业务侧注入的顶栏部件(headerWidgets),按序渲染在语言切换左侧 -->
<component :is="w" v-for="(w, i) in vueAdmin.headerWidgets" :key="i" />
<LangSwitch class="panel-item" />
<div class="panel-item" @click="screen">
<el-icon><el-icon-full-screen /></el-icon>
+1 -1
View File
@@ -2,7 +2,7 @@
//
// 消费侧用法见 README.md。本文件只做 re-export。
// ===== 类型契约(IShrimpType 本地副本,@syncedFrom shrimp-server contract 1.0.0)=====
// ===== 类型契约(IShrimpType 是 shrimp-server 那份的副本,由其 postbuild 自动同步)=====
export {
ShrimpCode,
ShrimpError,
+5
View File
@@ -55,6 +55,11 @@ textarea {
display: flex;
flex: 1;
overflow: auto;
/* 挂载点没加 class="aminui" 时的兜底:#app 已经是 height:100%(本文件开头),
但它是块级容器,上面那行 flex:1 在块级父容器里不生效,布局会塌成内容高度——
侧边栏比页面矮一截、还跟着表格异步加载忽长忽短,且不报错、页面照常打开。
父级确实是 .aminui 时,flex:1 1 0% 接管尺寸,这行等价不冲突。 */
height: 100%;
}
/* 全局滚动条样式 */