Sharkey/packages/frontend/src/widgets/WidgetButton.vue

106 lines
2.1 KiB
Vue
Raw Normal View History

<!--
SPDX-FileCopyrightText: syuilo and other misskey contributors
SPDX-License-Identifier: AGPL-3.0-only
-->
2020-12-27 06:13:01 -08:00
<template>
<div data-cy-mkw-button class="mkw-button">
<MkButton :primary="widgetProps.colored" full @click="run">
{{ widgetProps.label }}
2020-12-27 06:13:01 -08:00
</MkButton>
</div>
</template>
<script lang="ts" setup>
import { Interpreter, Parser } from '@syuilo/aiscript';
2023-09-28 19:22:59 -07:00
import { useWidgetPropsManager, Widget, WidgetComponentEmits, WidgetComponentExpose, WidgetComponentProps } from './widget.js';
2023-09-19 00:37:43 -07:00
import { GetFormResultType } from '@/scripts/form.js';
import * as os from '@/os.js';
import { createAiScriptEnv } from '@/scripts/aiscript/api.js';
import { $i } from '@/account.js';
import MkButton from '@/components/MkButton.vue';
2020-12-27 06:13:01 -08:00
const name = 'button';
2020-12-27 06:13:01 -08:00
const widgetPropsDef = {
label: {
type: 'string' as const,
default: 'BUTTON',
2020-12-27 06:13:01 -08:00
},
colored: {
type: 'boolean' as const,
default: true,
2020-12-27 06:13:01 -08:00
},
script: {
type: 'string' as const,
multiline: true,
default: 'Mk:dialog("hello" "world")',
},
};
2020-12-27 06:13:01 -08:00
type WidgetProps = GetFormResultType<typeof widgetPropsDef>;
2023-05-19 00:20:53 -07:00
const props = defineProps<WidgetComponentProps<WidgetProps>>();
const emit = defineEmits<WidgetComponentEmits<WidgetProps>>();
const { widgetProps, configure } = useWidgetPropsManager(name,
widgetPropsDef,
props,
emit,
);
2023-01-02 22:51:49 -08:00
const parser = new Parser();
const run = async () => {
2023-01-02 22:51:49 -08:00
const aiscript = new Interpreter(createAiScriptEnv({
storageKey: 'widget',
token: $i?.token,
}), {
in: (q) => {
return new Promise(ok => {
os.inputText({
title: q,
}).then(({ canceled, result: a }) => {
if (canceled) {
ok('');
} else {
ok(a);
}
2020-12-27 06:13:01 -08:00
});
});
2020-12-27 06:13:01 -08:00
},
out: (value) => {
// nop
},
log: (type, params) => {
// nop
},
});
let ast;
try {
2023-01-02 22:51:49 -08:00
ast = parser.parse(widgetProps.script);
} catch (err) {
os.alert({
type: 'error',
text: 'Syntax error :(',
});
return;
2020-12-27 06:13:01 -08:00
}
try {
await aiscript.exec(ast);
} catch (err) {
os.alert({
type: 'error',
text: err,
});
}
};
defineExpose<WidgetComponentExpose>({
name,
configure,
id: props.widget ? props.widget.id : null,
2020-12-27 06:13:01 -08:00
});
</script>