language
stringclasses
5 values
text
stringlengths
15
988k
JavaScript
class App extends Component { constructor(props) { super(props) this.state = { loading: true, loggedIn: null } } componentDidMount() { // Handle OAuth login redirects window.firebase.auth().getRedirectResult().then(result => { let token = account.getToken() let username = account.getUsername() // If no user found and we haven't previously logged in, show login button if (!result.user && (!token || !username)) { this.setState({ loggedIn: false }) return } // If we logged in for first time, save user information if (result.credential) { account.setData({ token: result.credential.accessToken, username: result.additionalUserInfo.username }) } }).catch(error => { if (error.message) { alert(JSON.stringify(error)) } }) // When a user logs in or out window.firebase.auth().onAuthStateChanged((user) => { this.setState({ loggedIn: !!user, user, loading: false }) // SEED lesson plans // db.createLessonPlan(lps['git-and-github']) }, (error) => { if (error.message) { alert(JSON.stringify(error)) } }) } render() { // Loading Screen if (this.state.loading) { return <LoadingScreen /> } // Login Screen if (!this.state.loggedIn) { return <LoginScreen /> } // Board return ( <main> <Route path="/" component={AccountButton} /> <Route exact path="/" component={LessonList} /> <Route exact path="/lessons/:id" component={Lesson} /> <Route exact path="/lessons/:id/:lessonId/" component={Lesson} /> <Route exact path="/lessons/:id/:lessonId/:lessonMode" component={Lesson} /> </main> ); } }
JavaScript
class Interaction { constructor() { this.bindShortcuts(); } /** * This function binds keyboard shortcuts. */ bindShortcuts() { document.onkeypress = function(e) { // Ignore if user is editing code e = e || window.event; if ($("#ProgramContent").is(":focus")) return; var charCode = typeof e.which == "number" ? e.which : e.keyCode; if (charCode) { switch (charCode) { // Q case 113: $(".chosenItem:nth-child(1)").click(); break; // W case 119: $(".chosenItem:nth-child(2)").click(); break; // E case 101: $(".chosenItem:nth-child(3)").click(); break; // R case 114: $(".chosenItem:nth-child(4)").click(); break; // A case 97: previousQuestion(); break; // S case 115: nextQuestion(); break; // T case 116: client.runProgram(); break; // G which is to-bottom action in vim case 71: window.scrollTo(0, document.body.scrollHeight); break; // gg is to-top action in vim. We recognize it by once. case 103: window.scrollTo(0, 0); default: console.log(charCode); } } }; } }
JavaScript
class Display { constructor() { this.clearPageLimits(); this.toggleEditMode(); this.appendStyles(); } toggleDarkMode() { $("html").attr( "ctas-darkmode", $("html").attr("ctas-darkmode") == "false" ? "true" : "false" ); } /** * To unlock most of features like copying and selecting on page. */ clearPageLimits() { var el = document.body; var listOfEvents = []; var attributes = [].slice.call(el.attributes); for (var i = 0; i < attributes.length; i++) { var att = attributes[i].name; if (att.indexOf("on") === 0) { var eventHandlers = {}; eventHandlers.attribute = attributes[i].name; eventHandlers.value = attributes[i].value; listOfEvents.push(eventHandlers); el.attributes.removeNamedItem(att); } } } /** * To make the contents in showcase can be edited. */ toggleEditMode() { document.getElementById("ProgramContent").designMode = "on"; document.getElementById("ProgramContent").contentEditable = "true"; } /** * This function will append necessary styles which CTAS-Client depends on.. */ appendStyles() { $(".page").append( '<style>\ .glLineNumber {\ user-select: none !important;\ } \ /** Setting Panel **/\ #ctas-inject[ctas-panel-expanded=false] > .ctas-setting-panel {\ display: none;\ }\ .ctas-href-action {\ color: rgba(233, 39, 100, 1.000) !important;\ border: solid rgba(25,25,25, .1) 1px;\ border-radius: 3px;\ padding: .6vmin 1.5vmin !important;\ background: rgba(255,255,255,.5) !important;\ }\ .ctas-href-action:hover {\ opacity: .7 !important;\ }\ tr > :first-child > div > div {\ position: fixed;\ }\ #ctas-msg {\ display: flex;\ flex-flow: row;\ align-items: baseline;\ }\ #ctas-msg :nth-child(3) {\ margin-left: auto;\ }\ #ctas-inject { \ background: rgba(0,0,0,.04);\ border-radius: 6px;\ margin: 2vmin 0;\ box-shadow: 0 3px 1px -2px rgba(0,0,0,.2), 0 2px 2px 0 rgba(0,0,0,.14), 0 1px 5px 0 rgba(0,0,0,.12);\ } \ #ctas-inject > * {\ padding: 1vmin 2vmin;\ color: #666666;\ }\ #ctas-inject > :last-child {\ background: rgba(0,0,0, .1);\ margin-top: 0px;\ padding-top: .5vmin;\ border-radius: 0 0 6px 6px;\ padding-bottom: .5vmin;\ color: #444444;\ }\ #ctas-inject > :not(:last-child) {\ padding-bottom: 0;\ margin-bottom: 1vmin;\ }\ td:last-child:after { \ content: "© Dalvik Shen 2018 | CTAS-Debugger v1.2.41";\ opacity: .3;font-size: .8em;\ }\ /** Dark Mode **/\ html[ctas-darkmode=true] {\ filter: invert(1);\ background-color: #000;\ }\ @keyframes tip {\ 0% {\ opacity: 1;\ }\ 25% {\ opacity: 0;\ }\ 50% {\ opacity: 1;\ font-size: 1.2em;\ }\ 75% {\ opacity: 0;\ }\ 100% {\ opacity: 1;\ }\ }\ </style>' ); } // UI Features printError(message) { this.printMessage("×", message, "重试", "connect"); } printMessage(icon, message, action = false, func = "") { $("#ctas-msg").text( icon + " " + message + " 💀已做:" + client.getPrecticeDone() + "题" ); $("#ctas-msg2").text(""); if (client.isAlive) $("#ctas-msg").append( '&nbsp;&nbsp;&nbsp;<a class="ctas-href-action" onclick="client.disconnect()" href="javascript:;">∥ 暂停</a>' ); if (action) { $("#ctas-msg").append( `&nbsp;&nbsp;<a class=\"ctas-href-action\" onclick=\"client.${func}()\" href=\"javascript:;\">${action}</a>` ); } $("#ctas-msg").append( `&nbsp;&nbsp;<a class=\"ctas-href-action\" href=\"javascript:display.toggleSetPanel();\">设置</a>` ); } toggleSetPanel() { $("#ctas-inject").attr( "ctas-panel-expanded", $("#ctas-inject").attr("ctas-panel-expanded") == "true" ? "false" : "true" ); } }
JavaScript
class ChangedPage extends Page { question = 'Add files'; /** * Constructor * Initializes this page's subclass * * @constructor * @param {object} props - Properties to initialize the class with */ constructor (props) { super(props); this.menu = new VerticalMenu({ canUnselect: true, acceptsMany: true, stdin: this.props.stdin, stdout: this.props.stdout, app: this.props.app, }); this.prompt = new Prompt({ stdin: this.props.stdin, stdout: this.props.stdout, }); this.pipeline = this.createPipeline(); } /** * Get Initial State * Initializes this component's state * * @method * @public * @returns {object} Initial state properties */ getInitialState () { return { files: this.getFiles(this.getGlob()), }; } /** * Create Options From * Takes our selected files and builds a menu options array * * @method * @public * @param {array} files - Array of filenames to make into options * @returns {array} Array of menu options */ createOptionsFrom (files) { let selectedFiles = this.select('files'), basedir = this.getBasedir(); return files.map((filename, i) => { return { id: i + 1, label: path.relative(basedir, filename), name: filename, value: filename, isSelected: selectedFiles.indexOf(filename) > -1, }; }) || []; } /** * Get Files * Returns an array of files to select * * @method * @public * @param {string} pattern - Glob pattern to filter against * @returns {array} Array of menu options */ getFiles (pattern) { let basedir = this.getBasedir(), output = execSync('git diff --name-only'), files = output.toString().split('\n'); if (!Array.isArray(pattern)) pattern = [pattern]; if (!files.length) return []; return files.map((filename) => { return path.resolve(filename); }) .filter((filename) => { return minimatch(filename, pattern) && filename.indexOf(basedir) > -1; }); } /** * Route * Routes the actions from the pipeline to navigation or error events. * * @param {stream} stream - Writable stream at the end of the pipeline * @param {object} action - Final action passed to router */ route (stream, action) { switch (action.type) { case 'navigate': switch (action.data) { case 'blank': stream.end(); this.navigate('index'); break; case 'all': this.navigate('index'); break; } break; case 'done': this.reprompt(); break; case 'error': this.displayError(action.data); break; } } /** * Show Prompt * Beckons the prompt * * @method * @public * @returns {stream} The resulting writable dispatcher stream. */ showPrompt () { if (this.menu.options().length === 0) { this.props.stdout.write(colors.bold.red('No files have been changed since last git commit.\n')); return this.navigate('index'); } return this.prompt.beckon(this.question) .pipe(this.pipeline) .pipe(new Dispatcher(this.route)); } /** * Workflow * Returns the steps in the pipeline to send to labeled stream splicer. * * @method * @public * @returns {object} named steps in the pipeline */ workflow () { return { query: new QueriesTransform(), menu: new MenuTransform({ menu: this.menu, }), dispatch: new DispatchTransform({ store: this.props.store, }), }; } renderMenu () { this.menu.setOptions(this.createOptionsFrom(this.state.files)); return this.menu.render(); } renderPrompt () { return this.showPrompt; } }
JavaScript
class Toggle extends PureComponent { static propTypes = { value: PropTypes.bool.isRequired, onChange: PropTypes.func, className: PropTypes.string, label: PropTypes.node, style: PropTypes.object, isEnabled: PropTypes.bool }; static defaultProps = { className: '', value: true, style: {}, isEnabled: true, onChange: () => {} }; state = { hasFocus: false, isHovered: false }; _onMouseEnter = () => this.setState({isHovered: true}); _onMouseLeave = () => this.setState({isHovered: false}); _onFocus = () => this.setState({hasFocus: true}); _onBlur = () => this.setState({hasFocus: false}); _onKeyDown = evt => { if (evt.keyCode === 32) { // space this.props.onChange(!this.props.value); } }; _onClick = () => { this.props.onChange(!this.props.value); }; render() { const {theme, className, style, value, label, isEnabled} = this.props; const {knobSize = theme.controlSize} = style; const styleProps = { theme, knobSize, value, isHovered: this.state.isHovered, hasFocus: this.state.hasFocus, isEnabled }; return ( <WrapperComponent className={className} onMouseEnter={this._onMouseEnter} onMouseLeave={this._onMouseLeave} onClick={this._onClick} userStyle={style.wrapper} {...styleProps} > {label} <ToggleComponent userStyle={style.toggle} {...styleProps} tabIndex={isEnabled ? 0 : -1} onKeyDown={this._onKeyDown} onFocus={this._onFocus} onBlur={this._onBlur} > <ToggleTrack userStyle={style.track} {...styleProps} /> <ToggleKnob userStyle={style.knob} {...styleProps} /> </ToggleComponent> </WrapperComponent> ); } }
JavaScript
class CockpitWorkingTimesSchema extends Schema { /** * Creates the schema in the database * * @return {void} */ up() { this.create('cockpit_working_times', (table) => { table.increments(); table.timestamps(); table.integer('cockpit_time_type_id').unsigned().notNullable() .references('id') .inTable('cockpit_time_types'); table.integer('cockpit_work_type_id').unsigned().notNullable() .references('id') .inTable('cockpit_work_types'); table.integer('cockpit_users_weekly_working_time_id').unsigned().notNullable(); table.integer('value').notNullable(); table.foreign('cockpit_users_weekly_working_time_id', 'cwt_cuwwt_id_foreign') .references('id').inTable('cockpit_users_weekly_working_times'); }); } /** * Drops the schema in the database * * @return {void} */ down() { this.drop('cockpit_working_times'); } }
JavaScript
class ConfigExpandRestServer { /** * Create a new webserver. */ constructor() { load('jstests/libs/python.js'); this.python = getPython3Binary(); print("Using python interpreter: " + this.python); this.web_server_py = "jstests/noPassthrough/libs/configExpand/rest_server.py"; this.pid = undefined; this.port = undefined; } /** * Get the Port. * * @return {number} port number of http server */ getPort() { return this.port; } /** * Get the URL. * * @return {string} url of http server */ getURL() { return "http://localhost:" + this.port; } /** * Construct a string reflection URL. * * @param {string} string to be reflected * @param {object} Options, any combination of: * { * sleep: int, // seconds to sleep during request * } */ getStringReflectionURL(str, options = {}) { let url = this.getURL() + '/reflect/string?string=' + encodeURI(str); if (options.sleep !== undefined) { url += '&sleep=' + encodeURI(options.sleep); } return url; } /** * Start the Mock HTTP Server. */ start() { this.port = allocatePort(); print("Mock Web server is listening on port: " + this.port); const args = [this.python, "-u", this.web_server_py, "--port=" + this.port]; this.pid = _startMongoProgram({args: args}); assert(checkProgram(this.pid)); // Wait for the web server to start assert.soon(function() { return rawMongoProgramOutput().search("Mock Web Server Listening") !== -1; }); print("Mock HTTP Server sucessfully started."); } /** * Stop the Mock HTTP Server. */ stop() { stopMongoProgramByPid(this.pid); } }
JavaScript
class PreviewMarkerContainer { constructor(editor) { this.reqMapping = new Map(); this.editor = editor; //used to unsubscribe from subs when being destroyed this.subscriptions = new CompositeDisposable(); this.editor.onDidDestroy(() => { }) this.rangeReqMapping = []; } addPreviewMarker(request, marker) { this.reqMapping.set(marker, request); this.showMarkerInEditor(marker); // check for changes, e.g. marker invalidated const sub = marker.onDidChange(() => { if(!marker.isValid()) { this.reqMapping.delete(marker); // delete marker sub.dispose(); // get rid of subscription } }) } isCursorInMarker(cursorPos) { for([req, marker] of requests) { if(marker.getBufferRange().containsPoint(cursorPos)) { return marker; } } return false; } showMarkerInEditor(marker) { this.editor.decorateMarker(marker, {type: 'highlight', class: "hl"}); } refreshMarkers(editor) { this.editor = editor; console.log('markers', this.editor.getMarkers()); Object.keys(this.reqMapping).forEach((marker) => { this.showMarkerInEditor(marker); }) } serialize() { const arr = []; //create array of objects containing request and range of marker this.reqMapping.forEach((req, marker) => { arr.push({bufferRange: marker.getBufferRange().serialize(), request: req}); }); return arr; } deserialize(state) { state.forEach((obj) => { const marker = this.editor.markBufferRange(obj.bufferRange); this.addPreviewMarker(obj.request, marker); }) } }
JavaScript
class Transfer extends BaseModel { constructor (args) { super(args, schemas.TransferSchema) } }
JavaScript
class MetricSpecification { /** * Create a MetricSpecification. * @member {string} [name] * @member {string} [displayName] * @member {string} [displayDescription] * @member {string} [unit] * @member {string} [aggregationType] * @member {boolean} [supportsInstanceLevelAggregation] * @member {boolean} [enableRegionalMdmAccount] * @member {string} [sourceMdmAccount] * @member {string} [sourceMdmNamespace] * @member {string} [metricFilterPattern] * @member {boolean} [fillGapWithZero] * @member {boolean} [isInternal] * @member {array} [dimensions] * @member {string} [category] * @member {array} [availabilities] */ constructor() { } /** * Defines the metadata of MetricSpecification * * @returns {object} metadata of MetricSpecification * */ mapper() { return { required: false, serializedName: 'MetricSpecification', type: { name: 'Composite', className: 'MetricSpecification', modelProperties: { name: { required: false, serializedName: 'name', type: { name: 'String' } }, displayName: { required: false, serializedName: 'displayName', type: { name: 'String' } }, displayDescription: { required: false, serializedName: 'displayDescription', type: { name: 'String' } }, unit: { required: false, serializedName: 'unit', type: { name: 'String' } }, aggregationType: { required: false, serializedName: 'aggregationType', type: { name: 'String' } }, supportsInstanceLevelAggregation: { required: false, serializedName: 'supportsInstanceLevelAggregation', type: { name: 'Boolean' } }, enableRegionalMdmAccount: { required: false, serializedName: 'enableRegionalMdmAccount', type: { name: 'Boolean' } }, sourceMdmAccount: { required: false, serializedName: 'sourceMdmAccount', type: { name: 'String' } }, sourceMdmNamespace: { required: false, serializedName: 'sourceMdmNamespace', type: { name: 'String' } }, metricFilterPattern: { required: false, serializedName: 'metricFilterPattern', type: { name: 'String' } }, fillGapWithZero: { required: false, serializedName: 'fillGapWithZero', type: { name: 'Boolean' } }, isInternal: { required: false, serializedName: 'isInternal', type: { name: 'Boolean' } }, dimensions: { required: false, serializedName: 'dimensions', type: { name: 'Sequence', element: { required: false, serializedName: 'DimensionElementType', type: { name: 'Composite', className: 'Dimension' } } } }, category: { required: false, serializedName: 'category', type: { name: 'String' } }, availabilities: { required: false, serializedName: 'availabilities', type: { name: 'Sequence', element: { required: false, serializedName: 'MetricAvailabilityElementType', type: { name: 'Composite', className: 'MetricAvailability' } } } } } } }; } }
JavaScript
class ApiError{ /** * Create a ApiError * @param {Error} error - the base error throwed by axios * @param {string} url - the url of the Modzy Api * @param {number} code - http error code * @param {string} message - error message */ constructor(error=null, url="", code=500, message="Unexpected"){ this.error = error !== null ? error.toJSON() : message; this.url = error !== null ? this.error.config.url : url; this.code = error !== null ? ( error.response?.data ? error.response.data.statusCode : code ) : code; this.message = error !== null ? ( error.response?.data ? error.response.data.message : this.error.message ) : message; } /** * Convert this error to string * @return {string} The string representation of this object */ toString(){ return `${this.code} :: ${this.message} :: ${this.url}`; } }
JavaScript
class TemplatesPathResolver extends ConfigJSONHandler { /** * Resolves the templates paths if they are not absolute. * * @param {Array} templates The templates array from the configuration JSON whose * template paths shall be updated. * @param {String} basePath The base path of this configuration that will be * used to resolve the relative paths. */ _resolveTemplatesPaths({ templates, basePath }) { if (templates) { for (const category of Object.values(templates)) { for (const [templateName, templatePath] of Object.entries(category)) { if (!templatePath.startsWith('/')) { category[templateName] = path.resolve(basePath, templatePath); } } } } } handle(json) { this._resolveTemplatesPaths(json); } }
JavaScript
class Editing { // create an annotation for the current selection using the given data annotate (tx, annotation) { const sel = tx.selection const schema = tx.getSchema() const AnnotationClass = schema.getNodeClass(annotation.type) if (!AnnotationClass) throw new Error('Unknown annotation type', annotation) const start = sel.start const end = sel.end const containerPath = sel.containerPath const nodeData = { start, end, containerPath } // TODO: we need to generalize how node category can be derived statically /* istanbul ignore else */ if (sel.isPropertySelection()) { if (!AnnotationClass.isAnnotation()) { throw new Error('Annotation can not be created for a selection.') } } else if (sel.isContainerSelection()) { if (AnnotationClass.isPropertyAnnotation()) { console.warn('NOT SUPPORTED YET: creating property annotations for a non collapsed container selection.') } } Object.assign(nodeData, annotation) return tx.create(nodeData) } break (tx) { const sel = tx.selection if (sel.isNodeSelection()) { const containerPath = sel.containerPath const nodeId = sel.getNodeId() const nodePos = getContainerPosition(tx, containerPath, nodeId) const textNode = this.createTextNode(tx, containerPath) if (sel.isBefore()) { insertAt(tx, containerPath, nodePos, textNode.id) // leave selection as is } else { insertAt(tx, containerPath, nodePos + 1, textNode.id) setCursor(tx, textNode, containerPath, 'before') } } else if (sel.isCustomSelection()) { // TODO: what to do with custom selections? } else if (sel.isCollapsed() || sel.isPropertySelection()) { const containerPath = sel.containerPath if (!sel.isCollapsed()) { // delete the selection this._deletePropertySelection(tx, sel) tx.setSelection(sel.collapse('left')) } // then break the node if (containerPath) { const nodeId = sel.start.path[0] const node = tx.get(nodeId) this._breakNode(tx, node, sel.start, containerPath) } } else if (sel.isContainerSelection()) { const start = sel.start const containerPath = sel.containerPath const startNodeId = start.path[0] const nodePos = getContainerPosition(tx, containerPath, startNodeId) this._deleteContainerSelection(tx, sel, { noMerge: true }) setCursor(tx, getNextNode(tx, containerPath, nodePos), containerPath, 'before') } } createTextNode (tx, containerPath, text) { // eslint-disable-line no-unused-vars const prop = tx.getProperty(containerPath) if (!prop.defaultTextType) { throw new Error('Container properties must have a "defaultTextType" defined in the schema') } return tx.create({ type: prop.defaultTextType, content: text }) } createListNode (tx, containerPath, params = {}) { // eslint-disable-line no-unused-vars // Note: override this create a different node type // according to the context return tx.create({ type: 'list', items: [], listType: params.listType || 'bullet' }) } delete (tx, direction) { const sel = tx.selection // special implementation for node selections: // either delete the node (replacing with an empty text node) // or just move the cursor /* istanbul ignore else */ if (sel.isNodeSelection()) { this._deleteNodeSelection(tx, sel, direction) // TODO: what to do with custom selections? } else if (sel.isCustomSelection()) { // if the selection is collapsed this is the classical one-character deletion // either backwards (backspace) or forward (delete) } else if (sel.isCollapsed()) { // Deletion of a single character leads to a merge // if cursor is at a text boundary (TextNode, ListItem) // and direction is towards that boundary const path = sel.start.path const nodeId = path[0] const containerPath = sel.containerPath const text = tx.get(path) const offset = sel.start.offset const needsMerge = (containerPath && ( (offset === 0 && direction === 'left') || (offset === text.length && direction === 'right') )) if (needsMerge) { // ATTENTION: deviation from standard implementation // for list items: Word and GDoc toggle a list item // when doing a BACKSPACE at the first position // IMO this is not 'consistent' because it is not the // inverse of 'break' // We will 'toggle' only if the cursor is on the first position // of the first item const root = getContainerRoot(tx, containerPath, nodeId) if (root.isList() && offset === 0 && direction === 'left') { return this.toggleList(tx) } else { this._merge(tx, root, sel.start, direction, containerPath) } } else { // if we are not in a merge scenario, we stop at the boundaries if ((offset === 0 && direction === 'left') || (offset === text.length && direction === 'right')) { return } const startOffset = (direction === 'left') ? offset - 1 : offset const endOffset = startOffset + 1 const start = { path: path, offset: startOffset } const end = { path: path, offset: endOffset } // ATTENTION: be careful not to corrupt suggorate pairs // i.e. if deleting to the left and we see a low-suggorate character // then we have to delete two chars // and if deleting to the right and we see a hight-suggorate character // we should also delete the lower one const charCode = text.charCodeAt(startOffset) // is character a low-suggorate? if (_isLowSurrogate(charCode)) { const nextCharCode = text.charCodeAt(endOffset) if (_isHighSurrogate(nextCharCode)) { end.offset++ } } else if (_isHighSurrogate(charCode)) { start.offset-- } deleteTextRange(tx, start, end) tx.setSelection({ type: 'property', path: path, startOffset: start.offset, containerPath: sel.containerPath }) } // deleting a range of characters within a text property } else if (sel.isPropertySelection()) { deleteTextRange(tx, sel.start, sel.end) tx.setSelection(sel.collapse('left')) // deleting a range within a container (across multiple nodes) } else if (sel.isContainerSelection()) { this._deleteContainerSelection(tx, sel) } else { console.warn('Unsupported case: tx.delete(%)', direction, sel) } } _deleteNodeSelection (tx, sel, direction) { const nodeId = sel.getNodeId() const containerPath = sel.containerPath const nodePos = getContainerPosition(tx, containerPath, nodeId) if (sel.isFull() || (sel.isBefore() && direction === 'right') || (sel.isAfter() && direction === 'left')) { // replace the node with default text node removeAt(tx, containerPath, nodePos) deepDeleteNode(tx, tx.get(nodeId)) const newNode = this.createTextNode(tx, sel.containerPath) insertAt(tx, containerPath, nodePos, newNode.id) tx.setSelection({ type: 'property', path: newNode.getPath(), startOffset: 0, containerPath }) } else { /* istanbul ignore else */ if (sel.isBefore() && direction === 'left') { if (nodePos > 0) { const previous = getPreviousNode(tx, containerPath, nodePos) if (previous.isText()) { tx.setSelection({ type: 'property', path: previous.getPath(), startOffset: previous.getLength() }) this.delete(tx, direction) } else { tx.setSelection({ type: 'node', nodeId: previous.id, containerPath }) } } else { // nothing to do } } else if (sel.isAfter() && direction === 'right') { const nodeIds = tx.get(containerPath) if (nodePos < nodeIds.length - 1) { const next = getNextNode(tx, containerPath, nodePos) if (next.isText()) { tx.setSelection({ type: 'property', path: next.getPath(), startOffset: 0 }) this.delete(tx, direction) } else { tx.setSelection({ type: 'node', nodeId: next.id, containerPath }) } } else { // nothing to do } } else { console.warn('Unsupported case: delete(%s)', direction, sel) } } } _deletePropertySelection (tx, sel) { const path = sel.start.path const start = sel.start.offset const end = sel.end.offset tx.update(path, { type: 'delete', start: start, end: end }) annotationHelpers.deletedText(tx, path, start, end) } // deletes all inner nodes and 'truncates' start and end node _deleteContainerSelection (tx, sel, options = {}) { const containerPath = sel.containerPath const start = sel.start const end = sel.end const startId = start.getNodeId() const endId = end.getNodeId() const startPos = getContainerPosition(tx, containerPath, startId) const endPos = getContainerPosition(tx, containerPath, endId) // special case: selection within one node if (startPos === endPos) { // ATTENTION: we need the root node here e.g. the list, not the list-item // OUCH: how we will we do it const node = getContainerRoot(tx, containerPath, startId) /* istanbul ignore else */ if (node.isText()) { deleteTextRange(tx, start, end) } else if (node.isList()) { deleteListRange(tx, node, start, end) } else { throw new Error('Not supported yet.') } tx.setSelection(sel.collapse('left')) return } // TODO: document the algorithm const firstNodeId = start.getNodeId() const lastNodeId = end.getNodeId() const firstNode = tx.get(start.getNodeId()) const lastNode = tx.get(end.getNodeId()) const firstEntirelySelected = isEntirelySelected(tx, firstNode, start, null) const lastEntirelySelected = isEntirelySelected(tx, lastNode, null, end) // delete or truncate last node if (lastEntirelySelected) { removeAt(tx, containerPath, endPos) deepDeleteNode(tx, lastNode) } else { // ATTENTION: we need the root node here e.g. the list, not the list-item const node = getContainerRoot(tx, containerPath, lastNodeId) /* istanbul ignore else */ if (node.isText()) { deleteTextRange(tx, null, end) } else if (node.isList()) { deleteListRange(tx, node, null, end) } else { // IsolatedNodes can not be selected partially } } // delete inner nodes for (let i = endPos - 1; i > startPos; i--) { const nodeId = removeAt(tx, containerPath, i) deepDeleteNode(tx, tx.get(nodeId)) } // delete or truncate the first node if (firstEntirelySelected) { removeAt(tx, containerPath, startPos) deepDeleteNode(tx, firstNode) } else { // ATTENTION: we need the root node here e.g. the list, not the list-item const node = getContainerRoot(tx, containerPath, firstNodeId) /* istanbul ignore else */ if (node.isText()) { deleteTextRange(tx, start, null) } else if (node.isList()) { deleteListRange(tx, node, start, null) } else { // IsolatedNodes can not be selected partially } } // insert a new TextNode if all has been deleted if (firstEntirelySelected && lastEntirelySelected) { // insert a new paragraph const textNode = this.createTextNode(tx, containerPath) insertAt(tx, containerPath, startPos, textNode.id) tx.setSelection({ type: 'property', path: textNode.getPath(), startOffset: 0, containerPath: containerPath }) } else if (!firstEntirelySelected && !lastEntirelySelected) { if (!options.noMerge) { const firstNodeRoot = getContainerRoot(tx, containerPath, firstNode.id) this._merge(tx, firstNodeRoot, sel.start, 'right', containerPath) } tx.setSelection(sel.collapse('left')) } else if (firstEntirelySelected) { setCursor(tx, lastNode, containerPath, 'before') } else { setCursor(tx, firstNode, containerPath, 'after') } } insertInlineNode (tx, nodeData) { let sel = tx.selection const text = '\uFEFF' this.insertText(tx, text) sel = tx.selection const endOffset = tx.selection.end.offset const startOffset = endOffset - text.length nodeData = Object.assign({}, nodeData, { start: { path: sel.path, offset: startOffset }, end: { path: sel.path, offset: endOffset } }) return tx.create(nodeData) } insertBlockNode (tx, nodeData) { const sel = tx.selection const containerPath = sel.containerPath // don't create the node if it already exists let blockNode if (!nodeData._isNode || !tx.get(nodeData.id)) { blockNode = tx.create(nodeData) } else { blockNode = tx.get(nodeData.id) } /* istanbul ignore else */ if (sel.isNodeSelection()) { const nodeId = sel.getNodeId() const nodePos = getContainerPosition(tx, containerPath, nodeId) // insert before if (sel.isBefore()) { insertAt(tx, containerPath, nodePos, blockNode.id) // insert after } else if (sel.isAfter()) { insertAt(tx, containerPath, nodePos + 1, blockNode.id) tx.setSelection({ type: 'node', containerPath, nodeId: blockNode.id, mode: 'after' }) } else { removeAt(tx, containerPath, nodePos) deepDeleteNode(tx, tx.get(nodeId)) insertAt(tx, containerPath, nodePos, blockNode.id) tx.setSelection({ type: 'node', containerPath, nodeId: blockNode.id, mode: 'after' }) } } else if (sel.isPropertySelection()) { /* istanbul ignore next */ if (!containerPath) throw new Error('insertBlockNode can only be used within a container.') if (!sel.isCollapsed()) { this._deletePropertySelection(tx, sel) tx.setSelection(sel.collapse('left')) } const node = tx.get(sel.path[0]) /* istanbul ignore next */ if (!node) throw new Error('Invalid selection.') const nodePos = getContainerPosition(tx, containerPath, node.id) /* istanbul ignore else */ if (node.isText()) { const text = node.getText() // replace node if (text.length === 0) { removeAt(tx, containerPath, nodePos) deepDeleteNode(tx, node) insertAt(tx, containerPath, nodePos, blockNode.id) setCursor(tx, blockNode, containerPath, 'after') // insert before } else if (sel.start.offset === 0) { insertAt(tx, containerPath, nodePos, blockNode.id) // insert after } else if (sel.start.offset === text.length) { insertAt(tx, containerPath, nodePos + 1, blockNode.id) setCursor(tx, blockNode, containerPath, 'before') // break } else { this.break(tx) insertAt(tx, containerPath, nodePos + 1, blockNode.id) setCursor(tx, blockNode, containerPath, 'after') } } else { console.error('Not supported: insertBlockNode() on a custom node') } } else if (sel.isContainerSelection()) { if (sel.isCollapsed()) { const start = sel.start /* istanbul ignore else */ if (start.isPropertyCoordinate()) { tx.setSelection({ type: 'property', path: start.path, startOffset: start.offset, containerPath }) } else if (start.isNodeCoordinate()) { tx.setSelection({ type: 'node', containerPath, nodeId: start.path[0], mode: start.offset === 0 ? 'before' : 'after' }) } else { throw new Error('Unsupported selection for insertBlockNode') } return this.insertBlockNode(tx, blockNode) } else { this.break(tx) return this.insertBlockNode(tx, blockNode) } } return blockNode } insertText (tx, text) { const sel = tx.selection // type over a selected node or insert a paragraph before // or after /* istanbul ignore else */ if (sel.isNodeSelection()) { const containerPath = sel.containerPath const nodeId = sel.getNodeId() const nodePos = getContainerPosition(tx, containerPath, nodeId) const textNode = this.createTextNode(tx, containerPath, text) if (sel.isBefore()) { insertAt(tx, containerPath, nodePos, textNode.id) } else if (sel.isAfter()) { insertAt(tx, containerPath, nodePos + 1, textNode.id) } else { removeAt(tx, containerPath, nodePos) deepDeleteNode(tx, tx.get(nodeId)) insertAt(tx, containerPath, nodePos, textNode.id) } setCursor(tx, textNode, containerPath, 'after') } else if (sel.isCustomSelection()) { // TODO: what to do with custom selections? } else if (sel.isCollapsed() || sel.isPropertySelection()) { // console.log('#### before', sel.toString()) this._insertText(tx, sel, text) // console.log('### setting selection after typing: ', tx.selection.toString()) } else if (sel.isContainerSelection()) { this._deleteContainerSelection(tx, sel) this.insertText(tx, text) } } paste (tx, content) { if (!content) return /* istanbul ignore else */ if (isString(content)) { paste(tx, { text: content }) } else if (content._isDocument) { paste(tx, { doc: content }) } else { throw new Error('Illegal content for paste.') } } /** * Switch text type for a given node. E.g. from `paragraph` to `heading`. * * @param {Object} args object with `selection`, `containerPath` and `data` with new node data * @return {Object} object with updated `selection` * * @example * * ```js * switchTextType(tx, { * selection: bodyEditor.getSelection(), * containerPath: bodyEditor.getContainerPath(), * data: { * type: 'heading', * level: 2 * } * }) * ``` */ switchTextType (tx, data) { const sel = tx.selection /* istanbul ignore next */ if (!sel.isPropertySelection()) { throw new Error('Selection must be a PropertySelection.') } const containerPath = sel.containerPath /* istanbul ignore next */ if (!containerPath) { throw new Error('Selection must be within a container.') } const path = sel.path const nodeId = path[0] const node = tx.get(nodeId) /* istanbul ignore next */ if (!(node.isText())) { throw new Error('Trying to use switchTextType on a non text node.') } const newId = uuid(data.type) // Note: a TextNode is allowed to have its own way to store the plain-text const oldPath = node.getPath() console.assert(oldPath.length === 2, 'Currently we assume that TextNodes store the plain-text on the first level') const textProp = oldPath[1] const newPath = [newId, textProp] // create a new node and transfer annotations const newNodeData = Object.assign({ id: newId, type: data.type, direction: node.direction }, data) newNodeData[textProp] = node.getText() const newNode = tx.create(newNodeData) annotationHelpers.transferAnnotations(tx, path, 0, newPath, 0) // hide and delete the old one, show the new node const pos = getContainerPosition(tx, containerPath, nodeId) removeAt(tx, containerPath, pos) deepDeleteNode(tx, node) insertAt(tx, containerPath, pos, newNode.id) tx.setSelection({ type: 'property', path: newPath, startOffset: sel.start.offset, endOffset: sel.end.offset, containerPath }) return newNode } toggleList (tx, params) { const sel = tx.selection const containerPath = sel.containerPath /* istanbul ignore next */ if (!containerPath) { throw new Error('Selection must be within a container.') } if (sel.isPropertySelection()) { const nodeId = sel.start.path[0] // ATTENTION: we need the root node here e.g. the list, not the list-item const node = getContainerRoot(tx, containerPath, nodeId) const nodePos = node.getPosition() /* istanbul ignore else */ if (node.isText()) { removeAt(tx, containerPath, nodePos) const newList = this.createListNode(tx, containerPath, params) const newItem = newList.createListItem(node.getText()) annotationHelpers.transferAnnotations(tx, node.getPath(), 0, newItem.getPath(), 0) newList.appendItem(newItem) deepDeleteNode(tx, node) insertAt(tx, containerPath, nodePos, newList.id) tx.setSelection({ type: 'property', path: newItem.getPath(), startOffset: sel.start.offset, containerPath }) } else if (node.isList()) { const itemId = sel.start.path[0] const item = tx.get(itemId) const itemPos = node.getItemPosition(item) const newTextNode = this.createTextNode(tx, containerPath, item.getText()) annotationHelpers.transferAnnotations(tx, item.getPath(), 0, newTextNode.getPath(), 0) // take the item out of the list node.removeItemAt(itemPos) if (node.isEmpty()) { removeAt(tx, containerPath, nodePos) deepDeleteNode(tx, node) insertAt(tx, containerPath, nodePos, newTextNode.id) } else if (itemPos === 0) { insertAt(tx, containerPath, nodePos, newTextNode.id) } else if (node.getLength() <= itemPos) { insertAt(tx, containerPath, nodePos + 1, newTextNode.id) } else { // split the const tail = [] const items = node.getItems() const L = items.length for (let i = L - 1; i >= itemPos; i--) { tail.unshift(items[i]) node.removeItemAt(i) } const newList = this.createListNode(tx, containerPath, node) for (let i = 0; i < tail.length; i++) { newList.appendItem(tail[i]) } insertAt(tx, containerPath, nodePos + 1, newTextNode.id) insertAt(tx, containerPath, nodePos + 2, newList.id) } tx.setSelection({ type: 'property', path: newTextNode.getPath(), startOffset: sel.start.offset, containerPath }) } else { // unsupported node type } } else if (sel.isContainerSelection()) { console.error('TODO: support toggleList with ContainerSelection') } } indent (tx) { const sel = tx.selection const containerPath = sel.containerPath if (sel.isPropertySelection()) { const nodeId = sel.start.getNodeId() // ATTENTION: we need the root node here, e.g. the list, not the list items const node = getContainerRoot(tx, containerPath, nodeId) if (node.isList()) { const itemId = sel.start.path[0] const item = tx.get(itemId) const level = item.getLevel() // Note: allowing only 3 levels if (item && level < 3) { item.setLevel(item.level + 1) // a pseudo change to let the list know that something has changed tx.set([node.id, '_itemsChanged'], true) } } } else if (sel.isContainerSelection()) { console.error('TODO: support toggleList with ContainerSelection') } } dedent (tx) { const sel = tx.selection const containerPath = sel.containerPath if (sel.isPropertySelection()) { const nodeId = sel.start.getNodeId() // ATTENTION: we need the root node here, e.g. the list, not the list items const node = getContainerRoot(tx, containerPath, nodeId) if (node.isList()) { const itemId = sel.start.path[0] const item = tx.get(itemId) const level = item.getLevel() if (item) { if (level > 1) { item.setLevel(item.level - 1) // a pseudo change to let the list know that something has changed tx.set([node.id, '_itemsChanged'], true) } // TODO: we could toggle the list item to paragraph // if dedenting on the first level // else { // return this.toggleList(tx) // } } } } else if (sel.isContainerSelection()) { console.error('TODO: support toggleList with ContainerSelection') } } /* <-->: anno |--|: area of change I: <--> |--| : nothing II: |--| <--> : move both by total span+L III: |-<-->-| : delete anno IV: |-<-|-> : move start by diff to start+L, and end by total span+L V: <-|->-| : move end by diff to start+L VI: <-->|--| : noting if !anno.autoExpandRight VII: <-|--|-> : move end by total span+L */ _insertText (tx, sel, text) { const start = sel.start const end = sel.end /* istanbul ignore next */ if (!isArrayEqual(start.path, end.path)) { throw new Error('Unsupported state: range should be on one property') } const path = start.path const startOffset = start.offset const endOffset = end.offset const typeover = !sel.isCollapsed() const L = text.length // delete selected text if (typeover) { tx.update(path, { type: 'delete', start: startOffset, end: endOffset }) } // insert new text tx.update(path, { type: 'insert', start: startOffset, text: text }) // update annotations const annos = tx.getAnnotations(path) annos.forEach(function (anno) { const annoStart = anno.start.offset const annoEnd = anno.end.offset /* istanbul ignore else */ // I anno is before if (annoEnd < startOffset) { // II anno is after } else if (annoStart >= endOffset) { tx.update([anno.id, 'start'], { type: 'shift', value: startOffset - endOffset + L }) tx.update([anno.id, 'end'], { type: 'shift', value: startOffset - endOffset + L }) // III anno is deleted // NOTE: InlineNodes only have a length of one character // so they are always 'covered', and as they can not expand // they are deleted } else if ( (annoStart >= startOffset && annoEnd < endOffset) || (anno.isInlineNode() && annoStart >= startOffset && annoEnd <= endOffset) ) { tx.delete(anno.id) // IV anno.start between and anno.end after } else if (annoStart >= startOffset && annoEnd >= endOffset) { // do not move start if typing over if (annoStart > startOffset || !typeover) { tx.update([anno.id, 'start'], { type: 'shift', value: startOffset - annoStart + L }) } tx.update([anno.id, 'end'], { type: 'shift', value: startOffset - endOffset + L }) // V anno.start before and anno.end between } else if (annoStart < startOffset && annoEnd < endOffset) { // NOTE: here the anno gets expanded (that's the common way) tx.update([anno.id, 'end'], { type: 'shift', value: startOffset - annoEnd + L }) // VI } else if (annoEnd === startOffset && !anno.constructor.autoExpandRight) { // skip // VII anno.start before and anno.end after } else if (annoStart < startOffset && annoEnd >= endOffset) { if (anno.isInlineNode()) { // skip } else { tx.update([anno.id, 'end'], { type: 'shift', value: startOffset - endOffset + L }) } } else { console.warn('TODO: handle annotation update case.') } }) const offset = startOffset + text.length tx.setSelection({ type: 'property', path: start.path, startOffset: offset, containerPath: sel.containerPath, surfaceId: sel.surfaceId }) } _breakNode (tx, node, coor, containerPath) { // ATTENTION: we need the root here, e.g. a list, not the list-item node = getContainerRoot(tx, containerPath, node.id) /* istanbul ignore else */ if (node.isText()) { this._breakTextNode(tx, node, coor, containerPath) } else if (node.isList()) { this._breakListNode(tx, node, coor, containerPath) } else { console.error('FIXME: _breakNode() not supported for type', node.type) } } _breakTextNode (tx, node, coor, containerPath) { const path = coor.path const offset = coor.offset const nodePos = node.getPosition() const text = node.getText() // when breaking at the first position, a new node of the same // type will be inserted. if (offset === 0) { const newNode = tx.create({ type: node.type, content: '' }) // show the new node insertAt(tx, containerPath, nodePos, newNode.id) tx.setSelection({ type: 'property', path: path, startOffset: 0, containerPath }) // otherwise split the text property and create a new paragraph node with trailing text and annotations transferred } else { const textPath = node.getPath() const textProp = textPath[1] const newId = uuid(node.type) const newNodeData = node.toJSON() newNodeData.id = newId newNodeData[textProp] = text.substring(offset) // if at the end insert a default text node no matter in which text node we are if (offset === text.length) { newNodeData.type = tx.getSchema().getDefaultTextType() } const newNode = tx.create(newNodeData) // Now we need to transfer annotations if (offset < text.length) { // transfer annotations which are after offset to the new node annotationHelpers.transferAnnotations(tx, path, offset, newNode.getPath(), 0) // truncate the original property tx.update(path, { type: 'delete', start: offset, end: text.length }) } // show the new node insertAt(tx, containerPath, nodePos + 1, newNode.id) // update the selection tx.setSelection({ type: 'property', path: newNode.getPath(), startOffset: 0, containerPath }) } } _breakListNode (tx, node, coor, containerPath) { const path = coor.path const offset = coor.offset const listItem = tx.get(path[0]) const L = node.length const itemPos = node.getItemPosition(listItem) const text = listItem.getText() const textProp = listItem.getPath()[1] const newItemData = listItem.toJSON() delete newItemData.id if (offset === 0) { // if breaking at an empty list item, then the list is split into two if (!text) { // if it is the first or last item, a default text node is inserted before or after, and the item is removed // if the list has only one element, it is removed const nodePos = node.getPosition() const newTextNode = this.createTextNode(tx, containerPath) // if the list is empty, replace it with a paragraph if (L < 2) { removeAt(tx, containerPath, nodePos) deepDeleteNode(tx, node) insertAt(tx, containerPath, nodePos, newTextNode.id) // if at the first list item, remove the item } else if (itemPos === 0) { node.removeItem(listItem) deepDeleteNode(tx, listItem) insertAt(tx, containerPath, nodePos, newTextNode.id) // if at the last list item, remove the item and append the paragraph } else if (itemPos >= L - 1) { node.removeItem(listItem) deepDeleteNode(tx, listItem) insertAt(tx, containerPath, nodePos + 1, newTextNode.id) // otherwise create a new list } else { const tail = [] const items = node.getItems().slice() for (let i = L - 1; i > itemPos; i--) { tail.unshift(items[i]) node.removeItem(items[i]) } node.removeItem(items[itemPos]) const newList = this.createListNode(tx, containerPath, node) for (let i = 0; i < tail.length; i++) { newList.appendItem(tail[i]) } insertAt(tx, containerPath, nodePos + 1, newTextNode.id) insertAt(tx, containerPath, nodePos + 2, newList.id) } tx.setSelection({ type: 'property', path: newTextNode.getPath(), startOffset: 0 }) // insert a new paragraph above the current one } else { newItemData[textProp] = '' const newItem = tx.create(newItemData) node.insertItemAt(itemPos, newItem) tx.setSelection({ type: 'property', path: listItem.getPath(), startOffset: 0 }) } // otherwise split the text property and create a new paragraph node with trailing text and annotations transferred } else { newItemData[textProp] = text.substring(offset) const newItem = tx.create(newItemData) // Now we need to transfer annotations if (offset < text.length) { // transfer annotations which are after offset to the new node annotationHelpers.transferAnnotations(tx, path, offset, newItem.getPath(), 0) // truncate the original property tx.update(path, { type: 'delete', start: offset, end: text.length }) } node.insertItemAt(itemPos + 1, newItem) tx.setSelection({ type: 'property', path: newItem.getPath(), startOffset: 0 }) } } _merge (tx, node, coor, direction, containerPath) { // detect cases where list items get merged // within a single list node if (node.isList()) { const list = node const itemId = coor.path[0] const item = tx.get(itemId) let itemPos = list.getItemPosition(item) const withinListNode = ( (direction === 'left' && itemPos > 0) || (direction === 'right' && itemPos < list.items.length - 1) ) if (withinListNode) { itemPos = (direction === 'left') ? itemPos - 1 : itemPos const target = list.getItemAt(itemPos) const targetLength = target.getLength() mergeListItems(tx, list.id, itemPos) tx.setSelection({ type: 'property', path: target.getPath(), startOffset: targetLength, containerPath }) return } } // in all other cases merge is done across node boundaries const nodeIds = tx.get(containerPath) const nodePos = node.getPosition() if (direction === 'left' && nodePos > 0) { this._mergeNodes(tx, containerPath, nodePos - 1, direction) } else if (direction === 'right' && nodePos < nodeIds.length - 1) { this._mergeNodes(tx, containerPath, nodePos, direction) } } _mergeNodes (tx, containerPath, pos, direction) { const nodeIds = tx.get(containerPath) const first = tx.get(nodeIds[pos]) let secondPos = pos + 1 const second = tx.get(nodeIds[secondPos]) if (first.isText()) { // Simplification for empty nodes if (first.isEmpty()) { removeAt(tx, containerPath, pos) secondPos-- deepDeleteNode(tx, first) // TODO: need to clear where to handle // selections ... probably better not to do it here setCursor(tx, second, containerPath, 'before') return } const target = first const targetPath = target.getPath() const targetLength = target.getLength() if (second.isText()) { const source = second const sourcePath = source.getPath() removeAt(tx, containerPath, secondPos) // append the text tx.update(targetPath, { type: 'insert', start: targetLength, text: source.getText() }) // transfer annotations annotationHelpers.transferAnnotations(tx, sourcePath, 0, targetPath, targetLength) deepDeleteNode(tx, source) tx.setSelection({ type: 'property', path: targetPath, startOffset: targetLength, containerPath }) } else if (second.isList()) { const list = second if (!second.isEmpty()) { const source = list.getFirstItem() const sourcePath = source.getPath() // remove merged item from list list.removeItemAt(0) // append the text tx.update(targetPath, { type: 'insert', start: targetLength, text: source.getText() }) // transfer annotations annotationHelpers.transferAnnotations(tx, sourcePath, 0, targetPath, targetLength) // delete item and prune empty list deepDeleteNode(tx, source) } if (list.isEmpty()) { removeAt(tx, containerPath, secondPos) deepDeleteNode(tx, list) } tx.setSelection({ type: 'property', path: targetPath, startOffset: targetLength, containerPath }) } else { selectNode(tx, direction === 'left' ? first.id : second.id, containerPath) } } else if (first.isList()) { if (second.isText()) { const target = first.getLastItem() const targetPath = target.getPath() const targetLength = target.getLength() const third = (nodeIds.length > pos + 2) ? tx.get(nodeIds[pos + 2]) : null if (second.getLength() === 0) { removeAt(tx, containerPath, secondPos) deepDeleteNode(tx, second) } else { const source = second const sourcePath = source.getPath() removeAt(tx, containerPath, secondPos) tx.update(targetPath, { type: 'insert', start: targetLength, text: source.getText() }) annotationHelpers.transferAnnotations(tx, sourcePath, 0, targetPath, targetLength) deepDeleteNode(tx, source) } // merge to lists if they were split by a paragraph if (third && third.type === first.type) { this._mergeTwoLists(tx, containerPath, first, third) } tx.setSelection({ type: 'property', path: target.getPath(), startOffset: targetLength, containerPath }) } else if (second.isList()) { /* istanbul ignore next */ if (direction !== 'right') { // ATTENTION: merging two lists by using BACKSPACE is not possible, // as BACKSPACE will first turn the list into a paragraph throw new Error('Illegal state') } const item = first.getLastItem() this._mergeTwoLists(tx, containerPath, first, second) tx.setSelection({ type: 'property', path: item.getPath(), startOffset: item.getLength(), containerPath }) } else { selectNode(tx, direction === 'left' ? first.id : second.id, containerPath) } } else { if (second.isText() && second.isEmpty()) { removeAt(tx, containerPath, secondPos) deepDeleteNode(tx, second) setCursor(tx, first, containerPath, 'after') } else { selectNode(tx, direction === 'left' ? first.id : second.id, containerPath) } } } _mergeTwoLists (tx, containerPath, first, second) { const secondPos = second.getPosition() removeAt(tx, containerPath, secondPos) const secondItems = second.getItems().slice() for (let i = 0; i < secondItems.length; i++) { second.removeItemAt(0) first.appendItem(secondItems[i]) } deepDeleteNode(tx, second) } }
JavaScript
class List { _initList({ element, attribute, readOnly = false }) { this._element = element; this._attribute = attribute; this._attributeRegistryEntry = element.constructor.attributeRegistry.get(attribute); this._readOnly = readOnly; this._list = []; this._version = -1; } get _needsResync() { return this._version < this._element._version; } _synchronize() { if (!this._needsResync) { return; } let value = []; if (this._element.hasAttributeNS(null, this._attribute)) { value = this._attributeRegistryEntry.getValue(this._element.getAttributeNS(null, this._attribute)); } if (value.length === 0 && this._attributeRegistryEntry.initialValue !== undefined) { value = this._attributeRegistryEntry.getValue(this._attributeRegistryEntry.initialValue); } // TODO: support non-DOMString lists. this._list = value; this._version = this._element._version; } _reserialize() { const elements = this._list; this._element.setAttributeNS(null, this._attribute, this._attributeRegistryEntry.serialize(elements)); // Prevent ping-ponging back and forth between _reserialize() and _synchronize(). this._version = this._element._version; } [idlUtils.supportsPropertyIndex](index) { this._synchronize(); return index >= 0 && index < this.length; } get [idlUtils.supportedPropertyIndices]() { this._synchronize(); return this._list.keys(); } get length() { this._synchronize(); return this._list.length; } get numberOfItems() { this._synchronize(); return this._list.length; } clear() { this._synchronize(); if (this._readOnly) { throw DOMException.create(this._globalObject, [ "Attempting to modify a read-only list", "NoModificationAllowedError" ]); } for (const item of this._list) { detach(item); } this._list.length = 0; this._reserialize(); } initialize(newItem) { this._synchronize(); if (this._readOnly) { throw DOMException.create(this._globalObject, [ "Attempting to modify a read-only list", "NoModificationAllowedError" ]); } for (const item of this._list) { detach(item); } this._list.length = 0; // TODO: clone non-DOMString list elements. attach(newItem, this); this._list.push(newItem); this._reserialize(); } getItem(index) { this._synchronize(); if (index >= this._list.length) { throw DOMException.create(this._globalObject, [ `The index provided (${index}) is greater than or equal to the maximum bound (${this._list.length}).`, "IndexSizeError" ]); } return this._list[index]; } insertItemBefore(newItem, index) { this._synchronize(); if (this._readOnly) { throw DOMException.create(this._globalObject, [ "Attempting to modify a read-only list", "NoModificationAllowedError" ]); } // TODO: clone non-DOMString list elements. if (index > this._list.length) { index = this._list.length; } this._list.splice(index, 0, newItem); attach(newItem, this); this._reserialize(); return newItem; } replaceItem(newItem, index) { this._synchronize(); if (this._readOnly) { throw DOMException.create(this._globalObject, [ "Attempting to modify a read-only list", "NoModificationAllowedError" ]); } if (index >= this._list.length) { throw DOMException.create(this._globalObject, [ `The index provided (${index}) is greater than or equal to the maximum bound (${this._list.length}).`, "IndexSizeError" ]); } // TODO: clone non-DOMString list elements. detach(this._list[index]); this._list[index] = newItem; attach(newItem, this); this._reserialize(); return newItem; } removeItem(index) { this._synchronize(); if (this._readOnly) { throw DOMException.create(this._globalObject, [ "Attempting to modify a read-only list", "NoModificationAllowedError" ]); } if (index >= this._list.length) { throw DOMException.create(this._globalObject, [ `The index provided (${index}) is greater than or equal to the maximum bound (${this._list.length}).`, "IndexSizeError" ]); } const item = this._list[index]; detach(item); this._list.splice(index, 1); this._reserialize(); return item; } appendItem(newItem) { this._synchronize(); // TODO: clone non-DOMString list elements. this._list.push(newItem); attach(newItem, this); this._reserialize(); return newItem; } [idlUtils.indexedSetNew](index, value) { // Note: this will always throw a IndexSizeError. this.replaceItem(value, index); } [idlUtils.indexedSetExisting](index, value) { this.replaceItem(value, index); } }
JavaScript
class EventGenerator { /** Create an async iteration of events. * @param {Element} element The DOM element to subscribe to an event on. * @param {string} event The name of the event to subscribe to. */ constructor(element, event) { this.running = true; this.element = element; this.event = event; } /** Stop listening for further events. * Sets flag so that next() will return done as true, and resolves and unsubscribes the current event. * This tidies up if the loop is exited early with break or return. * @returns {any} Object with done: true, always. */ return() { this.running = false; // If set resolve the current promise if(this.resolveCurrent) this.resolveCurrent(null); return { done: true }; } /** Return a promise that resolves when the next event fires, or when stop is called. * Called each time for-await-of iterates as long as done is false. * @returns {Promise} Resolves when the next event fires, or when stop is called. */ next() { // Each time this is called we await a promise resolving on the next event return new Promise((r,x) => { if(this.resolveCurrent) x(new Error('Cannot iterate to the next promise while previous is still active.')); // If not running then resolve any current event and return done if(!this.running) return r({ done: true }); // Hold on to the resolution event so we can stop it from outside the loop this.resolveCurrent = e => { // Always stop listening, though once: true will handle this normally this.element.removeEventListener(this.event, this.resolveCurrent); // Resolve the promise r({value: e, done: !this.running }); // This keeps a reference to the expired promise hanging around, so null it once done this.resolveCurrent = null; }; this.element.addEventListener(this.event, this.resolveCurrent, { once: true, passive: true }); }); } /** Iterate the event asynchronously */ [Symbol.asyncIterator]() { return this; } /** Stop listening for further events */ stop() { this.return(); } /** Execute an action each time an event is iterated. * @param {function} action To fire for each element. * @returns {Promise} Resolves once the event has been stopped. */ async each(action) { for await (const e of this) action(e); } /** Map the collection of events * @param {function} transform To translate each element. * @returns Async iterator of mapped items. */ async *map(transform) { for await (const e of this) yield transform(e); } /** Filter the collection of events * @param {function} predicate Determine whether the item should be included. * @returns Async iterator of filtered items. */ async *filter(predicate) { for await (const e of this) if(predicate(e)) yield e; } }
JavaScript
class WordMapper { // Arguments: // logger ({ log(...) }): optional logger constructor( logger ) { settings.load(); if (logger) { logger.log( '. . . . . . . . .' ); log = (...params) => { logger.log( 'WordMapper ', ...params ); }; } } // Arguments: // fixationLines (Array of (Array of Fixation)): only (all) fixations from one array correspond // to a text line // the array is sorted top-to-bottom // textLines (Array of (Array of Word)) // Notes // 1. If rescaling is enabled, then updates fixation.x value and copies the original value to fixation._x // 2, Fixations mapped on a word get property "word" = // {left, top, right, bottom, index=<index_in_line>, id=<index_in_text>, text } // 3. Words with mapped fixations get property "fixations" = (Array of Fixation) map( fixationLines, textLines ) { for (let i = 0; i < fixationLines.length; i += 1) { const fixations = fixationLines[i]; const lineID = fixations[0].line; const textLine = getTextLine( textLines, lineID ); if (textLine !== undefined) { if (settings.rescaleFixationX) { rescaleFixations( fixations, textLine ); } mapFixationsWithinLine( fixations, textLine ); } } } // Arguments: // fixations (Array of Fixation): the list of fixations // words (Array of Word): the Text.words clean( fixations, words ) { if (settings.ignoreTransitions) { removeTransitions( fixations, words ); } } }
JavaScript
class GiftCertificateItem { /** * Constructs a new <code>GiftCertificateItem</code>. * A gift certificate item. * @alias module:models/GiftCertificateItem * @class * @param amount {Number} The certificate item amount. * @param recipientEmail {String} The recipient's email. */ constructor(amount, recipientEmail) { this.amount = amount; this.recipient_email = recipientEmail } /** * Constructs a <code>GiftCertificateItem</code> from a plain JavaScript object, optionally creating a new instance. * Copies all relevant properties from <code>data</code> to <code>obj</code> if supplied or a new instance if not. * @param {Object} data The plain JavaScript object bearing properties of interest. * @param {module:models/GiftCertificateItem} obj Optional instance to populate. * @return {module:models/GiftCertificateItem} The populated <code>GiftCertificateItem</code> instance. */ static constructFromObject(data, obj) { if (data) { obj = obj || new GiftCertificateItem() if (data.hasOwnProperty('amount')) { obj.amount = ApiClient.convertToType(data.amount, 'Number') } if (data.hasOwnProperty('gift_certificate_item_id')) { obj.gift_certificate_item_id = ApiClient.convertToType(data.gift_certificate_item_id, 'String') } if (data.hasOwnProperty('message')) { obj.message = ApiClient.convertToType(data.message, 'String') } if (data.hasOwnProperty('recipient_email')) { obj.recipient_email = ApiClient.convertToType(data.recipient_email, 'String') } if (data.hasOwnProperty('recipient_name')) { obj.recipient_name = ApiClient.convertToType(data.recipient_name, 'String') } if (data.hasOwnProperty('sender_name')) { obj.sender_name = ApiClient.convertToType(data.sender_name, 'String') } if (data.hasOwnProperty('shipment_id')) { obj.shipment_id = ApiClient.convertToType(data.shipment_id, 'String') } } return obj } /** * The certificate item amount. * @member {Number} amount */ amount = undefined; /** * Id used to identify this item * @member {String} gift_certificate_item_id */ gift_certificate_item_id = undefined; /** * The certificate's message. * @member {String} message */ message = undefined; /** * The recipient's email. * @member {String} recipient_email */ recipient_email = undefined; /** * The recipient's name. * @member {String} recipient_name */ recipient_name = undefined; /** * The sender's name. * @member {String} sender_name */ sender_name = undefined; /** * The shipment id. * @member {String} shipment_id */ shipment_id = undefined; }
JavaScript
class Hover extends React.Component{ render(){ return( <Layout> <h1> hover </h1> <AniLink fade to="/" duration={3}> Go to Page 4 </AniLink> </Layout> ) } }
JavaScript
class Container extends React.Component { constructor() { super(); const logger = createLogger({ predicate: (getState, action) => isDebuggingInChrome, collapsed: true, duration: true }); const createAppStore = applyMiddleware(thunk, promiseMiddleware, logger)( createStore ); const store = autoRehydrate()(createAppStore)(reducers); persistStore( store, { storage: AsyncStorage, whitelist: [ "roasts", // deprecated "customBeans", "coffees", "settings", "beans", "user" ] }, () => { this.setState({ loading: false }); } ); if (isDebuggingInChrome) { window.store = store; } this.state = { loading: true, store }; } render() { if (this.state.loading) { return <View />; } return ( <Provider store={this.state.store}> <View style={{ flex: 1 }}> <Boot /> <OnboardNavigator /> </View> </Provider> ); } }
JavaScript
class A extends React.Component{ render(){ const {name,age,time} = this.props return <div><Link href="#test"><a>i am a ---${this.props.router.query.id}---{name}---{age}---{time}</a></Link> <span>这是A页面</span> </div> } }
JavaScript
class App extends Component { render() { // we can use ES6's object destructuring to effectively 'unpack' our props const { counter, actions, children} = this.props; return ( <div className="main-app-container"> <div className="main-app-nav"> <div id="main-app-title">Simple Redux Boilerplate</div> <div> <span><Link to="/">Home</Link></span> <span><Link to="/foo">Foo</Link></span> <span><Link to="/bar">Bar</Link></span> </div> </div> <div> {/* Here's a trick: we pass those props into the children by mapping and cloning the element, followed by passing props in. Notice that those props have been unpacked above! */} {React.Children.map(children, (child) => { return React.cloneElement(child, { counter, actions }); })} </div> <Footer /> </div> ); } }
JavaScript
class Details { constructor(){ this.name = "Unnamed"; this.designers= ""; this.theme = ""; this.minPlayers = ""; this.maxPlayers = ""; this.targetTime = ""; this.difficulty = "3"; this.objective = ""; this.description = ""; this.estimatedCost = ""; } }
JavaScript
class adminController { /** * @description - Get all Users Requests * @static * * @param {object} req - HTTP Request * @param {object} res - HTTP Response * * @memberOf adminController * * @returns {object} response JSON Object */ static getRequests(req, res) { const pool = new Pool({ connectionString, }); const selectQuery = { name: 'get-users-requests', text: 'SELECT * FROM requests ORDER BY id DESC LIMIT 20', }; if (req.query.page !== undefined) { selectQuery.text = 'SELECT * FROM requests ORDER BY id DESC OFFSET $1 LIMIT $2'; selectQuery.values = []; selectQuery.values.push(((req.query.page - 1) * 20)); selectQuery.values.push(20); } pool.query(selectQuery, (err, result) => { res.status(200).send({ success: true, status: 200, total: req.requestCount, data: result.rows, }); pool.end(); }); } /** * @description - Filter All Users Requests * @static * * @param {object} req - HTTP Request * @param {object} res - HTTP Response * * @memberOf adminController * * @returns {object} response JSON Object */ static filterRequests(req, res) { const pool = new Pool({ connectionString, }); const selectQuery = { name: 'filter-requests', text: 'SELECT * FROM requests WHERE title like $1 OR description like $1 ORDER BY id DESC LIMIT 20', values: [`%${req.query.searchText}%`], }; if (req.query.status !== 'All') { selectQuery.text = `SELECT * FROM requests WHERE description like $1 AND status = $2 OR title like $1 AND status = $2 ORDER BY id DESC LIMIT 20`; selectQuery.values.push(req.query.status); } if (req.query.searchText === '') { selectQuery.values[0] = '% %'; } if (req.query.page !== undefined) { selectQuery.text += ` OFFSET $${selectQuery.values.length + 1}`; selectQuery.values.push(((req.query.page - 1) * 20)); } pool.query(selectQuery, (err, result) => { res.status(200).send({ success: true, status: 200, total: result.rows.length, data: result.rows, }); pool.end(); }); } /** * @description - Get a Request * @static * * @param {object} req - HTTP Request * @param {object} res - HTTP Response * * @memberOf adminController * * @returns {object} response JSON Object */ static getRequest(req, res) { const error = {}; error.message = {}; const requestId = parseInt(req.params.id, 10); const pool = new Pool({ connectionString, }); const selectQuery = { name: 'get-users-request', text: `SELECT requests.id, requests.title, requests.description, requests.comment, requests.date, requests.status, requests.userid, users.fullname FROM requests INNER JOIN users ON (requests.userid = users.id) WHERE requests.id = $1`, values: [requestId], }; pool.query(selectQuery, (err, result) => { pool.end(); return res.status(200).send({ success: true, status: 200, data: result.rows, }); }); } /** * @description - Approve a Request * @static * * @param {object} req - HTTP Request * @param {object} res - HTTP Response * * @memberOf adminController * * @returns {object} response JSON Object */ static approveRequest(req, res, next) { const requestId = parseInt(req.params.id, 10); const status = 'Pending'; const pool = new Pool({ connectionString, }); const insertQuery = { name: 'update-users-requests', text: 'UPDATE requests SET status=$1, comment=$3 WHERE id = $2 RETURNING *', values: [status, requestId, null], }; pool.query(insertQuery, (err, result) => { req.data = result.rows; res.status(200).send({ success: true, status: 200, data: result.rows, }); pool.end(); next(); }); } /** * @description - Reject a Request * @static * * @param {object} req - HTTP Request * @param {object} res - HTTP Response * * @memberOf adminController * * @returns {object} response JSON Object */ static rejectRequest(req, res, next) { const { comment, } = req.body; const requestId = parseInt(req.params.id, 10); const status = 'Disapproved'; const pool = new Pool({ connectionString, }); const insertQuery = { name: 'update-users-requests', text: 'UPDATE requests SET status=$1, comment=$2 WHERE id = $3 RETURNING *', values: [status, comment, requestId], }; pool.query(insertQuery, (err, result) => { req.data = result.rows; const queryValues = []; queryValues.push(requestId); res.status(200).send({ success: true, status: 200, data: result.rows, }); pool.end(); next(); }); } /** * @description - Resolve a Request * @static * * @param {object} req - HTTP Request * @param {object} res - HTTP Response * * @memberOf adminController * * @returns {object} response JSON Object */ static resolveRequest(req, res, next) { const requestId = parseInt(req.params.id, 10); const status = 'Resolved'; const queryValues = []; queryValues.push(requestId); const pool = new Pool({ connectionString, }); const insertQuery = { name: 'update-users-requests', text: 'UPDATE requests SET status=$1 WHERE id = $2 RETURNING *', values: [status, requestId], }; pool.query(insertQuery, (err, result) => { req.data = result.rows; res.status(200).send({ success: true, status: 200, data: result.rows, }); pool.end(); next(); }); } /** * @description - Delete a Request * @static * * @param {object} req - HTTP Request * @param {object} res - HTTP Response * * @memberOf adminController * * @returns {object} response JSON Object */ static deleteRequest(req, res) { const requestId = parseInt(req.params.id, 10); const pool = new Pool({ connectionString, }); const deleteQuery = { name: 'delete-request', text: 'DELETE FROM requests WHERE id = $1 RETURNING *', values: [requestId], }; pool.query(deleteQuery, (err, result) => { req.data = result.rows; req.data[0].status = 'Deleted'; res.status(200).send({ success: true, status: 200, data: result.rows, }); pool.end(); }); } }
JavaScript
class BaseReporter { constructor(_config, _cid, caps) { this._config = _config; this._cid = _cid; this.caps = caps; // ensure all properties are set before initializing the reporters this._reporters = this._config.reporters.map(this.initReporter.bind(this)); } /** * emit events to all registered reporter and wdio launcer * * @param {String} e event name * @param {object} payload event payload */ emit(e, payload) { payload.cid = this._cid; /** * Send failure message (only once) in case of test or hook failure */ (0, utils_2.sendFailureMessage)(e, payload); this._reporters.forEach((reporter) => reporter.emit(e, payload)); } getLogFile(name) { // clone the config to avoid changing original properties let options = Object.assign({}, this._config); let filename = `wdio-${this._cid}-${name}-reporter.log`; const reporterOptions = this._config.reporters.find((reporter) => (Array.isArray(reporter) && (reporter[0] === name || typeof reporter[0] === 'function' && reporter[0].name === name))); if (reporterOptions) { const fileformat = reporterOptions[1].outputFileFormat; options.cid = this._cid; options.capabilities = this.caps; Object.assign(options, reporterOptions[1]); if (fileformat) { if (typeof fileformat !== 'function') { throw new Error('outputFileFormat must be a function'); } filename = fileformat(options); } } if (!options.outputDir) { return; } return path_1.default.join(options.outputDir, filename); } /** * return write stream object based on reporter name */ getWriteStreamObject(reporter) { return { write: /* istanbul ignore next */ (content) => process.send({ origin: 'reporter', name: reporter, content }) }; } /** * wait for reporter to finish synchronization, e.g. when sending data asynchronous * to a server (e.g. sumo reporter) */ waitForSync() { const startTime = Date.now(); return new Promise((resolve, reject) => { const interval = setInterval(() => { const unsyncedReporter = this._reporters .filter((reporter) => !reporter.isSynchronised) .map((reporter) => reporter.constructor.name); if ((Date.now() - startTime) > this._config.reporterSyncTimeout && unsyncedReporter.length) { clearInterval(interval); return reject(new Error(`Some reporters are still unsynced: ${unsyncedReporter.join(', ')}`)); } /** * no reporter are in need to sync anymore, continue */ if (!unsyncedReporter.length) { clearInterval(interval); return resolve(true); } log.info(`Wait for ${unsyncedReporter.length} reporter to synchronise`); // wait otherwise }, this._config.reporterSyncInterval); }); } /** * initialise reporters */ initReporter(reporter) { let ReporterClass; let options = {}; /** * check if reporter has custom options */ if (Array.isArray(reporter)) { options = Object.assign({}, options, reporter[1]); reporter = reporter[0]; } /** * check if reporter was passed in from a file, e.g. * * ```js * const MyCustomReporter = require('/some/path/MyCustomReporter.js') * export.config = { * //... * reporters: [ * MyCustomReporter, // or * [MyCustomReporter, { custom: 'option' }] * ] * //... * } * ``` */ if (typeof reporter === 'function') { ReporterClass = reporter; options.logFile = options.setLogFile ? options.setLogFile(this._cid, ReporterClass.name) : this.getLogFile(ReporterClass.name); options.writeStream = this.getWriteStreamObject(ReporterClass.name); return new ReporterClass(options); } /** * check if reporter is a node package, e.g. wdio-dot reporter * * ```js * export.config = { * //... * reporters: [ * 'dot', // or * ['dot', { custom: 'option' }] * ] * //... * } * ``` */ if (typeof reporter === 'string') { ReporterClass = (0, utils_1.initialisePlugin)(reporter, 'reporter').default; options.logFile = options.setLogFile ? options.setLogFile(this._cid, reporter) : this.getLogFile(reporter); options.writeStream = this.getWriteStreamObject(reporter); return new ReporterClass(options); } /** * throw error if reporter property was invalid */ throw new Error('Invalid reporters config'); } }
JavaScript
class PositioningStatus{ constructor(context){ this.context = context; } }
JavaScript
class SidebarStatus{ constructor(context){ this.context = context; } open(){} close(){} }
JavaScript
class Grid { /** * Create a grid of specific dimensions and ships. * @param {[number, number]} dimensions - the dimensions of the grid * @param {[Ship]} ships - the ships the player should place on the grid */ constructor(dimensions, ships) { this.dimensions = dimensions; this.width = dimensions[0]; this.height = dimensions[1]; this.ships = ships; } /** * Find a ship within our grid that is intersecting with the specified position. * @param {[number, number]} position - the position to find a ship at * @return {Ship} */ getShipAtPosition(position) { // upcast our position coordinates to a matrix that can be intersected position = new Matrix([[1]]).placeAt(position); return this.ships.find(ship => ship.computed.intersects([position])); } }
JavaScript
class Story extends Component{ static displayName="story" render(){ const {children, align="left"}=this.props const descent=children.reduce((h,{props:{descent=0}})=>Math.max(h,descent),0) const baseline=children.reduce((h,{props:{height=0,descent=0}})=>Math.max(h,height-descent),0) const aligned=this[align](children) return (<Group className="story" y={baseline} lineDescent={descent} children={aligned}/>) } /** * Group unpositioned for each positioned * *** last group should ignore minWidth==0 element for alignment * @param {*} right */ group=memoize((right=false,children=this.props.children)=>{ return children .reduce((groups,a)=>{ if(a.props.x!=undefined){ if(right){ groups.push({located:a,words:[]}) }else{ groups[groups.length-1].located=a groups.push({words:[]}) } }else{ groups[groups.length-1].words.push(a) } return groups },[{words:[]}]) .map((group,_i,_a,isLast=_i==_a.length-1)=>{ let i=group.words.length- Array.from(group.words) .reverse() .findIndex(a=>isLast ? a.props.minWidth!==0 : !isWhitespace(a) ) group.endingWhitespaces=group.words.slice(i) group.words=group.words.slice(0,i) return group }) }) left=memoize(children=>{ const groups=this.group(false, children) const {aligned}=groups.reduce((state, {words, endingWhitespaces,located})=>{ if(words.length+endingWhitespaces.length){ state.aligned.push( React.cloneElement( new Merge({ x:state.x, children:[...words,...endingWhitespaces].map((a,key)=>React.cloneElement(a,{key})) }).render(), {key:state.aligned.length} ) ) } if(located){ state.aligned.push(React.cloneElement(located,{key:state.aligned.length})) state.x=located.props.x+located.props.width } return state },{x:0, aligned:[]}) return aligned }) right=memoize(children=>{ const groups=this.group(true,children) const {aligned}=groups.reduceRight((state, {located,words,endingWhitespaces})=>{ if(endingWhitespaces.length>0){ state.aligned.push( React.cloneElement( new Merge({ x:state.x, children:endingWhitespaces.map((a,key)=>React.cloneElement(a,{key})) }).render(), {key:state.aligned.length} ) ) } if(words.length){ state.x=words.reduce((x,a)=>x-a.props.width,state.x) state.aligned.push( React.cloneElement( new Merge({ x:state.x, children:words.map((a,key)=>React.cloneElement(a,{key})) }).render(), {key:state.aligned.length} ) ) } if(located){ state.aligned.push(React.cloneElement(located,{key:state.aligned.length})) state.x=located.props.x } return state },{x:this.props.width,aligned:[]}) return aligned.reverse() }) center=memoize(children=>{ const contentWidth=pieces=>pieces.reduce((w,a)=>w+a.props.width,0) const groups=this.group(false, children) const {aligned}=groups.reduce((state, {words, endingWhitespaces,located})=>{ if(words.length+endingWhitespaces.length){ const width=(located ? located.props.x : this.props.width)-state.x const wordsWidth=contentWidth(words) state.aligned.push( React.cloneElement( new Merge({ x:state.x+(width-wordsWidth)/2, children:[...words,...endingWhitespaces].map((a,key)=>React.cloneElement(a,{key})) }).render(), {key:state.aligned.length} ) ) } if(located){ state.aligned.push(React.cloneElement(located,{key:state.aligned.length})) state.x=located.props.x+located.props.width } return state },{x:0, aligned:[]}) return aligned }) justify=memoize(children=>{ const groups=this.group(false, children) const {justified}=groups.reduce((state,{words,endingWhitespaces,located})=>{ let len=state.justified.length const width=(located ? located.props.x : this.props.width)-state.x const {whitespaces,contentWidth}=words.reduce((status,a,i)=>{ if(isWhitespace(a)){ status.whitespaces.push(i) }else{ status.contentWidth+=a.props.width } return status },{contentWidth:0,whitespaces:[]}) const whitespaceWidth=whitespaces.length>0 ? (width-contentWidth)/whitespaces.length : 0; [...words,...endingWhitespaces].reduce((x,word,i)=>{ state.justified.push(React.cloneElement(word,{x,key:len++})) return x+(whitespaces.includes(i) ? whitespaceWidth : word.props.width) },state.x) if(located){ state.justified.push(React.cloneElement(located,{key:len++})) state.x=located.props.x+located.props.width } return state },{x:0,justified:[]}) return justified }) both(){ return this.justify(this.props.children) } }
JavaScript
class Provider { get modelMetatdata() { throw new NotImplementedError("get modelMetadata", Provider ); } }
JavaScript
class Named { constructor(gameObject) { this.gameObject = gameObject; gameObject["__Named"] = this; /* START-USER-CTR-CODE */ // Write your code here. /* END-USER-CTR-CODE */ } /** @returns {Named} */ static getComponent(gameObject) { return gameObject["__Named"]; } /** @type {Phaser.GameObjects.Image} */ gameObject; /** @type {string} */ name = ""; /* START-USER-CODE */ // Write your code here. /* END-USER-CODE */ }
JavaScript
class EditableBlock extends React.Component { constructor(props) { super(props); this.handleChange = this.handleChange.bind(this); this.handleFocus = this.handleFocus.bind(this); this.handleBlur = this.handleBlur.bind(this); this.handleKeyDown = this.handleKeyDown.bind(this); this.handleKeyUp = this.handleKeyUp.bind(this); this.handleMouseUp = this.handleMouseUp.bind(this); this.handleDragHandleClick = this.handleDragHandleClick.bind(this); this.openActionMenu = this.openActionMenu.bind(this); this.closeActionMenu = this.closeActionMenu.bind(this); this.openTagSelectorMenu = this.openTagSelectorMenu.bind(this); this.closeTagSelectorMenu = this.closeTagSelectorMenu.bind(this); this.handleTagSelection = this.handleTagSelection.bind(this); this.handleImageUpload = this.handleImageUpload.bind(this); this.addPlaceholder = this.addPlaceholder.bind(this); this.calculateActionMenuPosition = this.calculateActionMenuPosition.bind( this ); this.calculateTagSelectorMenuPosition = this.calculateTagSelectorMenuPosition.bind( this ); this.contentEditable = React.createRef(); this.fileInput = null; this.state = { htmlBackup: null, html: "", tag: "p", imageUrl: "", placeholder: false, previousKey: null, isTyping: false, tagSelectorMenuOpen: false, tagSelectorMenuPosition: { x: null, y: null, }, actionMenuOpen: false, actionMenuPosition: { x: null, y: null, }, }; } // To avoid unnecessary API calls, the block component fully owns the draft state // i.e. while editing we only update the block component, only when the user // finished editing (e.g. switched to next block), we update the page as well // https://reactjs.org/blog/2018/06/07/you-probably-dont-need-derived-state.html componentDidMount() { // Add a placeholder if the first block has no sibling elements and no content const hasPlaceholder = this.addPlaceholder({ block: this.contentEditable.current, position: this.props.position, content: this.props.html || this.props.imageUrl, }); if (!hasPlaceholder) { this.setState({ ...this.state, html: this.props.html, tag: this.props.tag, imageUrl: this.props.imageUrl, }); } } componentDidUpdate(prevProps, prevState) { // update the page on the server if one of the following is true // 1. user stopped typing and the html content has changed & no placeholder set // 2. user changed the tag & no placeholder set // 3. user changed the image & no placeholder set const stoppedTyping = prevState.isTyping && !this.state.isTyping; const hasNoPlaceholder = !this.state.placeholder; const htmlChanged = this.props.html !== this.state.html; const tagChanged = this.props.tag !== this.state.tag; const imageChanged = this.props.imageUrl !== this.state.imageUrl; if ( ((stoppedTyping && htmlChanged) || tagChanged || imageChanged) && hasNoPlaceholder ) { this.props.updateBlock({ id: this.props.id, html: this.state.html, tag: this.state.tag, imageUrl: this.state.imageUrl, }); } } componentWillUnmount() { // In case, the user deleted the block, we need to cleanup all listeners document.removeEventListener("click", this.closeActionMenu, false); } handleChange(e) { this.setState({ ...this.state, html: e.target.value }); } handleFocus() { // If a placeholder is set, we remove it when the block gets focused if (this.state.placeholder) { this.setState({ ...this.state, html: "", placeholder: false, isTyping: true, }); } else { this.setState({ ...this.state, isTyping: true }); } } handleBlur(e) { // Show placeholder if block is still the only one and empty const hasPlaceholder = this.addPlaceholder({ block: this.contentEditable.current, position: this.props.position, content: this.state.html || this.state.imageUrl, }); if (!hasPlaceholder) { this.setState({ ...this.state, isTyping: false }); } } handleKeyDown(e) { if (e.key === CMD_KEY) { // If the user starts to enter a command, we store a backup copy of // the html. We need this to restore a clean version of the content // after the content type selection was finished. this.setState({ htmlBackup: this.state.html }); } else if (e.key === "Backspace" && !this.state.html) { this.props.deleteBlock({ id: this.props.id }); } else if ( e.key === "Enter" && this.state.previousKey !== "Shift" && !this.state.tagSelectorMenuOpen ) { // If the user presses Enter, we want to add a new block // Only the Shift-Enter-combination should add a new paragraph, // i.e. Shift-Enter acts as the default enter behaviour e.preventDefault(); this.props.addBlock({ id: this.props.id, html: this.state.html, tag: this.state.tag, imageUrl: this.state.imageUrl, ref: this.contentEditable.current, }); } // We need the previousKey to detect a Shift-Enter-combination this.setState({ previousKey: e.key }); } // The openTagSelectorMenu function needs to be invoked on key up. Otherwise // the calculation of the caret coordinates does not work properly. handleKeyUp(e) { // console.log(e.key); if (e.key === CMD_KEY) { this.openTagSelectorMenu("KEY_CMD"); } } handleMouseUp() { const block = this.contentEditable.current; const { selectionStart, selectionEnd } = getSelection(block); if (selectionStart !== selectionEnd) { this.openActionMenu(block, "TEXT_SELECTION"); } } handleDragHandleClick(e) { const dragHandle = e.target; this.openActionMenu(dragHandle, "DRAG_HANDLE_CLICK"); } openActionMenu(parent, trigger) { const { x, y } = this.calculateActionMenuPosition(parent, trigger); this.setState({ ...this.state, actionMenuPosition: { x: x, y: y }, actionMenuOpen: true, }); // Add listener asynchronously to avoid conflicts with // the double click of the text selection setTimeout(() => { document.addEventListener("click", this.closeActionMenu, false); }, 100); } closeActionMenu() { this.setState({ ...this.state, actionMenuPosition: { x: null, y: null }, actionMenuOpen: false, }); document.removeEventListener("click", this.closeActionMenu, false); } openTagSelectorMenu(trigger) { const { x, y } = this.calculateTagSelectorMenuPosition(trigger); this.setState({ ...this.state, tagSelectorMenuPosition: { x: x, y: y }, tagSelectorMenuOpen: true, }); document.addEventListener("click", this.closeTagSelectorMenu, false); } closeTagSelectorMenu() { this.setState({ ...this.state, htmlBackup: null, tagSelectorMenuPosition: { x: null, y: null }, tagSelectorMenuOpen: false, }); document.removeEventListener("click", this.closeTagSelectorMenu, false); } // Convert editableBlock shape based on the chosen tag // i.e. img = display <div><input /><img /></div> (input picker is hidden) // i.e. every other tag = <ContentEditable /> with its tag and html content handleTagSelection(tag) { if (tag === "img") { this.setState({ ...this.state, tag: tag }, () => { this.closeTagSelectorMenu(); if (this.fileInput) { // Open the native file picker this.fileInput.click(); } // Add new block so that the user can continue writing // after adding an image this.props.addBlock({ id: this.props.id, html: "", tag: "p", imageUrl: "", ref: this.contentEditable.current, }); }); } else { if (this.state.isTyping) { // Update the tag and restore the html backup without the command this.setState({ tag: tag, html: this.state.htmlBackup }, () => { setCaretToEnd(this.contentEditable.current); this.closeTagSelectorMenu(); }); } else { this.setState({ ...this.state, tag: tag }, () => { this.closeTagSelectorMenu(); }); } } } async handleImageUpload() { if (this.fileInput && this.fileInput.files[0]) { const pageId = this.props.pageId; const imageFile = this.fileInput.files[0]; const formData = new FormData(); formData.append("image", imageFile); try { const response = await fetch( `${process.env.NEXT_PUBLIC_API}/pages/images?pageId=${pageId}`, { method: "POST", credentials: "include", body: formData, } ); const data = await response.json(); const imageUrl = data.imageUrl; this.setState({ ...this.state, imageUrl: imageUrl }); } catch (err) { console.log(err); } } } // Show a placeholder for blank pages addPlaceholder({ block, position, content }) { const isFirstBlockWithoutHtml = position === 1 && !content; const isFirstBlockWithoutSibling = !block.parentElement.nextElementSibling; if (isFirstBlockWithoutHtml && isFirstBlockWithoutSibling) { this.setState({ ...this.state, html: "Type a page title...", tag: "h1", imageUrl: "", placeholder: true, isTyping: false, }); return true; } else { return false; } } // If we have a text selection, the action menu should be displayed above // If we have a drag handle click, the action menu should be displayed beside calculateActionMenuPosition(parent, initiator) { switch (initiator) { case "TEXT_SELECTION": const { x: endX, y: endY } = getCaretCoordinates(false); // fromEnd const { x: startX, y: startY } = getCaretCoordinates(true); // fromStart const middleX = startX + (endX - startX) / 2; return { x: middleX, y: startY }; case "DRAG_HANDLE_CLICK": const x = parent.offsetLeft - parent.scrollLeft + parent.clientLeft - 90; const y = parent.offsetTop - parent.scrollTop + parent.clientTop + 35; return { x: x, y: y }; default: return { x: null, y: null }; } } // If the user types the "/" command, the tag selector menu should be display above // If it is triggered by the action menu, it should be positioned relatively to its initiator calculateTagSelectorMenuPosition(initiator) { switch (initiator) { case "KEY_CMD": const { x: caretLeft, y: caretTop } = getCaretCoordinates(true); return { x: caretLeft, y: caretTop }; case "ACTION_MENU": const { x: actionX, y: actionY } = this.state.actionMenuPosition; return { x: actionX - 40, y: actionY }; default: return { x: null, y: null }; } } render() { return ( <> {this.state.tagSelectorMenuOpen && ( <TagSelectorMenu position={this.state.tagSelectorMenuPosition} closeMenu={this.closeTagSelectorMenu} handleSelection={this.handleTagSelection} /> )} {this.state.actionMenuOpen && ( <ActionMenu position={this.state.actionMenuPosition} actions={{ deleteBlock: () => this.props.deleteBlock({ id: this.props.id }), turnInto: () => this.openTagSelectorMenu("ACTION_MENU"), }} /> )} <Draggable draggableId={this.props.id} index={this.props.position}> {(provided, snapshot) => ( <div ref={provided.innerRef} className={styles.draggable} {...provided.draggableProps} > {this.state.tag !== "img" && ( <ContentEditable innerRef={this.contentEditable} data-position={this.props.position} data-tag={this.state.tag} html={this.state.html} onChange={this.handleChange} onFocus={this.handleFocus} onBlur={this.handleBlur} onKeyDown={this.handleKeyDown} onKeyUp={this.handleKeyUp} onMouseUp={this.handleMouseUp} tagName={this.state.tag} className={[ styles.block, this.state.isTyping || this.state.actionMenuOpen || this.state.tagSelectorMenuOpen ? styles.blockSelected : null, this.state.placeholder ? styles.placeholder : null, snapshot.isDragging ? styles.isDragging : null, ].join(" ")} /> )} {this.state.tag === "img" && ( <div data-position={this.props.position} data-tag={this.state.tag} ref={this.contentEditable} className={[ styles.image, this.state.actionMenuOpen || this.state.tagSelectorMenuOpen ? styles.blockSelected : null, ].join(" ")} > <input id={`${this.props.id}_fileInput`} name={this.state.tag} type="file" onChange={this.handleImageUpload} ref={(ref) => (this.fileInput = ref)} hidden /> {!this.state.imageUrl && ( <label htmlFor={`${this.props.id}_fileInput`} className={styles.fileInputLabel} > No Image Selected. Click To Select. </label> )} {this.state.imageUrl && ( <img src={ process.env.NEXT_PUBLIC_API + "/" + this.state.imageUrl } alt={/[^\/]+(?=\.[^\/.]*$)/.exec(this.state.imageUrl)[0]} /> )} </div> )} <span role="button" tabIndex="0" className={styles.dragHandle} onClick={this.handleDragHandleClick} {...provided.dragHandleProps} > <img src={DragHandleIcon} alt="Icon" /> </span> </div> )} </Draggable> </> ); } }
JavaScript
class Switch extends React.Component { render () { return ( <RouterContext.Consumer> {context => { const location = this.props.location || context.location let element, match // We use React.Children.forEach instead of React.Children.toArray().find() // here because toArray adds keys to all child elements and we do not want // to trigger an unmount/remount for two <Route>s that render the same // component at different URLs. React.Children.forEach(this.props.children, child => { if (match == null && React.isValidElement(child)) { element = child const path = child.props.path || child.props.from match = path ? matchPath(location.pathname, { ...child.props, path }) : context.match } }) return match ? React.cloneElement(element, { location, computedMatch: match }) : null }} </RouterContext.Consumer> ) } }
JavaScript
class WebAudioControlsMidiManager { constructor() { this.midiAccess = null; this.listOfWidgets = []; this.listOfExternalMidiListeners = []; this.updateWidgets(); this.initWebAudioControls(); } addWidget(w) { this.listOfWidgets.push(w); } updateWidgets() { // this.listOfWidgets = document.querySelectorAll("webaudio-knob,webaudio-slider,webaudio-switch"); } initWebAudioControls() { if (navigator.requestMIDIAccess) { navigator.requestMIDIAccess().then( (ma) => { this.midiAccess = ma, this.enableInputs() }, (err) => { console.log("MIDI not initialized - error encountered:" + err.code) } ); } } enableInputs() { let inputs = this.midiAccess.inputs.values(); //console.log("Found " + this.midiAccess.inputs.size + " MIDI input(s)"); for (let input = inputs.next(); input && !input.done; input = inputs.next()) { //console.log("Connected input: " + input.value.name); input.value.onmidimessage = this.handleMIDIMessage.bind(this); } } midiConnectionStateChange(e) { // console.log("connection: " + e.port.name + " " + e.port.connection + " " + e.port.state); enableInputs(); } onMIDIStarted(midi) { this.midiAccess = midi; midi.onstatechange = this.midiConnectionStateChange; enableInputs(midi); } // Add hooks for external midi listeners support addMidiListener(callback) { this.listOfExternalMidiListeners.push(callback); } getCurrentConfigAsJSON() { return currentConfig.stringify(); } handleMIDIMessage(event) { this.listOfExternalMidiListeners.forEach(function (externalListener) { externalListener(event); }); if (((event.data[0] & 0xf0) == 0xf0) || ((event.data[0] & 0xf0) == 0xb0 && event.data[1] >= 120)) return; for (let w of this.listOfWidgets) { if (w.processMidiEvent) w.processMidiEvent(event); } if (opt.mididump) console.log(event.data); } contextMenuOpen(e, knob) { if (!this.midiAccess) return; let menu = document.getElementById("webaudioctrl-context-menu"); menu.style.left = e.pageX + "px"; menu.style.top = e.pageY + "px"; menu.knob = knob; menu.classList.add("active"); menu.knob.focus(); // document.activeElement.onblur=this.contextMenuClose; menu.knob.addEventListener("keydown", this.contextMenuCloseByKey.bind(this)); } contextMenuCloseByKey(e) { if (e.keyCode == 27) this.contextMenuClose(); } contextMenuClose() { let menu = document.getElementById("webaudioctrl-context-menu"); menu.knob.removeEventListener("keydown", this.contextMenuCloseByKey); menu.classList.remove("active"); let menuItemLearn = document.getElementById("webaudioctrl-context-menu-learn"); menuItemLearn.innerHTML = 'Learn'; menu.knob.midiMode = 'normal'; } contextMenuLearn() { let menu = document.getElementById("webaudioctrl-context-menu"); let menuItemLearn = document.getElementById("webaudioctrl-context-menu-learn"); menuItemLearn.innerHTML = 'Listening...'; menu.knob.midiMode = 'learn'; } contextMenuClear(e) { let menu = document.getElementById("webaudioctrl-context-menu"); menu.knob.midiController = {}; this.contextMenuClose(); } }
JavaScript
class SecurityService { constructor(securityService) { if (securityService !== singletonSecurityService) { throw new Error("Cannot construct singleton"); } this._permissions = []; this._roles = []; } /** * Zugriff auf Singleton */ static get instance() { if (!this[singleton]) { this[singleton] = new SecurityService(singletonSecurityService); } return this[singleton]; } set permissions(permissions) { this._permissions = permissions; } set roles(roles) { this._roles = roles; } /** * Hole alle Berechtigungen */ get permissions() { return (this._permissions || []); } /** * Hole alle Rollen */ get roles() { return (this._roles || []); } /** * Prüfung auf Berechtigung. * @param {...string} arguments - Alle Berechtigungen müssen gegeben sein */ check() { // Siehe arguments zur Verwaltung von n Parametern. // ...arg funktioniert bspw. nicht im Edge. return Array.from(arguments).every((arg) => { if (typeof arg === "string" && this._permissions !== null) { return this.permissions.indexOf(arg) !== -1; } return true; }); } /** * Prüfung auf Berechtigung. * @param {(string|string[])} arguments - Mindestens eine der Berechtigungen muss gegeben sein */ checkOr() { // Siehe arguments zur Verwaltung von n Parametern. // ...arg funktioniert bspw. nicht im Edge. return Array.from(arguments).some((arg) => { if (typeof arg === "string" && this._permissions !== null) { return this.permissions.indexOf(arg) !== -1; } return true; }); } /** * Prüfung auf Rolle. * @param {string} role */ hasRole(role) { if (typeof role === "string" && this._roles !== null) { return this.roles.indexOf(role) !== -1; } return true; } }
JavaScript
class Tracer { /** * @constructor * @param {String} serviceKey * @param {Array} reporters * @returns {Tracer} */ constructor (serviceKey, reporters = []) { this._serviceKey = serviceKey this._reporters = reporters } /** * @method extract * @param {String} operationName - the name of the operation * @param {Object} options * @param {SpanContext} [options.childOf] - a parent SpanContext (or Span, * for convenience) that the newly-started span will be the child of * (per REFERENCE_CHILD_OF). If specified, `fields.references` must * be unspecified. * @param {array} [options.references] - an array of Reference instances, * each pointing to a causal parent SpanContext. If specified, * `fields.childOf` must be unspecified. * @param {object} [options.tags] - set of key-value pairs which will be set * as tags on the newly created Span. Ownership of the object is * passed to the created span for efficiency reasons (the caller * should not modify this object after calling startSpan). * @param {number} [options.startTime] - a manually specified start time for * the created Span object. The time should be specified in * milliseconds as Unix timestamp. Decimal value are supported * to represent time values with sub-millisecond accuracy. * @returns {Span} span - a new Span object */ startSpan (operationName, options = {}) { assert(typeof operationName === 'string', 'operationName is required') let spanContext // Handle options.childOf if (options.childOf) { const childOf = new Reference(REFERENCE_CHILD_OF, options.childOf) if (options.references) { options.references.push(childOf) } else { options.references = [childOf] } const parentSpanContext = childOf.referencedContext() const serviceKey = this._serviceKey const parentServiceKey = parentSpanContext._serviceKey const traceId = parentSpanContext._traceId const spanId = undefined const parentSpanId = parentSpanContext._spanId spanContext = new SpanContext( serviceKey, parentServiceKey, traceId, spanId, parentSpanId ) } spanContext = spanContext || new SpanContext(this._serviceKey) return new Span( this, operationName, spanContext, options.tags, options.startTime, options.references ) } /** * @method extract * @param {String} format - the format of the carrier * @param {*} carrier - the type of the carrier object is determined by the format * @returns {SpanContext|null} - The extracted SpanContext, or null if no such SpanContext could * be found in carrier */ // eslint-disable-next-line class-methods-use-this extract (format, carrier) { assert(format, [FORMAT_BINARY, FORMAT_TEXT_MAP, FORMAT_HTTP_HEADERS].includes(format), 'Invalid type') assert(typeof carrier === 'object', 'carrier is required') if (format === FORMAT_BINARY) { // TODO: log } else { const tmpServiceKeys = (carrier[Tracer.CARRIER_KEY_SERVICE_KEYS] || '').split(':') const tmpSpanKeys = (carrier[Tracer.CARRIER_KEY_SPAN_IDS] || '').split(':') const serviceKey = tmpServiceKeys.shift() const parentServiceKey = tmpServiceKeys.shift() || undefined const traceId = carrier[Tracer.CARRIER_KEY_TRACE_ID] const spanId = tmpSpanKeys.shift() const parentSpanId = tmpSpanKeys.shift() || undefined if (!serviceKey || !traceId || !spanId) { return null } return new SpanContext( serviceKey, parentServiceKey, traceId, spanId, parentSpanId ) } return null } /** * @method inject * @param {SpanContext|Span} spanContext - he SpanContext to inject into the carrier object. * As a convenience, a Span instance may be passed in instead * (in which case its .context() is used for the inject()) * @param {String} format - the format of the carrier * @param {*} carrier - the type of the carrier object is determined by the format */ // eslint-disable-next-line class-methods-use-this inject (spanContext, format, carrier) { assert(spanContext, 'spanContext is required') assert(format, [FORMAT_BINARY, FORMAT_TEXT_MAP, FORMAT_HTTP_HEADERS].includes(format), 'Invalid type') assert(typeof carrier === 'object', 'carrier is required') const injectedContext = spanContext instanceof Span ? spanContext.context() : spanContext if (format === FORMAT_BINARY) { // TODO: log not implemented } else { let serviceKeysStr = injectedContext._serviceKey if (injectedContext.parentServiceKey()) { serviceKeysStr += `:${injectedContext.parentServiceKey()}` } let spanIdsStr = injectedContext._spanId if (injectedContext._parentSpanId) { spanIdsStr += `:${injectedContext._parentSpanId}` } carrier[Tracer.CARRIER_KEY_SERVICE_KEYS] = serviceKeysStr carrier[Tracer.CARRIER_KEY_TRACE_ID] = injectedContext._traceId carrier[Tracer.CARRIER_KEY_SPAN_IDS] = spanIdsStr } } }
JavaScript
class MetricsTracer extends Tracer { /** * @method reportFinish * @param {Span} span */ reportFinish (span) { this._reporters.forEach((reporter) => reporter.reportFinish(span)) } }
JavaScript
class Modal extends Component { static propTypes = { handleClose: PropTypes.func, isFullScreen: PropTypes.bool, } handleEscape = e => { const isEscape = 'key' in e ? (e.key == 'Escape' || e.key == 'Esc') : e.keyCode == 27 if (isEscape) { this.props.handleClose() } } componentDidMount() { // Keep track of how many modals are open, // If this is the first modal, lock the page's scroll if (activeModals < 1) { $('body').addClass('modal-open') $('.Draftail-Toolbar').css('z-index', 0) $('footer').css('display', 'none') activeModals = 1 } else { activeModals++ } // Ensure `esc` closes this modal, but not parent modals for (let listener of listeners) { document.removeEventListener('keydown', listener) } document.addEventListener('keydown', this.handleEscape) listeners.push(this.handleEscape) // Create a div to render children in if (!this.portal) { this.portal = document.createElement('div') document.body.appendChild(this.portal) } // Kick off the render this.componentDidUpdate() } componentWillUnmount() { // Remove the `esc` key event listener, enable parent listener document.removeEventListener('keydown', this.handleEscape) listeners.pop() if (listeners.length > 0) { const previousListener = listeners.slice(-1)[0] document.addEventListener('keydown', previousListener) } // Clean up div used for rendering children document.body.removeChild(this.portal); // Keep track of how many modals are open, // If this is the last modal, unlock the page's scroll activeModals-- if (activeModals < 1) { $('body').removeClass('modal-open') $('.Draftail-Toolbar').attr('style', null) $('footer').css('display', 'block') } } componentDidUpdate() { const { children, handleClose, isFullScreen } = this.props ReactDOM.render( <ModalInner isFullScreen={isFullScreen} handleClose={handleClose}>{children}</ModalInner>, this.portal ) } render() { return null } }
JavaScript
class ModalInner extends Component { static propTypes = { handleClose: PropTypes.func, } static childContextTypes = { hideModalClose: PropTypes.func, showModalClose: PropTypes.func, } constructor(props) { super(props) this.state = { showCloseButton: true, } } getChildContext = () => ({ hideModalClose: this.hideModalClose, showModalClose: this.showModalClose, }) hideModalClose = () => { this.setState({showCloseButton: false}) } showModalClose = () => { this.setState({showCloseButton: true}) } render() { const { showCloseButton } = this.state const { children, handleClose, isFullScreen } = this.props return ( <div className={`${styles.wrapper} ${isFullScreen && styles.fullscreen}`}> <div className={`${styles.content} ${isFullScreen && styles.fullscreen}`}> {showCloseButton && <div onClick={handleClose} className={styles.closeBtn}>&times;</div> } {children} </div> </div> ) } }
JavaScript
class Minimap extends Widget { /** * @param {GlobeView} view The iTowns view the minimap should be * linked to. Only {@link GlobeView} is * supported at the moment. * @param {ColorLayer} layer The {@link ColorLayer} that should be * displayed on the minimap. * @param {Object} [options] The minimap optional configuration. * @param {HTMLElement} [options.parentElement=view.domElement] The parent HTML container of the div * which contains minimap widgets. * @param {number} [options.size] The size of the minimap. It is a number * that describes both width and height * in pixels of the minimap. * @param {number} [options.width=150] The width in pixels of the minimap. * @param {number} [options.height=150] The height in pixels of the minimap. * @param {string} [options.position='bottom-left'] Defines which position within the * `parentElement` the minimap should be * displayed to. Possible values are * `top`, `bottom`, `left`, `right`, * `top-left`, `top-right`, `bottom-left` * and `bottom-right`. If the input value * does not match one of these, it will * be defaulted to `bottom-left`. * @param {Object} [options.translate] An optional translation of the minimap. * @param {number} [options.translate.x=0] The minimap translation along the page * x-axis. * @param {number} [options.translate.y=0] The minimap translation along the page * y-axis. * @param {HTMLElement|string} [options.cursor] An html element or an HTML string * describing a cursor showing minimap * view camera target position at the * center of the minimap. * @param {number} [options.minScale=1/2000] The minimal scale the minimap can reach. * @param {number} [options.maxScale=1/1_250_000] The maximal scale the minimap can reach. * @param {number} [options.zoomRatio=1/30] The ratio between minimap camera zoom * and view camera zoom. * @param {number} [options.pitch=0.28] The screen pixel pitch, used to compute * view and minimap scale. */ constructor(view, layer, options = {}) { // ---------- BUILD PROPERTIES ACCORDING TO DEFAULT OPTIONS AND OPTIONS PASSED IN PARAMETERS : ---------- if (!view.isGlobeView) { throw new Error( '\'Minimap\' plugin only supports \'GlobeView\'. Therefore, the \'view\' parameter must be a ' + '\'GlobeView\'.', ); } if (!layer.isColorLayer) { throw new Error('\'layer\' parameter form \'Minimap\' constructor should be a \'ColorLayer\'.'); } super(view, options, DEFAULT_OPTIONS); this.minScale = options.minScale || DEFAULT_OPTIONS.minScale; this.maxScale = options.maxScale || DEFAULT_OPTIONS.maxScale; // TODO : it could be interesting to be able to specify a method as zoomRatio parameter. This method could // return a zoom ratio from the scale of the minimap. this.zoomRatio = options.zoomRatio || DEFAULT_OPTIONS.zoomRatio; // ---------- this.domElement SETTINGS SPECIFIC TO MINIMAP : ---------- this.domElement.id = 'widgets-minimap'; // Display a cursor at the center of the minimap, if requested. if (options.cursor) { // Wrap cursor domElement inside a div to center it in minimap. const cursorWrapper = document.createElement('div'); cursorWrapper.id = 'cursor-wrapper'; this.domElement.appendChild(cursorWrapper); // Add specified cursor to its wrapper. if (typeof options.cursor === 'string') { cursorWrapper.innerHTML = options.cursor; } else if (options.cursor instanceof HTMLElement) { cursorWrapper.appendChild(options.cursor); } } // ---------- CREATE A MINIMAP View AND DISPLAY DATA PASSED IN Layer PARAMETER : ---------- this.view = new PlanarView(this.domElement, layer.source.extent, { camera: { type: CAMERA_TYPE.ORTHOGRAPHIC }, placement: layer.source.extent, // TODO : the default placement should be the view extent for ortho camera noControls: true, maxSubdivisionLevel: view.tileLayer.maxSubdivisionLevel, disableFocusOnStart: true, }); this.view.addLayer(layer); // TODO : should this promise be returned by constructor so that user can use it ? // Prevent the minimap domElement to get focus when clicked, and prevent click event to be propagated to the // main view controls. this.domElement.addEventListener('pointerdown', (event) => { event.preventDefault(); }); // Store minimap view camera3D in constant for code convenience. const camera3D = this.view.camera.camera3D; // ---------- UPDATE MINIMAP VIEW WHEN UPDATING THE MAIN VIEW : ---------- // The minimal and maximal value the minimap camera3D zoom can reach in order to stay in the scale limits. const initialScale = this.view.getScale(options.pitch); const minZoom = camera3D.zoom * this.maxScale / initialScale; const maxZoom = camera3D.zoom * this.minScale / initialScale; // Coordinates used to transform position vectors from the main view CRS to the minimap view CRS. const mainViewCoordinates = new Coordinates(view.referenceCrs); const viewCoordinates = new Coordinates(this.view.referenceCrs); const targetPosition = view.controls.getCameraTargetPosition(); view.addFrameRequester(MAIN_LOOP_EVENTS.AFTER_RENDER, () => { // Update minimap camera zoom const distance = view.camera.camera3D.position.distanceTo(targetPosition); const scale = view.getScaleFromDistance(options.pitch, distance); camera3D.zoom = this.zoomRatio * maxZoom * scale / this.minScale; camera3D.zoom = Math.min(Math.max(camera3D.zoom, minZoom), maxZoom); camera3D.updateProjectionMatrix(); // Update minimap camera position. mainViewCoordinates.setFromVector3(view.controls.getCameraTargetPosition()); mainViewCoordinates.as(this.view.referenceCrs, viewCoordinates); camera3D.position.x = viewCoordinates.x; camera3D.position.y = viewCoordinates.y; camera3D.updateMatrixWorld(true); this.view.notifyChange(camera3D); }); } }
JavaScript
class ConfidentialStorageValueTable extends Advanced.AbstractTableContent { constructor(props, context) { super(props, context); // default filter status // true - open // false - close this.state = { filterOpened: false }; } _getType(name) { const type = name.split('.'); return type[type.length - 1]; } getManager() { return this.props.confidentialStorageValueManager; } getContentKey() { return 'content.confidentialStorage'; } useFilter(event) { if (event) { event.preventDefault(); } this.refs.table.useFilterForm(this.refs.filterForm); } _getCellOwnerId( rowIndex, data, property) { return ( <Advanced.EntityInfo entityType={ this._getType(data[rowIndex].ownerType ) } entityIdentifier={ data[rowIndex][property] } face="popover" showEntityType={ false }/> ); } cancelFilter(event) { if (event) { event.preventDefault(); } this.refs.table.cancelFilter(this.refs.filterForm); } showDetail(entity) { this.context.history.push('/confidential-storage/' + entity.id); } render() { const { uiKey, confidentialStorageValueManager } = this.props; const { filterOpened } = this.state; // return ( <Advanced.Table ref="table" uiKey={uiKey} manager={confidentialStorageValueManager} filter={ <Advanced.Filter onSubmit={this.useFilter.bind(this)}> <Basic.AbstractForm ref="filterForm"> <Basic.Row> <div className="col-lg-4"> <Advanced.Filter.TextField ref="text" placeholder={this.i18n('filter.text')}/> </div> <div className="col-lg-4"> <Advanced.Filter.TextField ref="ownerId" placeholder={this.i18n('filter.ownerId')}/> </div> <div className="col-lg-4 text-right"> <Advanced.Filter.FilterButtons cancelFilter={this.cancelFilter.bind(this)}/> </div> </Basic.Row> <Basic.Row> <div className="col-lg-4"> <Advanced.Filter.TextField ref="key" placeholder={this.i18n('filter.key')}/> </div> <div className="col-lg-4"> <Advanced.Filter.TextField ref="ownerType" placeholder={this.i18n('filter.ownerType')}/> </div> </Basic.Row> </Basic.AbstractForm> </Advanced.Filter> } filterOpened={!filterOpened} _searchParameters={ this.getSearchParameters() }> <Advanced.Column header="" className="detail-button" cell={ ({ rowIndex, data }) => { return ( <Advanced.DetailButton title={this.i18n('button.detail')} onClick={this.showDetail.bind(this, data[rowIndex])}/> ); } } sort={false}/> <Advanced.Column property="key" sort /> <Advanced.Column property="ownerId" cell={({ rowIndex, data, property}) => this._getCellOwnerId( rowIndex, data, property) }/> <Advanced.Column property="ownerType" sort /> </Advanced.Table> ); } }
JavaScript
class BatchJobRepository { /** * Submits a batch job. * @param {String} email * @param {Array<File>} files */ async uploadBatchJob(email, files) { // Get upload urls. const { jobID, uploadUrls } = await ( await fetch(`${__BATCH_JOB_ENDPOINT__}/job/upload-request`, { method: "POST", body: JSON.stringify({ email, fileNames: files.map((file) => file.name) }), }) ).json(); // Upload files. for (const [fileName, uploadUrl] of Object.entries(uploadUrls)) { const file = files.find((file) => file.name === fileName); const fileDataUrl = await encodeFileAsBase64DataUrl(file); const binary = atob(getBase64FromDataUrl(fileDataUrl)); const array = []; for (var i = 0; i < binary.length; i++) { array.push(binary.charCodeAt(i)); } const blobData = new Blob([new Uint8Array(array)], { type: file.type }); const uploadResponse = await fetch(uploadUrl, { method: "PUT", body: blobData, }); if (uploadResponse.status != 200) throw `Failed to upload file: ${fileName}`; } // Verify email. const verificationResponse = await fetch(`${__BATCH_JOB_ENDPOINT__}/job/verify-code`, { method: "POST", body: JSON.stringify({ verificationCode: "123456", jobID, }), }); if (verificationResponse.status != 200) throw "Email verification failed"; // Send done signal. const doneResponse = await fetch(`${__BATCH_JOB_ENDPOINT__}/job/upload-done`, { method: "POST", body: JSON.stringify({ uploadDone: "true", jobID, }), }); if (doneResponse.status != 200) throw "Failed to submit"; } // TODO: refactoring async getBatchJobReportData(publicKey, password) { const dataFolderResponse = await fetch(`${__BATCH_JOB_REPORT_ENDPOINT__}/jobdata`, { method: "POST", body: JSON.stringify({ publicKey: publicKey, pwd: password, }), }); if (dataFolderResponse.status != 200) throw "Failed to fetch job data folder url"; const dataFolderUrl = await dataFolderResponse.json().then((r) => r.url); const resultReferencesResponse = await fetch(dataFolderUrl); if (resultReferencesResponse.status != 200) throw "Failed to fetch job data folder contents"; const resultReferences = await resultReferencesResponse.json(); resultReferences.images = resultReferences.images.map(async (imageResult) => { imageResult.name = imageResult.orginalName; imageResult.bug_type = imageResult.titles; try { imageResult.orig_image = await fetch(`${__BATCH_JOB_REPORT_ENDPOINT__}/job/file`, { method: "POST", body: JSON.stringify({ filePath: imageResult.orig_image, }), }); imageResult.orig_image = await ( await fetch((await imageResult.orig_image.json()).url) ).blob(); imageResult.heatmap_image = await fetch(`${__BATCH_JOB_REPORT_ENDPOINT__}/job/file`, { method: "POST", body: JSON.stringify({ filePath: imageResult.heatmap_image, }), }); imageResult.heatmap_image = await imageResult.heatmap_image.json(); imageResult.heatmap_image = await (await fetch(imageResult.heatmap_image.url)).blob(); } catch (error) { console.error(error); } return imageResult; }); resultReferences.videos = resultReferences.videos.map(async (videoResult) => { videoResult.name = videoResult.orginalName; try { videoResult.video = await fetch(`${__BATCH_JOB_REPORT_ENDPOINT__}/job/file`, { method: "POST", body: JSON.stringify({ filePath: videoResult.video, }), }); videoResult.video = await videoResult.video.json(); videoResult.video = await (await fetch(videoResult.video.url)).blob(); } catch (error) { console.error(error); } return videoResult; }); return resultReferences; } }
JavaScript
class Session { /** * Method for getting all sessions * @returns Promise */ static getSessions() { return $.get('/api/sessions'); } static getShareSessions(shareId) { return $.get(`/api/sessions/shared/${shareId}`); } /** * Method for getting single session by id * @param {*} id * @returns Promise */ static getSession(id) { return $.get(`/api/sessions/${id}`); } /** * Method for deleting session * @param {*} id */ static deleteSession(id) { return $.ajax({ type: 'DELETE', url: `/api/sessions/${id}`, }); } static renameSession(id, name) { return $.ajax({ type: 'PATCH', url: `/api/sessions/rename/${id}`, data : {name: name} }); } static copySession(id, name) { return $.ajax({ type: 'POST', url: `/api/sessions/copy/${id}`, data : {name: name} }); } static filterSession(id, filterNumber) { return $.ajax({ type: 'PATCH', url: `/api/sessions/filter/${id}`, data : {filterNumber: filterNumber} }); } static cutSession(id, from, to) { return $.ajax({ type: 'PATCH', url: `/api/sessions/cut/${id}`, data : { from: from, to: to } }); } static joinSession(id, joinSessionId, name) { return $.ajax({ type: 'POST', url: `/api/sessions/join/${id}`, data : { joinSessionId: joinSessionId, name: name } }); } static addLocations(id, locations) { return $.ajax({ type: 'PATCH', url: `/api/sessions/addlocation/${id}`, data : {locations: locations} }); } }
JavaScript
class App extends Component { render() { return ( <div class="amp-benchmark"> <h1>AMP Benchmark</h1> <button onclick={() => benchmarkRunner.runMutation()}> (Debug) Run Mutation </button> <h2>Results</h2> <div> <i>Results recorded in microseconds, and converted to milliseconds</i> </div> <div>Total Mutations run: {benchmarkRunner.getTotalMutationsRun()}</div> <div>Times to layout: {timesToLayout}</div> <div>Mutations Per Pass: {numberOfMutationsPerPass}</div> <h3>Not Purified</h3> <table class="value-table"> <thead> <tr> <th>Statistic</th> {getTableHeadings("notSanitized")} </tr> </thead> <tbody>{getResultTableRows("notSanitized")}</tbody> </table> <h3>Purified</h3> <table class="value-table"> <thead> <tr> <th>Statistic</th> {getTableHeadings("sanitized")} </tr> </thead> <tbody>{getResultTableRows("sanitized")}</tbody> </table> </div> ); } }
JavaScript
class Employee { constructor(name, id, email) { this.name = name; this.id = id; this.email = email; } getName() { return this.name; } getId() { return this.id; } getEmail() { return this.email; } getRole() { return "Employee"; } }
JavaScript
class RichlistEntry { /** * @internal * @param address * @param publicKey * @param amount */ constructor( /** * The account address. */ address, /** * The account public key. */ publicKey, /** * The mosaic amount */ amount) { this.address = address; this.publicKey = publicKey; this.amount = amount; } /** * Create a Richlist Entry * @param address - Address of the account * @param publicKey - Public Key of the account * @param amount - The mosaic amount * @return {RichlistEntry} */ static create(address, publicKey, amount) { return new RichlistEntry(address, publicKey, amount); } }
JavaScript
class UsedDependencyUI{ constructor() { let SELF = this; SELF.reinit = SELF.reinit.bind(this); SELF.input = SELF.input.bind(this); SELF.UI_Semantic; //depr SELF.UI_Material; SELF.UI_Default; if(window.UI_settings){ if(window.UI_settings.Tooltip){ SELF.Tooltip = window.UI_settings.Tooltip.ensure; } if(window.UI_settings.UI){ switch (window.UI_settings.UI){ case "Semantic" : SELF.UI_Semantic=true; break; //depr case "Material" : SELF.UI_Material=true; break; default: SELF.UI_Default=true; } } } SELF.Tooltip; } reinit(){ let SELF = this; SELF.UI_Semantic; //depr SELF.UI_Material; SELF.UI_Default; if(window.UI_settings){ if(window.UI_settings.Tooltip){ SELF.Tooltip = window.UI_settings.Tooltip.ensure; } if(window.UI_settings.UI){ switch (window.UI_settings.UI){ case "Semantic" : SELF.UI_Semantic=true; break; //depr case "Material" : SELF.UI_Material=true; break; default: SELF.UI_Default=true; } } } } input(){ let SELF = this; let mainClass = ""; //стиль элемента из UI зависимостей let formField = ""; if(SELF.UI_Semantic) { //depr mainClass = " ui input form "; formField = " field " } if(SELF.UI_Material) { mainClass = " ui input form "; formField = " mdc-text-field " } return { mainClass:mainClass, formField:formField } } inputClickEdit(){ let SELF = this; let mainClass = ""; //стиль элемента из UI зависимостей let formField = ""; let iconEdit = ""; let iconCheck = "" ; let iconCancel = "" mainClass = " ui input form "; formField = " field "; iconEdit = " edit icon "; iconCheck = " icon check "; iconCancel = " close icon "; return { mainClass:mainClass, formField:formField, iconEdit:iconEdit, iconCheck:iconCheck, iconCancel:iconCancel } } btn(){ let SELF = this; let mainClass = ""; //стиль элемента из UI зависимостей let btnClass = ""; if(SELF.UI_Semantic) { mainClass = " btn "; btnClass = " ui button " } if(SELF.UI_Material) { mainClass = " btn "; btnClass = " ui button " } return { mainClass:mainClass, btnClass:btnClass } } btnWithConfirm(){ let SELF = this; let mainClass = ""; //стиль элемента из UI зависимостей let btnClass = ""; mainClass = " ui fluid search selection dropdown "; btnClass = " ui button " return { mainClass:mainClass, btnClass:btnClass } } checkbox(){ let SELF = this; let mainClass = ""; //стиль элемента из UI зависимостей let toggleType = ""; let sliderType = ""; if(SELF.UI_Semantic ) { mainClass = " ui checkbox "; toggleType = " toggle "; sliderType = " slider "; } if(SELF.UI_Material) { mainClass = " ui checkbox "; toggleType = " toggle "; sliderType = " slider "; } return { mainClass:mainClass, toggleType:toggleType, sliderType:sliderType } } dateTime(){ let SELF = this; let mainClass = ""; //стиль элемента из UI зависимостей let formField = ""; if(SELF.UI_Semantic || SELF.UI_Material) { mainClass = " ui calendar form "; formField = " ui calendar " } return { mainClass:mainClass, formField:formField } } label(){ let SELF = this; let mainClass = ""; //стиль элемента из UI зависимостей if(SELF.UI_Semantic || SELF.UI_Material) { mainClass = " ui label "; } return { mainClass:mainClass, } } textarea(){ let SELF = this; let mainClass = ""; //стиль элемента из UI зависимостей if(SELF.UI_Semantic || SELF.UI_Material) { mainClass = " ui textarea form"; } return { mainClass:mainClass, } } dropdown(){ let SELF = this; let mainClass = ""; //стиль элемента из UI зависимостей let searchClass = "" if(SELF.UI_Semantic || SELF.UI_Material) { searchClass = " ui fluid search selection dropdown "; mainClass = "ui dropdown label" } return { mainClass: "ui form ", mainField:mainClass, searchField:searchClass } } }
JavaScript
class AuthService extends BaseService { constructor({ userService, customerService }) { super() /** @private @const {UserService} */ this.userService_ = userService /** @private @const {CustomerService} */ this.customerService_ = customerService } /** * Verifies if a password is valid given the provided password hash * @param {string} password - the raw password to check * @param {string} hash - the hash to compare against * @return {bool} the result of the comparison */ async comparePassword_(password, hash) { const buf = Buffer.from(hash, "base64") return Scrypt.verify(buf, password) } /** * Authenticates a given user with an API token * @param {string} token - the api_token of the user to authenticate * @return {{ * success: (bool), * user: (object | undefined), * error: (string | undefined) * }} * success: whether authentication succeeded * user: the user document if authentication succeded * error: a string with the error message */ async authenticateAPIToken(token) { if (process.env.NODE_ENV === "development") { try { const user = await this.userService_.retrieve(token) return { success: true, user, } } catch (error) { // ignore } } try { const user = await this.userService_.retrieveByApiToken(token) return { success: true, user, } } catch (error) { return { success: false, error: "Invalid API Token", } } } /** * Authenticates a given user based on an email, password combination. Uses * scrypt to match password with hashed value. * @param {string} email - the email of the user * @param {string} password - the password of the user * @return {{ success: (bool), user: (object | undefined) }} * success: whether authentication succeeded * user: the user document if authentication succeded * error: a string with the error message */ async authenticate(email, password) { try { const userPasswordHash = await this.userService_.retrieveByEmail(email, { select: ["password_hash"], }) const passwordsMatch = await this.comparePassword_( password, userPasswordHash.password_hash ) if (passwordsMatch) { const user = await this.userService_.retrieveByEmail(email) return { success: true, user, } } else { return { success: false, error: "Invalid email or password", } } } catch (error) { console.log(error) return { success: false, error: "Invalid email or password", } } } /** * Authenticates a customer based on an email, password combination. Uses * scrypt to match password with hashed value. * @param {string} email - the email of the user * @param {string} password - the password of the user * @return {{ success: (bool), user: (object | undefined) }} * success: whether authentication succeeded * user: the user document if authentication succeded * error: a string with the error message */ async authenticateCustomer(email, password) { try { const customerPasswordHash = await this.customerService_.retrieveByEmail( email, { select: ["password_hash"], } ) if (!customerPasswordHash.password_hash) { return { success: false, error: "Invalid email or password", } } const passwordsMatch = await this.comparePassword_( password, customerPasswordHash.password_hash ) if (passwordsMatch) { const customer = await this.customerService_.retrieveByEmail(email) return { success: true, customer, } } else { return { success: false, error: "Invalid email or password", } } } catch (error) { return { success: false, error: "Invalid email or password", } } } }
JavaScript
class ie extends Error{constructor(t,e){super(function(t,e){return`${t?`NG0${t}: `:""}${e}`} /** * @license * Copyright Google LLC All Rights Reserved. * * Use of this source code is governed by an MIT-style license that can be * found in the LICENSE file at https://angular.io/license */(t,e)),this.code=t}}
JavaScript
class of{constructor(t,e,n,i){this.routeReuseStrategy=t,this.futureState=e,this.currState=n,this.forwardEvent=i}activate(t){const e=this.futureState._root,n=this.currState?this.currState._root:null;this.deactivateChildRoutes(e,n,t),Hp(this.futureState.root),this.activateChildRoutes(e,n,t)}deactivateChildRoutes(t,e,n){const i=Rp(e);t.children.forEach(t=>{const e=t.value.outlet;this.deactivateRoutes(t,i[e],n),delete i[e]}),ip(i,(t,e)=>{this.deactivateRouteAndItsChildren(t,n)})}deactivateRoutes(t,e,n){const i=t.value,r=e?e.value:null;if(i===r)if(i.component){const r=n.getContext(i.outlet);r&&this.deactivateChildRoutes(t,e,r.children)}else this.deactivateChildRoutes(t,e,n);else r&&this.deactivateRouteAndItsChildren(e,n)}deactivateRouteAndItsChildren(t,e){this.routeReuseStrategy.shouldDetach(t.value.snapshot)?this.detachAndStoreRouteSubtree(t,e):this.deactivateRouteAndOutlet(t,e)}detachAndStoreRouteSubtree(t,e){const n=e.getContext(t.value.outlet);if(n&&n.outlet){const e=n.outlet.detach(),i=n.children.onOutletDeactivated();this.routeReuseStrategy.store(t.value.snapshot,{componentRef:e,route:t,contexts:i})}}deactivateRouteAndOutlet(t,e){const n=e.getContext(t.value.outlet);if(n){const i=Rp(t),r=t.value.component?n.children:e;ip(i,(t,e)=>this.deactivateRouteAndItsChildren(t,r)),n.outlet&&(n.outlet.deactivate(),n.children.onOutletDeactivated())}}activateChildRoutes(t,e,n){const i=Rp(e);t.children.forEach(t=>{this.activateRoutes(t,i[t.value.outlet],n),this.forwardEvent(new qd(t.value.snapshot))}),t.children.length&&this.forwardEvent(new $d(t.value.snapshot))}activateRoutes(t,e,n){const i=t.value,r=e?e.value:null;if(Hp(i),i===r)if(i.component){const r=n.getOrCreateContext(i.outlet);this.activateChildRoutes(t,e,r.children)}else this.activateChildRoutes(t,e,n);else if(i.component){const e=n.getOrCreateContext(i.outlet);if(this.routeReuseStrategy.shouldAttach(i.snapshot)){const t=this.routeReuseStrategy.retrieve(i.snapshot);this.routeReuseStrategy.store(i.snapshot,null),e.children.onOutletReAttached(t.contexts),e.attachRef=t.componentRef,e.route=t.route.value,e.outlet&&e.outlet.attach(t.componentRef,t.route.value),af(t.route)}else{const n=function(t){for(let e=t.parent;e;e=e.parent){const t=e.routeConfig;if(t&&t._loadedConfig)return t._loadedConfig;if(t&&t.component)return null}return null} /** * @license * Copyright Google LLC All Rights Reserved. * * Use of this source code is governed by an MIT-style license that can be * found in the LICENSE file at https://angular.io/license */(i.snapshot),r=n?n.module.componentFactoryResolver:null;e.attachRef=null,e.route=i,e.resolver=r,e.outlet&&e.outlet.activateWith(i,r),this.activateChildRoutes(t,null,e.children)}}else this.activateChildRoutes(t,null,n)}}
JavaScript
class ErrorBoundary extends React.Component { state = { hasError: false, error: null, } static getDerivedStateFromError(error) { return { hasError: true, error, } } render() { if (this.state.hasError) { return this.props.fallback } return this.props.children } }
JavaScript
class MessageList extends PureComponent { constructor(props) { super(props); this.state = { message: '', emoFlex: 0, emoji: false, sticker:false, showEmoticons:true, }; } _keyExtractor = (item, index) => item._id _renderItem = ({ item }) => ( <View style={{ transform: [{ scaleY: -1 }] }} > <ChatView item={item} // to send user,friend to chatview // sticker = {this.props.sticker} user={this.props.user} friend={this.props.friend} /> </View> ) toggleEmo = () => { if (this.state.emoFlex === 0) { this.setState({ emoFlex: 1 }) Keyboard.dismiss() // console.log("sushas stick",this.props.stickers[0]._id); } else { this.setState({ emoFlex: 0 }) this.state.emoji // console.log("sushas stick",this.props.stickers[0]._id); } } toggleSticker = ()=>{ const oldSticker = this.state.sticker; // this.setState({emoji: false}) Keyboard.dismiss() this.setState({ sticker: !oldSticker,emoji: false }); } clearText = () => { if (this.state.message.trim() !== '') { this._textInput.clear(); Keyboard.dismiss() this.props.onPress(this.state.message); this.setState({ message: '',emoji: false }); } } toggleEmoji = () => { const oldEmoji = this.state.emoji; this.setState({sticker: false}) Keyboard.dismiss() // sticker.dismiss() this.setState({ emoji: !oldEmoji,sticker: false }); } onPress(x) { // this._textInput.clear(); this.setState({ message: this.state.message + x }) } onbackPress(x){ this._textInput.clear(); // this.setState({ // message: this.props.message.slice(message.length-1,message.length) // }) this.setState({ message: this.state.message.slice(0,-2) }) } _onBackspacePress() { if (this.props.onBackspacePress) this.props.onBackspacePress(); } render() { // console.log("sendMessage"); // console.log(this.props.friend,this.state.message); // console.log("packs",this.props.packs); // console.log("i got in sticker",this.props.sticker) if (this.props.messages.length !== '') { return ( <View style={{ height: "100%" }}> <View style={{ flex: 1}}> <FlatList scrollEnabled={true} horizontal={false} data={this.props.messages} keyExtractor={this._keyExtractor} renderItem={this._renderItem} style={{ transform: [{ scaleY: -1 }] }} /> </View> <View style={styles.input}> <TextInput accessibilityLabel="MessageTextinput" ref={component => this._textInput = component} placeholder="Start typing...." style={{ flex: 1 }} // keyboardType="default" value={this.state.message} clearButtonMode='while-editing' // onFocus={this.setState({emoFlex:0})} blurOnSubmit={true} clearTextOnFocus={true} onSubmitEditing={this.clearText} onChangeText={(message) => this.setState({ message: message })} /> <TouchableOpacity onPress={this.clearText}> <Icon name="send" accessibilityLabel="SendMessage" size={40} color="#900" /> </TouchableOpacity> </View> <View style={{backgroundColor:"red",width:"100%",flexDirection:"row"}}> <TouchableOpacity onPress={this.toggleEmoji} > <Icon name="insert-emoticon" size={40} color="#900" /> </TouchableOpacity> <TouchableOpacity onPress={this.toggleSticker } > <Icon name="insert-photo" size={40} color="#900" /> </TouchableOpacity> </View> {this.state.sticker && <View style={{ height: 300 }}> <TabbedView packs={this.props.packs} tabPress={this.ontabPress} onPress={this.onPressGetSticker} friend={this.props.friend} /> </View> } {this.state.emoji && <View style={{ height: 300 }}> <Tabbed onPress={this.onPress.bind(this)} /> {/* <Emoticons // ref={component => this._textInput = component} onEmoticonPress={(e)=>this.onPress(e.code)} onBackspacePress={(e)=>this.onbackPress()} show={this.state.showEmoticons} concise={false} asyncRender={true} showHistoryBar={true} showPlusBar={false} /> */} </View> } </View> ); } else { return ( <View > <View style={styles.input}> <TouchableOpacity onPress={this.toggleEmo} > <Icon name="insert-emoticon" size={40} color="#900" /> </TouchableOpacity> <TextInput accessibilityLabel="MessageTextinput" ref={component => this._textInput = component} placeholder="Start typing...." style={{ flex: 1 }} // keyboardType="default" value={this.state.message} clearButtonMode='while-editing' // onFocus={this.setState({emoFlex:0})} blurOnSubmit={true} clearTextOnFocus={true} onSubmitEditing={this.clearText} onChangeText={(message) => this.setState({ message: message })} /> <TouchableOpacity onPress={this.clearText}> <Icon name="send" accessibilityLabel="SendMessage" size={40} color="#900" /> </TouchableOpacity> </View> <TabbedView packs={this.props.packs} tabPress={this.ontabPress} onPress={this.onPressGetSticker} friend={this.props.friend} /> </View> // </View> ); } } }
JavaScript
class OrdersListCustomerComponent extends React.Component { constructor(props) { super(props); } render() { return ( <div> <div className="row"> <div className="col-sm-12"> <table id="property-table" className="table table-hover" role="grid" aria-describedby="property-table_info"> <thead> <tr className="text-rose" role="row"> <th>Mã</th> <th>Thời gian mua hàng</th> <th>Tổng tiền hàng</th> <th> Tiền trả hàng</th> <th> Tiền nợ</th> <th> Nhân viên bán hàng</th> </tr> </thead> <tbody> {this.props.ordersList && this.props.ordersList.map( (order) => { return ( <tr role="row" className="even" key={order.id}> <td className="sorting_1"> {order.code} </td> <td>{order.created_at}</td> <td>{order.total}</td> <td>{order.paid}</td> <td>{order.debt}</td> <td>{order.staff && order.staff.name}</td> </tr> ); })} </tbody> </table> </div> </div> </div> ); } }
JavaScript
class Home extends Component { constructor(props) { super(props); this.state = { } } render() { return ( <div> {/* THE HEADER */} <Header/> {/* MAIN CONTENT */} <div id="content-block"> <div className="head-bg"> <div className="head-bg-img"></div> <div className="head-bg-content"></div> </div> <div className="container-fluid custom-container"> <div className="row"> <div className="col-md-12"> <Feeds feeds={this.props.feeds}/> </div> </div> </div> </div> </div> ); } }
JavaScript
class Installer { get home() { return process.env[(process.platform == 'win32') ? 'USERPROFILE' : 'HOME']; } constructor(options, complete) { this.options = options || {}; this.complete = complete; this._shell = (process.env.SHELL || '').split('/').slice(-1)[0]; this.dest = this._shell === 'zsh' ? 'zshrc' : this._shell === 'bash' ? 'bashrc' : 'fish'; this.dest = this.dest.replace('~', process.env.HOME); } // Called on install command. // // Performs the installation process. handle(name, options) { this.options.name = name; if (options.stdout) return new Promise((r, errback) => { return this.writeTo({ destination: 'stdout' }); }); if (options.auto) { this.template = this._shell; return this.writeTo({ destination: this.dest }); } return this.prompt().then(this.writeTo.bind(this)); } writeTo(data) { var destination = data.destination; debug('Installing completion script to %s directory', destination); var script = this.complete.script(this.options.name, this.options.completer || this.options.name, this.template); if (destination === 'stdout') return process.stdout.write('\n\n' + script + '\n'); if (destination === 'bashrc') destination = path.join(this.home, '.bashrc'); else if (destination === 'zshrc') destination = path.join(this.home, '.zshrc'); else if (destination === 'fish') destination = path.join(this.home, '.config/fish/config.fish'); else if (destination === 'fishdir') destination = path.join(this.home, '.config/fish/completions', this.options.name + '.fish'); else destination = path.join(destination, this.options.name); return new Promise(this.createStream.bind(this, destination)) .then(this.installCompletion.bind(this, destination)); } createStream(destination, r, errback) { // debug('Check %s destination', destination); var flags = 'a'; fs.stat(destination, (err, stat) => { if (err && err.code === 'ENOENT') flags = 'w'; else if (err) return errback(err); mkdirp(path.dirname(destination), (err) => { if (err) return errback(err); var out = fs.createWriteStream(destination, { flags }); out.on('error', (err) => { if (err.code === 'EACCES') { console.error(errmsg.replace(':destination', destination)); } return errback(err); }); out.on('open', () => { debug('Installing completion script to %s directory', destination); debug('Writing to %s file in %s mode', destination, flags === 'a' ? 'append' : 'write'); r(out); }); }); }); } installCompletion(destination, out) { var name = this.options.name; var script = this.complete.script(name, this.options.completer || name, this.template); var filename = path.join(__dirname, '../.completions', name + '.' + this.template); if(process.platform === 'win32') { filename = filename.replace(/\\/g, '/'); } // win32: replace backslashes with forward slashes debug('Writing actual completion script to %s', filename); // First write internal completion script in a local .comletions directory // in this module. This gets sourced in user scripts after, to avoid // cluttering bash/zshrc files with too much boilerplate. return new Promise((r, errback) => { fs.writeFile(filename, script, (err) => { if (err) return errback(err); var regex = new RegExp(`tabtab source for ${name}`); fs.readFile(destination, 'utf8', (err, content) => { if (err) return errback(err); if (regex.test(content)) { return debug('Already installed %s in %s', name, destination); } console.error('\n[tabtab] Adding source line to load %s\nin %s\n', filename, destination); debug('. %s > %s', filename, destination); out.write('\n# tabtab source for ' + name + ' package'); out.write('\n# uninstall by removing these lines or running '); out.write('`tabtab uninstall ' + name + '`'); if (this.template === 'fish') { out.write('\n[ -f ' + filename + ' ]; and . ' + filename); } else if (this.template === 'zsh') { out.write('\n[[ -f ' + filename + ' ]] && . ' + filename); } else { out.write('\n[ -f ' + filename + ' ] && . ' + filename); } }); }); }); } uninstallCompletion(destination) { return new Promise((r, errback) => { fs.readFile(destination, 'utf8', (err, body) => { if (err) return errback(err); r(body); }); }) .then((body) => { var lines = body.split(/\r?\n/); debug('Uninstall', this.options); var name = this.options.name; var reg = new RegExp('(tabtab source for ' + name + ' package|`tabtab uninstall ' + name + '`|tabtab/.completions/' + name + ')'); lines = lines.filter((line) => { return !reg.test(line); }); return lines.join('\n'); }) .then((content) => { return new Promise((r, errback) => { fs.writeFile(destination, content, (err) => { if (err) return errback(err); debug('%s sucesfully updated to remove tabtab', destination); }); }); }); } // Prompts user for installation location. prompt() { var choices = [{ name: 'Nowhere. Just output to STDOUT', value: 'stdout', short: 'stdout' }]; var prompts = [{ message: 'Where do you want to setup the completion script', name: 'destination', type: 'list', choices: choices }]; return this.shell() .then((entries) => { prompts[0].choices = choices.concat(entries); return inquirer.prompt(prompts); }); } // Shell adapters. // // Supported: // // - bash - Asks pkg-config for completion directories // - zsh - Lookup $fpath environment variable // - fish - Lookup for $fish_complete_path shell() { return new Promise((r, errback) => { var shell = process.env.SHELL; if (shell) shell = shell.split((process.platform !== 'win32') ? '/' : '\\').slice(-1)[0]; return this[shell]().then(r) .catch(errback); }); } fish() { debug('Fish shell detected'); this.template = 'fish'; return new Promise((r, errback) => { var dir = path.join(this.home, '.config/fish/completions'); return r([{ name: 'Fish config file (~/.config/fish/config.fish)', value: 'fish', short: 'fish' }, { name: 'Fish completion directory (' + dir + ')', value: 'fishdir', short: 'fish' }]); }); } bash() { debug('Bash shell detected'); this.template = 'bash'; var entries = [{ name: 'Bash config file (~/.bashrc)', value: 'bashrc', short: 'bash' }]; return this.completionsdir() .then((dir) => { debug(dir); if (dir) { entries.push({ name: 'Bash completionsdir ( ' + dir + ' )', value: dir }); } return this.compatdir(); }) .then((dir) => { if (dir) { entries.push({ name: 'Bash compatdir ( ' + dir + ' )', value: dir }); } return entries; }); } zsh() { debug('Zsh shell detected'); this.template = 'zsh'; return new Promise((r, errback) => { var dir = '/usr/local/share/zsh/site-functions'; return r([{ name: 'Zsh config file (~/.zshrc)', value: 'zshrc', short: 'zsh' }, { name: 'Zsh completion directory (' + dir + ')', value: dir }]); }); } // Bash // Public: pkg-config wrapper pkgconfig(variable) { return new Promise((r, errback) => { var cmd = `pkg-config --variable=${variable} bash-completion`; debug('cmd', cmd); exec(cmd, function(err, stdout, stderr) { if (err) { // silently fail if pkg-config bash-completion returns an error, // meaning bash-completion is either not installed or misconfigured // with PKG_CONFIG_PATH return r(); } stdout = stdout.trim(); debug('Got %s for %s', stdout, variable); r(stdout); }); }); } // Returns the pkg-config variable for "completionsdir" and bash-completion completionsdir() { debug('Asking pkg-config for completionsdir'); return this.pkgconfig('completionsdir'); } // Returns the pkg-config variable for "compatdir" and bash-completion compatdir() { debug('Asking pkg-config for compatdir'); return this.pkgconfig('compatdir'); } }
JavaScript
class processorInput { get events() { return ["focusout"] }; parse() { if (event.target.type == "button" || event.target.type == "submit") { return; } return { type: event.type, content: event.target.value } } }
JavaScript
class Brain { constructor(inputSize, hiddenSize, outputSize, mutationRate) { this.inputSize = inputSize; this.hiddenSize = hiddenSize; this.outputSize = outputSize; this.mutationRate = mutationRate; let inputConfig = { shape: [inputSize] }; let hiddenConfig = { units: hiddenSize, activation: 'tanh', kernelInitializer: 'glorotNormal', biasInitializer: 'glorotNormal' }; let outConfig = { units: outputSize, activation: 'linear', kernelInitializer: 'glorotNormal', biasInitializer: 'glorotNormal' }; this.model = tf.tidy(() => { // Define input, which has a size of 5 (not including batch dimension). const input = tf.input(inputConfig); // First dense layer uses relu activation. const denseLayer1 = tf.layers.dense(hiddenConfig); // Second dense layer uses linear activation. const denseLayer2 = tf.layers.dense(outConfig); // Obtain the output symbolic tensor by applying the layers on the input. const output = denseLayer2.apply(denseLayer1.apply(input)); return tf.model({ inputs: input, outputs: output }); }); // Create the model based on the inputs. } think(input) { return tf.tidy(() => { const data = tf.tensor2d(input, [1, this.inputSize]); let activation = this.model.predict(data); return Array.from(activation.dataSync()); }); } mix(brain1, brain2) { this.mutate(brain1); //this.mutate(brain2); } mutate(parent) { const mutated = parent.model.getWeights().reduce((mutations, layer) => { const data = Array.from(layer.dataSync()); const numMutations = getBinomial(data.length, this.mutationRate); for (let i = 0; i < numMutations; i++) { const loc = getRandomInt(0, data.length); const newVal = data[loc] + Math.random() * 2 - 1; data[loc] = newVal; } let newLayer = tf.tensor(data, layer.shape); mutations.push(newLayer); return mutations; }, []); this.model.setWeights(mutated); mutated.forEach(element => { element.dispose(); }); } die() { this.model.getWeights().forEach(element => element.dispose()); //this.bias.dispose(); } toJSON() { let weights = Array.from(this.weights.dataSync()); let wShape = this.weights.shape; let bias = Array.from(this.bias.dataSync()); let bShape = this.bias.shape; return { weights: { data: weights, shape: wShape }, bias: { data: bias, shape: bShape } }; } fromJSON(JSON) { const old_w = this.weights; const old_b = this.bias; tf.tidy(() => { this.weights = tf.keep(tf.tensor(JSON.weights.data, JSON.weights.shape)); this.bias = tf.keep(tf.tensor(JSON.bias.data, JSON.bias.shape)); }); old_w.dispose(); old_b.dispose(); } display() { this.weights.print(); this.bias.print(); } }
JavaScript
class Process { constructor (program, context, time, rate) { this.id = "proc-" + procId++ // a stack of values this.stack = [] // the operations are also stored in a stack (reverse order) this.operations = program ? [program] : [] // the context is used to store variables with scope this.context = new Context(context) // the current time this.time = typeof time === "number" ? time : 0 // how fast time passes this.rate = typeof rate === "number" ? rate : 1 // bind error to this, to allow destructuring it in commands this.error = this.error.bind(this) } // wait an amount of time wait (time) { this.time += this.rate * time } // The process is agnostic about the commands to interpret step (commands) { const { operations } = this if (operations.length) { const instr = operations.pop() if (instr === null || instr === undefined) { // ignore } else if (typeof instr === "function") { instr(this) } else if (isProgram(instr)) { // if it"s program, and since the operations are stored into an stack, // we need add to the program operations in reverse order for (let i = instr.length - 1; i >= 0; i--) { operations.push(instr[i]) } } else if (isCommand(instr)) { const cmd = commands.resolve(instr) if (typeof cmd === "function") cmd(this) else this.error("step > ", ERR_INSTR_NOT_FOUND, instr) } else { // if it"s a value, push it into the stack this.stack.push(instr) } } } // the `resume` function run all the operations until time is reached resume (commands, time = Infinity, limit = 10000) { const { operations } = this while (--limit > 0 && this.time < time && operations.length) { this.step(commands) } if (limit === 0) throw Error(ERR_LIMIT_REACHED) return operations.length > 0 } // an utility function to write errors error (instr, msg, obj) { console.error(instr, msg, obj, "id", this.id, "time", this.time) } }
JavaScript
class TrainingData { constructor(xs, ys) { this._xs = xs; this._ys = ys; } get xs() { return this._xs; } get ys() { return this._ys; } }
JavaScript
class CustomControlSpacer extends Spacer { /** * Builds the default DOM `className`. * * @return {string} * The DOM `className` for this object. */ buildCSSClass() { return `vjs-custom-control-spacer ${super.buildCSSClass()}`; } /** * Create the `Component`'s DOM element * * @return {Element} * The element that was created. */ createEl() { return super.createEl('div', { className: this.buildCSSClass(), // No-flex/table-cell mode requires there be some content // in the cell to fill the remaining space of the table. textContent: '\u00a0' }); } }
JavaScript
class ElectionSystemAPI { // Singelton instance static #api = null; // Local Python backend #electionSystemServerBaseURL ='/electionSystem'; //Project related #getAllProjectsURL = () => `${this.#electionSystemServerBaseURL}/project`; #getProjectURL = (id) => `${this.#electionSystemServerBaseURL}/project/${id}`; #getProjectForProjectNameURL = (name) => `${this.#electionSystemServerBaseURL}/project-by-name/${name}`; #getProjectForProfessorURL = (id) => `${this.#electionSystemServerBaseURL}/project-by-prof/${id}`; #getProjectForProjecttypeURL = (id) => `${this.#electionSystemServerBaseURL}/project-by-projecttype/${id}`; #addProjectURL = () => `${this.#electionSystemServerBaseURL}/project`; #updateProjectURL = (id) => `${this.#electionSystemServerBaseURL}/project/${id}`; #deleteProjectURL = (id) => `${this.#electionSystemServerBaseURL}/project/${id}`; #getProjectForStateURL = (state) => `${this.#electionSystemServerBaseURL}/project-by-state/${state}`; #getProjectForModuleURL = (id) => `${this.#electionSystemServerBaseURL}/project-by-module/${id}`; //State related #getAllStatesURL = () => `${this.#electionSystemServerBaseURL}/state`; #getStateURL = (id) => `${this.#electionSystemServerBaseURL}/state/${id}`; //Projecttype related #getAllProjecttypesURL = () => `${this.#electionSystemServerBaseURL}/projecttype`; #getProjecttypeURL = (id) => `${this.#electionSystemServerBaseURL}/projecttype/${id}`; #getProjecttypeForProjectURL = (id) => `${this.#electionSystemServerBaseURL}/projects/${id}/projecttype`; #addProjecttypeURL = () => `${this.#electionSystemServerBaseURL}/projecttype`; #updateProjecttypeURL = (id) => `${this.#electionSystemServerBaseURL}/projecttype/${id}`; #deleteProjecttypeURL = (id) => `${this.#electionSystemServerBaseURL}/projecttype/${id}`; //Module related #getAllModulesURL = () => `${this.#electionSystemServerBaseURL}/module`; #getModuleURL = (id) => `${this.#electionSystemServerBaseURL}/module/${id}`; #getModuleForProjectURL = (id) => `${this.#electionSystemServerBaseURL}/projects/${id}/module`; #addModuleURL = () => `${this.#electionSystemServerBaseURL}/module`; #updateModuleURL = (id) => `${this.#electionSystemServerBaseURL}/module/${id}`; #deleteModuleURL = (id) => `${this.#electionSystemServerBaseURL}/module/${id}`; //Grading related #getAllGradesURL = () => `${this.#electionSystemServerBaseURL}/grading` #getGradeURL = (id) => `${this.#electionSystemServerBaseURL}/grading/${id}` #addGradeURL = () => `${this.#electionSystemServerBaseURL}/grading`; #updateGradeURL = (id) => `${this.#electionSystemServerBaseURL}/grade/${id}`; #deleteGradeURL = (id) => `${this.#electionSystemServerBaseURL}/grading/${id}`; //Participation related #getAllParticipationsForProjectURL = (id) => `${this.#electionSystemServerBaseURL}/participation-by-project/${id}`; #getParticipationURL = (id) => `${this.#electionSystemServerBaseURL}/participation/${id}`; #getParticipationsForStudentURL =(id) => `${this.#electionSystemServerBaseURL}/participation-by-student/${id}`; #addParticipationURL = () => `${this.#electionSystemServerBaseURL}/participation`; #updateParticipationURL = (id) => `${this.#electionSystemServerBaseURL}/participation/${id}`; #deleteParticipationURL = (id) => `${this.#electionSystemServerBaseURL}/participation/${id}`; #getParticipationForStudentAndProjectURL =(student_id, project_id) => `${this.#electionSystemServerBaseURL}/participation-by-student-project/${student_id}/${project_id}`; #electionURL = () => `${this.#electionSystemServerBaseURL}/finish-election`; //Semester related #getAllSemesterURL = () => `${this.#electionSystemServerBaseURL}/semester` #addSemesterURL = () => `${this.#electionSystemServerBaseURL}/semester`; #updateSemesterURL = (id) => `${this.#electionSystemServerBaseURL}/semester/${id}`; //Student related #getAllStudentsURL = () => `${this.#electionSystemServerBaseURL}/student`; #getStudentURL = (id) => `${this.#electionSystemServerBaseURL}/student/${id}`; #getStudentForGoogleIDURL = (googleId) => `${this.#electionSystemServerBaseURL}/student-by-google-id/${googleId}`; #getStudentForMailURL = (mail) => `${this.#electionSystemServerBaseURL}/student-by-mail/${mail}`; #addStudentURL =() => `${this.#electionSystemServerBaseURL}/student`; #updateStudentURL = (id) => `${this.#electionSystemServerBaseURL}/student/${id}`; #getStudentsByParticipationsURL =(id)=>`${this.#electionSystemServerBaseURL}/students-by-participations/${id}`; //User related #getAllUsersURL = () => `${this.#electionSystemServerBaseURL}/user`; #addUserURL = () => `${this.#electionSystemServerBaseURL}/user`; #getUserForGoogleIDURL = (googleID) => `${this.#electionSystemServerBaseURL}/user-by-google-id/${googleID}`; #getUserForMailURL = (mail) => `${this.#electionSystemServerBaseURL}/user-by-mail/${mail}`; #getUserForRoleURL = (role) => `${this.#electionSystemServerBaseURL}/user-by-role/${role}`; #getUserURL = (id) => `${this.#electionSystemServerBaseURL}/user/${id}`; #updateUserURL = (id) => `${this.#electionSystemServerBaseURL}/user/${id}`; #deleteUserURL = (id) => `${this.#electionSystemServerBaseURL}/user/${id}`; /** * Get the Singelton instance * * @public */ static getAPI() { if (this.#api == null) { this.#api = new ElectionSystemAPI(); } return this.#api; } /** * Returns a Promise which resolves to a json object. * The Promise returned from fetch() won’t reject on HTTP error status even if the response is an HTTP 404 or 500. * fetchAdvanced throws an Error also an server status errors */ #fetchAdvanced = (url, init) => fetch(url, init) .then(res => { // The Promise returned from fetch() won’t reject on HTTP error status even if the response is an HTTP 404 or 500. if (!res.ok) { throw Error(`${res.status} ${res.statusText}`); } return res.json(); } ) //----------Project related------------------------- /** * Returns a Promise, which resolves to an Array of ProjectBOs * * @public */ getAllProjects(){ return this.#fetchAdvanced(this.#getAllProjectsURL()).then((responseJSON) => { let projectBOs = ProjectBO.fromJSON(responseJSON); return new Promise(function (resolve){ resolve(projectBOs) }) }) } /** * Returns a Promise, which resolves to a ProjectBO * @param {pname} projectname of the project to be retrieved * @public */ getProjectForProjectName(pname){ return this.#fetchAdvanced(this.#getProjectForProjectNameURL(pname)).then((responseJSON) => { let projectBOs = ProjectBO.fromJSON(responseJSON)[0]; return new Promise(function (resolve) { resolve(projectBOs); }) }) } /** * Returns a Promise, which resolves to a ProjectBO * @param {profid} professor id of the project to be retrieved * @public */ getProjectForProfessor(profid){ return this.#fetchAdvanced(this.#getProjectForProfessorURL(profid)).then((responseJSON) => { let projectBOs = ProjectBO.fromJSON(responseJSON); return new Promise(function (resolve) { resolve(projectBOs); }) }) } /** * Returns a Promise, which resolves to a ProjectBO * @param {projecttypeid} projecttype id of the project to be retrieved * @public */ getProjectForProjecttype(projecttypeid){ return this.#fetchAdvanced(this.#getProjectForProjecttypeURL(projecttypeid)).then((responseJSON) => { let projectBOs = ProjecttypeBO.fromJSON(responseJSON); return new Promise(function (resolve) { resolve(projectBOs); }) }) } /** * Returns a Promise, which resolves to a ProjectBO * * @param {state} state of the project to be retrieved * @public */ getProjectForState(state){ return this.#fetchAdvanced(this.#getProjectForStateURL(state)).then((responseJSON) => { let projectBOs = ProjectBO.fromJSON(responseJSON); return new Promise(function (resolve) { resolve(projectBOs); }) }) } /** * Returns a Promise, which resolves to a ProjectBO * * @param {module} module of the project to be retrieved * @public */ getProjectForModule(module){ return this.#fetchAdvanced(this.#getProjectForModuleURL(module)).then((responseJSON) => { let projectBOs = ProjectBO.fromJSON(responseJSON); return new Promise(function (resolve) { resolve(projectBOs); }) }) } /** * Adds a project and returns a Promise, which resolves to a new ProjectBO object * * @param {ProjectBO} projectBO to be added. The ID of the new project is set by the backend * @public */ addProject(projectBO){ return this.#fetchAdvanced(this.#addProjectURL(), { method: 'POST', headers:{ 'Accept': 'application/json, text/plain', 'Content-type': 'application/json', }, body: JSON.stringify(projectBO) }).then((responseJSON) => { let responseProjectBO = ProjectBO.fromJSON(responseJSON)[0]; return new Promise(function (resolve) { resolve(responseProjectBO); }) }) } /** *@param {Number} projectID *@public */ getProject(projectID){ return this.#fetchAdvanced(this.#getProjectURL(projectID)).then((responseJSON) => { let responseProjectBO = ProjectBO.fromJSON(responseJSON)[0]; return new Promise(function (resolve) { resolve(responseProjectBO); }) }) } /** * Updates a project and returns a Promise, which resolves to a ProjectBO. * @param {projectBO} ProjectBO to be updated * @public */ updateProject(project){ return this.#fetchAdvanced(this.#updateProjectURL(project.getID()), { method: 'PUT', headers:{ 'Accept': 'application/json, text/plain', 'Content-type': 'application/json', }, body: JSON.stringify(project) }).then((responseJSON) => { let responseProjectBO = ProjectBO.fromJSON(responseJSON)[0]; return new Promise(function (resolve) { resolve(responseProjectBO); }) }) } /** * Returns a Promise, which resolves to an Array of ProjectBOs * @param {projectID} projectID to be deleted * @public */ deleteProject(projectID){ return this.#fetchAdvanced(this.#deleteProjectURL(projectID), { method: 'DELETE' }).then((responseJSON) => { let responseProjectBO = ProjectBO.fromJSON(responseJSON)[0]; return new Promise(function (resolve) { resolve(responseProjectBO); }) }) } //-------------------Election--------------------------------- election(){ return this.#fetchAdvanced(this.#electionURL()); } //----------State relevant operations------------------------- /** * Returns a Promise, which resolves to an Array of StateBOs * @public */ getAllStates(){ return this.#fetchAdvanced(this.#getAllStatesURL()).then((responseJSON)=> { let states = State.fromJSON(responseJSON); return new Promise(function(resolve){ resolve(states); }) }) } /** * Returns a Promise, which resolves to a stateBO * * @param {stateid} the state of the to be retrieved * @public */ getState(stateid){ return this.#fetchAdvanced(this.#getStateURL(stateid)).then((responseJSON)=> { let state = State.fromJSON(responseJSON)[0]; return new Promise(function(resolve){ resolve(state); }) }) } //----------Projecttype------------------------- /** * Returns a Promise, which resolves to an Array of ProjecttypeBOs * @public */ getAllProjecttypes(){ return this.#fetchAdvanced(this.#getAllProjecttypesURL()).then((responseJSON)=> { let projecttypeBOs =ProjecttypeBO.fromJSON(responseJSON); return new Promise(function(resolve){ resolve(projecttypeBOs); }) }) } /** * Returns a Promise, which resolves to a ProjecttypeBO * @param {projecttypeid} the projecttype id to be retrieved * @public */ getProjecttype(projecttypeid){ return this.#fetchAdvanced(this.#getProjecttypeURL(projecttypeid)).then((responseJSON)=> { let projecttypeBOs = ProjecttypeBO.fromJSON(responseJSON)[0]; return new Promise(function(resolve){ resolve(projecttypeBOs); }) }) } /** * Returns a Promise, which resolves to an Array of ProjecttypeBOs * @param {projectID} the projectid for which the the projecttype should be retrieved * @public */ getProjecttypeForProject(projectID){ return this.#fetchAdvanced(this.#getProjecttypeForProjectURL(projectID)).then((responseJSON) => { let projecttypeBOs = ProjecttypeBO.fromJSON(responseJSON)[0]; return new Promise(function (resolve) { resolve(projecttypeBOs); }) }) } /** * Adds a projecttype and returns a Promise, which resolves to a new projecttypeBO * @param {projecttype} projecttypeBO to be added. The ID of the new projecttype is set by the backend * @public */ addProjecttype(projecttype){ return this.#fetchAdvanced(this.#addProjecttypeURL(), { method: 'POST', headers:{ 'Accept': 'application/json, text/plain', 'Content-type': 'application/json', }, body: JSON.stringify(projecttype) }).then((responseJSON) => { let projecttypeBO = ProjecttypeBO.fromJSON(responseJSON)[0]; return new Promise(function (resolve) { resolve(projecttypeBO); }) }) } /** * Updates a projecttype and returns a Promise, which resolves to a ProjecttypeBO. * * @param {projecttypeBO} projecttypeBO to be updated * @public */ updateProjecttype(projecttypeBO){ return this.#fetchAdvanced(this.#updateProjecttypeURL(projecttypeBO.getID()), { method: 'PUT', headers:{ 'Accept': 'application/json, text/plain', 'Content-type': 'application/json', }, body: JSON.stringify(projecttypeBO) }).then((responseJSON) => { let responseProjecttypeBO = ProjecttypeBO.fromJSON(responseJSON)[0]; return new Promise(function (resolve) { resolve(responseProjecttypeBO); }) }) } /** * Returns a Promise, which resolves to an Array of projecttypeBOs * * @param {projecttypeID} the projecttypeID to be deleted * @public */ deleteProjecttype(projecttypeID){ return this.#fetchAdvanced(this.#deleteProjecttypeURL(projecttypeID), { method: 'DELETE' }).then((responseJSON) => { let responseProjecttypeBO = ProjecttypeBO.fromJSON(responseJSON)[0]; return new Promise(function (resolve) { resolve(responseProjecttypeBO); }) }) } //----------Module relevant------------------------- /** * Returns a Promise, which resolves to an Array of ModuleBOs * @public */ getAllModules(){ return this.#fetchAdvanced(this.#getAllModulesURL()).then((responseJSON) => { let responseModuleBOs = ModuleBO.fromJSON(responseJSON); return new Promise(function (resolve){ resolve(responseModuleBOs) }) }) } /** * Returns a Promise, which resolves to a ModuleBO * @param {moduleid} the module id to be retrieved * @public */ getModule(moduleid){ return this.#fetchAdvanced(this.#getModuleURL(moduleid)) .then((responseJSON) => { let responseModuleBOs = ModuleBO.fromJSON(responseJSON)[0]; return new Promise(function (resolve) { resolve(responseModuleBOs); }) }) } /** * Returns a Promise, which resolves to an Array of ModuleBOs * @param {projectID} project id for which the the module should be retrieved * @public */ getModuleForProject(projectID){ return this.#fetchAdvanced(this.#getModuleForProjectURL(projectID)) .then((responseJSON) => { let responseModuleBOs = ModuleBO.fromJSON(responseJSON)[0]; return new Promise(function (resolve) { resolve(responseModuleBOs); }) }) } /* Adds a module and returns a Promise, which resolves to a new ModuleBO object * @param {module} ModuleBO to be added. The ID of the new module is set by the backend * @public */ addModule(module){ return this.#fetchAdvanced(this.#addModuleURL(), { method: 'POST', headers:{ 'Accept': 'application/json, text/plain', 'Content-type': 'application/json', }, body: JSON.stringify(module) }).then((responseJSON) => { let responseModuleBO = ModuleBO.fromJSON(responseJSON)[0]; return new Promise(function (resolve) { resolve(responseModuleBO); }) }) } /** * Updates a module and returns a Promise, which resolves to a ModuleBO. * @param {moduleBO} the module BO to be updated * @public */ updateModule(moduleBO){ return this.#fetchAdvanced(this.#updateModuleURL(moduleBO.getID()), { method: 'PUT', headers:{ 'Accept': 'application/json, text/plain', 'Content-type': 'application/json', }, body: JSON.stringify(moduleBO) }).then((responseJSON) => { let responseModuleBO = ModuleBO.fromJSON(responseJSON)[0]; return new Promise(function (resolve) { resolve(responseModuleBO); }) }) } /** * Returns a Promise, which resolves to an Array of ModuleBOs * @param {moduleID} customerID to be deleted * @public */ deleteModule(moduleID){ return this.#fetchAdvanced(this.#deleteModuleURL(moduleID), { method: 'DELETE' }).then((responseJSON) => { let responseModuleBO = ModuleBO.fromJSON(responseJSON)[0]; return new Promise(function (resolve) { resolve(responseModuleBO); }) }) } //----------Grading relevant operation------------------------- /** * Returns a Promise, which resolves to an Array of GrandingBOs * @public */ getAllGrades(){ return this.#fetchAdvanced(this.#getAllGradesURL()).then((responseJSON)=> { let responseGradingBOs = GradingBO.fromJSON(responseJSON); console.info('response' + responseGradingBOs); return new Promise(function(resolve){ resolve(responseGradingBOs); }) }) } /** * Returns a Promise, which resolves to a GradingBO * @param {gradeID} gradingID to be retrieved * @public */ getGrade(gradeID){ return this.#fetchAdvanced(this.#getGradeURL(gradeID)).then((responseJSON)=> { let responseGradingBOs = GradingBO.fromJSON(responseJSON)[0]; return new Promise(function(resolve){ resolve(responseGradingBOs); }) }) } /** * Adds a grade and returns a Promise, which resolves to a new GradingBO object * @param {grading} gradingBO to be added. The ID of the new grade is set by the backend * @public */ addGrade(grading){ return this.#fetchAdvanced(this.#addGradeURL(), { method: 'POST', headers:{ 'Accept': 'application/json, text/plain', 'Content-type': 'application/json', }, body: JSON.stringify(grading) }).then((responseJSON) => { let responseGradeBO = GradingBO.fromJSON(responseJSON)[0]; return new Promise(function (resolve) { resolve(responseGradeBO); }) }) } /** * Updates a gradeand returns a Promise, which resolves to a GradingBO. * * @param {gradingBO} the gradingBO to be updated * @public */ updateGrade(gradingBO){ return this.#fetchAdvanced(this.#updateGradeURL(gradingBO.getID()), { method: 'PUT', headers:{ 'Accept': 'application/json, text/plain', 'Content-type': 'application/json', }, body: JSON.stringify(gradingBO) }).then((responseJSON) => { let responseGradingBO = GradingBO.fromJSON(responseJSON)[0]; return new Promise(function (resolve) { resolve(responseGradingBO); }) }) } /** * Returns a Promise, which resolves to an Array of GradingBOs * @param {gradeID} the gradingID to be deleted * @public */ deleteGrade(gradeID){ return this.#fetchAdvanced(this.#deleteGradeURL(gradeID), { method: 'DELETE' }).then((responseJSON) => { let responseGradingBO = GradingBO.fromJSON(responseJSON)[0]; return new Promise(function (resolve) { resolve(responseGradingBO); }) }) } //----------Participation relevant operations------------------------- /** * Returns a Promise, which resolves to an Array of ParticipationBOs * @param {ProjectID} projectID for which the the participations should be retrieved * @public */ getAllParticipationsForProject(projectID){ return this.#fetchAdvanced(this.#getAllParticipationsForProjectURL(projectID)) .then((responseJSON) => { let responseParticipationBOs = ParticipationBO.fromJSON(responseJSON); return new Promise(function (resolve) { resolve(responseParticipationBOs); }) }) } /** * Returns a Promise, which resolves to a ParticipationBO * @param {participationID} participationID to be retrieved * @public */ getParticipation(participationID){ return this.#fetchAdvanced(this.#getParticipationURL(participationID)) .then((responseJSON) => { let responseParticipationBOs = ParticipationBO.fromJSON(responseJSON)[0]; return new Promise(function (resolve) { resolve(responseParticipationBOs); }) }) } /** * Returns a Promise, which resolves to an Array of ParticipationBOs * @param {studentID} studentID for which the the participation should be retrieved * @public */ getParticipationsForStudent(studentID){ return this.#fetchAdvanced(this.#getParticipationsForStudentURL(studentID)) .then((responseJSON) => { let responseParticipationBOs = ParticipationBO.fromJSON(responseJSON); return new Promise(function (resolve) { resolve(responseParticipationBOs); }) }) } /** * Returns a Promise, which resolves to the new ParticipationBO * @param {participation} participation object to be added. The ID of the new grade is set by the backend. * @public */ addParticipation(participation){ return this.#fetchAdvanced(this.#addParticipationURL(), { method: 'POST', headers:{ 'Accept': 'application/json, text/plain', 'Content-type': 'application/json', }, body: JSON.stringify(participation) }).then((responseJSON) => { let responseParticipationBO = ParticipationBO.fromJSON(responseJSON)[0]; return new Promise(function (resolve) { resolve(responseParticipationBO); }) }) } /* * Updates a participation and returns a Promise, which resolves to a ParticipationBO. * @param {ParticipationBO} participationBO to be updated * @public */ updateParticipation(participationBO){ return this.#fetchAdvanced(this.#updateParticipationURL(participationBO.getID()), { method: 'PUT', headers:{ 'Accept': 'application/json, text/plain', 'Content-type': 'application/json', }, body: JSON.stringify(participationBO) }).then((responseJSON) => { let responseParticipationBO = ParticipationBO.fromJSON(responseJSON)[0]; return new Promise(function (resolve) { resolve(responseParticipationBO); }) }) } /** * Deletes the given participation and returns a Promise, which resolves to an ParticipationBO * @param participationID to be deleted * @public */ deleteParticipation(participationID){ return this.#fetchAdvanced(this.#deleteParticipationURL(participationID), { method: 'DELETE' }).then((responseJSON) => { let responseParticipationBO = ParticipationBO.fromJSON(responseJSON)[0]; return new Promise(function (resolve) { resolve(responseParticipationBO); }) }) } /** * Returns a Promise, which resolves to an Array of ParticipationBOs * @param {studentID, projectID} studentID, projectID for which the the participation should be retrieved * @public */ getParticipationForStudentAndProject(studentID, projectID){ return this.#fetchAdvanced(this.#getParticipationForStudentAndProjectURL(studentID, projectID)) .then((responseJSON) => { let responseParticipationBOs = ParticipationBO.fromJSON(responseJSON)[0]; return new Promise(function (resolve) { resolve(responseParticipationBOs); }) }) } //----------Semester relevant operations------------------------- /* Returns a Promise, which resolves to an Array of SemesterBOs*/ getAllSemester(){ return this.#fetchAdvanced(this.#getAllSemesterURL()).then((responseJSON) => { let responseSemesterBOs = SemesterBO.fromJSON(responseJSON); return new Promise(function (resolve){ resolve(responseSemesterBOs) }) }) } /** * Adds a semester and returns a Promise, which resolves to a new SemesterBO object * @param {SemesterBO} semesterBO to be added. The ID of the new semester is set by the backend * @public */ addSemester(semester){ return this.#fetchAdvanced(this.#addSemesterURL(), { method: 'POST', headers:{ 'Accept': 'application/json, text/plain', 'Content-type': 'application/json', }, body: JSON.stringify(semester) }).then((responseJSON) => { let responseSemesterBO = SemesterBO.fromJSON(responseJSON)[0]; return new Promise(function (resolve) { resolve(responseSemesterBO); }) }) } /** * Updates a semester and returns a Promise, which resolves to a SemesterBO. * @param {semester} SemesterBO to be updated * @public */ updateSemester(semester){ return this.#fetchAdvanced(this.#updateSemesterURL(semester.getID()), { method: 'PUT', headers:{ 'Accept': 'application/json, text/plain', 'Content-type': 'application/json', }, body: JSON.stringify(semester) }).then((responseJSON) => { let responseSemesterBO = SemesterBO.fromJSON(responseJSON); return new Promise(function (resolve) { resolve(responseSemesterBO); }) }) } //----------Student relevant operation------------------------- /** * Returns a Promise, which resolves to an Array of StudentBOs * @public */ getAllStudents(){ return this.#fetchAdvanced(this.#getAllStudentsURL()).then((responseJSON) => { let studentBOs = StudentBO.fromJSON(responseJSON); return new Promise(function (resolve){ resolve(studentBOs) }) }) } /** * Returns a Promise, which resolves to a StudentBO * @param {studentID} studentID to be retrieved * @public */ getStudent(studentID){ return this.#fetchAdvanced(this.#getStudentURL(studentID)) .then((responseJSON) => { let responseStudentBOs = StudentBO.fromJSON(responseJSON)[0]; return new Promise(function (resolve) { resolve(responseStudentBOs); }) }) } /** * Returns a Promise, which resolves to a StudentBOs * @param {googleID} googleID to be retrieved * @public */ getStudentForGoogleID(googleID){ return this.#fetchAdvanced(this.#getStudentForGoogleIDURL(googleID)) .then((responseJSON) => { let responseStudentBOs = StudentBO.fromJSON(responseJSON)[0]; return new Promise(function (resolve) { resolve(responseStudentBOs); }) }) } /** * Returns a Promise, which resolves to an Array of StudentBOs * @param {mail} mail for which the the Student should be retrieved * @public */ getStudentForMail(mail){ return this.#fetchAdvanced(this.#getStudentForMailURL(mail)) .then((responseJSON) => { let responseStudentBOs = StudentBO.fromJSON(responseJSON)[0]; return new Promise(function (resolve) { resolve(responseStudentBOs); }) }) } /** * Adds a student and returns a Promise, which resolves to a new StudentBO object * @param {StudentBO} studentBO to be added. The ID of the new student is set by the backend * @public */ addStudent(student){ return this.#fetchAdvanced(this.#addStudentURL(), { method: 'POST', headers:{ 'Accept': 'application/json, text/plain', 'Content-type': 'application/json', }, body: JSON.stringify(student) }).then((responseJSON) => { let responseStudentBO = StudentBO.fromJSON(responseJSON)[0]; return new Promise(function (resolve) { resolve(responseStudentBO); }) }) } /** * Updates a student and returns a Promise, which resolves to a StudentBO. * @param {StudentBO} studentBO to be updated * @public */ updateStudent(studentBO){ return this.#fetchAdvanced(this.#updateStudentURL(studentBO.getID()), { method: 'PUT', headers:{ 'Accept': 'application/json, text/plain', 'Content-type': 'application/json', }, body: JSON.stringify(studentBO) }).then((responseJSON) => { let responseStudentBO = UserBO.fromJSON(responseJSON)[0]; return new Promise(function (resolve) { resolve(responseStudentBO); }) }) } /** * Returns a Promise, which resolves to an Array of StudentBOs * @param {projectID} projectID for which the the students should be retrieved * @public */ getStudentByParticipations(projectID){ return this.#fetchAdvanced(this.#getStudentsByParticipationsURL(projectID)) .then((responseJSON) => { let responseStudentBOs = StudentBO.fromJSON(responseJSON); return new Promise(function (resolve) { resolve(responseStudentBOs); }) }) } //----------User relevant operations------------------------- /** * Returns a Promise, which resolves to an Array of UserBOs * @public */ getAllUsers(){ return this.#fetchAdvanced(this.#getAllUsersURL()).then((responseJSON) => { let userBOs = UserBO.fromJSON(responseJSON); return new Promise(function (resolve){ resolve(userBOs) }) }) } /** * Adds a user and returns a Promise, which resolves to a new UserBO object * @param {userBO} userBO to be added. The ID of the new user is set by the backend * @public */ addUser(user){ return this.#fetchAdvanced(this.#addUserURL(), { method: 'POST', headers:{ 'Accept': 'application/json, text/plain', 'Content-type': 'application/json', }, body: JSON.stringify(user) }).then((responseJSON) => { let responseUserBO = UserBO.fromJSON(responseJSON)[0]; return new Promise(function (resolve) { resolve(responseUserBO); }) }) } /** * Returns a Promise, which resolves to a UserBO * @param {userID} userID to be retrieved * @public */ getUser(userID){ return this.#fetchAdvanced(this.#getUserURL(userID)) .then((responseJSON) => { let responseUserBOs = UserBO.fromJSON(responseJSON)[0]; return new Promise(function (resolve) { resolve(responseUserBOs); }) }) } /** * Returns a Promise, which resolves to a UserBO * @param {googleID} googleID to be retrieved * @public */ getUserForGoogleID(googleID){ return this.#fetchAdvanced(this.#getUserForGoogleIDURL(googleID)) .then((responseJSON) => { let responseUserBOs = UserBO.fromJSON(responseJSON)[0]; return new Promise(function (resolve) { resolve(responseUserBOs); }) }) } /** * Returns a Promise, which resolves to a UserBO * * @param {role} role for which the user should be retrieved * @public */ getUserForRole(role){ return this.#fetchAdvanced(this.#getUserForRoleURL(role)) .then((responseJSON) => { let responseUserBOs = UserBO.fromJSON(responseJSON); return new Promise(function (resolve) { resolve(responseUserBOs); }) }) } /** * Returns a Promise, which resolves to a UserBO * @param {mail} mail for which the user should be retrieved * @public */ getUserForMail(mail){ return this.#fetchAdvanced(this.#getUserForMailURL(mail)) .then((responseJSON) => { let responseUserBOs = UserBO.fromJSON(responseJSON)[0]; return new Promise(function (resolve) { resolve(responseUserBOs); }) }) } /** * Updates a user and returns a Promise, which resolves to a UserBO. * @param {userBO} userBO to be updated * @public */ updateUser(userBO){ return this.#fetchAdvanced(this.#updateUserURL(userBO.getID()), { method: 'PUT', headers:{ 'Accept': 'application/json, text/plain', 'Content-type': 'application/json', }, body: JSON.stringify(userBO) }).then((responseJSON) => { let responseUserBO = UserBO.fromJSON(responseJSON)[0]; return new Promise(function (resolve) { resolve(responseUserBO); }) }) } /** * Deletes the given user and returns a Promise, which resolves to an UserBO * @param userID to be deleted * @public */ deleteUser(userID){ return this.#fetchAdvanced(this.#deleteUserURL(userID), { method: 'DELETE' }).then((responseJSON) => { let responseUserBO = UserBO.fromJSON(responseJSON)[0]; return new Promise(function (resolve) { resolve(responseUserBO); }) }) } }
JavaScript
class TerrainMap { /** * @param {number} tileSize The size of a tile. Must be a power of two. * @param {number} scale The scale based on the original heightmap size. */ constructor(tileSize, scale = 1.0) { this.tileSize = tileSize; this.scale = scale; // Must be computed post-load. this.elementSize = 1 * this.scale; this.tiles = null; this.TerrainTileClass = TerrainTile; } /** * Sets a custom tile implementation for use within the terrain map. * @param {TerrainTile} terrainTileClass */ setTerrainTileClass(terrainTileClass) { this.TerrainTileClass = terrainTileClass; return this; } /** * Loads the terrain map from a 3D model. * @param {string} modelUrl * @async */ async loadFromFile(modelUrl) { const model = await Models.get().loadModelWithoutStorage(modelUrl); const heightmapObj = model.getObjectByName('Grid'); const bufferGeometry = heightmapObj.geometry; const geometry = new THREE.Geometry().fromBufferGeometry(bufferGeometry); geometry.mergeVertices(); this.elementSize = this.computeGeometryElementSize_(geometry); const heightmap = this.extractHeightmapFromGeometry(geometry); geometry.dispose(); // Compute how large each element will be within a tile. this.tiles = this.breakIntoTiles_(heightmap); await this.buildTiles_(); this.positionTiles_(); } /** * Loads the terrain map from a geometry. * @param {THREE.Geometry} geometry * @async */ async loadFromGeometry(geometry) { geometry.mergeVertices(); this.elementSize = this.computeGeometryElementSize_(geometry); const heightmap = this.extractHeightmapFromGeometry(geometry); geometry.dispose(); // Compute how large each element will be within a tile. this.tiles = this.breakIntoTiles_(heightmap); await this.buildTiles_(); this.positionTiles_(); } /** * Extracts elevation data from the given geometry and forms a generic matrix. * The y element of each vertex is meant to be the height. * @param {THREE.Geometry} geometry * @returns {Array<Array<number>} */ extractHeightmapFromGeometry(geometry) { const vertices = geometry.vertices; // Preprocess vertices first. // TODO: This is inefficient, and also depends on stable sorting. vertices.sort((a, b) => a.x - b.x); vertices.sort((a, b) => b.z - a.z); // Extract values. const dimensions = Math.sqrt(vertices.length); if (parseInt(dimensions) != dimensions) { return console.error('Dimensions not an integer, geometry not square.'); } const matrix = new Array(); for (let i = 0; i < dimensions; i++) { const row = new Array(); for (let j = 0; j < dimensions; j++) { const vIndex = i * dimensions + j; const value = vertices[vIndex].y; row.push(value); } matrix.push(row); } return matrix; } /** * Compute the size of each element within a tile, based on the original * geometry dimensions as well as how many tiles there will be. * @param {THREE.Geometry} geometry * @return {number} */ computeGeometryElementSize_(geometry) { geometry.computeBoundingBox(); const width = geometry.boundingBox.max.x - geometry.boundingBox.min.x; const numVertices = Math.sqrt(geometry.vertices.length); return (width / numVertices) * this.scale; } /** * Breaks the given heightmap into tiles. * @param {Array<Array<number>>} heightmap * @async * @protected */ breakIntoTiles_(heightmap) { // Determine how many tiles we need in a row on the given map. const tilesInMapRow = (heightmap.length - 1) / this.tileSize; // We can throw all tiles into an array, as they each keep their own // coordinates relative to the map. const tiles = new Array(); // Iterate to create tiles. One tile will be filled at a time. for (let i = 0; i < tilesInMapRow; i++) { for (let j = 0; j < tilesInMapRow; j++) { const tile = new this.TerrainTileClass( this.tileSize, this.scale, this.elementSize ) .withPhysics() .setCoordinates(i, j) .fromParentMatrix(heightmap); tiles.push(tile); } } return tiles; } /** * Loads all tile textures before the terrain map is finished loading. * @async * @private */ async buildTiles_() { const promises = new Array(); this.tiles.forEach((tile) => promises.push(tile.build())); return Promise.all(promises); } /** * Positions all tiles in the world so that they align properly. * @private */ positionTiles_() { this.tiles.forEach((tile) => { const coords = tile.getCoordinates(); const tilesInMapRow = Math.sqrt(this.tiles.length); // We want the middle of the terrain map to be at the world origin, so we // create an offset based on half of the terrain map width. const tileOffset = tilesInMapRow / 2 - 0.5; const x = (coords.x - tileOffset) * this.tileSize * this.elementSize; const z = -(coords.y - tileOffset) * this.tileSize * this.elementSize; tile.setPosition(new THREE.Vector3(x, 0, z)); }); } }
JavaScript
class TimelineView extends Component { /* * Overrides default constructor. */ constructor(props) { super(props); this.updateView = this.updateView.bind(this); this.getTimelineItems = this.getTimelineItems.bind(this); this.getTimelineOptions = this.getTimelineOptions.bind(this); this.getTimeLineGroups = this.getTimeLineGroups.bind(this); this.getLocalizedString = locale.getLocalizedString.bind(props.GLOBAL_LANGUAGE); } /* * Overrides React method. */ componentWillUpdate(nextProps, nextState) { if (this.props.GLOBAL_LANGUAGE !== nextProps.GLOBAL_LANGUAGE) { this.getLocalizedString = locale.getLocalizedString.bind(nextProps.GLOBAL_LANGUAGE); } } /* * Updates component state. */ updateView(value) { return event => this.props.dispatch(actions[event.target.id](!value)); } /* * Gets timeline items. */ getTimelineItems(data) { const GROUP_WORK = 1; const GROUP_EDUCATION = 2; const GROUP_PROJECTS = 3; let work = []; let projects = []; let education = []; if (data) { if (data.experience) { for (let prop of data.experience.data) { if (prop.visible) { work.push({ start: new Date(prop.startdate), end: new Date(prop.enddate), content: prop.title, title: `<h5>${prop.title}</h5><p>${prop.name}<br/>${prop.description}</p>`, group: GROUP_WORK, className: 'timeline-item-tuni' }); } } } if (data.projects) { for (let prop of data.projects.data) { if (prop.visible) { projects.push({ start: new Date(prop.completion_date), type: 'box', title: `<h5>${prop.name}</h5><p>${prop.description}</p>`, content: prop.name, group: GROUP_PROJECTS, className: 'timeline-item-tuni' }); } } } if (data.education) { for (let prop of data.education.data) { if (prop.visible) { education.push({ start: new Date(prop.startdate), end: new Date(prop.enddate), title: `<h5>${prop.type === 'education' ? prop.field_name : prop.course_name}</h5><p>${prop.type === 'education' ? prop.school_name : prop.provider_name}</p>`, content: `${prop.type === 'education' ? prop.field_name : prop.course_name}`, group: GROUP_EDUCATION, className: 'timeline-item-tuni' }); } } } } return work.concat(projects, education); } /* * Gets timeline groups. */ getTimeLineGroups() { return [ { id: 1, content: this.getLocalizedString(locale.TIMELINE_WORK), visible: this.props.SHOW_WORK }, { id: 2, content: this.getLocalizedString(locale.TIMELINE_EDUCATION), visible: this.props.SHOW_EDUCATION }, { id: 3, content: this.getLocalizedString(locale.TIMELINE_PROJECTS), visible: this.props.SHOW_PROJECTS } ]; } /* * Gets timeline options. */ getTimelineOptions() { return { width: '100%', stack: true, showMajorLabels: true, showCurrentTime: true, min: new Date(Date.now() - 1000 * 60 * 60 * 24 * 365 * 100), // Current date - 100 years max: new Date(Date.now() + 1000 * 60 * 60 * 24 * 365), // Current date + one year zoomMin: 1000 * 60 * 60 * 24 * 7, // One week zoomMax: 1000 * 60 * 60 * 24 * 365 * 25, // 25 years start: new Date(Date.now() - 1000 * 60 * 60 * 24 * 365 * 20), end: new Date(Date.now()) }; } /* * Renders component. */ render() { const propertyWork = { text: this.getLocalizedString(this.props.SHOW_WORK ? locale.TIMELINE_HIDE_WORK : locale.TIMELINE_SHOW_WORK), variant: this.props.SHOW_WORK ? 'info' : 'secondary' }; const propertyEducation = { text: this.getLocalizedString(this.props.SHOW_EDUCATION ? locale.TIMELINE_HIDE_EDUCATION : locale.TIMELINE_SHOW_EDUCATION), variant: this.props.SHOW_EDUCATION ? 'info' : 'secondary' }; const propertyProjects = { text: this.getLocalizedString(this.props.SHOW_PROJECTS ? locale.TIMELINE_HIDE_PROJECTS : locale.TIMELINE_SHOW_PROJECTS), variant: this.props.SHOW_PROJECTS ? 'info' : 'secondary' }; const data = this.props.GLOBAL_DATA; const initData = { experience: { data: [ { 'enddate': new Date(Date.now()), 'achievements': [], 'visible': true, 'name': 'placeholder', 'description': 'placeholder', 'id': 1, 'type': 'place', 'startdate': new Date(Date.now() - 1000 * 60 * 60 * 24 * 365 * 20), 'title': 'placeholder' } ] } }; return ( <Container id="page"> <Row> <Col xs={12}> <ButtonToolbar> <Button id="showWork" variant={propertyWork.variant} onClick={this.updateView(this.props.SHOW_WORK)}>{propertyWork.text}</Button> <Button id="showEducation" variant={propertyEducation.variant} onClick={this.updateView(this.props.SHOW_EDUCATION)}>{propertyEducation.text}</Button> <Button id="showProjects" variant={propertyProjects.variant} onClick={this.updateView(this.props.SHOW_PROJECTS)}>{propertyProjects.text}</Button> </ButtonToolbar> </Col> </Row> <Row> <Col xs={12} id="timeline"> <Timeline items={this.getTimelineItems(data ? data : initData)} options={this.getTimelineOptions()} groups={this.getTimeLineGroups()}/> </Col> </Row> </Container> ); } }
JavaScript
class DistoMachineNode extends CompositeAudioNode { /** * @type {ParamMgrNode} */ _wamNode = undefined; reverbImpulses = [ { name: "Fender Hot Rod", url: "/assets/impulses/reverb/cardiod-rear-levelled.wav", }, { name: "PCM 90 clean plate", url: "/assets/impulses/reverb/pcm90cleanplate.wav", }, { name: "Scala de Milan", url: "/assets/impulses/reverb/ScalaMilanOperaHall.wav", }, ]; cabinetImpulses = [ { name: "Marshall 1960, axis", url: "/assets/impulses/cabinet/Marshall1960.wav", }, { name: "Vintage Marshall 1", url: "/assets/impulses/cabinet/Block%20Inside.wav", }, { name: "Vox Custom Bright 4x12 M930 Axis 1", url: "/assets/impulses/cabinet/voxCustomBrightM930OnAxis1.wav", }, { name: "Fender Champ, axis", url: "assets/impulses/cabinet/FenderChampAxisStereo.wav", }, { name: "Mesa Boogie 4x12", url: "/assets/impulses/cabinet/Mesa-OS-Rectifier-3.wav", }, { name: "001a-SM57-V30-4x12", url: "/assets/impulses/cabinet/KalthallenCabsIR/001a-SM57-V30-4x12.wav", }, { name: "028a-SM7-V30-4x12", url: "/assets/impulses/cabinet/KalthallenCabsIR/028a-SM7-V30-4x12.wav", }, { name: "034a-SM58-V30-4x12", url: "/assets/impulses/cabinet/KalthallenCabsIR/034a-SM58-V30-4x12.wav", }, { name: "022a-MD21-V30-4x12", url: "/assets/impulses/cabinet/KalthallenCabsIR/022a-MD21-V30-4x12.wav", }, { name: "023a-MD21-V30-4x12", url: "/assets/impulses/cabinet/KalthallenCabsIR/023a-MD21-V30-4x12.wav", }, { name: "024a-MD21-G12T75-4x12", url: "/assets/impulses/cabinet/KalthallenCabsIR/024a-MD21-G12T75-4x12.wav", }, { name: "009a-SM57-G12T75-4x12", url: "/assets/impulses/cabinet/KalthallenCabsIR/009a-SM57-G12T75-4x12.wav", }, ]; /** * @param {ParamMgrNode} wamNode */ // Mandatory. setup(wamNode) { this._wamNode = wamNode; this.connectNodes(); } constructor(context, options) { super(context, options); // add absolute URL to relative urls... this.fixImpulseURLs(); this.createNodes(); } fixImpulseURLs() { let relativeURL; this.reverbImpulses.forEach(impulse => { relativeURL = impulse.url; impulse.url = getAssetUrl(relativeURL); }); this.cabinetImpulses.forEach(impulse => { relativeURL = impulse.url; impulse.url = getAssetUrl(relativeURL); }); } /* ######### Personnal code for the web audio graph ######### */ createNodes() { // mandatory, will create defaul input and output /* this.outputNode = this.context.createGain(); this.dryGainNode = this.context.createGain(); this.wetGainNode = this.context.createGain(); this.lowpassLeft = this.context.createBiquadFilter(); this.lowpassLeft.type = 'lowpass'; this.lowpassLeft.frequency.value = 147; this.lowpassLeft.Q.value = 0.7071; this.bandpass1Left = this.context.createBiquadFilter(); this.bandpass1Left.type = 'bandpass'; this.bandpass1Left.frequency.value = 587; this.bandpass1Left.Q.value = 0.7071; this.bandpass2Left = this.context.createBiquadFilter(); this.bandpass2Left.type = 'bandpass'; this.bandpass2Left.frequency.value = 2490; this.bandpass2Left.Q.value = 0.7071; this.highpassLeft = this.context.createBiquadFilter(); this.highpassLeft.type = 'highpass'; this.highpassLeft.frequency.value = 4980; this.highpassLeft.Q.value = 0.7071; this.overdrives = []; for (let i = 0; i < 4; i++) { this.overdrives[i] = this.context.createWaveShaper(); this.overdrives[i].curve = this.getDistortionCurve(this.normalize(0.5, 0, 150)); } */ this._outputGain = this.context.createGain(); this._inputGain = this.context.createGain(); this.equalizer = new EqualizerDisto(this.context); this.ampReverb = new ConvolverDisto( this.context, this.reverbImpulses, "reverbImpulses" ); this.cabinetSim = new ConvolverDisto( this.context, this.cabinetImpulses, "cabinetImpulses" ); this.boost = new BoostDisto(this.context); this.amp = new AmpDisto( this.context, this.boost, this.equalizer, this.ampReverb, this.cabinetSim ); } connectNodes() { /* this.connect(this.amp.input); // shihong.... this.amp.output.connect(this._outputGain); this._output = this._outputGain; */ this.connect(this._inputGain); this._inputGain.connect(this.amp.input); this.amp.output.connect(this._outputGain); this._output = this._outputGain; this._input = this._inputGain; } setParam(key, value) { try { this[key] = value; } catch (error) { console.warn("this plugin does not implement this param"); } } set volume(val) { //this.params.volume = val; this.amp.changeOutputGain(val); } set master(val) { //this.params.master = val; this.amp.changeMasterVolume(val); } set drive(val) { //this.params.drive = val; this.amp.changeDrive(val); } set bass(val) { //this.params.bass = val; this.amp.changeBassFilterValue(val); } set middle(val) { //this.params.middle = val; this.amp.changeMidFilterValue(val); } set treble(val) { //this.params.treble = val; this.amp.changeTrebleFilterValue(val); } set reverb(val) { //this.params.reverb = val; this.amp.changeReverbGain(val); } set presence(val) { //this.params.presence = val; this.amp.changePresenceFilterValue(val); } set preset(val) { console.log("########### SET PRESET val=" + val + "#######"); //this.params.preset = val; this.amp.setPresetByIndex(this, val); } set LS1Freq(val) { //this.params.LS1Freq = val; this.amp.changeLowShelf1FrequencyValue(val); } set LS1Gain(val) { //this.params.LS1Gain = val; this.amp.changeLowShelf1GainValue(val); } set LS2Freq(val) { //this.params.LS2Freq = val; this.amp.changeLowShelf2FrequencyValue(val); } set LS2Gain(val) { //this.params.LS2Gain = val; this.amp.changeLowShelf2GainValue(val); } set LS3Freq(val) { //this.params.LS3Freq = val; this.amp.changeLowShelf3FrequencyValue = val; } set LS3Gain(val) { //this.params.LS3Gain = val; this.amp.changeLowShelf3GainValue(val); } set gain1(val) { //this.params.gain1 = val; this.amp.changePreampStage1GainValue(val); } set gain2(val) { //this.params.gain2 = val; this.amp.changePreampStage2GainValue(val); } set HP1Freq(val) { //this.params.HP1Freq = val; this.amp.changeHighPass1FrequencyValue(val); } set HP1Q(val) { //this.params.HP1Q = val; this.amp.changeHighPass1QValue(val); } set EQ(val) { //this.params.EQ = val; this.amp.changeEQValues(val); } set CG(val) { //this.params.CG = val; this.amp.changeRoom(val); } isEnabled = true; set status(_sig) { if (this.isEnabled === _sig) return; this.isEnabled = _sig; if (_sig) { //console.log('BYPASS MODE OFF FX RUNNING'); this._input.disconnect(); this._input.connect(this.amp.input); } else { //console.log('BYPASS MODE ON'); this._input.disconnect(); this._input.connect(this._output); } } // MANDATORY : redefine these methods // eslint-disable-next-line class-methods-use-this getParamValue(name) { return this._wamNode.getParamValue(name); } setParamValue(name, value) { return this._wamNode.setParamValue(name, value); } getParamsValues() { return this._wamNode.getParamsValues(); } setParamsValues(values) { return this._wamNode.setParamsValues(values); } }
JavaScript
class Service extends EventEmitter { /** * * @param {server} config */ constructor(config) { super(); m_private.set(this, /** @type {servicePrivate} */ { config: new ServerConfiguration(config), containerMap: new Map(), wsClients: new Map(), wsApplets: new Map() }); process.nextTick(Initialize.bind(this)); } /** * * @param {string} [name] Optional applet web path * @returns {server|appConfig} */ toJSON(name) { /** @type {ServerConfiguration} */ let config = m_private.get(this).config; if (!name) return config.toJSON(); // if the applet name has been specified, return // just applet appropriate information // hide cert and key paths, etc. let result = {}; result.applet = config.applets.find(applet => applet.container == name); result.applet = result.applet ? result.applet.toJSON() : null; result.errorTemplate = config.errorTemplate; for (let protocol in config.protocols) { result[protocol] = { port: config.protocols[protocol].port, listen: config.protocols[protocol].listen, websockets: config.protocols[protocol].websockets, ssl: config.protocols[protocol].ssl }; } return result; } }
JavaScript
class Controller { constructor (el) { this.el = el this.minAge = ageSchema.min this.maxAge = ageSchema.max } onClick (e) { e.stopImmediatePropagation() console.log('Bonjour') } removeAllHandlers (e) { this.el.off() } validate () { // Get the schema and validate function const data = this.el.props // Call the validator const result = { ok: validate(data) } // Get the errors if in an invalid state if (!result.ok) { result.errors = validate.errors } return result } }
JavaScript
class GamepadEventProcessor extends EventProcessor { /** * Constructor * @param {Game} game */ constructor(game) { super(game); } /** * Process gamepad event * @param {Event} event */ process(event) { } }
JavaScript
class Debounce { /** * Create a Debounce. * * @param {Function|GeneratorFunction|AsyncFunction} func * @param {int} millis * * @returns {Function} */ constructor(func, millis) { if (! isFunction(func)) { throw new LogicException('Trying to bind a non-function object'); } /** * @type {int} * * @private */ this._wait = millis; /** * @type {Function|GeneratorFunction} * * @private */ this._func = func; /** * @type {*} * * @private */ this._result = undefined; /** * @type {Object} * * @private */ this._timerId = undefined; /** * @type {int} * * @private */ this._lastCallTime = undefined; /** * @type {int} * * @private */ this._timeSinceLastCall = undefined; /** * @type {*[]} * * @private */ this._lastArgs = undefined; /** * @type {Object} * * @private */ this._lastThis = undefined; const self = this; function debounced(...args) { const time = Date.now(); const isInvoking = self._shouldInvoke(time); self._lastArgs = args; self._lastThis = this; self._lastCallTime = time; if (isInvoking && self._timerId === undefined) { self._timerId = setTimeout(self._timerExpired.bind(self), self._wait); return self._result; } if (self._timerId === undefined) { self._timerId = setTimeout(self._timerExpired.bind(self), self._wait); } return self._result; } debounced.cancel = this.cancel.bind(this); debounced.flush = this.flush.bind(this); debounced.pending = this.pending.bind(this); return debounced; } /** * Cancels a debounced functions. */ cancel() { if (this._timerId !== undefined) { clearTimeout(this._timerId); } this._lastArgs = this._lastCallTime = this._lastThis = this._timerId = undefined; } /** * Immediately invoke the function. * * @returns {*} */ flush() { return this._timerId === undefined ? this._result : this._edge(); } /** * Whether a debounce function is pending. * * @returns {boolean} */ pending() { return this._timerId !== undefined; } /** * Either this is the first call, activity has stopped and we're at the * trailing edge, the system time has gone backwards and we're treating * it as the trailing edge. * * @param {int} time * * @returns {boolean} * * @private */ _shouldInvoke(time) { return this._lastCallTime === undefined || time - this._lastCallTime >= this._wait || 0 > this._timeSinceLastCall; } /** * Invokes the function. * * @returns {*} * * @private */ _edge() { this._timerId = undefined; if (this._lastArgs) { return this._invokeFunc(); } this._lastArgs = this._lastThis = undefined; return this._result; } /** * Timer bound function. * * @returns {*} * * @private */ _timerExpired() { const time = Date.now(); if (this._shouldInvoke(time)) { return this._edge(); } // Restart the timer. this._timerId = setTimeout(this._timerExpired.bind(this), this._wait - (time - this._lastCallTime)); } /** * Invokes the function and saves the result. * * @returns {*} * * @private */ _invokeFunc() { const args = this._lastArgs; const thisArg = this._lastThis; this._lastArgs = this._lastThis = undefined; return this._result = this._func.apply(thisArg, args); } }
JavaScript
class EmailController { /** * @method sendMailMethod * @description sends an email notification to the specified email address * @param {object} message - The email address, subject & body * @returns {*} nothing */ static sendMailMethod(message) { const response = message; const transport = nodemailer.createTransport({ host: 'smtp.gmail.com', service: 'gmail', secure: false, auth: { user: process.env.SERVER_MAIL, pass: process.env.MAIL_PASSWORD, }, tls: { rejectUnauthorized: false, }, }); const mailOptions = { from: '[email protected]', to: response.email, subject: response.subject, html: response.body, }; transport.sendMail(mailOptions, (error) => { if (error) { console.log(error); } console.log('messageSent!'); }); } }
JavaScript
class PrecacheCacheKeyPlugin { constructor({ precacheController }) { this.cacheKeyWillBeUsed = async ({ request, params, }) => { const cacheKey = params && params.cacheKey || this._precacheController.getCacheKeyForURL(request.url); return cacheKey ? new Request(cacheKey) : request; }; this._precacheController = precacheController; } }
JavaScript
class ShowRooms extends React.Component { showUnread = (room) => { const user = this.props.auth; if (user) { const { uid } = user; const person = room.people.find((p) => { return uid === p.id; }); return person && person.unread; } }; returnRooms = () => { const rooms = this.props.rooms; if (rooms.length > 0) { const roomList = rooms.filter((room) => !room.restricted).map((room, idx) => { return ( <div key={idx} className="room-name-wrapper"> <button className="button--unread-messages" onClick={() => this.props.startClearUnread(room.name)} > {this.showUnread(room)} </button> <NavLink to={`/room/${room.name}`} activeClassName="room-selected"> <div className="room-name">{room.name}</div> </NavLink> </div> ); }); return roomList; } }; render() { return ( <div className="container__left"> <div className="container__left__text"> <h3 className="header--user">Public Channels</h3> {this.returnRooms()} <ShowUsers /> </div> </div> ); } }
JavaScript
class MinStack { constructor() { this.min = Number.MAX_VALUE; this.stack = new Array(); } push(x) { if (x <= this.min) { this.stack.push(this.min); this.min = x; } this.stack.push(x); } pop() { if (this.stack.pop() === this.min) this.min = this.stack.pop(); } top() { return this.stack[this.stack.length - 1]; } getMin() { return this.min; } }
JavaScript
class ManagedPolicy extends core_1.Resource { /** * @stability stable */ constructor(scope, id, props = {}) { super(scope, id, { physicalName: props.managedPolicyName, }); /** * The policy document. * * @stability stable */ this.document = new policy_document_1.PolicyDocument(); this.roles = new Array(); this.users = new Array(); this.groups = new Array(); this.description = props.description || ''; this.path = props.path || '/'; if (props.document) { this.document = props.document; } const resource = new iam_generated_1.CfnManagedPolicy(this, 'Resource', { policyDocument: this.document, managedPolicyName: this.physicalName, description: this.description, path: this.path, roles: util_1.undefinedIfEmpty(() => this.roles.map(r => r.roleName)), users: util_1.undefinedIfEmpty(() => this.users.map(u => u.userName)), groups: util_1.undefinedIfEmpty(() => this.groups.map(g => g.groupName)), }); if (props.users) { props.users.forEach(u => this.attachToUser(u)); } if (props.groups) { props.groups.forEach(g => this.attachToGroup(g)); } if (props.roles) { props.roles.forEach(r => this.attachToRole(r)); } if (props.statements) { props.statements.forEach(p => this.addStatements(p)); } // arn:aws:iam::123456789012:policy/teststack-CreateTestDBPolicy-16M23YE3CS700 this.managedPolicyName = this.getResourceNameAttribute(core_1.Stack.of(this).parseArn(resource.ref, '/').resourceName); this.managedPolicyArn = this.getResourceArnAttribute(resource.ref, { region: '', service: 'iam', resource: 'policy', resourceName: this.physicalName, }); } /** * Import a customer managed policy from the managedPolicyName. * * For this managed policy, you only need to know the name to be able to use it. * * @stability stable */ static fromManagedPolicyName(scope, id, managedPolicyName) { class Import extends core_1.Resource { constructor() { super(...arguments); this.managedPolicyArn = core_1.Stack.of(scope).formatArn({ service: 'iam', region: '', account: core_1.Stack.of(scope).account, resource: 'policy', resourceName: managedPolicyName, }); } } return new Import(scope, id); } /** * Import an external managed policy by ARN. * * For this managed policy, you only need to know the ARN to be able to use it. * This can be useful if you got the ARN from a CloudFormation Export. * * If the imported Managed Policy ARN is a Token (such as a * `CfnParameter.valueAsString` or a `Fn.importValue()`) *and* the referenced * managed policy has a `path` (like `arn:...:policy/AdminPolicy/AdminAllow`), the * `managedPolicyName` property will not resolve to the correct value. Instead it * will resolve to the first path component. We unfortunately cannot express * the correct calculation of the full path name as a CloudFormation * expression. In this scenario the Managed Policy ARN should be supplied without the * `path` in order to resolve the correct managed policy resource. * * @param scope construct scope. * @param id construct id. * @param managedPolicyArn the ARN of the managed policy to import. * @stability stable */ static fromManagedPolicyArn(scope, id, managedPolicyArn) { class Import extends core_1.Resource { constructor() { super(...arguments); this.managedPolicyArn = managedPolicyArn; } } return new Import(scope, id); } /** * Import a managed policy from one of the policies that AWS manages. * * For this managed policy, you only need to know the name to be able to use it. * * Some managed policy names start with "service-role/", some start with * "job-function/", and some don't start with anything. Do include the * prefix when constructing this object. * * @stability stable */ static fromAwsManagedPolicyName(managedPolicyName) { class AwsManagedPolicy { constructor() { this.managedPolicyArn = core_1.Lazy.uncachedString({ produce(ctx) { return core_1.Stack.of(ctx.scope).formatArn({ service: 'iam', region: '', account: 'aws', resource: 'policy', resourceName: managedPolicyName, }); }, }); } } return new AwsManagedPolicy(); } /** * Adds a statement to the policy document. * * @stability stable */ addStatements(...statement) { this.document.addStatements(...statement); } /** * Attaches this policy to a user. * * @stability stable */ attachToUser(user) { if (this.users.find(u => u === user)) { return; } this.users.push(user); } /** * Attaches this policy to a role. * * @stability stable */ attachToRole(role) { if (this.roles.find(r => r === role)) { return; } this.roles.push(role); } /** * Attaches this policy to a group. * * @stability stable */ attachToGroup(group) { if (this.groups.find(g => g === group)) { return; } this.groups.push(group); } /** * Validate the current construct. * * This method can be implemented by derived constructs in order to perform * validation logic. It is called on all constructs before synthesis. * * @stability stable */ validate() { const result = new Array(); // validate that the policy document is not empty if (this.document.isEmpty) { result.push('Managed Policy is empty. You must add statements to the policy'); } result.push(...this.document.validateForIdentityPolicy()); return result; } }
JavaScript
class WebGLShaderRenderer { vertexShaderPath = "./shader/vertex.glsl"; programInfo = { shaders: [ { type: "vertex", }, { type: "fragment" }, ], uniforms: [], attributes: [ "position" ], }; constructor(id, resolution) { this.id = id; this.resolution = resolution; this.initCanvas(); this.initWebGLRenderingContext(); this.initVertexBuffer(); }; static async downloadShader(path) { const response = await fetch(path); return response.text(); } initCanvas() { this.canvas = document.getElementById(this.id); this.canvas.width = this.resolution[0]; this.canvas.height = this.resolution[1]; this.canvas.style.width = this.resolution[0]; this.canvas.style.height = this.resolution[1]; } initWebGLRenderingContext() { this.gl = this.canvas.getContext("webgl", { antialias: false, depth: false, }); if (!this.gl) return alert("WebGL not supported"); this.shader = { [this.gl.VERTEX_SHADER]: "vertex", [this.gl.FRAGMENT_SHADER]: "fragment", vertex: this.gl.VERTEX_SHADER, fragment: this.gl.FRAGMENT_SHADER, }; } initVertexBuffer() { this.vertices = new Float32Array([ -1, 1, 0, 0, 1, 1, 1, 0, -1, -1, 0, 1, 1, -1, 1, 1, ]); this.vertexBuffer = this.gl.createBuffer(); this.gl.bindBuffer(this.gl.ARRAY_BUFFER, this.vertexBuffer); this.gl.bufferData(this.gl.ARRAY_BUFFER, this.vertices, this.gl.STATIC_DRAW); this.vertexCount = this.vertices.length / 4; } async setShader(vertex, fragment) { this.programInfo.shaders[0].code = await WebGLShaderRenderer.downloadShader(vertex); this.programInfo.shaders[1].code = await WebGLShaderRenderer.downloadShader(fragment); this.shaderProgram = this.buildShaderProgram(); this.gl.enableVertexAttribArray(this.shaderProgram.attributes.position); this.gl.vertexAttribPointer(this.shaderProgram.attributes.position, 2, this.gl.FLOAT, false, 4 * 4, 0); } compileShader(code, type) { const gl = this.gl; let shader = gl.createShader(type); gl.shaderSource(shader, code); gl.compileShader(shader); if (!gl.getShaderParameter(shader, gl.COMPILE_STATUS)) { console.error(`Error compiling ${this.shader[type]} shader:\n${gl.getShaderInfoLog(shader)}`); } return shader; } buildShaderProgram() { let program = this.gl.createProgram(); this.programInfo.shaders.forEach(desc => { let shader = this.compileShader(desc.code, this.shader[desc.type]); if (shader) this.gl.attachShader(program, shader); }); this.gl.linkProgram(program); if (!this.gl.getProgramParameter(program, this.gl.LINK_STATUS)) { console.error(`Error linking shader program:\n${this.gl.getProgramInfoLog(program)}`); } let uniforms = Object.fromEntries(this.programInfo.uniforms.map(name => [ name, this.gl.getUniformLocation(program, name) ])); let attributes = Object.fromEntries(this.programInfo.attributes.map(name => [ name, this.gl.getAttribLocation(program, name) ])); return { program, uniforms, attributes }; } start() { this.ms = 0; window.requestAnimationFrame(ts => this.loop(ts)); } loop(ts) { window.requestAnimationFrame(ts => this.loop(ts)); this.dt = ts - this.ms; this.ms = ts; this.gl.useProgram(this.shaderProgram.program); this.callback(this.gl, this.shaderProgram); this.gl.drawArrays(this.gl.TRIANGLE_STRIP, 0, this.vertexCount); } callback() { } }
JavaScript
class FileDialogButtonView extends ButtonView { /** * @inheritDoc */ constructor( locale ) { super( locale ); /** * Hidden input view used to execute file dialog. It will be hidden and added to the end of `document.body`. * * @protected * @member {module:upload/ui/filedialogbuttonview~FileInputView} */ this.fileInputView = new FileInputView( locale ); /** * Accepted file types. Can be provided in form of file extensions, media type or one of: * * `audio/*`, * * `video/*`, * * `image/*`. * * @observable * @member {String} #acceptedType */ this.fileInputView.bind( 'acceptedType' ).to( this, 'acceptedType' ); /** * Indicates if multiple files can be selected. Defaults to `true`. * * @observable * @member {Boolean} #allowMultipleFiles */ this.set( 'allowMultipleFiles', false ); this.fileInputView.bind( 'allowMultipleFiles' ).to( this, 'allowMultipleFiles' ); /** * Fired when file dialog is closed with file selected. * * fileDialogButtonView.on( 'done', ( evt, files ) => { * for ( const file of files ) { * processFile( file ); * } * } * * @event done * @param {Array.<File>} files Array of selected files. */ this.fileInputView.delegate( 'done' ).to( this ); this.on( 'execute', () => { this.fileInputView.open(); } ); document.body.appendChild( this.fileInputView.element ); } /** * @inheritDoc */ destroy() { document.body.removeChild( this.fileInputView.element ); super.destroy(); } }
JavaScript
class FileInputView extends View { /** * @inheritDoc */ constructor( locale ) { super( locale ); /** * Accepted file types. Can be provided in form of file extensions, media type or one of: * * `audio/*`, * * `video/*`, * * `image/*`. * * @observable * @member {String} #acceptedType */ this.set( 'acceptedType' ); /** * Indicates if multiple files can be selected. Defaults to `false`. * * @observable * @member {Boolean} #allowMultipleFiles */ this.set( 'allowMultipleFiles', false ); const bind = this.bindTemplate; this.template = new Template( { tag: 'input', attributes: { class: [ 'ck-hidden' ], type: 'file', tabindex: '-1', accept: bind.to( 'acceptedType' ), multiple: bind.to( 'allowMultipleFiles' ) }, on: { // Removing from code coverage since we cannot programmatically set input element files. change: bind.to( /* istanbul ignore next */ () => { if ( this.element && this.element.files && this.element.files.length ) { this.fire( 'done', this.element.files ); } this.element.value = ''; } ) } } ); } /** * Opens file dialog. */ open() { this.element.click(); } }
JavaScript
class Toolbar{ constructor(codeMirrorTarget,editorWrapper){ this.me =""; this.editorWrapper=editorWrapper; this.codeMirrorTarget=codeMirrorTarget; this.icons=this.iconsF(); this.keyMaps= { "120" : {keyboard:"F9",handler:"watch"}, "121" : {keyboard:"F10",handler:"preview"}, "122" : {keyboard:"F11",handler:"fullscreen"} }; } registerKeyMaps() { document.body.addEventListener("keydown",(event) =>{ const key=event.keyCode; const item=""; if(!(key in this.keyMaps)){ return } const name=this.keyMaps[key].handler; for(let i=0,len=this.icons.length;i<len;i++){ if(this.icons[i].Name==name){ item=this.icons[i]; break; } } if(item!=""){ item.Func(); } }); } create(){ const lista=document.createElement("ul"); lista.classList.add("yaposi-toolbar"); for (let i=0,len=this.icons.length;i<len;i++){ const icon = this.icons[i]; const liTag=document.createElement("li"); liTag.classList.add("icon"); liTag.dataset.name=icon.Name; let add=""; switch (icon.Img.Kind){ case "text": add=document.createElement("span"); add.textContent=icon.Img.Value; add.classList.add("text"); break; case "svg": let temp=document.createElement("template"); temp.innerHTML=icon.Img.Value; add=temp.content.querySelector("svg"); add.classList.add("img"); break; case "img": add=document.createElement("img"); add.src=icon.Img.Value; add.classList.add("img"); break; default: console.log(`Error type: ${icon.Img.Kind}; Valid types: text, svg`); continue } if ("Title" in icon){ liTag.setAttribute("title",icon.Title); } if ("Func" in icon){ liTag.addEventListener("click",icon.Func); } liTag.appendChild(add); lista.appendChild(liTag); } this.me =lista; return lista } iconsF() { return [ { Name:"undo", Title:"Undo", Img:{ Kind:"svg", Value:` <svg xmlns="http://www.w3.org/2000/svg" viewBox="0 0 24 24"> <path fill="none" d="M0 0h24v24H0V0z"/> <path d="M12.5 8c-2.65 0-5.05.99-6.9 2.6L3.71 8.71C3.08 8.08 2 8.52 2 9.41V15c0 .55.45 1 1 1h5.59c.89 0 1.34-1.08.71-1.71l-1.91-1.91c1.39-1.16 3.16-1.88 5.12-1.88 3.16 0 5.89 1.84 7.19 4.5.27.56.91.84 1.5.64.71-.23 1.07-1.04.75-1.72C20.23 10.42 16.65 8 12.5 8z"/> </svg> `}, Func: ()=> { this.codeMirrorTarget.undo(); this.codeMirrorTarget.focus(); }, }, { Name:"redo", Title:"Redo", Img:{ Kind:"svg", Value:` <svg xmlns="http://www.w3.org/2000/svg" viewBox="0 0 24 24"> <path fill="none" d="M0 0h24v24H0V0z"/> <path d="M18.4 10.6C16.55 8.99 14.15 8 11.5 8c-4.16 0-7.74 2.42-9.44 5.93-.32.67.04 1.47.75 1.71.59.2 1.23-.08 1.5-.64 1.3-2.66 4.03-4.5 7.19-4.5 1.95 0 3.73.72 5.12 1.88l-1.91 1.91c-.63.63-.19 1.71.7 1.71H21c.55 0 1-.45 1-1V9.41c0-.89-1.08-1.34-1.71-.71l-1.89 1.9z"/> </svg> `}, Func: ()=> { this.codeMirrorTarget.redo(); this.codeMirrorTarget.focus(); }, }, { Name:"bold", Title:"Bold", Img:{ Kind:"svg", Value:` <svg xmlns="http://www.w3.org/2000/svg" viewBox="0 0 24 24"> <path fill="none" d="M0 0h24v24H0V0z"/> <path d="M15.6 10.79c.97-.67 1.65-1.77 1.65-2.79 0-2.26-1.75-4-4-4H8c-.55 0-1 .45-1 1v12c0 .55.45 1 1 1h5.78c2.07 0 3.96-1.69 3.97-3.77.01-1.53-.85-2.84-2.15-3.44zM10 6.5h3c.83 0 1.5.67 1.5 1.5s-.67 1.5-1.5 1.5h-3v-3zm3.5 9H10v-3h3.5c.83 0 1.5.67 1.5 1.5s-.67 1.5-1.5 1.5z"/> </svg> `}, Func: ()=> { const cm = this.codeMirrorTarget; const cursor = cm.getCursor(); const selection = cm.getSelection(); cm.replaceSelection("**" + selection + "**"); if(selection === "") { cm.setCursor(cursor.line, cursor.ch + 2); } this.codeMirrorTarget.focus(); }, }, { Name:"del", Title:"Strikethrough", Img:{ Kind:"svg", Value:` <svg xmlns="http://www.w3.org/2000/svg" viewBox="0 0 24 24"> <path fill="none" d="M0 0h24v24H0z"/> <path d="M14.59 7.52c0-.31-.05-.59-.15-.85-.09-.27-.24-.49-.44-.68-.2-.19-.45-.33-.75-.44-.3-.1-.66-.16-1.06-.16-.39 0-.74.04-1.03.13s-.53.21-.72.36c-.19.16-.34.34-.44.55-.1.21-.15.43-.15.66 0 .48.25.88.74 1.21.38.25.77.48 1.41.7H7.39c-.05-.08-.11-.17-.15-.25-.26-.48-.39-1.03-.39-1.67 0-.61.13-1.16.4-1.67.26-.5.63-.93 1.11-1.29.48-.35 1.05-.63 1.7-.83.66-.19 1.39-.29 2.18-.29.81 0 1.54.11 2.21.34.66.22 1.23.54 1.69.94.47.4.83.88 1.08 1.43s.38 1.15.38 1.81h-3.01M20 10H4c-.55 0-1 .45-1 1s.45 1 1 1h8.62c.18.07.4.14.55.2.37.17.66.34.87.51s.35.36.43.57c.07.2.11.43.11.69 0 .23-.05.45-.14.66-.09.2-.23.38-.42.53-.19.15-.42.26-.71.35-.29.08-.63.13-1.01.13-.43 0-.83-.04-1.18-.13s-.66-.23-.91-.42c-.25-.19-.45-.44-.59-.75s-.25-.76-.25-1.21H6.4c0 .55.08 1.13.24 1.58s.37.85.65 1.21c.28.35.6.66.98.92.37.26.78.48 1.22.65.44.17.9.3 1.38.39.48.08.96.13 1.44.13.8 0 1.53-.09 2.18-.28s1.21-.45 1.67-.79c.46-.34.82-.77 1.07-1.27s.38-1.07.38-1.71c0-.6-.1-1.14-.31-1.61-.05-.11-.11-.23-.17-.33H20c.55 0 1-.45 1-1V11c0-.55-.45-1-1-1z"/> </svg> `}, Func: ()=> { const cm = this.codeMirrorTarget; const cursor = cm.getCursor(); const selection = cm.getSelection(); cm.replaceSelection("~~" + selection + "~~"); if(selection === "") { cm.setCursor(cursor.line, cursor.ch + 2); } this.codeMirrorTarget.focus(); } }, { Name:"italic", Title:"Italic", Img:{ Kind:"svg", Value:` <svg xmlns="http://www.w3.org/2000/svg" viewBox="0 0 24 24"> <path fill="none" d="M0 0h24v24H0V0z"/> <path d="M10 5.5c0 .83.67 1.5 1.5 1.5h.71l-3.42 8H7.5c-.83 0-1.5.67-1.5 1.5S6.67 18 7.5 18h5c.83 0 1.5-.67 1.5-1.5s-.67-1.5-1.5-1.5h-.71l3.42-8h1.29c.83 0 1.5-.67 1.5-1.5S17.33 4 16.5 4h-5c-.83 0-1.5.67-1.5 1.5z"/> </svg> `}, Func:()=> { const cm = this.codeMirrorTarget; const cursor = cm.getCursor(); const selection = cm.getSelection(); cm.replaceSelection("*" + selection + "*"); if(selection === "") { cm.setCursor(cursor.line, cursor.ch + 1); } this.codeMirrorTarget.focus(); } }, { Name:"quote", Title:"Quote", Img:{ Kind:"svg", Value:` <svg xmlns="http://www.w3.org/2000/svg" viewBox="0 0 24 24"> <path fill="none" d="M0 0h24v24H0V0z"/> <path d="M7.17 17c.51 0 .98-.29 1.2-.74l1.42-2.84c.14-.28.21-.58.21-.89V8c0-.55-.45-1-1-1H5c-.55 0-1 .45-1 1v4c0 .55.45 1 1 1h2l-1.03 2.06c-.45.89.2 1.94 1.2 1.94zm10 0c.51 0 .98-.29 1.2-.74l1.42-2.84c.14-.28.21-.58.21-.89V8c0-.55-.45-1-1-1h-4c-.55 0-1 .45-1 1v4c0 .55.45 1 1 1h2l-1.03 2.06c-.45.89.2 1.94 1.2 1.94z"/> </svg> `}, Func: ()=> { const cm = this.codeMirrorTarget; const cursor = cm.getCursor(); const selection = cm.getSelection(); if (cursor.ch !== 0){ cm.setCursor(cursor.line, 0); cm.replaceSelection("> " + selection); cm.setCursor(cursor.line, cursor.ch + 2); } else{ cm.replaceSelection("> " + selection); } this.codeMirrorTarget.focus(); //cm.replaceSelection("> " + selection); //cm.setCursor(cursor.line, (selection === "") ? cursor.ch + 2 : cursor.ch + selection.length + 2); } }, { Name:"ucfirst", Title:"First letter of each word to upper case, the remaning in lower case", Img:{ Kind:"text", Value:"Aa" }, Func:()=> { const cm = this.codeMirrorTarget; const selection = cm.getSelection(); const selections = cm.listSelections(); let str= selection.toLowerCase().replace(/\b(\w)|\s(\w)/g, allLower => allLower.toUpperCase()); cm.replaceSelection(str); cm.setSelections(selections); this.codeMirrorTarget.focus(); } }, { Name:"uppercase", Title:"All selected text to upper case", Img:{ Kind:"text", Value:"A" }, Func:()=> { const cm = this.codeMirrorTarget; const selection = cm.getSelection(); const selections = cm.listSelections(); cm.replaceSelection(selection.toUpperCase()); cm.setSelections(selections); this.codeMirrorTarget.focus(); } }, { Name:"lowercase", Title:"All selected text to lower case", Img:{ Kind:"text", Value:"a" }, Func:()=> { const cm = this.codeMirrorTarget; const selection = cm.getSelection(); const selections = cm.listSelections(); cm.replaceSelection(selection.toLowerCase()); cm.setSelections(selections); this.codeMirrorTarget.focus(); } }, { Name:"h1", Title:"Heading 1", Img:{ Kind:"text", Value:"H1" }, Func:()=> { const cm = this.codeMirrorTarget; const cursor = cm.getCursor(); const selection = cm.getSelection(); if (cursor.ch === 0){ cm.replaceSelection("# " + selection); }else{ cm.setCursor(cursor.line, 0); cm.replaceSelection("# " + selection); cm.setCursor(cursor.line, cursor.ch + 2); } this.codeMirrorTarget.focus(); } } , { Name:"h2", Title:"Heading 2", Img:{ Kind:"text", Value:"H2" }, Func:()=> { const cm = this.codeMirrorTarget; const cursor = cm.getCursor(); const selection = cm.getSelection(); if (cursor.ch === 0){ cm.replaceSelection("## " + selection); }else{ cm.setCursor(cursor.line, 0); cm.replaceSelection("## " + selection); cm.setCursor(cursor.line, cursor.ch + 3); } this.codeMirrorTarget.focus(); } } , { Name:"h3", Title:"Heading 3", Img:{ Kind:"text", Value:"H3" }, Func:()=> { const cm = this.codeMirrorTarget; const cursor = cm.getCursor(); const selection = cm.getSelection(); if (cursor.ch === 0){ cm.replaceSelection("### " + selection); }else{ cm.setCursor(cursor.line, 0); cm.replaceSelection("### " + selection); cm.setCursor(cursor.line, cursor.ch + 4); } this.codeMirrorTarget.focus(); } } , { Name:"h4", Title:"Heading 4", Img:{ Kind:"text", Value:"H4" }, Func:()=> { const cm = this.codeMirrorTarget; const cursor = cm.getCursor(); const selection = cm.getSelection(); if (cursor.ch === 0){ cm.replaceSelection("#### " + selection); }else{ cm.setCursor(cursor.line, 0); cm.replaceSelection("#### " + selection); cm.setCursor(cursor.line, cursor.ch + 5); } this.codeMirrorTarget.focus(); } } , { Name:"h5", Title:"Heading 5", Img:{ Kind:"text", Value:"H5" }, Func:()=>{ const cm = this.codeMirrorTarget; const cursor = cm.getCursor(); const selection = cm.getSelection(); if (cursor.ch === 0){ cm.replaceSelection("##### " + selection); }else{ cm.setCursor(cursor.line, 0); cm.replaceSelection("##### " + selection); cm.setCursor(cursor.line, cursor.ch + 6); } this.codeMirrorTarget.focus(); } } , { Name:"h6", Title:"Heading 6", Img:{ Kind:"text", Value:"H6" }, Func:()=> { const cm = this.codeMirrorTarget; const cursor = cm.getCursor(); const selection = cm.getSelection(); if (cursor.ch === 0){ cm.replaceSelection("###### " + selection); }else{ cm.setCursor(cursor.line, 0); cm.replaceSelection("###### " + selection); cm.setCursor(cursor.line, cursor.ch + 7); } this.codeMirrorTarget.focus(); } } , { Name:"list-ul", Title:"Unordered list", Img:{ Kind:"svg", Value:` <svg xmlns="http://www.w3.org/2000/svg" viewBox="0 0 24 24"> <path fill="none" d="M0 0h24v24H0V0z"/><path d="M4 10.5c-.83 0-1.5.67-1.5 1.5s.67 1.5 1.5 1.5 1.5-.67 1.5-1.5-.67-1.5-1.5-1.5zm0-6c-.83 0-1.5.67-1.5 1.5S3.17 7.5 4 7.5 5.5 6.83 5.5 6 4.83 4.5 4 4.5zm0 12c-.83 0-1.5.68-1.5 1.5s.68 1.5 1.5 1.5 1.5-.68 1.5-1.5-.67-1.5-1.5-1.5zM8 19h12c.55 0 1-.45 1-1s-.45-1-1-1H8c-.55 0-1 .45-1 1s.45 1 1 1zm0-6h12c.55 0 1-.45 1-1s-.45-1-1-1H8c-.55 0-1 .45-1 1s.45 1 1 1zM7 6c0 .55.45 1 1 1h12c.55 0 1-.45 1-1s-.45-1-1-1H8c-.55 0-1 .45-1 1z"/> </svg> `}, Func:()=> { const cm = this.codeMirrorTarget; const selection = cm.getSelection(); if (selection === "") { cm.replaceSelection("- " + selection); }else{ let selectionText = selection.split("\n"); for (let i = 0, len = selectionText.length; i < len; i++){ if(selectionText[i] != ""){ selectionText[i]="- " + selectionText[i]; } } cm.replaceSelection(selectionText.join("\n")); } this.codeMirrorTarget.focus(); } } , { Name:"list-ol", Title:"Ordered list", Img:{ Kind:"svg", Value:` <svg xmlns="http://www.w3.org/2000/svg" viewBox="0 0 24 24"> <path fill="none" d="M0 0h24v24H0V0z"/> <path d="M8 7h12c.55 0 1-.45 1-1s-.45-1-1-1H8c-.55 0-1 .45-1 1s.45 1 1 1zm12 10H8c-.55 0-1 .45-1 1s.45 1 1 1h12c.55 0 1-.45 1-1s-.45-1-1-1zm0-6H8c-.55 0-1 .45-1 1s.45 1 1 1h12c.55 0 1-.45 1-1s-.45-1-1-1zM4.5 16h-2c-.28 0-.5.22-.5.5s.22.5.5.5H4v.5h-.5c-.28 0-.5.22-.5.5s.22.5.5.5H4v.5H2.5c-.28 0-.5.22-.5.5s.22.5.5.5h2c.28 0 .5-.22.5-.5v-3c0-.28-.22-.5-.5-.5zm-2-11H3v2.5c0 .28.22.5.5.5s.5-.22.5-.5v-3c0-.28-.22-.5-.5-.5h-1c-.28 0-.5.22-.5.5s.22.5.5.5zm2 5h-2c-.28 0-.5.22-.5.5s.22.5.5.5h1.3l-1.68 1.96c-.08.09-.12.21-.12.32v.22c0 .28.22.5.5.5h2c.28 0 .5-.22.5-.5s-.22-.5-.5-.5H3.2l1.68-1.96c.08-.09.12-.21.12-.32v-.22c0-.28-.22-.5-.5-.5z"/> </svg> `}, Func:()=> { const cm = this.codeMirrorTarget; const selection = cm.getSelection(); if(selection == "") { cm.replaceSelection("1. " + selection); }else{ let selectionText = selection.split("\n"); for (let i = 0, len = selectionText.length; i < len; i++){ if(selectionText[i]!=""){ selectionText[i]=(i+1) + ". " + selectionText[i] } } cm.replaceSelection(selectionText.join("\n")); } this.codeMirrorTarget.focus(); } } , { Name:"hr", Title:"Horizontal rule", Img:{ Kind:"svg", Value:` <svg xmlns="http://www.w3.org/2000/svg" viewBox="0 0 24 24"> <path d="M19 13H5v-2h14v2z"/> <path d="M0 0h24v24H0z" fill="none"/> </svg> `}, Func:()=> { const cm = this.codeMirrorTarget; const cursor = cm.getCursor(); let put="\n\n"; if(cursor.ch==0){ put="\n"; } put+="------------\n"; cm.replaceSelection(put); this.codeMirrorTarget.focus(); } } , { Name:"link", Title:"Link", Img:{ Kind:"svg", Value:` <svg xmlns="http://www.w3.org/2000/svg" viewBox="0 0 24 24"> <path fill="none" d="M0 0h24v24H0V0z"/> <path d="M17 7h-3c-.55 0-1 .45-1 1s.45 1 1 1h3c1.65 0 3 1.35 3 3s-1.35 3-3 3h-3c-.55 0-1 .45-1 1s.45 1 1 1h3c2.76 0 5-2.24 5-5s-2.24-5-5-5zm-9 5c0 .55.45 1 1 1h6c.55 0 1-.45 1-1s-.45-1-1-1H9c-.55 0-1 .45-1 1zm2 3H7c-1.65 0-3-1.35-3-3s1.35-3 3-3h3c.55 0 1-.45 1-1s-.45-1-1-1H7c-2.76 0-5 2.24-5 5s2.24 5 5 5h3c.55 0 1-.45 1-1s-.45-1-1-1z"/> </svg> `}, Func:()=>{ const cm = this.codeMirrorTarget; let selection = cm.getSelection(); if(selection.trim()==""){ selection="title"; } this.codeMirrorTarget.replaceSelection("["+selection+"](link)"); this.codeMirrorTarget.focus(); } }, { Name:"image", Title:"add image", Img:{ Kind:"svg", Value:` <svg version="1.1" xmlns="http://www.w3.org/2000/svg" viewBox="0 0 32 32"> <path d="M29.996 4c0.001 0.001 0.003 0.002 0.004 0.004v23.993c-0.001 0.001-0.002 0.003-0.004 0.004h-27.993c-0.001-0.001-0.003-0.002-0.004-0.004v-23.993c0.001-0.001 0.002-0.003 0.004-0.004h27.993zM30 2h-28c-1.1 0-2 0.9-2 2v24c0 1.1 0.9 2 2 2h28c1.1 0 2-0.9 2-2v-24c0-1.1-0.9-2-2-2v0z"></path> <path d="M26 9c0 1.657-1.343 3-3 3s-3-1.343-3-3 1.343-3 3-3 3 1.343 3 3z"></path> <path d="M28 26h-24v-4l7-12 8 10h2l7-6z"></path> </svg> `} }, { Name:"code", Title:"Lineal code", Img:{ Kind:"svg", Value:` <svg xmlns="http://www.w3.org/2000/svg" viewBox="0 0 24 24"> <path fill="none" d="M0 0h24v24H0V0z"/> <path d="M9.4 16.6L4.8 12l4.6-4.6L8 6l-6 6 6 6 1.4-1.4zm5.2 0l4.6-4.6-4.6-4.6L16 6l6 6-6 6-1.4-1.4z"/> </svg> `}, Func:()=> { const cm = this.codeMirrorTarget; const cursor = cm.getCursor(); const selection = cm.getSelection(); cm.replaceSelection("`" + selection + "`"); if (selection === "") { cm.setCursor(cursor.line, cursor.ch + 1); } } }, { Name:"code-block", Title:"Code block", Img:{ Kind:"svg", Value:` <svg version="1.1" xmlns="http://www.w3.org/2000/svg" viewBox="0 0 40 32"> <path d="M26 23l3 3 10-10-10-10-3 3 7 7z"></path> <path d="M14 9l-3-3-10 10 10 10 3-3-7-7z"></path> <path d="M21.916 4.704l2.171 0.592-6 22.001-2.171-0.592 6-22.001z"></path> </svg> `}, }, { Name:"table", Title:"Tables", Img:{ Kind:"svg", Value:` <svg xmlns="http://www.w3.org/2000/svg" viewBox="0 0 24 24"><path fill="none" d="M0 0h24v24H0V0z"/> <path d="M20 2H4c-1.1 0-2 .9-2 2v16c0 1.1.9 2 2 2h16c1.1 0 2-.9 2-2V4c0-1.1-.9-2-2-2zM8 20H4v-4h4v4zm0-6H4v-4h4v4zm0-6H4V4h4v4zm6 12h-4v-4h4v4zm0-6h-4v-4h4v4zm0-6h-4V4h4v4zm6 12h-4v-4h4v4zm0-6h-4v-4h4v4zm0-6h-4V4h4v4z"/> </svg> `}, }, { Name:"latex", Title:"Latex", Img:{ Kind:"text", Value:"∰" }, Func:()=> { const cm = this.codeMirrorTarget; const cursor = cm.getCursor(); const selection = cm.getSelection(); cm.replaceSelection("🥚" + selection + "🐤"); if (selection === "") { cm.setCursor(cursor.line, cursor.ch + 1); } } }, { Name:"fullscreen", Title:"Full screen", Img:{ Kind:"svg", Value:` <svg xmlns="http://www.w3.org/2000/svg" viewBox="0 0 24 24"> <path d="M0 0h24v24H0z" fill="none"/> <path d="M5 16h3v3h2v-5H5v2zm3-8H5v2h5V5H8v3zm6 11h2v-3h3v-2h-5v5zm2-11V5h-2v5h5V8h-3z"/> </svg> `}, Func:()=>{ if (!document.fullscreenElement) { this.editorWrapper.requestFullscreen() .then((me)=>{ console.log(me); }) .catch((e)=>{ console.log(e); }); } else { if (document.exitFullscreen) { document.exitFullscreen(); } } this.codeMirrorTarget.focus(); } }, { Name:"search", Title:"Search", Img:{ Kind:"svg", Value:` <svg xmlns="http://www.w3.org/2000/svg" viewBox="0 0 24 24"> <path d="M15.5 14h-.79l-.28-.27C15.41 12.59 16 11.11 16 9.5 16 5.91 13.09 3 9.5 3S3 5.91 3 9.5 5.91 16 9.5 16c1.61 0 3.09-.59 4.23-1.57l.27.28v.79l5 4.99L20.49 19l-4.99-5zm-6 0C7.01 14 5 11.99 5 9.5S7.01 5 9.5 5 14 7.01 14 9.5 11.99 14 9.5 14z"/><path d="M0 0h24v24H0z" fill="none"/> </svg> `}, Func:()=>{ this.codeMirrorTarget.execCommand("find"); } }, { Name:"nuevaLinea", Title:"New line", Img:{ Kind:"svg", Value:` <svg xmlns="http://www.w3.org/2000/svg" viewBox="0 0 24 24"> <path d="M16.59 8.59L12 13.17 7.41 8.59 6 10l6 6 6-6z"/> <path d="M0 0h24v24H0z" fill="none"/> </svg> `}, Func:()=> { const cm = this.codeMirrorTarget; const cursor = cm.getCursor(); let put="💥\r\n"; if(cursor.ch != 0){ put="\r\n"+put; } cm.replaceSelection(put); this.codeMirrorTarget.focus(); } }, { Name:"withoutPreview", Title:"Watch only preview", Img:{ Kind:"svg", Value:` <svg version="1.1" xmlns="http://www.w3.org/2000/svg" viewBox="0 0 32 32"> <path d="M16 6c-6.979 0-13.028 4.064-16 10 2.972 5.936 9.021 10 16 10s13.027-4.064 16-10c-2.972-5.936-9.021-10-16-10zM23.889 11.303c1.88 1.199 3.473 2.805 4.67 4.697-1.197 1.891-2.79 3.498-4.67 4.697-2.362 1.507-5.090 2.303-7.889 2.303s-5.527-0.796-7.889-2.303c-1.88-1.199-3.473-2.805-4.67-4.697 1.197-1.891 2.79-3.498 4.67-4.697 0.122-0.078 0.246-0.154 0.371-0.228-0.311 0.854-0.482 1.776-0.482 2.737 0 4.418 3.582 8 8 8s8-3.582 8-8c0-0.962-0.17-1.883-0.482-2.737 0.124 0.074 0.248 0.15 0.371 0.228v0zM16 13c0 1.657-1.343 3-3 3s-3-1.343-3-3 1.343-3 3-3 3 1.343 3 3z"></path> </svg> `}, Func:()=>{ const preview=this.editorWrapper.querySelector(".yaposi-preview"); const cmWrapper=this.editorWrapper.querySelector(".codeMirrorWrapper"); const li=this.editorWrapper.querySelector(`.yaposi-toolbar li[data-name="withoutPreview"]`); const img=li.querySelector(".img"); switch (preview.dataset.state){ case "both": cmWrapper.style.display="none"; preview.dataset.state="preview"; this.editorWrapper.classList.add("modePreview"); li.setAttribute("title","Watch only editor"); img.innerHTML=` <path d="M27 0h-24c-1.65 0-3 1.35-3 3v26c0 1.65 1.35 3 3 3h24c1.65 0 3-1.35 3-3v-26c0-1.65-1.35-3-3-3zM26 28h-22v-24h22v24zM8 14h14v2h-14zM8 18h14v2h-14zM8 22h14v2h-14zM8 10h14v2h-14z"/> `; break; case "preview": cmWrapper.style.display="flex"; preview.style.display="none"; preview.dataset.state="editor"; this.editorWrapper.classList.remove("modePreview"); this.editorWrapper.classList.add("modeEditor"); li.setAttribute("title","Watch both, editor and preview"); img.innerHTML=` <path d="M20 8v-8h-14l-6 6v18h12v8h20v-24h-12zM6 2.828v3.172h-3.172l3.172-3.172zM2 22v-14h6v-6h10v6l-6 6v8h-10zM18 10.828v3.172h-3.172l3.172-3.172zM30 30h-16v-14h6v-6h10v20z"/> `; break; case "editor": preview.style.display="block"; preview.dataset.state="both"; this.editorWrapper.classList.remove("modeEditor"); li.setAttribute("title","Watch only preview"); img.innerHTML=` <path d="M16 6c-6.979 0-13.028 4.064-16 10 2.972 5.936 9.021 10 16 10s13.027-4.064 16-10c-2.972-5.936-9.021-10-16-10zM23.889 11.303c1.88 1.199 3.473 2.805 4.67 4.697-1.197 1.891-2.79 3.498-4.67 4.697-2.362 1.507-5.090 2.303-7.889 2.303s-5.527-0.796-7.889-2.303c-1.88-1.199-3.473-2.805-4.67-4.697 1.197-1.891 2.79-3.498 4.67-4.697 0.122-0.078 0.246-0.154 0.371-0.228-0.311 0.854-0.482 1.776-0.482 2.737 0 4.418 3.582 8 8 8s8-3.582 8-8c0-0.962-0.17-1.883-0.482-2.737 0.124 0.074 0.248 0.15 0.371 0.228v0zM16 13c0 1.657-1.343 3-3 3s-3-1.343-3-3 1.343-3 3-3 3 1.343 3 3z"></path> `; break; } this.codeMirrorTarget.refresh(); } }, ] } }
JavaScript
class IoColorPicker extends IoColorMixin(IoItem) { static get Style() { return /* css */ ` :host { display: flex; box-sizing: border-box; border-radius: var(--io-border-radius); border: var(--io-border); border-color: var(--io-color-border-inset); min-width: var(--io-item-height); min-height: var(--io-item-height); padding: 0; } :host > io-color-swatch { border: 0; flex: 1 1 auto; align-self: stretch; min-width: 0; min-height: 0; border-radius: 0; } `; } static get Properties() { return { value: [0.5, 0.5, 0.5, 0.5], horizontal: false, role: 'slider', tabindex: 0, }; } static get Listeners() { return { 'click': '_onClick', 'keydown': '_onKeydown', }; } _onClick() { this.focus(); this.toggle(); } get expanded() { return IoColorPanelSingleton.expanded && IoColorPanelSingleton.value === this.value; } _onKeydown(event) { const rect = this.getBoundingClientRect(); const pRect = IoColorPanelSingleton.getBoundingClientRect(); if (event.key === 'Enter' || event.key === ' ') { event.preventDefault(); this.toggle(); if (this.expanded) IoColorPanelSingleton.firstChild.focus(); } else if (this.expanded && pRect.top >= rect.bottom && event.key === 'ArrowDown') { event.preventDefault(); IoColorPanelSingleton.firstChild.focus(); } else if (this.expanded && pRect.bottom <= rect.top && event.key === 'ArrowUp') { event.preventDefault(); IoColorPanelSingleton.firstChild.focus(); } else { this.collapse(); super._onKeydown(event); } } _onValueSet() { this.dispatchEvent('value-set', { property: 'value', value: this.value }, true); } toggle() { if (this.expanded) { this.collapse(); } else { this.expand(); } } expand() { const hasAlpha = this.alpha !== undefined; IoColorPanelSingleton.value = this.value; IoColorPanelSingleton.mode = this.mode; IoColorPanelSingleton.style.width = hasAlpha ? '192px' : '160px'; IoColorPanelSingleton.style.height = '128px'; IoColorPanelSingleton.expanded = true; IoLayerSingleton.setElementPosition(IoColorPanelSingleton, 'bottom', this.getBoundingClientRect()); // hook up 'value-set' event dispatch IoColorPanelSingleton.removeEventListener('value-set', IoColorPanelSingleton._targetValueSetHandler); IoColorPanelSingleton.addEventListener('value-set', this._onValueSet); IoColorPanelSingleton._targetValueSetHandler = this._onValueSet; } collapse() { IoColorPanelSingleton.expanded = false; } changed() { this.template([['io-color-swatch', { value: this.value, mode: this.mode }]]); } }
JavaScript
class Store { constructor() { this.todos = []; } }
JavaScript
class State_C4 { constructor(playHistory, board, player) { this.playHistory = playHistory this.board = board this.player = player } isPlayer(player) { return (player === this.player) } hash() { return JSON.stringify(this.playHistory) } // Note: If hash uses board, multiple parents possible }
JavaScript
class FundingInfo extends Model { serialize () { throw new Error('unimplemented') } static unserialize (arr) { throw new Error('unimplemented') } }
JavaScript
class Process { constructor(pid, pName, arrTime, exeTime) { this.pid = pid; this.pname = pName; this.arrTime = arrTime; this.exeTime = exeTime; this.tarTime = -1; this.waitTime = -1; this.isExecuting = false; } }
JavaScript
class TdVirtualScrollRowDirective extends TemplatePortalDirective { /** * @param {?} templateRef * @param {?} viewContainerRef */ constructor(templateRef, viewContainerRef) { super(templateRef, viewContainerRef); } }
JavaScript
class Kucoin { /** * You'll need to provide your KuCoin API key and secret. * @param {string} apiKey Your KuCoin API Key. * @param {string} apiSecret Your KuCoin API Secret. */ constructor(apiKey, apiSecret) { this._apiKey = apiKey this._apiSecret = apiSecret this.client = clients.createJsonClient({ url: 'https://api.kucoin.com' }) this.path_prefix = '/v1' } /** * Send the request to the KuCoin API, sign if authorisation is required. * @access private * @param {string} method HTTP request method, either 'get' or 'post'. * @param {string} endpoint API endpoint URL suffix. * @param {boolean} [signed=false] Whether this endpoint requires authentiation. * @param {Object} params Any parameters for the request. * @return {Promise} An object containing the API response. */ rawRequest(method, endpoint, signed = false, params) { let deferred = Q.defer() let path = this.path_prefix + endpoint let nonce = new Date().getTime() let queryString if (params !== undefined) { queryString = []; for (let key in params) { queryString.push(key + '=' + params[key]) } queryString.sort() queryString = queryString.join('&') } else { queryString = '' } let options = { path: path + (queryString ? '?' + queryString : ''), headers: {} } if (signed) { options.headers = { 'Content-Type': 'application/json', 'KC-API-KEY': this._apiKey, 'KC-API-NONCE': nonce, 'KC-API-SIGNATURE': this.getSignature(path, queryString, nonce) } } else { options.headers = { 'Content-Type': 'application/json' } } if (method == 'post') { this.client.post(options, {}, (err, req, res, obj) => { if (err || !obj.success) { if (!err && !obj.success) { err = obj } deferred.reject(err) } else { deferred.resolve(obj) } }) } else { this.client.get(options, (err, req, res, obj) => { if (err || !obj.success) { if (!err && !obj.success) { err = obj } deferred.reject(err) } else { deferred.resolve(obj) } }) } return deferred.promise } /** * Generate a signature to sign API requests that require authorisation. * @access private * @param {string} path API endpoint URL suffix. * @param {string} queryString A querystring of parameters for the request. * @param {number} nonce Number of milliseconds since the Unix epoch. * @return {string} A string to be used as the authorisation signature. */ getSignature(path, queryString, nonce) { let strForSign = path + '/' + nonce + '/' + queryString let signatureStr = new Buffer(strForSign).toString('base64') let signatureResult = crypto.createHmac('sha256', this._apiSecret) .update(signatureStr) .digest('hex') return signatureResult } /** * Do a standard public request. * @access private * @param {string} method HTTP request method, either 'get' or 'post'. * @param {string} endpoint API endpoint URL suffix. * @param {Object} params Any parameters for the request. * @return {Promise} An object containing the API response. */ doRequest(method, endpoint, params) { return this.rawRequest(method, endpoint, false, params) } /** * Do a signed private request. * @access private * @param {string} method HTTP request method, either 'get' or 'post'. * @param {string} endpoint API endpoint URL suffix. * @param {Object} params Any parameters for the request. * @return {Promise} An object containing the API response. */ doSignedRequest(method, endpoint, params) { return this.rawRequest(method, endpoint, true, params) } /** * Retrieve exchange rates for coins. * @access public * @param {{symbols: string[]}} [params] An Array of symbols, or if blank BTC will be returned. * @return {Promise} An object containing the API response. * @example <caption>Specify one or more symbols:</caption> * kc.getExchangeRates({ * symbols: ['NEO','GAS'] * }).then(console.log).catch(console.error) * * // Returns: * * { * "success": true, * "code": "OK", * "msg": "Operation succeeded.", * "timestamp": 1509589905631, * "data": { * "currencies": [["USD", "$"], ["EUR", "€"], ["AUD", "$"], ["CAD", "$"], ["CHF", "CHF"], ["CNY", "¥"], ["GBP", "£"], ["JPY", "¥"], ["NZD", "$"], ["BGN", "лв."], ["BRL", "R$"], ["CZK", "Kč"], ["DKK", "kr"], ["HKD", "$"], ["HRK", "kn"], ["HUF", "Ft"], ["IDR", "Rp"], ["ILS", "₪"], ["INR", "₹"], ["KRW", "₩"], ["MXN", "$"], ["MYR", "RM"], ["NOK", "kr"], ["PHP", "₱"], ["PLN", "zł"], ["RON", "lei"], ["RUB", "₽"], ["SEK", "kr"], ["SGD", "$"], ["THB", "฿"], ["TRY", "₺"], ["ZAR", "R"]], * "rates": { * "GAS": { "CHF": 14.57, "HRK": 94.19, "MXN": 279.02, "ZAR": 205.31, "INR": 939.59, "CNY": 96.15, "THB": 482.3, "AUD": 18.95, "ILS": 51.16, "KRW": 16176.81, "JPY": 1660.88, "PLN": 53.03, "GBP": 10.94, "IDR": 197577.69, "HUF": 3904.86, "PHP": 751.63, "TRY": 55.6, "RUB": 845.61, "HKD": 113.47, "EUR": 12.52, "DKK": 93.21, "USD": 14.54, "CAD": 18.77, "MYR": 61.54, "BGN": 24.49, "NOK": 118.5, "RON": 57.66, "SGD": 19.8, "CZK": 320.11, "SEK": 122.16, "NZD": 21.12, "BRL": 47.78 * }, * "NEO": { * "CHF": 25.33, "HRK": 163.66, "MXN": 484.81, "ZAR": 356.73, "INR": 1632.55, "CNY": 167.07, "THB": 838.01, "AUD": 32.94, "ILS": 88.89, "KRW": 28107.31, "JPY": 2885.78, "PLN": 92.14, "GBP": 19.01, "IDR": 343292.4, "HUF": 6784.72, "PHP": 1305.97, "TRY": 96.61, "RUB": 1469.25, "HKD": 197.16, "EUR": 21.76, "DKK": 161.95, "USD": 25.27, "CAD": 32.61, "MYR": 106.93, "BGN": 42.56, "NOK": 205.9, "RON": 100.18, "SGD": 34.4, "CZK": 556.2, "SEK": 212.27, "NZD": 36.7, "BRL": 83.02 * } * } * } * } * @example <caption>Retrieve data for BTC by default:</caption> * kc.getExchangeRates().then(console.log).catch(console.error) * * // Returns: * * { * "success": true, * "code": "OK", * "msg": "Operation succeeded.", * "timestamp": 1509590207497, * "data": { * "rates": { * "BTC": { "CHF": 6817.62, "HRK": 44045.89, "MXN": 130476.13, "ZAR": 96007.15, "INR": 439363.98, "CNY": 44963.39, "THB": 225531.1, "AUD": 8865.49, "ILS": 23923.57, "KRW": 7564405.86, "JPY": 776640.44, "PLN": 24798.21, "GBP": 5118.25, "IDR": 92388859.2, "HUF": 1825945.01, "PHP": 351470.78, "TRY": 26002.05, "RUB": 395413.97, "HKD": 53061.7, "EUR": 5857.14, "DKK": 43586.13, "USD": 6801.3, "CAD": 8777.75, "MYR": 28779.7, "BGN": 11455.42, "NOK": 55414.27, "RON": 26962.39, "SGD": 9259.28, "CZK": 149689.81, "SEK": 57127.51, "NZD": 9878.88, "BRL": 22344.99 * } * }, * "currencies": [["USD", "$"], ["EUR", "€"], ["AUD", "$"], ["CAD", "$"], ["CHF", "CHF"], ["CNY", "¥"], ["GBP", "£"], ["JPY", "¥"], ["NZD", "$"], ["BGN", "лв."], ["BRL", "R$"], ["CZK", "Kč"], ["DKK", "kr"], ["HKD", "$"], ["HRK", "kn"], ["HUF", "Ft"], ["IDR", "Rp"], ["ILS", "₪"], ["INR", "₹"], ["KRW", "₩"], ["MXN", "$"], ["MYR", "RM"], ["NOK", "kr"], ["PHP", "₱"], ["PLN", "zł"], ["RON", "lei"], ["RUB", "₽"], ["SEK", "kr"], ["SGD", "$"], ["THB", "฿"], ["TRY", "₺"], ["ZAR", "R"]] * } * } */ getExchangeRates(params = {}) { params.coins = (params.symbols ? params.symbols.join(',') : '') return this.doRequest('get', '/open/currencies', params) } /** * Retrieve a list of supported languages. * @access public * @return {Promise} An object containing the API response. * @example * kc.getLanguages().then(console.log).catch(console.error) * * // Returns: * * { * "success": true, * "code": "OK", * "msg": "Operation succeeded.", * "timestamp": 1509590811348, * "data": [["zh_CN", "中文简体", true], ["zh_HK", "中文繁体", true], ["en_US", "English", true], ["ja_JP", "日本語", true], ["ru_RU", "русский", true], ["pt_PT", "Portugues", true], ["de_DE", "Deutsch", true], ["nl_NL", "Nederlands", true], ["ko_KR", "한국어", true], ["fr_FR", "Français", true], ["es_ES", "Español", false]] * } */ getLanguages() { return this.doRequest('get', '/open/lang-list') } /** * Change the language for your account. * @access public * @param {{lang: string}} params The specific language locale to change to from the list provided by getLanguages. * @return {Promise} An object containing the API response. * @example * kc.changeLanguage({ * lang: 'en_US' * }).then(console.log).catch(console.error) * * // Returns: * * { * "success": true, * "code": "OK", * "msg": "Operation succeeded.", * "timestamp": 1509590866149, * "data": null * } */ changeLanguage(params = {}) { return this.doSignedRequest('post', '/user/change-lang', params) } /** * Get account information for the authenticated user. * @access public * @return {Promise} An object containing the API response. * @example * kc.getUserInfo().then(console.log).catch(console.error) * * // Returns: * * { * "success": true, * "code": "OK", * "msg": "Operation succeeded.", * "timestamp": 1509590943414, * "data": { * "referrer_code": "XXXXXX", * "photoCredentialValidated": false, * "videoValidated": false, * "language": "en_US", * "csrf": "XXXXXXXXXXXXXXXXXXXXXXX=", * "oid": "xxxxxxxxxxxxxxxxxxxxxxxx", * "baseFeeRate": 1, * "hasCredential": false, * "phoneValidated": true, * "phone": "", * "credentialValidated": false, * "googleTwoFaBinding": true, * "nickname": null, * "name": "", * "hasTradePassword": false, * "currency": null, * "emailValidated": true, * "email": "[email protected]" * } * } */ getUserInfo() { return this.doSignedRequest('get', '/user/info') } /** * Get the number of invitees from the authenticated user's referral code. * @access public * @return {Promise} An object containing the API response. * @example * kc.getInviteCount().then(console.log).catch(console.error) * * // Returns: * * { * "success": true, * "code": "OK", * "msg": "Operation succeeded.", * "timestamp": 1509591130780, * "data": { * "countThree": 0, * "count": 0, * "countTwo": 0 * } * } */ getInviteCount() { return this.doSignedRequest('get', '/referrer/descendant/count') } /** * Get promotion reward info. * @access public * @param {{symbol: string}} [params] The coin's symbol to retrieve reward info for. * @return {Promise} An object containing the API response. * @example <caption>Specify a symbol:</caption> * kc.getPromotionRewardInfo({ * symbol: 'NEO' * }).then(console.log).catch(console.error) * @example <caption>Retrieve data for all symbols:</caption> * kc.getPromotionRewardInfo().then(console.log).catch(console.error) * * // Returns: * * { * "success": true, * "code": "OK", * "msg": "Operation succeeded.", * "timestamp": 1509591205512, * "data": { * "grantCountDownSeconds": 219994, * "drawingCount": 0, * "assignedCount": 0 * } * } */ getPromotionRewardInfo(params = {}) { params.coin = (params.symbol ? params.symbol : '') return this.doSignedRequest('get', '/account/' + (params.symbol != undefined ? params.symbol + '/' : '') + 'promotion/info', params) } /** * Get promotion reward summary. * @access public * @param {{symbol: string}} [params] The coin's symbol to retrieve reward summary for. * @return {Promise} An object containing the API response. * @example <caption>Specify a symbol:</caption> * kc.getPromotionRewardSummary({ * symbol: 'NEO' * }).then(console.log).catch(console.error) * @example <caption>Retrieve data for all symbols:</caption> * kc.getPromotionRewardSummary().then(console.log).catch(console.error) * * // Returns: * * { * "success": true, * "code": "OK", * "msg": "Operation succeeded.", * "timestamp": 1509591324280, * "data": [] * } */ getPromotionRewardSummary(params = {}) { params.coin = (params.symbol ? params.symbol : '') return this.doSignedRequest('get', '/account/' + (params.symbol != undefined ? params.symbol + '/' : '') + 'promotion/sum') } /** * Retrieve the deposit address for a particular coin. * @access public * @param {{symbol: string}} params The coin's symbol to retrieve an address for. * @return {Promise} An object containing the API response. * @example * kc.getDepositAddress({ * symbol: 'NEO' * }).then(console.log).catch(console.error) * * // Returns: * * { * "success": true, * "code": "OK", * "msg": "Operation succeeded.", * "timestamp": 1509591494043, * "data": { * "oid": "xxxxxxxxxxxxxxxxxxxxxxxx", * "address": "Axxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxx", * "context": null, * "userOid": "xxxxxxxxxxxxxxxxxxxxxxxx", * "coinType": "GAS", * "createdAt": 1509354932000, * "deletedAt": null, * "updatedAt": 1509354932000, * "lastReceivedAt": 1509541029000 * } * } */ getDepositAddress(params = {}) { return this.doSignedRequest('get', '/account/' + params.symbol + '/wallet/address') } /** * Create a withdrawal request for the specified coin. * @access public * @param {{symbol: string, amount: number, address: string}} params Withdrawal details including the coin's symbol, amount, and address to withdraw to. * @return {Promise} An object containing the API response. * @example * kc.createWithdrawal({ * symbol: 'NEO', * amount: 5, * address: 'AWcAwoXK6gbMUTojHMHEx8FgEfaVK9Hz5s' * }).then(console.log).catch(console.error) */ createWithdrawal(params = {}) { params.coin = params.symbol return this.doSignedRequest('post', '/account/' + params.symbol + '/withdraw/apply', params) } /** * Cancel a withdrawal request for the specified coin. * @access public * @param {{symbol: string, txOid: string}} params Withdrawal details including the coin's symbol and transaction ID for the withdrawal. * @return {Promise} An object containing the API response. * @example * kc.cancelWithdrawal({ * symbol: 'NEO', * txOid: '59fa71673b7468701cd714a1' * }).then(console.log).catch(console.error) */ cancelWithdrawal(params = {}) { return this.doSignedRequest('post', '/account/' + params.symbol + '/withdraw/cancel', params) } /** * Retrieve deposit and withdrawal record history. * @access public * @param {{symbol: string, type: string, status: string, limit: number, page: number}} params Record details including the coin's symbol, type, status, limit, and page number for the records. * @return {Promise} An object containing the API response. * @example * kc.getDepositAndWithdrawalRecords({ * symbol: 'GAS' * }).then(console.log).catch(console.error) * * // Returns: * * { * "success": true, * "code": "OK", * "msg": "Operation succeeded.", * "timestamp": 1509591779228, * "data": { * "total": 2, * "firstPage": true, * "lastPage": false, * "datas": [{ * "coinType": "GAS", * "createdAt": 1509540909000, * "amount": 0.1117, * "address": "Axxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxx", * "fee": 0, * "outerWalletTxid": "xxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxx@Axxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxx@gas", * "remark": null, * "oid": "xxxxxxxxxxxxxxxxxxxxxxxx", * "confirmation": 7, * "type": "DEPOSIT", * "status": "SUCCESS", * "updatedAt": 1509541029000 * }, { * "coinType": "GAS", * "createdAt": 1509358609000, * "amount": 1.1249, * "address": "Axxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxx", * "fee": 0, * "outerWalletTxid": "xxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxx@Axxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxx@gas", * "remark": null, * "oid": "xxxxxxxxxxxxxxxxxxxxxxxx", * "confirmation": 6, * "type": "DEPOSIT", * "status": "SUCCESS", * "updatedAt": 1509358729000 * }], * "currPageNo": 1, * "limit": 12, * "pageNos": 1 * } * } */ getDepositAndWithdrawalRecords(params = {}) { return this.doSignedRequest('get', '/account/' + params.symbol + '/wallet/records', params) } /** * Retrieve balance for a particular coin. * @access public * @param {{symbol: string}} [params] The coin's symbol for the balance you want to retrieve. * @return {Promise} An object containing the API response. * @example <caption>Retrieve the balance for NEO:</caption> * kc.getBalance({ * symbol: 'NEO' * }).then(console.log).catch(console.error) * * // Returns: * * { * "success": true, * "code": "OK", * "msg": "Operation succeeded.", * "timestamp": 1509592077557, * "data": { * "coinType": "NEO", * "balanceStr": "10.72040467", * "freezeBalance": 0, * "balance": 10.72040467, * "freezeBalanceStr": "0.0" * } * } * @example <caption>Retrieve the balance for all coins (including zero balances):</caption> * kc.getBalance().then(console.log).catch(console.error) */ getBalance(params = {}) { return this.doSignedRequest('get', '/account/' + (params.symbol ? params.symbol + '/' : '') + 'balance') } /** * Create an order for the specified trading pair. * @access public * @param {{pair: string, amount: number, price: number, type: string}} params Order details including the trading pair, amount, price, and type of order. * @return {Promise} An object containing the API response. * @example <caption>Create an order to sell 5 GAS for NEO at the specified price:</caption> * kc.createWithdrawal({ * pair: 'GAS-NEO', * amount: 5, * price: 0.608004 * type: 'SELL' * }).then(console.log).catch(console.error) * * // Returns: * * { * success: true, * code: 'OK', * msg: 'OK', * timestamp: 1509592202904, * data: { * orderOid: 'xxxxxxxxxxxxxxxxxxxxxxxx' * } * } */ createOrder(params = {}) { params.symbol = params.pair return this.doSignedRequest('post', '/order', params) } /** * View a list of active orders for the specified trading pair * @access public * @param {{pair: string}} params The trading pair to retrieve orders for. * @return {Promise} An object containing the API response. * @example * kc.getActiveOrders({ * pair: 'GAS-NEO' * }).then(console.log).catch(console.error) * * // Returns: * * { * "success": true, * "code": "OK", * "msg": "Operation succeeded.", * "timestamp": 1509592278263, * "data": { * "SELL": [[1509592203000, "SELL", 1, 0.11206064, 0, "xxxxxxxxxxxxxxxxxxxxxxxx"]], * "BUY": [] * } * } */ getActiveOrders(params = {}) { params.symbol = params.pair return this.doSignedRequest('get', '/' + params.pair + '/order/active', params) } /** * Get the details of a specific order * * @access public * @param {{symbol: string, type: string, orderOid: string}} params * * @return {Promise} An object containing the API response. * * @example * * REQUEST: * kc.getOrderDetails( * { * "symbol": 'GAS-NEO', * "type": 'BUY', * "orderOid": '9ab18a37aefbe22ed1b406c9', * } * ).then(console.log).catch(console.error) * * RESPONSE: * { * "success": true, * "code": "OK", * "msg": "Operation succeeded.", * "timestamp": 1509592278263, * "data": * { * "coinType": "NEO", * "dealValueTotal": 0, * "feeTotal": 0, * "userOid": "9ab18a37aefbe22ed1b406c9", * "dealAmount": 0, * } * } * */ getOrderDetails(params = {}) { return this.doSignedRequest('get', '/order/detail', params); } /** * Cancel an order for the specified trading pair. * @access public * @param {{pair: string, txOid: string}} params Order details including the trading pair and transaction ID for the order. * @return {Promise} An object containing the API response. * @example * kc.cancelOrder({ * pair: 'GAS-NEO', * txOid: '59fa71673b7468701cd714a1' * }).then(console.log).catch(console.error) * * // Returns: * * { * success: true, * code: 'OK', * msg: 'Operation succeeded.', * timestamp: 1509592278426, * data: null * } */ cancelOrder(params = {}) { params.symbol = params.pair return this.doSignedRequest('post', '/cancel-order', params) } /** * Retrieve a list of completed orders for the specified trading pair. * @access public * @param {{pair: string, type: string, limit: number, page: number}} params Order details including the trading pair, type, limit, and page number for the orders. * @return {Promise} An object containing the API response. * @example * kc.getDealtOrders({ * pair: 'GAS-NEO' * }).then(console.log).catch(console.error) * * // Returns: * * { * "success": true, * "code": "OK", * "msg": "Operation succeeded.", * "timestamp": 1509592427203, * "data": { * "total": 1, * "firstPage": true, * "lastPage": false, * "datas": [{ * "coinType": "GAS", * "createdAt": 1509455416000, * "amount": 0.14494322, * "dealValue": 0.0929086, * "fee": 0.00009291, * "dealDirection": "SELL", * "coinTypePair": "NEO", * "oid": "xxxxxxxxxxxxxxxxxxxxxxxx", * "dealPrice": 0.641, * "orderOid": "xxxxxxxxxxxxxxxxxxxxxxxx", * "feeRate": 0.001, * "direction": "SELL" * }], * "currPageNo": 1, * "limit": 12, * "pageNos": 1 * } * } */ getDealtOrders(params = {}) { params.symbol = params.pair return this.doSignedRequest('get', '/' + params.pair + '/deal-orders', params) } /** * Retrieve current price ticker data for the specified trading pair. * @access public * @param {{pair: string}} params The trading pair to retrieve price ticker for. * @return {Promise} An object containing the API response. * @example * kc.getTicker({ * pair: 'GAS-NEO' * }).then(console.log).catch(console.error) * * // Returns: * * { * "success": true, * "code": "OK", * "msg": "Operation succeeded.", * "timestamp": 1509592566746, * "data": { * "coinType": "GAS", * "trading": true, * "symbol": "GAS-NEO", * "lastDealPrice": 0.627999, * "buy": 0.608004, * "sell": 0.628, * "change": 0.019994, * "coinTypePair": "NEO", * "sort": 0, * "feeRate": 0.001, * "volValue": 5246.36133161, * "high": 0.635, * "datetime": 1509592566000, * "vol": 8499.38951847, * "low": 0.601101, * "changeRate": 0.0329 * } * } */ getTicker(params = {}) { return this.doRequest('get', '/' + params.pair + '/open/tick') } /** * Retrieve a list of orders for the specified trading pair. * @access public * @param {{pair: string, type: string, group: number, limit: number}} params Order book details including the trading pair, type, group, and limit for the orders. * @return {Promise} An object containing the API response. * @example <caption>Retrieve all orders currently on the books for the GAS-NEO trading pair:</caption> * kc.getOrderBooks({ * pair: 'GAS-NEO' * }).then(console.log).catch(console.error) * * // Returns: * * { * "success": true, * "code": "OK", * "msg": "Operation succeeded.", * "timestamp": 1509592645132, * "data": { * "SELL": [[0.628, 227.1374, 142.6422872], [0.632999, 10, 6.32999], [0.633, 4.20740806, 2.6632893], [0.65, 0.6346, 0.41249], [0.6611, 6.7998, 4.49534778], [0.665699, 0.1875, 0.12481856]], * "BUY": [[0.608004, 9.8481, 5.98768419], [0.608003, 21.9264, 13.33131698], [0.608001, 43.8442, 26.65731744], [0.604001, 25.5521, 15.43349395], [0.603, 1.0561, 0.6368283], [0.602006, 25, 15.05015]] * } * } * @example <caption>Retrieve only SELL orders currently on the books for the GAS-NEO trading pair:</caption> * kc.getOrderBooks({ * pair: 'GAS-NEO', * type: 'SELL' * }).then(console.log).catch(console.error) * * // Returns: * * { * "success": true, * "code": "OK", * "msg": "Operation succeeded.", * "timestamp": 1509592734633, * "data": [[0.628, 227.1374, 142.6422872], [0.632999, 10, 6.32999], [0.633, 4.20740806, 2.6632893], [0.65, 0.6346, 0.41249], [0.6611, 6.7998, 4.49534778], [0.665699, 0.1875, 0.12481856]] * } */ getOrderBooks(params = {}) { params.symbol = params.pair return this.doRequest('get', '/' + params.pair + '/open/orders' + (params.type ? '-' + params.type.toLowerCase() : ''), params) } /** * Retrieve a list of recently completed orders for the specified trading pair. * @access public * @param {{pair: string, limit: number, since: number}} params Order book details including the trading pair, limit, and since for the orders. * @return {Promise} An object containing the API response. * @example * kc.getRecentlyDealtOrders({ * pair: 'GAS-NEO' * }).then(console.log).catch(console.error) * * // Returns: * * { * "success": true, * "code": "OK", * "msg": "Operation succeeded.", * "timestamp": 1509592783348, * "data": [[1509591191000, "SELL", 0.608005, 10.771, 6.54882186], [1509591198000, "SELL", 0.608005, 10.7648, 6.54505222], [1509591512000, "SELL", 0.608005, 13.0292, 7.92181875], [1509591714000, "BUY", 0.627999, 19.9774, 12.54578722], [1509591951000, "SELL", 0.608005, 15.6217, 9.49807171], [1509592026000, "SELL", 0.608005, 15.2009, 9.2422232], [1509592105000, "SELL", 0.608005, 13.4969, 8.20618268], [1509592219000, "BUY", 0.627999, 20.9506, 13.15695585], [1509592311000, "BUY", 0.627999, 23.5278, 14.77543487], [1509592724000, "SELL", 0.608005, 8.6837, 5.27973302]] * } */ getRecentlyDealtOrders(params = {}) { return this.doRequest('get', '/' + params.pair + '/open/deal-orders', params) } /** * Retrieve a list of available trading pairs. * @access public * @return {Promise} An object containing the API response. * @example * kc.getTradingSymbols().then(console.log).catch(console.error) * * // Returns: * * { * "success": true, * "code": "OK", * "msg": "Operation succeeded.", * "timestamp": 1509592839027, * "data": [{ * "coinType": "KCS", * "trading": true, * "symbol": "KCS-BTC", * "lastDealPrice": 0.00009277, * "buy": 0.00009003, * "sell": 0.0000927, * "change": -0.00000322, * "coinTypePair": "BTC", * "sort": 0, * "feeRate": 0.001, * "volValue": 139.78123495, * "high": 0.00012281, * "datetime": 1509592836000, * "vol": 1347022.79127505, * "low": 0.0000835, * "changeRate": -0.0335 * }, { * ... * }] * } */ getTradingSymbols() { return this.doRequest('get', '/market/open/symbols') } /** * Retrieve a list of trending trading pairs. * @access public * @return {Promise} An object containing the API response. * @example * kc.getTrending().then(console.log).catch(console.error) * * // Returns: * * { * "success": true, * "code": "OK", * "msg": "Operation succeeded.", * "timestamp": 1509593321973, * "data": [{ * "coinPair": "KCS-BTC", * "deals": [[1509591600000, 0.0000928], [1509588000000, 0.00009421], [1509584400000, 0.00009134], [1509580800000, 0.000096], [1509577200000, 0.00010014], [1509573600000, 0.00010293], [1509570000000, 0.00010368], [1509566400000, 0.000107], [1509562800000, 0.00010496], [1509559200000, 0.0001057], [1509555600000, 0.000108], [1509552000000, 0.0001117], [1509548400000, 0.0001142], [1509544800000, 0.000114], [1509541200000, 0.000114], [1509537600000, 0.0001135], [1509534000000, 0.0001135], [1509530400000, 0.0001011], [1509526800000, 0.00010799], [1509523200000, 0.00011405], [1509519600000, 0.0001164], [1509516000000, 0.00012099], [1509512400000, 0.00012107], [1509508800000, 0.00012244], [1509505200000, 0.00012281], [1509501600000, 0.00012295], [1509498000000, 0.00012348], [1509494400000, 0.0001242], [1509490800000, 0.00012895], [1509487200000, 0.00012897], [1509483600000, 0.00012899], [1509480000000, 0.00012849], [1509476400000, 0.00012987], [1509472800000, 0.00013], [1509469200000, 0.00013188], [1509465600000, 0.00012978], [1509462000000, 0.00012978], [1509458400000, 0.000126], [1509454800000, 0.00012978], [1509451200000, 0.00012562], [1509447600000, 0.00012999], [1509444000000, 0.00013009], [1509440400000, 0.0001346], [1509436800000, 0.00013465], [1509433200000, 0.00013465], [1509429600000, 0.00013376], [1509426000000, 0.00013465], [1509422400000, 0.00013457], [1509418800000, 0.00013489], [1509415200000, 0.00013693], [1509411600000, 0.0001329], [1509408000000, 0.00013499], [1509404400000, 0.00013711], [1509400800000, 0.00013723], [1509397200000, 0.00013999], [1509393600000, 0.00013992], [1509390000000, 0.00014195], [1509386400000, 0.00014284], [1509382800000, 0.0001425], [1509379200000, 0.00014286], [1509375600000, 0.00014406], [1509372000000, 0.00014591], [1509368400000, 0.00014647], [1509364800000, 0.0001457], [1509361200000, 0.00014575], [1509357600000, 0.00014659], [1509354000000, 0.00014998], [1509350400000, 0.0001517], [1509346800000, 0.0001488], [1509343200000, 0.0001488], [1509339600000, 0.00014999], [1509336000000, 0.0001521]] * }, { * ... * }] * } */ getTrending() { return this.doRequest('get', '/market/open/coins-trending') } /** * Retrieve a list of available coins. * @access public * @return {Promise} An object containing the API response. * @example * kc.getCoins().then(console.log).catch(console.error) * * // Returns: * * { * "success": true, * "code": "OK", * "msg": "Operation succeeded.", * "timestamp": 1509593539250, * "data": [{ * "withdrawMinFee": 2, * "withdrawMinAmount": 50, * "withdrawFeeRate": 0.001, * "confirmationCount": 12, * "name": "Kucoin Shares", * "tradePrecision": 4, * "enableWithdraw": true, * "enableDeposit": true, * "coin": "KCS" * }, { * ... * }] * } */ getCoins() { return this.doRequest('get', '/market/open/coins-list') } }
JavaScript
class MockMock { constructor() { this.replayCalled = false; this.resetCalled = false; this.verifyCalled = false; this.tearDownCalled = false; } }
JavaScript
class Command { /** * Creates new Command instance * @param {Client} client * @param {CommandOptions} options */ constructor(client, options = {}) { /** * Client * @type {Client} */ this.client = client; /** * Name * @type {string} */ this.name = resolveString(options.name); /** * ContextMenuName * @type {string} */ this.contextMenuName = resolveString(options.contextMenuName); /** * Description * @type {string} */ this.description = resolveString(options.description); /** * Cooldown * @type {string} */ this.cooldown = resolveString(options.cooldown); /** * ExpectedArgs * @type {string | Array} * @deprecated */ this.expectedArgs = options.expectedArgs; /** * Args * @type {CommandArgsOption[]} */ this.args = options.args ? options.args.map(arg => { const types = arg.channel_types ? !Array.isArray(arg.channel_types) ? [arg.channel_types] : arg.channel_types : []; const final = []; for (const type of types) { final.push(ArgumentChannelTypes[type]); } if (final.length !== 0) arg.channel_types = final; return arg; }) : null; /** * AlwaysObtain * @type {boolean} */ this.alwaysObtain = options.alwaysObtain ? Boolean(options.alwaysObtain) : false; /** * MinArgs * @type {number} * @deprecated use args */ this.minArgs = Number(options.minArgs); /** * UserRequiredPermissions * @type {string | Array} */ this.userRequiredPermissions = options.userRequiredPermissions; /** * UserRequiredRoles * @type {string | Array} */ this.userRequiredRoles = options.userRequiredRoles; /** * ClientRequiredPermissions * @type {string | Array} */ this.clientRequiredPermissions = options.clientRequiredPermissions; /** * UserOnly * @type {Snowflake | Array} */ this.userOnly = options.userOnly; /** * ChannelOnly * @type {Snowflake | Array} */ this.channelOnly = options.channelOnly; /** * ChannelTextOnly * @type {boolean} */ this.channelTextOnly = options.channelTextOnly; /** * ChannelNewsOnly * @type {boolean} */ this.channelNewsOnly = options.channelNewsOnly; /** * ChannelThreadOnly * @type {boolean} */ this.channelThreadOnly = options.channelThreadOnly; /** * AllowDm * @type {boolean} */ this.allowDm = options.allowDm; /** * GuildOnly * @type {Snowflake | Array} */ this.guildOnly = options.guildOnly ? Array.isArray(options.guildOnly) ? options.guildOnly : Array(options.guildOnly) : undefined; /** * Nsfw * @type {boolean} */ this.nsfw = options.nsfw; /** * Slash * @type {boolean} */ this.slash = options.slash; /** * Context * @type {GCommandsOptionsCommandsContext} */ this.context = options.context; /** * Aliases * @type {Array} */ this.aliases = Array.isArray(options.aliases) ? options.aliases : Array(options.aliases); /** * Category * @type {string} */ this.category = resolveString(options.category); /** * Usage * @type {string} */ this.usage = resolveString(options.usage); /** * Command Path * @type {string} * @private */ this._path; /** * Options, ability to add own options * @type {Object} */ this._options = options; } /** * Run function * @param {CommandRunOptions} options * @param {Array} arrayArgs * @param {Object} objectArgs */ async run(options, arrayArgs, objectArgs) { // eslint-disable-line no-unused-vars, require-await throw new GError('[COMMAND]',`Command ${this.name} doesn't provide a run method!`); } /** * Reloads the command */ async reload() { const cmdPath = this.client.gcommands.get(this.name)._path; delete require.cache[require.resolve(cmdPath)]; this.client.gcommands.delete(this.name); let newCommand = await require(cmdPath); if (!isClass(newCommand)) throw new GError('[COMMAND]',`Command ${this.name} must be class!`); else newCommand = new newCommand(this.client); if (!(newCommand instanceof Command)) throw new GError('[COMMAND]',`Command ${newCommand.name} doesnt belong in Commands.`); if (newCommand.name !== this.name) throw new GError('[COMMAND]','Command name cannot change.'); const nglds = newCommand.guildOnly ? Array.isArray(newCommand.guildOnly) ? newCommand.guildOnly : Array(newCommand.guildOnly) : undefined; const check1 = nglds.every((x, i) => x === this.guildOnly[i]); const check2 = this.guildOnly.every((x, i) => x === nglds[i]); if (!check1 || !check2) throw new GError('[COMMAND]','Command guildOnly cannot change.'); newCommand._path = cmdPath; this.client.gcommands.set(newCommand.name, newCommand); return true; } }
JavaScript
class RaceGame extends VehicleGame { // The level of nitrous injection that should be available to participants. static kNitrousInjectionNone = 0; static kNitrousInjectionSingleShot = 1; static kNitrousInjectionFiveShot = 5; static kNitrousInjectionTenShot = 10; static kNitrousInjectionInfinite = 100; #airborne_ = null; #database_ = null; #description_ = null; #disposed_ = false; #infiniteHealth_ = null; #infiniteHealthTime_ = null; #nitrousInjection_ = RaceGame.kNitrousInjectionNone; #nitrousInjectionTime_ = null; #checkpoint_ = new WeakMap(); #finished_ = 0; #progression_ = new WeakMap(); #results_ = new WeakMap(); #scoreboard_ = new Map(); #start_ = null; async onInitialized(settings, userData) { await super.onInitialized(settings, userData); this.#database_ = userData.database; // (1) Make sure that we understand which race |this| instance is being created for. this.#description_ = userData.registry.getDescription(settings.get('game/description_id')); if (!this.#description_) throw new Error(`Invalid race ID specified in ${this}.`); // (2) Determine whether this is a ground race or an air race. if (!this.#description_.spawnPositions || !this.#description_.spawnPositions.length) throw new Error(`Expected at least one spawn position to be defined for the race.`); const vehicleModelId = this.#description_.spawnPositions[0].vehicleModelId; const vehicleModel = VehicleModel.getById(vehicleModelId); if (!vehicleModel) throw new Error(`Invalid vehicle model supplied for a race: ${vehicleModelId}.`); this.#airborne_ = vehicleModel.isAirborne(); // (3) Determine the level of nitrous injection that should be available to participants. if (this.#description_.settings.unlimitedNos) this.#nitrousInjection_ = RaceGame.kNitrousInjectionInfinite; else if ([ 1, 5, 10 ].includes(this.#description_.settings.nos)) this.#nitrousInjection_ = this.#description_.settings.nos; // (4) Determine if infinite health should be available to participants. this.#infiniteHealth_ = this.#description_.settings.disableVehicleDamage; this.#infiniteHealthTime_ = server.clock.monotonicallyIncreasingTime(); // (5) Start the quick timer that runs until the race has finished. this.quickTimer(); } async onPlayerAdded(player) { await super.onPlayerAdded(player); // If the |player| has an account and is identified, load their personal high scores for the // race so that they can play against themselves if nobody else. if (player.account.isIdentified()) { this.#database_.readResults(player, this.#description_).then(results => { if (!results.length) return; // no results could be loaded for the |player| if (this.#scoreboard_.has(player)) this.#scoreboard_.get(player).updateHighscore(results); else this.#results_.set(player, results); }); } } async onPlayerSpawned(player, countdown) { await super.onPlayerSpawned(player, countdown); // Spawning is highly asynchronous, it's possible they've disconnected since. It's important // to note that the |player| might not be in their vehicle yet. if (!player.isConnected()) return; // Players only spawn once in a race, so we have to display our own countdown to them. First // disable their engines, then display the countdown, then enable their engines. const vehicle = this.getVehicleForPlayer(player); if (!vehicle) throw new Error(`${this}: expected a vehicle to have been created.`); // Apply the non-infinite nitrous injection components to their vehicle. switch (this.#nitrousInjection_) { case RaceGame.kNitrousInjectionInfinite: this.#nitrousInjectionTime_ = server.clock.monotonicallyIncreasingTime(); /* deliberate fall-through */ case RaceGame.kNitrousInjectionSingleShot: vehicle.addComponent(Vehicle.kComponentNitroSingleShot); break; case RaceGame.kNitrousInjectionFiveShot: vehicle.addComponent(Vehicle.kComponentNitroFiveShots); break; case RaceGame.kNitrousInjectionTenShot: vehicle.addComponent(Vehicle.kComponentNitroTenShots); break; } // Disable their engine, so that they can't drive off while the countdown is active. vehicle.toggleEngine(/* engineRunning= */ false); // Create the |player|'s progression tracker, and display the first checkpoint for them. const tracker = new RaceProgressionTracker( this.#description_.checkpoints, this.#description_.settings.laps); this.updateCheckpoint(player, tracker); this.#progression_.set(player, tracker); // Create the scoreboard for the |player|, and load their personal best times. If they are // not yet available, give up - we've already waited ~2 seconds. const scoreboard = new Scoreboard(player, tracker, this.players); if (this.#results_.has(player)) scoreboard.updateHighscore(this.#results_.get(player)); this.#scoreboard_.set(player, scoreboard); // Display the start countdown for the |player|. They'll be getting ready... await StartCountdown.displayForPlayer( player, kStartCountdownSeconds, () => this.players.has(player)); // Again, verify that they're still part of this game before re-enabling their engine, and // throw them out if they're no longer in their vehicle. This is a bit tedious. if (!player.isConnected() || !this.players.has(player)) return; if (player.vehicle !== vehicle) return this.playerLost(player); player.vehicle.toggleEngine(/* engineRunning= */ true); // Start the |player|'s progression tracker, and mark |this| race as having started if this // is the first player who we'll be unlocking. if (!this.#start_) this.#start_ = server.clock.monotonicallyIncreasingTime(); tracker.start(); } // Updates and creates the checkpoint for the |player|. This tells them where to go, and also // gives us the necessary metrics for determining where they are. updateCheckpoint(player, tracker) { const checkpointInfo = tracker.getCurrentCheckpoint(); if (!checkpointInfo) return; // the |player| has finished the race let checkpointType = null; // Determine the type of checkpoint that should be shown. This depends on whether it's an // airborne race, as well on whether the |checkpointInfo| is the final one. if (this.#airborne_) { checkpointType = checkpointInfo.final ? RaceCheckpoint.kTypeAirborneFinish : RaceCheckpoint.kTypeAirborneNormal; } else { checkpointType = checkpointInfo.final ? RaceCheckpoint.kTypeGroundedFinish : RaceCheckpoint.kTypeGroundedNormal; } // Create the checkpoint instance, and show it to the |player|. The checkpoint manager will // already have deleted the previously showing checkpoint. const checkpoint = new RaceCheckpoint( checkpointType, checkpointInfo.position, checkpointInfo.target ?? checkpointInfo.position, checkpointInfo.size); checkpoint.displayForPlayer(player).then(entered => { if (entered) this.onPlayerEnterCheckpoint(player); }); this.#checkpoint_.set(player, checkpoint); } // Returns an array with all the participants, ordered by their position within the race. This // is determined based on their getRankedParticipants() { const progress = []; // (a) Iterate over all participants, and get their progression into the race, as // well as their distance from their previous checkpoint. The participants will be // sorted on these values, to be able to drop them out in order. for (const player of this.players) { const tracker = this.#progression_.get(player); if (!tracker) { progress.push([ player, /* progress= */ 0, /* distance= */ 0 ]); } else { const checkpointInfo = tracker.getCurrentCheckpoint(); if (!checkpointInfo) { progress.push([ player, tracker.progress, /* distance= */ 0 ]); } else { progress.push([ player, tracker.progress, checkpointInfo.position.distanceTo(player.position) ]); } } } // (b) Sort the participants based on the |progress| they've made. progress.sort((lhs, rhs) => { if (lhs[1] === rhs[1]) return lhs[2] > rhs[2] ? 1 : -1; return lhs[1] > rhs[1] ? -1 : 1; }); // (c) Return a new array with just the participants. return progress.map(entry => entry[0]); } // Called when the |player| has entered a checkpoint that was created by this race. We split // their progress, and determine whether there's a next checkpoint to show. onPlayerEnterCheckpoint(player) { const tracker = this.#progression_.get(player); if (!tracker) return; // the may've just dropped out of the race tracker.split(); // If the player hasn't finished, proceed to the next checkpoint and bail out. if (tracker.progress < 1) { const scoreboard = this.#scoreboard_.get(player); if (scoreboard && player.account.isIdentified()) scoreboard.updateHighscoreInterval(); return this.updateCheckpoint(player, tracker); } Banner.displayForPlayer(player, { title: 'congratulations!', message: format('you have finished the %s race', this.#description_.name), }); // Store the |player|'s racing times in the database, for future reference. This will be // done asynchronously, as the results don't have to be readily available. if (player.account.isIdentified()) { this.#database_.storeResults( player, this.#description_, ++this.#finished_, tracker.results); } this.playerWon(player, tracker.time / 1000); } async onTick() { await super.onTick(); const currentTime = server.clock.monotonicallyIncreasingTime(); // (1) If infinite nitrous has been configured, re-issue it to all participant's vehicles // every |kNitrousInjectionIssueTimeMs| to remove the regular cooldown time. if ((currentTime - this.#nitrousInjectionTime_) >= kNitrousInjectionIssueTimeMs) { for (const player of this.players) { if (player.vehicle) player.vehicle.addComponent(Vehicle.kComponentNitroSingleShot); } this.#nitrousInjectionTime_ = currentTime; } // (2) If infinite health has been enabled, repair all participant's vehicles every bunch of // milliseconds to not just make them drive great, but also to make them look great. if (this.#infiniteHealth_ && (currentTime - this.#infiniteHealthTime_) >= kVehicleDamageRepairTimeMs) { for (const player of this.players) { if (player.vehicle) player.vehicle.repair(); } this.#infiniteHealthTime_ = currentTime; } // (3) If the race has already started, and is past the allowed time limit for the race, we // will have to drop out all the participants in order of progression. if (this.#start_) { const runtimeSeconds = (currentTime - this.#start_) / 1000; if (runtimeSeconds >= this.#description_.settings.timeLimit) { for (const player of this.getRankedParticipants()) { Banner.displayForPlayer(player, { title: 'dropped out!', message: `you've exceeded the maximum time`, }); this.playerLost(player); } } } // (4) Participants who left their vehicle will be dropped out of the race, unless this has // been allowed by the race. Only run this check when the race has started. if (!this.#description_.settings.allowLeaveVehicle && this.#start_) { for (const player of this.players) { const vehicle = this.getVehicleForPlayer(player); if (vehicle !== player.vehicle) { Banner.displayForPlayer(player, { title: 'dropped out!', message: `you're no longer in your vehicle`, }); this.playerLost(player); } } } // (5) Update the positions between the players on the scoreboards that are being displayed // on their screens. This only has to be done once the race has started. if (this.#start_) { const participants = this.getRankedParticipants(); for (const [ index, player ] of participants.entries()) { const scoreboard = this.#scoreboard_.get(player); if (scoreboard) scoreboard.updatePositions(participants, index + 1); } } } async quickTimer() { while (!this.#disposed_ && !this.#start_) await wait(kQuickTimerFrequencyMs); while (!this.#disposed_) { const duration = server.clock.monotonicallyIncreasingTime() - this.#start_; for (const scoreboard of this.#scoreboard_.values()) scoreboard.updateTime(duration); await wait(kQuickTimerFrequencyMs); } } async onPlayerRemoved(player) { await super.onPlayerRemoved(player); if (this.#checkpoint_.has(player)) { this.#checkpoint_.get(player).hideForPlayer(player); this.#checkpoint_.delete(player); } if (this.#scoreboard_.has(player)) { this.#scoreboard_.get(player).dispose(); this.#scoreboard_.delete(player); } this.#results_.delete(player); } async onFinished() { await super.onFinished(); this.#disposed_ = true; } }
JavaScript
class V1LoadBalancerIngress { static getAttributeTypeMap() { return V1LoadBalancerIngress.attributeTypeMap; } }
JavaScript
class PostStreamScrubber extends Component { init() { this.handlers = {}; /** * The index of the post that is currently at the top of the viewport. * * @type {Number} */ this.index = 0; /** * The number of posts that are currently visible in the viewport. * * @type {Number} */ this.visible = 1; /** * The description to render on the scrubber. * * @type {String} */ this.description = ''; // When the post stream begins loading posts at a certain index, we want our // scrubber scrollbar to jump to that position. this.props.stream.on('unpaused', this.handlers.streamWasUnpaused = this.streamWasUnpaused.bind(this)); // Define a handler to update the state of the scrollbar to reflect the // current scroll position of the page. this.scrollListener = new ScrollListener(this.onscroll.bind(this)); // Create a subtree retainer that will always cache the subtree after the // initial draw. We render parts of the scrubber using this because we // modify their DOM directly, and do not want Mithril messing around with // our changes. this.subtree = new SubtreeRetainer(() => true); } view() { const retain = this.subtree.retain(); const count = this.count(); const unreadCount = this.props.stream.discussion.unreadCount(); const unreadPercent = count ? Math.min(count - this.index, unreadCount) / count : 0; const viewing = app.translator.transChoice('core.forum.post_scrubber.viewing_text', count, { index: <span className="Scrubber-index">{retain || formatNumber(Math.min(Math.ceil(this.index + this.visible), count))}</span>, count: <span className="Scrubber-count">{formatNumber(count)}</span> }); function styleUnread(element, isInitialized, context) { const $element = $(element); const newStyle = { top: (100 - unreadPercent * 100) + '%', height: (unreadPercent * 100) + '%' }; if (context.oldStyle) { $element.stop(true).css(context.oldStyle).animate(newStyle); } else { $element.css(newStyle); } context.oldStyle = newStyle; } return ( <div className={'PostStreamScrubber Dropdown ' + (this.disabled() ? 'disabled ' : '') + (this.props.className || '')}> <button className="Button Dropdown-toggle" data-toggle="dropdown"> {viewing} {icon('fas fa-sort')} </button> <div className="Dropdown-menu dropdown-menu"> <div className="Scrubber"> <a className="Scrubber-first" onclick={this.goToFirst.bind(this)}> {icon('fas fa-angle-double-up')} {app.translator.trans('core.forum.post_scrubber.original_post_link')} </a> <div className="Scrubber-scrollbar"> <div className="Scrubber-before"/> <div className="Scrubber-handle"> <div className="Scrubber-bar"/> <div className="Scrubber-info"> <strong>{viewing}</strong> <span className="Scrubber-description">{retain || this.description}</span> </div> </div> <div className="Scrubber-after"/> <div className="Scrubber-unread" config={styleUnread}> {app.translator.trans('core.forum.post_scrubber.unread_text', {count: unreadCount})} </div> </div> <a className="Scrubber-last" onclick={this.goToLast.bind(this)}> {icon('fas fa-angle-double-down')} {app.translator.trans('core.forum.post_scrubber.now_link')} </a> </div> </div> </div> ); } /** * Go to the first post in the discussion. */ goToFirst() { this.props.stream.goToFirst(); this.index = 0; this.renderScrollbar(true); } /** * Go to the last post in the discussion. */ goToLast() { this.props.stream.goToLast(); this.index = this.count(); this.renderScrollbar(true); } /** * Get the number of posts in the discussion. * * @return {Integer} */ count() { return this.props.stream.count(); } /** * When the stream is unpaused, update the scrubber to reflect its position. */ streamWasUnpaused() { this.update(window.pageYOffset); this.renderScrollbar(true); } /** * Check whether or not the scrubber should be disabled, i.e. if all of the * posts are visible in the viewport. * * @return {Boolean} */ disabled() { return this.visible >= this.count(); } /** * When the page is scrolled, update the scrollbar to reflect the visible * posts. * * @param {Integer} top */ onscroll(top) { const stream = this.props.stream; if (stream.paused || !stream.$()) return; this.update(top); this.renderScrollbar(); } /** * Update the index/visible/description properties according to the window's * current scroll position. * * @param {Integer} scrollTop */ update(scrollTop) { const stream = this.props.stream; const marginTop = stream.getMarginTop(); const viewportTop = scrollTop + marginTop; const viewportHeight = $(window).height() - marginTop; // Before looping through all of the posts, we reset the scrollbar // properties to a 'default' state. These values reflect what would be // seen if the browser were scrolled right up to the top of the page, // and the viewport had a height of 0. const $items = stream.$('> .PostStream-item[data-index]'); let index = $items.first().data('index') || 0; let visible = 0; let period = ''; // Now loop through each of the items in the discussion. An 'item' is // either a single post or a 'gap' of one or more posts that haven't // been loaded yet. $items.each(function() { const $this = $(this); const top = $this.offset().top; const height = $this.outerHeight(true); // If this item is above the top of the viewport, skip to the next // one. If it's below the bottom of the viewport, break out of the // loop. if (top + height < viewportTop) { return true; } if (top > viewportTop + viewportHeight) { return false; } // Work out how many pixels of this item are visible inside the viewport. // Then add the proportion of this item's total height to the index. const visibleTop = Math.max(0, viewportTop - top); const visibleBottom = Math.min(height, viewportTop + viewportHeight - top); const visiblePost = visibleBottom - visibleTop; if (top <= viewportTop) { index = parseFloat($this.data('index')) + visibleTop / height; } if (visiblePost > 0) { visible += visiblePost / height; } // If this item has a time associated with it, then set the // scrollbar's current period to a formatted version of this time. const time = $this.data('time'); if (time) period = time; }); this.index = index; this.visible = visible; this.description = period ? moment(period).format('MMMM YYYY') : ''; } config(isInitialized, context) { if (isInitialized) return; context.onunload = this.ondestroy.bind(this); this.scrollListener.start(); // Whenever the window is resized, adjust the height of the scrollbar // so that it fills the height of the sidebar. $(window).on('resize', this.handlers.onresize = this.onresize.bind(this)).resize(); // When any part of the whole scrollbar is clicked, we want to jump to // that position. this.$('.Scrubber-scrollbar') .bind('click', this.onclick.bind(this)) // Now we want to make the scrollbar handle draggable. Let's start by // preventing default browser events from messing things up. .css({ cursor: 'pointer', 'user-select': 'none' }) .bind('dragstart mousedown touchstart', e => e.preventDefault()); // When the mouse is pressed on the scrollbar handle, we capture some // information about its current position. We will store this // information in an object and pass it on to the document's // mousemove/mouseup events later. this.dragging = false; this.mouseStart = 0; this.indexStart = 0; this.$('.Scrubber-handle') .css('cursor', 'move') .bind('mousedown touchstart', this.onmousedown.bind(this)) // Exempt the scrollbar handle from the 'jump to' click event. .click(e => e.stopPropagation()); // When the mouse moves and when it is released, we pass the // information that we captured when the mouse was first pressed onto // some event handlers. These handlers will move the scrollbar/stream- // content as appropriate. $(document) .on('mousemove touchmove', this.handlers.onmousemove = this.onmousemove.bind(this)) .on('mouseup touchend', this.handlers.onmouseup = this.onmouseup.bind(this)); } ondestroy() { this.scrollListener.stop(); this.props.stream.off('unpaused', this.handlers.streamWasUnpaused); $(window) .off('resize', this.handlers.onresize); $(document) .off('mousemove touchmove', this.handlers.onmousemove) .off('mouseup touchend', this.handlers.onmouseup); } /** * Update the scrollbar's position to reflect the current values of the * index/visible properties. * * @param {Boolean} animate */ renderScrollbar(animate) { const percentPerPost = this.percentPerPost(); const index = this.index; const count = this.count(); const visible = this.visible || 1; const $scrubber = this.$(); $scrubber.find('.Scrubber-index').text(formatNumber(Math.min(Math.ceil(index + visible), count))); $scrubber.find('.Scrubber-description').text(this.description); $scrubber.toggleClass('disabled', this.disabled()); const heights = {}; heights.before = Math.max(0, percentPerPost.index * Math.min(index, count - visible)); heights.handle = Math.min(100 - heights.before, percentPerPost.visible * visible); heights.after = 100 - heights.before - heights.handle; const func = animate ? 'animate' : 'css'; for (const part in heights) { const $part = $scrubber.find(`.Scrubber-${part}`); $part.stop(true, true)[func]({height: heights[part] + '%'}, 'fast'); // jQuery likes to put overflow:hidden, but because the scrollbar handle // has a negative margin-left, we need to override. if (func === 'animate') $part.css('overflow', 'visible'); } } /** * Get the percentage of the height of the scrubber that should be allocated * to each post. * * @return {Object} * @property {Number} index The percent per post for posts on either side of * the visible part of the scrubber. * @property {Number} visible The percent per post for the visible part of the * scrubber. */ percentPerPost() { const count = this.count() || 1; const visible = this.visible || 1; // To stop the handle of the scrollbar from getting too small when there // are many posts, we define a minimum percentage height for the handle // calculated from a 50 pixel limit. From this, we can calculate the // minimum percentage per visible post. If this is greater than the actual // percentage per post, then we need to adjust the 'before' percentage to // account for it. const minPercentVisible = 50 / this.$('.Scrubber-scrollbar').outerHeight() * 100; const percentPerVisiblePost = Math.max(100 / count, minPercentVisible / visible); const percentPerPost = count === visible ? 0 : (100 - percentPerVisiblePost * visible) / (count - visible); return { index: percentPerPost, visible: percentPerVisiblePost }; } onresize() { this.scrollListener.update(true); // Adjust the height of the scrollbar so that it fills the height of // the sidebar and doesn't overlap the footer. const scrubber = this.$(); const scrollbar = this.$('.Scrubber-scrollbar'); scrollbar.css('max-height', $(window).height() - scrubber.offset().top + $(window).scrollTop() - parseInt($('#app').css('padding-bottom'), 10) - (scrubber.outerHeight() - scrollbar.outerHeight())); } onmousedown(e) { this.mouseStart = e.clientY || e.originalEvent.touches[0].clientY; this.indexStart = this.index; this.dragging = true; this.props.stream.paused = true; $('body').css('cursor', 'move'); } onmousemove(e) { if (!this.dragging) return; // Work out how much the mouse has moved by - first in pixels, then // convert it to a percentage of the scrollbar's height, and then // finally convert it into an index. Add this delta index onto // the index at which the drag was started, and then scroll there. const deltaPixels = (e.clientY || e.originalEvent.touches[0].clientY) - this.mouseStart; const deltaPercent = deltaPixels / this.$('.Scrubber-scrollbar').outerHeight() * 100; const deltaIndex = (deltaPercent / this.percentPerPost().index) || 0; const newIndex = Math.min(this.indexStart + deltaIndex, this.count() - 1); this.index = Math.max(0, newIndex); this.renderScrollbar(); } onmouseup() { if (!this.dragging) return; this.mouseStart = 0; this.indexStart = 0; this.dragging = false; $('body').css('cursor', ''); this.$().removeClass('open'); // If the index we've landed on is in a gap, then tell the stream- // content that we want to load those posts. const intIndex = Math.floor(this.index); this.props.stream.goToIndex(intIndex); this.renderScrollbar(true); } onclick(e) { // Calculate the index which we want to jump to based on the click position. // 1. Get the offset of the click from the top of the scrollbar, as a // percentage of the scrollbar's height. const $scrollbar = this.$('.Scrubber-scrollbar'); const offsetPixels = (e.clientY || e.originalEvent.touches[0].clientY) - $scrollbar.offset().top + $('body').scrollTop(); let offsetPercent = offsetPixels / $scrollbar.outerHeight() * 100; // 2. We want the handle of the scrollbar to end up centered on the click // position. Thus, we calculate the height of the handle in percent and // use that to find a new offset percentage. offsetPercent = offsetPercent - parseFloat($scrollbar.find('.Scrubber-handle')[0].style.height) / 2; // 3. Now we can convert the percentage into an index, and tell the stream- // content component to jump to that index. let offsetIndex = offsetPercent / this.percentPerPost().index; offsetIndex = Math.max(0, Math.min(this.count() - 1, offsetIndex)); this.props.stream.goToIndex(Math.floor(offsetIndex)); this.index = offsetIndex; this.renderScrollbar(true); this.$().removeClass('open'); } }
JavaScript
class VarStoragePolyfill { constructor () { this.map = new Map(); } /** * @param {string} key * @param {any} newValue */ setItem (key, newValue) { this.map.set(key, newValue); } /** * @param {string} key */ getItem (key) { return this.map.get(key) } }
JavaScript
class Decoder { /** * @param {Uint8Array} uint8Array Binary data to decode */ constructor (uint8Array) { /** * Decoding target. * * @type {Uint8Array} */ this.arr = uint8Array; /** * Current decoding position. * * @type {number} */ this.pos = 0; } }
JavaScript
class Encoder { constructor () { this.cpos = 0; this.cbuf = new Uint8Array(100); /** * @type {Array<Uint8Array>} */ this.bufs = []; } }
JavaScript
class Observable { constructor () { /** * Some desc. * @type {Map<N, any>} */ this._observers = create(); } /** * @param {N} name * @param {function} f */ on (name, f) { setIfUndefined(this._observers, name, create$1).add(f); } /** * @param {N} name * @param {function} f */ once (name, f) { /** * @param {...any} args */ const _f = (...args) => { this.off(name, _f); f(...args); }; this.on(name, _f); } /** * @param {N} name * @param {function} f */ off (name, f) { const observers = this._observers.get(name); if (observers !== undefined) { observers.delete(f); if (observers.size === 0) { this._observers.delete(name); } } } /** * Emit a named event. All registered event listeners that listen to the * specified name will receive the event. * * @todo This should catch exceptions * * @param {N} name The event name. * @param {Array<any>} args The arguments that are applied to the event listener. */ emit (name, args) { // copy all listeners to an array first to make sure that no event is emitted to listeners that are subscribed while the event handler is called. return from((this._observers.get(name) || create()).values()).forEach(f => f(...args)) } destroy () { this._observers = create(); } }
JavaScript
class VConsole { /** * @param {Element} dom */ constructor (dom) { this.dom = dom; /** * @type {Element} */ this.ccontainer = this.dom; this.depth = 0; vconsoles.add(this); } /** * @param {Array<string|Symbol|Object|number>} args * @param {boolean} collapsed */ group (args, collapsed = false) { enqueue(() => { const triangleDown = element('span', [create$4('hidden', collapsed), create$4('style', 'color:grey;font-size:120%;')], [text('▼')]); const triangleRight = element('span', [create$4('hidden', !collapsed), create$4('style', 'color:grey;font-size:125%;')], [text('▶')]); const content = element('div', [create$4('style', `${lineStyle};padding-left:${this.depth * 10}px`)], [triangleDown, triangleRight, text(' ')].concat(_computeLineSpans(args))); const nextContainer = element('div', [create$4('hidden', collapsed)]); const nextLine = element('div', [], [content, nextContainer]); append(this.ccontainer, [nextLine]); this.ccontainer = nextContainer; this.depth++; // when header is clicked, collapse/uncollapse container addEventListener(content, 'click', event => { nextContainer.toggleAttribute('hidden'); triangleDown.toggleAttribute('hidden'); triangleRight.toggleAttribute('hidden'); }); }); } /** * @param {Array<string|Symbol|Object|number>} args */ groupCollapsed (args) { this.group(args, true); } groupEnd () { enqueue(() => { if (this.depth > 0) { this.depth--; // @ts-ignore this.ccontainer = this.ccontainer.parentElement.parentElement; } }); } /** * @param {Array<string|Symbol|Object|number>} args */ print (args) { enqueue(() => { append(this.ccontainer, [element('div', [create$4('style', `${lineStyle};padding-left:${this.depth * 10}px`)], _computeLineSpans(args))]); }); } /** * @param {Error} err */ printError (err) { this.print([RED, BOLD, err.toString()]); } /** * @param {string} url * @param {number} height */ printImg (url, height) { enqueue(() => { append(this.ccontainer, [element('img', [create$4('src', url), create$4('height', `${round(height * 1.5)}px`)])]); }); } /** * @param {Node} node */ printDom (node) { enqueue(() => { append(this.ccontainer, [node]); }); } destroy () { enqueue(() => { vconsoles.delete(this); }); } }
JavaScript
class DeleteSet { constructor () { /** * @type {Map<number,Array<DeleteItem>>} */ this.clients = new Map(); } }
JavaScript
class Doc extends Observable { /** * @param {Object} conf configuration * @param {boolean} [conf.gc] Disable garbage collection (default: gc=true) * @param {function(Item):boolean} [conf.gcFilter] Will be called before an Item is garbage collected. Return false to keep the Item. */ constructor ({ gc = true, gcFilter = () => true } = {}) { super(); this.gc = gc; this.gcFilter = gcFilter; this.clientID = generateNewClientId(); /** * @type {Map<string, AbstractType<YEvent>>} */ this.share = new Map(); this.store = new StructStore(); /** * @type {Transaction | null} */ this._transaction = null; /** * @type {Array<Transaction>} */ this._transactionCleanups = []; } /** * Changes that happen inside of a transaction are bundled. This means that * the observer fires _after_ the transaction is finished and that all changes * that happened inside of the transaction are sent as one message to the * other peers. * * @param {function(Transaction):void} f The function that should be executed as a transaction * @param {any} [origin] Origin of who started the transaction. Will be stored on transaction.origin * * @public */ transact (f, origin = null) { transact(this, f, origin); } /** * Define a shared data type. * * Multiple calls of `y.get(name, TypeConstructor)` yield the same result * and do not overwrite each other. I.e. * `y.define(name, Y.Array) === y.define(name, Y.Array)` * * After this method is called, the type is also available on `y.share.get(name)`. * * *Best Practices:* * Define all types right after the Yjs instance is created and store them in a separate object. * Also use the typed methods `getText(name)`, `getArray(name)`, .. * * @example * const y = new Y(..) * const appState = { * document: y.getText('document') * comments: y.getArray('comments') * } * * @param {string} name * @param {Function} TypeConstructor The constructor of the type definition. E.g. Y.Text, Y.Array, Y.Map, ... * @return {AbstractType<any>} The created type. Constructed with TypeConstructor * * @public */ get (name, TypeConstructor = AbstractType) { const type = setIfUndefined(this.share, name, () => { // @ts-ignore const t = new TypeConstructor(); t._integrate(this, null); return t }); const Constr = type.constructor; if (TypeConstructor !== AbstractType && Constr !== TypeConstructor) { if (Constr === AbstractType) { // @ts-ignore const t = new TypeConstructor(); t._map = type._map; type._map.forEach(/** @param {Item?} n */ n => { for (; n !== null; n = n.left) { // @ts-ignore n.parent = t; } }); t._start = type._start; for (let n = t._start; n !== null; n = n.right) { n.parent = t; } t._length = type._length; this.share.set(name, t); t._integrate(this, null); return t } else { throw new Error(`Type with the name ${name} has already been defined with a different constructor`) } } return type } /** * @template T * @param {string} name * @return {YArray<T>} * * @public */ getArray (name) { // @ts-ignore return this.get(name, YArray) } /** * @param {string} name * @return {YText} * * @public */ getText (name) { // @ts-ignore return this.get(name, YText) } /** * @param {string} name * @return {YMap<any>} * * @public */ getMap (name) { // @ts-ignore return this.get(name, YMap) } /** * @param {string} name * @return {YXmlFragment} * * @public */ getXmlFragment (name) { // @ts-ignore return this.get(name, YXmlFragment) } /** * Emit `destroy` event and unregister all event handlers. */ destroy () { this.emit('destroyed', [true]); super.destroy(); } /** * @param {string} eventName * @param {function} f */ on (eventName, f) { super.on(eventName, f); } /** * @param {string} eventName * @param {function} f */ off (eventName, f) { super.off(eventName, f); } }
JavaScript
class EventHandler { constructor () { /** * @type {Array<function(ARG0, ARG1):void>} */ this.l = []; } }
JavaScript
class Transaction { /** * @param {Doc} doc * @param {any} origin * @param {boolean} local */ constructor (doc, origin, local) { /** * The Yjs instance. * @type {Doc} */ this.doc = doc; /** * Describes the set of deleted items by ids * @type {DeleteSet} */ this.deleteSet = new DeleteSet(); /** * Holds the state before the transaction started. * @type {Map<Number,Number>} */ this.beforeState = getStateVector(doc.store); /** * Holds the state after the transaction. * @type {Map<Number,Number>} */ this.afterState = new Map(); /** * All types that were directly modified (property added or child * inserted/deleted). New types are not included in this Set. * Maps from type to parentSubs (`item.parentSub = null` for YArray) * @type {Map<AbstractType<YEvent>,Set<String|null>>} */ this.changed = new Map(); /** * Stores the events for the types that observe also child elements. * It is mainly used by `observeDeep`. * @type {Map<AbstractType<YEvent>,Array<YEvent>>} */ this.changedParentTypes = new Map(); /** * @type {Array<AbstractStruct>} */ this._mergeStructs = []; /** * @type {any} */ this.origin = origin; /** * Stores meta information on the transaction * @type {Map<any,any>} */ this.meta = new Map(); /** * Whether this change originates from this doc. * @type {boolean} */ this.local = local; } }
JavaScript
class YEvent { /** * @param {AbstractType<any>} target The changed type. * @param {Transaction} transaction */ constructor (target, transaction) { /** * The type on which this event was created on. * @type {AbstractType<any>} */ this.target = target; /** * The current target on which the observe callback is called. * @type {AbstractType<any>} */ this.currentTarget = target; /** * The transaction that triggered this event. * @type {Transaction} */ this.transaction = transaction; /** * @type {Object|null} */ this._changes = null; } /** * Computes the path from `y` to the changed type. * * The following property holds: * @example * let type = y * event.path.forEach(dir => { * type = type.get(dir) * }) * type === event.target // => true */ get path () { // @ts-ignore _item is defined because target is integrated return getPathTo(this.currentTarget, this.target) } /** * Check if a struct is deleted by this event. * * In contrast to change.deleted, this method also returns true if the struct was added and then deleted. * * @param {AbstractStruct} struct * @return {boolean} */ deletes (struct) { return isDeleted(this.transaction.deleteSet, struct.id) } /** * Check if a struct is added by this event. * * In contrast to change.deleted, this method also returns true if the struct was added and then deleted. * * @param {AbstractStruct} struct * @return {boolean} */ adds (struct) { return struct.id.clock >= (this.transaction.beforeState.get(struct.id.client) || 0) } /** * @return {{added:Set<Item>,deleted:Set<Item>,delta:Array<{insert:Array<any>}|{delete:number}|{retain:number}>}} */ get changes () { let changes = this._changes; if (changes === null) { const target = this.target; const added = create$1(); const deleted = create$1(); /** * @type {Array<{insert:Array<any>}|{delete:number}|{retain:number}>} */ const delta = []; /** * @type {Map<string,{ action: 'add' | 'update' | 'delete', oldValue: any}>} */ const keys = new Map(); changes = { added, deleted, delta, keys }; const changed = /** @type Set<string|null> */ (this.transaction.changed.get(target)); if (changed.has(null)) { /** * @type {any} */ let lastOp = null; const packOp = () => { if (lastOp) { delta.push(lastOp); } }; for (let item = target._start; item !== null; item = item.right) { if (item.deleted) { if (this.deletes(item) && !this.adds(item)) { if (lastOp === null || lastOp.delete === undefined) { packOp(); lastOp = { delete: 0 }; } lastOp.delete += item.length; deleted.add(item); } // else nop } else { if (this.adds(item)) { if (lastOp === null || lastOp.insert === undefined) { packOp(); lastOp = { insert: [] }; } lastOp.insert = lastOp.insert.concat(item.content.getContent()); added.add(item); } else { if (lastOp === null || lastOp.retain === undefined) { packOp(); lastOp = { retain: 0 }; } lastOp.retain += item.length; } } } if (lastOp !== null && lastOp.retain === undefined) { packOp(); } } changed.forEach(key => { if (key !== null) { const item = /** @type {Item} */ (target._map.get(key)); /** * @type {'delete' | 'add' | 'update'} */ let action; let oldValue; if (this.adds(item)) { let prev = item.left; while (prev !== null && this.adds(prev)) { prev = prev.left; } if (this.deletes(item)) { if (prev !== null && this.deletes(prev)) { action = 'delete'; oldValue = last(prev.content.getContent()); } else { return } } else { if (prev !== null && this.deletes(prev)) { action = 'update'; oldValue = last(prev.content.getContent()); } else { action = 'add'; oldValue = undefined; } } } else { if (this.deletes(item)) { action = 'delete'; oldValue = last(/** @type {Item} */ item.content.getContent()); } else { return // nop } } keys.set(key, { action, oldValue }); } }); this._changes = changes; } return /** @type {any} */ (changes) } }
JavaScript
class AbstractType { constructor () { /** * @type {Item|null} */ this._item = null; /** * @type {Map<string,Item>} */ this._map = new Map(); /** * @type {Item|null} */ this._start = null; /** * @type {Doc|null} */ this.doc = null; this._length = 0; /** * Event handlers * @type {EventHandler<EventType,Transaction>} */ this._eH = createEventHandler(); /** * Deep event handlers * @type {EventHandler<Array<YEvent>,Transaction>} */ this._dEH = createEventHandler(); } /** * Integrate this type into the Yjs instance. * * * Save this struct in the os * * This type is sent to other client * * Observer functions are fired * * @param {Doc} y The Yjs instance * @param {Item|null} item */ _integrate (y, item) { this.doc = y; this._item = item; } /** * @return {AbstractType<EventType>} */ _copy () { throw methodUnimplemented() } /** * @param {encoding.Encoder} encoder */ _write (encoder) { } /** * The first non-deleted item */ get _first () { let n = this._start; while (n !== null && n.deleted) { n = n.right; } return n } /** * Creates YEvent and calls all type observers. * Must be implemented by each type. * * @param {Transaction} transaction * @param {Set<null|string>} parentSubs Keys changed on this type. `null` if list was modified. */ _callObserver (transaction, parentSubs) { /* skip if no type is specified */ } /** * Observe all events that are created on this type. * * @param {function(EventType, Transaction):void} f Observer function */ observe (f) { addEventHandlerListener(this._eH, f); } /** * Observe all events that are created by this type and its children. * * @param {function(Array<YEvent>,Transaction):void} f Observer function */ observeDeep (f) { addEventHandlerListener(this._dEH, f); } /** * Unregister an observer function. * * @param {function(EventType,Transaction):void} f Observer function */ unobserve (f) { removeEventHandlerListener(this._eH, f); } /** * Unregister an observer function. * * @param {function(Array<YEvent>,Transaction):void} f Observer function */ unobserveDeep (f) { removeEventHandlerListener(this._dEH, f); } /** * @abstract * @return {any} */ toJSON () {} }
JavaScript
class YArrayEvent extends YEvent { /** * @param {YArray<T>} yarray The changed type * @param {Transaction} transaction The transaction object */ constructor (yarray, transaction) { super(yarray, transaction); this._transaction = transaction; } }