feat(ui): render workspace-context notifications with styled chips

The login-success and tenant-switch toasts previously showed the
workspace name and role inline as bracketed plain text, which read
flat and made the two key data points hard to scan at a glance.

Render them through a shared `renderWorkspaceNotifyContent` helper
that produces a NotifyPlugin VNode with:

* a neutral rounded chip for the workspace name (with a generic
  workspace icon), and
* a role-coloured chip for the role (with the existing per-role icon
  from useRoleLabel), so owner / admin / contributor / viewer each
  get a distinct visual identity that matches the role badges used
  elsewhere in the product.

The i18n templates lose the surrounding 「」 / "" / «» quote marks
because the chip itself now provides the visual delineation; double
emphasis looked off. Translators control the surrounding wording via
`{name}` and `{role}` placeholders and the renderer splits on those
markers to interleave plain text and chips in the original order.

The PendingTenantSwitchToast payload (sessionStorage-stashed for the
hard-reload survival trick) grows a `roleEnum` field so the post-
reload toast can colour the chip — without that, the switch toast
would fall back to a neutral chip while the login toast got the
colour treatment.

Note on icon resolution: the chip renderer imports TDesign's `Icon`
component directly rather than referencing it by string tag in `h()`
— Vue's render function does not auto-resolve component names the
way templates do, so `h('t-icon', ...)` would silently render an
unknown HTML element.
This commit is contained in:
wizardchen
2026-05-18 20:32:50 +08:00
committed by lyingbug
parent 60a579d869
commit 559b5a6e20
11 changed files with 224 additions and 31 deletions
+13 -5
View File
@@ -10,6 +10,7 @@ import { getCurrentUser } from '@/api/auth'
import { consumePendingTenantSwitchToast } from '@/utils/tenantSwitch'
import { useRoleLabel } from '@/composables/useRoleLabel'
import { notifyLoginSuccess } from '@/utils/loginNotify'
import { renderWorkspaceNotifyContent } from '@/utils/workspaceNotifyContent'
// TDesign locale configs
import enUSConfig from 'tdesign-vue-next/esm/locale/en_US'
@@ -18,7 +19,7 @@ import koKRConfig from 'tdesign-vue-next/esm/locale/ko_KR'
import ruRUConfig from 'tdesign-vue-next/esm/locale/ru_RU'
const { locale, t } = useI18n()
const { formatRole } = useRoleLabel()
const { formatRole, roleIcon } = useRoleLabel()
const router = useRouter()
const authStore = useAuthStore()
const settingsStore = useSettingsStore()
@@ -143,7 +144,7 @@ const handleGlobalOIDCCallback = async () => {
if (response.success) {
clearOIDCCallbackState('/')
await persistOIDCLoginResponse(response)
notifyLoginSuccess(response, t, formatRole)
notifyLoginSuccess(response, t, formatRole, roleIcon)
return
}
@@ -203,11 +204,18 @@ watch(
const showPendingTenantSwitchToast = () => {
const pending = consumePendingTenantSwitchToast()
if (!pending) return
const templateKey = pending.role
? 'tenant.switchSuccessContentWithRole'
: 'tenant.switchSuccessContent'
NotifyPlugin.success({
title: t('tenant.switchSuccessTitle'),
content: pending.role
? t('tenant.switchSuccessContentWithRole', { name: pending.name, role: pending.role })
: t('tenant.switchSuccessContent', { name: pending.name }),
content: renderWorkspaceNotifyContent({
template: t(templateKey),
name: pending.name,
roleLabel: pending.role,
roleEnum: pending.roleEnum,
roleIconName: pending.roleEnum ? roleIcon(pending.roleEnum) : undefined,
}),
duration: 6000,
closeBtn: true,
})
+5 -1
View File
@@ -180,7 +180,11 @@ const selectTenant = (tenantId: number) => {
const membership = (authStore.memberships ?? []).find((m) => Number(m.tenant_id) === tenantId)
const roleLabel = membership ? formatRole(membership.role) : ''
// Toast 在 reload 后由 App.vue 弹出(直接在这里弹会被 hard reload 干掉)。
stashTenantSwitchToast({ name: displayName, role: roleLabel || undefined })
stashTenantSwitchToast({
name: displayName,
role: roleLabel || undefined,
roleEnum: membership?.role || undefined,
})
// Persist "last active tenant" preference (switching to home clears
// it). Fire-and-forget, but race it against the existing 500ms grace
// window so most writes finish before the hard reload tears the page
+1
View File
@@ -455,6 +455,7 @@ const switchToTenant = (m: Membership) => {
stashTenantSwitchToast({
name: tenantDisplayName(m),
role: formatRole(m.role) || undefined,
roleEnum: m.role || undefined,
})
// Persist "last active tenant" preference (switching to home clears
// it). Hard reload so every cached store / open SSE stream / in-flight
+4 -4
View File
@@ -1297,8 +1297,8 @@ export default {
forgotPassword: 'Forgot Password?',
loginSuccess: 'Login successful!',
loginSuccessTitle: 'Login successful',
loginSuccessContent: 'Welcome back. You are now in "{name}"',
loginSuccessContentWithRole: 'Welcome back. You are now in "{name}" as {role}',
loginSuccessContent: 'Welcome back. You are now in {name}',
loginSuccessContentWithRole: 'Welcome back. You are now in {name} · as {role}',
loginFailed: 'Login failed',
loggingIn: 'Logging in...',
register: 'Register',
@@ -2393,8 +2393,8 @@ export default {
searchHint: 'Search by name or enter tenant ID directly',
noMatch: 'No matching tenants found',
switchSuccessTitle: 'Workspace switched',
switchSuccessContent: 'You are now in "{name}"',
switchSuccessContentWithRole: 'You are now in "{name}" as {role}',
switchSuccessContent: 'You are now in {name}',
switchSuccessContentWithRole: 'You are now in {name} · as {role}',
loadTenantsFailed: 'Failed to load tenant list',
loading: 'Loading...',
loadMore: 'Load more',
+4 -4
View File
@@ -1148,8 +1148,8 @@ export default {
forgotPassword: "비밀번호를 잊으셨나요?",
loginSuccess: "로그인 성공!",
loginSuccessTitle: "로그인 성공",
loginSuccessContent: "환영합니다. 「{name}」에 입장했습니다",
loginSuccessContentWithRole: "환영합니다. 「{name}」에 입장했습니다 · 역할: {role}",
loginSuccessContent: "환영합니다. {name} 에 입장했습니다",
loginSuccessContentWithRole: "환영합니다. {name} 에 입장했습니다 · 역할 {role}",
loginFailed: "로그인 실패",
loggingIn: "로그인 중...",
oidcLogin: "OIDC로 로그인",
@@ -1641,8 +1641,8 @@ export default {
searchHint: "이름으로 검색하거나 테넌트 ID를 직접 입력할 수 있습니다",
noMatch: "일치하는 테넌트를 찾을 수 없습니다",
switchSuccessTitle: "공간이 전환되었습니다",
switchSuccessContent: "「{name}」에 입장했습니다",
switchSuccessContentWithRole: "「{name}」에 입장했습니다 · 역할: {role}",
switchSuccessContent: "{name} 에 입장했습니다",
switchSuccessContentWithRole: "{name} 에 입장했습니다 · 역할 {role}",
loadTenantsFailed: "테넌트 목록 로드 실패",
loading: "로딩 중...",
loadMore: "더 보기",
+4 -4
View File
@@ -1249,8 +1249,8 @@ export default {
forgotPassword: 'Забыли пароль?',
loginSuccess: 'Вход выполнен успешно!',
loginSuccessTitle: 'Вход выполнен',
loginSuccessContent: 'С возвращением. Вы вошли в «{name}»',
loginSuccessContentWithRole: 'С возвращением. Вы вошли в «{name}» · роль: {role}',
loginSuccessContent: 'С возвращением. Вы вошли в {name}',
loginSuccessContentWithRole: 'С возвращением. Вы вошли в {name} · роль {role}',
loginFailed: 'Ошибка входа',
loggingIn: 'Вход...',
register: 'Регистрация',
@@ -1439,8 +1439,8 @@ export default {
searchHint: 'Поиск по имени или введите ID арендатора напрямую',
noMatch: 'Не найдено подходящих арендаторов',
switchSuccessTitle: 'Пространство переключено',
switchSuccessContent: 'Вы вошли в «{name}»',
switchSuccessContentWithRole: 'Вы вошли в «{name}» · роль: {role}',
switchSuccessContent: 'Вы вошли в {name}',
switchSuccessContentWithRole: 'Вы вошли в {name} · роль {role}',
loadTenantsFailed: 'Не удалось загрузить список арендаторов',
loading: 'Загрузка...',
loadMore: 'Загрузить еще',
+4 -4
View File
@@ -1143,8 +1143,8 @@ export default {
forgotPassword: "忘记密码?",
loginSuccess: "登录成功!",
loginSuccessTitle: "登录成功",
loginSuccessContent: "欢迎,你已进入「{name}」",
loginSuccessContentWithRole: "欢迎,你已进入「{name}」,身份:{role}",
loginSuccessContent: "欢迎,你已进入 {name}",
loginSuccessContentWithRole: "欢迎,你已进入 {name} · 身份 {role}",
loginFailed: "登录失败",
loggingIn: "登录中...",
oidcLogin: "使用 OIDC 登录",
@@ -1621,8 +1621,8 @@ export default {
searchHint: "支持按名称搜索或直接输入空间 ID",
noMatch: "未找到匹配的空间",
switchSuccessTitle: "已切换空间",
switchSuccessContent: "你已进入「{name}」",
switchSuccessContentWithRole: "你已进入「{name}」,身份:{role}",
switchSuccessContent: "你已进入 {name}",
switchSuccessContentWithRole: "你已进入 {name} · 身份 {role}",
loadTenantsFailed: "加载空间列表失败",
loading: "加载中...",
loadMore: "加载更多",
+23 -6
View File
@@ -4,13 +4,15 @@
// flows feel identical to the user.
//
// Kept as a free function — not a composable — because the caller
// already has `t` and `formatRole` in scope from useI18n / useRoleLabel
// and there is no per-instance state worth tracking.
// already has `t`, `formatRole` and `roleIcon` in scope from useI18n /
// useRoleLabel and there is no per-instance state worth tracking.
import { NotifyPlugin } from 'tdesign-vue-next'
import { renderWorkspaceNotifyContent } from './workspaceNotifyContent'
type Translator = (key: string, params?: Record<string, unknown>) => string
type RoleFormatter = (role: string | null | undefined) => string
type RoleIconResolver = (role: string | null | undefined) => string
interface LoginResponseLike {
// Password-login response uses `active_tenant`; the OIDC callback
@@ -25,6 +27,7 @@ export function notifyLoginSuccess(
response: LoginResponseLike | null | undefined,
t: Translator,
formatRole: RoleFormatter,
roleIcon: RoleIconResolver,
): void {
const activeTenant = response?.active_tenant || response?.tenant
if (!activeTenant) return
@@ -34,13 +37,27 @@ export function notifyLoginSuccess(
const membership = Array.isArray(response?.memberships)
? response!.memberships!.find((m) => Number(m?.tenant_id) === activeTenantId)
: null
const roleLabel = membership?.role ? formatRole(membership.role) : ''
const roleEnum = membership?.role
const roleLabel = roleEnum ? formatRole(roleEnum) : ''
const roleIconName = roleEnum ? roleIcon(roleEnum) : ''
// Fetch the template without interpolation so the workspace / role
// placeholders survive and the renderer can swap them for styled chips.
// vue-i18n returns the message verbatim when the named keys aren't
// provided in the params bag.
const templateKey = roleLabel
? 'auth.loginSuccessContentWithRole'
: 'auth.loginSuccessContent'
NotifyPlugin.success({
title: t('auth.loginSuccessTitle'),
content: roleLabel
? t('auth.loginSuccessContentWithRole', { name: tenantName, role: roleLabel })
: t('auth.loginSuccessContent', { name: tenantName }),
content: renderWorkspaceNotifyContent({
template: t(templateKey),
name: tenantName,
roleLabel: roleLabel || undefined,
roleEnum: roleEnum || undefined,
roleIconName: roleIconName || undefined,
}),
duration: 6000,
closeBtn: true,
})
+8 -1
View File
@@ -32,7 +32,10 @@ const PENDING_TOAST_KEY = 'weknora_pending_tenant_switch_toast'
export interface PendingTenantSwitchToast {
name: string
/** Human-readable role label, e.g. "所有者" / "Owner". Drives the role chip text. */
role?: string
/** Raw role enum, e.g. "owner". Drives the role chip color + icon. */
roleEnum?: string
}
export function stashTenantSwitchToast(payload: PendingTenantSwitchToast): void {
@@ -50,7 +53,11 @@ export function consumePendingTenantSwitchToast(): PendingTenantSwitchToast | nu
sessionStorage.removeItem(PENDING_TOAST_KEY)
const parsed = JSON.parse(raw)
if (parsed && typeof parsed.name === 'string') {
return { name: parsed.name, role: typeof parsed.role === 'string' ? parsed.role : undefined }
return {
name: parsed.name,
role: typeof parsed.role === 'string' ? parsed.role : undefined,
roleEnum: typeof parsed.roleEnum === 'string' ? parsed.roleEnum : undefined,
}
}
return null
} catch {
@@ -0,0 +1,156 @@
// Shared content renderer for the post-login and post-tenant-switch
// NotifyPlugin cards. Both cards present the same shape ("you are in
// <workspace> as <role>"), so we render them with a unified visual
// language — a neutral chip for the workspace name and a role-coloured
// chip for the role — instead of plain interpolated text.
//
// The renderer interpolates a template string carrying `{name}` and
// optionally `{role}` placeholders. Everything around those placeholders
// is rendered verbatim, which lets translators reorder the sentence
// however their language wants without further code changes.
//
// Why not just pass html to NotifyPlugin's `content` string?
// TDesign's plugin treats `content` as text. Passing a render function
// (TNode) is the supported way to inject styled VNodes; doing it
// through a shared helper keeps the chip styles in one place rather
// than scattered across two call sites.
import { h, type VNode } from 'vue'
import { Icon as TIcon } from 'tdesign-vue-next'
// Inline styles (rather than a global stylesheet) because NotifyPlugin
// renders into a teleported overlay outside any scoped <style>. Keeping
// the CSS adjacent to the markup also makes the chip self-contained:
// callers don't need to remember to import a stylesheet.
const NAME_CHIP_STYLE: Record<string, string> = {
display: 'inline-flex',
alignItems: 'center',
gap: '4px',
padding: '1px 8px',
borderRadius: '10px',
background: 'var(--td-bg-color-secondarycontainer)',
color: 'var(--td-text-color-primary)',
fontWeight: '500',
margin: '0 2px',
maxWidth: '220px',
overflow: 'hidden',
textOverflow: 'ellipsis',
whiteSpace: 'nowrap',
verticalAlign: 'middle',
}
// Role chip palettes mirror the colour intent of the role badges used
// elsewhere (TenantMembers, the permission matrix) so the user gets a
// consistent "this is what an owner / admin / contributor / viewer
// looks like" signal across the app.
const ROLE_TINTS: Record<string, { bg: string; fg: string }> = {
owner: { bg: 'rgba(7, 192, 95, 0.12)', fg: '#067a45' },
admin: { bg: 'rgba(0, 102, 255, 0.12)', fg: '#1a5dd0' },
contributor: { bg: 'rgba(255, 153, 0, 0.12)', fg: '#b46a00' },
viewer: { bg: 'rgba(120, 120, 120, 0.12)', fg: '#5a5a5a' },
}
const ROLE_DEFAULT_TINT = {
bg: 'rgba(120, 120, 120, 0.12)',
fg: 'var(--td-text-color-secondary)',
}
function roleChipStyle(roleEnum: string | undefined): Record<string, string> {
const tint = (roleEnum && ROLE_TINTS[roleEnum]) || ROLE_DEFAULT_TINT
return {
...NAME_CHIP_STYLE,
background: tint.bg,
color: tint.fg,
maxWidth: '120px',
}
}
// Use the imported TDesign Icon component directly. `h('t-icon', ...)`
// would treat the tag as a custom HTML element in render-function land
// (component name resolution is a template-compiler-only feature), so
// the icon would silently render nothing.
function icon(name: string): VNode {
return h(TIcon, {
name,
size: '13px',
style: { flexShrink: '0' },
})
}
function nameChip(name: string): VNode {
return h('span', { style: NAME_CHIP_STYLE, title: name }, [
icon('application'),
h('span', name),
])
}
function roleChip(label: string, roleEnum: string | undefined, iconName: string): VNode {
return h('span', { style: roleChipStyle(roleEnum), title: label }, [
iconName ? icon(iconName) : null,
h('span', label),
])
}
export interface WorkspaceNotifyContentOptions {
/**
* The i18n-translated template carrying `{name}` and optionally
* `{role}` placeholders. Anything around the placeholders is rendered
* as plain text in the output, in order, so the sentence reads
* naturally in every locale.
*/
template: string
/** Workspace display name. Wrapped in a neutral chip. */
name: string
/** Human-readable role label, e.g. "所有者" / "Owner". Omit for the no-role variant. */
roleLabel?: string
/** Raw role enum value, e.g. "owner". Drives chip colour. */
roleEnum?: string
/** Icon name for the role chip. Pass from useRoleLabel().roleIcon. */
roleIconName?: string
}
/**
* Render a NotifyPlugin `content` VNode for the workspace-context
* cards. The returned function is suitable for the plugin's `content:
* () => VNode` slot. Returns a `() => VNode` rather than a VNode so
* TDesign re-invokes it on each render (matches the plugin's
* expectation of a TNode factory).
*/
export function renderWorkspaceNotifyContent(
opts: WorkspaceNotifyContentOptions,
): () => VNode {
return () => {
const parts: Array<string | VNode> = []
// Split on the two placeholders but keep delimiters so we can
// interleave plain text and chips in original order.
const tokens = opts.template.split(/(\{name\}|\{role\})/g)
for (const tok of tokens) {
if (tok === '{name}') {
parts.push(nameChip(opts.name))
} else if (tok === '{role}') {
if (opts.roleLabel) {
parts.push(roleChip(opts.roleLabel, opts.roleEnum, opts.roleIconName || ''))
}
// If the template carries {role} but the caller didn't pass a
// label, drop the marker silently — caller should normally pick
// a no-role template instead, but this avoids leaking the raw
// "{role}" string into the UI if they forget.
} else if (tok) {
parts.push(tok)
}
}
return h(
'div',
{
style: {
display: 'flex',
flexWrap: 'wrap',
alignItems: 'center',
rowGap: '6px',
lineHeight: '1.8',
},
},
parts.map((p) => (typeof p === 'string' ? h('span', p) : p)),
)
}
}
+2 -2
View File
@@ -391,7 +391,7 @@ import screenshot4 from '@/assets/img/screenshot-4.svg'
const router = useRouter()
const authStore = useAuthStore()
const { t, locale } = useI18n()
const { formatRole } = useRoleLabel()
const { formatRole, roleIcon } = useRoleLabel()
// Swiper modules
const modules = [Autoplay, EffectFade, Pagination]
@@ -666,7 +666,7 @@ const handleLogin = async () => {
if (response.success) {
await persistLoginResponse(response)
notifyLoginSuccess(response, t, formatRole)
notifyLoginSuccess(response, t, formatRole, roleIcon)
} else {
MessagePlugin.error(response.message || t('auth.loginError'))
}