Skip to content

UI组件.js ​

查看原文件

js
/**
 * 全部 11 类 UI 组件集中在本文件。公开入口:@kodet/content 的 Blocks、Page、UI。
 * 数据展示 UI.get()/事件 target 的公开快照;实际写插件用注释中的调用,不直接把这些对象传给 Page。
 * id 在相应容器内唯一;input/webView 必填,其余可省略。需要 UI(id) 定位时显式设置。
 * 所有点击使用 onClick,接受 Host 命令或函数;其他事件接受函数。回调对象由 SDK 自动生成。
 */
/**
 * 文本。支持当前宿主的 Markdown 渲染;样式由宿主主题统一提供。
 * 调用写法:
 *
 * blocks.text("支持 **Markdown**", {
 *     id: "intro",
 *     onClick: Host.openPage("about"),
 * });
 *
 * blocks.text("简写", Host.back());
 * blocks.text("函数点击", async event => {
 *     await toast.show(event.id);
 * });
 */
const text = {
    type: "text",
    id: "intro",
    text: "支持 **Markdown**",
};
/** 分割线。调用写法:blocks.divider(12, { id: "gap" }); */
const divider = {
    type: "divider",
    id: "gap",
    size: 12,
};
/**
 * 列表。header、tags、author 都有独立点击和顶层业务字段。
 * 调用写法:
 *
 * const list = blocks.list({
 *     id: "book_list",
 *     style: "media",
 *     ratio: "poster",
 *     orientation: "vertical",
 *     columns: 3,
 *     adaptiveColumns: true,
 * });
 *
 * list.header({ name: "推荐", actionText: "更多" });
 * const item = list.item({ id: "book_1", name: "书名", score: "9.0" });
 * item.tag("完结", { onClick: Host.openPage("finished") });
 * item.author({ name: "作者", onClick: Host.openPage("author") });
 *
 * item 的 tags 数组也可直接传入;.tag() 追加,.author() 替换。
 * list.item() 返回条目句柄,下一条继续调用 list.item()。
 */
const list = {
    type: "list",
    id: "book_list",
    style: "media",
    ratio: "poster",
    orientation: "vertical",
    columns: 3,
    adaptiveColumns: true,
    header: {
        id: "books_header",
        name: "推荐",
        desc: "列表说明",
        actionText: "更多",
        image: "",
        imageHeaders: {},
    },
    items: [
        {
            id: "book_1",
            name: "书名",
            desc: "简介",
            image: "@res/cover.png",
            imageHeaders: {},
            label: "更新中",
            score: "9.0",
            bookId: "book-1",
            tags: [
                {
                    id: "tag_finished",
                    name: "完结",
                    desc: "标签说明",
                    image: "",
                    imageHeaders: {},
                    // 可选 onClick,结构与其他点击相同。
                },
            ],
            author: {
                id: "book_author",
                name: "作者",
                desc: "作者介绍",
                image: "",
                imageHeaders: {},
            },
        },
    ],
};
/**
 * 轮播图。没有 header,条目不支持 label/score/tags/author。
 * 调用写法:
 *
 * const banner = blocks.banner({ id: "banner", ratio: "strip" });
 * banner.item({ name: "轮播标题", image: "@res/banner.png" });
 */
const banner = {
    type: "banner",
    id: "banner",
    style: "image",
    ratio: "strip",
    items: [
        {
            id: "banner_1",
            name: "轮播标题",
            desc: "轮播说明",
            image: "@res/banner.png",
            imageHeaders: {},
            // 可选 onClick;自动轮播间隔、动画时长不是当前公开参数。
        },
    ],
};
/**
 * 工具组。header 与列表标题结构相同,item 与轮播条目结构相同。
 * 调用写法:
 *
 * const tools = blocks.tools({ id: "tools", style: "card", layout: "grid", columns: 3 });
 * tools.header({ name: "常用工具", actionText: "更多" });
 * tools.item({ name: "工具名称", desc: "短介绍", onClick: Host.openPage("tool") });
 */
const tools = {
    type: "tools",
    id: "tools",
    style: "card",
    layout: "grid",
    columns: 3,
    adaptiveColumns: true,
    header: {
        name: "常用工具",
        desc: "",
        actionText: "更多",
        image: "",
        imageHeaders: {},
    },
    items: [
        {
            id: "tool_1",
            name: "工具名称",
            desc: "短介绍",
            image: "",
            imageHeaders: {},
        },
    ],
};
/**
 * 独立入口。不需要放进 list;没有 style/persist/storageKey/score/tags 参数。
 * 调用写法:
 *
 * blocks.entry({
 *     id: "favorite",
 *     name: "收藏",
 *     desc: "查看收藏内容",
 *     onClick: Host.openPage("favorite"),
 * });
 */
const entry = {
    type: "entry",
    id: "favorite",
    name: "收藏",
    desc: "查看收藏内容",
    image: "",
    imageHeaders: {},
    // 可选 onClick,结构见 Host功能.js。
};
/**
 * 开关。id 不等于存储 key,自动持久化必须显式开启。
 * 调用写法:
 *
 * blocks.switch({
 *     id: "remember",
 *     name: "记住选择",
 *     defaultValue: false,
 *     persist: "remember", // 组件 id 与持久化键独立。
 *     onChange: async event => {
 *         await toast.show(String(event.value));
 *     },
 * });
 */
const switchControl = {
    type: "switch",
    id: "remember",
    name: "记住选择",
    desc: "下次继续使用",
    defaultValue: false,
    persist: "remember",
};
/**
 * 选择器。values 接受字符串或 {name,value?},省略value取name,业务值必须唯一。
 * persist 是明确字符串键或false,不自动使用id。
 * 调用写法:
 *
 * blocks.select({
 *     id: "quality",
 *     name: "清晰度",
 *     values: ["自动", "高清"],
 *     defaultValue: "自动",
 *     onChange: async event => {
 *         await toast.show(event.value);
 *     },
 * });
 */
const select = {
    type: "select",
    id: "quality",
    name: "清晰度",
    desc: "请选择",
    values: ["自动", "高清"],
    defaultValue: "自动",
    multiple: false,
    persist: false,
    // 单选事件 value 为string;multiple:true时defaultValue/value/target.value/get/update/persist均为真实JSON数组。
};
/**
 * blocks.select({multiple:true,name:'偏好',desc:'可清空',values:[{name:'冒险',value:'adventure'},'日常'],
 *   defaultValue:[],persist:'tags',onChange(ctx){console.log(ctx.value,ctx.target.value);}});
 * 普通多选在页面内显示可换行选项,点击即时提交数组。
 * []表示未选择;数组去重按values顺序,动态删项保留有效值,明确无效值/类型拒绝。
 * 用户每次有效点击立即保存并回调一次;程序更新/恢复不回调,multiple变化必须replace。
 */
/**
 * 输入框。通过 UI(id).get().text 读取;onChange/onSubmit 的 ctx.value 为当前文本。
 * 统一普通文本,默认单行;multiline: true 开启多行,maxLines 默认 5,只限制显示行数。
 * maxLines 必须是正整数且仅可在多行时设置;超出后内部滚动,保留完整文本,不自动保存。
 * 调用写法:
 *
 * blocks.input({ id: "nickname", hint: "请输入称呼", text: "" });
 * blocks.input({ id: "note", hint: "请输入备注", multiline: true, maxLines: 3 });
 * const snapshot = await UI("nickname").get();
 * const nickname = snapshot.text;
 */
const input = {
    type: "input",
    id: "nickname", // 必填。
    hint: "请输入称呼",
    text: "",
    multiline: false,
    maxLines: 1,
};
/**
 * WebView。调用时 url/html 二选一;底层归一化后另一个字段为空字符串。
 * ctx.target / UI.get() 中的 documentId、generation、title、progress、loading、canGoForward
 * 是原生实时只读字段,WebView 创建和 UI.update 都拒绝写入;其他组件的同名字段仍可作为普通业务 JSON。
 * url、canGoBack 保留现有配置与更新语义,不属于这六个只读保留字段。
 * 调用写法:
 *
 * blocks.webView({
 *     id: "web",
 *     html: "<p>网页内容</p>",
 *     height: "300px",
 *     onMessage: async event => {
 *         await toast.show(JSON.stringify(event.value.data));
 *     },
 * });
 */
const webView = {
    type: "webView",
    id: "web", // 必填;页面按 ID 保留网页实例。
    url: "",
    html: "<p>网页内容</p>",
    baseURL: "https://example.invalid/",
    height: "300px",
    minHeight: "180px",
    maxHeight: "60vh",
    style: "card",
    headers: {},
    userAgent: "",
    injectJs: "",
    navigation: "normal",
    canGoBack: true,
    autoConfirm: {
        urlContains: "", // 与下两项至少提供一种非空条件。
        urlRegex: "",
        titleContains: "完成",
        match: "any", // any(默认)/all。
        delay: 200, // 非负毫秒数,默认 0。
        once: true, // 当前来源只确认一次,默认 true。
    },
    // onLoad/onError/onMessage/onAutoConfirm 在声明中绑定,公开快照不包含回调。
};
/** 四种网页事件的 event.value,不是四种组件配置。 */
const webViewEventValues = {
    onLoad: {
        url: "https://example.invalid/",
        title: "网页标题",
        loading: false,
        progress: 100,
        canGoBack: false,
        canGoForward: false,
    },
    onError: {
        url: "https://example.invalid/",
        code: -1,
        message: "错误说明",
    },
    onMessage: {
        url: "https://example.invalid/",
        origin: "https://example.invalid",
        isMainFrame: true,
        documentId: "opaque-document-id",
        generation: 1,
        data: {
            text: "消息",
        },
    },
    onAutoConfirm: {
        url: "https://example.invalid/",
        title: "完成",
    },
};
/**
 * 声明 onMessage 后,网页内可以 Kodet.postMessage(data);这是网页桥,不是 QuickJS 全局 SDK。
 * QuickJS 向网页发送:await UI("web").postMessage(data)。
 * 网页接收:addEventListener("kodetmessage", event => { ... event.detail ... })。
 *
 * 其他网页调用:
 * await UI("web").reload({ ignoreCache: true });
 * const changed = await UI("web").goBack();
 * const changed = await UI("web").goForward();
 * const title = await UI("web").evaluate("Promise.resolve(document.title)");
 * // 等待 Promise 结果;异常 SCRIPT_ERROR,8 秒超时 TIMEOUT,导航/移除 ABORTED。
 * // 取消等待不能撤销已经执行的网页 JS、副作用或定时器。
 * const cookie = await UI("web").getCookie(); // 省略 URL 时使用当前主文档 URL。
 * const info = await UI("web").getCookieInfo(); // 不支持 GET_COOKIE_INFO 时明确 NOT_SUPPORTED。
 * await UI("web").setCookie("https://example.invalid/", "token=value; Path=/; Secure");
 * await UI("web").removeCookie("https://example.invalid/", { name: "token", path: "/" });
 * await UI("web").clearCookies();
 * await UI("web").update({ html: "<p>新内容</p>", autoConfirm: null });
 *
 * 默认独立临时 Profile;显式同名 session 才共享网页数据,更换 session 用 replace。
 * 当前 Android 实现要求独立 WebView Profile,不支持时会报告不可用。
 * 普通页面和底部面板可通过网页视频的原生入口自动全屏,不增加 JS 配置;退出保留同一网页、积木高度和滚动位置。
 * 全屏期间暂停 auto 高度采样,不把临时全屏视口写回积木;隐藏、替换或释放时结束全屏。
 * Cookie 方法只操作该积木绑定的 Profile,不访问其它 WebView,也不与 http.session 自动同步。
 * getCookieInfo 返回只读结构化快照;普通事件和 UI get 快照都不会泄露 Cookie。
 * 网页消息上限 64 KiB;页面移除/销毁时释放实例,列表 Holder 回收不等于销毁网页。
 */
/**
 * 通用 UI 操作(均异步):
 * const exists = await UI("intro").exists();
 * const snapshot = await UI("intro").get();
 * await UI("intro").update({ text: "新文本" });
 * await UI("intro").replace(blocks => {
 *     blocks.entry({ name: "替换成入口", onClick: Host.back() });
 * });
 * await UI("intro").remove();
 *
 * 根集合新增:await UI().append(b => { b.text("新增提示", { id: "notice" }); });
 * 条目追加:await UI("book_list").items.append({ id: "book_2", name: "新作品" });
 * 插入:await UI("book_list").items.insert({ id: "book_0", name: "首项" }, { at: 0 });
 * 移动:await UI("book_list").item("book_2").move({ before: "book_0" });
 * 集合还有 prepend / replaceAll / clear;clear 保留空集合供后续追加。
 * 隐藏/恢复:await UI("notice").hide(); await UI("notice").show(); 不占空间,保留状态。
 * 组件及条目都有 before / after,可在自身前后插入同级节点。
 * position 三选一:{ at: 0 } / { before: "id" } / { after: "id" }。
 * 下标包含隐藏节点;移动按取出自身后的集合计数,非法位置不会自动修正。
 *
 * 原子批量:
 * await UI.batch(ui => {
 *     ui("intro").update({ text: "新的说明" });
 *     ui("book_list").items.append({ id: "book_3", name: "第三本" });
 * });
 * batch 内同步收集,不 await,不读取、不做 IO;必须用传入的 ui,最多 200 项修改。
 * 未捕获异常或宿主校验失败则整批不提交;同步校验错误若主动捕获,仅跳过该项并清理其回调。
 * 积木 builder 内不允许重入调用 ui 修改方法;并发刷新/输入导致 CONFLICT 时重新读取后再决定。
 * 所有更新可传 { animate: false };整批关闭动画传 batch 第二参。
 * 首次显示/切页无额外文本渐显,已露出内容的显式 UI 更新默认有过渡;replace 会重建被替换状态。
 * 连续文字更新承接当前透明度和可绘制边界,隐藏替换前不提前放出旧长文字;临时clip只约束绘制,结束/取消/回收归还,不缩放或重测字形。
 * 详情里的积木批量更新、Markdown隐藏替换与info/actions尺寸变化共用目录的几何owner。
 * 原子绑定前捕获旧布局,绘制高度、合法滚动范围与真实scrollY一起过渡,工具栏读取同一实际scrollY。
 * 列表仍测量自然终态,用户滚动可接管;首次/恢复/animate:false直接提交终态,不增加作者API。
 * 弹窗根集合:dialog.ui().append(...);弹窗事件内 UI.batch 指向弹窗。
 *
 * 条目定位:UI("book_list").item("book_1"),支持 exists/get/update/replace/remove。
 * 条目 replace 传条目配置;组件 replace 必须恰好一个积木,目标 ID 保留。
 * get 返回扁平公开快照,不包含回调,也不保证存在 type 字段。
 * update 只改数据/样式;id、子项目、header、tags、author、事件用 replace 修改。
 * 开关/单选用 update({value:...}),不会触发 onChange;单选还可更新 values。
 * UI 句柄保留创建时的页面/弹窗归属,不能在页面销毁后操作新页面中的同名组件。
 */
/** 输入框事件:每次变更收到字符串 ctx.value,IME 提交触发 onSubmit。
 * b.input({ id:'query', onChange(ctx) { }, async onSubmit(ctx) { await search(ctx.value); } });
 * 组件业务字段直接进入 ctx.target;持久化根入口参数仍须显式传入。
 */
/**
 * 按钮组。颜色全部使用平台 MD3 主题。
 * 调用:blocks.buttons({
 *     id: "actions", style: "tonal", shape: "pill", layout: "auto",
 *     items: [
 *         { id: "open", name: "打开", onClick: Host.openPage("about") },
 *         { id: "save", name: "保存", style: "filled", onClick(ctx) {} },
 *     ],
 * });
 * style: filled/tonal/outlined。filled 强调色白字;tonal 使用 tabs 选中指示器相同的浅色背景和灰字;outlined 强调色描边。
 * shape: pill/rounded;layout: auto(按实际宽度与文字换行)/column(竖排)。
 * items 为 1–24 项。每项 name 必填,无动作正常显示但不派发。
 * 单项未写 style 时继承组。业务字段直接写在项目上,由 ctx.target 读取;onClick 接受 Host 命令或函数。
 * 更新组:await UI("actions").update({ style: "outlined" });
 * 更新按钮:await UI("actions").item("save").update({ name: "已保存" });
 */
const buttons = {
    type: "buttons",
    id: "actions",
    style: "tonal",
    shape: "pill",
    layout: "auto",
    items: [
        { id: "open", name: "打开",
        },
        { id: "save", name: "保存",
            style: "filled",
        },
    ],
};

/** 普通事件的 target 是当前触发节点,不把整页或宿主身份混入业务对象。 */
const businessEvent = {
    id: "book_1", targetType: "item", event: "click",
    target: { id: "book_1", name: "书名", bookId: "book-1", request: { url: "/book/1" }, data: null, ext: ["普通业务值"] },
};
// await UI("book_1").update({ request: { url: "/book/2" }, data: null });
// request 整体替换,null 保留;删除字段使用 replace 并省略。嵌套字段只读。
// JSON 自有字段 "__proto__" 也按普通业务字段保留;动态 append/replace/batch、作者/标签子节点、UI.get 与 ctx.target 使用同一规则。