dsh-sansheng-liubu/sansheng/src/native/index.js

202 lines
7.9 KiB
JavaScript
Raw Blame History

This file contains ambiguous Unicode characters

This file contains Unicode characters that might be confused with other characters. If you think that this is intentional, you can safely ignore this warning. Use the Escape button to reveal them.

// dsh-go 原生接入:把纯视图树挂到宿主原生面板桥。
// 全程用特性探测(ctx.inject + typeof 检查),不 import 宿主内部源码。
import { buildPanelView } from './panel.js'
import { SEAT_IDS } from '../shared/roles.js'
const PANEL_ID = 'sansheng'
// 进程内缓存:原生作用域没有 workspaceId,只能由 sessionId 反查项目。
// 真实数据源需要宿主注入的服务或 HTTP 接通;拿不到时视图如实显示提示。
const viewBySession = new Map()
const selectionBySession = new Map()
const modelsBySession = new Map()
/** 把一个项目视图中各席的 sessionId 记入缓存,供 scope.sessionId 反查。 */
function cacheProject(project) {
if (!project || typeof project !== 'object') return
const seats = project.seats
for (const id of SEAT_IDS) {
let seat = null
if (Array.isArray(seats)) seat = seats.find((s) => s && s.id === id) || null
else if (seats && typeof seats === 'object') seat = seats[id] || null
if (seat && typeof seat.sessionId === 'string' && seat.sessionId) {
viewBySession.set(seat.sessionId, project)
}
}
}
/** 由 scope 反查项目视图:优先宿主注入的反查服务,其次 sessions.binding,最后进程内缓存。 */
function resolveProject(native, scope) {
const sid = scope && typeof scope.sessionId === 'string' ? scope.sessionId : null
const lookup = (native && (native.sansheng || native.sanshengProjects)) || null
if (lookup && typeof lookup.projectForScope === 'function') {
try {
const p = lookup.projectForScope(scope)
if (p) { cacheProject(p); return p }
} catch (e) { /* 特性探测失败,忽略 */ }
}
if (lookup && typeof lookup.projectForSession === 'function' && sid) {
try {
const p = lookup.projectForSession(sid)
if (p) { cacheProject(p); return p }
} catch (e) { /* ignore */ }
}
let workspaceId = null
try {
const sessions = native && native.sessions
if (sessions && typeof sessions.binding === 'function' && sid) {
const b = sessions.binding(sid)
workspaceId = (b && (b.workspaceId || (b.workspace && b.workspace.id))) || null
}
} catch (e) { /* ignore */ }
if (lookup && typeof lookup.projectForWorkspace === 'function' && workspaceId) {
try {
const p = lookup.projectForWorkspace(workspaceId)
if (p) { cacheProject(p); return p }
} catch (e) { /* ignore */ }
}
if (sid && viewBySession.has(sid)) return viewBySession.get(sid)
return null
}
/** 组装 buildPanelView 所需的 input。 */
function makeView(native, scope) {
const sid = scope && typeof scope.sessionId === 'string' ? scope.sessionId : null
const project = resolveProject(native, scope)
const selectedSeatId = sid && selectionBySession.has(sid) ? selectionBySession.get(sid) : null
const models = sid && modelsBySession.has(sid) ? modelsBySession.get(sid) : null
return buildPanelView({ project, selectedSeatId, models })
}
/** 归一化事件里的 action(dsh-go 可能回传对象或字符串 + value)。 */
function normalizeAction(event) {
const a = event && event.action
if (a && typeof a === 'object') return a
const v = event && event.value
if (v && typeof v === 'object' && typeof v.type === 'string') return v
if (typeof a === 'string') return Object.assign({ type: a }, v && typeof v === 'object' ? v : {})
return null
}
async function handleEvent(native, scope, event) {
const sid = scope && typeof scope.sessionId === 'string' ? scope.sessionId : null
const action = normalizeAction(event)
if (!action || typeof action.type !== 'string') return []
switch (action.type) {
case 'sansheng/select-seat': {
if (sid && action.seatId) selectionBySession.set(sid, action.seatId)
return [{ type: 'refresh', id: PANEL_ID }]
}
case 'sansheng/select-model': {
if (sid && action.seatId) selectionBySession.set(sid, action.seatId)
// 模型持久化需要宿主 HTTP / 服务接通;原生面板暂不静默写入。
return [{ type: 'toast', text: '模型选择在原生面板暂未接持久化,请在 Web 端保存(需真机核验)' }]
}
case 'sansheng/enter-session': {
// effect 契约暂无会话跳转;优先探测宿主扩展方法,否则如实提示。
const bridged = native && native.dshGo
const open =
(bridged && (bridged.openSession || bridged.navigate)) ||
(native && native.sansheng && native.sansheng.openSession)
if (typeof open === 'function' && action.sessionId) {
try {
await open(action.sessionId)
return [{ type: 'toast', text: '已请求打开会话' }]
} catch (e) { /* 落到提示分支 */ }
}
return [{ type: 'toast', text: '原生 effect 暂不支持会话跳转,请从宿主会话列表进入(需真机核验)' }]
}
default:
return []
}
}
/** 可选 data 提供者:尽力通过宿主 HTTP 的 list/project 反查项目(特性探测 fetch)。 */
function makeDataProvider(native, dshGo) {
return function data(scope, emit) {
let cancelled = false
const run = async () => {
if (typeof fetch !== 'function') return
const sid = scope && typeof scope.sessionId === 'string' ? scope.sessionId : null
if (!sid) return
const post = async (endpoint, payload) => {
const res = await fetch('/api/sansheng', {
method: 'POST',
credentials: 'same-origin',
headers: { 'content-type': 'application/json' },
body: JSON.stringify({ endpoint, payload: payload == null ? null : payload }),
})
if (!res.ok) throw new Error('HTTP ' + res.status)
const r = await res.json()
if (!r || r.ok !== true) throw new Error((r && r.error && r.error.message) || 'request failed')
return r.value
}
const list = await post('list')
const projects = list && Array.isArray(list.projects) ? list.projects : []
for (const meta of projects) {
const value = await post('project', { projectId: meta.id })
const project = value && value.project ? value.project : value
cacheProject(project)
const seats = project && project.seats
const found = Array.isArray(seats)
? seats.some((s) => s && s.sessionId === sid)
: seats && Object.values(seats).some((s) => s && s.sessionId === sid)
if (found) {
if (!cancelled) {
try { emit({ project }) } catch (e) { /* ignore */ }
try { if (dshGo && typeof dshGo.refresh === 'function') dshGo.refresh(PANEL_ID, scope) } catch (e) { /* ignore */ }
}
return
}
}
}
run().catch(() => {})
return () => { cancelled = true }
}
}
/**
* 原生接入入口。
* @param {object} ctx Cordis context(由宿主注入)。
* @returns {() => void} disposer
*/
export function install(ctx) {
if (!ctx || typeof ctx.inject !== 'function') return () => {}
return ctx.inject(['dshGo', 'sessions'], (native) => {
const dshGo = native && native.dshGo
// 特性探测:宿主没有 dshGo.panel 就安静退出(不是 dsh-go / 桥未就绪)。
if (!dshGo || typeof dshGo.panel !== 'function') return () => {}
const disposers = []
try {
const offPanel = native.dshGo.panel(PANEL_ID, {
view: (scope, caps) => makeView(native, scope),
data: makeDataProvider(native, native.dshGo),
})
if (typeof offPanel === 'function') disposers.push(offPanel)
} catch (e) { /* 桥不完整时保持静默 */ }
if (typeof native.dshGo.on === 'function') {
try {
const offOn = native.dshGo.on(PANEL_ID, (scope, event) => handleEvent(native, scope, event))
if (typeof offOn === 'function') disposers.push(offOn)
} catch (e) { /* ignore */ }
}
return () => {
for (const off of disposers) {
try { off() } catch (e) { /* ignore */ }
}
}
})
}
export default { install }