fs-walle-react-ts/src/LexEdit.tsx

122 lines
3.6 KiB
TypeScript

import * as React from 'react';
import * as _ from 'lodash';
import { componentForType } from './LexSingleInput';
import {
Card,
Button
} from 'semantic-ui-react';
const { Box } = require('reflexbox');
const serialize = function(obj: any) {
var str = [];
for (var p in obj) {
if (obj.hasOwnProperty(p)) {
str.push(encodeURIComponent(p) + '=' + encodeURIComponent(obj[p]));
}
}
return str.join('&');
};
export class LexEdit extends React.Component<any, any> {
imageRoot = '/png/';
constructor(props: any) {
super(props);
this.state = { lexItem: this.props.lexItem };
}
public render() {
let li = this.state.lexItem;
let editLang = this.props.fieldMetaMap.lang.get(li);
let langSelOpts = _.get<any>(this.props.selectionMeta, editLang, []);
let lexFields = _.keys(this.props.fieldMetaMap).map(field => {
let fieldMeta = this.props.fieldMetaMap[field];
let value = fieldMeta.get(li);
let origValue = fieldMeta.get(this.props.lexItem);
let options = fieldMeta.options;
let changed = !_.isEqual(value, origValue) && this.props.existing;
let sh = (v: any) => {
this.handleOnChange({ field, value: v });
};
let params = { field, sh, value, options, langSelOpts, changed };
return componentForType(fieldMeta.type, params);
});
return (
<Box m={2}>
<Card raised={true}>
<Card.Content>
<Card.Header>
{_.get<any>(li, 'label', '')}
<Button
floated="right"
icon="download"
size="tiny"
onClick={(e, d) => this.handleOnLoad(d)}
/>
<Button
floated="right"
icon="undo"
size="tiny"
onClick={(e, d) => this.handleOnUndo(d)}
/>
</Card.Header>
<Card.Meta>
language: {_.get<any>(li, '$.id', '')}
</Card.Meta>
<Card.Description>
{lexFields}
</Card.Description>
</Card.Content>
<Card.Content extra={true}>
<Button
basic={true}
fluid={true}
color="green"
onClick={(e, d) => this.handleOnSave(d)}
>
Save
</Button>
</Card.Content>
</Card>
</Box>
);
}
private handleOnUndo(event: any) {
let lexItem = this.props.lexItem;
this.setState({ lexItem });
}
private handleOnLoad(event: any) {
// this.props.load(this.state.lexItem)
let li = this.state.lexItem;
let word = this.props.fieldMetaMap.label.get(li);
let pos = this.props.fieldMetaMap.pos.get(li);
let args = serialize({ word, pos });
let morphQuery = '/api/morph?' + args;
fetch(morphQuery)
.then((response) => response.text())
.then((jsonMorph) => {
let morphDict = JSON.parse(jsonMorph);
let morphMeta = this.props.fieldMetaMap.morphclass;
let lexItem = morphMeta.set(this.state.lexItem, morphDict.morphclass);
this.setState({ lexItem });
})
.catch((e) => {
console.log('errored :', e);
});
}
private handleOnChange(event: any) {
let { field, value } = event;
let meta = this.props.fieldMetaMap[field];
let lexItem = meta.set(this.state.lexItem, value);
this.setState({ lexItem });
}
private handleOnSave(event: any) {
this.props.save(this.state.lexItem, this.props.fieldMetaMap);
if (!_.isEqual(this.state.lexItem, this.props.lexItem)) {
this.props.markDirty();
}
}
}