sapit-ui-base-guide.en.md 70 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 What the package contains

The sapit-ui-plus a business project installs carries only what runs at runtime (not the base source tree):

node_modules/sapit-ui-plus/
├─ lib/              # build output: js / css / images — what the business actually imports
├─ docs/             # this document, rendered by the built-in /docs page
├─ vite-plugins/     # plugins referenced by the business vite.config.js (e.g. sso-plugin)
├─ static/           # static assets (login page images, ...)
└─ package.json

A business project only references three things: the entry sapit-ui-plus, the styles sapit-ui-plus/lib/css/style.css, and vite-plugins/* on demand.


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), SListLayout, SListCardLayout (card list), SListTableTreeLayout, SSuperListLayout (advanced list: column settings + advanced filter), SFormLayout, SPanelLayout, SCollapses/SCollapsesItem, SDrawer
Overlay SModal, SModalTemplate, ModalHeader, SIconModal, SImportModal (bulk import)
Form / filter SForm, SFormItem (multi-column + full for a whole row), SExtendFieldsForm/SExtendFieldsFormItem (dynamic extra fields), SFilterWrap, SFilterItem (full for a whole row), SFilterToolbar (filter area shell: main row + more-filters collapse + reset), STableToolbar (table area shell: body height auto-fits the content area; used as a pair with SFilterToolbar), SCascader, STree, STreeSelect, SDataRangeTreeSelect (data-permission scope tree), SUserSelect, SUserSelectButton, SChooseUser (user picker with data permission), SBelowChoosePosition (position picker), 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), SEditor, SEmpty, SIcon, SSvg, SAnchor, SColorPicker, SToggleLanguage, SettingFilter, SettingColumns, SSideMenu/STopMenu

Props / events / methods / slots, live previews and example code for every component live in the built-in component page /components (it also has a "tools / config" tab listing every web-config option and every $utils method).

A few usage notes:

  • Component names are PascalCase (SForm / STable); both <SForm> and <s-form> resolve in templates — just stay consistent.
  • All @ant-design/icons-vue icons are registered globally, and the icon map is exposed as $icons.
  • A few helper components are internal (e.g. ModalHeader, CropperModal, SettingColumns / SettingFilter) — do not reference them from business code.

2.2 Global properties / methods

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

Name Description
$registerGlobalConfig(config, pages) Initialization entry (see 4.2)
$utils Utility collection: $utils.env / $utils.ls / $utils.http plus general helpers
env Merged environment configuration (= $utils.env)
$i18n / $l(name) 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

Business pages render inside the content area of BasicLayout. There are three shells:

Layout Purpose
BasicLayout Header + side/top menu + content (dynamic and static routes are both wrapped in it by default)
UserLayout Login, QR login, forgot password, activation — pages reachable before signing in
BlankLayout A bare shell without menu or header

Page height: the content height is computed by BasicLayout and passed down to router-view, so a page root with height: 100% fills the area automatically. Never write calc(100vh - 58px)-style subtractions: header height, footer and tabs all make that number wrong, and the symptom is pagination floating mid-page or an extra scrollbar.

Use a layout component for the page body (SListLayout / SFormLayout / SSkeletonLayout / SPanelLayout, ...): they take the remaining height and scroll internally, so you only write the content.

Choosing a page layout component:

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

2.4 Routes

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

Path Description
/login/index Login page (base default, can be overridden by the business, see 4.3)
/login/:officeCode Same page entered with an office code (written to $utils.ls as officeCode, see 2.10)
/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 (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). Where they render and their wording: see 2.11

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

Static routes (staticRoutes, independent of backend menus): see 4.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 4.7 permissions).

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.

Business side setup (documented here only)

  1. Drop dictionaries at views/<module>/i18n.js as described above; adding files or folders needs no code change.
  2. Aggregate them once in the business src/config/app-config.js; main.js spreads { ...config, ...appConfig } into $registerGlobalConfig:
// src/config/app-config.js
const locales = import.meta.glob(['@/views/**/i18n.js', '@/locales/**/i18n.js'], { eager: true })
export default {
  // ...other business config
  locales
}
  1. src/locales/** overrides base entries: src/locales/components/i18n.js maps to the components namespace (shared component-library words); the business wins on duplicates.
  2. The language switcher is controlled by VITE_APP_LANG_ENABLE in .env (true shows it); with false the dictionaries still work and Chinese renders as-is.
  3. 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.

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: a separate --s-menu-* set, derived from the primary color (light) or fixed antd black (dark); the business picks the mode and cannot change the values — see 2.12 Menu palette.
.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

Business styles must use var(--s-*) instead of literal colors (#1677ff / #e8e8e8 / rgba(0,0,0,.65) and the like): primary values come from the primary tokens, greys from the neutral tokens, statuses from the semantic tokens — that is what makes a theme switch a one-line change.

Only blue / green / orange / pink / customer are available; a business project can select a theme but not add one.

2.9 Other built-in capabilities

Built in How a business project uses it
Login / SSO / forgot-password / activation API set Use the base login page; details in 2.10, visual override in 4.3
Built-in pages: workplace, todo, message, 403/404/500, /docs, /components Open them directly; workplace / home can be overridden by business pages
Static assets, global styles, theme tokens Shipped inside packages/static and packages/style — nothing to copy
Common dependencies Already shipped in sapit-ui-plus dependencies, import directly; list in 4.8

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 provided by the base: business projects no longer maintain sso.js / sso.html under public/ — just import the plugin in 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 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

How the jump shows: the error page is switched inside the content area — the sidebar, header and footer stay as they are, the shell is never replaced. A page 404 (no route matched) and an API 404 behave exactly the same.

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 })

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.
  • All three pages fill the content area at height:100%, so long content only scrolls inside the card and never creates a page-level 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.12 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

Only three keys are optional:

Config Default Notes
VITE_APP_MENU_BAR left left sidebar / top top bar (a layout option)
VITE_APP_MENU_THEME light light derived from the primary / dark black
VITE_APP_THEME_FOLLOW_SYSTEM true Whether to follow the OS prefers-color-scheme

The 11 color / tuning keys below are force-written back on base startup, so menu colors set in the business .env, src/config/web-config.js or the deployed config.json all have no effect — every business project matches the base demo exactly, by design:

Key Default Purpose
VITE_APP_MENU_BG theme Top-level background: theme follows the primary / #RRGGBB
VITE_APP_MENU_BG_LIGHTNESS 93 Top-level lightness, 0-100
VITE_APP_MENU_BG_SATURATION 66 Saturation ceiling, 0-100
VITE_APP_MENU_BG_ACTIVE_MIX 16 Share of the primary color in the selected block, 0-100
VITE_APP_MENU_SUB_BG empty Submenu panel background; empty = derived from the hue
VITE_APP_MENU_HOVER_BG empty Hovered item background; empty = derived from the hue
VITE_APP_MENU_ACTIVE_BG empty Selected block background; empty = primary mixed with white
VITE_APP_MENU_TEXT empty Normal text color; empty = derived from the hue
VITE_APP_MENU_TEXT_HOVER empty Hover text color
VITE_APP_MENU_TEXT_ACTIVE empty Selected text color
VITE_APP_MENU_GROUP_TITLE empty Group title color

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.

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.

3. Build and configuration

3.1 How a business project picks up base changes

The base is published as the npm package sapit-ui-plus, and business projects consume pre-built output, not source:

Scenario How it takes effect
The base changed components / config / copy Base releases → business updates the dependency (npm start, or delete the lock file and npm i)
Only business pages changed Restart the business dev server

When updating the dependency you must delete the lock files (package-lock.json / yarn.lock / node_modules/.package-lock.json), otherwise the install stays pinned to an old commit and it looks like "the new base feature never arrived".

3.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

The 14 menu-palette keys (VITE_APP_MENU_BAR / _THEME / THEME_FOLLOW_SYSTEM are optional, the other 11 are locked by the base) are listed once in 2.12 Menu palette.

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.

3.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.

4. Business project integration

4.1 Install

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

4.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.

4.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).

4.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.

4.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.

4.6 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).

4.7 Using components and permissions

<template>
  <s-list-layout :columns="columns" :load-data="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.


4.8 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. Caveats

5.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. Components are globally available: every S* component and STable is registered by the base — just write the tag; do not import it and do not register it locally again.
  5. Theme / menu palette / i18n: all defined in the base. The business only picks VITE_APP_THEME_VALUE, VITE_APP_MENU_THEME and VITE_APP_THEME_FOLLOW_SYSTEM, and writes i18n copy; VITE_APP_MENU_* color values are forced back (see 2.7 / 2.8 / 2.12).
  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.

5.2 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: 403 (301 included) — /403, 404 — /404, swapped inside the content-area router-view with no notification stacked on top; 5xx does not navigate and keeps the normal notification. Auxiliary requests (polling) can pass { skipErrorPage: true } to keep the current page. Query parameters, wording and color overrides: see 2.11:
this.$utils.http.post('/api/msg/count', {}, { skipErrorPage: true })

6. Online documentation entry

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