hippofish/packages/client/src/widgets/button.vue

107 lines
2 KiB
Vue
Raw Normal View History

2020-12-27 15:13:01 +01:00
<template>
2023-04-08 02:01:42 +02:00
<div class="mkw-button">
<MkButton :primary="widgetProps.colored" full @click="run">
{{ widgetProps.label }}
</MkButton>
</div>
2020-12-27 15:13:01 +01:00
</template>
<script lang="ts" setup>
import { onMounted, onUnmounted, ref, watch } from "vue";
import { Interpreter, Parser } from "@syuilo/aiscript";
import { createAiScriptEnv } from "@/scripts/aiscript/api";
import {
useWidgetPropsManager,
WidgetComponentEmits,
WidgetComponentProps,
} from "./widget";
import type { WidgetComponentExpose } from "./widget";
2023-07-17 00:32:32 +02:00
import type { GetFormResultType } from "@/scripts/form";
2023-04-08 02:01:42 +02:00
import * as os from "@/os";
import { $i } from "@/reactiveAccount";
2023-04-08 02:01:42 +02:00
import MkButton from "@/components/MkButton.vue";
2020-12-27 15:13:01 +01:00
2023-04-08 02:01:42 +02:00
const name = "button";
2020-12-27 15:13:01 +01:00
const widgetPropsDef = {
label: {
2023-04-08 02:01:42 +02:00
type: "string" as const,
default: "BUTTON",
2020-12-27 15:13:01 +01:00
},
colored: {
2023-04-08 02:01:42 +02:00
type: "boolean" as const,
default: true,
2020-12-27 15:13:01 +01:00
},
script: {
2023-04-08 02:01:42 +02:00
type: "string" as const,
multiline: true,
default: 'Mk:dialog("hello" "world")',
},
};
2020-12-27 15:13:01 +01:00
type WidgetProps = GetFormResultType<typeof widgetPropsDef>;
const props = defineProps<WidgetComponentProps<WidgetProps>>();
const emit = defineEmits<WidgetComponentEmits<WidgetProps>>();
2023-04-08 02:01:42 +02:00
const { widgetProps, configure } = useWidgetPropsManager(
name,
widgetPropsDef,
props,
2023-07-06 03:28:27 +02:00
emit,
);
const parser = new Parser();
const run = async () => {
const aiscript = new Interpreter(
2023-04-08 02:01:42 +02:00
createAiScriptEnv({
storageKey: "widget",
token: $i?.token,
}),
{
in: (q) => {
return new Promise((ok) => {
os.inputText({
title: q,
}).then(({ canceled, result: a }) => {
ok(a);
});
2020-12-27 15:13:01 +01:00
});
2023-04-08 02:01:42 +02:00
},
out: (value) => {
// nop
},
log: (type, params) => {
// nop
},
2023-07-06 03:28:27 +02:00
},
2023-04-08 02:01:42 +02:00
);
let ast;
try {
ast = parser.parse(widgetProps.script);
} catch (err) {
os.alert({
2023-04-08 02:01:42 +02:00
type: "error",
text: `Syntax error: ${err}`,
});
return;
2020-12-27 15:13:01 +01:00
}
try {
await aiscript.exec(ast);
} catch (err) {
os.alert({
2023-04-08 02:01:42 +02:00
type: "error",
text: String(err),
});
}
};
defineExpose<WidgetComponentExpose>({
name,
configure,
id: props.widget ? props.widget.id : null,
2020-12-27 15:13:01 +01:00
});
</script>