useHostAction
HOOK

HOOKS & API / 宿主动作

useHostAction

从桌面小组件的点击交互中调用宿主安全动作:打开外部网页、复制文本到剪贴板、打开当前小组件的编辑设置面板,或更新组件设置项。

签名#

签名
function useHostAction(): (
  action: string,
  payload?: Record<string, any>
) => any

可用宿主动作#

openURL{ url: string }公网链接
在默认浏览器中打开公网 https:// 或 http:// 链接,例如 act("openURL", { url: "https://ideskset.com" })(自动拦截 file:// 和内网地址)。
copyText{ text: string }剪贴板
将文本复制到 macOS 剪贴板,例如 act("copyText", { text: "#0071E3" })。
openInspector无参数编辑面板
打开当前小组件的「编辑小组件」配置抽屉,例如 act("openInspector")。
updateSetting{ key, value }配置项
更新 deskpack.json 中声明的配置项,例如 act("updateSetting", { key: "goal", value: 10 })(通常直接用 useSetting 更方便)。

示例:带一键复制与跳转的快捷工具栏#

TSX
import React, { Button, HStack, Spacer, Text, VStack, useHostAction, useState, useWidget } from "deskset-react";

export default function QuickLinks() {
  const { theme, t } = useWidget();
  const act = useHostAction();
  const [copied, setCopied] = useState(false);

  const handleCopy = () => {
    act("copyText", { text: "https://ideskset.com/docs/" });
    setCopied(true);
    setTimeout(() => setCopied(false), 1500);
  };

  return (
    <VStack
      maxWidth={true}
      maxHeight={true}
      padding={16}
      spacing={10}
      background={theme.isPure ? "clear" : "theme.card"}
      cornerRadius={theme.isPure ? 0 : theme.corner}
      clip={!theme.isPure}
    >
      <Text fontSize={14} fontWeight="semibold">{t("开发快捷入口", "Quick Actions")}</Text>
      <Spacer />
      <HStack spacing={8}>
        <Button
          title={t("打开文档", "Open Docs")}
          icon="safari"
          variant="filled"
          color="theme.accent"
          onClick={() => act("openURL", { url: "https://ideskset.com/docs/" })}
        />
        <Button
          title={copied ? t("已复制", "Copied") : t("复制链接", "Copy")}
          icon={copied ? "checkmark" : "doc.on.doc"}
          variant="tinted"
          onClick={handleCopy}
        />
        <Button
          icon="slider.horizontal.3"
          variant="tinted"
          onClick={() => act("openInspector")}
        />
      </HStack>
    </VStack>
  );
}

注意事项#

  • 在预览模式(useWidget().isPreview === true)下,所有宿主动作都会静默忽略,避免误触打开浏览器或修改剪贴板。
  • 社区小组件不能执行 Shell 命令、不能访问本地文件系统,也不能启动任意本机可执行程序。