FoundKey/packages/client/src/widgets/button.vue
syuilo 09fe55379e
client: check input for aiscript
af1c9251fc
5f3640c7fd

Co-authored-by: Johann150 <johann.galle@protonmail.com>
Changelog: Fixed
2023-02-10 20:06:31 +01:00

103 lines
2.1 KiB
Vue

<template>
<div class="mkw-button">
<MkButton :primary="widgetProps.colored" full @click="run">
{{ widgetProps.label }}
</MkButton>
</div>
</template>
<script lang="ts" setup>
import { AiScript, parse } from '@syuilo/aiscript';
import { useWidgetPropsManager, Widget, WidgetComponentExpose } from './widget';
import { GetFormResultType } from '@/scripts/form';
import * as os from '@/os';
import { createAiScriptEnv } from '@/scripts/aiscript/api';
import { $i } from '@/account';
import MkButton from '@/components/ui/button.vue';
const name = 'button';
const widgetPropsDef = {
label: {
type: 'string' as const,
default: 'BUTTON',
},
colored: {
type: 'boolean' as const,
default: true,
},
script: {
type: 'string' as const,
multiline: true,
default: 'Mk:dialog("hello" "world")',
},
};
type WidgetProps = GetFormResultType<typeof widgetPropsDef>;
// 現時点ではvueの制限によりimportしたtypeをジェネリックに渡せない
//const props = defineProps<WidgetComponentProps<WidgetProps>>();
//const emit = defineEmits<WidgetComponentEmits<WidgetProps>>();
const props = defineProps<{
widget?: Widget<WidgetProps>;
}>();
const emit = defineEmits<{
(ev: 'updateProps', widgetProps: WidgetProps): void;
}>();
const { widgetProps, configure } = useWidgetPropsManager(name,
widgetPropsDef,
props,
emit,
);
const run = async (): Promise<void> => {
const aiscript = new AiScript(createAiScriptEnv({
storageKey: 'widget',
token: $i?.token,
}), {
in: (q) => {
return new Promise(ok => {
os.inputText({
title: q,
}).then(({ canceled, result: a }) => {
if (canceled) return;
ok(a);
});
});
},
out: (_value) => {
// nop
},
log: (_type, _params) => {
// nop
},
});
let ast;
try {
ast = parse(widgetProps.script);
} catch (err) {
os.alert({
type: 'error',
text: 'Syntax error :(',
});
return;
}
try {
await aiscript.exec(ast);
} catch (err) {
os.alert({
type: 'error',
text: err,
});
}
};
defineExpose<WidgetComponentExpose>({
name,
configure,
id: props.widget ? props.widget.id : null,
});
</script>