sapit-ui-base-guide.en.md 134 KB

sapit-ui base framework guide and business usage

Applies to: sapit-ui-framework (the base / sources), sapit-ui-plus (published artifact), sapit-base-template (business sample).

This document is also the data source of the built-in /docs page and the /components page.

Prop defaults in the base source are written in Chinese and translated at render time, so the tables below show their English rendering.


Contents


1. Overview

1.1 The five pieces

Project Role Description
sapit-ui-framework Base (sources) Library project holding the built-in components and common dependencies, packed in Vite lib mode
sapit-ui-plus Published artifact The git repository that receives the base dist (lib/, docs/, vite-plugins/)
sapit-base-template Business consumer Builds business pages and configuration on top of the sapit-ui-plus git dependency
sapit-ui-framework --(npm run build)--> dist/lib --(git push)--> sapit-ui-plus(git) --> sapit-base-template

1.2 Directory structure (base)

sapit-ui-framework/
├─ packages/                 # published content source (entry dependency graph)
│  ├─ index.js               # library entry, exports registerGlobalConfig
│  ├─ components/            # built-in S* components
│  ├─ layouts/               # BasicLayout / BlankLayout / UserLayout / RouteView / PageView
│  ├─ router/                # constant routes + dynamic routes + static routes + guards
│  ├─ store/ api/ utils/ locales/ static/ style/
│  └─ pages/      # login, workplace, todo, message, 404/403/500, docs pages
├─ docs/                     # this document (rendered by the built-in /docs)
├─ vite-plugins/             # docs-viewer plugin
├─ src/                      # the base's own debug shell
└─ vite.config.js / package.json

2. What the base provides

2.1 Global components

packages/index.js uses import.meta.glob('./components/**/*.vue') to register every components/**/*.vue by file name, so templates can use the file name as the tag (e.g. <s-modal>, <s-user-select>).

Category Components
Layout SSkeletonLayout (skeleton layout: title + button group + content, see 2.16), SListLayout, SListCardLayout (card list, see 2.19), SListTableTreeLayout, SSuperListLayout (advanced list, see 2.20), SFormLayout, SPanelLayout, SCollapses/SCollapsesItem, SDrawer
Overlay SModal, SModalTemplate, ModalHeader, SIconModal, SImportModal (bulk import, see 2.11)
Form / filter SForm, SFormItem (multi-column + full for a whole row, see 3.4), SExtendFieldsForm/SExtendFieldsFormItem (dynamic extra fields), SFilterWrap, SFilterItem (full for a whole row, see 3.4), SFilterToolbar (filter area shell: main row + more-filters collapse + reset, see 3.4), STableToolbar (table area shell: body height auto-fits the content area; used as a pair with SFilterToolbar, see 3.4), SCascader, STree, STreeSelect, SDataRangeTreeSelect (data-permission scope tree), SUserSelect, SUserSelectButton, SChooseUser (user picker with data permission, see 2.14), SBelowChoosePosition (position picker, see 2.15), SOfficeSelect, SIconSelect (icon dropdown, searchable/multiple), SIconSelectPopover (icon grid panel), SIconModal (icon browser)
Upload SFileUpload, SDraggerUpload, SCopperUpload, CropperModal
Display / others STab/STabItem (tab bar: arrows + drag when the tabs overflow, see 2.21), SEditor, SEmpty, SIcon, SSvg, SAnchor, SColorPicker, SToggleLanguage, SettingFilter, SettingColumns, SSideMenu/STopMenu

Component usage lives in the built-in component page /components (two tabs: "s components" and "tools / config"; the latter lists every web-config option and every $utils method).

Registration rule: components/**/*.vue is registered globally by file name (SForm.vue → <SForm>, not kebab-case); the later one wins on conflict. Table/index.jsx is a .jsx file that import.meta.glob cannot match, so the base registers it separately as the global STable in packages/index.js (<s-table> works without any import). All @ant-design/icons-vue icons are registered globally and exposed as $icons. Some helper components are internal only: ModalHeader (SModal), CropperModal (SCopperUpload), CustomInput/SettingColumns/SettingFilter (SSuperListLayout).

2.1.1 Choosing a layout component

Scenario Use
Title + buttons + custom content (no table / pagination / form) SSkeletonLayout (see 2.16, ships with a title bar and permission-aware buttons)
Ordinary list page SListLayout
Card list SListCardLayout (card grid + three slots, see 2.19)
List + left tree SListTableTreeLayout (the left tree container class must be .side.s-side-tree, see 3.5)
List with advanced search / table SSuperListLayout (column settings + advanced filter, see 2.20)
Add / edit / detail (routed) SFormLayout (#form slot holds SForm; #footer-callback receives save/cancel/prev/next)
Form as modal content SModal (do not nest SFormLayout)
Dynamic form driven by backend fields SExtendFieldsForm (data + defaultValue; the ref exposes validate/clearValidate/getModel)
Data-permission scope selection SDataRangeTreeSelect (autoSysConfig manages the system dataScope config)

2.2 Global properties / methods

Available after $registerGlobalConfig runs (this.$xxx / $xxx in templates / window.$xxx):

Name Description
$registerGlobalConfig(config, pages) Initialization entry (see 5.2)
$utils Utility collection: $utils.env / $utils.ls / $utils.http plus general helpers
env Merged environment configuration (= $utils.env)
$i18n / $l(name, key) Internationalization (see 2.7). Lives on globalProperties: usable directly in templates as $l('xx'); inside <script setup> scripts you must call window.$l('xx') (setup has no this)
$theme / $staticRoutes / $pinia Theme object / static route list / user store instance
$modal / $message / $notice / $confirm antd Modal / message / notification / Modal.confirm (list component button api branch calls this.$confirm)
$push(path, query) / $open(...) In-app navigation / new window (automatically prefixes VITE_APP_BASE_URL)
$filter / $icons / $socket Date formatting / icon collection / websocket wrapper. $icons maps every @ant-design/icons-vue icon by Pascal name (InfoCircleOutlined) and is also exposed on window.$icons (so $utils.iconOf works outside components). Legacy antd v1 <a-icon type="info-circle"> names convert via $utils.iconOf('info-circle'); SIcon's name only accepts Pascal names
$getPdf({ el, title }) Export the page to PDF (Vue3 port of the legacy Vue.prototype.getPdf). Pass the capture container and file name explicitly: <a-button @click="$getPdf({ el: '#pdfDom', title: htmlTitle })">Export</a-button>. html2canvas + jsPDF are imported dynamically, so nothing loads until the button is clicked; A4 pagination is automatic and it returns Promise<boolean>. Optional fileName / scale / backgroundColor / beforeCapture / afterCapture / onError. A dollar-less getPdf alias is registered for legacy code (default container #pdfDom, title from document.title)

2.3 Layouts

packages/layouts/index.js: BasicLayout (header + side menu + content), BlankLayout, UserLayout (login), RouteView, PageView.

The height chain of BasicLayout (business layout components must match it, see chapter 3):

.basic-layout-common (100vh)
→ .ant-layout
→ .main-content
→ .container (height = mainHeight = clientHeight - headerHeight)
   └─ minus footerHeight(56) when the footer is shown
   → router-view (height = contentHeight, overflow: hidden auto)
      → business layout component (.list-layout / .form-layout, flex:1)

mainHeight / contentHeight are computed from the real header.offsetHeight (not a hard-coded 58) so the layout cannot disagree with the actual rendering and produce overflow scrollbars.

2.4 Routes

Constant routes (packages/router/index.js):

Path Description
/login/index Login page (base default, can be overridden by the business, see 5.3)
/login/:officeCode Same page entered with an office code (written to $utils.ls as officeCode and reused for later logins)
/user/qrCode, /user/forgotPassword, /user/activate QR login / forgot password / account activation pages. The parent /user carries meta.public, so they are reachable before login; /user/login redirects to VITE_APP_LOGIN_PATH (see 2.10)
/workplace/index Default home (VITE_APP_DEFAULT_PATH, overridable)
/workbench/index, /message/index Workbench / messages
/docs, /components Built-in docs / component pages (public = no login, hidden = not in the menu)
/404, /403, /500, /:pathMatch(.*)* Error pages; the catch-all renders 404 (no redirect, so refreshing dynamic routes never lands on a 404). All four sit under BasicLayout and swap only the content-area router-view, keeping the sidebar and header untouched

Redirect rules, query parameters, wording and color overrides for the error pages are documented in 2.17 Error pages.

Static routes (staticRoutes, independent of backend menus): see 5.4. The base ships /docs and /components.

Dynamic routes (packages/router/generator-routers.js): after login a tree is generated from the backend menus, rooted at BasicLayout; leaf nodes use item.hrefs to match business pages (keys of import.meta.glob('@/views/**/*.vue')) and fall back to 404 when nothing matches. Registration happens inside the guard (memory flag, re-registered on refresh).

Guards: public pages (meta.public) pass straight through; the token is read live; unauthenticated users are redirected to login; an authenticated user visiting the login page or the root is sent to the default home; a failed user-info fetch clears state and returns to login (so nothing stays pending). When the URL carries a code, the guard exchanges it for a token (see 5.8 permissions and 6.1).

2.5 State management (pinia)

packages/store/user.js (useUserStore): state user/menus/permissions/clients/dynamicRouter/menuOpenKeys; actions Info() (fetch and write to localStorage), setDynamicRouter(), setMenuOpenKeys(); persisted in localStorage.

2.6 Utilities ($utils)

Module Description
$utils.env Environment configuration object
$utils.ls Local storage (namespace VITE_APP_SYS_SERVER_NAME)
$utils.http axios instance (token/client-id injection, response unwrapping, login timeout, file download)
parseAppUrl / innerRedirect etc. Build in-app URLs with the base (sub-path aware); external http(s) URLs are kept as-is
messageFormat(str, values) {0} / {name} placeholder substitution (confirm dialogs etc.)
filterSelectOption(iv, opt) antd4-ready :filterOption (reads option.label / option.value)
randomDrawerPlacement() Randomly returns left / right / top / bottom (kept from the source project)
getTableHeight({ selector, offset }) List table height = window height − search area − offset (defaults .table-page-search-wrapper / 320; no-arg call keeps legacy behaviour). Only for legacy fixed-height lists — SListLayout uses flex sizing
iconOf(type) Converts legacy antd v1 <a-icon type="info-circle"> names: kebab / snake / Pascal in → icon component. Usage: <component :is="$utils.iconOf('info-circle')" />
hasAction(name) Functional button-level permission check, same source as v-action; for v-if OR / AND logic and disabled computation
Others Type checks, dates, arrays, url, dom, debounce/throttle, money, phone validation, etc.

⚠️ Type checks are not format validation: $utils.isNumber / isInt / isDate use Object.prototype.toString ($utils.isNumber('123') is always false). They are not string-format validators; a business-side regex version with the same name must not be replaced by them.

Likewise $utils.uuid(len) returns a purely random string, a different shape from a "timestamp + random" getUUID() — do not swap them when the value feeds backend keys.

v-action:xxx is the button-level permission directive: <a-button v-action="'add'">Add</a-button>.

  • It delegates to $utils.hasAction(actionName) — the directive and the function share one decision path
  • Source priority: permission (singular, the current route's button array written by the router/index.js guard) → falls back to permissions (plural, the full route → buttons map written by store/user.js) + CURRENT_ROUTER_KEY
  • Matching rule: String(button_code) === String(actionName), exact equality (add no longer matches batchAdd)
  • Functional usage: <a-button v-if="$utils.hasAction('add') || $utils.hasAction('edit')">

2.7 Internationalization

A language pack is a file named i18n.js placed directly in a module's top-level folder, with no prefix, and its shape is a flat dictionary:

// src/views/user/i18n.js  ->  namespace user
export default {
  '<source text>': 'Cancel'
}

The namespace is the first path segment after views/ or packages/ (views/user/i18n.js → user, packages/components/i18n.js → components). Packs are aggregated at build time by import.meta.glob, so adding files or folders requires no code change.

Register the namespace inside the page, then call $l('<source text>') directly — never $l('user.<source text>'):

export default {
  created() {
    this.useI18n('user') // Options API
  }
}
// also works inside <script setup>
const { $l } = useI18n('user')

Lookup order for $l(name): namespace registered by the current component → global fallback dictionary (packages/locales/lang/dict.js) → the name itself. useI18n logs a console.warn (non-blocking) when the namespace does not exist.

Call site Usage Namespace
Template / inside a component, this.$l(...) {{ $l('<source text>') }} yes, the one registered via useI18n first
Plain JS outside components (api / utils) window.$l('<source text>') no, global dictionary only

In Chinese mode the source text is returned as-is; in English mode, a missing translation falls back to the source text. antd's own locale is controlled by a-config-provider's locale.

2.8 Theme

Definitions are maintained by the base only: VITE_APP_THEME in packages/config/web-config.js (each set carries color/lightColor/darkColor/borderColor/bgColor); the business only picks one with VITE_APP_THEME_VALUE (blue/green/orange). A VITE_APP_THEME coming from the business or config.json is ignored.

How it takes effect:

  1. antd: a-config-provider tokens (colorPrimary/colorLink).
  2. CSS variables: on startup the selected theme is resolved into the full token set and written to :root (10 primary-family + 11 semantic + 11 neutral tokens, see the table below); the utility classes .s-theme-bg, .s-theme-color, .s-theme-border, .s-theme-border-top, .s-theme-icon-bg are built in.
  3. body class: theme-<VITE_APP_THEME_VALUE> (e.g. theme-blue).
  4. Menu palette: on startup the palette is derived from the primary color (light) or fixed to antd black (dark) and emitted as solid #rrggbb only — no alpha. It is written to :root as --s-menu-bg, --s-menu-sub-bg, --s-menu-text, --s-menu-text-hover, --s-menu-text-active, --s-menu-hover-bg, --s-menu-active-bg, --s-menu-active-text, plus window.$menuTheme (a reactive object carrying the antd Menu tokens and an isLightBg flag).

The menu defaults to light with backgrounds derived from the primary color (orange #f9f1e1 / blue #e1ebf9 / green #e1f9ef). The colors are owned by the base: the business can only pick light or dark via VITE_APP_MENU_THEME; color values written into the business .env / config.json are forced back to the base defaults. Palette derivation, OS light / dark following and the locking mechanism live in 2.18 Menu palette.

In light only the text colors follow the primary hue (blue → #344051, green → #345145); backgrounds stay fixed, so switching VITE_APP_THEME_VALUE keeps the pale blue menu and still holds a contrast ratio >= 4.6. The side menu, the top menu (VITE_APP_MENU_BAR: 'top'), the logo variant and the header text color all share window.$menuTheme.isLightBg.

.my-box {
  color: var(--s-color);
  background: var(--s-bg-color);
}

Full token set (resolved by packages/utils/theme-vars.js into :root on startup; components and business code use var(--s-*) only, never literal colors):

Group Token Default (blue) Notes
Primary family --s-color #1677ff Primary color from VITE_APP_THEME
--s-light-color, --s-dark-color, --s-border-color, --s-bg-color #6495ed, #00008b, #b0c4de, #f0f2f5 Taken straight from the theme
--s-color-hover / --s-color-active #4592ff / #146be6 Hover (+20% white) / active (+10% black)
--s-color-bg / --s-color-bg-hover / --s-color-border #e8f1ff / #d5e7ff / #adcfff Selected tint / hover tint / light border
Semantic --s-color-success, --s-color-warning, --s-color-error, --s-color-info #52c41a, #faad14, #ff4d4f, #1677ff Status semantics, theme independent
--s-color-success-bg, --s-color-warning-bg, --s-color-error-bg #f6ffed, #fffbe6, #fff1f0 Status tints
--s-color-warning-light / --s-color-error-light #ffc069 / #ff7875 Light status variants (error pages)
--s-color-warning-border / --s-color-error-border rgba(250,140,22,.42) / rgba(245,34,45,.42) Translucent status borders
Neutral --s-text-color #262626 Primary text
--s-text-color-regular #595959 Regular text
--s-text-color-secondary, --s-text-color-disabled, --s-text-color-inverse #8c8c8c, #bfbfbf, #ffffff Secondary / disabled / inverse
--s-border-color-base, --s-border-color-light, --s-border-color-split #d9d9d9, #e8e8e8, #f0f0f0 Three border levels
--s-bg-color-container / --s-bg-color-hover #ffffff / #f5f5f5 Container / hover background
--s-mask-color rgba(0,0,0,.45) Mask

Components no longer contain literal colors: primary-related values use the primary tokens, greys use the neutral tokens, statuses use the semantic tokens. New components must follow the same rule — no more #1677ff / #e8e8e8 / rgba(0,0,0,.65).

Adding a theme: append a set to the base VITE_APP_THEME, select it with the business VITE_APP_THEME_VALUE, and antd plus var(--s-*) follow automatically.

2.9 API / page components / others

  • packages/api: login.js (login, getCode, verify, rsaPublicKey, getLoginConfig, ...), common.js, upload.js, workbench.js.
  • packages/pages: login.vue, login-common/LoginForm.vue, workbench.vue, todo.vue, message.vue, 403/404/500.vue, docs.vue, components-doc.vue.
  • Static assets live in packages/static/*, styles in packages/style/*; antd icons, axios, dayjs, moment, pinia, vue-router, vue-i18n, jodit, vue-cropper, vuedraggable, html2canvas, crypto-js, jsencrypt, nprogress, qs, lodash.* and more are already bundled.

2.10 Login / SSO

  • Login page /login/index: account + password. Once failures reach the getLoginConfig policy (enabled + codeThreshold), an image captcha appears (/user/verify); verificationCode is submitted as plain text together with verificationCodeId.
  • SSO callback: when the URL carries a code, the guard calls getCode(code) to exchange it for a token → stores it via $utils.ls → strips the code and does a full page reload (same as the reference project).
  • Related configuration: VITE_APP_CLIENT_ID must equal the client registered in the auth center; the API gateway uses VITE_APP_PORTAL_SERVER_NAME.

Four login themes (VITE_APP_LOGIN_PATH_THEME, 1~4; an unset or invalid value falls back to 1):

packages/pages/login/index.vue only resolves the theme id, passes logo/sysName down and renders the language switcher. Each layout lives in its own page-level component under login-themes/, so they are independent and can be edited separately.

| Id | Component | Layout | | -- | ------------------ | ----------------------------------------------------------------------------------- | | 1 | LoginTheme1.vue | Split screen: login-cover.png + logo + system name on the left, form on the right | | 2 | LoginTheme2.vue | Full-bleed login-cover-right.png, form pinned left (padding-left: 336px) | | 3 | LoginTheme3.vue | Full-bleed login-cover-center.png, form centred (web-config default) | | 4 | LoginTheme4.vue | Dark-blue brand panel + white card, same as the portal ops console (full version) |

Theme 4 capabilities (login-themes/LoginTheme4.vue):

  • Account/password login + remember me (stores LOGIN_ACCOUNT, account only, never the password).
  • Image captcha: shown once failures reach the getLoginConfig threshold; click the image to refresh.
  • Account lock countdown: when the backend returns lockUser (lockEndTime/nowTime) the button switches to a-statistic-countdown and login stays disabled until it ends.
  • "Activate account" entry: visibility is driven by defaultActivateAccount from getSysAccountConfig.
  • "Forgot password" / "QR login": navigate to the built-in /user/forgotPassword and /user/qrCode.
  • Office code: entering via /login/:officeCode stores the code as officeCode in $utils.ls.
  • After a successful login: writes token / USER-TOKEN; when redirect_client_id is present it resolves the client list and hands over to sso.html for client authorization, otherwise it returns to VITE_APP_DEFAULT_PATH.
  • The form column is flex-centred (align-items: safe center + justify-content: center). It deliberately avoids overflow-y: auto: the parent .login-page is overflow: hidden, so scrolling cannot rescue a clipped card; safe center degrades to top alignment when the viewport is too short, so the top of the card is never pushed out of view.

Login helper pages (packages/pages/login/, all meta.public, reachable before login):

Route Component Description
/user/qrCode qr-code.vue QR login: fetches a key via qrLogin/generate, renders with a-qrcode, counts down validity, expired overlay + refresh
/user/forgotPassword forgot-password.vue Four steps: pick method → account info → verify code (gets a temporary token) → set new password; policy from sysPwdConfig
/user/activate activate.vue Four steps: identity check (+captcha) → SMS/email code → set password (strength bar) → completion summary card
/user/login — Redirects to VITE_APP_LOGIN_PATH; used by the "back to login" links on the three pages

Account APIs live in packages/api/account.js (pre-login whitelist chain, gateway VITE_APP_PORTAL_SERVER_NAME):

Method Description
getSysAccountConfig Activation entry switch (sysAccountConfig/listByActivate)
getPwdConfig Password policy (sysPwdConfig/getFirstData)
getLoginQrCodeKey QR login key (qrLogin/generate)
getValidationCodeWithoutToken Send reset-password verification code
checkValidationCodeWithoutToken Verify code → temporary access_token
updatePasswordWithoutToken Reset password with the temporary token (account/password Base64, token via the user-token header)
checkUseInfo Activation identity check
getActivateValidationCode Send activation code
checkActivateValidationCode Verify activation code
activateUpdatePassword Set the password during activation

SSO static assets are now part of the base: the sources live in packages/sso/ (sso.js / sso.html) and ship with the npm package (sso is listed in files, and the build copies dist/sso). Business projects no longer maintain sso files under public/; just add this to vite.config.js:

import ssoPlugin from 'sapit-ui-plus/vite-plugins/sso-plugin.js'
ssoPlugin()

In dev the plugin middleware serves them (registered before the internal middleware, shadowing public with the packaged version). sso.html reads the same-origin localStorage (wrapped by vue-ls) when exchanging the token, so a cross-origin platform SSO cannot be used directly.

⚠️ redirect_uri supports the {code} placeholder; without the placeholder the jump is raw and the code is not exchanged. The platform standard requires ?code={code} — keep that in the portal client's redirectUri, do not "optimize" the placeholder away.

2.11 SImportModal — generic bulk import modal

Three-step import: upload file → data preview (rows editable / deletable) → import result (with exception export). File limits: .xls/.xlsx, ≤ 500KB.

<s-import-modal
  ref="importModalRef"
  :upload-url="IMPORT_UPLOAD_URL"
  :columns="importColumns"
  :apis="importApis"
  :type-select="importTypeSelect"
  @reload="handChange"
/>

<script setup>
importModalRef.value.show() // open the modal (it resets its own state)

const importApis = { templateDownload, importPreview, importData, exportExceptionData }
const importColumns = [{ title: 'Device SN', dataIndex: 'sn', width: 150 }]
// optional: a business-parameter dropdown passed with the import; its value is submitted with every API call via extraKey
const importTypeSelect = computed(() => ({
  options: [{ label: 'Camera', value: '1' }],
  placeholder: 'Select device category'
}))
</script>
props Type Default Description
value Boolean false Visibility (v-model:value)
title String Bulk import Modal title
width String / Number 1000 Modal width
uploadUrl String '' Upload endpoint (full gateway address, e.g. /monitor/DeviceInfo/Uploader)
columns Array [] Preview / result table columns [{ title, dataIndex, width }]
apis Object {} The four import APIs (see below)
typeSelect Object null { options, placeholder, loading }; omit when no business parameter is needed
extraKey String 'deviceTypeId' Field name used to submit the typeSelect value
events Description
update:value Visibility change (v-model)
reload List must be refreshed after a successful import / close
methods (via ref) Description
show() Open the modal and reset its state

API contract (all return a Promise; the component accepts both { code, data } and plain data):

API Input Output
templateDownload { ...extraParams } { url } (the component triggers the download)
importPreview { fileName, ...extra } { dataRow: [] }
importData { list, ...extra } { resultType, snum, fnum, failResult: [] }
exportExceptionData { list, ...extra } { url }
Upload (internal) FormData(file) → uploadUrl { name } / { fileName } (later APIs receive fileName)

⚠️ SImportModal is three-step (upload → preview/edit → result/exception export). If a business project has a single-step import component that imports as soon as a file is chosen (e.g. hy-monitor's views/people/components/ImportModal.vue, views/basicData/components/ImportModal.vue), the two differ in layout, API, events and the contract with the calling page, so they must not be swapped for one another — keep each implementation.

2.12 SDataRangeTreeSelect — data permission scope tree

Selects a data permission scope (organization / campus / unit); internally calls findOfficeList / getOfficeByIds / getSysConfigByCode('dataScope').

<s-data-range-tree-select v-model:value="ids" :auto-sys-config="true" />

Common props: value (array of ids) / multiple / treeCheckable / allowClear / placeholder / maxTagCount / disabledGroup ('1' organization, '2' campus, '3' unit; an array is allowed) / showOnlyOrganization / treeSelectData (pass an array to skip the request) / isDataScopeFilter / autoSysConfig / defaultValue. events: update:value, change (both emit an array of ids).

⚠️ The template hard-codes label-in-value + tree-check-strictly, so antd requires value to be an array of { label, value } objects. Therefore echoing back a value must first convert ids with getOfficeByIds(ids); assigning raw id strings raises an Invalid prop value warning and the input shows bare numeric ids.

2.13 SExtendFieldsForm — dynamic extra field form

The backend delivers field configuration (fillModeConfig is a JSON string containing showType / config) and the front end renders from it.

<s-extend-fields-form ref="extRef" :data="fields" :default-value="values" type="edit" :cols="2" />
<script setup>
// the ref exposes three methods
extRef.value.validate() // Promise<boolean>
extRef.value.clearValidate()
extRef.value.getModel() // [{ fieldCode, value }] (object values are already JSON.stringify'd)
</script>
props Type Default Description
data Array [] Field definitions (fieldCode/fieldName/fillModeConfig)
type String 'add' add / edit / view (view skips validation)
defaultValue Array [] Values echoed in edit mode [ { fieldCode, value } ]
cols Number 2 Columns per row (non-full-width fields take 100/cols%)
labelWidth String auto' Label width

showType values that automatically take the whole row: textarea, upload, and select with config.multiple. Default values are converted per showType: datePicker → dayjs object, number → Number, multi-select select → comma-split array.

2.14 SChooseUser — user picker modal (with data permission)

Modal user picker: organization tree on the left, user list on the right (avatar / name / employee or student number + unit). The search area contains a user-type filter (all / staff / student / external), and it supports single or multiple selection, scroll paging, select-all / invert, and a selected list on the right in multi-select mode. The modal closes automatically after confirming.

How it differs from SUserSelect (the criteria for choosing between them):

Aspect SUserSelect SChooseUser
Shape Read-only input plus an integrated modal Pure modal; visibility controlled by the business
Data permission Tree / list APIs carry no data permission Uses levelOneChildrenWithAuth / levelTwoChildrenWithAuth / findUsersWithAuth, filtered by the logged-in user's permission
User type No filter Built-in staff / student / external filter
Value contract v-model:value binds ids directly (string for single, array for multiple) v-model:value controls visibility; v-model:selectedIds/selectedId bind selected ids; @callback emits the list of selected objects
<s-choose-user
  v-model:value="userScopeVisible"
  v-model:selectedIds="userScopeIds"
  :multiple="true"
  @callback="userScopeCallback"
/>
<script setup>
// confirm (single or multiple): payload = [{ id, name, cover, userid, company, department }] (a single pick is a one-element array)
// cancel / close: payload = undefined
const userScopeCallback = (payload) => {
  if (payload) userNames.value = payload.map((u) => u.name).join(',')
  userScopeVisible.value = false
}
</script>
props Type Default Description
value Boolean false Modal visibility (v-model:value)
title String Select users Modal title
multiple Boolean false Multiple selection (the selected list appears on the right)
searchPlaceholder String Search by name, employee/student number or phone Search box placeholder
required Boolean false When nothing is selected, confirming warns and does not close
selectedIds Array [] Echoed id array for multi-select (v-model:selectedIds); getBUseryIds loads objects
selectedId String '' Echoed id for single select (v-model:selectedId); getUserById loads the object
events Description
update:value Modal closed (both confirm and cancel set it to false, no manual close needed)
update:selectedIds Two-way binding of the selected id array
update:selectedId Selected id in single-select mode
callback On confirm emits the selected objects array; nothing on close

⚠️ All APIs live in the base packages/api/common.js (findUsersWithAuth = /user/users/authorized, etc.), so the business passes none; an empty tree/list in a backend-less preview environment is expected. In the list, userid shows loginName (employee / student number).

2.15 SBelowChoosePosition — position picker modal

Modal position picker (originally from the business project's /components/BelowChoosePosition, now part of the base): the left tree loads the whole tree of "the root node and every unit below it" in one call (getBelowUnit, scope determined by rootId), while the right list queries positions (findJobs); single and multiple selection are supported.

How it differs from the other base selectors: SOfficeSelect/SUserSelect query organizations/users with a lazily loaded left tree, whereas this component queries positions with a fully loaded tree. It does not close automatically after confirming; the business must close it in callback (same behaviour as the source project).

<s-below-choose-position
  v-model:value="visible"
  v-model:selectedIds="positionIds"
  multiple
  :root-id="campusId"
  @callback="onCallback"
/>
<script setup>
// confirm (multiple): payload = { selectedList: [{ id, name, deptName, nameOrCount }] }
// confirm (single): payload = { selected: { id, name, ... } }
// cancel / close: payload = false
const onCallback = (payload) => {
  if (payload && payload.selectedList) {
    names.value = payload.selectedList.map((i) => i.name).join(',')
  }
  visible.value = false // the component does not close on confirm, so close it manually
}
</script>

The props match SChooseUser (title defaults to Select position, searchPlaceholder to Search by position name or code), plus one component-specific prop:

props Type Default Description
rootId String '' Left tree root id, which defines the data scope; changing it reloads the tree, '-1' is used when omitted
methods (via ref) Description
initLeftTreeData(id) Manually reload the left tree
events Description
update:value Set to false only on cancel; confirm does not close the modal
update:selectedIds Two-way binding of the selected position ids (echo uses getPositionByIds)
update:selectedId Single-select id (echo uses getPositionById)
callback Confirm emits { selectedList } / { selected }; close emits false

⚠️ The callback payload shape differs from SChooseUser (an object { selectedList } versus an array) and the close-on-confirm behaviour is the opposite, so the two callbacks are not interchangeable.


2.16 SSkeletonLayout — skeleton layout (title + button group + content)

Added 2026-10-28. A page-level "title bar + action buttons + content area" shell. Same tier as SListLayout / SFormLayout but lighter: no table, no form, no pagination — the content area is entirely up to the slot.

<s-skeleton-layout
  :title="$l('Collection jobs')"
  :buttons="[
    { key: 'add', name: 'Add', icon: true },
    { key: 'remove', name: 'Delete', disabled: true },
    { key: 'export', name: 'Export', icon: 'DownloadOutlined' }
  ]"
  bg-color="#fff"
  @btnCallback="onBtnClick"
>
  <div class="my-content">...</div>
  <template #otherBtns><a-button>Custom</a-button></template>
  <template #other>Footer content</template>
</s-skeleton-layout>
props Type Default Description
title String — Required title bar text
buttons Array [] Button config array, see below
Each buttons item:
Field Type Description
key String Unique key, emitted on click; 'add' makes the button primary by default
name String Button label (passed through $l, so the source Chinese text is fine)
icon String | Boolean String = icon component name (e.g. 'PlusOutlined'); true = look up the built-in iconMap by key; omit for no icon
action String v-action permission code, defaults to key (real permission filtering — unauthorised buttons are removed)
show Boolean Default true; false hides via v-show (keeps layout, still permission-registered)
disabled Boolean Greyed out
type String Overrides a-button's type
slots Description
default Content area (.skeleton-layout-main)
otherBtns Appended to the right of the button group
other Bottom area
events Description
btnCallback Emits the clicked button's key
methods (via ref) Description
— None. Height is allocated by flex; no method call is needed (see below)

Built-in iconMap keys: add / edit / delete / remove / import / export / assign / execute / pause / resume / approve / setting / TopOfType / TOP / synchronize.

Height implementation (revised 2026-10-28): root height:100%; display:flex; flex-direction:column, title bar flex:0 0 60px, content area flex:1 1 auto; min-height:0; overflow:hidden auto, bottom slot flex:0 0 auto. Zero JS, no resize listener — follows window resize / sidebar collapse automatically.

Prerequisite: the parent container must have a definite height. The base BasicLayout already renders router-view with :style="{ height: contentHeight + 'px' }", which falls through to the page root component, so usually nothing extra is needed; a custom height:auto wrapper must be given a definite height.

The old initLayoutHeight() method has been removed, and layoutHeight is no longer exposed (the previous implementation was parentNode.offsetHeight - 76, computed only once on mounted).


2.17 Error pages (301 / 403 / 404 / 500)

The base ships three error pages. One page serves both "the page itself failed" and "an API failed", and the wording is selected by the ?api= query parameter.

Path Component Status sources Accent
/403 pages/403.vue API 403 (no permission), API 301 (address changed), page without permission Orange #fa8c16
/404 pages/404.vue No route matched (catch-all /:pathMatch(.*)*), API 404 Primary color var(--s-color)
/500 pages/500.vue Reachable directly only; API 5xx does not redirect, it still shows a notification Red #f5222d

Where they render: buildErrorRoute() wraps all three under BasicLayout as nested children (children: [{ path: '' }]) — navigation replaces only the content-area router-view, leaving the sidebar, header and footer untouched. The route-miss 404 (catch-all) and the API 404 share the same structure and behave identically.

Login-free: /403, /404 and /500 carry meta.public (an API failure may mean the token is already gone, and the page must not get stuck in the login guard); the catch-all /:pathMatch(.*)* does not — an unauthenticated visit to an unknown URL still goes to login.

API status mapping (packages/utils/request.js):

HTTP status Behaviour Target URL
301 Go to the 403 page with the "API address changed" wording /403?api=<api>&status=301&from=<page>
403 Go to the 403 page with the "no API permission" wording /403?api=<api>&status=403&from=<page>
404 Go to the 404 page with the "API does not exist" wording /404?api=<api>&status=404&from=<page>
Anything else (incl. 5xx) No redirect, a notification is shown as before —

Query parameters:

Parameter Meaning
api Failing API address. Its presence switches to the API wording; page-level failures omit it
status Original status code; 301 gets its own "API address changed" wording
from Source page address (with VITE_APP_BASE_URL stripped), rendered as the "source address" line

Wording matrix:

Source 403 page 404 page
Page (no api) Insufficient page permission Page not found
API (with api) No API permission API does not exist
API 301 API address changed —

The two buttons: "Back to home" uses VITE_APP_DEFAULT_PATH (default /workplace/index); "Back" calls router.back() and falls back to home when there is no history, so the button is never dead.

Skipping the redirect (polling, auxiliary requests — keeps one failing side request from taking over the whole page):

// the third argument accepts { skipErrorPage: true } (also readable from the request meta)
window.$utils.http.post(url, data, { skipErrorPage: true })

Concurrency and fallback: error-page navigation is serialised, last one wins, so a 403 and a 404 arriving together no longer cancel each other. After navigating it re-reads currentRoute to verify the arrival (tolerating a redirect that rewrites the path), retries twice, and only then falls back to a full-page location.replace, so the user always ends up on the error page. When already on the error page with an api parameter the reason is not overwritten — otherwise an auxiliary request fired by the error page itself would replace the real cause.

Changing colors / wording:

  • All wording lives in i18n entries (packages/pages/i18n.js, namespace pages).
  • The 403 and 500 pages each declare --e-color (accent), --e-light-color (light accent) and --e-border-color (dashed border) on their root node, so the business can override them with the same variables; the 404 page uses the primary --s-color and follows VITE_APP_THEME_VALUE.
  • Every root node is height:100%; overflow:hidden, and the decorative glows are clipped by __deco, so overflow only scrolls inside the card and never creates a page scrollbar.

The error pages sit under BasicLayout, so the layout still fires the getSystemIcon and message-count requests. If those are auxiliary endpoints that can fail on their own, give them skipErrorPage: true; otherwise a 403 can bounce to the 404 page.

2.18 Menu palette (side / top)

The palette is either derived from the primary color (light) or a fixed antd black (dark). On startup packages/utils/menu-theme.js emits solid #rrggbb values (no rgba / alpha), writes them to :root as --s-menu-* and exposes window.$menuTheme (antd Menu tokens + isLightBg). Switching VITE_APP_THEME_VALUE re-derives the whole menu — it is no longer a hard-coded pale blue.

Part CSS variable light (orange default) light (blue) light (green) dark
Top-level background --s-menu-bg #f9f1e1 #e1ebf9 #e1f9ef #001529
Submenu panel --s-menu-sub-bg #fcf9f2 #f2f7fc #f2fcf8 #000c17
Hovered item --s-menu-hover-bg #f4e4c8 #c8daf4 #c8f4e1 #1a2c3e
Selected item --s-menu-active-bg #fff1d6 #dae9ff #d6f4e7 #FFA500 (primary)
Normal text --s-menu-text #514734 #344051 #345145 #d7dde6
Hover text --s-menu-text-hover #825d17 #1f5aad #14714a #ffffff
Selected text --s-menu-text-active, --s-menu-active-text #8b6318 #1a4d93 #157950 #ffffff
Group title text $menuTheme.groupTitle #8a7a5c #5c6f8a #5c8a77 #737e89
isLightBg — true true true false

The three light columns are one set of rules evaluated against different primary colors (VITE_APP_MENU_BG: 'theme'): hue from the primary, saturation capped by _BG_SATURATION, lightness from _BG_LIGHTNESS, and text colors solved for a contrast ratio >= 4.6. dark fixes the antd black background and ignores VITE_APP_MENU_BG; only the selected item follows the primary color.

Following the OS light / dark setting

VITE_APP_THEME_FOLLOW_SYSTEM (default true) is handled by packages/utils/color-scheme.js: it listens to prefers-color-scheme; when the OS goes dark it immediately recomputes the menu in dark, swaps the neutral tokens to their dark variants and adds scheme-dark to body — and restores everything when the OS goes light. No reload needed.

Token Light Dark
--s-text-color #262626 #e8e8e8
--s-text-color-secondary #8c8c8c #a6a6a6
--s-bg-color-container #ffffff #1f1f1f
--s-border-color-base #d9d9d9 #3d3d3d
--s-color-warning-bg #fffbe6 #2b2413 (darkened)

⚠️ The dark tokens only affect places that read var(--s-*). Hard-coded background: #fff in business pages will not darken on its own — switch those to var(--s-bg-color-container), or write your own overrides under body.scheme-dark. With the switch off (VITE_APP_THEME_FOLLOW_SYSTEM: false) the scheme stays as configured by VITE_APP_MENU_THEME; businesses that already set dark are unaffected.

The business picks the mode, never the colors

Config Default Business can override Notes
VITE_APP_MENU_THEME light Yes light derived from the primary / dark black
VITE_APP_MENU_BAR left Yes left sidebar / top top bar (a layout option)
VITE_APP_THEME_FOLLOW_SYSTEM true Yes Whether to follow the OS prefers-color-scheme
VITE_APP_MENU_BG / _SUB_BG / _HOVER_BG / _ACTIVE_BG / _TEXT / _TEXT_HOVER / _TEXT_ACTIVE / _GROUP_TITLE / _BG_LIGHTNESS / _BG_SATURATION / _BG_ACTIVE_MIX see 4.2 No 11 color / tuning keys, always forced back by the base

Locking mechanism: packages/config/web-config.js exports menuColorKeys (the 11 keys marked "No" above); packages/index.js force-writes the base defaults for those keys onto env inside registerGlobalConfig, after loadRemoteConfig() has merged. So menu colors written in the business .env, src/config/web-config.js or the deployed config.json have no effect, and every business project matches the base demo exactly.

To verify the lock yourself: put "VITE_APP_MENU_BG": "#ff0000" into the business config.json and reload — the menu still uses the palette derived from the primary color.

Changing a whole palette (base-side work, not something a single business can do):

  1. Values: edit the VITE_APP_MENU_* defaults in packages/config/web-config.js;
  2. Derivation: the light branch lives in packages/utils/menu-theme.js (the dark branch is a fixed black system and ignores VITE_APP_MENU_BG);
  3. CSS fallback: update the --s-menu-* variables in packages/style/theme.less;
  4. Rebuild the base → business projects update sapit-ui-plus (see 4.1).

Notes

  1. VITE_APP_MENU_BG: 'dark' under light is ignored with a warning (a black background belongs to dark mode); the pale palette is still used.
  2. Per-part color overrides only apply to light; dark stays pure black, so a "black background + pale blue submenu" mix cannot happen.
  3. Do not hard-code menu colors such as #001529 or rgba(255,255,255,.1) in business styles — use var(--s-menu-*).
  4. The side menu, the top menu (VITE_APP_MENU_BAR: 'top'), the logo variant and the header text color all read window.$menuTheme.isLightBg, not VITE_APP_MENU_THEME — OS dark-mode following rewrites it, so always branch on this field.
  5. window.$menuTheme is a reactive object: light / dark switching only mutates its properties (same reference), so SSideMenu's computed reading window.$menuTheme.token re-evaluates and the antd Menu tokens follow without any manual refresh.

2.19 SListCardLayout card list layout

Same skeleton as SListLayout (title bar + filter area + pagination) with the table replaced by a card grid. Cards are square with an 8px radius, and the header / body / footer are all slot-driven.

<s-list-card-layout title="Card list" :column="5" :load-data="loadData" @card-action="onCardAction">
  <!-- header: falls back to item.title; if that is empty the header is not rendered -->
  <template #cardHeader="{ item }">{{ item.title }}</template>

  <!-- default: the body, fully custom (scope has item / index) -->
  <template #default="{ item, index }">
    <div>Name: {{ item.name }}</div>
  </template>

  <!-- footer: omitted = default edit / delete buttons; provided = fully replaces them -->
  <template #cardFooter="{ item }">
    <a-button type="link" size="small" @click="edit(item)">Edit</a-button>
  </template>
</s-list-card-layout>
Prop Type Default Description
title String required Title bar text
column Number / String 5 Cards per row, applied as repeat(column, 1fr)
loadData Function required ({ pageNo, pageSize }) => { list, total }
rowKey String / Function 'id' Card key; falls back to the index when missing
buttons Array add / batch remove / import / export Same shape as SListLayout (name/key/show/type/icon/api)
showPagination Boolean true Whether to show pagination
pSize Number / String 20 Default page size
pageSizeOptions Array ['10', '20', '40', '80'] Page size choices
Slot Scope Description
default { item, index } Card body, fully custom
cardHeader { item, index } Card header; falls back to item.title, and renders nothing when both are empty
cardFooter { item, index } Card footer; omitted = default edit / delete, which emit cardAction
filter / filterMore / desc / tabs / tree / empty / other / otherBtns same as SListLayout Identical to the ordinary list layout

Events: cardAction(key, item, index) (key is edit / delete), btnCallback(key, selections), reset. The ref exposes reload(forceFirst) / fetchList().

Style conventions (all component-scoped, class names prefixed with s-card- so business card-* classes are never hit):

Class Description
s-card-grid display:grid + gap:12px, column count from column
s-card-item aspect-ratio: 1/1 square + border-radius: 8px
s-card-header Header, single line with ellipsis
s-card-body Body, fills the remaining height, overflow clipped inside
s-card-footer Footer button area, min-height:36px, space-between
s-card-empty Empty state, grid-column: 1 / -1 spans the whole row
s-card-pagination Pagination bar; its height is subtracted from the card area, so no double scrollbar

Response normalisation: rows come from list (or data), the total from total / pagination.total / totalCount, the current page is written back from pageNo / pageNum / pagination.current. A failed request only logs a console.warn and clears the list instead of spinning forever. Changing the page size is handled once in change, so one action never fires two requests.

2.20 SSuperListLayout advanced list (column settings + advanced filter)

Adds two drawers on top of SListLayout: "advanced table" for columns and "advanced search" for conditions. Both use a draft + confirm model — the drawer edits a copy, "OK" writes back and refreshes the table, "Close" discards the draft, so a single click never re-renders the table.

<s-super-list-layout title="Advanced list" :columns="columns" :load-data="loadData" />
Prop Type Default Description
title String required Title bar text
columns Array [] Column config, see below
loadData Function required Fetcher; receives the filter result
rowKey String / Function 'id' Row key
buttons Array add / batch remove / import / export Same shape as SListLayout
isSelection Boolean false Show the selection column
showPagination Boolean true Show pagination
pSize Number / String 20 Default page size

Column config adds two fields on top of SListLayout:

Field Description
filterConfig Only columns with it appear in "advanced search"; without it the column can be displayed but not filtered
width px / plain number → applied as-is and seeded into the width input of the column drawer; % → header-only, the pixel input stays empty

filterConfig keys: filterType / filterApi / filterData / props / precision / step / minValue / maxValue / length / startDate / endDate. filterType: INPUT text, INT, FLOAT, DATE, DATETIME, SINGLE_SELECT, MULTIPLE_SELECT, GANDER (gender), IS (boolean), USER, OFFICE. Select-type options come from filterData first; only when it is missing does filterApi run once and backfill.

Column settings (SettingColumns)

  • Show / hide: ticking edits the draft; only after "OK" are show === false columns dropped from the table (they can still be filtered);
  • Freeze / unfreeze: the original freeze side of each column is remembered, so unfreezing then freezing restores the previous left / right; the action column (action) is always right and disabled;
  • Width: a px or plain-number width is rounded and seeded into the input; a 20% value is not seeded; clearing the input restores "auto";
  • "OK" writes the columns back and closes the drawer; "Reset" restores the columns passed by the caller; "Close" discards the draft.

Advanced filter (SettingFilter)

  • Filterable fields = columns with filterConfig (a hidden column can still be filtered);
  • Operators narrow by type: text (INPUT or no type) allows includes / excludes / equal / notequal / null / notnull; select, number and date keep only equal / notequal / null / notnull;
  • Switching the field resets the operator for the new type (text defaults to "contains", everything else to "equals");
  • null / notnull need no value; any other row without a value is dropped on submit, so empty conditions never reach the backend.

The fetch payload becomes:

loadData({
  pageNo,
  pageSize,
  filterMode, // 1
  filterConditions: [{ dataIndex, equals, value }],
  [dataIndex]: value // single-value equal / includes conditions are also flattened
})

Single-value equal / includes conditions are additionally flattened to a same-named field (params[dataIndex] = value), so the backend can read them directly without parsing filterConditions.

2.21 STab — horizontal tab bar (arrows appear only when the tabs overflow)

A single horizontal row of tabs. Left/right arrows appear only when the tabs do not fit, and the bar can be dragged horizontally with the left mouse button.

<!-- option 1: pass an array, the component renders the tabs -->
<s-tab v-model:activeKey="active" :tabs="tabs" @change="onChange" />

<!-- option 2: write <s-tab-item> yourself (for custom tab content) -->
<s-tab v-model:activeKey="active">
  <s-tab-item value="1">Task config</s-tab-item>
  <s-tab-item value="2"><span>Execution log</span><a-badge :count="3" /></s-tab-item>
</s-tab>

<!-- no activeKey at all: defaultActiveKey wins, otherwise the first tab is selected -->
<s-tab :tabs="tabs" default-active-key="2" />
Item Description
v-model:activeKey Current value, String/Number. Leaving it empty (or '') still selects something — see the next row
defaultActiveKey Default value used when activeKey is absent or empty; if both are absent the first tab is selected
tabs [{ label, value }]; map other field names with tabKey (default { label: 'label', value: 'value' })
tabKey Field mapping, same convention as SFormLayout / SSkeletonLayout
stepRatio Screens to scroll per arrow click when already at the first/last tab, default 0.6
@change (key, item); item is undefined in slot mode
Slot Default slot holds s-tab-item; once used, tabs is ignored
expose syncArrow() / scrollToActive() / scrollRef

Interaction rules

Case Behaviour
Tabs fit No arrows rendered, tabs fill the row
Tabs overflow Left/right arrows appear
Click right arrow Selects the next tab and scrolls it into view; on the last tab it degrades to "scroll one screen"
Arrow disabled Neither the previous/next tab nor further scrolling is available
Mouse wheel Vertical wheel scrolls horizontally, the page does not move
Mouse drag Hold the left button and drag to pan the bar (only when overflowing); a move beyond 5px counts as a drag, so click-to-switch never fires by accident. Hovering shows no grab cursor — it turns into a grabbing hand only while the button is pressed
Touch Not intercepted — native horizontal scrolling and momentum are kept
Keyboard Left/right arrow keys switch tabs once a tab has focus

The bar only renders the tab bar, not the panes. Render the content yourself from activeKey — use v-show rather than v-if, otherwise component instances inside hidden tabs are destroyed (permission pages that must read every tab's selection depend on this).

Colours are derived from the theme (--s-color); override --s-tab-color / --s-tab-active-color / --s-tab-disabled-color on a wrapper to tune them without touching the component.

3. Layout and height rules

This chapter is a mandatory contract for the base's internal layout components. Business pages only use the layouts and never compute heights themselves; any new layout component must satisfy these rules first.

3.1 Heights: prefer CSS flex fill; when dynamic calculation is needed, follow the three constraints

Revised 2026-10-28: the old title "never compute heights via JS subtraction" is deprecated. When a business content area needs its own scrollbar, the height should be computed dynamically — it just has to follow the constraints below instead of copying magic numbers per page.

The wrong way (both SListLayout and SFormLayout did this early on):

// ❌ compute the main area height by subtracting offsetHeight values
this.layoutHeight = this.$refs.layout.offsetHeight - toolsH - footerH - tabsH - 16

Why it is always wrong: offsetHeight reads the current rendering result, and that result depends on the height you are about to write — a circular dependency. Symptoms:

  • with less than a full page of data the pagination floats in the middle, leaving 15–588px of empty space at the bottom;
  • the table/form area overflows its container by 1–N px, adding an extra page scrollbar;
  • changing one magic number (e.g. tpH = 103) skews every other page.

Preferred (zero JS): parent height:100% + display:flex; flex-direction:column, main area flex:1 1 auto; min-height:0; overflow:auto, footer bar flex:0 0 auto. This covers the vast majority of list and form pages.

When dynamic JS calculation is needed (the content area must scroll, or its height follows the window / sibling nodes): it is allowed and recommended, but must satisfy three constraints:

  1. One place only: a single calcXxxHeight() per layout, never a magic number per page
  2. Follow the container: recalculate with ResizeObserver on the parent container, not just window.resize
  3. Never read $parent.$el: it breaks as soon as the parent DOM changes — use a ref on your own container

Still forbidden: subtracting the offsetHeight of the very ancestor whose height you are about to write — a circular dependency. Read only values that do not depend on your own height (window.innerHeight, the height of a fixed header/footer node).

3.2 The table fill chain (what keeps pagination pinned to the bottom)

STable's body gets its remaining height through flex, and a single missing level in the chain prevents the fill:

.table-content {
  flex: 1;
  display: flex;
  flex-direction: column;
  min-height: 0;
}
.tabs-wrap {
  flex: 0 0 auto;
}
.table-container {
  flex: 1 1 auto;
  min-height: 0;
  display: flex;
  flex-direction: column;
}
.table-wrapper {
  flex: 1 1 auto;
  ...;
} /* STable's root node — omit it and the whole chain breaks */
.ant-table-wrapper {
  flex: 1 1 auto;
  ...;
}
.ant-spin-nested-loading .ant-spin-container .ant-table .ant-table-container {
  margin-left: 10px;
} /* indent the table with margin, not padding */
.ant-table-header {
  flex: 0 0 auto;
}
.ant-table-body {
  flex: 1 1 auto;
  min-height: 0;
  max-height: none !important;
}
.ant-table-pagination {
  margin-bottom: 0;
  flex: 0 0 auto;
} /* one margin off is a 15–16px gap */

Key points:

  1. .table-wrapper must not be missed — it is STable's root node; measurement shows the body will not fill without it;
  2. the max-height written by scroll.y must be overridden with none !important, otherwise it fights flex;
  3. pagination needs margin-bottom: 0, otherwise a permanent margin separates it from the container edge;
  4. indent the table with :deep(.ant-table-container){margin-left:10px}, never padding-left (it distorts the body width calculation).

3.3 The .tools header bar is uniformly 60px

Every layout's .tools (title + button bar) is:

.tools {
  height: 60px;
  display: flex;
  justify-content: space-between;
  align-items: center;
  padding: 0 16px;
  box-sizing: border-box;
  border-bottom: 1px solid #f0f2f5;
}
.list-filter-wrap {
  padding: 10px 16px;
  box-sizing: border-box;
}

⚠️ If the .tools height ever changes, the subtrahend in every layout's initTable() (e.g. - 76) must change with it, otherwise every list page in the product skews at once.

3.4 Form layout SFormLayout

.form-layout fills with the same flex approach; initStyle() only computes the footer width (the collapses + anchor scenario must dodge the right-hand anchor) and no longer computes heights:

.form-layout {
  height: 100%;
  overflow: hidden;
  :deep(.ant-spin-nested-loading),
  :deep(.ant-spin-container) {
    /* a-spin's wrappers must each fill, otherwise form-layout cannot resolve its height */
    height: 100%;
    display: flex;
    flex-direction: column;
    min-height: 0;
  }
}
.tools,
.step-wrap,
.tabs-wrap,
.modal,
.form-fixed-footer {
  flex: 0 0 auto;
}
.form-layout-main {
  flex: 1 1 auto;
  min-height: 0;
  overflow: hidden auto;
}
.form-fixed-footer {
  height: 60px;
}

Multi-column and full-row items (full)

The a-form inside SForm and the content area of SCollapsesItem both use display:grid; grid-template-columns: repeat(column, 1fr). With more than one column, give the child a full prop to make it span the whole row (implemented as grid-column: 1 / -1):

<!-- 3-column form, the remark spans a full row -->
<s-form :column="3" :model="form">
  <s-form-item label="Name" name="name"><a-input /></s-form-item>
  <s-form-item label="Code" name="code"><a-input /></s-form-item>
  <s-form-item label="Remark" name="remark" full><a-textarea /></s-form-item>
</s-form>

<!-- 2-column collapse group -->
<s-collapses>
  <s-collapses-item title="Basic info" :column="2">
    <s-form-item label="Name" name="a"><a-input /></s-form-item>
    <s-form-item label="Age" name="b"><a-input /></s-form-item>
    <s-form-item label="Address" name="c" full><a-input /></s-form-item>
  </s-collapses-item>
</s-collapses>

Full-row filter item (full on SFilterItem)

SFilterWrap is a display:flex; flex-wrap:wrap; gap:10px container, and each item's width comes from width (px, default 280). Adding full makes that item take the whole row (100% / flex: 1 1 100%), and the following items wrap onto the next line:

<s-filter-wrap>
  <s-filter-item label="Name"><a-input /></s-filter-item>
  <s-filter-item label="Status"><a-select /></s-filter-item>
  <!-- long field, give it its own row -->
  <s-filter-item label="Remark" full><a-textarea /></s-filter-item>
</s-filter-wrap>
  • full wins over width: when both are set, width is ignored.
  • label still uses labelWidth (default 70); the rest goes to the content area, so a-select stretches automatically.
  • Only SFilterItem has this prop; SFilterWrap needs no column count.
Prop Type Default Belongs to
full Boolean false SFormItem, SCollapsesItem, SFilterItem
  • With a single column 1 / -1 is just the whole row, so switching a form between 1 and N columns needs no code change.
  • column is a prop of SCollapsesItem, not of SCollapses; putting it on <s-collapses column="2"> does nothing.
  • full is declared as a prop on SFormItem and SFilterItem, so it is not forwarded onto the inner a-form-item and does not trigger an antd warning.
  • Implementation differs: SFormItem / SCollapsesItem use grid-column: 1 / -1, SFilterItem uses flex-basis: 100%; usage is identical.

Filter area shell (SFilterToolbar)

When you need only the filter area (no table, no layout shell), use SFilterToolbar: the main filter row is always visible, with a "More / Collapse" toggle and a condition reset. It behaves exactly like the filter / filterMore slots of SListLayout / SListBasicLayout, but it already wraps SFilterWrap, so you only write SFilterItem.

<s-filter-toolbar @reset="reset" @toggle="onFilterToggle">
  <template #filter>
    <s-filter-item label="Keyword" :width="320"><a-input v-model:value="query.keyword" /></s-filter-item>
    <s-filter-item label="Status" :width="220"><a-select v-model:value="query.status" /></s-filter-item>
  </template>
  <!-- optional: without this slot the "More / Collapse" button is not rendered -->
  <template #filterMore>
    <s-filter-item label="Dimension" full><check-box v-model:value="query.scopeIds" /></s-filter-item>
  </template>
</s-filter-toolbar>
Slot Description
filter Main filter row, always visible
filterMore Collapsed row, toggled via v-show; the button is hidden when omitted
Event Payload Description
reset — Reset clicked; the parent clears its params and reloads on its own
toggle isMoreFilter Collapse state changed; no handling needed when the table area uses STableToolbar (it observes its own container), only custom tables must recompute
  • The "More / Collapse" button sits right next to the filter content (left-aligned), while the reset button is pushed to the far right — identical to .filter-more-btn / .reset-wrap in SListLayout.
  • The filter area's height changes on collapse. Prefer STableToolbar for the table area: it observes its own container with ResizeObserver and recomputes the body height automatically, zero config for the parent.
  • defineExpose: isMoreFilter, toggleFilter(), filterReset(), collapse() (collapse proactively when switching tabs).

Table area shell (STableToolbar)

The fixed partner of SFilterToolbar: wraps STable + pagination + auto-fitted body height, so business pages never implement the "content area − filter − header − pagination" math and never produce a page-level scrollbar.

<!-- the parent only handles vertical layout; no flex / height needed on the table area -->
<div class="page">
  <s-filter-toolbar @reset="reset">
    <template #filter>...</template>
    <template #filterMore>...</template>
  </s-filter-toolbar>

  <s-table-toolbar ref="tableToolbar" row-key="id" :columns="columns" :data="page" :page-size="10">
    <!-- cell slots follow SListLayout: the column dataIndex is the slot name -->
    <template #ruleName="{ record }">
      <a @click="detail(record)">{{ record.ruleName }}</a>
    </template>
    <template #action="{ record }">
      <a @click="edit(record)" v-action="'edit'">Edit</a>
    </template>
  </s-table-toolbar>
</div>
.page {
  height: 100%;
  min-height: 0;
  display: flex;
  flex-direction: column;
}
Prop Default Description
columns / data — Same as STable; data is required
rowKey 'id' Same as STable
pageSize 10 Same as STable
size 'middle' Same as STable
scrollX '100%' Horizontal scroll; the body y is computed internally and a parent-supplied scroll is ignored
tableHeight 300 Initial scroll.y; the real height comes from the flex layout, so the parent normally omits it
  • All other attributes are forwarded as-is to STable.
  • Cell slots follow SListLayout exactly: the column dataIndex is the slot name, receiving { text, record, index, column }. Columns without a matching slot render their raw value. Non-column slots (#headerCell, #expandedRowRender, #emptyText, ...) are still forwarded.
  • Do not use #bodyCell: the component already occupies it for column dispatching, so a business-provided #bodyCell is ignored and that column renders empty (this is exactly what made an action column "disappear").
  • Height is handled by pure flex, no arithmetic: root → .table-wrapper → .ant-table-wrapper → .ant-spin-container → .ant-table → .ant-table-container are all flex:1 1 auto;min-height:0; header/pagination are flex:0 0 auto; body is flex:1 1 auto;max-height:none!important. The container is overflow: hidden, so it never pushes a page-level scrollbar.
  • Viewport changes (expanding filterMore, switching tabs, window resize, collapsing the sidebar) follow the layout automatically; the parent needs no onFilterToggle.
  • defineExpose: resize() (manual recompute), refresh(deleteFlag) (forwards STable.refresh and recomputes pagination height), reload(), tableRef, scrollY.
  • The parent root must provide a sized vertical flex container (height:100%; display:flex; flex-direction:column); the component takes the remaining space via flex: 1 1 0%.

3.5 Uniform left tree container height (.s-side-tree)

The .side of SListLayout / SListTableTreeLayout / SListCardLayout all use padding: 10px (all four sides), so the tree container height must equal ".side box height − top/bottom padding (20px)", otherwise you get double scrollbars or a clipped tree.

The rule lives in the global packages/style/tree.less under .s-side-tree (a unique extra class on .side, so a generic name cannot be overridden by business styles); writing a copy inside a business page's scoped style is forbidden. It covers two tree sources:

  • ① a standard <s-tree>: the root is .s-tree-common, height:100%;
  • ② a native <a-spin><a-tree>: each level is stretched (.ant-spin-container → .ant-tree → .ant-tree-list → .ant-tree-list-holder) and .ant-tree-list-holder takes overflow-y:auto.

⚠️ Branch ② must start from .s-side-tree with >, it must not be written as a descendant selector — STree also renders .ant-tree internally and a descendant selector would hit branch ①.

3.6 STree self-sizing and horizontal ellipsis

STree's height prop default must be undefined (never a hard-coded 300):

height: { type: Number, default: undefined }

Reason: antd's Tree turns height into an inline max-height:300px on the virtual-list holder, which clips the tree and adds an inner scrollbar.

Horizontal text never wraps, overflows into an ellipsis, and the width follows the parent — these structural rules now live in one place, packages/style/tree.less. Components and business pages must not keep scoped copies:

/* packages/style/tree.less (excerpt) */
.s-tree-common {
  height: 100%;
  width: 100%;
  overflow-x: hidden;
  overflow-y: auto;
}
.ant-tree,
.ant-tree-list,
.ant-tree-list-holder,
.ant-tree-list-holder-inner {
  width: 100%;
  min-width: 0;
}
.ant-tree-node-content-wrapper {
  min-width: 0;
  overflow: hidden;
}
.ant-tree-title,
.ant-tree-title > .node-title {
  display: block;
  width: 100%;
  overflow: hidden;
  white-space: nowrap;
  text-overflow: ellipsis;
}

.node-title is a generic class name, so the global rule is scoped to .ant-tree-title > .node-title and cannot leak into business code.

3.7 Unified tree style file and theme variables (packages/style/tree.less)

All tree styles live in that single file, pulled in by common.less via @import './tree.less'. The rules previously spread over STree.vue (scoped), SBelowChoosePosition.vue (scoped copy) and common.less (global) have all been folded in.

Covered tree types:

Type Selector root Used by
Directory / plain tree (a-directory-tree, a-tree) .s-tree-common, .ant-tree* STree, SBelowChoosePosition, native <a-tree> in business pages
Tree-select dropdown (a-tree-select) .s-tree-select-popup STreeSelect, SDataRangeTreeSelect (popup-class-name)
Sidebar tree container height .s-side-tree SListLayout / SListTableTreeLayout / SListCardLayout

Every colour and size is a --s-tree-* variable; the defaults equal the previous hard-coded values, so the visuals are unchanged:

Variable Default Meaning
--s-tree-node-height 30px Node row height (dropdown uses it too)
--s-tree-node-line-height 32px Tree title line height
--s-tree-node-padding-x 4px Dropdown node horizontal padding
--s-tree-row-gap 4px Row gap (leaves a seam in the row background)
--s-tree-node-radius 8px Row corner radius (hover + selected, painted on ::before)
--s-tree-switcher-color #000000a6 Expand arrow colour
--s-tree-hover-bg var(--s-color-bg) Row hover background, follows the theme primary colour (primary mixed with 90% white; dark mode switches to a primary-based dark tone)
--s-tree-selected-bg var(--s-color, #1677ff) Selected row background, already follows the theme primary colour
--s-tree-selected-text #fff Selected row text / arrow colour
--s-tree-directory-selected-bg #bae7ff Directory-tree selected row (antd blue-2)
--s-tree-directory-selected-text #000000a6 Directory-tree selected text colour
--s-tree-icon-color #fff Node type icon glyph colour
--s-tree-icon-bg transparent Default node icon background
--s-tree-icon-bg-g / -c / -d #a9a9f5 / #d3b403 / #f09191 Node icon G/C/D backgrounds

Override per theme instead of touching the components:

/* pure CSS theme: the base already puts theme-xxx on body (see 2.8) */
body.theme-green {
  --s-tree-selected-bg: #00b96b;
  --s-tree-directory-selected-bg: #d9f7e9;
  --s-tree-directory-selected-text: #1f1f1f;
}

/* global size tweak */
:root {
  --s-tree-node-height: 32px;
  --s-tree-row-gap: 6px;
}

Two caveats:

  1. --s-tree-selected-bg defaults to var(--s-color, #1677ff), so it follows the theme primary colour automatically; the light variant --s-tree-directory-selected-bg still defaults to antd blue-2 — override it explicitly if it should follow.
  2. Variables hold a colour/length only, never a whole declaration (e.g. --x: background:red).

3.8 The iron rule for diagnosing rendering issues

Rendering/height problems must be measured on the real page after logging in, using puppeteer to read offsetHeight/offsetLeft/box metrics — never guess the root cause by reading code statically.

// measure: container height, main height, bottom bar offset, document overflow
const r = await page.evaluate(() => {
  const q = (s) => document.querySelector(s)
  const box = (s) => {
    const el = q(s)
    if (!el) return null
    const b = el.getBoundingClientRect()
    return { h: el.offsetHeight, top: Math.round(b.top), bottom: Math.round(b.bottom) }
  }
  return {
    container: box('.list-layout-main'),
    tableContent: box('.table-content'),
    pagination: box('.ant-table-pagination'),
    docOverflowY: document.documentElement.scrollHeight - document.documentElement.clientHeight
  }
})

Acceptance criteria (all must be 0):

Metric Pass condition
documentOverflowY 0 (no page scrollbar)
pagination.bottom minus container bottom 0 (pagination sits exactly at the viewport bottom)
table body overflow beyond the container 0

Spot-check several viewports (1920×1080 / 1600×900 / 1440×900 / 1366×768 / 1280×720 / 2560×1440); the change is only done when all of them pass.


4. Build and configuration

4.1 Build and release

npm run dev      # base local development
npm run build    # lib build + copy docs/vite-plugins/package.json into dist + git push
npm run lint

The base build does not drop console ($utils/i18n debug output is controlled at runtime by VITE_CONFIG_sapit-base-template); only business builds drop it.

Output: entry ./packages/index.js, vue external, output dist/lib, and the bundle contains the entry dependency graph (not the whole project); package.json declares files: ["lib","docs","vite-plugins"].

4.2 Configuration sources and priority

base defaultEnv  <  business web-config.js  <  .env.[sapit-base-template] (written into config.json at build time)  <  deployed config.json (runtime override)
  • web-config.js: may hold defaults or import.meta.env.VITE_APP_*;
  • .env / .env.[sapit-base-template]: one set per environment (dev/test/uat/prod), written into config.json by the business vite.config.js;
  • config.json: at the site root (or <base>config.json for sub-path deploys), fetched and merged by loadRemoteConfig() at startup, editable after deployment without rebuilding; values in .env are strings and the base normalizes "true"/"false" to booleans.

Common switches (the business may override them; checks use !== false, so an unset value keeps the base default):

Option Default Description
VITE_APP_FOOTER_VISIBLE false Whether to show the footer
VITE_APP_MESSAGE_VISIBLE true Whether to show the message bell at the top right (set false to hide)
VITE_APP_SOCKET_URL ws://127.0.0.1:8080/websocket Socket address: protocol + host + port only, no /apig/ or any path; empty or / means same origin; the local placeholder is skipped automatically outside a local machine
VITE_APP_SOCKET_PATH /apig/ws/websocket socket.io handshake path, must match the backend (the only place the service path is defined)
VITE_APP_LANG_ENABLE false Whether internationalization is enabled
VITE_APP_MENU_BAR left Menu layout: left / top (business may override)
VITE_APP_MENU_THEME light Menu palette mode: light derived from the primary color / dark black (business may override)
VITE_APP_THEME_FOLLOW_SYSTEM true Follow the OS light / dark setting (prefers-color-scheme): dark menu + dark neutral tokens, applied at runtime without reload (business may override)
VITE_APP_MENU_BG theme Locked by the base: light top-level background; theme follows the primary color (default) / fixed #RRGGBB
VITE_APP_MENU_BG_LIGHTNESS 93 Locked by the base: top-level lightness 0-100
VITE_APP_MENU_BG_SATURATION 66 Locked by the base: saturation ceiling 0-100
VITE_APP_MENU_BG_ACTIVE_MIX 16 Locked by the base: share of the primary color in the selected background 0-100
VITE_APP_MENU_SUB_BG empty Locked by the base: submenu panel background; empty = derived from the primary hue
VITE_APP_MENU_HOVER_BG empty Locked by the base: hovered item background; empty = derived from the primary hue
VITE_APP_MENU_ACTIVE_BG empty Locked by the base: selected item background; empty = primary mixed with white (share set by _BG_ACTIVE_MIX)
VITE_APP_MENU_TEXT empty Locked by the base: normal text color; empty = derived from the primary hue
VITE_APP_MENU_TEXT_HOVER empty Locked by the base: hover text color
VITE_APP_MENU_TEXT_ACTIVE empty Locked by the base: selected text color
VITE_APP_MENU_GROUP_TITLE empty Locked by the base: group title color

The 11 rows marked "locked by the base" are force-rewritten to the defaults above even when set in the business .env, src/config/web-config.js or the deployed config.json; the business only decides VITE_APP_MENU_THEME (which palette) and VITE_APP_MENU_BAR (sidebar / top bar). Mechanism and both palettes: 2.18.

There is one socket connection for the whole site (packages/utils/socket.js, a singleton — same as the source project registering VueSocketIO once). Message badge and QR-code login share the same address and the same path, separated only by event names:

Feature Emits Listens to Module
Top-right message badge sendUserId (userId) wsEvent packages/utils/message-socket.js
QR-code login QRCodeKey (qrId) QRWsEvent packages/utils/qr-login-socket.js

Badge logic: on entering the system it calls message/center/counts for totalCount, and afterwards every wsEvent pushed over the socket triggers a refetch. The business registers nothing extra — just point VITE_APP_SOCKET_URL / VITE_APP_SOCKET_PATH at the gateway.

Putting a path into VITE_APP_SOCKET_URL breaks the handshake: socket.io treats the URL path as the namespace (io('http://h:50001/apig/') → namespace /apig/), the server answers Invalid namespace, the WebSocket opens but the socket never connects and no connect_error is raised. The base strips the path in resolveSocketUrl as a fallback, but the config should still be written correctly.

4.3 Starting a business project (npm start)

A business project's (sapit-base-template) npm start runs the bundled script refresh-sapit-base-template.ps1:

  1. remove node_modules/.vite, node_modules/sapit-ui-plus and the lock files (package-lock.json/yarn.lock/pnpm-lock.yaml/node_modules/.package-lock.json);
  2. npm install to pull the latest published sapit-ui-plus;
  3. run npm run dev automatically.

Purpose: clear the dependency cache, update business dependencies and start in one step. You can also double-click refresh-sapit-base-template.cmd; -NoStart only updates without starting. This command is normally needed only when the base project has been updated.

5. Business project integration

5.1 Install

{ "dependencies": { "sapit-ui-plus": "git+http://192.168.200.4:6110/sapit/sapit-ui-plus.git" } }

5.2 Entry main.js

import { createApp } from 'vue'
import App from './App.vue'
import config from './config/web-config'
import appConfig from './config/app-config'
import SapitUiPlus from 'sapit-ui-plus'
import 'sapit-ui-plus/lib/css/style.css'

async function init() {
  const pages = import.meta.glob('@/views/**/*.vue')
  const app = createApp(App)
  app.use(SapitUiPlus)
  await app.config.globalProperties.$registerGlobalConfig({ ...config, ...appConfig }, pages)
  app.mount('#app')
}
init()
  • config: environment configuration (web-config);
  • appConfig: build-time configuration (login/home overrides, static routes, language packs) that never enters config.json;
  • pages: every business page, used by dynamic routing to match hrefs.

5.3 Login page / home override

app-config.js:

export default {
  components: {
    login: () => import('@/views/login/index.vue'),
    home: () => import('@/views/home/index.vue')
  }
}

When not configured, the base defaults are used (pages/login.vue, todo.vue).

5.4 Static pages staticRoutes

export default {
  staticRoutes: [
    {
      path: '/help',
      name: 'Help',
      component: () => import('@/views/help/index.vue'),
      meta: { title: 'Help' } // hidden: not in the menu; public: no login required
    }
  ]
}

layout: false / raw: true skips BasicLayout; a business route with the same path overrides the built-in one.

5.5 Business pages and menus

Backend menu hrefs must match the business views path (or the component name); any page under src/views/** is picked up by dynamic routing. The side menu renders "dynamic menu + staticRoutes" and the base's constant routes never appear in it.

5.6 Internationalization / theme

Internationalization

  • Dictionary file: views/<module>/i18n.js, a flat { '<source text>': 'English' }; the namespace is the first folder after views.
  • Pages do not need useI18n: $l('<source text>') resolves against the page's own folder automatically. To force a namespace across folders use this.useI18n('<module>') (Options API) or window.useI18n('<module>') (<script setup>).
  • Aggregation happens once, in the business src/config/app-config.js; new files or folders need no code change:
// src/config/app-config.js
const locales = import.meta.glob(['@/views/**/i18n.js', '@/locales/**/i18n.js'], { eager: true })
export default {
  // ...other business config
  locales // main.js spreads { ...config, ...appConfig } into $registerGlobalConfig, merging with the base
}
  • locales/** overrides base entries: src/locales/components/i18n.js maps to the components namespace (shared component-library words); the business wins on duplicates.
  • The language switcher is controlled by VITE_APP_LANG_ENABLE in .env (true shows it); with false the dictionaries still work and Chinese is rendered as-is.
  • Prefixed filenames such as home-i18n.js / login-i18n.js are obsolete: always use i18n.js, otherwise the derived namespace is a non-existent default/home, default/login and the entries never resolve.

Theme

Only change VITE_APP_THEME_VALUE; style with var(--s-*) or .s-theme-*. Menu colors are owned by the base (derived from the primary color, plus OS dark-mode following) — the business only picks light or dark via VITE_APP_MENU_THEME and decides whether to enable VITE_APP_THEME_FOLLOW_SYSTEM (see 2.18).

5.7 Sub-path deployment (example /monitor/)

  1. .env: VITE_APP_BASE_URL=/monitor/;
  2. business vite.config.js: base: getViteEnv(res.mode, 'VITE_APP_BASE_URL') || '/';
  3. the base router base, $push/$open, redirectLogin and parseAppUrl all read that value and prefix automatically;
  4. nginx:
location /monitor/ {
    alias /home/project/tmp/dist/;
    index index.html;
    try_files $uri $uri/ /monitor/index.html;
}
location = /monitor/config.json {
    alias /home/project/tmp/dist/config.json;
    add_header Cache-Control "no-store";
}

createWebHistory base, the Vite base and every window.location jump must all be /monitor/ (with the trailing slash).

5.8 Using components and permissions

<template>
  <s-list-layout :columns="columns" :loadData="page" title="Example" />
  <s-user-select v-model:value="ids" />
  <a-button v-action="'add'">Add</a-button>
</template>

After the backend delivers permissions the base writes permission, and v-action:xxx controls button-level permission. Documentation is available at <business base>/docs and <business base>/components.


5.9 Built-in dependencies (ready to use in a business project)

The dependencies of sapit-ui-plus are installed into the business node_modules together with the base, so the business can import them without installing anything (a business package.json usually only lists sapit-ui-plus).

Dependency Version Purpose
dayjs ^1.11.12 Date formatting (recommended, also used inside $utils)
axios ^1.7.3 Requests (wrapped as window.$utils.http, rarely used directly)
qs ^6.13.0 Parameter serialization (stringify)
lodash.get / lodash.clonedeep ^4.4.2 / ^4.5.0 Safe access / deep clone
crypto-js ^4.2.0 Encryption / decryption
js-base64 ^3.7.2 Base64 encode/decode
jsencrypt ^3.3.2 RSA encryption
moment ^2.30.1 Dates (legacy compatibility; use dayjs for new code)
html2canvas ^1.4.1 Page screenshots
nprogress ^0.2.0 Top loading progress bar
@vueuse/core ^11.0.3 Composition utilities
vue-cropper ^1.1.4 Image cropping (used by SCopperUpload)
vuedraggable ^4.1.0 Drag-and-drop sorting
v-clipboard ^3.0.0-next.1 Copy to clipboard (v-clipboard directive)
vue-ls ^4.2.0 localStorage wrapper (already exposed as $utils.ls)
jodit 3.24.7 Rich text editor (SEditor)
less / less-loader ^4.2.0 / ^12.2.0 Style compilation
vite-plugin-html / vite-plugin-generate-file ^3.2.2 / ^0.2.0 Build plugins (generate config.json etc.)
@ant-design/icons-vue follows ant-design-vue Icons, all registered globally as components

Singleton dependencies: the base does not bundle them and the business must install them itself (external in vite.config.js), otherwise two module instances appear (routes cannot be injected, pinia mismatches, theme/message context is lost):

Dependency Version
vue ^3.4.29
vue-router ^4.3.3
pinia ^2.1.7
vue-i18n ^9.14.0
ant-design-vue 4.x

Usage: import dayjs from 'dayjs' just works; but do not install a second copy of vue/ant-design-vue/pinia with a different major version in the business — the base version wins.

5.10 Global injection (no import needed)

Name Description
$utils Utilities: $utils.http (requests), $utils.ls (local storage), $utils.env (config), etc.
$message / $modal / $notice ant-design-vue message / Modal / notification
$push / $open In-app navigation / new window (deployment base prefixed automatically)
$l i18n lookup ($l('<source text>'))
$theme Current theme variables; CSS variables such as --s-color
$icons All antd icon components
$socket / $filter / $pinia / $i18n websocket / filters / user store / i18n instance
env Same as $utils.env
$getPdf({ el, title }) Export the page to PDF; html2canvas + jsPDF are loaded dynamically (see 2.2)
$staticRoutes Static page routes (including business-defined ones)

6. Caveats

6.1 On the business side

  1. Dependencies are prebuilt artifacts: a base change only takes effect after npm run build + push + reinstalling dependencies in the business; the base's own dev server reflects changes immediately.
  2. Lock files pin the old commit: delete package-lock.json, yarn.lock and node_modules/.package-lock.json before updating.
  3. Sub-path: keep VITE_APP_BASE_URL and the Vite base identical and trailing-slashed.
  4. Global component naming: registered by file name (SForm.vue → <SForm>, not kebab-case); the later one wins on conflict.
  5. Theme / menu palette / i18n: all defined in the base. The business only picks VITE_APP_THEME_VALUE, VITE_APP_MENU_THEME (light / dark) and VITE_APP_THEME_FOLLOW_SYSTEM (whether to follow the OS scheme), and writes i18n copy; the VITE_APP_MENU_* colors and tuning keys are locked by the base and forced back if set (see 2.18).
  6. Deep imports into base internals are not allowed: the lib output has a single entry, lib/js/index.js, and internal modules are rolled into chunks. To expose a capability to the business, attach it as a global property (like $utils / $modal).
  7. Feature parity: whatever the reference (old Vue2) project has, we have; do not "helpfully" add what it does not have. Confirm the reference implementation before adding a feature.

6.2 Development / build

  1. Never run two vite build at the same time: it reports Rollup failed to resolve import "sapit-ui-plus", which is a false cache-conflict error; rerun serially and it recovers. If it persists serially, check whether node_modules/sapit-ui-plus was emptied (npm reinstall often clears it) — restore it with:
   # the base dist is exactly the npm package content (the build script copies package.json + docs + vite-plugins into dist)
   cp -r <base>/dist/lib <base>/dist/docs <base>/dist/vite-plugins <base>/dist/package.json <business>/node_modules/sapit-ui-plus/
   cp -r <base>/packages/sso <base>/packages/static <business>/node_modules/sapit-ui-plus/
  1. vite build --emptyOutDir false: emptying dist is blocked by the bulk-delete guard; use this flag when only verifying compilation, and do not run the npm run build that pushes to the internal git repository just to verify (that is a release action and needs confirmation first).
  2. Never run two base builds or two business installs concurrently, to avoid cache contamination.
  3. vite build does not check undefined variables: referencing a non-existent variable in a template or script still compiles. After a large edit, review added and removed lines with git diff and scan for unused imports to catch accidental deletions.
  4. npm network in China: registry.npmjs.org is basically unreachable and installing sapit-ui-plus stalls on the big packages (ant-design-vue unpacks to 78MB, jodit to 23MB). Use a domestic registry:

    npm i git+http://192.168.200.4:6110/sapit/sapit-ui-plus.git --registry=https://registry.npmmirror.com
    

    If git ls-remote inside the npm process returns 403 (sandbox/network interception, while a manual git ls-remote works), temporarily remove that git dependency, install the rest, then restore it from the local base dist as in item 8.

    1. The npm package must contain a root-level static/: the lib build does not rewrite new URL('../../static/...', import.meta.url), and at runtime it resolves from lib/js/*.js to static/ at the package root. Without it every login-page image 404s in the business dev server while the base's own dev and production are fine — extremely misleading.
    2. Images in the lib build: Vite forces every asset inline for build.lib, so the output can contain MB-sized base64 data URIs (beyond Chrome's URL limit). closeBundle in vite-plugins/sso-plugin extracts data URIs larger than 100KB into real files under lib/img/; always reference source assets through import.

    6.3 Business dictionary / form conventions (hy-monitor)

    1. Always bind dropdown values and copy to the dictionary item's value (the dictionary value), never its id (primary key). Fetch several dictionaries at once with mapByDictTypes('a','b') and read the result with underscores converted to camelCase (recycle_status → res.recycleStatus); each item is {label, value, id}.
    2. An a-select placeholder only shows when the value is undefined/null; an empty string '' counts as an existing value. Initialize every dropdown-like field (search parameters, form fields) to undefined and never '' (multi-select binding to [] is fine).
    3. Time range parameters are always millisecond timestamps (dayjs(x).valueOf()), not unix seconds. Basis: the reference DateRange onChange emits date.map(o => dayjs(o).valueOf()) and useFormValues.fieldMapToTime passes values through by default (format='').
    4. Do not add catch to API requests (errors are reported by the global interceptor). Three kinds of catch must stay: ① the form validation chain .catch(() => {}); ② try { await validate() } catch { return }; ③ tolerant JSON.parse.
    5. API failures navigate to the built-in error pages: HTTP 403 (301 included) → /403, 404 → /404, swapped inside the content-area router-view (sidebar and header stay, the shell is never replaced) with no notification stacked on top. The URL carries ?api=<endpoint>&status=<original status>, so the page switches to the API wording (403 "no permission for this API", 301 "API endpoint moved", 404 "API not found") and shows the endpoint; without ?api= it stays on the page wording (no page permission / page not found). 5xx does not navigate — it keeps the normal notification (/500 stays available by direct URL). Background polling and other auxiliary requests can pass { skipErrorPage: true } to keep the current page:
    this.$utils.http.post('/api/msg/count', {}, { skipErrorPage: true })
    

7. Global method quick reference

Call Purpose
$l('<source text>'[, key]) Internationalization
$push(path, query) / $open(path, query) Navigate / open a new window (base prefixed)
$message.* / $modal.* / $notice.* / $confirm(...) Toast / modal / notification / confirm dialog
this.$utils.ls.get/set/clear Local storage
this.$utils.http(config) Send a request (POST by default)
$filter.dateFormat(v, fmt) Date formatting
v-action:code Button-level permission (exact button_code match)
$utils.hasAction(code) Button-level permission (functional, supports OR / AND)
$utils.iconOf('info-circle') Legacy antd v1 type name → icon component
$utils.messageFormat(str, values) {0} / {name} placeholder substitution
$utils.filterSelectOption(iv, opt) antd4-ready select filter
$utils.randomDrawerPlacement() Random drawer direction
$utils.getTableHeight() Legacy list table height (window − search − offset)
var(--s-color) / .s-theme-color Theme color (CSS variable / utility class)

8. Online documentation entry

Address Content
<base>/docs This guide
<base>/components s components (built-in components: left menu + preview + source)