91 lines
2.3 KiB
TypeScript
91 lines
2.3 KiB
TypeScript
/**
|
||
* iframe 与宿主页通信消息类型常量
|
||
*
|
||
* 消息格式:{ type: MESSAGE_TYPE, ...其他字段 }
|
||
* 发送方式:window.parent.postMessage(message, "*")
|
||
*/
|
||
|
||
// 发送给宿主页的消息类型
|
||
export const POST_MESSAGE_TYPES = {
|
||
// 全屏切换
|
||
FULLSCREEN: "fullscreen",
|
||
// 会话是否处于聊天态
|
||
IS_CHATTING: "isChatting",
|
||
// 选择预定义 skill
|
||
SELECT_SKILL: "selectSkill",
|
||
// 打开 skill 选择对话框
|
||
OPEN_SKILL_DIALOG: "openSkillDialog",
|
||
} as const;
|
||
|
||
// 接收来自宿主页的消息类型
|
||
export const RECEIVE_MESSAGE_TYPES = {
|
||
// 选中的 skill 数据
|
||
SELECTED_SKILL: "selectedSkill",
|
||
} as const;
|
||
|
||
// 消息类型
|
||
export type PostMessageType =
|
||
(typeof POST_MESSAGE_TYPES)[keyof typeof POST_MESSAGE_TYPES];
|
||
export type ReceiveMessageType =
|
||
(typeof RECEIVE_MESSAGE_TYPES)[keyof typeof RECEIVE_MESSAGE_TYPES];
|
||
|
||
// 消息数据类型
|
||
export interface FullscreenMessage {
|
||
type: typeof POST_MESSAGE_TYPES.FULLSCREEN;
|
||
fullscreen: boolean;
|
||
}
|
||
|
||
export interface IsChattingMessage {
|
||
type: typeof POST_MESSAGE_TYPES.IS_CHATTING;
|
||
isChatting: boolean;
|
||
}
|
||
|
||
export interface SelectSkillMessage {
|
||
type: typeof POST_MESSAGE_TYPES.SELECT_SKILL;
|
||
skill_id: string[];
|
||
}
|
||
|
||
export interface OpenSkillDialogMessage {
|
||
type: typeof POST_MESSAGE_TYPES.OPEN_SKILL_DIALOG;
|
||
openSkillDialog: true;
|
||
}
|
||
|
||
export interface SelectedSkillMessage {
|
||
type: typeof RECEIVE_MESSAGE_TYPES.SELECTED_SKILL;
|
||
id: string | number;
|
||
title: string;
|
||
}
|
||
|
||
type UnknownRecord = Record<string, unknown>;
|
||
|
||
function asRecord(value: unknown): UnknownRecord | null {
|
||
if (typeof value !== "object" || value === null) {
|
||
return null;
|
||
}
|
||
return value as UnknownRecord;
|
||
}
|
||
|
||
export function isSelectedSkillMessage(value: unknown): value is SelectedSkillMessage {
|
||
const record = asRecord(value);
|
||
if (record?.type !== RECEIVE_MESSAGE_TYPES.SELECTED_SKILL) {
|
||
return false;
|
||
}
|
||
const { id, title } = record;
|
||
const isValidId = typeof id === "string" || typeof id === "number";
|
||
return isValidId && typeof title === "string" && title.trim().length > 0;
|
||
}
|
||
|
||
// 发送消息的辅助函数
|
||
export function sendToParent(
|
||
message:
|
||
| FullscreenMessage
|
||
| IsChattingMessage
|
||
| SelectSkillMessage
|
||
| OpenSkillDialogMessage,
|
||
): void {
|
||
console.log("[iframe] sendToParent:", message);
|
||
if (window.parent !== window) {
|
||
window.parent.postMessage(message, "*");
|
||
}
|
||
}
|