page.js 19 KB

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