page.js 19 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514
  1. import React from 'react';
  2. import { Form, Input, InputNumber, Tabs, Switch, Checkbox, Row, Col, Button, Tag, Dropdown, Menu } from 'antd';
  3. import './index.less';
  4. import Page from '@src/containers/Page';
  5. import Block from '@src/components/Block';
  6. import Editor from '@src/components/Editor';
  7. // import ContextMenuLayout from '@src/layouts/ContextMenuLayout';
  8. // import Select from '@src/components/Select';
  9. // import FileUpload from '@src/components/FileUpload';
  10. import { formatFormError, generateUUID } from '@src/services/Tools';
  11. import { asyncSMessage } from '@src/services/AsyncTools';
  12. import { SentenceOption } from '../../../../Constant';
  13. // import { Preview } from '../../../stores/preview';
  14. import { Exercise } from '../../../stores/exercise';
  15. import { Sentence } from '../../../stores/sentence';
  16. import config from './index';
  17. const stopWords = [',', '.', ':', '!', ';', '?', '\\', '/', '`', '\'', '', '。', ',', '?', '!', '“', '”'];
  18. const htmlReg = /[.,!?。,!?“”]*<[^>]+>[.,!?。,!?“”]*/i;
  19. const sReg = /[.,!?。,!?“”]+/i;
  20. // const uuidReg = /@(.*)@(.*)/i;
  21. export default class extends Page {
  22. constructor(props) {
  23. super(props);
  24. this.targetWord = null;
  25. this.uuidMap = {};
  26. this.uuidList = [];
  27. const { id } = this.params;
  28. if (id) {
  29. config.title = '编辑长难句题目';
  30. } else {
  31. config.title = '添加长难句题目';
  32. }
  33. }
  34. initState() {
  35. return { currentKey: 'subject' };
  36. }
  37. init() {
  38. Exercise.allStruct().then(result => {
  39. result = result.filter(row => row.level === 2).map(row => { row.title = `${row.titleZh}/${row.titleEn}`; row.value = row.id; return row; });
  40. this.setState({ exercise: result });
  41. });
  42. }
  43. initData() {
  44. const { id } = this.params;
  45. const { form } = this.props;
  46. this.uuidMap = {};
  47. this.uuidList = [];
  48. this.targetWord = null;
  49. let handler;
  50. if (id) {
  51. handler = Sentence.getQuestion({ id });
  52. this.setState({ mode: 'setting' });
  53. } else {
  54. // "<p><span uuid='CmS0'>The</span> <span uuid='2BKs'>furthest</span> <span uuid='3JxJ'>distance</span> <span uuid='hVsF'>in</span> <span uuid='OlAJ'>the</span> <span uuid='RrCt'>world</span>&nbsp;<span uuid='Axff'></span>&nbsp;<span uuid='wovI'></span></p><p><span uuid='odI3'>Is</span> <span uuid='HHXm'>not</span> <span uuid='ld8s'>between</span> <span uuid='wuh2'>life</span> <span uuid='o29m'>and</span> <span uuid='NLCc'>death</span>&nbsp;<span uuid='GCaB'></span></p><p><span uuid='WENt'>But</span> <span uuid='kHpB'>when</span> <span uuid='nMb4'>I</span> <span uuid='CNoW'>stand</span> <span uuid='EwJh'>in</span> <span uuid='MOL4'>front</span> <span uuid='Vg1e'>of</span> <span uuid='aZAW'>you</span>&nbsp;<span uuid='z7zD'></span></p><p><span uuid='hLr7'>Yet</span> <span uuid='s7lJ'>you</span> <span uuid='xhmd'>don\"t</span> <span uuid='uKQk'>know</span> <span uuid='mDus'>that</span> <span uuid='neve'>I</span> <span uuid='yWSc'>love</span> <span uuid='7JRW'>you</span></p>"
  55. handler = Promise.resolve({ no: 1, question: { stem: '' } });
  56. }
  57. handler
  58. .then(result => {
  59. result.isPaper = !!result.isPaper;
  60. result.isTrail = !!result.isTrail;
  61. result.question.questionType = 'sentence';
  62. result.question.answer = result.question.answer || {};
  63. form.getFieldDecorator('question.answer.subject');
  64. form.getFieldDecorator('question.answer.predicate');
  65. form.getFieldDecorator('question.answer.object');
  66. form.getFieldDecorator('question.answer.options');
  67. form.getFieldDecorator('question.qxContent');
  68. form.getFieldDecorator('question.stem');
  69. form.getFieldDecorator('question.questionType');
  70. form.getFieldDecorator('question.place');
  71. form.getFieldDecorator('question.id');
  72. form.getFieldDecorator('questionId');
  73. form.getFieldDecorator('chinese');
  74. form.getFieldDecorator('title');
  75. form.getFieldDecorator('isPaper');
  76. form.getFieldDecorator('isTrail');
  77. form.getFieldDecorator('no');
  78. form.getFieldDecorator('id');
  79. form.setFieldsValue(result);
  80. const { stem } = result.question;
  81. const { subject, predicate, object } = result.question.answer;
  82. this.setState({ data: result, subject, predicate, object, stem });
  83. // 生成uuid列表
  84. this.uuidList = (stem || '').replace(/<span\suuid=["']([^>]*)["']>([^<>]*)<\/span>/g, '@@$1_@_$2@@').split('@@').filter(row => row.indexOf('_@_') >= 0).map(row => {
  85. const [uuid, content] = row.split('_@_');
  86. this.uuidMap[uuid] = content;
  87. return uuid;
  88. });
  89. console.log(this.uuidList, this.uuidMap);
  90. });
  91. }
  92. submit() {
  93. const { form } = this.props;
  94. const { mode } = this.state;
  95. if (mode !== 'setting') {
  96. asyncSMessage('请先退出编辑模式', 'warn');
  97. return;
  98. }
  99. form.validateFields((err) => {
  100. if (!err) {
  101. const data = form.getFieldsValue();
  102. data.isTrail = data.isTrail ? 1 : 0;
  103. data.isPaper = data.isPaper ? 1 : 0;
  104. data.question.stem = this.state.stem;
  105. data.question.description = data.question.stem.replace(/<[^>]+>/g, '');
  106. data.question.answer = data.question.answer || {};
  107. let handler;
  108. if (!data.id) {
  109. handler = Sentence.addQuestion(data);
  110. } else {
  111. handler = Sentence.editQuestion(data);
  112. }
  113. handler.then((result) => {
  114. asyncSMessage('保存成功');
  115. if (data.id) {
  116. linkTo(`/subject/sentence/question/${data.id}`);
  117. } else {
  118. linkTo(`/subject/sentence/question/${result.id}`);
  119. }
  120. }).catch((e) => {
  121. if (e.result) form.setFields(formatFormError(data, e.result));
  122. });
  123. }
  124. });
  125. }
  126. removeAnswer(key, index) {
  127. const { setFieldsValue, getFieldValue } = this.props.form;
  128. const data = getFieldValue(`question.answer.${key}`) || [];
  129. if (data.length > index) {
  130. data.splice(index, 1);
  131. }
  132. setFieldsValue({ [`question.answer.${key}`]: data });
  133. this.setState({ [key]: data });
  134. }
  135. addAnswer(key, uuid, text) {
  136. const { setFieldsValue, getFieldValue } = this.props.form;
  137. const data = getFieldValue(`question.answer.${key}`) || [];
  138. data.push([{ text, uuid }]);
  139. setFieldsValue({ [`question.answer.${key}`]: data });
  140. this.setState({ [key]: data });
  141. }
  142. appendAnswer(key, index, uuid, text) {
  143. const { setFieldsValue, getFieldValue } = this.props.form;
  144. const data = getFieldValue(`question.answer.${key}`) || [];
  145. data[index].push({ text, uuid });
  146. setFieldsValue({ [`question.answer.${key}`]: data });
  147. this.setState({ [key]: data });
  148. }
  149. renderContextMenu() {
  150. const { getFieldValue } = this.props.form;
  151. const { currentKey } = this.state;
  152. const uuid = this.targetWord.getAttribute('uuid');
  153. const text = this.targetWord.innerText;
  154. const data = getFieldValue(`question.answer.${currentKey}`) || [];
  155. const items = [];
  156. items.push({ title: '新答案', command: 'new' });
  157. data.forEach((row, i) => {
  158. // 过滤已经在的答案
  159. if (row.filter(r => r.uuid !== uuid).length !== row.length) return;
  160. items.push({ title: `插入: ${row.map(r => r.text).join(', ')}`, command: 'append', i });
  161. });
  162. return (
  163. <Menu onClick={k => this.clickContentMenu(currentKey, k, uuid, text)}>
  164. {items.map((item, i) => {
  165. return <Menu.Item key={i} command={item.command} i={item.i}>{item.title || item.name}</Menu.Item>;
  166. })}
  167. </Menu>
  168. );
  169. }
  170. clickContentMenu(key, k, uuid, text) {
  171. const item = k.item.props;
  172. switch (item.command) {
  173. case 'new':
  174. this.addAnswer(key, uuid, text);
  175. break;
  176. case 'append':
  177. this.appendAnswer(key, item.i, uuid, text);
  178. break;
  179. default:
  180. }
  181. }
  182. generateContent(content) {
  183. const { setFieldsValue } = this.props.form;
  184. // 处理编辑器未清除的标签: 主要是包含空格的标签属性
  185. content = content.replace(/<[^>]+\s+[^>]+>([^<>]*)<\/[^>]+>/g, '$1');
  186. this.index = 0;
  187. const list = ['</p><p>', ' ', ',', '.', '!', '?', '&nbsp;', ':', ';'];
  188. const result = this.splitList(list, 0, content);
  189. // console.log(this.uuidList, this.uuidMap);
  190. // 对比答案,是否uuid存在
  191. let { subject = [], predicate = [], object = [] } = this.state;
  192. let flag = false;
  193. subject = subject.map(row => {
  194. return row.filter(r => {
  195. if (this.uuidMap[r.uuid] === r.text) return true;
  196. flag = true;
  197. return false;
  198. });
  199. }).filter(row => row.length);
  200. predicate = predicate.map(row => {
  201. return row.filter(r => {
  202. if (this.uuidMap[r.uuid] === r.text) return true;
  203. flag = true;
  204. return false;
  205. });
  206. }).filter(row => row.length);
  207. object = object.map(row => {
  208. return row.filter(r => {
  209. if (this.uuidMap[r.uuid] === r.text) return true;
  210. flag = true;
  211. return false;
  212. });
  213. }).filter(row => row.length);
  214. if (flag) {
  215. asyncSMessage('修改影响答案,请再次确认答案', 'warn');
  216. setFieldsValue({ 'question.answer.subject': subject, 'question.answer.predicate': predicate, 'question.answer.object': object });
  217. // console.log(subject, predicate, object);
  218. this.setState({ subject, predicate, object });
  219. }
  220. return result;
  221. }
  222. splitList(list, index, content) {
  223. if (list.length === index) {
  224. return this.generateText(content);
  225. }
  226. const result = content.split(list[index]).map(row => {
  227. return this.splitList(list, index + 1, row);
  228. });
  229. if (result.length === 0) return content;
  230. if (result.length === 1) return result[0];
  231. return result.join(list[index]);
  232. }
  233. generateText(content) {
  234. if (content.indexOf(stopWords) >= 0) return content;
  235. // 判断是否包含html标签
  236. const r = htmlReg.exec(content);
  237. if (r === null) {
  238. const sr = sReg.exec(content);
  239. if (sr === null) {
  240. return this.generateTag(content);
  241. }
  242. // 句尾标点符号
  243. return `${this.generateTag(content.replace(sr[0], ''))}${sr[0]}`;
  244. }
  245. if (r.index === 0) {
  246. // 头部html标签
  247. return `${r[0]}${this.generateTag(content.replace(r[0], ''))}`;
  248. }
  249. // 尾部html标签
  250. return `${this.generateTag(content.replace(r[0], ''))}${r[0]}`;
  251. }
  252. generateTag(content) {
  253. // return `<span>${content}</span>`;
  254. // 处理uuid信息
  255. // const r = uuidReg.exec(content);
  256. // if (r === null) {
  257. let uuid;
  258. if (this.uuidList.length <= this.index) {
  259. do {
  260. uuid = generateUUID(4);
  261. } while (this.uuidMap[uuid]);
  262. this.uuidMap[uuid] = content;
  263. this.uuidList.push(uuid);
  264. } else {
  265. uuid = this.uuidList[this.index];
  266. this.uuidMap[uuid] = content;
  267. }
  268. this.index += 1;
  269. return `<span uuid='${uuid}'>${content}</span>`;
  270. // }
  271. // uuidMap[r[1]] = `${r[2]}`;
  272. // return `<span uuid='${r[1]}'>${r[2]}</span>`;
  273. }
  274. renderTitle() {
  275. const { getFieldDecorator } = this.props.form;
  276. return <Block>
  277. <Form>
  278. {getFieldDecorator('id')(<input hidden />)}
  279. <Form.Item labelCol={{ span: 5 }} wrapperCol={{ span: 16 }} label='题目序号'>
  280. {getFieldDecorator('no', {
  281. rules: [
  282. { required: true, message: '请输入序号' },
  283. // {
  284. // validator: (rule, value, callback) => {
  285. // if (this.partList.indexOf(value) >= 0) callback('该part已被使用');
  286. // else callback();
  287. // callback();
  288. // },
  289. // },
  290. ],
  291. })(
  292. <InputNumber min={1} precision={0} formatter={(v) => parseInt(v, 10) || 1} />,
  293. )}
  294. </Form.Item>
  295. <Form.Item labelCol={{ span: 5 }} wrapperCol={{ span: 16 }} label='名称'>
  296. {getFieldDecorator('title', {
  297. rules: [
  298. { required: true, message: '请输入名称' },
  299. ],
  300. })(
  301. <Input placeholder='请输入' />,
  302. )}
  303. </Form.Item>
  304. <Form.Item labelCol={{ span: 5 }} wrapperCol={{ span: 16 }} label='开放试用'>
  305. {getFieldDecorator('isTrail', {
  306. valuePropName: 'checked',
  307. })(
  308. <Switch checkedChildren='on' unCheckedChildren='off' />,
  309. )}
  310. </Form.Item>
  311. {/* 不允许修改组卷逻辑 */}
  312. <Form.Item labelCol={{ span: 5 }} wrapperCol={{ span: 16 }} label='组卷题目' >
  313. {getFieldDecorator('isPaper', {
  314. valuePropName: 'checked',
  315. })(
  316. <Switch checkedChildren='on' unCheckedChildren='off' />,
  317. )}
  318. </Form.Item>
  319. </Form>
  320. </Block>;
  321. }
  322. renderBase() {
  323. const { getFieldDecorator, getFieldValue, setFieldsValue } = this.props.form;
  324. const { stem, mode } = this.state;
  325. return <Block flex>
  326. <h1>题干信息:
  327. <Switch checked={mode !== 'setting'} checkedChildren='编辑模式' unCheckedChildren='设置模式' onChange={(value) => {
  328. if (value) {
  329. // console.log(stem);
  330. getFieldDecorator('question.stem');
  331. setFieldsValue({ 'question.stem': stem });
  332. this.setState({ mode: 'edit' });
  333. } else {
  334. // 编辑器未修改会使用添加好uuid标签的结果
  335. // 通过保留onChange获取到最后一次修改记录
  336. this.setState({ mode: 'setting', stem: this.generateContent(this.stem || getFieldValue('question.stem') || '') });
  337. }
  338. }} /></h1>
  339. <Form>
  340. {getFieldDecorator('question.id')(<input hidden />)}
  341. {<Form.Item style={{ display: (mode === 'edit' || !mode) ? 'block' : 'none' }}>
  342. {getFieldDecorator('question.stem')(
  343. <Editor
  344. // onChange={(content, delta, source, editor) => {
  345. // console.log(content, delta, source, editor);
  346. // setFieldsValue({ 'question.stem': content });
  347. // }}
  348. onChange={(content) => {
  349. this.stem = content;
  350. // console.log(this.stem);
  351. }}
  352. placeholder='请输入内容' />,
  353. )}
  354. </Form.Item>}
  355. {mode === 'setting' && <Dropdown overlay={() => this.renderContextMenu()} trigger={['click']}><div className='stem-content' dangerouslySetInnerHTML={{ __html: stem }} onClick={(e) => {
  356. this.targetWord = e.target;
  357. }} /></Dropdown>}
  358. </Form>
  359. </Block>;
  360. }
  361. renderAnswer() {
  362. const { getFieldDecorator } = this.props.form;
  363. const { subject = [], predicate = [], object = [], currentKey } = this.state;
  364. return <Block flex>
  365. <h1>题目答案: <span>进入设置模式,选择主谓宾后,点击答案单词</span></h1>
  366. <table boarder cellSpacing className='answer'>
  367. <tr>
  368. <td width={30}><Checkbox checked={currentKey === 'subject'} onClick={(value) => value.target.checked && this.setState({ currentKey: 'subject' })} /> 主语</td>
  369. <td><Form.Item>
  370. {getFieldDecorator('question.answer.subject', {
  371. rules: [{ required: true, message: '请输入主语' }],
  372. })(<input hidden />)}
  373. {subject.map((row, index) => {
  374. return <Tag key={index} closable visible onClose={() => {
  375. this.removeAnswer('subject', index);
  376. }}>{row.map(r => r.text).join(', ')}</Tag>;
  377. })}
  378. </Form.Item></td>
  379. </tr>
  380. <tr>
  381. <td><Checkbox checked={currentKey === 'predicate'} onClick={(value) => value.target.checked && this.setState({ currentKey: 'predicate' })} /> 谓语</td>
  382. <td><Form.Item>
  383. {getFieldDecorator('question.answer.predicate', {
  384. rules: [{ required: true, message: '请输入谓语' }],
  385. })(<input hidden />)}
  386. {predicate.map((row, index) => {
  387. return <Tag key={index} closable visible onClose={() => {
  388. this.removeAnswer('predicate', index);
  389. }}>{row.map(r => r.text).join(', ')}</Tag>;
  390. })}
  391. </Form.Item></td>
  392. </tr>
  393. <tr>
  394. <td><Checkbox checked={currentKey === 'object'} onClick={(value) => value.target.checked && this.setState({ currentKey: 'object' })} /> 宾语</td>
  395. <td><Form.Item>
  396. {getFieldDecorator('question.answer.object', {
  397. rules: [{ required: true, message: '请输入宾语' }],
  398. })(<input hidden />)}
  399. {object.map((row, index) => {
  400. return <Tag key={index} closable visible onClose={() => {
  401. this.removeAnswer('object', index);
  402. }}>{row.map(r => r.text).join(', ')}</Tag>;
  403. })}
  404. </Form.Item></td>
  405. </tr>
  406. </table>
  407. </Block >;
  408. }
  409. renderOption() {
  410. const { getFieldDecorator } = this.props.form;
  411. return <Block flex>
  412. <h1>选项信息(长难句)</h1>
  413. <Form>
  414. <Form.Item>
  415. {getFieldDecorator('question.answer.options', {
  416. rules: [{ required: true, message: '请输入选项信息' }],
  417. })(
  418. <Checkbox.Group options={SentenceOption} />,
  419. )}
  420. </Form.Item>
  421. </Form>
  422. </Block>;
  423. }
  424. renderQX() {
  425. const { getFieldDecorator } = this.props.form;
  426. return <Block flex>
  427. <Form>
  428. <Form.Item label='千行解析'>
  429. {getFieldDecorator('question.qxContent', {
  430. })(
  431. <Editor placeholder='输入内容' />,
  432. )}
  433. </Form.Item>
  434. </Form>
  435. </Block>;
  436. }
  437. renderChinese() {
  438. const { getFieldDecorator } = this.props.form;
  439. return <Block flex>
  440. <Form>
  441. <Form.Item label='中文解析'>
  442. {getFieldDecorator('chinese', {
  443. })(
  444. <Editor placeholder='输入内容' />,
  445. )}
  446. </Form.Item>
  447. </Form>
  448. </Block>;
  449. }
  450. renderTab() {
  451. return <Tabs activeKey='sentence' onChange={(tab) => {
  452. switch (tab) {
  453. case 'textbook':
  454. linkTo('/subject/textbook/question');
  455. break;
  456. case 'base':
  457. linkTo('/subject/question');
  458. break;
  459. default:
  460. }
  461. }}>
  462. <Tabs.TabPane key='base' tab='考试题型' />
  463. <Tabs.TabPane key='sentence' tab='长难句' />
  464. <Tabs.TabPane key='textbook' tab='数学机经' />
  465. </Tabs>;
  466. }
  467. renderView() {
  468. return <div flex >
  469. {this.renderTab()}
  470. {this.renderTitle()}
  471. {this.renderBase()}
  472. {this.renderAnswer()}
  473. {this.renderOption()}
  474. {this.renderQX()}
  475. {this.renderChinese()}
  476. <Row type="flex" justify="center">
  477. <Col>
  478. <Button type="primary" onClick={() => {
  479. this.submit();
  480. }}>保存</Button>
  481. </Col>
  482. </Row>
  483. </div>;
  484. }
  485. }