APLをJSXで書きたいんです・・・
途中までやってみて飽きたので、「こうしたらどう?」とか「これ使えばいいよ」みたいなコメントもらえると嬉しいです。
Input
const Template = ({ name }) => (
<Sequence>
<Container>
<Text
width="100%"
textAlign="center"
style="textStylePrimary2"
maxLines={2}
text={`<b>こんにちは。${name}</b>アシスタントのアレクサです。`}
/>
</Container>
</Sequence>
)
renderAlexaAPL(<Template name="John" />)
Output
{
"type": "Sequence",
"item": {
"type": "Container",
"items": [
{
"type": "Text",
"width": "100%",
"textAlign": "center",
"style": "textStylePrimary2",
"maxLines": 2,
"text": "<b>こんにちは。</b>アシスタントのアレクサです。"
}
]
}
}
途中までやろうとしたもの
react-json-rendererでJSONにはできるので、プロパティ変換処理書けばいけそうな気はするんです。
import React from 'react';
import { Renderer, convertToJSON } from 'react-json-renderer'
import JSONPretty from 'react-json-pretty';
import logo from './logo.svg';
import Greeding from './test'
import './App.css';
// Simple strings will be exported as component types and functions will be executed
const Sequence = 'Sequence'
const Text = 'Text'
const Container = 'Container'
const Welcome = ({ name }) =>
<Sequence>
<Container>
<Text
width="100%"
textAlign="center"
style="textStylePrimary2"
maxLines={2}
text="<b>こんにちは。</b>アシスタントのアレクサです。"
/>
</Container>
</Sequence>
// Returns the JSON payload to provide to the client
const convertToAPLJSON = (json) => {
const obj = JSON.parse(json)
switch (obj.type) {
case 'Sequence': {
let item = obj.props.children
if (item.props.children) {
item = convertToAPLJSON(JSON.stringify(item))
}
obj.props.item = item
delete obj.props.children
}
case 'Container': {
let items = obj.props.children
if (items && items.props.children) {
items = convertToAPLJSON(JSON.stringify(items))
}
if (!Array.isArray(items)) items = [items]
obj.props.items = items
delete obj.props.children
}
default:
break
}
const template = {
type: obj.type,
...obj.props
}
return template
}
export const createWelcome = (name) => {
const json = convertToJSON(<Welcome name={name} />)
return convertToAPLJSON(json)
}
function App() {
return (
<div className="App">
<header className="App-header">
<div style={{textAlign: 'left'}}>
<JSONPretty
id="json-pretty"
data={createWelcome()}
/>
</div>
</header>
</div>
);
}
export default App;
これだとこんな感じになる。