type
stringclasses
7 values
content
stringlengths
4
9.55k
repo
stringlengths
7
96
path
stringlengths
4
178
language
stringclasses
1 value
ArrowFunction
(r) => { r.should.haveOwnProperty('id') r.should.haveOwnProperty('jsonrpc') r.should.haveOwnProperty('error') r['error'].should.haveOwnProperty('message') r['error'].should.haveOwnProperty('code') r['error']['message'].should.equal( JSONRPC_ERRORS.INVALID_REQUEST.message ) r['error']['code'].should.equal(JSONRPC_ERRORS.INVALID_REQUEST.code) r['jsonrpc'].should.equal('2.0') }
Genysys/optimism-monorepo
packages/rollup-full-node/test/app/fullnode-rpc-server.spec.ts
TypeScript
ClassDeclaration
class DummyFullnodeHandler implements FullnodeHandler { public async handleRequest( method: string, params: string[] ): Promise<string> { if (method === unsupportedMethod) { throw new UnsupportedMethodError() } if (method === revertMethod) { throw new RevertError() } return dummyResponse } }
Genysys/optimism-monorepo
packages/rollup-full-node/test/app/fullnode-rpc-server.spec.ts
TypeScript
MethodDeclaration
public async handleRequest( method: string, params: string[] ): Promise<string> { if (method === unsupportedMethod) { throw new UnsupportedMethodError() } if (method === revertMethod) { throw new RevertError() } return dummyResponse }
Genysys/optimism-monorepo
packages/rollup-full-node/test/app/fullnode-rpc-server.spec.ts
TypeScript
FunctionDeclaration
/** @docs-private */ export function OWL_LUXON_DATE_TIME_ADAPTER_OPTIONS_FACTORY(): OwlLuxonDateTimeAdapterOptions { return { useUtc: false, parseStrict: false, }; }
David-Lees/date-time-picker
projects/picker/src/lib/date-time/adapter/luxon-adapter/luxon-date-time-adapter.class.ts
TypeScript
FunctionDeclaration
/** Creates an array and fills it with values. */ function range<T>(length: number, valueFunction: (index: number) => T): T[] { const valuesArray = Array(length); for (let i = 0; i < length; i++) { valuesArray[i] = valueFunction(i); } return valuesArray; }
David-Lees/date-time-picker
projects/picker/src/lib/date-time/adapter/luxon-adapter/luxon-date-time-adapter.class.ts
TypeScript
ClassDeclaration
@Injectable() export class LuxonDateTimeAdapter extends DateTimeAdapter<DateTime> { getDate(date: DateTime): number { throw new Error('Method not implemented.'); } getTime(date: DateTime): number { throw new Error('Method not implemented.'); } clone(date: DateTime): DateTime { return date; } constructor( @Optional() @Inject(OWL_DATE_TIME_LOCALE) private owlDateTimeLocale: string, @Optional() @Inject(OWL_LUXON_DATE_TIME_ADAPTER_OPTIONS) private options?: OwlLuxonDateTimeAdapterOptions ) { super(); this.setLocale(owlDateTimeLocale || DateTime.now().locale); } public setLocale(locale: string) { super.setLocale(locale); } public getYear(date: DateTime): number { return date.year; } public getMonth(date: DateTime): number { return date.month; } public getDay(date: DateTime): number { return date.day; } public getHours(date: DateTime): number { return date.hour; } public getMinutes(date: DateTime): number { return date.minute; } public getSeconds(date: DateTime): number { return date.second; } public getNumDaysInMonth(date: DateTime): number { return date.daysInMonth; } public differenceInCalendarDays( dateLeft: DateTime, dateRight: DateTime ): number { return dateLeft.diff(dateRight, 'days').days; } public getYearName(date: DateTime): string { return date.toFormat('YYYY'); } public getMonthNames(style: 'long' | 'short' | 'narrow'): string[] { return style === 'long' ? Info.months('long') : Info.months('short'); } public getDayOfWeekNames(style: 'long' | 'short' | 'narrow'): string[] { if (style === 'long') { return Info.weekdays('long'); } return Info.weekdays('short'); } public getDateNames(): string[] { return []; } public toIso8601(date: DateTime): string { return date.toISO(); } public isEqual(dateLeft: DateTime, dateRight: DateTime): boolean { if (dateLeft && dateRight) { return dateLeft === dateRight; } return dateLeft === dateRight; } public isSameDay(dateLeft: DateTime, dateRight: DateTime): boolean { if (dateLeft && dateRight) { return dateLeft.hasSame(dateRight, 'day'); } return dateLeft === dateRight; } public isValid(date: DateTime): boolean { return date.isValid; } public invalid(): DateTime { return DateTime.invalid(''); } public isDateInstance(obj: any): boolean { return DateTime.isDateTime(obj); } public addCalendarYears(date: DateTime, amount: number): DateTime { return date.plus({ years: amount }); } public addCalendarMonths(date: DateTime, amount: number): DateTime { return date.plus({ months: amount }); } public addCalendarDays(date: DateTime, amount: number): DateTime { return date.plus({ days: amount }); } public setHours(date: DateTime, amount: number): DateTime { return date.set({ hour: amount }); } public setMinutes(date: DateTime, amount: number): DateTime { return date.set({ minute: amount }); } public setSeconds(date: DateTime, amount: number): DateTime { return date.set({ second: amount }); } public createDate(year: number, month: number, date: number): DateTime; public createDate( year: number, month: number, date: number, hours: number = 0, minutes: number = 0, seconds: number = 0 ): DateTime { if (month < 1 || month > 12) { throw Error( `Invalid month index "${month}". Month index has to be between 1 and 12.` ); } if (date < 1) { throw Error( `Invalid date "${date}". Date has to be greater than 0.` ); } if (hours < 0 || hours > 23) { throw Error( `Invalid hours "${hours}". Hours has to be between 0 and 23.` ); } if (minutes < 0 || minutes > 59) { throw Error( `Invalid minutes "${minutes}". Minutes has to between 0 and 59.` ); } if (seconds < 0 || seconds > 59) { throw Error( `Invalid seconds "${seconds}". Seconds has to be between 0 and 59.` ); } const result = this.createDateTime({ year, month, date, hours, minutes, seconds, }).setLocale(this.getLocale()); // If the result isn't valid, the date must have been out of bounds for this month. if (!result.isValid) { throw Error( `Invalid date "${date}" for month with index "${month}".` ); } return result; } public now(): DateTime { return DateTime.now(); } public format(date: DateTime, displayFormat: any): string { if (!this.isValid(date)) { throw Error('LuxonDateTimeAdapter: Cannot format invalid date.'); } return date.toFormat(displayFormat); } public parse(value: any, parseFormat: any): DateTime | null { if (value && value instanceof Date) { return DateTime.fromJSDate(value); } if (value && typeof value === 'string') { return DateTime.fromFormat(value, parseFormat); } return value ? this.createDateTime(value).setLocale(this.getLocale()) : null; } get parseStrict() { return this.options && this.options.parseStrict; } /** * Returns the given value if given a valid DateTime or null. Deserializes valid ISO 8601 strings * (https://www.ietf.org/rfc/rfc3339.txt) and valid Date objects into valid DateTimes and empty * string into null. Returns an invalid date for all other values. */ deserialize(value: any): DateTime | null { let date: DateTime | null; if (value instanceof Date) { date = DateTime.fromJSDate(value); } if (typeof value === 'string') { if (!value) { return null; } date = DateTime.fromISO(value); } if (date && this.isValid(date)) { return date; } return super.deserialize(value); } /** Creates a DateTime instance while respecting the current UTC settings. */ private createDateTime(...args: any[]): DateTime { return this.options && this.options.useUtc ? DateTime.utc(...args) : DateTime.local(...args); } }
David-Lees/date-time-picker
projects/picker/src/lib/date-time/adapter/luxon-adapter/luxon-date-time-adapter.class.ts
TypeScript
InterfaceDeclaration
/** Configurable options for {@see LuxonDateAdapter}. */ export interface OwlLuxonDateTimeAdapterOptions { /** * Turns the use of utc dates on or off. * Changing this will change how the DateTimePicker output value. * {@default false} */ useUtc: boolean; /** * Turns the use of strict string parsing in luxon. * Changing this will change how the DateTimePicker interprets input. * {@default false} */ parseStrict: boolean; }
David-Lees/date-time-picker
projects/picker/src/lib/date-time/adapter/luxon-adapter/luxon-date-time-adapter.class.ts
TypeScript
MethodDeclaration
getDate(date: DateTime): number { throw new Error('Method not implemented.'); }
David-Lees/date-time-picker
projects/picker/src/lib/date-time/adapter/luxon-adapter/luxon-date-time-adapter.class.ts
TypeScript
MethodDeclaration
getTime(date: DateTime): number { throw new Error('Method not implemented.'); }
David-Lees/date-time-picker
projects/picker/src/lib/date-time/adapter/luxon-adapter/luxon-date-time-adapter.class.ts
TypeScript
MethodDeclaration
clone(date: DateTime): DateTime { return date; }
David-Lees/date-time-picker
projects/picker/src/lib/date-time/adapter/luxon-adapter/luxon-date-time-adapter.class.ts
TypeScript
MethodDeclaration
public setLocale(locale: string) { super.setLocale(locale); }
David-Lees/date-time-picker
projects/picker/src/lib/date-time/adapter/luxon-adapter/luxon-date-time-adapter.class.ts
TypeScript
MethodDeclaration
public getYear(date: DateTime): number { return date.year; }
David-Lees/date-time-picker
projects/picker/src/lib/date-time/adapter/luxon-adapter/luxon-date-time-adapter.class.ts
TypeScript
MethodDeclaration
public getMonth(date: DateTime): number { return date.month; }
David-Lees/date-time-picker
projects/picker/src/lib/date-time/adapter/luxon-adapter/luxon-date-time-adapter.class.ts
TypeScript
MethodDeclaration
public getDay(date: DateTime): number { return date.day; }
David-Lees/date-time-picker
projects/picker/src/lib/date-time/adapter/luxon-adapter/luxon-date-time-adapter.class.ts
TypeScript
MethodDeclaration
public getHours(date: DateTime): number { return date.hour; }
David-Lees/date-time-picker
projects/picker/src/lib/date-time/adapter/luxon-adapter/luxon-date-time-adapter.class.ts
TypeScript
MethodDeclaration
public getMinutes(date: DateTime): number { return date.minute; }
David-Lees/date-time-picker
projects/picker/src/lib/date-time/adapter/luxon-adapter/luxon-date-time-adapter.class.ts
TypeScript
MethodDeclaration
public getSeconds(date: DateTime): number { return date.second; }
David-Lees/date-time-picker
projects/picker/src/lib/date-time/adapter/luxon-adapter/luxon-date-time-adapter.class.ts
TypeScript
MethodDeclaration
public getNumDaysInMonth(date: DateTime): number { return date.daysInMonth; }
David-Lees/date-time-picker
projects/picker/src/lib/date-time/adapter/luxon-adapter/luxon-date-time-adapter.class.ts
TypeScript
MethodDeclaration
public differenceInCalendarDays( dateLeft: DateTime, dateRight: DateTime ): number { return dateLeft.diff(dateRight, 'days').days; }
David-Lees/date-time-picker
projects/picker/src/lib/date-time/adapter/luxon-adapter/luxon-date-time-adapter.class.ts
TypeScript
MethodDeclaration
public getYearName(date: DateTime): string { return date.toFormat('YYYY'); }
David-Lees/date-time-picker
projects/picker/src/lib/date-time/adapter/luxon-adapter/luxon-date-time-adapter.class.ts
TypeScript
MethodDeclaration
public getMonthNames(style: 'long' | 'short' | 'narrow'): string[] { return style === 'long' ? Info.months('long') : Info.months('short'); }
David-Lees/date-time-picker
projects/picker/src/lib/date-time/adapter/luxon-adapter/luxon-date-time-adapter.class.ts
TypeScript
MethodDeclaration
public getDayOfWeekNames(style: 'long' | 'short' | 'narrow'): string[] { if (style === 'long') { return Info.weekdays('long'); } return Info.weekdays('short'); }
David-Lees/date-time-picker
projects/picker/src/lib/date-time/adapter/luxon-adapter/luxon-date-time-adapter.class.ts
TypeScript
MethodDeclaration
public getDateNames(): string[] { return []; }
David-Lees/date-time-picker
projects/picker/src/lib/date-time/adapter/luxon-adapter/luxon-date-time-adapter.class.ts
TypeScript
MethodDeclaration
public toIso8601(date: DateTime): string { return date.toISO(); }
David-Lees/date-time-picker
projects/picker/src/lib/date-time/adapter/luxon-adapter/luxon-date-time-adapter.class.ts
TypeScript
MethodDeclaration
public isEqual(dateLeft: DateTime, dateRight: DateTime): boolean { if (dateLeft && dateRight) { return dateLeft === dateRight; } return dateLeft === dateRight; }
David-Lees/date-time-picker
projects/picker/src/lib/date-time/adapter/luxon-adapter/luxon-date-time-adapter.class.ts
TypeScript
MethodDeclaration
public isSameDay(dateLeft: DateTime, dateRight: DateTime): boolean { if (dateLeft && dateRight) { return dateLeft.hasSame(dateRight, 'day'); } return dateLeft === dateRight; }
David-Lees/date-time-picker
projects/picker/src/lib/date-time/adapter/luxon-adapter/luxon-date-time-adapter.class.ts
TypeScript
MethodDeclaration
public isValid(date: DateTime): boolean { return date.isValid; }
David-Lees/date-time-picker
projects/picker/src/lib/date-time/adapter/luxon-adapter/luxon-date-time-adapter.class.ts
TypeScript
MethodDeclaration
public invalid(): DateTime { return DateTime.invalid(''); }
David-Lees/date-time-picker
projects/picker/src/lib/date-time/adapter/luxon-adapter/luxon-date-time-adapter.class.ts
TypeScript
MethodDeclaration
public isDateInstance(obj: any): boolean { return DateTime.isDateTime(obj); }
David-Lees/date-time-picker
projects/picker/src/lib/date-time/adapter/luxon-adapter/luxon-date-time-adapter.class.ts
TypeScript
MethodDeclaration
public addCalendarYears(date: DateTime, amount: number): DateTime { return date.plus({ years: amount }); }
David-Lees/date-time-picker
projects/picker/src/lib/date-time/adapter/luxon-adapter/luxon-date-time-adapter.class.ts
TypeScript
MethodDeclaration
public addCalendarMonths(date: DateTime, amount: number): DateTime { return date.plus({ months: amount }); }
David-Lees/date-time-picker
projects/picker/src/lib/date-time/adapter/luxon-adapter/luxon-date-time-adapter.class.ts
TypeScript
MethodDeclaration
public addCalendarDays(date: DateTime, amount: number): DateTime { return date.plus({ days: amount }); }
David-Lees/date-time-picker
projects/picker/src/lib/date-time/adapter/luxon-adapter/luxon-date-time-adapter.class.ts
TypeScript
MethodDeclaration
public setHours(date: DateTime, amount: number): DateTime { return date.set({ hour: amount }); }
David-Lees/date-time-picker
projects/picker/src/lib/date-time/adapter/luxon-adapter/luxon-date-time-adapter.class.ts
TypeScript
MethodDeclaration
public setMinutes(date: DateTime, amount: number): DateTime { return date.set({ minute: amount }); }
David-Lees/date-time-picker
projects/picker/src/lib/date-time/adapter/luxon-adapter/luxon-date-time-adapter.class.ts
TypeScript
MethodDeclaration
public setSeconds(date: DateTime, amount: number): DateTime { return date.set({ second: amount }); }
David-Lees/date-time-picker
projects/picker/src/lib/date-time/adapter/luxon-adapter/luxon-date-time-adapter.class.ts
TypeScript
MethodDeclaration
public createDate(year: number, month: number, date: number): DateTime;
David-Lees/date-time-picker
projects/picker/src/lib/date-time/adapter/luxon-adapter/luxon-date-time-adapter.class.ts
TypeScript
MethodDeclaration
public createDate( year: number, month: number, date: number, hours: number = 0, minutes: number = 0, seconds: number = 0 ): DateTime { if (month < 1 || month > 12) { throw Error( `Invalid month index "${month}". Month index has to be between 1 and 12.` ); } if (date < 1) { throw Error( `Invalid date "${date}". Date has to be greater than 0.` ); } if (hours < 0 || hours > 23) { throw Error( `Invalid hours "${hours}". Hours has to be between 0 and 23.` ); } if (minutes < 0 || minutes > 59) { throw Error( `Invalid minutes "${minutes}". Minutes has to between 0 and 59.` ); } if (seconds < 0 || seconds > 59) { throw Error( `Invalid seconds "${seconds}". Seconds has to be between 0 and 59.` ); } const result = this.createDateTime({ year, month, date, hours, minutes, seconds, }).setLocale(this.getLocale()); // If the result isn't valid, the date must have been out of bounds for this month. if (!result.isValid) { throw Error( `Invalid date "${date}" for month with index "${month}".` ); } return result; }
David-Lees/date-time-picker
projects/picker/src/lib/date-time/adapter/luxon-adapter/luxon-date-time-adapter.class.ts
TypeScript
MethodDeclaration
public now(): DateTime { return DateTime.now(); }
David-Lees/date-time-picker
projects/picker/src/lib/date-time/adapter/luxon-adapter/luxon-date-time-adapter.class.ts
TypeScript
MethodDeclaration
public format(date: DateTime, displayFormat: any): string { if (!this.isValid(date)) { throw Error('LuxonDateTimeAdapter: Cannot format invalid date.'); } return date.toFormat(displayFormat); }
David-Lees/date-time-picker
projects/picker/src/lib/date-time/adapter/luxon-adapter/luxon-date-time-adapter.class.ts
TypeScript
MethodDeclaration
public parse(value: any, parseFormat: any): DateTime | null { if (value && value instanceof Date) { return DateTime.fromJSDate(value); } if (value && typeof value === 'string') { return DateTime.fromFormat(value, parseFormat); } return value ? this.createDateTime(value).setLocale(this.getLocale()) : null; }
David-Lees/date-time-picker
projects/picker/src/lib/date-time/adapter/luxon-adapter/luxon-date-time-adapter.class.ts
TypeScript
MethodDeclaration
/** * Returns the given value if given a valid DateTime or null. Deserializes valid ISO 8601 strings * (https://www.ietf.org/rfc/rfc3339.txt) and valid Date objects into valid DateTimes and empty * string into null. Returns an invalid date for all other values. */ deserialize(value: any): DateTime | null { let date: DateTime | null; if (value instanceof Date) { date = DateTime.fromJSDate(value); } if (typeof value === 'string') { if (!value) { return null; } date = DateTime.fromISO(value); } if (date && this.isValid(date)) { return date; } return super.deserialize(value); }
David-Lees/date-time-picker
projects/picker/src/lib/date-time/adapter/luxon-adapter/luxon-date-time-adapter.class.ts
TypeScript
MethodDeclaration
/** Creates a DateTime instance while respecting the current UTC settings. */ private createDateTime(...args: any[]): DateTime { return this.options && this.options.useUtc ? DateTime.utc(...args) : DateTime.local(...args); }
David-Lees/date-time-picker
projects/picker/src/lib/date-time/adapter/luxon-adapter/luxon-date-time-adapter.class.ts
TypeScript
ArrowFunction
(width: number, height: number) => { var canvas = document.createElement('canvas'); canvas.width = width; canvas.height = height; canvas.oncontextmenu = () => false; canvas.onselectstart = () => false; return canvas; }
playpuppy/matter-ts
src/render.ts
TypeScript
ArrowFunction
(canvas: HTMLCanvasElement) => { const context = canvas.getContext('2d') as any; const devicePixelRatio = window.devicePixelRatio || 1; const backingStorePixelRatio = context.webkitBackingStorePixelRatio || context.mozBackingStorePixelRatio || context.msBackingStorePixelRatio || context.oBackingStorePixelRatio || context.backingStorePixelRatio || 1; return devicePixelRatio / backingStorePixelRatio; }
playpuppy/matter-ts
src/render.ts
TypeScript
ArrowFunction
(imagePath: string) => { const image = textures[imagePath]; if (image) { return image; } const image2 = textures[imagePath] = new Image(); image2.src = imagePath; return image2; }
playpuppy/matter-ts
src/render.ts
TypeScript
ArrowFunction
(time: number) => { this.frameRequestId = _requestAnimationFrame(loop); this.draw(); }
playpuppy/matter-ts
src/render.ts
TypeScript
MethodDeclaration
/** * Continuously updates the render canvas on the `requestAnimationFrame` event. * @method run * @param {render} this */ public run() { if (_requestAnimationFrame !== undefined) { const loop = (time: number) => { this.frameRequestId = _requestAnimationFrame(loop); this.draw(); }; loop(1);// } }
playpuppy/matter-ts
src/render.ts
TypeScript
MethodDeclaration
/** * Ends execution of `Render.run` on the given `render`, by canceling the animation frame request event loop. * @method stop * @param {render} render */ public stop() { if (_cancelAnimationFrame !== undefined) { _cancelAnimationFrame(this.frameRequestId); } }
playpuppy/matter-ts
src/render.ts
TypeScript
MethodDeclaration
/** * Sets the pixel ratio of the renderer and updates the canvas. * To automatically detect the correct ratio, pass the string `'auto'` for `pixelRatio`. * @method setPixelRatio * @param {render} this * @param {number} pixelRatio */ private setPixelRatio(pixelRatio?: number) { var options = this.options; var canvas = this.canvas; if (pixelRatio === undefined) { pixelRatio = _getPixelRatio(canvas); } options.pixelRatio = pixelRatio; canvas.setAttribute('data-pixel-ratio', `${pixelRatio}`); canvas.width = options.width * pixelRatio; canvas.height = options.height * pixelRatio; canvas.style.width = options.width + 'px'; canvas.style.height = options.height + 'px'; }
playpuppy/matter-ts
src/render.ts
TypeScript
MethodDeclaration
/** * Positions and sizes the viewport around the given object bounds. * Objects must have at least one of the following properties: * - `object.bounds` * - `object.position` * - `object.min` and `object.max` * - `object.x` and `object.y` * @method lookAt * @param {render} this * @param {object[]} objects * @param {vector} [padding] * @param {bool} [center=true] */ public lookAt(objects: any[], padding?: Vector, center = true) { objects = Array.isArray(objects) ? objects : [objects]; if (padding === undefined) { padding = new Vector(); } // find bounds of all objects var bounds = new Bounds(Infinity, Infinity, -Infinity, -Infinity); for (var i = 0; i < objects.length; i += 1) { var object = objects[i], min = object.bounds ? object.bounds.min : (object.min || object.position || object), max = object.bounds ? object.bounds.max : (object.max || object.position || object); if (min && max) { if (min.x < bounds.min.x) bounds.min.x = min.x; if (max.x > bounds.max.x) bounds.max.x = max.x; if (min.y < bounds.min.y) bounds.min.y = min.y; if (max.y > bounds.max.y) bounds.max.y = max.y; } } // find ratios var width = (bounds.max.x - bounds.min.x) + 2 * padding.x, height = (bounds.max.y - bounds.min.y) + 2 * padding.y, viewHeight = this.canvas.height, viewWidth = this.canvas.width, outerRatio = viewWidth / viewHeight, innerRatio = width / height, scaleX = 1, scaleY = 1; // find scale factor if (innerRatio > outerRatio) { scaleY = innerRatio / outerRatio; } else { scaleX = outerRatio / innerRatio; } // enable bounds this.options.hasBounds = true; // position and size this.bounds.min.x = bounds.min.x; this.bounds.max.x = bounds.min.x + width * scaleX; this.bounds.min.y = bounds.min.y; this.bounds.max.y = bounds.min.y + height * scaleY; // center if (center) { this.bounds.min.x += width * 0.5 - (width * scaleX) * 0.5; this.bounds.max.x += width * 0.5 - (width * scaleX) * 0.5; this.bounds.min.y += height * 0.5 - (height * scaleY) * 0.5; this.bounds.max.y += height * 0.5 - (height * scaleY) * 0.5; } // padding this.bounds.min.x -= padding.x; this.bounds.max.x -= padding.x; this.bounds.min.y -= padding.y; this.bounds.max.y -= padding.y; // update mouse if (this.mouse) { this.mouse.setScale(new Vector( (this.bounds.max.x - this.bounds.min.x) / this.canvas.width, (this.bounds.max.y - this.bounds.min.y) / this.canvas.height )); this.mouse.setOffset(this.bounds.min); } }
playpuppy/matter-ts
src/render.ts
TypeScript
MethodDeclaration
/** * Applies viewport transforms based on `render.bounds` to a render context. * @method startViewTransform * @param {render} this */ public startViewTransform() { var boundsWidth = this.bounds.max.x - this.bounds.min.x, boundsHeight = this.bounds.max.y - this.bounds.min.y, boundsScaleX = boundsWidth / this.options.width, boundsScaleY = boundsHeight / this.options.height; this.context.setTransform( this.options.pixelRatio / boundsScaleX, 0, 0, this.options.pixelRatio / boundsScaleY, 0, 0 ); this.context.translate(-this.bounds.min.x, -this.bounds.min.y); }
playpuppy/matter-ts
src/render.ts
TypeScript
MethodDeclaration
/** * Resets all transforms on the render context. * @method endViewTransform * @param {render} render */ public endViewTransform() { this.context.setTransform(this.options.pixelRatio, 0, 0, this.options.pixelRatio, 0, 0); }
playpuppy/matter-ts
src/render.ts
TypeScript
MethodDeclaration
public draw() { const engine = this.engine; const world = engine.world; const canvas = this.canvas; const context = this.context; const options = this.options; const allBodies = world.allBodies(); const allConstraints = world.allConstraints(); const background = options.wireframes ? options.wireframeBackground : options.background; var bodies: Body[] = []; var constraints: Constraint[] = []; var event = { timestamp: engine.timing.timestamp } Events.trigger(this, 'beforeRender', event); // apply background if it has changed if (this.currentBackground !== background) { this.applyBackground(background); } // clear the canvas with a transparent fill, to allow the canvas background to show context.globalCompositeOperation = 'source-in'; context.fillStyle = "transparent"; context.fillRect(0, 0, canvas.width, canvas.height); context.globalCompositeOperation = 'source-over'; // handle bounds if (options.hasBounds) { // filter out bodies that are not in view for (var i = 0; i < allBodies.length; i++) { var body = allBodies[i]; if (Bounds.overlaps(body.bounds, this.bounds)) bodies.push(body); } // filter out constraints that are not in view for (var i = 0; i < allConstraints.length; i++) { var constraint = allConstraints[i], bodyA = constraint.bodyA, bodyB = constraint.bodyB, pointAWorld = constraint.pointA, pointBWorld = constraint.pointB; if (bodyA) pointAWorld = Vector.add(bodyA.position, constraint.pointA!); if (bodyB) pointBWorld = Vector.add(bodyB.position, constraint.pointB!); if (!pointAWorld || !pointBWorld) continue; if (Bounds.contains(this.bounds, pointAWorld) || Bounds.contains(this.bounds, pointBWorld)) constraints.push(constraint); } // transform the view this.startViewTransform(); // update mouse if (this.mouse) { this.mouse.setScale(new Vector( (this.bounds.max.x - this.bounds.min.x) / this.options.width, (this.bounds.max.y - this.bounds.min.y) / this.options.height )); this.mouse.setOffset(this.bounds.min); } } else { constraints = allConstraints; bodies = allBodies; if (this.options.pixelRatio !== 1) { this.context.setTransform(this.options.pixelRatio, 0, 0, this.options.pixelRatio, 0, 0); } } if (!options.wireframes || (engine.enableSleeping && options.showSleeping)) { // fully featured rendering of bodies this.bodies(bodies, context); } else { if (options.showConvexHulls) this.bodyConvexHulls(bodies, context); // optimised method for wireframes only this.bodyWireframes(bodies, context); } if (options.showBounds) this.bodyBounds(bodies, context); if (options.showAxes || options.showAngleIndicator) this.bodyAxes(bodies, context); if (options.showPositions) this.bodyPositions(bodies, context); if (options.showVelocity) this.bodyVelocity(bodies, context); if (options.showIds) this.bodyIds(bodies, context); if (options.showSeparations) this.separations(engine.pairs.list, context); if (options.showCollisions) this.collisions(engine.pairs.list, context); if (options.showVertexNumbers) this.vertexNumbers(bodies, context); if (options.showMousePosition) this.mousePosition(this.mouse, context); Render.constraints(constraints, context); if (options.showBroadphase && engine.broadphase instanceof Grid) this.grid(engine.broadphase, context); if (options.showDebug) this.debug(context); if (options.hasBounds) { // revert view transforms this.endViewTransform(); } Events.trigger(this, 'afterRender', event); }
playpuppy/matter-ts
src/render.ts
TypeScript
MethodDeclaration
/** * Applies the background to the canvas using CSS. * @method applyBackground * @private * @param {render} render * @param {string} background */ private applyBackground(background: string) { var cssBackground = background; if (/(jpg|gif|png)$/.test(background)) cssBackground = 'url(' + background + ')'; this.canvas.style.background = cssBackground; this.canvas.style.backgroundSize = "contain"; this.currentBackground = background; }
playpuppy/matter-ts
src/render.ts
TypeScript
MethodDeclaration
/** * Description * @private * @method debug * @param {render} this * @param {RenderingContext} context */ private debug(context: CanvasRenderingContext2D) { var c = context, engine = this.engine, world = engine.world, // metrics = engine.metrics, options = this.options, bodies = world.allBodies(), space = " "; if (engine.timing.timestamp - (this.debugTimestamp) >= 500) { var text = ""; // if (metrics.timing) { // text += "fps: " + Math.round(metrics.timing.fps) + space; // } // // @if DEBUG // if (metrics.extended) { // if (metrics.timing) { // text += "delta: " + metrics.timing.delta.toFixed(3) + space; // text += "correction: " + metrics.timing.correction.toFixed(3) + space; // } // text += "bodies: " + bodies.length + space; // if (engine.broadphase.controller === Grid) // text += "buckets: " + metrics.buckets + space; // text += "\n"; // text += "collisions: " + metrics.collisions + space; // text += "pairs: " + engine.pairs.list.length + space; // text += "broad: " + metrics.broadEff + space; // text += "mid: " + metrics.midEff + space; // text += "narrow: " + metrics.narrowEff + space; // } // @endif this.debugString = text; this.debugTimestamp = engine.timing.timestamp; } if (this.debugString) { c.font = "12px Arial"; if (options.wireframes) { c.fillStyle = 'rgba(255,255,255,0.5)'; } else { c.fillStyle = 'rgba(0,0,0,0.5)'; } var split = this.debugString.split('\n'); for (var i = 0; i < split.length; i++) { c.fillText(split[i], 50, 50 + i * 18); } } }
playpuppy/matter-ts
src/render.ts
TypeScript
MethodDeclaration
/** * Description * @private * @method constraints * @param {constraint[]} constraints * @param {RenderingContext} context */ private static constraints(constraints: Constraint[], context: CanvasRenderingContext2D) { var c = context; for (var i = 0; i < constraints.length; i++) { var constraint = constraints[i]; if (!constraint.visible || !constraint.pointA || !constraint.pointB) continue; var bodyA = constraint.bodyA, bodyB = constraint.bodyB, start, end = Vector.Null; if (bodyA) { start = Vector.add(bodyA.position, constraint.pointA); } else { start = constraint.pointA; } if (constraint.renderType === 'pin') { c.beginPath(); c.arc(start.x, start.y, 3, 0, 2 * Math.PI); c.closePath(); } else { if (bodyB) { end = Vector.add(bodyB.position, constraint.pointB); } else { end = constraint.pointB; } c.beginPath(); c.moveTo(start.x, start.y); if (constraint.renderType === 'spring') { var delta = Vector.sub(end, start), normal = Vector.perp(Vector.normalise(delta)), coils = Math.ceil(Common.clamp(constraint.length / 5, 12, 20)), offset; for (var j = 1; j < coils; j += 1) { offset = j % 2 === 0 ? 1 : -1; c.lineTo( start.x + delta.x * (j / coils) + normal.x * offset * 4, start.y + delta.y * (j / coils) + normal.y * offset * 4 ); } } c.lineTo(end.x, end.y); } if (constraint.lineWidth) { c.lineWidth = constraint.lineWidth; c.strokeStyle = constraint.strokeStyle; c.stroke(); } if (constraint.anchors) { c.fillStyle = constraint.strokeStyle; c.beginPath(); c.arc(start.x, start.y, 3, 0, 2 * Math.PI); c.arc(end.x, end.y, 3, 0, 2 * Math.PI); c.closePath(); c.fill(); } } }
playpuppy/matter-ts
src/render.ts
TypeScript
MethodDeclaration
/** * Description * @private * @method bodyShadows * @param {render} render * @param {body[]} bodies * @param {RenderingContext} context */ private bodyShadows(bodies: Body[], context: CanvasRenderingContext2D) { var c = context, engine = this.engine; for (var i = 0; i < bodies.length; i++) { var body = bodies[i]; if (!body.visible) continue; if (body.circleRadius) { c.beginPath(); c.arc(body.position.x, body.position.y, body.circleRadius, 0, 2 * Math.PI); c.closePath(); } else { c.beginPath(); c.moveTo(body.vertices[0].x, body.vertices[0].y); for (var j = 1; j < body.vertices.length; j++) { c.lineTo(body.vertices[j].x, body.vertices[j].y); } c.closePath(); } var distanceX = body.position.x - this.options.width * 0.5, distanceY = body.position.y - this.options.height * 0.2, distance = Math.abs(distanceX) + Math.abs(distanceY); c.shadowColor = 'rgba(0,0,0,0.15)'; c.shadowOffsetX = 0.05 * distanceX; c.shadowOffsetY = 0.05 * distanceY; c.shadowBlur = 1 + 12 * Math.min(1, distance / 1000); c.fill(); // FIXME // c.shadowColor = null; // c.shadowOffsetX = null; // c.shadowOffsetY = null; // c.shadowBlur = null; } }
playpuppy/matter-ts
src/render.ts
TypeScript
MethodDeclaration
/** * Description * @private * @method bodies * @param {render} render * @param {body[]} bodies * @param {RenderingContext} context */ private bodies(bodies: Body[], context: CanvasRenderingContext2D) { var c = context, engine = this.engine, options = this.options, showInternalEdges = options.showInternalEdges || !options.wireframes, body, part, i, k; for (i = 0; i < bodies.length; i++) { body = bodies[i]; if (!body.visible) continue; // handle compound parts for (k = body.parts.length > 1 ? 1 : 0; k < body.parts.length; k++) { part = body.parts[k]; if (!part.visible) continue; if (options.showSleeping && body.isSleeping) { c.globalAlpha = 0.5 * part.opacity; } else if (part.opacity !== 1) { c.globalAlpha = part.opacity; } if (part.texture && !options.wireframes) { // part sprite const texture = _getTexture(part.texture); c.translate(part.position.x, part.position.y); c.rotate(part.angle); c.drawImage( texture, texture.width * -part.xOffset * part.xScale, texture.height * -part.yOffset * part.yScale, texture.width * part.xScale, texture.height * part.yScale ); // revert translation, hopefully faster than save / restore c.rotate(-part.angle); c.translate(-part.position.x, -part.position.y); } else { // part polygon if (part.circleRadius) { c.beginPath(); c.arc(part.position.x, part.position.y, part.circleRadius, 0, 2 * Math.PI); } else { c.beginPath(); c.moveTo(part.vertices[0].x, part.vertices[0].y); for (var j = 1; j < part.vertices.length; j++) { if (!part.vertices[j - 1].isInternal || showInternalEdges) { c.lineTo(part.vertices[j].x, part.vertices[j].y); } else { c.moveTo(part.vertices[j].x, part.vertices[j].y); } if (part.vertices[j].isInternal && !showInternalEdges) { c.moveTo(part.vertices[(j + 1) % part.vertices.length].x, part.vertices[(j + 1) % part.vertices.length].y); } } c.lineTo(part.vertices[0].x, part.vertices[0].y); c.closePath(); } if (!options.wireframes) { c.fillStyle = part.fillStyle; if (part.lineWidth) { c.lineWidth = part.lineWidth; c.strokeStyle = part.strokeStyle; c.stroke(); } c.fill(); } else { c.lineWidth = 1; c.strokeStyle = '#bbb'; c.stroke(); } } c.globalAlpha = 1; } } }
playpuppy/matter-ts
src/render.ts
TypeScript
MethodDeclaration
/** * Optimised method for drawing body wireframes in one pass * @private * @method bodyWireframes * @param {render} this * @param {body[]} bodies * @param {RenderingContext} context */ private bodyWireframes(bodies: Body[], context: CanvasRenderingContext2D) { var c = context, showInternalEdges = this.options.showInternalEdges, body, part, i, j, k; c.beginPath(); // render all bodies for (i = 0; i < bodies.length; i++) { body = bodies[i]; if (!body.visible) continue; // handle compound parts for (k = body.parts.length > 1 ? 1 : 0; k < body.parts.length; k++) { part = body.parts[k]; c.moveTo(part.vertices[0].x, part.vertices[0].y); for (j = 1; j < part.vertices.length; j++) { if (!part.vertices[j - 1].isInternal || showInternalEdges) { c.lineTo(part.vertices[j].x, part.vertices[j].y); } else { c.moveTo(part.vertices[j].x, part.vertices[j].y); } if (part.vertices[j].isInternal && !showInternalEdges) { c.moveTo(part.vertices[(j + 1) % part.vertices.length].x, part.vertices[(j + 1) % part.vertices.length].y); } } c.lineTo(part.vertices[0].x, part.vertices[0].y); } } c.lineWidth = 1; c.strokeStyle = '#bbb'; c.stroke(); }
playpuppy/matter-ts
src/render.ts
TypeScript
MethodDeclaration
/** * Optimised method for drawing body convex hull wireframes in one pass * @private * @method bodyConvexHulls * @param {render} this * @param {body[]} bodies * @param {RenderingContext} context */ private bodyConvexHulls(bodies: Body[], context: CanvasRenderingContext2D) { var c = context, body, part, i, j, k; c.beginPath(); // render convex hulls for (i = 0; i < bodies.length; i++) { body = bodies[i]; if (!body.visible || body.parts.length === 1) continue; c.moveTo(body.vertices[0].x, body.vertices[0].y); for (j = 1; j < body.vertices.length; j++) { c.lineTo(body.vertices[j].x, body.vertices[j].y); } c.lineTo(body.vertices[0].x, body.vertices[0].y); } c.lineWidth = 1; c.strokeStyle = 'rgba(255,255,255,0.2)'; c.stroke(); }
playpuppy/matter-ts
src/render.ts
TypeScript
MethodDeclaration
/** * Renders body vertex numbers. * @private * @method vertexNumbers * @param {render} render * @param {body[]} bodies * @param {RenderingContext} context */ private vertexNumbers(bodies: Body[], context: CanvasRenderingContext2D) { var c = context, i, j, k; for (i = 0; i < bodies.length; i++) { var parts = bodies[i].parts; for (k = parts.length > 1 ? 1 : 0; k < parts.length; k++) { var part = parts[k]; for (j = 0; j < part.vertices.length; j++) { c.fillStyle = 'rgba(255,255,255,0.2)'; c.fillText(i + '_' + j, part.position.x + (part.vertices[j].x - part.position.x) * 0.8, part.position.y + (part.vertices[j].y - part.position.y) * 0.8); } } } }
playpuppy/matter-ts
src/render.ts
TypeScript
MethodDeclaration
/** * Renders mouse position. * @private * @method mousePosition * @param {render} render * @param {mouse} mouse * @param {RenderingContext} context */ private mousePosition(mouse: any, context: CanvasRenderingContext2D) { var c = context; c.fillStyle = 'rgba(255,255,255,0.8)'; c.fillText(mouse.position.x + ' ' + mouse.position.y, mouse.position.x + 5, mouse.position.y - 5); }
playpuppy/matter-ts
src/render.ts
TypeScript
MethodDeclaration
/** * Draws body bounds * @private * @method bodyBounds * @param {render} render * @param {body[]} bodies * @param {RenderingContext} context */ private bodyBounds(bodies: Body[], context: CanvasRenderingContext2D) { var c = context, engine = this.engine, options = this.options; c.beginPath(); for (var i = 0; i < bodies.length; i++) { var body = bodies[i]; if (body.visible) { var parts = bodies[i].parts; for (var j = parts.length > 1 ? 1 : 0; j < parts.length; j++) { var part = parts[j]; c.rect(part.bounds.min.x, part.bounds.min.y, part.bounds.max.x - part.bounds.min.x, part.bounds.max.y - part.bounds.min.y); } } } if (options.wireframes) { c.strokeStyle = 'rgba(255,255,255,0.08)'; } else { c.strokeStyle = 'rgba(0,0,0,0.1)'; } c.lineWidth = 1; c.stroke(); }
playpuppy/matter-ts
src/render.ts
TypeScript
MethodDeclaration
/** * Draws body angle indicators and axes * @private * @method bodyAxes * @param {render} render * @param {body[]} bodies * @param {RenderingContext} context */ private bodyAxes(bodies: Body[], context: CanvasRenderingContext2D) { var c = context, engine = this.engine, options = this.options, part, i, j, k; c.beginPath(); for (i = 0; i < bodies.length; i++) { var body = bodies[i], parts = body.parts; if (!body.visible) continue; if (options.showAxes) { // render all axes for (j = parts.length > 1 ? 1 : 0; j < parts.length; j++) { part = parts[j]; for (k = 0; k < part.axes.length; k++) { var axis = part.axes[k]; c.moveTo(part.position.x, part.position.y); c.lineTo(part.position.x + axis.x * 20, part.position.y + axis.y * 20); } } } else { for (j = parts.length > 1 ? 1 : 0; j < parts.length; j++) { part = parts[j]; for (k = 0; k < part.axes.length; k++) { // render a single axis indicator c.moveTo(part.position.x, part.position.y); c.lineTo((part.vertices[0].x + part.vertices[part.vertices.length - 1].x) / 2, (part.vertices[0].y + part.vertices[part.vertices.length - 1].y) / 2); } } } } if (options.wireframes) { c.strokeStyle = 'indianred'; c.lineWidth = 1; } else { c.strokeStyle = 'rgba(255, 255, 255, 0.4)'; c.globalCompositeOperation = 'overlay'; c.lineWidth = 2; } c.stroke(); c.globalCompositeOperation = 'source-over'; }
playpuppy/matter-ts
src/render.ts
TypeScript
MethodDeclaration
/** * Draws body positions * @private * @method bodyPositions * @param {render} render * @param {body[]} bodies * @param {RenderingContext} context */ private bodyPositions(bodies: Body[], context: CanvasRenderingContext2D) { var c = context, engine = this.engine, options = this.options, body, part, i, k; c.beginPath(); // render current positions for (i = 0; i < bodies.length; i++) { body = bodies[i]; if (!body.visible) continue; // handle compound parts for (k = 0; k < body.parts.length; k++) { part = body.parts[k]; c.arc(part.position.x, part.position.y, 3, 0, 2 * Math.PI, false); c.closePath(); } } if (options.wireframes) { c.fillStyle = 'indianred'; } else { c.fillStyle = 'rgba(0,0,0,0.5)'; } c.fill(); c.beginPath(); // render previous positions for (i = 0; i < bodies.length; i++) { body = bodies[i]; if (body.visible) { c.arc(body.positionPrev.x, body.positionPrev.y, 2, 0, 2 * Math.PI, false); c.closePath(); } } c.fillStyle = 'rgba(255,165,0,0.8)'; c.fill(); }
playpuppy/matter-ts
src/render.ts
TypeScript
MethodDeclaration
/** * Draws body velocity * @private * @method bodyVelocity * @param {render} this * @param {body[]} bodies * @param {RenderingContext} context */ private bodyVelocity(bodies: Body[], context: CanvasRenderingContext2D) { var c = context; c.beginPath(); for (var i = 0; i < bodies.length; i++) { var body = bodies[i]; if (!body.visible) continue; c.moveTo(body.position.x, body.position.y); c.lineTo(body.position.x + (body.position.x - body.positionPrev.x) * 2, body.position.y + (body.position.y - body.positionPrev.y) * 2); } c.lineWidth = 3; c.strokeStyle = 'cornflowerblue'; c.stroke(); }
playpuppy/matter-ts
src/render.ts
TypeScript
MethodDeclaration
/** * Draws body ids * @private * @method bodyIds * @param {render} this * @param {body[]} bodies * @param {RenderingContext} context */ private bodyIds(bodies: Body[], context: CanvasRenderingContext2D) { var c = context, i, j; for (i = 0; i < bodies.length; i++) { if (!bodies[i].visible) continue; var parts = bodies[i].parts; for (j = parts.length > 1 ? 1 : 0; j < parts.length; j++) { var part = parts[j]; c.font = "12px Arial"; c.fillStyle = 'rgba(255,255,255,0.5)'; c.fillText(`${part.id}`, part.position.x + 10, part.position.y - 10); } } }
playpuppy/matter-ts
src/render.ts
TypeScript
MethodDeclaration
/** * Description * @private * @method collisions * @param {render} render * @param {pair[]} pairs * @param {RenderingContext} context */ private collisions(pairs: Pair[], context: CanvasRenderingContext2D) { var c = context, options = this.options, pair, collision, corrected, bodyA, bodyB, i, j; c.beginPath(); // render collision positions for (i = 0; i < pairs.length; i++) { pair = pairs[i]; if (!pair.isActive) continue; collision = pair.collision; for (j = 0; j < pair.activeContacts.length; j++) { var contact = pair.activeContacts[j], vertex = contact.vertex; c.rect(vertex.x - 1.5, vertex.y - 1.5, 3.5, 3.5); } } if (options.wireframes) { c.fillStyle = 'rgba(255,255,255,0.7)'; } else { c.fillStyle = 'orange'; } c.fill(); c.beginPath(); // render collision normals for (i = 0; i < pairs.length; i++) { pair = pairs[i]; if (!pair.isActive) continue; collision = pair.collision!; if (pair.activeContacts.length > 0) { var normalPosX = pair.activeContacts[0].vertex.x, normalPosY = pair.activeContacts[0].vertex.y; if (pair.activeContacts.length === 2) { normalPosX = (pair.activeContacts[0].vertex.x + pair.activeContacts[1].vertex.x) / 2; normalPosY = (pair.activeContacts[0].vertex.y + pair.activeContacts[1].vertex.y) / 2; } if (collision.bodyB === collision.supports[0].body || collision.bodyA.isStatic === true) { c.moveTo(normalPosX - collision.normal.x * 8, normalPosY - collision.normal.y * 8); } else { c.moveTo(normalPosX + collision.normal.x * 8, normalPosY + collision.normal.y * 8); } c.lineTo(normalPosX, normalPosY); } } if (options.wireframes) { c.strokeStyle = 'rgba(255,165,0,0.7)'; } else { c.strokeStyle = 'orange'; } c.lineWidth = 1; c.stroke(); }
playpuppy/matter-ts
src/render.ts
TypeScript
MethodDeclaration
/** * Description * @private * @method separations * @param {render} render * @param {pair[]} pairs * @param {RenderingContext} context */ private separations(pairs: Pair[], context: CanvasRenderingContext2D) { var c = context, options = this.options, pair, collision, corrected, bodyA, bodyB, i, j; c.beginPath(); // render separations for (i = 0; i < pairs.length; i++) { pair = pairs[i]; if (!pair.isActive) continue; collision = pair.collision!; bodyA = collision.bodyA; bodyB = collision.bodyB; var k = 1; if (!bodyB.isStatic && !bodyA.isStatic) k = 0.5; if (bodyB.isStatic) k = 0; c.moveTo(bodyB.position.x, bodyB.position.y); c.lineTo(bodyB.position.x - collision.penetration.x * k, bodyB.position.y - collision.penetration.y * k); k = 1; if (!bodyB.isStatic && !bodyA.isStatic) k = 0.5; if (bodyA.isStatic) k = 0; c.moveTo(bodyA.position.x, bodyA.position.y); c.lineTo(bodyA.position.x + collision.penetration.x * k, bodyA.position.y + collision.penetration.y * k); } if (options.wireframes) { c.strokeStyle = 'rgba(255,165,0,0.5)'; } else { c.strokeStyle = 'orange'; } c.stroke(); }
playpuppy/matter-ts
src/render.ts
TypeScript
MethodDeclaration
/** * Description * @private * @method grid * @param {render} this * @param {grid} grid * @param {RenderingContext} context */ private grid(grid: Grid, context: CanvasRenderingContext2D) { var c = context, options = this.options; if (options.wireframes) { c.strokeStyle = 'rgba(255,180,0,0.1)'; } else { c.strokeStyle = 'rgba(255,180,0,0.5)'; } c.beginPath(); var bucketKeys = Common.keys(grid.buckets); for (var i = 0; i < bucketKeys.length; i++) { var bucketId = bucketKeys[i]; if (grid.buckets[bucketId].length < 2) continue; var region = bucketId.split(/C|R/); c.rect(0.5 + parseInt(region[1], 10) * grid.bucketWidth, 0.5 + parseInt(region[2], 10) * grid.bucketHeight, grid.bucketWidth, grid.bucketHeight); } c.lineWidth = 1; c.stroke(); }
playpuppy/matter-ts
src/render.ts
TypeScript
MethodDeclaration
/** * Description * @private * @method inspector * @param {inspector} inspector * @param {RenderingContext} context */ private inspector(inspector: any, context: CanvasRenderingContext2D) { var engine = inspector.engine, selected = inspector.selected, render = inspector.render, options = render.options, bounds; if (options.hasBounds) { var boundsWidth = render.bounds.max.x - render.bounds.min.x, boundsHeight = render.bounds.max.y - render.bounds.min.y, boundsScaleX = boundsWidth / render.options.width, boundsScaleY = boundsHeight / render.options.height; context.scale(1 / boundsScaleX, 1 / boundsScaleY); context.translate(-render.bounds.min.x, -render.bounds.min.y); } for (var i = 0; i < selected.length; i++) { var item = selected[i].data; context.translate(0.5, 0.5); context.lineWidth = 1; context.strokeStyle = 'rgba(255,165,0,0.9)'; context.setLineDash([1, 2]); switch (item.type) { case 'body': // render body selections bounds = item.bounds; context.beginPath(); context.rect(Math.floor(bounds.min.x - 3), Math.floor(bounds.min.y - 3), Math.floor(bounds.max.x - bounds.min.x + 6), Math.floor(bounds.max.y - bounds.min.y + 6)); context.closePath(); context.stroke(); break; case 'constraint': // render constraint selections var point = item.pointA; if (item.bodyA) point = item.pointB; context.beginPath(); context.arc(point.x, point.y, 10, 0, 2 * Math.PI); context.closePath(); context.stroke(); break; } context.setLineDash([]); context.translate(-0.5, -0.5); } // render selection region if (inspector.selectStart !== null) { context.translate(0.5, 0.5); context.lineWidth = 1; context.strokeStyle = 'rgba(255,165,0,0.6)'; context.fillStyle = 'rgba(255,165,0,0.1)'; bounds = inspector.selectBounds; context.beginPath(); context.rect(Math.floor(bounds.min.x), Math.floor(bounds.min.y), Math.floor(bounds.max.x - bounds.min.x), Math.floor(bounds.max.y - bounds.min.y)); context.closePath(); context.stroke(); context.fill(); context.translate(-0.5, -0.5); } if (options.hasBounds) context.setTransform(1, 0, 0, 1, 0, 0); }
playpuppy/matter-ts
src/render.ts
TypeScript
ArrowFunction
() => ( <div> <Label>I
AvinaLakshmi/sp-dev-fx-controls-react
node_modules/@microsoft/office-ui-fabric-react-bundle/node_modules/office-ui-fabric-react/src/components/Label/examples/Label.Basic.Example.tsx
TypeScript
FunctionDeclaration
export function getFamily(runtime: string | undefined): SamLambdaRuntimeFamily { switch (runtime) { case 'python3.7': case 'python3.6': case 'python2.7': case 'python': return SamLambdaRuntimeFamily.Python case 'nodejs8.10': case 'nodejs10.x': case 'nodejs': return SamLambdaRuntimeFamily.NodeJS case 'dotnetcore2.1': case 'dotnetcore': case 'dotnet': return SamLambdaRuntimeFamily.DotNetCore default: throw new Error(`Unrecognized runtime: '${runtime}'`) } }
PseudoAj/aws-toolkit-vscode
src/lambda/models/samLambdaRuntime.ts
TypeScript
FunctionDeclaration
function getSortableCompareText(runtime: SamLambdaRuntime): string { return runtimeCompareText.get(runtime) || runtime.toString() }
PseudoAj/aws-toolkit-vscode
src/lambda/models/samLambdaRuntime.ts
TypeScript
FunctionDeclaration
export function compareSamLambdaRuntime(a: SamLambdaRuntime, b: SamLambdaRuntime): number { return getSortableCompareText(a).localeCompare(getSortableCompareText(b)) }
PseudoAj/aws-toolkit-vscode
src/lambda/models/samLambdaRuntime.ts
TypeScript
EnumDeclaration
export enum SamLambdaRuntimeFamily { Python, NodeJS, DotNetCore }
PseudoAj/aws-toolkit-vscode
src/lambda/models/samLambdaRuntime.ts
TypeScript
TypeAliasDeclaration
// TODO: Can we dynamically determine the available runtimes? We could theoretically parse the // output of `sam init --help`, but that's a hack. export type SamLambdaRuntime = 'python3.7' | 'python3.6' | 'python2.7' | 'nodejs8.10' | 'nodejs10.x' | 'dotnetcore2.1'
PseudoAj/aws-toolkit-vscode
src/lambda/models/samLambdaRuntime.ts
TypeScript
ArrowFunction
() => { this._elementRef.nativeElement.appendChild(this._img); this._loaded(true); }
Amonratchantawon/ecommerce-by-ass
src/components/preload-image/preload-image.ts
TypeScript
ClassDeclaration
@Component({ selector: 'preload-image', templateUrl: 'preload-image.html' }) export class PreloadImage implements OnChanges { _src: string = ''; _ratio: { w: number, h: number }; _img: any; constructor(public _elementRef: ElementRef, public _renderer: Renderer) { this._img = new Image(); } @Input() alt: string; @Input() title: string; @Input() set src(val: string) { this._src = isPresent(val) ? val : ''; } @Input() set ratio(ratio: { w: number, h: number }){ this._ratio = ratio || null; } ngOnChanges(changes: { [propName: string]: SimpleChange }) { let ratio_height = (this._ratio.h / this._ratio.w * 100)+"%"; // Conserve aspect ratio (see: http://stackoverflow.com/a/10441480/1116959) this._renderer.setElementStyle(this._elementRef.nativeElement, 'padding-bottom', ratio_height); this._update(); // console.log("CHANGES preload-image", this._src); // console.log(changes['src'].isFirstChange()); } _update() { if (isPresent(this.alt)) { this._img.alt = this.alt; } if (isPresent(this.title)) { this._img.title = this.title; } this._img.addEventListener('load', () => { this._elementRef.nativeElement.appendChild(this._img); this._loaded(true); }); this._img.src = this._src; this._loaded(false); } _loaded(isLoaded: boolean) { this._elementRef.nativeElement.classList[isLoaded ? 'add' : 'remove']('img-loaded'); } }
Amonratchantawon/ecommerce-by-ass
src/components/preload-image/preload-image.ts
TypeScript
MethodDeclaration
ngOnChanges(changes: { [propName: string]: SimpleChange }) { let ratio_height = (this._ratio.h / this._ratio.w * 100)+"%"; // Conserve aspect ratio (see: http://stackoverflow.com/a/10441480/1116959) this._renderer.setElementStyle(this._elementRef.nativeElement, 'padding-bottom', ratio_height); this._update(); // console.log("CHANGES preload-image", this._src); // console.log(changes['src'].isFirstChange()); }
Amonratchantawon/ecommerce-by-ass
src/components/preload-image/preload-image.ts
TypeScript
MethodDeclaration
_update() { if (isPresent(this.alt)) { this._img.alt = this.alt; } if (isPresent(this.title)) { this._img.title = this.title; } this._img.addEventListener('load', () => { this._elementRef.nativeElement.appendChild(this._img); this._loaded(true); }); this._img.src = this._src; this._loaded(false); }
Amonratchantawon/ecommerce-by-ass
src/components/preload-image/preload-image.ts
TypeScript
MethodDeclaration
_loaded(isLoaded: boolean) { this._elementRef.nativeElement.classList[isLoaded ? 'add' : 'remove']('img-loaded'); }
Amonratchantawon/ecommerce-by-ass
src/components/preload-image/preload-image.ts
TypeScript
ArrowFunction
(): JSX.Element => ( <DemoContainer title="String Item"> <PropertyItemString onChange
Gulbrandr/alva
packages/components/src/property-item-string/demo.tsx
TypeScript
ArrowFunction
() => { const [orphanages, setOrphanages] = useState<Orphanage[]>([]); useEffect(() => { (async () => { const { data } = await api.get<Orphanage[]>('/orphanages'); setOrphanages(data); })(); }, []); return ( <Container> <aside> <header> <img src={MapMarkerImg} alt="Happy" /> <h2>Escolha um orfanato no mapa</h2> <p>Muitas crianças estão esperando a sua visita :)</p> </header> <footer> <strong>Mogi Mirim</strong> <span>São Paulo</span> </footer> </aside> <MapContainer> <Map center={[-22.4432173, -46.8148575]} zoom={15}> <TileLayer url="https://a.tile.openstreetmap.org/{z}/{x}/{y}.png" /> {orphanages.map(orphanage => ( <Marker key={orphanage.id} position={[orphanage.latitude, orphanage.longitude]} icon={mapIcon} > <Popup closeButton={false} maxWidth={240} minWidth={240}> {orphanage.name} <Link to={`/orphanages/${orphanage.id}`}> <FiArrowRight size={20} color="#FFF" /> </Link> </Popup> </Marker>
RodrigoSSilverio/HappyNWL
src/pages/OrphanagesMap/index.tsx
TypeScript
ArrowFunction
() => { (async () => { const { data } = await api.get<Orphanage[]>('/orphanages'); setOrphanages(data); })(); }
RodrigoSSilverio/HappyNWL
src/pages/OrphanagesMap/index.tsx
TypeScript
ArrowFunction
async () => { const { data } = await api.get<Orphanage[]>('/orphanages'); setOrphanages(data); }
RodrigoSSilverio/HappyNWL
src/pages/OrphanagesMap/index.tsx
TypeScript
ArrowFunction
orphanage => ( <Marker key={orphanage.id}
RodrigoSSilverio/HappyNWL
src/pages/OrphanagesMap/index.tsx
TypeScript
InterfaceDeclaration
interface Orphanage { id: number; name: string; latitude: number; longitude: number; }
RodrigoSSilverio/HappyNWL
src/pages/OrphanagesMap/index.tsx
TypeScript
ArrowFunction
async () => { try { const PORT = process.env.SERVER_PORT || 5000; const app = await NestFactory.create(AppModule); app.enableCors(); await app.listen(PORT, () => { console.log(`server started on PORT: ${PORT}`); }) } catch (error) { console.log(error); } }
MuscularSloth/music-platform-api
src/main.ts
TypeScript
ArrowFunction
() => { console.log(`server started on PORT: ${PORT}`); }
MuscularSloth/music-platform-api
src/main.ts
TypeScript
ClassDeclaration
export class OpenZeppelinExtensionAdapter implements IExtensionAdapter { private extensionInfo: any; private extension: Extension<any> | undefined; constructor() { this.extensionInfo = Constants.externalExtensions[Constants.coreSdk.openZeppelin]; this.extension = extensions.getExtension(this.extensionInfo.name); } public async validateExtension(): Promise<void> { if (!this.extension) { throw new Error(Constants.errorMessageStrings.ExtensionNotInstalled(this.extensionInfo.name)); } const version = this.extension.packageJSON.version; if (!semver.eq(version, this.extensionInfo.supportedVersion)) { throw new Error(Constants.informationMessage.unsupportedVersionOfExternalExtension( this.extensionInfo.name, version, this.extensionInfo.supportedVersion)); } if (!this.extension.isActive) { await this.extension.activate(); } } public async build(): Promise<void> { return commands.executeCommand(this.extensionInfo.commands.buildContracts); } public async deploy(): Promise<void> { return commands.executeCommand(this.extensionInfo.commands.deployContracts); } }
MHMYunos2020/vscode-azure-blockchain-ethereum
src/services/extensionAdapter/OpenZeppelinExtensionAdapter.ts
TypeScript
MethodDeclaration
public async validateExtension(): Promise<void> { if (!this.extension) { throw new Error(Constants.errorMessageStrings.ExtensionNotInstalled(this.extensionInfo.name)); } const version = this.extension.packageJSON.version; if (!semver.eq(version, this.extensionInfo.supportedVersion)) { throw new Error(Constants.informationMessage.unsupportedVersionOfExternalExtension( this.extensionInfo.name, version, this.extensionInfo.supportedVersion)); } if (!this.extension.isActive) { await this.extension.activate(); } }
MHMYunos2020/vscode-azure-blockchain-ethereum
src/services/extensionAdapter/OpenZeppelinExtensionAdapter.ts
TypeScript
MethodDeclaration
public async build(): Promise<void> { return commands.executeCommand(this.extensionInfo.commands.buildContracts); }
MHMYunos2020/vscode-azure-blockchain-ethereum
src/services/extensionAdapter/OpenZeppelinExtensionAdapter.ts
TypeScript
MethodDeclaration
public async deploy(): Promise<void> { return commands.executeCommand(this.extensionInfo.commands.deployContracts); }
MHMYunos2020/vscode-azure-blockchain-ethereum
src/services/extensionAdapter/OpenZeppelinExtensionAdapter.ts
TypeScript
FunctionDeclaration
export declare function maskSchema(schema: string): string;
Dazpel/redwoodjs
node_modules/@prisma/sdk/dist/utils/maskSchema.d.ts
TypeScript
FunctionDeclaration
export declare function mapScalarValues(obj: any, mapper: (value: any) => any): {};
Dazpel/redwoodjs
node_modules/@prisma/sdk/dist/utils/maskSchema.d.ts
TypeScript
ClassDeclaration
/** * Cloud Logging API * * Writes log entries and manages your Cloud Logging configuration. The table entries below are presented in alphabetical order, not in order of common use. For explanations of the concepts found in the table entries, read the documentation at https://cloud.google.com/logging/docs. * * @example * const {google} = require('googleapis'); * const logging = google.logging('v2'); * * @namespace logging * @type {Function} * @version v2 * @variation v2 * @param {object=} options Options for Logging */ export class Logging { context: APIRequestContext; billingAccounts: Resource$Billingaccounts; entries: Resource$Entries; exclusions: Resource$Exclusions; folders: Resource$Folders; locations: Resource$Locations; logs: Resource$Logs; monitoredResourceDescriptors: Resource$Monitoredresourcedescriptors; organizations: Resource$Organizations; projects: Resource$Projects; sinks: Resource$Sinks; v2: Resource$V2; constructor(options: GlobalOptions, google?: GoogleConfigurable); }
GumballWatterson00/DevCBatch1Project
node_modules/googleapis/build/src/apis/logging/v2.d.ts
TypeScript
ClassDeclaration
export class Resource$Billingaccounts { context: APIRequestContext; buckets: Resource$Billingaccounts$Buckets; exclusions: Resource$Billingaccounts$Exclusions; locations: Resource$Billingaccounts$Locations; logs: Resource$Billingaccounts$Logs; sinks: Resource$Billingaccounts$Sinks; constructor(context: APIRequestContext); }
GumballWatterson00/DevCBatch1Project
node_modules/googleapis/build/src/apis/logging/v2.d.ts
TypeScript
ClassDeclaration
export class Resource$Billingaccounts$Buckets { context: APIRequestContext; constructor(context: APIRequestContext); /** * logging.billingAccounts.buckets.get * @desc Gets a bucket (Beta). * @example * // Before running the sample: * // - Enable the API at: * // https://console.developers.google.com/apis/api/logging.googleapis.com * // - Login into gcloud by running: * // `$ gcloud auth application-default login` * // - Install the npm module by running: * // `$ npm install googleapis` * * const {google} = require('googleapis'); * const logging = google.logging('v2'); * * async function main() { * const auth = new google.auth.GoogleAuth({ * // Scopes can be specified either as an array or as a single, space-delimited string. * scopes: [ * 'https://www.googleapis.com/auth/cloud-platform', * 'https://www.googleapis.com/auth/cloud-platform.read-only', * 'https://www.googleapis.com/auth/logging.admin', * 'https://www.googleapis.com/auth/logging.read', * ], * }); * * // Acquire an auth client, and bind it to all future calls * const authClient = await auth.getClient(); * google.options('auth', authClient); * * // Do the magic * const res = await logging.billingAccounts.buckets.get({ * // Required. The resource name of the bucket: * // "projects/[PROJECT_ID]/locations/[LOCATION_ID]/buckets/[BUCKET_ID]" * // "organizations/[ORGANIZATION_ID]/locations/[LOCATION_ID]/buckets/[BUCKET_ID]" * // "billingAccounts/[BILLING_ACCOUNT_ID]/locations/[LOCATION_ID]/buckets/[BUCKET_ID]" * // "folders/[FOLDER_ID]/locations/[LOCATION_ID]/buckets/[BUCKET_ID]" * // Example: "projects/my-project-id/locations/my-location/buckets/my-bucket-id". * name: 'billingAccounts/my-billingAccount/buckets/my-bucket', * }); * console.log(res.data); * * // Example response * // { * // "createTime": "my_createTime", * // "description": "my_description", * // "lifecycleState": "my_lifecycleState", * // "name": "my_name", * // "retentionDays": 0, * // "updateTime": "my_updateTime" * // } * } * * main().catch(e => { * console.error(e); * throw e; * }); * * @alias logging.billingAccounts.buckets.get * @memberOf! () * * @param {object} params Parameters for request * @param {string} params.name Required. The resource name of the bucket: "projects/[PROJECT_ID]/locations/[LOCATION_ID]/buckets/[BUCKET_ID]" "organizations/[ORGANIZATION_ID]/locations/[LOCATION_ID]/buckets/[BUCKET_ID]" "billingAccounts/[BILLING_ACCOUNT_ID]/locations/[LOCATION_ID]/buckets/[BUCKET_ID]" "folders/[FOLDER_ID]/locations/[LOCATION_ID]/buckets/[BUCKET_ID]" Example: "projects/my-project-id/locations/my-location/buckets/my-bucket-id". * @param {object} [options] Optionally override request options, such as `url`, `method`, and `encoding`. * @param {callback} callback The callback that handles the response. * @return {object} Request object */ get(params: Params$Resource$Billingaccounts$Buckets$Get, options: StreamMethodOptions): GaxiosPromise<Readable>; get(params?: Params$Resource$Billingaccounts$Buckets$Get, options?: MethodOptions): GaxiosPromise<Schema$LogBucket>; get(params: Params$Resource$Billingaccounts$Buckets$Get, options: StreamMethodOptions | BodyResponseCallback<Readable>, callback: BodyResponseCallback<Readable>): void; get(params: Params$Resource$Billingaccounts$Buckets$Get, options: MethodOptions | BodyResponseCallback<Schema$LogBucket>, callback: BodyResponseCallback<Schema$LogBucket>): void; get(params: Params$Resource$Billingaccounts$Buckets$Get, callback: BodyResponseCallback<Schema$LogBucket>): void; get(callback: BodyResponseCallback<Schema$LogBucket>): void; }
GumballWatterson00/DevCBatch1Project
node_modules/googleapis/build/src/apis/logging/v2.d.ts
TypeScript
ClassDeclaration
export class Resource$Billingaccounts$Locations { context: APIRequestContext; buckets: Resource$Billingaccounts$Locations$Buckets; constructor(context: APIRequestContext); }
GumballWatterson00/DevCBatch1Project
node_modules/googleapis/build/src/apis/logging/v2.d.ts
TypeScript