Skip to content

WebView2 Service Triad & Vue 3 Frontend Architecture ​

ShibaPPT combines a .NET VSTO backend with a Vue 3.5 + Vite 7.2 multi-page frontend hosted inside Microsoft Edge WebView2. To guarantee rock-solid stability across multi-window STA COM threads (preventing white flashes, reentrancy deadlocks, and shutdown crashes), all WebView2 hosts adhere to the Core WebView2 Service Triad.


1. The C# WebView2 Service Triad (Core/WebView/) ​

IMPORTANT

verify-architecture.ps1 blocks direct calls to .EnsureCoreWebView2Async, .SetVirtualHostNameToFolderMapping, and .WebMessageReceived += outside Core/WebView/. Always use the three services below.

1. Environment & Initialization: WebView2EnvironmentManager + WebView2InitializationService ​

  • Per-STA-Thread Shared Environment: CoreWebView2Environment has strict COM thread affinity. WebView2EnvironmentManager caches one environment per Thread.CurrentThread.ManagedThreadId backed by %LocalAppData%\ShibAppt\WebView2Data.
  • 30s Timeout & Self-Healing COM Retry: WebView2InitializationService.InitializeAsync(webView, ownerName) supports both WPF and WinForms controls. If attempt 1 fails with COMException or InvalidComObjectException, it resets the cached environment and retries automatically.
  • Virtual Host Folder Mapping (MapLocalFolder): Maps local bundle directories to HTTPS virtual origins (e.g., https://design.local), enabling standard ES Modules without file:/// CORS restrictions.

2. Lifecycle & Live Bridges: WebView2LifecycleService ​

Calling WebView2LifecycleService.Attach(ownerWindowOrControl, webView, ownerName, messageHandler) automatically provides:

  1. Idempotent Attachment: Uses ConditionalWeakTable to prevent duplicate event subscriptions.
  2. Live Language Sync: Listens to NavigationCompleted and ShibaLocalizationManager.LanguageChanged, pushing { action: "languageChanged", locale, messages } to the WebView.
  3. Live Theme Sync: Subscribes WPF windows to UnifiedWindowChromeManager.Instance.WindowThemeChanged and pushes { action: "themeChanged", isDark, isDarkTheme, theme }.
  4. Crash-Free STA Disposal (SafeDisposeWebView2): Explicitly closes the underlying _coreWebView2Controller on its owning STA thread and calls GC.SuppressFinalize so MTA finalizers never crash powerpnt.exe during AppDomain unload.

3. Reentrancy-Safe Routing: WebViewMessageRouter ​

  • COM Reentrancy Protection: Opening modal dialogs or child WebView2 windows synchronously inside a native WebMessageReceived callback can deadlock or crash Chromium (0xff). HandleWebMessageReceived extracts the raw JSON string synchronously, exits the native callback immediately, and queues Dispatch(rawJson) via Dispatcher.BeginInvoke.
  • Declarative Fluent API:
    csharp
    _router = new WebViewMessageRouter(nameof(MyTaskPane), SendJsonToWeb)
        .On("applyAlign", payload =>
        {
            ApplyAlignment(payload["mode"]?.ToString());
        })
        .On("getSlideStats", payload => new
        {
            action = "slideStatsLoaded",
            messageId = payload["messageId"]?.ToString(),
            success = true,
            shapeCount = GetActiveSlideShapeCount()
        });
    Note: "getLanguagePack" is pre-registered automatically in every WebViewMessageRouter instance.

2. Vue 3 Multi-Entry Frontend (shibappt-ui/) ​

shibappt-ui is a multi-entry Vite 7 project compiling 9 standalone frontend bundles alongside shared UI primitives and composables.

1. All 9 Vite Rollup Entries & Virtual Hosts ​

Vite --modeSource Entry (shibappt-ui/src/...)Built Output DirectoryWebView2 Virtual Origin
designmodules/design/main.jsmod_design/html/https://design.local/index.html
colorpickermodules/design/color-picker-main.jsmod_colorpicker/html/https://colorpicker.local/index.html
fontsmodules/fonts/main.jsmod_Fonts/html/https://fonts.local/index.html
icon-pickercomponents/icon-picker/main.jsshibappt-ui/dist/html-templates/circular-menu/icon-picker.htmlhttps://circular-menu.local/html-templates/circular-menu/icon-picker.html
command-centercomponents/circular-menu/command-center/main.jsshibappt-ui/dist/html-templates/circular-menu/command-center.htmlhttps://circular-menu.local/html-templates/circular-menu/command-center.html
vba-editorcomponents/vba-editor/main.jsshibappt-ui/dist/html-templates/circular-menu/vba-editor.htmlhttps://circular-menu.local/html-templates/circular-menu/vba-editor.html
web-image-pickercomponents/web-image-picker/main.jsshibappt-ui/dist/html-templates/circular-menu/web-image-picker.htmlhttps://circular-menu.local/html-templates/circular-menu/web-image-picker.html
custom-ribbonmodules/custom-ribbon/main.jsshibappt-ui/dist/html-templates/circular-menu/custom-ribbon.htmlhttps://circular-menu.local/html-templates/circular-menu/custom-ribbon.html
cross-pagemodules/cross-page/main.jsshibappt-ui/dist/html-templates/circular-menu/cross-page.htmlhttps://circular-menu.local/html-templates/circular-menu/cross-page.html

Note: mod_paperjs/html (https://paperjs.local) and mod_vtracer (https://vtracer.local) maintain standalone JS/HTML bundles, while lightweight dialogs such as PluginSettingsWebWindow render inline HTML via NavigateToString.

2. Custom Vite Plugins (moveHtmlPlugin.js & fix-paths.cjs) ​

  • moveHtmlPlugin.js: Recursively traces static import, dynamic import(), and Vite __vite__mapDeps graphs to copy exact transitive JS/CSS chunks into mod_design/html, mod_colorpicker/html, and mod_Fonts/html, while stripping crossorigin attributes.
  • fix-paths.cjs: Rewrites /assets/... paths to ./assets/... across .html, .js, and .css files, verified afterward by verify-web-assets.ps1.

3. Shared Vue Composables (shibappt-ui/src/shared/composables/) ​

1. useWebView2.js — Bidirectional Messaging ​

javascript
import { useWebView2 } from '@/shared/composables/useWebView2.js'

const { postMessage, sendMessage, onMessage } = useWebView2()

// Fire-and-forget command to C#
postMessage({ action: 'applyAlign', mode: 'left' })

// Promise-based request/response (auto-attaches messageId with 10s timeout)
const res = await sendMessage({ action: 'getSlideStats' })

// Subscribe to C# push events (returns unsubscribe callback)
const stop = onMessage('selectionChanged', (payload) => {
  console.log('Selection updated:', payload)
})

2. useI18n.js — Reactive Localization ​

javascript
import { useI18n } from '@/shared/composables/useI18n.js'

const { t, currentLocale } = useI18n()
const saveLabel = computed(() => t('ui.common.save', '保存'))

3. useTheme.js & useConfirmDialog.js ​

  • useTheme(): HTML templates pre-set data-theme="dark" in <head> to avoid startup flash; useTheme() listens to themeChanged / initialTheme and syncs data-theme and .dark CSS variables (shadcn.css).
  • useConfirmDialog(): Promise-based modal dialog (await showConfirmDialog(...)) replacing blocking window.confirm() calls inside WebView2.