type
stringclasses
7 values
content
stringlengths
4
9.55k
repo
stringlengths
7
96
path
stringlengths
4
178
language
stringclasses
1 value
MethodDeclaration
getOptions( keys?: keyof MathfieldOptionsPrivate | (keyof MathfieldOptionsPrivate)[] ): any | Partial<MathfieldOptionsPrivate> { return getOptions(this.options, keys); }
zeyad-ahmad-aql/mathlive
src/editor-mathfield/mathfield-private.ts
TypeScript
MethodDeclaration
getOption<K extends keyof MathfieldOptionsPrivate>( key: K ): MathfieldOptionsPrivate[K] { return getOptions(this.options, key) as MathfieldOptionsPrivate[K]; }
zeyad-ahmad-aql/mathlive
src/editor-mathfield/mathfield-private.ts
TypeScript
MethodDeclaration
/* * HandleEvent is a function invoked when an event is registered with an * object instead ( see `addEventListener()` in `on()`) * The name is defined by `addEventListener()` and cannot be changed. * This pattern is used to be able to release bound event handlers, * (event handlers that need access to `this`) as the bind() function * would create a new function that would have to be kept track off * to be able to properly remove the event handler later. */ handleEvent(evt: Event): void { switch (evt.type) { case 'focus': if (!this.focusBlurInProgress) { this.focusBlurInProgress = true; this.onFocus(); this.focusBlurInProgress = false; } break; case 'blur': if (!this.focusBlurInProgress) { this.focusBlurInProgress = true; this.onBlur(); this.focusBlurInProgress = false; } break; case 'touchstart': case 'mousedown': // iOS <=13 Safari and Firefox on Android onPointerDown(this, evt as PointerEvent); break; case 'pointerdown': onPointerDown(this, evt as PointerEvent); break; case 'resize': if (this.resizeTimer) { cancelAnimationFrame(this.resizeTimer); } this.resizeTimer = requestAnimationFrame( () => isValidMathfield(this) && this.onResize() ); break; case 'wheel': this.onWheel(evt as WheelEvent); break; default: console.warn('Unexpected event type', evt.type); } }
zeyad-ahmad-aql/mathlive
src/editor-mathfield/mathfield-private.ts
TypeScript
MethodDeclaration
dispose(): void { if (!isValidMathfield(this)) return; const element = this.element!; delete this.element; delete element.mathfield; element.innerHTML = this.getValue(); off(element, 'pointerdown', this); off(element, 'touchstart:active mousedown', this); off(element, 'focus', this); off(element, 'blur', this); off(window, 'resize', this); delete this.accessibleNode; delete this.ariaLiveText; delete this.field; delete this.fieldContent; delete this.keyboardDelegate; this.virtualKeyboardToggle!.remove(); delete this.virtualKeyboardToggle; if (this.virtualKeyboard) { this.virtualKeyboard.dispose(); delete this.virtualKeyboard; } disposePopover(this); disposeKeystrokeCaption(this); this.stylesheets.forEach((x) => x?.release()); }
zeyad-ahmad-aql/mathlive
src/editor-mathfield/mathfield-private.ts
TypeScript
MethodDeclaration
resetKeystrokeBuffer(options?: { defer: boolean }): void { options = options ?? { defer: false }; if (options.defer) { // If there is a timeout greater than 0, defer the reset // If the timeout is 0, never do the reset: regardless of the amount // of time between keystrokes, consider them as candidates for // a shortcut if (this.options.inlineShortcutTimeout > 0) { // Set a timer to reset the shortcut buffer this.keystrokeBufferResetTimer = setTimeout(() => { this.resetKeystrokeBuffer(); }, this.options.inlineShortcutTimeout); } return; } this.keystrokeBuffer = ''; this.keystrokeBufferStates = []; clearTimeout(this.keystrokeBufferResetTimer); }
zeyad-ahmad-aql/mathlive
src/editor-mathfield/mathfield-private.ts
TypeScript
MethodDeclaration
executeCommand( command: SelectorPrivate | [SelectorPrivate, ...unknown[]] ): boolean { if (getCommandTarget(command) === 'virtual-keyboard') { return this.virtualKeyboard?.executeCommand(command) ?? false; } return perform(this, command); }
zeyad-ahmad-aql/mathlive
src/editor-mathfield/mathfield-private.ts
TypeScript
MethodDeclaration
getValue(): string;
zeyad-ahmad-aql/mathlive
src/editor-mathfield/mathfield-private.ts
TypeScript
MethodDeclaration
getValue(format: OutputFormat): string;
zeyad-ahmad-aql/mathlive
src/editor-mathfield/mathfield-private.ts
TypeScript
MethodDeclaration
getValue(start: Offset, end: Offset, format?: OutputFormat): string;
zeyad-ahmad-aql/mathlive
src/editor-mathfield/mathfield-private.ts
TypeScript
MethodDeclaration
getValue(range: Range, format?: OutputFormat): string;
zeyad-ahmad-aql/mathlive
src/editor-mathfield/mathfield-private.ts
TypeScript
MethodDeclaration
getValue(selection: Selection, format?: OutputFormat): string;
zeyad-ahmad-aql/mathlive
src/editor-mathfield/mathfield-private.ts
TypeScript
MethodDeclaration
getValue( arg1?: Offset | OutputFormat | Range | Selection, arg2?: Offset | OutputFormat, arg3?: OutputFormat ): string { return this.model.getValue(arg1, arg2, arg3); }
zeyad-ahmad-aql/mathlive
src/editor-mathfield/mathfield-private.ts
TypeScript
MethodDeclaration
setValue(value: string, options?: InsertOptions): void { options = options ?? { mode: 'math' }; if (options.insertionMode === undefined) { options.insertionMode = 'replaceAll'; } if (options.format === undefined || options.format === 'auto') { options.format = 'latex'; } let mode: ParseMode = 'math'; if (options.mode === undefined || options.mode === 'auto') { mode = getMode(this.model, this.model.position) ?? 'math'; } if ( ModeEditor.insert(mode, this.model, value, { ...options, colorMap: this.colorMap, backgroundColorMap: this.backgroundColorMap, }) ) { this.undoManager.snapshot(this.options); requestUpdate(this); } }
zeyad-ahmad-aql/mathlive
src/editor-mathfield/mathfield-private.ts
TypeScript
MethodDeclaration
getPlaceholderField(placeholderId: string): MathfieldElement | undefined { return this._placeholders.get(placeholderId)?.field; }
zeyad-ahmad-aql/mathlive
src/editor-mathfield/mathfield-private.ts
TypeScript
MethodDeclaration
scrollIntoView(): void { // If a render is pending, do it now to make sure we have correct layout // and caret position if (this.dirty) { render(this); } const fieldBounds = this.field!.getBoundingClientRect(); let caretPoint: number | undefined = undefined; if (this.model.selectionIsCollapsed) { caretPoint = getCaretPoint(this.field!)?.x; } else { const selectionBounds = getSelectionBounds(this); if (selectionBounds.length > 0) { let maxRight = -Infinity; for (const r of selectionBounds) { if (r.right > maxRight) maxRight = r.right; } caretPoint = maxRight + fieldBounds.left - this.field!.scrollLeft; } } if (caretPoint !== undefined) { const x = caretPoint - window.scrollX; if (x < fieldBounds.left) { this.field!.scroll({ top: 0, left: x - fieldBounds.left + this.field!.scrollLeft - 20, behavior: 'smooth', }); } else if (x > fieldBounds.right) { this.field!.scroll({ top: 0, left: x - fieldBounds.right + this.field!.scrollLeft + 20, behavior: 'smooth', }); } } }
zeyad-ahmad-aql/mathlive
src/editor-mathfield/mathfield-private.ts
TypeScript
MethodDeclaration
insert(s: string, options?: InsertOptions): boolean { if (typeof s === 'string' && s.length > 0) { options = options ?? { mode: 'math' }; if (options.focus) { this.focus(); } if (options.feedback) { if (this.options.keypressVibration && canVibrate()) { navigator.vibrate(HAPTIC_FEEDBACK_DURATION); } void this.keypressSound?.play().catch(console.warn); } if (options.scrollIntoView) { this.scrollIntoView(); } if (s === '\\\\') { // This string is interpreted as an "insert row after" command addRowAfter(this.model); } else if (s === '&') { addColumnAfter(this.model); } else { const savedStyle = this.style; ModeEditor.insert(this.mode, this.model, s, { style: this.model.at(this.model.position).computedStyle, ...options, }); if (options.resetStyle) { this.style = savedStyle; } } this.undoManager.snapshot(this.options); requestUpdate(this); return true; } return false; }
zeyad-ahmad-aql/mathlive
src/editor-mathfield/mathfield-private.ts
TypeScript
MethodDeclaration
switchMode(mode: ParseMode, prefix = '', suffix = ''): void { if (this.mode === mode || this.options.readOnly) return; const { model } = this; model.deferNotifications( { content: Boolean(suffix) || Boolean(prefix), selection: true }, (): boolean => { let contentChanged = false; this.resetKeystrokeBuffer(); // Suppress (temporarily) smart mode if switching to/from text or math // This prevents switching to/from command mode from suppressing smart mode. this.smartModeSuppressed = /text|math/.test(this.mode) && /text|math/.test(mode); if (prefix && mode !== 'latex') { const atoms = parseLatex(prefix, { parseMode: { math: 'text', text: 'math' }[mode as ParseMode], }); model.collapseSelection('forward'); const cursor = model.at(model.position); model.position = model.offsetOf( cursor.parent!.addChildrenAfter(atoms, cursor) ); contentChanged = true; } this.mode = mode; if (mode === 'latex') { let wasCollapsed = model.selectionIsCollapsed; // We can have only a single latex group at a time. // If a latex group is open, close it first complete(this, 'accept'); // Switch to the command mode keyboard layer if (this.virtualKeyboard?.visible) { this.executeCommand(['switchKeyboardLayer', 'latex-lower']); } // Insert a latex group atom let latex: string; let cursor = model.at(model.position); if (wasCollapsed) { latex = '\\'; } else { const selRange = range(model.selection); latex = this.model.getValue(selRange, 'latex'); const extractedAtoms = this.model.extractAtoms(selRange); if ( extractedAtoms.length === 1 && extractedAtoms[0] instanceof PlaceholderAtom ) { // If we just had a placeholder selected, pretend we had an empty // selection latex = prefix; wasCollapsed = true; } cursor = model.at(selRange[0]); } const atom = new LatexGroupAtom(latex); cursor.parent!.addChildAfter(atom, cursor); if (wasCollapsed) { model.position = model.offsetOf(atom.lastChild); } else { model.setSelection( model.offsetOf(atom.firstChild), model.offsetOf(atom.lastChild) ); } } else { // Remove any error indicator on the current command sequence (if there is one) getLatexGroupBody(model).forEach((x) => { x.isError = false; }); } if (suffix) { const atoms = parseLatex(suffix, { parseMode: { math: 'text', text: 'math' }[mode], }); model.collapseSelection('forward'); const cursor = model.at(model.position); model.position = model.offsetOf( cursor.parent!.addChildrenAfter(atoms, cursor) ); contentChanged = true; } // Notify of mode change if (typeof this.options.onModeChange === 'function') { this.options.onModeChange(this, this.mode); } requestUpdate(this); return contentChanged; } ); }
zeyad-ahmad-aql/mathlive
src/editor-mathfield/mathfield-private.ts
TypeScript
MethodDeclaration
hasFocus(): boolean { return ( isBrowser() && document.hasFocus() && this.keyboardDelegate!.hasFocus() ); }
zeyad-ahmad-aql/mathlive
src/editor-mathfield/mathfield-private.ts
TypeScript
MethodDeclaration
focus(): void { if (!this.hasFocus()) { this.keyboardDelegate!.focus(); this.model.announce('line'); } }
zeyad-ahmad-aql/mathlive
src/editor-mathfield/mathfield-private.ts
TypeScript
MethodDeclaration
blur(): void { if (this.hasFocus()) { this.keyboardDelegate!.blur(); } }
zeyad-ahmad-aql/mathlive
src/editor-mathfield/mathfield-private.ts
TypeScript
MethodDeclaration
select(): void { this.model.selection = { ranges: [[0, this.model.lastOffset]] }; }
zeyad-ahmad-aql/mathlive
src/editor-mathfield/mathfield-private.ts
TypeScript
MethodDeclaration
applyStyle(inStyle: Style, inOptions: Range | ApplyStyleOptions = {}): void { const options: ApplyStyleOptions = { operation: 'set', suppressChangeNotifications: false, }; if (isRange(inOptions)) { options.range = inOptions; } else { options.range = inOptions.range; options.suppressChangeNotifications = inOptions.suppressChangeNotifications ?? false; } const style = validateStyle(this, inStyle); const operation = options.operation ?? 'set'; this.model.deferNotifications( { content: !options.suppressChangeNotifications }, () => { if (options.range === undefined) { this.model.selection.ranges.forEach((range) => applyStyle(this.model, range, style, { operation }) ); } else { applyStyle(this.model, options.range, style, { operation }); } } ); requestUpdate(this); }
zeyad-ahmad-aql/mathlive
src/editor-mathfield/mathfield-private.ts
TypeScript
MethodDeclaration
getCaretPoint(): { x: number; y: number } | null { const caretOffset = getCaretPoint(this.field!); return caretOffset ? { x: caretOffset.x, y: caretOffset.y } : null; }
zeyad-ahmad-aql/mathlive
src/editor-mathfield/mathfield-private.ts
TypeScript
MethodDeclaration
setCaretPoint(x: number, y: number): boolean { const newPosition = offsetFromPoint(this, x, y, { bias: 0 }); if (newPosition < 0) return false; const previousPosition = this.model.position; this.model.position = newPosition; this.model.announce('move', previousPosition); requestUpdate(this); return true; }
zeyad-ahmad-aql/mathlive
src/editor-mathfield/mathfield-private.ts
TypeScript
MethodDeclaration
attachNestedMathfield(): void { let needsUpdate = false; this._placeholders.forEach((v) => { const container = this.field?.querySelector( `[data-placeholder-id=${v.atom.placeholderId}]` ) as HTMLElement; if (container) { const placeholderPosition = container.getBoundingClientRect(); const parentPosition = this.field?.getBoundingClientRect(); const scaleDownFontsize = parseInt(window.getComputedStyle(container).fontSize) * 0.6; if ( !v.field.style.fontSize || Math.abs(scaleDownFontsize - parseFloat(v.field.style.fontSize)) >= 0.2 ) { needsUpdate = true; v.field.style.fontSize = `${scaleDownFontsize}px`; } const newTop = (placeholderPosition?.top ?? 0) - (parentPosition?.top ?? 0) + (this.element?.offsetTop ?? 0); const newLeft = (placeholderPosition?.left ?? 0) - (parentPosition?.left ?? 0) + (this.element?.offsetLeft ?? 0); if ( !v.field.style.left || Math.abs(newLeft - parseFloat(v.field.style.left)) >= 1 ) { needsUpdate = true; v.field.style.left = `${newLeft}px`; } if ( !v.field.style.top || Math.abs(newTop - parseFloat(v.field.style.top)) >= 1 ) { needsUpdate = true; v.field.style.top = `${newTop}px`; } console.log('attaching', !!v.field.style.left, !!v.field.style.top); } }); if (needsUpdate) { requestUpdate(this); } }
zeyad-ahmad-aql/mathlive
src/editor-mathfield/mathfield-private.ts
TypeScript
MethodDeclaration
canUndo(): boolean { return this.undoManager.canUndo(); }
zeyad-ahmad-aql/mathlive
src/editor-mathfield/mathfield-private.ts
TypeScript
MethodDeclaration
canRedo(): boolean { return this.undoManager.canRedo(); }
zeyad-ahmad-aql/mathlive
src/editor-mathfield/mathfield-private.ts
TypeScript
MethodDeclaration
popUndoStack(): void { this.undoManager.pop(); }
zeyad-ahmad-aql/mathlive
src/editor-mathfield/mathfield-private.ts
TypeScript
MethodDeclaration
snapshot(): void { this.undoManager.snapshot({ ...this.options, onUndoStateDidChange: (mf, reason): void => { this.virtualKeyboard?.executeCommand([ 'onUndoStateChanged', this.canUndo(), this.canRedo(), ]); this.options.onUndoStateDidChange(mf, reason); }, }); }
zeyad-ahmad-aql/mathlive
src/editor-mathfield/mathfield-private.ts
TypeScript
MethodDeclaration
snapshotAndCoalesce(): void { this.undoManager.snapshotAndCoalesce({ ...this.options, onUndoStateDidChange: (mf, reason): void => { this.virtualKeyboard?.executeCommand([ 'onUndoStateChanged', this.canUndo(), this.canRedo(), ]); this.options.onUndoStateDidChange(mf, reason); }, }); }
zeyad-ahmad-aql/mathlive
src/editor-mathfield/mathfield-private.ts
TypeScript
MethodDeclaration
getUndoRecord(): UndoRecord { return this.undoManager.save(); }
zeyad-ahmad-aql/mathlive
src/editor-mathfield/mathfield-private.ts
TypeScript
MethodDeclaration
restoreToUndoRecord(s: UndoRecord): void { this.undoManager.restore(s, { ...this.options, suppressChangeNotifications: true, }); }
zeyad-ahmad-aql/mathlive
src/editor-mathfield/mathfield-private.ts
TypeScript
MethodDeclaration
undo(): void { return this.undoManager.undo({ ...this.options, onUndoStateDidChange: (mf, reason): void => { this.virtualKeyboard!.executeCommand([ 'onUndoStateChanged', this.canUndo(), this.canRedo(), ]); this.options.onUndoStateDidChange(mf, reason); }, }); }
zeyad-ahmad-aql/mathlive
src/editor-mathfield/mathfield-private.ts
TypeScript
MethodDeclaration
redo(): void { return this.undoManager.redo({ ...this.options, onUndoStateDidChange: (mf, reason): void => { this.virtualKeyboard?.executeCommand([ 'onUndoStateChanged', this.canUndo(), this.canRedo(), ]); this.options.onUndoStateDidChange(mf, reason); }, }); }
zeyad-ahmad-aql/mathlive
src/editor-mathfield/mathfield-private.ts
TypeScript
MethodDeclaration
private _onSelectionDidChange(): void { // Keep the content of the textarea in sync wiht the selection. // This will allow cut/copy to work. this.keyboardDelegate!.setValue( this.getValue(this.model.selection, 'latex-expanded') ); const selectedAtoms = this.model.getAtoms(this.model.selection); if (selectedAtoms.length === 1 && selectedAtoms[0].type === 'placeholder') { const placeholder = selectedAtoms[0] as PlaceholderAtom; if (this.model.mathfield._placeholders.has(placeholder.placeholderId!)) { this.model.mathfield._placeholders .get(placeholder.placeholderId!) ?.field.focus(); } } // Adjust mode { const cursor = this.model.at(this.model.position); const newMode = cursor.mode ?? effectiveMode(this.options); if (this.mode !== newMode) { if (this.mode === 'latex') { complete(this, 'accept', { mode: newMode }); this.model.position = this.model.offsetOf(cursor); } else { this.switchMode(newMode); } } } // Invoke client listeners, if provided. if (typeof this.options.onSelectionDidChange === 'function') { this.options.onSelectionDidChange(this); } }
zeyad-ahmad-aql/mathlive
src/editor-mathfield/mathfield-private.ts
TypeScript
MethodDeclaration
private onFocus(): void { if (this.blurred) { this.blurred = false; this.keyboardDelegate!.focus(); this.virtualKeyboard?.enable(); if (this.options.virtualKeyboardMode === 'onfocus') { this.executeCommand('showVirtualKeyboard'); } updatePopoverPosition(this); this.options.onFocus?.(this); // Save the current value. // It will be compared in `onBlur()` to see if the // `onCommit` listener needs to be invoked. This // mimic the `<input>` and `<textarea>` behavior this.valueOnFocus = this.getValue(); requestUpdate(this); } }
zeyad-ahmad-aql/mathlive
src/editor-mathfield/mathfield-private.ts
TypeScript
MethodDeclaration
private onBlur(): void { if (!this.blurred) { this.blurred = true; this.ariaLiveText!.textContent = ''; if (/onfocus|manual/.test(this.options.virtualKeyboardMode)) { this.executeCommand('hideVirtualKeyboard'); } complete(this, 'accept'); requestUpdate(this); if (typeof this.options.onBlur === 'function') { this.options.onBlur(this); } this.virtualKeyboard?.disable(); if ( typeof this.options.onCommit === 'function' && this.getValue() !== this.valueOnFocus ) { this.options.onCommit(this); } } }
zeyad-ahmad-aql/mathlive
src/editor-mathfield/mathfield-private.ts
TypeScript
MethodDeclaration
private onCompositionStart(_composition: string): void { // Clear the selection if there is one this.model.position = this.model.deleteAtoms(range(this.model.selection)); requestAnimationFrame(() => { render(this); // Recalculate the position of the caret // Synchronize the location and style of textarea // so that the IME candidate window can align with the composition const caretPoint = getCaretPoint(this.field!); if (!caretPoint) return; this.keyboardDelegate!.moveTo(caretPoint.x, caretPoint.y); }); }
zeyad-ahmad-aql/mathlive
src/editor-mathfield/mathfield-private.ts
TypeScript
MethodDeclaration
private onCompositionUpdate(composition: string): void { updateComposition(this.model, composition); requestUpdate(this); }
zeyad-ahmad-aql/mathlive
src/editor-mathfield/mathfield-private.ts
TypeScript
MethodDeclaration
private onCompositionEnd(composition: string): void { removeComposition(this.model); onTypedText(this, composition, { simulateKeystroke: true, }); }
zeyad-ahmad-aql/mathlive
src/editor-mathfield/mathfield-private.ts
TypeScript
MethodDeclaration
private onResize(): void { if (!isValidMathfield(this)) return; this.element!.classList.remove( 'ML__isNarrowWidth', 'ML__isWideWidth', 'ML__isExtendedWidth' ); if (window.innerWidth >= 1024) { this.element!.classList.add('ML__isExtendedWidth'); } else if (window.innerWidth >= 768) { this.element!.classList.add('ML__isWideWidth'); } else { this.element!.classList.add('ML__isNarrowWidth'); } updatePopoverPosition(this); }
zeyad-ahmad-aql/mathlive
src/editor-mathfield/mathfield-private.ts
TypeScript
MethodDeclaration
private onWheel(ev: WheelEvent): void { const wheelDelta = 5 * ev.deltaX; if (!Number.isFinite(wheelDelta) || wheelDelta === 0) return; const field = this.field!; if (wheelDelta < 0 && field.scrollLeft === 0) return; if ( wheelDelta > 0 && field.offsetWidth + field.scrollLeft >= field.scrollWidth ) { return; } field.scrollBy({ top: 0, left: wheelDelta }); ev.preventDefault(); ev.stopPropagation(); }
zeyad-ahmad-aql/mathlive
src/editor-mathfield/mathfield-private.ts
TypeScript
ClassDeclaration
@Injectable() export class RoleService extends GenericService<Role>{ constructor( @InjectRepository(Role) private rolesRepository: Repository<Role>, ) { super(rolesRepository) } async findOneByName(name: string) { return await this.rolesRepository.findOne({name}); } }
Novytskyi-Yevhen/music-school
src/role/providers/role.service.ts
TypeScript
MethodDeclaration
async findOneByName(name: string) { return await this.rolesRepository.findOne({name}); }
Novytskyi-Yevhen/music-school
src/role/providers/role.service.ts
TypeScript
ClassDeclaration
export class CreateCustomerDto { constructor( public name: string, public document: string, public email: string, public password: string, ) { } }
ThiagoBottacin/balta.io-petshop
src/backoffice/dtos/create-customer.dto.ts
TypeScript
ArrowFunction
(socket: WebSocket, request) => this.handleConnection(socket, request)
Avid-Gaming-Esports/lol-pick-ban-ui
backend/websocket/WebSocketServer.ts
TypeScript
ArrowFunction
(newState: StateData) => { newState.config = this.config; this.sendEvent(new NewStateEvent(newState)); }
Avid-Gaming-Esports/lol-pick-ban-ui
backend/websocket/WebSocketServer.ts
TypeScript
ArrowFunction
() => this.sendEvent(new ChampSelectStartedEvent())
Avid-Gaming-Esports/lol-pick-ban-ui
backend/websocket/WebSocketServer.ts
TypeScript
ArrowFunction
() => this.sendEvent(new ChampSelectEndedEvent())
Avid-Gaming-Esports/lol-pick-ban-ui
backend/websocket/WebSocketServer.ts
TypeScript
ArrowFunction
(action) => { this.sendEvent(new NewActionEvent(action)); }
Avid-Gaming-Esports/lol-pick-ban-ui
backend/websocket/WebSocketServer.ts
TypeScript
ArrowFunction
(client: WebSocket) => { client.send(serializedEvent); }
Avid-Gaming-Esports/lol-pick-ban-ui
backend/websocket/WebSocketServer.ts
TypeScript
ArrowFunction
(client: WebSocket) => { client.send(heartbeatSerialized); }
Avid-Gaming-Esports/lol-pick-ban-ui
backend/websocket/WebSocketServer.ts
TypeScript
ClassDeclaration
class WebSocketServer { server: ws.Server; state: State; clients: Array<WebSocket> = []; exampleClients: Array<WebSocket> = []; heartbeatInterval?: NodeJS.Timeout; config: any; constructor(server: http.Server, state: State) { this.server = new ws.Server({ server }); this.state = state; this.sendHeartbeat = this.sendHeartbeat.bind(this); // Event listeners this.server.on("connection", (socket: WebSocket, request) => this.handleConnection(socket, request) ); state.on("stateUpdate", (newState: StateData) => { newState.config = this.config; this.sendEvent(new NewStateEvent(newState)); }); state.on("champSelectStarted", () => this.sendEvent(new ChampSelectStartedEvent()) ); state.on("champSelectEnded", () => this.sendEvent(new ChampSelectEndedEvent()) ); state.on("newAction", (action) => { this.sendEvent(new NewActionEvent(action)); }); } startHeartbeat(): void { this.heartbeatInterval = setInterval(this.sendHeartbeat, 1000); } handleConnection(socket: WebSocket, request: http.IncomingMessage): void { this.clients.push(socket); socket.send(JSON.stringify(new NewStateEvent(this.state.data))); } sendEvent(event: PBEvent): void { const serializedEvent = JSON.stringify(event); log.debug(`New Event: ${serializedEvent}`); this.clients.forEach((client: WebSocket) => { client.send(serializedEvent); }); } sendHeartbeat(): void { this.config = JSON.parse(fs.readFileSync("./config.json", "utf8")); const heartbeatEvent = new HeartbeatEvent(this.config); const heartbeatSerialized = JSON.stringify(heartbeatEvent); this.clients.forEach((client: WebSocket) => { client.send(heartbeatSerialized); }); } }
Avid-Gaming-Esports/lol-pick-ban-ui
backend/websocket/WebSocketServer.ts
TypeScript
MethodDeclaration
startHeartbeat(): void { this.heartbeatInterval = setInterval(this.sendHeartbeat, 1000); }
Avid-Gaming-Esports/lol-pick-ban-ui
backend/websocket/WebSocketServer.ts
TypeScript
MethodDeclaration
handleConnection(socket: WebSocket, request: http.IncomingMessage): void { this.clients.push(socket); socket.send(JSON.stringify(new NewStateEvent(this.state.data))); }
Avid-Gaming-Esports/lol-pick-ban-ui
backend/websocket/WebSocketServer.ts
TypeScript
MethodDeclaration
sendEvent(event: PBEvent): void { const serializedEvent = JSON.stringify(event); log.debug(`New Event: ${serializedEvent}`); this.clients.forEach((client: WebSocket) => { client.send(serializedEvent); }); }
Avid-Gaming-Esports/lol-pick-ban-ui
backend/websocket/WebSocketServer.ts
TypeScript
MethodDeclaration
sendHeartbeat(): void { this.config = JSON.parse(fs.readFileSync("./config.json", "utf8")); const heartbeatEvent = new HeartbeatEvent(this.config); const heartbeatSerialized = JSON.stringify(heartbeatEvent); this.clients.forEach((client: WebSocket) => { client.send(heartbeatSerialized); }); }
Avid-Gaming-Esports/lol-pick-ban-ui
backend/websocket/WebSocketServer.ts
TypeScript
ArrowFunction
(props) => { const { percentage } = props; return ( <a href="https://stackoverflow.com/story/johannchopin" target="_blank" className="top-so-answerer mt-1"> <Icon icon="external-link-alt" className="pr-1" /> <Localize translations={localize.top_answerers} vars={{ __PERCENTAGE__: percentage }}
johannchopin/my-cv
src/components/TopSoAnswerer/TopSoAnswerer.tsx
TypeScript
InterfaceDeclaration
// END IMPORT STYLES ZONE // INTERFACE ZONE export interface TopSoAnswererProps { percentage: number }
johannchopin/my-cv
src/components/TopSoAnswerer/TopSoAnswerer.tsx
TypeScript
FunctionDeclaration
function deduplicatePicsIds(pictures: Iterable<Picture>, picIds: Set<string>): Picture[] { const pics = new Array<Picture>(); for (const pic of pictures) { const newPic = clone(pic); if (picIds.has(pic.id)) { let newId = picIds.size; while (picIds.has("m"+newId)) { newId++; } newPic.id = "m"+newId; } picIds.add(newPic.id); pics.push(newPic); } return pics; }
IonPostglacial/Hazo
src/features/codec.ts
TypeScript
FunctionDeclaration
function encodeHierarchicalItem(item: Hierarchy<any>, picIds: Set<string>) { const children = new Set<string>(); for (const child of item.children) { children.add(child.id); } return { id: item.id, type: item.type, parentId: item.parentId, topLevel: isTopLevel(item), children: [...children], name: item.name.S, nameEN: item.name.EN, nameCN: item.name.CN, photos: deduplicatePicsIds(item.pictures, picIds), vernacularName: item.name.V, }; }
IonPostglacial/Hazo
src/features/codec.ts
TypeScript
FunctionDeclaration
function encodeDescription(character: Character, states: State[]): EncodedDescription { return { descriptorId: character.id, statesIds: states.map(s => s.id) }; }
IonPostglacial/Hazo
src/features/codec.ts
TypeScript
FunctionDeclaration
function encodeTaxon(taxon: Taxon, dataset: Dataset, picIds: Set<string>) { return { ...encodeHierarchicalItem(taxon, picIds), bookInfoByIds: taxon.bookInfoByIds, specimenLocations: taxon.specimenLocations, descriptions: [...dataset.taxonDescriptions(taxon)].map(d => encodeDescription(d.character, d.states)), author: taxon.author, vernacularName2: taxon.vernacularName2, name2: taxon.name2, meaning: taxon.meaning, herbariumPicture: taxon.herbariumPicture, website: taxon.website, noHerbier: taxon.noHerbier, fasc: taxon.fasc, page: taxon.page, detail: taxon.detail, extra: taxon.extra, }; }
IonPostglacial/Hazo
src/features/codec.ts
TypeScript
FunctionDeclaration
function encodeCharacter(dataset: Dataset, character: Character, picIds: Set<string>) { return { states: Array.from(dataset.characterStates(character)).filter(s => typeof s !== "undefined").map(s => s.id), preset: character.characterType === "discrete" ? character.preset : undefined, inherentStateId: character.characterType === "discrete" ? character.inherentState?.id : '', inapplicableStatesIds: character.inapplicableStates.filter(s => typeof s !== "undefined").map(s => s.id), requiredStatesIds: character.requiredStates.filter(s => typeof s !== "undefined").map(s => s.id), ...encodeHierarchicalItem(character, picIds), }; }
IonPostglacial/Hazo
src/features/codec.ts
TypeScript
FunctionDeclaration
function decodeState(encoded: EncodedState): State { return { id: encoded.id, name: { S: encoded.name, CN: encoded.nameCN, EN: encoded.nameEN, }, pictures: picturesFromPhotos(encoded.photos), description: encoded.description, color: encoded.color, } }
IonPostglacial/Hazo
src/features/codec.ts
TypeScript
FunctionDeclaration
function encodeState(state: State, picIds: Set<string>): EncodedState { return { id: state.id, name: state.name.S, nameEN: state.name.EN ?? "", nameCN: state.name.CN ?? "", photos: deduplicatePicsIds(state.pictures, picIds), description: state.description, color: state.color, }; }
IonPostglacial/Hazo
src/features/codec.ts
TypeScript
FunctionDeclaration
export function encodeDataset(dataset: Dataset): EncodedDataset { const allStates = new Map<string, State>(); const picIds = new Set<string>(); for (const state of dataset.allStates()) { allStates.set(state.id, state); } return { id: dataset.id, taxons: Array.from(dataset.taxons).filter(t => t.id !== "t0").map(taxon => encodeTaxon(taxon, dataset, picIds)), characters: Array.from(dataset.characters).filter(c => c.id !== "c0").map(character => encodeCharacter(dataset, character, picIds)), states: Array.from(map(allStates.values(), s => encodeState(s, picIds))), books: dataset.books, extraFields: dataset.extraFields, }; }
IonPostglacial/Hazo
src/features/codec.ts
TypeScript
FunctionDeclaration
function decodeHierarchicalItem(item: EncodedHierarchicalItem): HierarchicalItem { return createHierarchicalItem({ ...item, name: { S: item.name, V: item.vernacularName, CN: item.nameCN, EN: item.nameEN, FR: item.name, }, pictures: picturesFromPhotos(item.photos), }); }
IonPostglacial/Hazo
src/features/codec.ts
TypeScript
FunctionDeclaration
function decodeTaxon(encodedTaxon: ReturnType<typeof encodeTaxon>, books: Book[]): Taxon { const bookInfoByIds = (typeof encodedTaxon.bookInfoByIds !== "undefined") ? encodedTaxon.bookInfoByIds : {}; if (Object.keys(bookInfoByIds).length === 0) { for (const book of books) { const info:BookInfo = { fasc: (book.id === "fmc") ? "" + encodedTaxon.fasc : "", page: (book.id === "fmc") ? encodedTaxon.page : undefined, detail: "" }; bookInfoByIds[book.id] = info; } } const item = decodeHierarchicalItem(encodedTaxon); return createTaxon({ ...item, specimenLocations: encodedTaxon.specimenLocations, bookInfoByIds, author: encodedTaxon.author, vernacularName2: encodedTaxon.vernacularName2, name2: encodedTaxon.name2, meaning: encodedTaxon.meaning, herbariumPicture: encodedTaxon.herbariumPicture, website: encodedTaxon.website, noHerbier: encodedTaxon.noHerbier, fasc: encodedTaxon.fasc, page: encodedTaxon.page, detail : encodedTaxon.detail, extra: encodedTaxon.extra, }); }
IonPostglacial/Hazo
src/features/codec.ts
TypeScript
FunctionDeclaration
function decodeCharacter(presetStates: Record<CharacterPreset, State[]>, character: EncodedCharacter, states: IMap<State>): Character { const item = decodeHierarchicalItem(character); const charStates = new Map<string, State>(); for (const stateId of character.states) { const state = states.get(stateId); if (typeof state !== "undefined") { charStates.set(state.id, state); } } return createCharacter({ ...item, presetStates, states: character.preset || Array.from(charStates.values()), inherentState: typeof character.inherentStateId === "undefined" ? undefined : states.get(character.inherentStateId), inapplicableStates: character.inapplicableStatesIds?.map(id => states.get(id)!) ?? [], requiredStates: character.requiredStatesIds?.map(id => states.get(id)!) ?? [], }); }
IonPostglacial/Hazo
src/features/codec.ts
TypeScript
FunctionDeclaration
export function decodeDataset(makeMap: { new(): IMap<any> }, dataset: AlreadyEncodedDataset|undefined): Dataset { const states: IMap<State> = new makeMap(); const books = standardBooks.slice(); const ds = new Dataset( dataset?.id ?? "0", createTaxon({ id: "t0", name: { S: "<TOP>" } }), createCharacter({ id: "c0", name: { S: "<TOP>" } }), books, dataset?.extraFields ?? [], states, ); for (const state of dataset?.states ?? []) { states.set(state.id, decodeState(state)); } for (const character of (dataset?.characters ?? dataset?.descriptors ?? [])) { const decodedCharacter = decodeCharacter(ds.presetStates, character, states); ds.addCharacter(decodedCharacter); } for (const taxon of dataset?.taxons ?? []) { ds.addTaxon(decodeTaxon(taxon, books)); taxon.descriptions.forEach(d => { for (const stateId of d.statesIds) { const t = ds.taxon(taxon.id); const state = states.get(stateId); if (typeof t !== "undefined" && typeof state !== "undefined") { ds.setTaxonState(t.id, state); } } }); } return ds; }
IonPostglacial/Hazo
src/features/codec.ts
TypeScript
ArrowFunction
d => encodeDescription(d.character, d.states)
IonPostglacial/Hazo
src/features/codec.ts
TypeScript
ArrowFunction
s => typeof s !== "undefined"
IonPostglacial/Hazo
src/features/codec.ts
TypeScript
ArrowFunction
t => t.id !== "t0"
IonPostglacial/Hazo
src/features/codec.ts
TypeScript
ArrowFunction
taxon => encodeTaxon(taxon, dataset, picIds)
IonPostglacial/Hazo
src/features/codec.ts
TypeScript
ArrowFunction
c => c.id !== "c0"
IonPostglacial/Hazo
src/features/codec.ts
TypeScript
ArrowFunction
character => encodeCharacter(dataset, character, picIds)
IonPostglacial/Hazo
src/features/codec.ts
TypeScript
ArrowFunction
s => encodeState(s, picIds)
IonPostglacial/Hazo
src/features/codec.ts
TypeScript
ArrowFunction
id => states.get(id)!
IonPostglacial/Hazo
src/features/codec.ts
TypeScript
ArrowFunction
d => { for (const stateId of d.statesIds) { const t = ds.taxon(taxon.id); const state = states.get(stateId); if (typeof t !== "undefined" && typeof state !== "undefined") { ds.setTaxonState(t.id, state); } } }
IonPostglacial/Hazo
src/features/codec.ts
TypeScript
InterfaceDeclaration
export interface EncodedDataset { id: string taxons: ReturnType<typeof encodeTaxon>[]; characters: ReturnType<typeof encodeCharacter>[]; states: EncodedState[]; books: Book[]; extraFields: Field[]; }
IonPostglacial/Hazo
src/features/codec.ts
TypeScript
InterfaceDeclaration
interface AlreadyEncodedDataset extends Omit<EncodedDataset, "characters"> { descriptors?: EncodedCharacter[]; // Legacy name of characters characters?: EncodedCharacter[]; }
IonPostglacial/Hazo
src/features/codec.ts
TypeScript
TypeAliasDeclaration
type EncodedState = { id: string; name: string; nameEN: string; nameCN: string; photos: Picture[]; description?: string; color?: string; };
IonPostglacial/Hazo
src/features/codec.ts
TypeScript
TypeAliasDeclaration
type EncodedCharacter = Omit<ReturnType<typeof encodeCharacter>, "photos"> & { photos: string[]|Picture[] };
IonPostglacial/Hazo
src/features/codec.ts
TypeScript
TypeAliasDeclaration
type EncodedHierarchicalItem = Omit<ReturnType<typeof encodeHierarchicalItem>, "photos"> & { photos: string[]|Picture[] };
IonPostglacial/Hazo
src/features/codec.ts
TypeScript
TypeAliasDeclaration
type EncodedDescription = { descriptorId: string, statesIds: string[] };
IonPostglacial/Hazo
src/features/codec.ts
TypeScript
ClassDeclaration
@Component({ selector: 'app-comp-4767', templateUrl: './comp-4767.component.html', styleUrls: ['./comp-4767.component.css'] }) export class Comp4767Component implements OnInit { constructor() { } ngOnInit() { } }
angular/angular-cli-stress-test
src/app/components/comp-4767/comp-4767.component.ts
TypeScript
ArrowFunction
() => ( <div className="footer"> {/* <p>{`© ${globals.yourName} ${new Date().getFullYear()}`}</p> <a href="/rss.xml"> <img src="/img/rss-white.svg" alt="RSS Feed" height="30" width="30" /> </a> */} </div>
ksorathiya/my-portfolio
components/Footer.tsx
TypeScript
ArrowFunction
() => { beforeEach(async(() => { TestBed.configureTestingModule({ imports: [ RouterTestingModule ], declarations: [ AppComponent ], }).compileComponents(); })); it('should create the app', () => { const fixture = TestBed.createComponent(AppComponent); const app = fixture.debugElement.componentInstance; expect(app).toBeTruthy(); }); it(`should have as title 'refactorings'`, () => { const fixture = TestBed.createComponent(AppComponent); const app = fixture.debugElement.componentInstance; expect(app.title).toEqual('refactorings'); }); it('should render title', () => { const fixture = TestBed.createComponent(AppComponent); fixture.detectChanges(); const compiled = fixture.debugElement.nativeElement; expect(compiled.querySelector('.content span').textContent).toContain('refactorings app is running!'); }); }
andreidana/refactorings
src/app/app.component.spec.ts
TypeScript
ArrowFunction
() => { const fixture = TestBed.createComponent(AppComponent); const app = fixture.debugElement.componentInstance; expect(app.title).toEqual('refactorings'); }
andreidana/refactorings
src/app/app.component.spec.ts
TypeScript
ArrowFunction
() => { const fixture = TestBed.createComponent(AppComponent); fixture.detectChanges(); const compiled = fixture.debugElement.nativeElement; expect(compiled.querySelector('.content span').textContent).toContain('refactorings app is running!'); }
andreidana/refactorings
src/app/app.component.spec.ts
TypeScript
ArrowFunction
({ publications = [], hideViewAllLinksNode = false, }) => { const { colorMode } = useColorMode(); const cardBgColor = { light: "white", dark: "gray.900" }; const cardColor = { light: "gray.900", dark: "white" }; const [searchQuery, setSearchQuery] = useState(""); const sortedPublications = publications .sort( (a: IPublication, b: IPublication) => Number(new Date(b.date)) - Number(new Date(a.date)) ) .filter((article) => article.title.toLowerCase().includes(searchQuery.toLowerCase()) ); const viewAllLinksNode = () => { return ( <Link href="/publications"> <_Link p={2} href="/publications" rounded="md"> <Stack spacing={2} isInline alignItems="center"> <Box fontWeight="bold">View all publications</Box> <Box as={IoMdArrowRoundForward} size="15px" /> </Stack> </_Link> </Link>
ratheeps/ratheep.dev
components/layouts/publications/index.tsx
TypeScript
ArrowFunction
(a: IPublication, b: IPublication) => Number(new Date(b.date)) - Number(new Date(a.date))
ratheeps/ratheep.dev
components/layouts/publications/index.tsx
TypeScript
ArrowFunction
(article) => article.title.toLowerCase().includes(searchQuery.toLowerCase())
ratheeps/ratheep.dev
components/layouts/publications/index.tsx
TypeScript
ArrowFunction
() => { return ( <Link href="/publications"> <_Link p={2} href="/publications" rounded="md"> <Stack spacing={2} isInline alignItems="center"> <Box fontWeight="bold">View all publications</Box> <Box as={IoMdArrowRoundForward} size="15px" /> </Stack> </_Link> </Link>
ratheeps/ratheep.dev
components/layouts/publications/index.tsx
TypeScript
ArrowFunction
() => { if (!hideViewAllLinksNode) return false; return ( <Box> <Input bg={cardBgColor[colorMode]} color={cardColor[colorMode]} value={searchQuery} onChange={(e: FormEvent<HTMLInputElement>)
ratheeps/ratheep.dev
components/layouts/publications/index.tsx
TypeScript
ArrowFunction
() => { if (hideViewAllLinksNode) { return ( <Box> <Stack spacing={2}> <Heading as="h1" size="xl"> Publications </Heading> <Text> publications which have been published on other websites </Text> </Stack> </Box>
ratheeps/ratheep.dev
components/layouts/publications/index.tsx
TypeScript
ArrowFunction
(date: string) => { return ( <Stack spacing={2} isInline alignItems="center"> <Box> <Text fontSize="xs">{dayjs(date).format("LL")}</Text> </Box> </Stack>
ratheeps/ratheep.dev
components/layouts/publications/index.tsx
TypeScript
ArrowFunction
(title: string) => { return ( <Heading as="h3" size="md" letterSpacing="tight" lineHeight="tall"> {title} </Heading>
ratheeps/ratheep.dev
components/layouts/publications/index.tsx
TypeScript
ArrowFunction
(description: string) => { return <Text fontSize="sm">{description}</Text>; }
ratheeps/ratheep.dev
components/layouts/publications/index.tsx
TypeScript