mirror of
https://gitcode.com/gh_mirrors/hy/Hydro.git
synced 2026-10-19 17:38:19 +08:00
Merge branch 'master' into milkdown
This commit is contained in:
commit
08c0d34420
137 files changed
+2795
-1521
No files matched your search
@@ -1,5 +1,5 @@
|
||||
import React from 'react';
|
||||
import ReactDOM from 'react-dom';
|
||||
import ReactDOM from 'react-dom/client';
|
||||
import { assign } from 'lodash';
|
||||
import DOMAttachedObject from 'vj/components/DOMAttachedObject';
|
||||
import AutoComplete from '.';
|
||||
@@ -33,15 +33,12 @@ export default class DomainSelectAutoComplete extends AutoComplete {
|
||||
|
||||
attach() {
|
||||
const value = this.$dom.val();
|
||||
ReactDOM.render(
|
||||
<Component
|
||||
ref={(ref) => { this.ref = ref; }}
|
||||
value={value}
|
||||
onChange={this.onChange}
|
||||
multi={this.options.multi}
|
||||
/>,
|
||||
this.container,
|
||||
);
|
||||
ReactDOM.createRoot(this.container).render(<Component
|
||||
ref={(ref) => { this.ref = ref; }}
|
||||
value={value}
|
||||
onChange={this.onChange}
|
||||
multi={this.options.multi}
|
||||
/>);
|
||||
}
|
||||
}
|
||||
|
||||
|
||||
@@ -1,5 +1,5 @@
|
||||
import React from 'react';
|
||||
import ReactDOM from 'react-dom';
|
||||
import ReactDOM from 'react-dom/client';
|
||||
import { assign } from 'lodash';
|
||||
import DOMAttachedObject from 'vj/components/DOMAttachedObject';
|
||||
import AutoComplete from '.';
|
||||
@@ -33,14 +33,13 @@ export default class ProblemSelectAutoComplete extends AutoComplete {
|
||||
|
||||
attach() {
|
||||
const value = this.$dom.val();
|
||||
ReactDOM.render(
|
||||
ReactDOM.createRoot(this.container).render(
|
||||
<Component
|
||||
ref={(ref) => { this.ref = ref; }}
|
||||
value={value}
|
||||
multi={this.options.multi}
|
||||
onChange={this.onChange}
|
||||
/>,
|
||||
this.container,
|
||||
);
|
||||
}
|
||||
}
|
||||
|
||||
@@ -1,5 +1,5 @@
|
||||
import React from 'react';
|
||||
import ReactDOM from 'react-dom';
|
||||
import ReactDOM from 'react-dom/client';
|
||||
import { assign } from 'lodash';
|
||||
import DOMAttachedObject from 'vj/components/DOMAttachedObject';
|
||||
import AutoComplete, { AutoCompleteOptions } from '.';
|
||||
@@ -38,14 +38,13 @@ export default class UserSelectAutoComplete<Multi extends boolean> extends AutoC
|
||||
|
||||
attach() {
|
||||
const value = this.$dom.val();
|
||||
ReactDOM.render(
|
||||
ReactDOM.createRoot(this.container).render(
|
||||
<Component
|
||||
ref={(ref) => { this.ref = ref; }}
|
||||
value={value}
|
||||
multi={this.options.multi}
|
||||
onChange={this.onChange}
|
||||
/>,
|
||||
this.container,
|
||||
);
|
||||
}
|
||||
}
|
||||
|
||||
@@ -53,7 +53,7 @@
|
||||
white-space: nowrap
|
||||
text-overflow: ellipsis
|
||||
|
||||
&>span.bp3-icon>svg
|
||||
&>span.bp4-icon>svg
|
||||
font-size: 12px
|
||||
cursor: pointer
|
||||
padding: 4px
|
||||
@@ -78,19 +78,19 @@
|
||||
&>div
|
||||
flex-grow: 1
|
||||
|
||||
&>span.bp3-icon>svg
|
||||
&>span.bp4-icon>svg
|
||||
color: transparent
|
||||
|
||||
&[aria-selected='true']
|
||||
background-color: #fafafa
|
||||
font-weight: 600
|
||||
|
||||
&>span.bp3-icon>svg
|
||||
&>span.bp4-icon>svg
|
||||
color: #1890ff
|
||||
|
||||
&[data-focus='true']
|
||||
background-color: #e6f7ff
|
||||
cursor: pointer
|
||||
|
||||
&>span.bp3-icon>svg
|
||||
&>span.bp4-icon>svg
|
||||
color: currentColor
|
||||
@@ -17,6 +17,7 @@ export interface AutoCompleteProps<Item> {
|
||||
*/
|
||||
height?: string;
|
||||
disabled?: boolean;
|
||||
placeholder?: string;
|
||||
disabledHint?: string;
|
||||
listStyle?: React.CSSProperties;
|
||||
cacheKey?: string;
|
||||
@@ -128,8 +129,10 @@ const AutoComplete = forwardRef(function Impl<T>(props: AutoCompleteProps<T>, re
|
||||
else onChange(selectedKeys.join(','));
|
||||
};
|
||||
|
||||
let first = !multi;
|
||||
useEffect(() => {
|
||||
dispatchChange();
|
||||
if (first) first = false;
|
||||
else dispatchChange();
|
||||
const ids = [];
|
||||
for (const key of selectedKeys) if (!valueCache[key]) ids.push(key);
|
||||
if (!ids.length) return;
|
||||
@@ -293,6 +296,7 @@ const AutoComplete = forwardRef(function Impl<T>(props: AutoCompleteProps<T>, re
|
||||
if (allowEmptyQuery) handleInputChange();
|
||||
setFocused(true);
|
||||
}}
|
||||
placeholder={props.placeholder}
|
||||
onBlur={() => setFocused(false)}
|
||||
onKeyDown={handleInputKeyDown}
|
||||
defaultValue={multi ? '' : selectedKeys.join(',')}
|
||||
@@ -342,6 +346,7 @@ AutoComplete.propTypes = {
|
||||
allowEmptyQuery: PropTypes.bool,
|
||||
freeSolo: PropTypes.bool,
|
||||
freeSoloConverter: PropTypes.func,
|
||||
placeholder: PropTypes.string,
|
||||
};
|
||||
|
||||
AutoComplete.defaultProps = {
|
||||
|
||||
@@ -33,7 +33,7 @@ CustomSelectAutoComplete.propTypes = {
|
||||
allowEmptyQuery: PropTypes.bool,
|
||||
freeSolo: PropTypes.bool,
|
||||
freeSoloConverter: PropTypes.func,
|
||||
data: PropTypes.any,
|
||||
data: PropTypes.arrayOf(PropTypes.any),
|
||||
};
|
||||
|
||||
CustomSelectAutoComplete.displayName = 'CustomSelectAutoComplete';
|
||||
|
||||
@@ -0,0 +1,51 @@
|
||||
import React from 'react';
|
||||
import PropTypes from 'prop-types';
|
||||
import AutoComplete from './AutoComplete';
|
||||
|
||||
type DefaultProps = {
|
||||
_id: string;
|
||||
name: string;
|
||||
} & string;
|
||||
|
||||
const FileSelectAutoComplete = React.forwardRef<any, any>((props, ref) => (
|
||||
<AutoComplete<DefaultProps>
|
||||
ref={ref as any}
|
||||
fetchItems={(keys) => props.data.filter((i) => (i._id ? keys.includes(i._id) : keys.includes(i)))}
|
||||
queryItems={(query) => props.data.filter((i) => (i.name
|
||||
? i.name.toLowerCase().match(query.toLowerCase())
|
||||
: i.toString().toLowerCase().match(query.toLowerCase())
|
||||
))}
|
||||
itemText={(item) => `${item.name || item}`}
|
||||
itemKey={(item) => `${item._id?.toString() || item.name || item}`}
|
||||
renderItem={(item) => item.name || item._id || item} // TODO icon
|
||||
allowEmptyQuery
|
||||
{...props}
|
||||
/>
|
||||
));
|
||||
|
||||
FileSelectAutoComplete.propTypes = {
|
||||
width: PropTypes.string,
|
||||
height: PropTypes.string,
|
||||
listStyle: PropTypes.object,
|
||||
onChange: PropTypes.func.isRequired,
|
||||
multi: PropTypes.bool,
|
||||
selectedKeys: PropTypes.arrayOf(PropTypes.string),
|
||||
allowEmptyQuery: PropTypes.bool,
|
||||
freeSolo: PropTypes.bool,
|
||||
freeSoloConverter: PropTypes.func,
|
||||
data: PropTypes.arrayOf(PropTypes.any),
|
||||
};
|
||||
|
||||
FileSelectAutoComplete.displayName = 'FileSelectAutoComplete';
|
||||
|
||||
FileSelectAutoComplete.defaultProps = {
|
||||
width: '100%',
|
||||
height: 'auto',
|
||||
listStyle: {},
|
||||
multi: false,
|
||||
selectedKeys: [],
|
||||
freeSolo: false,
|
||||
freeSoloConverter: (input) => input,
|
||||
};
|
||||
|
||||
export default FileSelectAutoComplete;
|
||||
@@ -1,5 +1,5 @@
|
||||
import React from 'react';
|
||||
import ReactDOM from 'react-dom';
|
||||
import ReactDOM from 'react-dom/client';
|
||||
import { assign } from 'lodash';
|
||||
import DOMAttachedObject from 'vj/components/DOMAttachedObject';
|
||||
import AutoCompleteFC from './components/AutoComplete';
|
||||
@@ -64,7 +64,7 @@ export default class AutoComplete extends DOMAttachedObject {
|
||||
|
||||
attach() {
|
||||
const value = this.$dom.val();
|
||||
ReactDOM.render(
|
||||
ReactDOM.createRoot(this.container).render(
|
||||
<AutoCompleteFC
|
||||
ref={(ref) => { this.ref = ref; }}
|
||||
height="34px"
|
||||
@@ -76,7 +76,6 @@ export default class AutoComplete extends DOMAttachedObject {
|
||||
multi={this.options.multi}
|
||||
freeSolo={this.options.multi}
|
||||
/>,
|
||||
this.container,
|
||||
);
|
||||
}
|
||||
|
||||
|
||||
@@ -1,7 +1,7 @@
|
||||
import 'jquery.easing';
|
||||
|
||||
import * as React from 'react';
|
||||
import ReactDOM from 'react-dom';
|
||||
import ReactDOM from 'react-dom/client';
|
||||
import { Popover } from '@blueprintjs/core';
|
||||
import { AutoloadPage } from 'vj/misc/Page';
|
||||
import CommentBox from 'vj/components/discussion/CommentBox';
|
||||
@@ -256,7 +256,7 @@ const commentsPage = new AutoloadPage('commentsPage', () => {
|
||||
|
||||
const canUseReaction = $('[data-op="react"]').length > 0;
|
||||
$('[data-op="react"]').each((i, e) => {
|
||||
ReactDOM.render(<Reaction payload={$(e).data('form')} ele={$(e).closest('.media__body').find('.reactions')} />, e);
|
||||
ReactDOM.createRoot(e).render(<Reaction payload={$(e).data('form')} ele={$(e).closest('.media__body').find('.reactions')} />);
|
||||
});
|
||||
$(document).on('click', '.reaction', async (e) => {
|
||||
if (!canUseReaction) {
|
||||
|
||||
@@ -62,7 +62,7 @@ export default class VjEditor extends DOMAttachedObject {
|
||||
? monaco.editor.getModel(monaco.Uri.parse(model))
|
||||
|| monaco.editor.createModel(value, language === 'auto' ? undefined : language, monaco.Uri.parse(model))
|
||||
: model;
|
||||
this.model.setValue(value);
|
||||
if (!this.options.model) this.model.setValue(value);
|
||||
const cfg: import('../monaco').default.editor.IStandaloneEditorConstructionOptions = {
|
||||
theme,
|
||||
lineNumbers: 'on',
|
||||
|
||||
@@ -38,15 +38,15 @@ function testElementHotkey(hotkey, $element, attr) {
|
||||
const [defStr, trigger] = singleDef.split(':');
|
||||
if (isHotkeyMatch(hotkey, defStr)) {
|
||||
switch (trigger) {
|
||||
case 'submit':
|
||||
$element.closest('form').trigger('submit');
|
||||
break;
|
||||
case undefined:
|
||||
$element.trigger('click');
|
||||
break;
|
||||
default:
|
||||
$element.trigger(trigger);
|
||||
break;
|
||||
case 'submit':
|
||||
$element.closest('form').trigger('submit');
|
||||
break;
|
||||
case undefined:
|
||||
$element.trigger('click');
|
||||
break;
|
||||
default:
|
||||
$element.trigger(trigger);
|
||||
break;
|
||||
}
|
||||
}
|
||||
});
|
||||
|
||||
@@ -42,6 +42,9 @@
|
||||
opacity: 0.85
|
||||
|
||||
a.menu__link, button.menu__link
|
||||
&.half
|
||||
padding-right: 0
|
||||
width: 50%
|
||||
&.disabled
|
||||
cursor: default
|
||||
opacity: 0.5
|
||||
|
||||
@@ -1,67 +0,0 @@
|
||||
import { AutoloadPage } from 'vj/misc/Page';
|
||||
import { InfoDialog } from 'vj/components/dialog';
|
||||
import VjNotification from 'vj/components/notification/index';
|
||||
import { FLAG_ALERT } from 'vj/constant/message';
|
||||
import i18n from 'vj/utils/i18n';
|
||||
import tpl from 'vj/utils/tpl';
|
||||
|
||||
const messagePage = new AutoloadPage('messagePage', (pagename) => {
|
||||
if (pagename === 'home_messages' || !UserContext._id) return;
|
||||
|
||||
if (UserContext.unreadMsg) {
|
||||
new VjNotification({
|
||||
type: 'info',
|
||||
message: i18n(`You have ${UserContext.unreadMsg > 1 ? 'new messages' : 'a new message'}.`),
|
||||
duration: 5000,
|
||||
action: () => window.open('/home/messages', '_blank'),
|
||||
}).show();
|
||||
}
|
||||
|
||||
const onmessage = (message) => {
|
||||
const msg = JSON.parse(message);
|
||||
console.log('Received message', msg);
|
||||
if (msg.mdoc.flag & FLAG_ALERT) {
|
||||
// Is alert
|
||||
return new InfoDialog({
|
||||
cancelByClickingBack: false,
|
||||
$body: tpl`
|
||||
<div class="typo">
|
||||
${{ templateRaw: true, html: i18n('Message from {0}:', `<div data-user>${msg.mdoc.from}</div>`) }}
|
||||
<p>${i18n(msg.mdoc.content)}</p>
|
||||
</div>`,
|
||||
}).open();
|
||||
}
|
||||
if (msg.udoc._id === 1 && msg.mdoc.flag & 4) {
|
||||
// System notification
|
||||
return new VjNotification({
|
||||
message: i18n('You received a system message, click here to view.'),
|
||||
duration: 15000,
|
||||
action: () => window.open(`/home/messages?uid=${msg.udoc._id}`, '_blank'),
|
||||
}).show();
|
||||
}
|
||||
// Is message
|
||||
return new VjNotification({
|
||||
title: msg.udoc.uname,
|
||||
avatar: msg.udoc.avatarUrl,
|
||||
message: msg.mdoc.content,
|
||||
duration: 15000,
|
||||
action: () => window.open(`/home/messages?uid=${msg.udoc._id}`, '_blank'),
|
||||
}).show();
|
||||
};
|
||||
|
||||
const path = new URL('/home/messages-conn', window.location.href).toString();
|
||||
const worker = new SharedWorker('/sharedworker.js', { name: 'Hydro Messages Shared Worker' });
|
||||
worker.port.start();
|
||||
worker.port.postMessage({ type: 'init', path, cookie: document.cookie });
|
||||
worker.port.onmessage = (e) => {
|
||||
if (e.data.type !== 'message') return;
|
||||
if (document.hidden) {
|
||||
worker.port.postMessage({ type: 'fail' });
|
||||
} else {
|
||||
worker.port.postMessage({ type: 'success' });
|
||||
onmessage(e.data.payload);
|
||||
}
|
||||
};
|
||||
});
|
||||
|
||||
export default messagePage;
|
||||
@@ -0,0 +1,122 @@
|
||||
import { AutoloadPage } from 'vj/misc/Page';
|
||||
import { InfoDialog } from 'vj/components/dialog';
|
||||
import VjNotification from 'vj/components/notification/index';
|
||||
import ReconnectingWebsocket from 'reconnecting-websocket';
|
||||
import { FLAG_ALERT } from 'vj/constant/message';
|
||||
import i18n from 'vj/utils/i18n';
|
||||
import tpl from 'vj/utils/tpl';
|
||||
import { nanoid } from 'nanoid';
|
||||
|
||||
const onmessage = (msg) => {
|
||||
console.log('Received message', msg);
|
||||
if (msg.mdoc.flag & FLAG_ALERT) {
|
||||
// Is alert
|
||||
return new InfoDialog({
|
||||
cancelByClickingBack: false,
|
||||
$body: tpl`
|
||||
<div class="typo">
|
||||
${{ templateRaw: true, html: i18n('Message from {0}:', `<div data-user>${msg.mdoc.from}</div>`) }}
|
||||
<p>${i18n(msg.mdoc.content)}</p>
|
||||
</div>`,
|
||||
}).open();
|
||||
}
|
||||
// Is message
|
||||
return new VjNotification({
|
||||
...(msg.udoc._id === 1 && msg.mdoc.flag & 4)
|
||||
? { message: i18n('You received a system message, click here to view.') }
|
||||
: {
|
||||
title: msg.udoc.uname,
|
||||
avatar: msg.udoc.avatarUrl,
|
||||
message: msg.mdoc.content,
|
||||
},
|
||||
duration: 15000,
|
||||
action: () => window.open(`/home/messages?uid=${msg.udoc._id}`, '_blank'),
|
||||
}).show();
|
||||
};
|
||||
|
||||
const messagePage = new AutoloadPage('messagePage', (pagename) => {
|
||||
if (pagename === 'home_messages' || !UserContext._id) return;
|
||||
if (UserContext.unreadMsg) {
|
||||
new VjNotification({
|
||||
type: 'info',
|
||||
message: i18n(`You have ${UserContext.unreadMsg > 1 ? 'new messages' : 'a new message'}.`),
|
||||
duration: 5000,
|
||||
action: () => window.open('/home/messages', '_blank'),
|
||||
}).show();
|
||||
}
|
||||
if (!window.BroadcastChannel) {
|
||||
console.error('BoardcastChannel not supported');
|
||||
return;
|
||||
}
|
||||
|
||||
let isMaster = false;
|
||||
const selfId = nanoid();
|
||||
const channel = new BroadcastChannel('hydro-messages');
|
||||
const pages = JSON.parse(localStorage.getItem('pages') || '[]') as string[];
|
||||
pages.push(selfId);
|
||||
pages.sort();
|
||||
localStorage.setItem('pages', JSON.stringify(pages));
|
||||
|
||||
window.onunload = () => {
|
||||
const c = JSON.parse(localStorage.getItem('pages') || '[]') as string[];
|
||||
localStorage.setItem('pages', JSON.stringify(c.filter((i) => i !== selfId)));
|
||||
if (!isMaster) return;
|
||||
localStorage.removeItem('page.master');
|
||||
channel?.postMessage({ type: 'master' });
|
||||
};
|
||||
|
||||
function asMaster() {
|
||||
console.log('init as master');
|
||||
isMaster = true;
|
||||
localStorage.setItem('page.master', selfId);
|
||||
const masterChannel = new BroadcastChannel('hydro-messages');
|
||||
const url = new URL('/home/messages-conn', window.location.href.replace('http', 'ws'));
|
||||
// TODO handle a better way for cookie
|
||||
url.searchParams.append('sid', document.cookie);
|
||||
const sock = new ReconnectingWebsocket(url.toString());
|
||||
const pending = {};
|
||||
sock.onopen = () => console.log('Connected');
|
||||
sock.onerror = console.error;
|
||||
sock.onclose = (...args) => console.log('Closed', ...args);
|
||||
sock.onmessage = async (message) => {
|
||||
if (process.env.NODE_ENV !== 'production') console.log('onmessage: ', message);
|
||||
const payload = JSON.parse(message.data);
|
||||
const id = nanoid();
|
||||
masterChannel.postMessage({ type: 'message', id, payload });
|
||||
const success = await new Promise<boolean>((resolve) => {
|
||||
pending[id] = resolve;
|
||||
setTimeout(() => {
|
||||
delete pending[id];
|
||||
resolve(false);
|
||||
}, 1000);
|
||||
});
|
||||
if (!success && window.Notification?.permission === 'granted') {
|
||||
const notification = new window.Notification(
|
||||
payload.udoc.uname || 'Hydro Notification',
|
||||
{
|
||||
icon: payload.udoc.avatarUrl || '/android-chrome-192x192.png',
|
||||
body: payload.mdoc.content,
|
||||
},
|
||||
);
|
||||
notification.onclick = () => window.open('/home/messages');
|
||||
}
|
||||
};
|
||||
masterChannel.onmessage = (msg) => {
|
||||
if (msg.data.type === 'message-push') pending[msg.data.id]?.(true);
|
||||
};
|
||||
}
|
||||
|
||||
channel.onmessage = (msg) => {
|
||||
if (msg.data.type === 'message' && !document.hidden) {
|
||||
channel.postMessage({ type: 'message-push', id: msg.data.id });
|
||||
onmessage(msg.data.payload);
|
||||
}
|
||||
if (msg.data.type === 'master') {
|
||||
const c = JSON.parse(localStorage.getItem('pages') || '[]') as string[];
|
||||
if (c[0] === selfId) asMaster();
|
||||
}
|
||||
};
|
||||
if (!localStorage.getItem('page.master')) asMaster();
|
||||
});
|
||||
|
||||
export default messagePage;
|
||||
@@ -21,14 +21,14 @@ function scrollToViewport() {
|
||||
|
||||
export default function reducer(state = null, action) {
|
||||
switch (action.type) {
|
||||
case 'DIALOGUES_SWITCH_TO': {
|
||||
scrollToViewport();
|
||||
return action.payload;
|
||||
}
|
||||
case 'DIALOGUES_POST_SEND_FULFILLED': {
|
||||
return action.meta.dialogueId;
|
||||
}
|
||||
default:
|
||||
return state;
|
||||
case 'DIALOGUES_SWITCH_TO': {
|
||||
scrollToViewport();
|
||||
return action.payload;
|
||||
}
|
||||
case 'DIALOGUES_POST_SEND_FULFILLED': {
|
||||
return action.meta.dialogueId;
|
||||
}
|
||||
default:
|
||||
return state;
|
||||
}
|
||||
}
|
||||
@@ -2,52 +2,52 @@ import _ from 'lodash';
|
||||
|
||||
export default function reducer(state = {}, action) {
|
||||
switch (action.type) {
|
||||
case 'DIALOGUES_LOAD_DIALOGUES_FULFILLED': {
|
||||
const { messages } = action.payload;
|
||||
return { ...state, ..._.keyBy(messages, 'udoc._id') };
|
||||
}
|
||||
case 'DIALOGUES_CREATE': {
|
||||
const { user } = action.payload;
|
||||
if (state[user._id]) return state;
|
||||
return {
|
||||
...state,
|
||||
[user._id]: {
|
||||
_id: user._id,
|
||||
udoc: { ...user },
|
||||
messages: [],
|
||||
},
|
||||
};
|
||||
}
|
||||
case 'DIALOGUES_POST_SEND_FULFILLED': {
|
||||
const id = action.meta.dialogueId;
|
||||
const { mdoc } = action.payload;
|
||||
return {
|
||||
...state,
|
||||
[id]: {
|
||||
...state[id],
|
||||
messages: [
|
||||
...state[id].messages,
|
||||
mdoc,
|
||||
],
|
||||
},
|
||||
};
|
||||
}
|
||||
case 'DIALOGUES_MESSAGE_PUSH': {
|
||||
const { mdoc, udoc } = action.payload;
|
||||
const to = mdoc.from === UserContext._id ? mdoc.to : mdoc.from;
|
||||
return {
|
||||
...state,
|
||||
[to]: {
|
||||
...state[to] || {},
|
||||
udoc,
|
||||
messages: [
|
||||
...state[to]?.messages || [],
|
||||
mdoc,
|
||||
],
|
||||
},
|
||||
};
|
||||
}
|
||||
default:
|
||||
return state;
|
||||
case 'DIALOGUES_LOAD_DIALOGUES_FULFILLED': {
|
||||
const { messages } = action.payload;
|
||||
return { ...state, ..._.keyBy(messages, 'udoc._id') };
|
||||
}
|
||||
case 'DIALOGUES_CREATE': {
|
||||
const { user } = action.payload;
|
||||
if (state[user._id]) return state;
|
||||
return {
|
||||
...state,
|
||||
[user._id]: {
|
||||
_id: user._id,
|
||||
udoc: { ...user },
|
||||
messages: [],
|
||||
},
|
||||
};
|
||||
}
|
||||
case 'DIALOGUES_POST_SEND_FULFILLED': {
|
||||
const id = action.meta.dialogueId;
|
||||
const { mdoc } = action.payload;
|
||||
return {
|
||||
...state,
|
||||
[id]: {
|
||||
...state[id],
|
||||
messages: [
|
||||
...state[id].messages,
|
||||
mdoc,
|
||||
],
|
||||
},
|
||||
};
|
||||
}
|
||||
case 'DIALOGUES_MESSAGE_PUSH': {
|
||||
const { mdoc, udoc } = action.payload;
|
||||
const to = mdoc.from === UserContext._id ? mdoc.to : mdoc.from;
|
||||
return {
|
||||
...state,
|
||||
[to]: {
|
||||
...state[to] || {},
|
||||
udoc,
|
||||
messages: [
|
||||
...state[to]?.messages || [],
|
||||
mdoc,
|
||||
],
|
||||
},
|
||||
};
|
||||
}
|
||||
default:
|
||||
return state;
|
||||
}
|
||||
}
|
||||
@@ -2,42 +2,42 @@ import _ from 'lodash';
|
||||
|
||||
export default function reducer(state = {}, action) {
|
||||
switch (action.type) {
|
||||
case 'DIALOGUES_LOAD_DIALOGUES_FULFILLED': {
|
||||
const dialogues = action.payload.messages;
|
||||
return { ...state, ..._.fromPairs(_.map(dialogues, (d) => [d._id, ''])) };
|
||||
}
|
||||
case 'DIALOGUES_CREATE': {
|
||||
const { user } = action.payload;
|
||||
return {
|
||||
...state,
|
||||
[user._id]: '',
|
||||
};
|
||||
}
|
||||
case 'DIALOGUES_INPUT_CHANGED': {
|
||||
const id = action.meta.dialogueId;
|
||||
return {
|
||||
...state,
|
||||
[id]: action.payload,
|
||||
};
|
||||
}
|
||||
case 'DIALOGUES_POST_SEND_FULFILLED': {
|
||||
const id = action.meta.dialogueId;
|
||||
return {
|
||||
...state,
|
||||
[id]: '',
|
||||
};
|
||||
}
|
||||
case 'DIALOGUES_MESSAGE_PUSH': {
|
||||
const { udoc } = action.payload;
|
||||
if (!state[udoc._id]) {
|
||||
case 'DIALOGUES_LOAD_DIALOGUES_FULFILLED': {
|
||||
const dialogues = action.payload.messages;
|
||||
return { ...state, ..._.fromPairs(_.map(dialogues, (d) => [d._id, ''])) };
|
||||
}
|
||||
case 'DIALOGUES_CREATE': {
|
||||
const { user } = action.payload;
|
||||
return {
|
||||
...state,
|
||||
[udoc._id]: '',
|
||||
[user._id]: '',
|
||||
};
|
||||
}
|
||||
return state;
|
||||
}
|
||||
default:
|
||||
return state;
|
||||
case 'DIALOGUES_INPUT_CHANGED': {
|
||||
const id = action.meta.dialogueId;
|
||||
return {
|
||||
...state,
|
||||
[id]: action.payload,
|
||||
};
|
||||
}
|
||||
case 'DIALOGUES_POST_SEND_FULFILLED': {
|
||||
const id = action.meta.dialogueId;
|
||||
return {
|
||||
...state,
|
||||
[id]: '',
|
||||
};
|
||||
}
|
||||
case 'DIALOGUES_MESSAGE_PUSH': {
|
||||
const { udoc } = action.payload;
|
||||
if (!state[udoc._id]) {
|
||||
return {
|
||||
...state,
|
||||
[udoc._id]: '',
|
||||
};
|
||||
}
|
||||
return state;
|
||||
}
|
||||
default:
|
||||
return state;
|
||||
}
|
||||
}
|
||||
@@ -3,47 +3,47 @@ import Notification from 'vj/components/notification';
|
||||
|
||||
export default function reducer(state = {}, action) {
|
||||
switch (action.type) {
|
||||
case 'DIALOGUES_LOAD_DIALOGUES_FULFILLED': {
|
||||
const dialogues = action.payload.messages;
|
||||
return { ...state, ..._.fromPairs(_.map(dialogues, (d) => [d._id, false])) };
|
||||
}
|
||||
case 'DIALOGUES_CREATE': {
|
||||
const { user } = action.payload;
|
||||
return {
|
||||
...state,
|
||||
[user._id]: false,
|
||||
};
|
||||
}
|
||||
case 'DIALOGUES_POST_SEND_PENDING': {
|
||||
const id = action.meta.dialogueId;
|
||||
return {
|
||||
...state,
|
||||
[id]: true,
|
||||
};
|
||||
}
|
||||
case 'DIALOGUES_POST_SEND_REJECTED': {
|
||||
Notification.error(action.payload.message);
|
||||
const id = action.meta.dialogueId;
|
||||
return {
|
||||
...state,
|
||||
[id]: false,
|
||||
};
|
||||
}
|
||||
case 'DIALOGUES_POST_SEND_FULFILLED': {
|
||||
const id = action.meta.dialogueId;
|
||||
return {
|
||||
...state,
|
||||
[id]: false,
|
||||
};
|
||||
}
|
||||
case 'DIALOGUES_MESSAGE_PUSH': {
|
||||
const { udoc } = action.payload;
|
||||
return {
|
||||
...state,
|
||||
[udoc._id]: false,
|
||||
};
|
||||
}
|
||||
default:
|
||||
return state;
|
||||
case 'DIALOGUES_LOAD_DIALOGUES_FULFILLED': {
|
||||
const dialogues = action.payload.messages;
|
||||
return { ...state, ..._.fromPairs(_.map(dialogues, (d) => [d._id, false])) };
|
||||
}
|
||||
case 'DIALOGUES_CREATE': {
|
||||
const { user } = action.payload;
|
||||
return {
|
||||
...state,
|
||||
[user._id]: false,
|
||||
};
|
||||
}
|
||||
case 'DIALOGUES_POST_SEND_PENDING': {
|
||||
const id = action.meta.dialogueId;
|
||||
return {
|
||||
...state,
|
||||
[id]: true,
|
||||
};
|
||||
}
|
||||
case 'DIALOGUES_POST_SEND_REJECTED': {
|
||||
Notification.error(action.payload.message);
|
||||
const id = action.meta.dialogueId;
|
||||
return {
|
||||
...state,
|
||||
[id]: false,
|
||||
};
|
||||
}
|
||||
case 'DIALOGUES_POST_SEND_FULFILLED': {
|
||||
const id = action.meta.dialogueId;
|
||||
return {
|
||||
...state,
|
||||
[id]: false,
|
||||
};
|
||||
}
|
||||
case 'DIALOGUES_MESSAGE_PUSH': {
|
||||
const { udoc } = action.payload;
|
||||
return {
|
||||
...state,
|
||||
[udoc._id]: false,
|
||||
};
|
||||
}
|
||||
default:
|
||||
return state;
|
||||
}
|
||||
}
|
||||
@@ -1,4 +1,4 @@
|
||||
import * as monaco from 'monaco-editor/esm/vs/editor/editor.api';
|
||||
import { setDiagnosticsOptions } from 'monaco-yaml';
|
||||
|
||||
/** @type {Record<string, import('json-schema').JSONSchema7Definition>} */
|
||||
const problemConfigSchemaDef = {
|
||||
@@ -8,6 +8,9 @@ const problemConfigSchemaDef = {
|
||||
properties: {
|
||||
input: { type: 'string' },
|
||||
output: { type: 'string' },
|
||||
time: { $ref: '#/def/time' },
|
||||
memory: { $ref: '#/def/memory' },
|
||||
score: { $ref: '#/def/score', description: 'score' },
|
||||
},
|
||||
required: ['input'],
|
||||
additionalProperties: false,
|
||||
@@ -28,7 +31,7 @@ const problemConfigSchemaDef = {
|
||||
additionalProperties: false,
|
||||
},
|
||||
time: { type: 'string', pattern: '^([0-9]+(?:\\.[0-9]*)?)([mu]?)s?$' },
|
||||
memory: { type: 'string', pattern: '^([0-9]+(?:\\.[0-9]*)?)([kmg])b?$' },
|
||||
memory: { type: 'string', pattern: '^([0-9]+(?:\\.[0-9]*)?)([kKmMgG])[bB]?$' },
|
||||
score: { type: 'integer', maximum: 100, minimum: 1 },
|
||||
};
|
||||
|
||||
@@ -37,7 +40,7 @@ const problemConfigSchema = {
|
||||
type: 'object',
|
||||
def: problemConfigSchemaDef,
|
||||
properties: {
|
||||
redirect: { type: 'string', pattern: '[0-9a-z_-]+\\/[0-9]+' },
|
||||
redirect: { type: 'string', pattern: '[0-9a-zA-Z_-]+\\/[0-9]+' },
|
||||
key: { type: 'string', pattern: '[0-9a-f]{32}' },
|
||||
type: { enum: ['default', 'interactive', 'submit_answer', 'objective', 'remote_judge'] },
|
||||
subType: { type: 'string' },
|
||||
@@ -75,8 +78,7 @@ const problemConfigSchema = {
|
||||
additionalProperties: false,
|
||||
};
|
||||
|
||||
// @ts-ignore
|
||||
monaco.languages.yaml.yamlDefaults.setDiagnosticsOptions({
|
||||
setDiagnosticsOptions({
|
||||
validate: true,
|
||||
enableSchemaRequest: true,
|
||||
hover: true,
|
||||
@@ -86,7 +88,7 @@ monaco.languages.yaml.yamlDefaults.setDiagnosticsOptions({
|
||||
{
|
||||
uri: 'https://hydro.js.org/schema/problemConfig.json',
|
||||
fileMatch: ['hydro://problem/file/config.yaml'],
|
||||
schema: problemConfigSchema,
|
||||
schema: problemConfigSchema as any,
|
||||
},
|
||||
{
|
||||
uri: `${UiContext.cdn_prefix}manage/setting/schema.json`,
|
||||
|
||||
@@ -1,6 +1,7 @@
|
||||
import React from 'react';
|
||||
import { sortBy } from 'lodash';
|
||||
import request from 'vj/utils/request';
|
||||
import Notification from 'vj/components/notification';
|
||||
|
||||
export default class ObjectiveContainer extends React.PureComponent {
|
||||
constructor(args) {
|
||||
|
||||
@@ -0,0 +1,69 @@
|
||||
import React from 'react';
|
||||
import { useDispatch, useSelector } from 'react-redux';
|
||||
import i18n from 'vj/utils/i18n';
|
||||
import type { RootState } from './reducer/index';
|
||||
import FileSelectAutoComplete from '../autocomplete/components/FileSelectAutoComplete';
|
||||
|
||||
export function FormItem({
|
||||
columns, label, children, helpText = '', disableLabel = false, ...props
|
||||
}) {
|
||||
return (
|
||||
<div {...props} className={`${columns && `medium-${columns}`} columns form__item`}>
|
||||
<label htmlFor={`${label}-form`}>
|
||||
{!disableLabel && i18n(label)}
|
||||
{children}
|
||||
{helpText && (<p className="help-text">{i18n(helpText)}</p>)}
|
||||
</label>
|
||||
</div>
|
||||
);
|
||||
}
|
||||
|
||||
type KeyType<K, T = string | number> = {
|
||||
[Q in keyof K]: K[Q] extends T ? Q : never;
|
||||
}[keyof K];
|
||||
|
||||
export function ManagedInput({ placeholder, formKey }: { placeholder?: string, formKey: KeyType<RootState['config']> }) {
|
||||
const value = useSelector((state: RootState) => state.config[formKey]);
|
||||
const dispatch = useDispatch();
|
||||
return (
|
||||
<input
|
||||
placeholder={i18n(placeholder)}
|
||||
value={value || ''}
|
||||
type={typeof value === 'number' ? 'number' : 'text'}
|
||||
onChange={(ev) => {
|
||||
dispatch({ type: 'CONFIG_FORM_UPDATE', key: formKey, value: ev.currentTarget.value });
|
||||
}}
|
||||
className="textbox"
|
||||
/>
|
||||
);
|
||||
}
|
||||
|
||||
export function ManagedSelect({ options, formKey }: { options: string[], formKey: KeyType<RootState['config']> }) {
|
||||
const value = useSelector((state: RootState) => state.config[formKey]);
|
||||
const dispatch = useDispatch();
|
||||
return (
|
||||
<select
|
||||
value={value || ''}
|
||||
onChange={(ev) => {
|
||||
dispatch({ type: 'CONFIG_FORM_UPDATE', key: formKey, value: ev.currentTarget.value });
|
||||
}}
|
||||
className="select"
|
||||
>
|
||||
{options.map((o) => (<option id={o} key={o}>{o}</option>))}
|
||||
</select>
|
||||
);
|
||||
}
|
||||
|
||||
export function SingleFileSelect({ formKey }: { formKey: KeyType<RootState['config']> }) {
|
||||
const value = useSelector((state: RootState) => state.config[formKey]);
|
||||
const Files = useSelector((state: RootState) => state.testdata);
|
||||
const dispatch = useDispatch();
|
||||
return (
|
||||
<FileSelectAutoComplete
|
||||
width="100%"
|
||||
data={Files}
|
||||
selectedKeys={[value]}
|
||||
onChange={(val) => dispatch({ type: 'CONFIG_FORM_UPDATE', key: formKey, value: val })}
|
||||
/>
|
||||
);
|
||||
}
|
||||
@@ -0,0 +1,162 @@
|
||||
import React from 'react';
|
||||
import type { editor } from 'monaco-editor';
|
||||
import { connect } from 'react-redux';
|
||||
import { load } from 'vj/components/monaco/loader';
|
||||
import Editor from 'vj/components/editor';
|
||||
import { diffLines } from 'diff';
|
||||
import yaml from 'js-yaml';
|
||||
import type { ProblemConfigFile, TestCaseConfig } from 'hydrooj/src/interface';
|
||||
|
||||
const mapStateToProps = (state) => ({
|
||||
config: state.config,
|
||||
});
|
||||
const mapDispatchToProps = (dispatch) => ({
|
||||
handleUpdateCode: (code) => {
|
||||
dispatch({
|
||||
type: 'CONFIG_CODE_UPDATE',
|
||||
payload: code,
|
||||
});
|
||||
},
|
||||
});
|
||||
|
||||
interface Props {
|
||||
config: object;
|
||||
handleUpdateCode: Function;
|
||||
}
|
||||
|
||||
const configKey = [
|
||||
'type', 'subType', 'target', 'score', 'time',
|
||||
'memory', 'filename', 'checker_type', 'checker', 'interactor',
|
||||
'user_extra_files', 'judge_extra_files', 'detail', 'outputs', 'redirect',
|
||||
'cases', 'subtasks', 'langs',
|
||||
];
|
||||
|
||||
const subtasksKey = [
|
||||
'time', 'memory', 'score', 'if', 'id',
|
||||
'type', 'cases',
|
||||
];
|
||||
|
||||
const casesKey = ['time', 'memory', 'input', 'output'];
|
||||
|
||||
export function configYamlFormat(config: ProblemConfigFile) {
|
||||
const formatConfig: ProblemConfigFile = {};
|
||||
configKey.forEach((key) => {
|
||||
if (config[key] !== undefined) {
|
||||
if (key === 'subType' && ['single', 'multi'].includes(config[key]) && config.type !== 'submit_answer') return;
|
||||
if (key === 'checker_type' && config.type !== 'default') return;
|
||||
if (key === 'checker'
|
||||
&& (['default', 'strict'].includes(formatConfig.checker_type) || !formatConfig.checker_type)) return;
|
||||
if (key === 'interactor' && config.type !== 'interactive') return;
|
||||
if (key === 'subtasks') {
|
||||
formatConfig[key] = [];
|
||||
config[key].forEach((subtask) => {
|
||||
const formatSubtask: object = {};
|
||||
subtasksKey.forEach((subtaskKey) => {
|
||||
if (subtask && subtask[subtaskKey] !== undefined) {
|
||||
formatSubtask[subtaskKey] = subtask[subtaskKey];
|
||||
}
|
||||
});
|
||||
formatConfig[key].push(formatSubtask);
|
||||
});
|
||||
} else if (key === 'cases') {
|
||||
formatConfig[key] = [];
|
||||
config[key].forEach((caseItem) => {
|
||||
const formatCase: TestCaseConfig = {
|
||||
time: '1000ms', memory: '256MB', input: '', output: '',
|
||||
};
|
||||
casesKey.forEach((caseKey) => {
|
||||
if (caseItem[caseKey] !== undefined) formatCase[caseKey] = caseItem[caseKey];
|
||||
else delete formatCase[caseKey];
|
||||
});
|
||||
formatConfig[key].push(formatCase);
|
||||
});
|
||||
} else formatConfig[key] = config[key];
|
||||
}
|
||||
});
|
||||
if (formatConfig.type === 'objective') {
|
||||
Object.keys(formatConfig).filter((i) => !['type', 'outputs'].includes(i)).forEach((i) => delete formatConfig[i]);
|
||||
formatConfig.outputs = formatConfig.outputs || [];
|
||||
}
|
||||
Object.keys(formatConfig).filter((i) => i.startsWith('__')).forEach((i) => delete formatConfig[i]);
|
||||
return formatConfig;
|
||||
}
|
||||
|
||||
export default connect(mapStateToProps, mapDispatchToProps)(class MonacoEditor extends React.PureComponent<Props> {
|
||||
disposable = [];
|
||||
containerElement: HTMLElement;
|
||||
private __preventUpdate = false;
|
||||
private __preventFormat = false;
|
||||
|
||||
editor: editor.IStandaloneCodeEditor;
|
||||
model: editor.ITextModel;
|
||||
vjEditor: Editor;
|
||||
|
||||
async componentDidMount() {
|
||||
const { monaco } = await load(['yaml']);
|
||||
const uri = monaco.Uri.parse('hydro://problem/file/config.yaml');
|
||||
this.model = monaco.editor.createModel(yaml.dump(configYamlFormat(this.props.config)), 'yaml', uri);
|
||||
this.vjEditor = Editor.getOrConstruct($(this.containerElement), {
|
||||
language: 'yaml',
|
||||
model: this.model,
|
||||
onChange: (value: string) => {
|
||||
this.__preventUpdate = true;
|
||||
if (!this.__preventFormat) this.props.handleUpdateCode(value);
|
||||
this.__preventUpdate = false;
|
||||
},
|
||||
}) as Editor;
|
||||
this.editor = this.vjEditor.editor;
|
||||
}
|
||||
|
||||
componentDidUpdate(prevProps) {
|
||||
if (this.__preventUpdate || !this.model) return;
|
||||
if (yaml.dump(prevProps.config) !== yaml.dump(this.props.config)) {
|
||||
this.__preventFormat = true;
|
||||
const curValue = this.model.getValue();
|
||||
const diff = diffLines(curValue, yaml.dump(configYamlFormat(this.props.config)));
|
||||
const ops = [];
|
||||
let cursor = 1;
|
||||
for (const line of diff) {
|
||||
if (line.added) {
|
||||
let range = this.model.getFullModelRange();
|
||||
range = range.setStartPosition(cursor, 0);
|
||||
range = range.setEndPosition(cursor, 0);
|
||||
ops.push({ range, text: line.value });
|
||||
} else if (line.removed) {
|
||||
let range = this.model.getFullModelRange();
|
||||
range = range.setStartPosition(cursor, 0);
|
||||
cursor += line.count;
|
||||
range = range.setEndPosition(cursor, 0);
|
||||
ops.push({ range, text: '' });
|
||||
} else cursor += line.count;
|
||||
}
|
||||
this.model.pushEditOperations([], ops, undefined);
|
||||
this.__preventFormat = false;
|
||||
}
|
||||
}
|
||||
|
||||
componentWillUnmount() {
|
||||
if (this.vjEditor) this.vjEditor.destory();
|
||||
if (this.model) this.model.dispose();
|
||||
if (this.editor) this.editor.dispose();
|
||||
this.disposable.map((i) => i.dispose());
|
||||
}
|
||||
|
||||
assignRef = (component) => {
|
||||
this.containerElement = component;
|
||||
};
|
||||
|
||||
render() {
|
||||
return (
|
||||
<div
|
||||
ref={this.assignRef}
|
||||
style={{
|
||||
minHeight: '500px',
|
||||
height: '100%',
|
||||
width: '100%',
|
||||
}}
|
||||
className="ConfigMonacoEditor"
|
||||
>
|
||||
</div>
|
||||
);
|
||||
}
|
||||
});
|
||||
@@ -0,0 +1,128 @@
|
||||
import React from 'react';
|
||||
import { useDispatch, useSelector } from 'react-redux';
|
||||
import i18n from 'vj/utils/i18n';
|
||||
import {
|
||||
Card, Tab, Tabs, InputGroup, Tag,
|
||||
} from '@blueprintjs/core';
|
||||
import type { RootState } from './reducer/index';
|
||||
import CustomSelectAutoComplete from '../autocomplete/components/CustomSelectAutoComplete';
|
||||
import FileSelectAutoComplete from '../autocomplete/components/FileSelectAutoComplete';
|
||||
import { FormItem } from './BasicForm';
|
||||
import ProblemType from './ProblemType';
|
||||
import { TaskConfig } from './SubtaskTable';
|
||||
|
||||
function FileIOConfig() {
|
||||
const filename = useSelector((state: RootState) => state.config.filename);
|
||||
const dispatch = useDispatch();
|
||||
return (
|
||||
<FormItem columns={12} label="FileIOConfig" disableLabel>
|
||||
<Card style={{ padding: 10 }}>
|
||||
<div className="row">
|
||||
<FormItem columns={6} label="FileIO">
|
||||
<InputGroup
|
||||
rightElement={<Tag minimal>.in/.out</Tag>}
|
||||
value={filename || ''}
|
||||
onChange={(ev) => {
|
||||
dispatch({ type: 'CONFIG_FORM_UPDATE', key: 'filename', value: ev.currentTarget.value });
|
||||
}}
|
||||
fill
|
||||
/>
|
||||
</FormItem>
|
||||
</div>
|
||||
</Card>
|
||||
</FormItem>
|
||||
);
|
||||
}
|
||||
|
||||
function ExtraFilesConfig() {
|
||||
const Files = useSelector((state: RootState) => state.testdata);
|
||||
const userExtraFiles = useSelector((state: RootState) => state.config.user_extra_files) || [];
|
||||
const judgeExtraFiles = useSelector((state: RootState) => state.config.judge_extra_files) || [];
|
||||
const dispatch = useDispatch();
|
||||
const userRef = React.useRef<any>();
|
||||
const judgeRef = React.useRef<any>();
|
||||
React.useEffect(() => {
|
||||
userRef.current.setSelectedKeys(userExtraFiles);
|
||||
}, [JSON.stringify(userExtraFiles)]);
|
||||
React.useEffect(() => {
|
||||
judgeRef.current.setSelectedKeys(judgeExtraFiles);
|
||||
}, [JSON.stringify(judgeExtraFiles)]);
|
||||
return (
|
||||
<FormItem columns={12} label="ExtraFilesTabs" disableLabel>
|
||||
<Tabs id="ExtraFilesTabs">
|
||||
<Tab
|
||||
id="user_extra_files"
|
||||
title={i18n('user_extra_files')}
|
||||
panel={(
|
||||
<FileSelectAutoComplete
|
||||
ref={userRef}
|
||||
data={Files}
|
||||
selectedKeys={userExtraFiles}
|
||||
onChange={(val) => dispatch({ type: 'CONFIG_FORM_UPDATE', key: 'user_extra_files', value: val.split(',') })}
|
||||
multi
|
||||
/>
|
||||
)}
|
||||
/>
|
||||
<Tab
|
||||
id="judge_extra_files"
|
||||
title={i18n('judge_extra_files')}
|
||||
panel={(
|
||||
<FileSelectAutoComplete
|
||||
ref={judgeRef}
|
||||
data={Files}
|
||||
selectedKeys={judgeExtraFiles}
|
||||
onChange={(val) => dispatch({ type: 'CONFIG_FORM_UPDATE', key: 'judge_extra_files', value: val.split(',') })}
|
||||
multi
|
||||
/>
|
||||
)}
|
||||
/>
|
||||
</Tabs>
|
||||
</FormItem>
|
||||
);
|
||||
}
|
||||
|
||||
function LangConfig() {
|
||||
const langs = useSelector((state: RootState) => state.config.langs) || [];
|
||||
const prefixes = new Set(Object.keys(LANGS).filter((i) => i.includes('.')).map((i) => i.split('.')[0]));
|
||||
const data = Object.keys(LANGS).filter((i) => !prefixes.has(i))
|
||||
.map((i) => ({ name: LANGS[i].display, _id: i }));
|
||||
const dispatch = useDispatch();
|
||||
const ref = React.useRef<any>();
|
||||
const selectedKeys = langs.filter((i) => !prefixes.has(i));
|
||||
React.useEffect(() => {
|
||||
ref.current.setSelectedKeys(selectedKeys);
|
||||
}, [JSON.stringify(selectedKeys)]);
|
||||
return (
|
||||
<FormItem columns={12} label="langs">
|
||||
<CustomSelectAutoComplete
|
||||
ref={ref}
|
||||
data={data}
|
||||
placeholder={i18n('Unlimited')}
|
||||
selectedKeys={selectedKeys}
|
||||
onChange={(val) => {
|
||||
const value = val.split(',');
|
||||
value.push(...Array.from(new Set(value.filter((i) => i.includes('.')).map((i) => i.split('.')[0]))));
|
||||
dispatch({ type: 'CONFIG_FORM_UPDATE', key: 'langs', value });
|
||||
}}
|
||||
multi
|
||||
/>
|
||||
</FormItem>
|
||||
);
|
||||
}
|
||||
|
||||
export default function ProblemConfigForm() {
|
||||
const Type = useSelector((state: RootState) => state.config.type);
|
||||
return (
|
||||
<div className="row problem-config-form">
|
||||
<ProblemType />
|
||||
{Type === 'default' && <FileIOConfig />}
|
||||
{!['submit_answer', 'objective'].includes(Type) && (
|
||||
<>
|
||||
<TaskConfig />
|
||||
<ExtraFilesConfig />
|
||||
<LangConfig />
|
||||
</>
|
||||
)}
|
||||
</div>
|
||||
);
|
||||
}
|
||||
@@ -0,0 +1,129 @@
|
||||
import React from 'react';
|
||||
import { useDispatch, useSelector } from 'react-redux';
|
||||
import i18n from 'vj/utils/i18n';
|
||||
import {
|
||||
Card, Switch, Tab, Tabs,
|
||||
} from '@blueprintjs/core';
|
||||
import type { RootState } from './reducer/index';
|
||||
import { FormItem, ManagedSelect, SingleFileSelect } from './BasicForm';
|
||||
|
||||
export default function ProblemType() {
|
||||
const Type = useSelector((state: RootState) => state.config.type);
|
||||
const checkerType = useSelector((state: RootState) => state.config.checker_type);
|
||||
const filename = useSelector((state: RootState) => state.config.filename);
|
||||
const subType = useSelector((state: RootState) => state.config.subType);
|
||||
const dispatch = useDispatch();
|
||||
const dispatcher = (base) => (value) => dispatch({ ...base, value });
|
||||
return (
|
||||
<FormItem columns={12} label="" disableLabel>
|
||||
<Card style={{ padding: 10 }}>
|
||||
<Tabs
|
||||
id="ProblemTypeTabs"
|
||||
selectedTabId={Type}
|
||||
onChange={dispatcher({ type: 'CONFIG_FORM_UPDATE', key: 'type' })}
|
||||
defaultSelectedTabId="default"
|
||||
renderActiveTabPanelOnly
|
||||
>
|
||||
<span className="bp4-tab">{i18n('Problem Type')}</span>
|
||||
<Tabs.Expander />
|
||||
<Tab
|
||||
id="default"
|
||||
title={i18n('problem_type.default')}
|
||||
panel={(
|
||||
<Tabs
|
||||
id="CheckerTypeTabs"
|
||||
selectedTabId={
|
||||
['strict', 'default'].includes(checkerType) || !checkerType
|
||||
? 'default' : (checkerType !== 'testlib' ? 'other' : 'testlib')
|
||||
}
|
||||
onChange={dispatcher({ type: 'CONFIG_FORM_UPDATE', key: 'checker_type' })}
|
||||
renderActiveTabPanelOnly
|
||||
>
|
||||
<span className="bp4-tab">{i18n('CheckerType')}</span>
|
||||
<Tabs.Expander />
|
||||
<Tab
|
||||
id="default"
|
||||
title={i18n('default')}
|
||||
panel={(
|
||||
<div className="row">
|
||||
<FormItem columns={12} label="Config">
|
||||
<Switch
|
||||
checked={checkerType !== 'strict'}
|
||||
label={i18n('Ignore trailing space and enter.')}
|
||||
onChange={() => {
|
||||
dispatch({ type: 'CONFIG_FORM_UPDATE', key: 'checker_type', value: checkerType === 'strict' ? 'default' : 'strict' });
|
||||
}}
|
||||
/>
|
||||
</FormItem>
|
||||
</div>
|
||||
)}
|
||||
/>
|
||||
{['testlib', 'other'].map((i) => (
|
||||
<Tab
|
||||
id={i}
|
||||
title={i}
|
||||
key={i}
|
||||
panel={(
|
||||
<div className="row">
|
||||
{i === 'other' && (
|
||||
<FormItem columns={6} label="Interface">
|
||||
<ManagedSelect options={['syzoj', 'hustoj', 'qduoj', 'lemon']} formKey="checker_type" />
|
||||
</FormItem>
|
||||
)}
|
||||
<FormItem columns={6} label="Checker">
|
||||
<SingleFileSelect formKey="checker" />
|
||||
</FormItem>
|
||||
</div>
|
||||
)}
|
||||
/>
|
||||
))}
|
||||
</Tabs>
|
||||
)}
|
||||
/>
|
||||
<Tab
|
||||
id="interactive"
|
||||
title={i18n('problem_type.interactive')}
|
||||
panel={(
|
||||
<div className="row">
|
||||
<FormItem columns={6} label="Interactor">
|
||||
<SingleFileSelect formKey="interactor" />
|
||||
</FormItem>
|
||||
</div>
|
||||
)}
|
||||
/>
|
||||
<Tab
|
||||
id="submit_answer"
|
||||
title={i18n('problem_type.submit_answer')}
|
||||
panel={(
|
||||
<div className="row">
|
||||
<FormItem columns={6} label="Config" disableLabel>
|
||||
<Switch
|
||||
checked={subType === 'multi'}
|
||||
label={i18n('Multi-file')}
|
||||
onChange={() => {
|
||||
dispatch({ type: 'CONFIG_FORM_UPDATE', key: 'subType', value: subType === 'multi' ? 'single' : 'multi' });
|
||||
}}
|
||||
/>
|
||||
</FormItem>
|
||||
<FormItem columns={6} label="Filename">
|
||||
<input
|
||||
defaultValue={filename || '#.txt'}
|
||||
placeholder="#.txt"
|
||||
disabled={subType !== 'multi'}
|
||||
onChange={(ev) => dispatch(({ type: 'CONFIG_FORM_UPDATE', key: 'filename', value: ev.currentTarget.value }))}
|
||||
className="textbox"
|
||||
/>
|
||||
</FormItem>
|
||||
</div>
|
||||
)}
|
||||
/>
|
||||
<Tab
|
||||
id="objective"
|
||||
title={i18n('problem_type.objective')}
|
||||
panel={(<p>{i18n('Unsupported configure this type of problem. Please refer to the documentation.')}</p>)}
|
||||
/>
|
||||
</Tabs>
|
||||
</Card>
|
||||
</FormItem>
|
||||
);
|
||||
}
|
||||
@@ -0,0 +1,186 @@
|
||||
import { Card, NumericInput, Tag } from '@blueprintjs/core';
|
||||
import { pick, isEqual } from 'lodash';
|
||||
import React from 'react';
|
||||
import { useSelector, useDispatch } from 'react-redux';
|
||||
import { SubtaskConfig } from 'hydrooj/src/interface';
|
||||
import { parseTimeMS, parseMemoryMB } from '@hydrooj/utils/lib/common';
|
||||
import i18n from 'vj/utils/i18n';
|
||||
import CustomSelectAutoComplete from '../autocomplete/components/CustomSelectAutoComplete';
|
||||
import { FormItem } from './BasicForm';
|
||||
import { RootState } from './reducer';
|
||||
import { CasesTable } from './TestCasesTable';
|
||||
|
||||
const eq = (a: SubtaskConfig, b: SubtaskConfig) => isEqual(a, b);
|
||||
|
||||
export function SubtasksIds({ index }) {
|
||||
const ids = useSelector((state: RootState) => state.config.subtasks.map((i) => (i ? i.id : undefined)).filter((i) => i !== undefined).join(','));
|
||||
const subtaskIf = useSelector((state: RootState) => state.config.subtasks[index].if);
|
||||
const dispatch = useDispatch();
|
||||
return (
|
||||
<tr>
|
||||
<td style={{ textAlign: 'center' }}>if</td>
|
||||
<td colSpan={4}>
|
||||
<CustomSelectAutoComplete
|
||||
data={ids.split(',').filter((i) => i.length)}
|
||||
selectedKeys={subtaskIf?.map(String) || []}
|
||||
onChange={(val) => dispatch({
|
||||
type: 'CONFIG_SUBTASK_UPDATE', id: index, key: 'if', value: val.split(','),
|
||||
})}
|
||||
multi
|
||||
/>
|
||||
</td>
|
||||
</tr>
|
||||
);
|
||||
}
|
||||
|
||||
export function SubtasksTable({ index }) {
|
||||
const keys = ['id', 'type', 'score', 'time', 'memory'];
|
||||
const subtask = useSelector((state: RootState) => pick(state.config.subtasks[index], keys), eq);
|
||||
const defaultTime = useSelector((state: RootState) => state.config.time);
|
||||
const defaultMemory = useSelector((state: RootState) => state.config.memory);
|
||||
const dispatch = useDispatch();
|
||||
const dispatcher = (key: string, suffix = '') => (ev: React.ChangeEvent<HTMLInputElement | HTMLSelectElement> | number) => {
|
||||
let value = typeof ev !== 'object' ? ev : ev.currentTarget?.value;
|
||||
if (value === 0) value = '';
|
||||
if (value && suffix) value += suffix;
|
||||
dispatch({
|
||||
type: 'CONFIG_SUBTASK_UPDATE', id: index, key, value,
|
||||
});
|
||||
};
|
||||
if (!subtask || Object.keys(subtask).length === 0) {
|
||||
return (
|
||||
<Card style={{ padding: 0 }}>
|
||||
<span>Subtasks #{index + 1} </span>
|
||||
<p>{i18n('Failed to parse subtask.')}</p>
|
||||
</Card>
|
||||
);
|
||||
}
|
||||
return (
|
||||
<Card style={{ padding: 0 }}>
|
||||
<span>Subtasks #{index + 1} </span>
|
||||
<a onClick={() => dispatch({ type: 'CONFIG_SUBTASK_UPDATE', id: index, key: 'add' })}><span className="icon icon-add"></span></a>
|
||||
<a
|
||||
style={index === 0 ? { display: 'none' } : {}}
|
||||
onClick={() => dispatch({ type: 'CONFIG_SUBTASK_UPDATE', id: index, key: 'delete' })}
|
||||
>
|
||||
<span className="icon icon-delete"></span>
|
||||
</a>
|
||||
<table className="data-table">
|
||||
<thead>
|
||||
<tr>
|
||||
<th>#</th>
|
||||
<th>Score</th>
|
||||
<th>Type</th>
|
||||
<th>Time</th>
|
||||
<th>Memory</th>
|
||||
</tr>
|
||||
</thead>
|
||||
<tbody>
|
||||
<tr>
|
||||
{['id', 'score'].map((key) => (
|
||||
<td key={key}>
|
||||
<input
|
||||
value={subtask[key] ?? ''}
|
||||
onChange={dispatcher(key)}
|
||||
type="number"
|
||||
className="textbox"
|
||||
/>
|
||||
</td>
|
||||
))}
|
||||
<td>
|
||||
<select
|
||||
value={subtask.type ?? 'min'}
|
||||
onChange={dispatcher('type')}
|
||||
className="select"
|
||||
>
|
||||
{['min', 'max', 'sum'].map((i) => (<option value={i} key={i}>{i}</option>))}
|
||||
</select>
|
||||
</td>
|
||||
<td>
|
||||
<NumericInput
|
||||
rightElement={<Tag minimal>ms</Tag>}
|
||||
value={subtask.time ? parseTimeMS(subtask.time, false).toString() : ''}
|
||||
placeholder={parseTimeMS(defaultTime || '1000ms', false).toString()}
|
||||
onValueChange={dispatcher('time', 'ms')}
|
||||
buttonPosition="none"
|
||||
fill
|
||||
/>
|
||||
</td>
|
||||
<td>
|
||||
<NumericInput
|
||||
rightElement={<Tag minimal>MB</Tag>}
|
||||
value={subtask.memory ? parseMemoryMB(subtask.memory, false).toString() : ''}
|
||||
placeholder={parseMemoryMB(defaultMemory || '256m', false).toString()}
|
||||
onValueChange={dispatcher('memory', 'MB')}
|
||||
buttonPosition="none"
|
||||
fill
|
||||
/>
|
||||
</td>
|
||||
</tr>
|
||||
<SubtasksIds index={index} />
|
||||
</tbody>
|
||||
</table>
|
||||
<CasesTable index={index} />
|
||||
</Card>
|
||||
);
|
||||
}
|
||||
|
||||
function GlobalTaskConfig() {
|
||||
const time = useSelector((state: RootState) => state.config.time);
|
||||
const memory = useSelector((state: RootState) => state.config.memory);
|
||||
const dispatch = useDispatch();
|
||||
const dispatcher = (key: string, suffix = '') => (ev: React.ChangeEvent<HTMLInputElement | HTMLSelectElement> | number) => {
|
||||
let value = typeof ev !== 'object' ? ev : ev.currentTarget?.value;
|
||||
if (value === 0) value = '';
|
||||
if (value && suffix) value += suffix;
|
||||
dispatch({ type: 'CONFIG_FORM_UPDATE', key, value });
|
||||
};
|
||||
return (
|
||||
<>
|
||||
<FormItem columns={6} label="Time">
|
||||
<NumericInput
|
||||
rightElement={<Tag minimal>ms</Tag>}
|
||||
value={time ? parseTimeMS(time, false).toString() : ''}
|
||||
placeholder={parseTimeMS('1000ms').toString()}
|
||||
onValueChange={dispatcher('time', 'ms')}
|
||||
buttonPosition="none"
|
||||
fill
|
||||
/>
|
||||
</FormItem>
|
||||
<FormItem columns={6} label="Memory">
|
||||
<NumericInput
|
||||
rightElement={<Tag minimal>MB</Tag>}
|
||||
value={memory ? parseMemoryMB(memory, false).toString() : ''}
|
||||
placeholder={parseMemoryMB('256m').toString()}
|
||||
onValueChange={dispatcher('memory', 'MB')}
|
||||
buttonPosition="none"
|
||||
fill
|
||||
/>
|
||||
</FormItem>
|
||||
</>
|
||||
);
|
||||
}
|
||||
|
||||
export function TaskConfig() {
|
||||
const len = useSelector((state: RootState) => state.config.subtasks?.length);
|
||||
const dispatch = useDispatch();
|
||||
return (
|
||||
<FormItem columns={12} label="Task Settings">
|
||||
<div className="row">
|
||||
<GlobalTaskConfig />
|
||||
<FormItem columns={12} label="TestCases" disableLabel>
|
||||
{len > 0
|
||||
? [...Array(len).keys()].map((i) => <SubtasksTable index={i} key={i} />)
|
||||
: (
|
||||
<>
|
||||
<span>Subtasks # </span>
|
||||
<a onClick={() => dispatch({ type: 'CONFIG_SUBTASK_UPDATE', id: 0, key: 'add' })}>
|
||||
<span className="icon icon-add"></span>
|
||||
</a>
|
||||
</>
|
||||
)}
|
||||
</FormItem>
|
||||
</div>
|
||||
</FormItem>
|
||||
);
|
||||
}
|
||||
@@ -0,0 +1,128 @@
|
||||
import React from 'react';
|
||||
import { useDispatch, useSelector } from 'react-redux';
|
||||
import i18n from 'vj/utils/i18n';
|
||||
import { isEqual } from 'lodash';
|
||||
import { Tag, NumericInput } from '@blueprintjs/core';
|
||||
import { parseTimeMS, parseMemoryMB } from '@hydrooj/utils/lib/common';
|
||||
import type { SubtaskConfig } from 'hydrooj/src/interface';
|
||||
import type { RootState } from './reducer/index';
|
||||
import FileSelectAutoComplete from '../autocomplete/components/FileSelectAutoComplete';
|
||||
|
||||
const eq = (a: SubtaskConfig, b: SubtaskConfig) => isEqual(a, b);
|
||||
const eqArr = (a: any[], b: any[]) => isEqual(a, b);
|
||||
|
||||
export function TestCaseEntry({ index, subindex }) {
|
||||
const testcase = useSelector((state: RootState) => state.config.subtasks[index].cases[subindex], eq);
|
||||
const Files = useSelector((state: RootState) => state.testdata, eqArr);
|
||||
const defaultTime = useSelector((state: RootState) => state.config.subtasks[index].time || state.config.time);
|
||||
const defaultMemory = useSelector((state: RootState) => state.config.subtasks[index].memory || state.config.memory);
|
||||
const dispatch = useDispatch();
|
||||
const dispatcher = (casesKey: string, valueSuffix = '') => (ev: React.ChangeEvent<HTMLInputElement | HTMLSelectElement> | number) => {
|
||||
let value = typeof ev !== 'object' ? ev : ev.currentTarget.value;
|
||||
if (value === 0) value = '';
|
||||
if (valueSuffix && value) value += valueSuffix;
|
||||
dispatch({
|
||||
type: 'CONFIG_SUBTASK_UPDATE',
|
||||
id: index,
|
||||
key: 'cases-edit',
|
||||
casesId: subindex,
|
||||
casesKey,
|
||||
value,
|
||||
});
|
||||
};
|
||||
if (!testcase || Object.keys(testcase).length === 0) {
|
||||
return (
|
||||
<tr><td colSpan={5}>{i18n('Failed to parse testcase.')}</td></tr>
|
||||
);
|
||||
}
|
||||
return (
|
||||
<tr>
|
||||
<td>
|
||||
<NumericInput
|
||||
rightElement={<Tag minimal>ms</Tag>}
|
||||
value={testcase.time ? parseTimeMS(testcase.time, false).toString() : ''}
|
||||
placeholder={parseTimeMS(defaultTime || '1000ms', false).toString()}
|
||||
onValueChange={dispatcher('time', 'ms')}
|
||||
buttonPosition="none"
|
||||
fill
|
||||
/>
|
||||
</td>
|
||||
<td>
|
||||
<NumericInput
|
||||
rightElement={<Tag minimal>MB</Tag>}
|
||||
value={testcase.memory ? parseMemoryMB(testcase.memory, false).toString() : ''}
|
||||
placeholder={parseMemoryMB(defaultMemory || '256m', false).toString()}
|
||||
onValueChange={dispatcher('memory', 'MB')}
|
||||
buttonPosition="none"
|
||||
fill
|
||||
/>
|
||||
</td>
|
||||
{['input', 'output'].map((t) => (
|
||||
<td key={t}>
|
||||
<FileSelectAutoComplete
|
||||
width="100%"
|
||||
data={Files}
|
||||
selectedKeys={[testcase[t]]}
|
||||
onChange={dispatcher(t)}
|
||||
/>
|
||||
</td>
|
||||
))}
|
||||
<td className="col--operation">
|
||||
<a
|
||||
onClick={() => dispatch({
|
||||
type: 'CONFIG_SUBTASK_UPDATE', id: index, key: 'cases-delete', value: subindex,
|
||||
})}
|
||||
><span className="icon icon-close"></span>
|
||||
</a>
|
||||
</td>
|
||||
</tr>
|
||||
);
|
||||
}
|
||||
|
||||
export function CasesTable({ index }) {
|
||||
const len = useSelector((state: RootState) => state.config.subtasks[index].cases?.length);
|
||||
const dispatch = useDispatch();
|
||||
return (
|
||||
<table className="data-table">
|
||||
<thead style={{ display: 'none' }}>
|
||||
<tr>
|
||||
<th>{i18n('Time')}</th>
|
||||
<th>{i18n('Memory')}</th>
|
||||
<th>{i18n('Input')}</th>
|
||||
<th>{i18n('Output')}</th>
|
||||
<th className="col--operation">
|
||||
<a
|
||||
onClick={() => dispatch({
|
||||
type: 'CONFIG_SUBTASK_UPDATE',
|
||||
id: index,
|
||||
key: 'cases-add',
|
||||
value: { input: '', output: '' },
|
||||
})}
|
||||
><span className="icon icon-add" />
|
||||
</a>
|
||||
</th>
|
||||
</tr>
|
||||
</thead>
|
||||
<tbody>
|
||||
<tr className="thead">
|
||||
<td>{i18n('Time')}</td>
|
||||
<td>{i18n('Memory')}</td>
|
||||
<td>{i18n('Input')}</td>
|
||||
<td>{i18n('Output')}</td>
|
||||
<td className="col--operation">
|
||||
<a
|
||||
onClick={() => dispatch({
|
||||
type: 'CONFIG_SUBTASK_UPDATE',
|
||||
id: index,
|
||||
key: 'cases-add',
|
||||
value: { input: '', output: '' },
|
||||
})}
|
||||
><span className="icon icon-add" />
|
||||
</a>
|
||||
</td>
|
||||
</tr>
|
||||
{len > 0 && [...Array(len).keys()].map((i) => <TestCaseEntry index={index} subindex={i} key={i} />)}
|
||||
</tbody>
|
||||
</table>
|
||||
);
|
||||
}
|
||||
@@ -0,0 +1,69 @@
|
||||
import yaml from 'js-yaml';
|
||||
import type { ProblemConfigFile } from 'hydrooj/src/interface';
|
||||
import { cloneDeep } from 'lodash';
|
||||
import { parseMemoryMB, parseTimeMS } from '@hydrooj/utils/lib/common';
|
||||
|
||||
type State = ProblemConfigFile & { __loaded: boolean };
|
||||
|
||||
export default function reducer(state = { type: 'default', __loaded: false } as State, action): State {
|
||||
switch (action.type) {
|
||||
case 'CONFIG_LOAD_FULFILLED': {
|
||||
return { ...state, ...yaml.load(action.payload.config) as object, __loaded: true };
|
||||
}
|
||||
case 'CONFIG_FORM_UPDATE': {
|
||||
const next = { ...state, [action.key]: action.value };
|
||||
if (action.key === 'score' && action.value) next.score = +next.score;
|
||||
if (action.key === 'checker_type' && action.value === 'other') next.checker_type = 'syzoj';
|
||||
if (!action.value || (typeof action.value === 'object' && !action.value.join(''))) delete next[action.key];
|
||||
return next;
|
||||
}
|
||||
case 'CONFIG_CODE_UPDATE': {
|
||||
try {
|
||||
return { ...state, ...yaml.load(action.payload) as object };
|
||||
} catch {
|
||||
return state;
|
||||
}
|
||||
}
|
||||
case 'CONFIG_AUTOCASES_UPDATE': {
|
||||
const next = { ...state };
|
||||
const { subtasks } = action;
|
||||
for (const subtask of subtasks) {
|
||||
if (subtask.time === parseTimeMS(state.time || '1s')) delete subtask.time;
|
||||
if (subtask.memory === parseMemoryMB(state.memory || '256m')) delete subtask.memory;
|
||||
if (subtask.time) subtask.time += 'ms';
|
||||
if (subtask.memory) subtask.memory += 'MB';
|
||||
}
|
||||
if (subtasks.length === 0) next.subtasks = [];
|
||||
else {
|
||||
next.subtasks = subtasks.map((subtask) => (
|
||||
{ ...subtask, ...{ cases: subtask.cases.map((i) => ({ input: i.input, output: i.output })) } }));
|
||||
}
|
||||
return next;
|
||||
}
|
||||
case 'CONFIG_SUBTASK_UPDATE': {
|
||||
const subtasks = cloneDeep(state.subtasks);
|
||||
const subsubtasks = cloneDeep(state.subtasks[action.id]);
|
||||
if (action.value !== '' && ['score', 'id'].includes(action.key)) action.value = +action.value;
|
||||
if (action.key === 'if' && action.value.join('') !== '') action.value = action.value.map((i) => +i);
|
||||
if (action.key.split('-')[0] === 'cases') {
|
||||
if (action.key === 'cases-add') subsubtasks.cases.push(action.value);
|
||||
else if (action.key === 'cases-edit') {
|
||||
if (action.value === '') delete subsubtasks.cases[action.casesId][action.casesKey];
|
||||
else subsubtasks.cases[action.casesId][action.casesKey] = action.value;
|
||||
} else if (action.key === 'cases-delete') {
|
||||
subsubtasks.cases = subsubtasks.cases.filter((k, v) => v !== action.value);
|
||||
}
|
||||
} else if (action.key === 'add') {
|
||||
return { ...state, subtasks: [...subtasks, { time: state.time || '1s', memory: state.memory || '256m', cases: [] }] };
|
||||
} else if (action.key === 'delete') return { ...state, subtasks: subtasks.filter((k, v) => v !== action.id) };
|
||||
else {
|
||||
if (action.value === '' || (action.key === 'if' && action.value.join('') === '')) delete subsubtasks[action.key];
|
||||
else subsubtasks[action.key] = action.value;
|
||||
}
|
||||
subtasks[action.id] = subsubtasks;
|
||||
return { ...state, subtasks };
|
||||
}
|
||||
default:
|
||||
return state;
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,11 @@
|
||||
import { combineReducers } from 'redux';
|
||||
import config from './config';
|
||||
import testdata from './testdata';
|
||||
|
||||
const reducer = combineReducers({
|
||||
config,
|
||||
testdata,
|
||||
});
|
||||
|
||||
export default reducer;
|
||||
export type RootState = ReturnType<typeof reducer>;
|
||||
@@ -0,0 +1,16 @@
|
||||
export default function reducer(state = [], action) {
|
||||
switch (action.type) {
|
||||
case 'CONFIG_LOAD_FULFILLED': {
|
||||
return state.concat(action.payload.testdata);
|
||||
}
|
||||
case 'CONFIG_DELETE_TESTDATA': {
|
||||
const next = state.filter((i) => i.name !== action.value[0]);
|
||||
return next;
|
||||
}
|
||||
case 'CONFIG_ADD_TESTDATA': {
|
||||
return state.concat([action.value]);
|
||||
}
|
||||
default:
|
||||
return state;
|
||||
}
|
||||
}
|
||||
@@ -5,36 +5,36 @@ export default function reducer(state = {
|
||||
items: {},
|
||||
}, action) {
|
||||
switch (action.type) {
|
||||
case 'SCRATCHPAD_RECORDS_LOAD_SUBMISSIONS_FULFILLED': {
|
||||
const { rdocs } = action.payload;
|
||||
return {
|
||||
...state,
|
||||
rows: _.map(rdocs, '_id'),
|
||||
items: _.keyBy(rdocs, '_id'),
|
||||
};
|
||||
}
|
||||
case 'SCRATCHPAD_RECORDS_PUSH': {
|
||||
const { rdoc } = action.payload;
|
||||
const rows = [...state.rows];
|
||||
if (!rows.includes(rdoc._id)) {
|
||||
case 'SCRATCHPAD_RECORDS_LOAD_SUBMISSIONS_FULFILLED': {
|
||||
const { rdocs } = action.payload;
|
||||
return {
|
||||
...state,
|
||||
rows: _.map(rdocs, '_id'),
|
||||
items: _.keyBy(rdocs, '_id'),
|
||||
};
|
||||
}
|
||||
case 'SCRATCHPAD_RECORDS_PUSH': {
|
||||
const { rdoc } = action.payload;
|
||||
const rows = [...state.rows];
|
||||
if (!rows.includes(rdoc._id)) {
|
||||
return {
|
||||
...state,
|
||||
rows: [rdoc._id, ...state.rows],
|
||||
items: {
|
||||
...state.items,
|
||||
[rdoc._id]: rdoc,
|
||||
},
|
||||
};
|
||||
}
|
||||
return {
|
||||
...state,
|
||||
rows: [rdoc._id, ...state.rows],
|
||||
items: {
|
||||
...state.items,
|
||||
[rdoc._id]: rdoc,
|
||||
},
|
||||
};
|
||||
}
|
||||
return {
|
||||
...state,
|
||||
items: {
|
||||
...state.items,
|
||||
[rdoc._id]: rdoc,
|
||||
},
|
||||
};
|
||||
}
|
||||
default:
|
||||
return state;
|
||||
default:
|
||||
return state;
|
||||
}
|
||||
}
|
||||
@@ -19,93 +19,93 @@ export default function reducer(state = {
|
||||
isPosting: false,
|
||||
}, action) {
|
||||
switch (action.type) {
|
||||
case 'SCRATCHPAD_UI_CHANGE_SIZE': {
|
||||
const { uiElement, size } = action.payload;
|
||||
return {
|
||||
...state,
|
||||
[uiElement]: {
|
||||
...state[uiElement],
|
||||
size,
|
||||
},
|
||||
};
|
||||
}
|
||||
case 'SCRATCHPAD_UI_SET_VISIBILITY': {
|
||||
const { uiElement, visibility } = action.payload;
|
||||
localStorage.setItem(`scratchpad/${uiElement}`, visibility.toString());
|
||||
return {
|
||||
...state,
|
||||
[uiElement]: {
|
||||
...state[uiElement],
|
||||
visible: visibility,
|
||||
},
|
||||
};
|
||||
}
|
||||
case 'SCRATCHPAD_UI_TOGGLE_VISIBILITY': {
|
||||
const { uiElement } = action.payload;
|
||||
localStorage.setItem(`scratchpad/${uiElement}`, (!state[uiElement].visible).toString());
|
||||
return {
|
||||
...state,
|
||||
[uiElement]: {
|
||||
...state[uiElement],
|
||||
visible: !state[uiElement].visible,
|
||||
},
|
||||
};
|
||||
}
|
||||
case 'SCRATCHPAD_POST_PRETEST_PENDING':
|
||||
case 'SCRATCHPAD_POST_SUBMIT_PENDING': {
|
||||
return {
|
||||
...state,
|
||||
isPosting: true,
|
||||
};
|
||||
}
|
||||
case 'SCRATCHPAD_POST_PRETEST_FULFILLED':
|
||||
case 'SCRATCHPAD_POST_SUBMIT_FULFILLED': {
|
||||
Notification.success(i18n('Submitted.'));
|
||||
if (action.type === 'SCRATCHPAD_POST_SUBMIT_FULFILLED' && UiContext.canViewRecord) {
|
||||
state.records.visible = true;
|
||||
case 'SCRATCHPAD_UI_CHANGE_SIZE': {
|
||||
const { uiElement, size } = action.payload;
|
||||
return {
|
||||
...state,
|
||||
[uiElement]: {
|
||||
...state[uiElement],
|
||||
size,
|
||||
},
|
||||
};
|
||||
}
|
||||
return {
|
||||
...state,
|
||||
isPosting: false,
|
||||
};
|
||||
}
|
||||
case 'SCRATCHPAD_POST_PRETEST_REJECTED':
|
||||
case 'SCRATCHPAD_POST_SUBMIT_REJECTED': {
|
||||
Notification.error(action.payload.message);
|
||||
return {
|
||||
...state,
|
||||
isPosting: false,
|
||||
};
|
||||
}
|
||||
case 'SCRATCHPAD_RECORDS_LOAD_SUBMISSIONS_PENDING': {
|
||||
return {
|
||||
...state,
|
||||
records: {
|
||||
...state.records,
|
||||
isLoading: true,
|
||||
},
|
||||
};
|
||||
}
|
||||
case 'SCRATCHPAD_RECORDS_LOAD_SUBMISSIONS_REJECTED': {
|
||||
Notification.error(action.payload.message);
|
||||
return {
|
||||
...state,
|
||||
records: {
|
||||
...state.records,
|
||||
isLoading: false,
|
||||
},
|
||||
};
|
||||
}
|
||||
case 'SCRATCHPAD_RECORDS_LOAD_SUBMISSIONS_FULFILLED': {
|
||||
return {
|
||||
...state,
|
||||
records: {
|
||||
...state.records,
|
||||
isLoading: false,
|
||||
},
|
||||
};
|
||||
}
|
||||
default:
|
||||
return state;
|
||||
case 'SCRATCHPAD_UI_SET_VISIBILITY': {
|
||||
const { uiElement, visibility } = action.payload;
|
||||
localStorage.setItem(`scratchpad/${uiElement}`, visibility.toString());
|
||||
return {
|
||||
...state,
|
||||
[uiElement]: {
|
||||
...state[uiElement],
|
||||
visible: visibility,
|
||||
},
|
||||
};
|
||||
}
|
||||
case 'SCRATCHPAD_UI_TOGGLE_VISIBILITY': {
|
||||
const { uiElement } = action.payload;
|
||||
localStorage.setItem(`scratchpad/${uiElement}`, (!state[uiElement].visible).toString());
|
||||
return {
|
||||
...state,
|
||||
[uiElement]: {
|
||||
...state[uiElement],
|
||||
visible: !state[uiElement].visible,
|
||||
},
|
||||
};
|
||||
}
|
||||
case 'SCRATCHPAD_POST_PRETEST_PENDING':
|
||||
case 'SCRATCHPAD_POST_SUBMIT_PENDING': {
|
||||
return {
|
||||
...state,
|
||||
isPosting: true,
|
||||
};
|
||||
}
|
||||
case 'SCRATCHPAD_POST_PRETEST_FULFILLED':
|
||||
case 'SCRATCHPAD_POST_SUBMIT_FULFILLED': {
|
||||
Notification.success(i18n('Submitted.'));
|
||||
if (action.type === 'SCRATCHPAD_POST_SUBMIT_FULFILLED' && UiContext.canViewRecord) {
|
||||
state.records.visible = true;
|
||||
}
|
||||
return {
|
||||
...state,
|
||||
isPosting: false,
|
||||
};
|
||||
}
|
||||
case 'SCRATCHPAD_POST_PRETEST_REJECTED':
|
||||
case 'SCRATCHPAD_POST_SUBMIT_REJECTED': {
|
||||
Notification.error(action.payload.message);
|
||||
return {
|
||||
...state,
|
||||
isPosting: false,
|
||||
};
|
||||
}
|
||||
case 'SCRATCHPAD_RECORDS_LOAD_SUBMISSIONS_PENDING': {
|
||||
return {
|
||||
...state,
|
||||
records: {
|
||||
...state.records,
|
||||
isLoading: true,
|
||||
},
|
||||
};
|
||||
}
|
||||
case 'SCRATCHPAD_RECORDS_LOAD_SUBMISSIONS_REJECTED': {
|
||||
Notification.error(action.payload.message);
|
||||
return {
|
||||
...state,
|
||||
records: {
|
||||
...state.records,
|
||||
isLoading: false,
|
||||
},
|
||||
};
|
||||
}
|
||||
case 'SCRATCHPAD_RECORDS_LOAD_SUBMISSIONS_FULFILLED': {
|
||||
return {
|
||||
...state,
|
||||
records: {
|
||||
...state.records,
|
||||
isLoading: false,
|
||||
},
|
||||
};
|
||||
}
|
||||
default:
|
||||
return state;
|
||||
}
|
||||
}
|
||||
@@ -5,7 +5,6 @@ export default class Sock {
|
||||
const i = new URL(url, window.location.href);
|
||||
i.protocol = i.protocol.replace('http', 'ws');
|
||||
this.url = i.toString();
|
||||
this.closed = false;
|
||||
this.sock = new ReconnectingWebSocket(this.url);
|
||||
this.sock.onopen = () => {
|
||||
console.log('Connected');
|
||||
@@ -13,17 +12,14 @@ export default class Sock {
|
||||
};
|
||||
this.sock.onclose = ({ code, reason }) => {
|
||||
console.warn('Connection closed, ', code, reason);
|
||||
if (code >= 4000) this.closed = true;
|
||||
if (code >= 4000) this.close();
|
||||
this.onclose?.(code, reason);
|
||||
};
|
||||
this.sock.onmessage = (message) => {
|
||||
if (process.env.NODE_ENV !== 'production') console.log('Sock.onmessage: ', message);
|
||||
const msg = JSON.parse(message.data);
|
||||
if (msg.event === 'auth') {
|
||||
if (msg.error === 'PermissionError' || msg.error === 'PrivilegeError') {
|
||||
this.close();
|
||||
}
|
||||
} else this.onmessage?.(message);
|
||||
if (msg.error === 'PermissionError' || msg.error === 'PrivilegeError') this.close();
|
||||
else this.onmessage?.(message);
|
||||
};
|
||||
}
|
||||
|
||||
@@ -32,7 +28,6 @@ export default class Sock {
|
||||
}
|
||||
|
||||
close() {
|
||||
this.closed = true;
|
||||
this.sock?.close?.();
|
||||
}
|
||||
}
|
||||
@@ -51,6 +51,7 @@ export default async function download(filename, targets) {
|
||||
stream,
|
||||
};
|
||||
} catch (e) {
|
||||
window.captureException?.(e);
|
||||
stopDownload();
|
||||
Notification.error(i18n('Download Error', [target.filename, e.toString()]));
|
||||
}
|
||||
@@ -144,6 +145,7 @@ export async function downloadProblemSet(pids, name = 'Export') {
|
||||
}
|
||||
await download(`${name}.zip`, targets);
|
||||
} catch (e) {
|
||||
window.captureException?.(e);
|
||||
Notification.error(`${e.message} ${e.params?.[0]}`);
|
||||
}
|
||||
}
|
||||
|
||||
Reference in new issue
Block a user