main.tsx 7.1 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189
  1. import type { ReactNode } from "react";
  2. import { createRoot } from "react-dom/client";
  3. import { LucideProvider } from "lucide-react";
  4. import "../../share-ui/src/styles.css";
  5. import { DEFAULT_LUCIDE_STROKE_WIDTH } from "../../ui/src/components/icons/windowIcons.js";
  6. import { applyTheme, type Theme } from "../../ui/src/useTheme.js";
  7. import {
  8. ConversationShareLandingLoader,
  9. ConversationShareLandingStatus,
  10. } from "../../web/src/share/ConversationShareLandingPage.js";
  11. import {
  12. ConversationSharePreviewClient,
  13. resolveConversationShareRouteLocale,
  14. } from "../../web/src/share/conversationSharePreviewClient.js";
  15. import {
  16. conversationShareManagePath,
  17. isConversationSharePath,
  18. resolveConversationShareCodeFromPath,
  19. resolveConversationShareManageLocale,
  20. } from "../../web/src/share/conversationShareRoute.js";
  21. import {
  22. ConversationShareManageClient,
  23. ConversationShareManageLoader,
  24. } from "../../web/src/share-manage/index.js";
  25. import { resolveWebRemoteControlInitialTheme } from "../../web/src/web-remote-control/adapters/webRemoteControlThemeSeed.js";
  26. import { createWebAuthService } from "../../web/src/auth/webAuthService.js";
  27. import {
  28. WEB_ZAI_OAUTH_CONFIG,
  29. resolveWebAuthDevReturnTo,
  30. } from "../../web/src/auth/webZaiOAuthConfig.js";
  31. import { ShareCallbackPage } from "./ShareAuthPages.js";
  32. import type { WebOAuthProviderId } from "../../web/src/auth/browserOAuthCredentialRepo.js";
  33. const reactRoot = createRoot(document.getElementById("root")!);
  34. // 问题:Share 是独立入口,不经过 App 的 Root,原来没有 LucideProvider,
  35. // 共用组件里未显式传 strokeWidth 的图标(思考、工具摘要等)回退到 lucide 默认 2,比 App 的 1.5 更粗。
  36. // 修复:在唯一渲染出口统一注入同一个默认线宽,分享页、管理页、回调页都生效。
  37. const root = {
  38. render(node: ReactNode): void {
  39. reactRoot.render(
  40. <LucideProvider strokeWidth={DEFAULT_LUCIDE_STROKE_WIDTH}>{node}</LucideProvider>,
  41. );
  42. },
  43. };
  44. const webAuthService = createWebAuthService();
  45. function resolveThemePreference(): Theme {
  46. const saved = localStorage.getItem("zcode-theme");
  47. return resolveWebRemoteControlInitialTheme({ storedTheme: saved, defaultTheme: "zai-light" });
  48. }
  49. // Share 是独立入口,不会经过完整 Web 的 bootstrap;必须在渲染前同步根主题 class,
  50. // 否则页面外壳使用默认浅色 token,而 MessageResponse 会按 zai-dark 选择 github-dark,
  51. // 最终产生浅色页面套深色 Markdown 代码块的混合样式。
  52. const INITIAL_THEME = resolveThemePreference();
  53. applyTheme(INITIAL_THEME);
  54. function isOAuthCallback(): boolean {
  55. return (
  56. window.location.pathname === "/cn/share/callback" ||
  57. window.location.pathname === "/share/callback"
  58. );
  59. }
  60. function renderCallback(): void {
  61. // Bug 原因:区域登录改为同页跳转后,回调带的是服务端 flow state,不含 app_return_to;原先只解析
  62. // 本端编码的 state,失败后“重新登录”落到无分享码的 /share 错误页。回跳地址只记在 pending 里,
  63. // 改用与完整 Web 入口相同的解析,且必须在 handleCallback 取出 pending 之前读取。
  64. const retryTarget = webAuthService.resolveCallbackReturnTo(window.location.href) ?? "/share";
  65. root.render(
  66. <ShareCallbackPage
  67. authService={webAuthService}
  68. onSuccess={({ appReturnTo }) => window.location.replace(appReturnTo ?? "/share")}
  69. onRetry={() => window.location.replace(retryTarget)}
  70. />,
  71. );
  72. }
  73. const endpointOrigin =
  74. import.meta.env.VITE_ZCODE_BASE_URL?.trim().replace(/\/+$/u, "") || window.location.origin;
  75. const mockMode =
  76. import.meta.env.DEV && import.meta.env.VITE_CONVERSATION_SHARE_PREVIEW_MOCK === "true";
  77. const getMockToken = () =>
  78. mockMode && window.sessionStorage.getItem("zcode:share:mock-auth") === "owner"
  79. ? "mock-owner-token"
  80. : null;
  81. const getAccessToken = () => getMockToken() ?? webAuthService.getZCodeJwtToken();
  82. // Bug 原因:登录按钮靠返回的 promise 判断失败、靠 signal 在跳转前取消;原先不传 signal、不返回 promise,
  83. // 取消后页面仍跳到授权站,初始化失败时一直停在等待态。
  84. function startLogin(provider: WebOAuthProviderId, signal?: AbortSignal): Promise<void> | void {
  85. if (mockMode) {
  86. window.sessionStorage.setItem("zcode:share:mock-auth", "owner");
  87. window.location.reload();
  88. return;
  89. }
  90. return webAuthService.startLogin({
  91. signal,
  92. provider,
  93. appReturnTo: window.location.href,
  94. redirectUri: WEB_ZAI_OAUTH_CONFIG.shareRedirectUri,
  95. devReturnTo: resolveWebAuthDevReturnTo(WEB_ZAI_OAUTH_CONFIG, "share"),
  96. });
  97. }
  98. function logout(): void {
  99. if (mockMode) window.sessionStorage.removeItem("zcode:share:mock-auth");
  100. void webAuthService.logout();
  101. }
  102. async function renderManage(locale: "zh-CN" | "en-US"): Promise<void> {
  103. document.documentElement.lang = locale;
  104. document.title = locale === "zh-CN" ? "我的分享 · ZCode" : "My shares · ZCode";
  105. const client = mockMode
  106. ? new (
  107. await import("../../web/src/share-manage/mockConversationShareManageClient.js")
  108. ).MockConversationShareManageClient()
  109. : new ConversationShareManageClient({ baseUrl: `${endpointOrigin}/api/v1` });
  110. root.render(
  111. <ConversationShareManageLoader
  112. client={client}
  113. getAccessToken={getAccessToken}
  114. onLogin={startLogin}
  115. onLogout={logout}
  116. locale={locale}
  117. theme={INITIAL_THEME}
  118. />,
  119. );
  120. }
  121. async function renderShare(): Promise<void> {
  122. const locale = resolveConversationShareRouteLocale(window.location.pathname);
  123. document.documentElement.lang = locale;
  124. document.title = locale === "zh-CN" ? "ZCode 会话分享" : "ZCode Conversation Share";
  125. const shareCode = resolveConversationShareCodeFromPath(window.location.pathname);
  126. if (!shareCode) {
  127. root.render(
  128. <ConversationShareLandingStatus
  129. state={{ kind: "error", error: "invalid_contract" }}
  130. locale={locale}
  131. />,
  132. );
  133. return;
  134. }
  135. const client = mockMode
  136. ? new (
  137. await import("../../web/src/share/mockConversationSharePreviewClient.js")
  138. ).MockConversationSharePreviewClient()
  139. : new ConversationSharePreviewClient({ baseUrl: `${endpointOrigin}/api/v1` });
  140. root.render(
  141. <ConversationShareLandingLoader
  142. shareCode={shareCode}
  143. client={client}
  144. getAccessToken={getAccessToken}
  145. onLogin={startLogin}
  146. onLogout={() => {
  147. logout();
  148. window.location.reload();
  149. }}
  150. locale={locale}
  151. theme={INITIAL_THEME}
  152. manageHref={conversationShareManagePath(locale)}
  153. />,
  154. );
  155. }
  156. async function main(): Promise<void> {
  157. if (isOAuthCallback()) {
  158. renderCallback();
  159. return;
  160. }
  161. // 管理页必须先于分享码解析匹配,否则 /share/manage 会被当成分享码 "manage" 去请求 preview。
  162. const manageLocale = resolveConversationShareManageLocale(window.location.pathname);
  163. if (manageLocale) {
  164. await renderManage(manageLocale);
  165. return;
  166. }
  167. if (isConversationSharePath(window.location.pathname)) {
  168. await renderShare();
  169. return;
  170. }
  171. root.render(
  172. <ConversationShareLandingStatus state={{ kind: "error", error: "invalid_contract" }} />,
  173. );
  174. }
  175. void main();