repo_name
stringlengths
5
122
path
stringlengths
3
232
text
stringlengths
6
1.05M
financialforcedev/orizuru-auth
test/index/userInfo/userinfo.test.ts
<filename>test/index/userInfo/userinfo.test.ts<gh_stars>1-10 /* * Copyright (c) 2017-2019, FinancialForce.com, inc * All rights reserved. * * Redistribution and use in source and binary forms, with or without modification, * are permitted provided that the following conditions are met: * * - Redistributions of source code must retain the above copyright notice, * this list of conditions and the following disclaimer. * - Redistributions in binary form must reproduce the above copyright notice, * this list of conditions and the following disclaimer in the documentation * and/or other materials provided with the distribution. * - Neither the name of the FinancialForce.com, inc nor the names of its contributors * may be used to endorse or promote products derived from this software without * specific prior written permission. * * THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS" AND * ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED WARRANTIES * OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL * THE COPYRIGHT HOLDER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, * EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS * OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY * OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) * ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE. */ import chai from 'chai'; import chaiAsPromised from 'chai-as-promised'; import sinon from 'sinon'; import sinonChai from 'sinon-chai'; import { Environment, OpenIDTokenWithStandardClaims, UserInfoRequester } from '../../../src'; import * as cache from '../../../src/index/client/cache'; import { OAuth2Client } from '../../../src/index/client/oauth2'; import { OpenIdClient } from '../../../src/index/client/openid'; import { SalesforceClient } from '../../../src/index/client/salesforce'; import * as validator from '../../../src/index/client/validator/environment'; import { createUserInfoRequester } from '../../../src/index/userInfo/userinfo'; const expect = chai.expect; chai.use(chaiAsPromised); chai.use(sinonChai); describe('index/userInfo/userinfo', () => { let env: Environment; beforeEach(() => { env = { httpTimeout: 4001, issuerURI: 'https://login.salesforce.com/', type: 'OpenID' }; sinon.stub(validator, 'validate').returns(env); }); afterEach(() => { sinon.restore(); }); it('should return a function when called with the environment', () => { // Given // When const userInfoRequester = createUserInfoRequester(env); // Then expect(userInfoRequester).to.be.a('function'); expect(validator.validate).to.have.been.calledOnce; expect(validator.validate).to.have.been.calledWithExactly(env); }); describe('requestUserInfo', () => { let requestUserInfo: UserInfoRequester; beforeEach(() => { requestUserInfo = createUserInfoRequester(env); }); describe('should throw an error', () => { it('if the client cannot be created', async () => { // Given sinon.stub(cache, 'findOrCreateClient').rejects(new Error('Failed to create client.')); // When // Then await expect(requestUserInfo('ABCDE123')).to.be.rejectedWith('Failed to retrieve user information. Caused by: Failed to create client.'); }); it('if the client is not a OpenID client', async () => { // Given sinon.stub(cache, 'findOrCreateClient').resolves(new OAuth2Client(env)); // When // Then await expect(requestUserInfo('ABCDE123')).to.be.rejectedWith('Failed to retrieve user information. Caused by: This function must be used with a OpenID client.'); }); it('if the userinfo request fails', async () => { // Given const clientStubInstance = sinon.createStubInstance(OpenIdClient); sinon.stub(cache, 'findOrCreateClient').resolves(clientStubInstance); clientStubInstance.userinfo.throws(new Error('Bad_OAuth_Token.')); // When // Then await expect(requestUserInfo('ABCDE123')).to.be.rejectedWith('Failed to retrieve user information. Caused by: Bad_OAuth_Token.'); }); }); describe('should return the user info on success', () => { it('for an OpenID client', async () => { // Given const clientStubInstance = sinon.createStubInstance(OpenIdClient); sinon.stub(cache, 'findOrCreateClient').resolves(clientStubInstance); const partialUserInfo: Partial<OpenIDTokenWithStandardClaims> = { preferred_username: '<EMAIL>' }; clientStubInstance.userinfo.resolves(partialUserInfo as OpenIDTokenWithStandardClaims); // When const result = await requestUserInfo('ABCDE123'); // Then expect(result).to.eql({ preferred_username: '<EMAIL>' }); }); it('for a Salesforce client', async () => { // Given const clientStubInstance = sinon.createStubInstance(SalesforceClient); sinon.stub(cache, 'findOrCreateClient').resolves(clientStubInstance); const partialUserInfo: Partial<OpenIDTokenWithStandardClaims> = { preferred_username: 'user<EMAIL>' }; clientStubInstance.userinfo.resolves(partialUserInfo as OpenIDTokenWithStandardClaims); // When const result = await requestUserInfo('ABCDE123'); // Then expect(result).to.eql({ preferred_username: '<EMAIL>' }); }); }); }); });
financialforcedev/orizuru-auth
src/index/client/openid/identity.ts
<reponame>financialforcedev/orizuru-auth<gh_stars>1-10 /* * Copyright (c) 2019, FinancialForce.com, inc * All rights reserved. * * Redistribution and use in source and binary forms, with or without modification, * are permitted provided that the following conditions are met: * * - Redistributions of source code must retain the above copyright notice, * this list of conditions and the following disclaimer. * - Redistributions in binary form must reproduce the above copyright notice, * this list of conditions and the following disclaimer in the documentation * and/or other materials provided with the distribution. * - Neither the name of the FinancialForce.com, inc nor the names of its contributors * may be used to endorse or promote products derived from this software without * specific prior written permission. * * THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS" AND * ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED WARRANTIES * OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL * THE COPYRIGHT HOLDER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, * EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS * OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY * OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) * ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE. */ /** * @module client/openid/identity */ import { decode, verify } from 'jsonwebtoken'; import { AccessTokenResponse } from '../oauth2'; import { OpenIDAccessTokenResponse, OpenIDToken, OpenIDTokenWithStandardClaims } from '../openid'; import { JsonWebKeyPemFormatMap } from './jwk'; /** * Decode the `id_token` from an access token response. * * This does not verify the token. * * @param accessTokenResponse The access token response. */ export function decodeIdToken(accessTokenResponse: OpenIDAccessTokenResponse) { if (accessTokenResponse.id_token) { if (typeof accessTokenResponse.id_token === 'string') { accessTokenResponse.id_token = decode(accessTokenResponse.id_token) as OpenIDToken | OpenIDTokenWithStandardClaims; } } else if (accessTokenResponse.scope) { const scopes = accessTokenResponse.scope.split(' '); if (scopes.includes('openid')) { throw new Error('No id_token present'); } } else { throw new Error('No id_token present'); } } /** * Verify the `id_token` from an access token response. * * @param accessTokenResponse The access token response. * @param [jwkPemFormatMap] Map of the retrieved JSON Web Keys, keyed by the Key ID Parameter, in PEM format. */ export function verifyIdToken(accessTokenResponse: OpenIDAccessTokenResponse, jwkPemFormatMap?: JsonWebKeyPemFormatMap) { if (!jwkPemFormatMap) { throw new Error('Unable to verify ID token: No JWKs provided'); } if (accessTokenResponse.id_token) { if (typeof accessTokenResponse.id_token !== 'string') { throw new Error('Unable to verify ID token: id_token is not a string'); } const decodedIdToken = decode(accessTokenResponse.id_token, { complete: true }); if (!decodedIdToken || typeof decodedIdToken !== 'object') { throw new Error('Unable to verify ID token: decoded token is not an object'); } if (!decodedIdToken.header) { throw new Error('Unable to verify ID token: decoded token does not contain the header'); } if (!decodedIdToken.header.kid) { throw new Error('Unable to verify ID token: decoded token header does not contain the kid'); } const publicKey = jwkPemFormatMap[decodedIdToken.header.kid]; verify(accessTokenResponse.id_token, publicKey); } else if (accessTokenResponse.scope) { const scopes = accessTokenResponse.scope.split(' '); if (scopes.includes('openid')) { throw new Error('No id_token present'); } } else { throw new Error('No id_token present'); } } /** * Determines whether the id token is an OpenID token with standard claims. * * @param token The id token. * @returns A boolean indicating if this id token is an OpenID token with standard claims. */ export function isOpenIdTokenWithStandardClaims(token?: string | OpenIDToken | OpenIDTokenWithStandardClaims | null): token is OpenIDTokenWithStandardClaims { return (token as OpenIDTokenWithStandardClaims).email !== undefined; } /** * Determines whether the token is a Salesforce access token response. * * @param token The access token response. * @returns A boolean indicating if this token is a Salesforce access token response. */ export function isOpenIdAccessTokenResponse(token: AccessTokenResponse | OpenIDAccessTokenResponse): token is OpenIDAccessTokenResponse { return (token as OpenIDAccessTokenResponse).id_token !== undefined; }
financialforcedev/orizuru-auth
src/index/middleware/tokenIntrospection.ts
<reponame>financialforcedev/orizuru-auth<filename>src/index/middleware/tokenIntrospection.ts /* * Copyright (c) 2019, FinancialForce.com, inc * All rights reserved. * * Redistribution and use in source and binary forms, with or without modification, * are permitted provided that the following conditions are met: * * - Redistributions of source code must retain the above copyright notice, * this list of conditions and the following disclaimer. * - Redistributions in binary form must reproduce the above copyright notice, * this list of conditions and the following disclaimer in the documentation * and/or other materials provided with the distribution. * - Neither the name of the FinancialForce.com, inc nor the names of its contributors * may be used to endorse or promote products derived from this software without * specific prior written permission. * * THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS" AND * ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED WARRANTIES * OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL * THE COPYRIGHT HOLDER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, * EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS * OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY * OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) * ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE. */ /** * @module middleware/tokenIntrospection */ import { NextFunction, Request, RequestHandler, Response } from '@financialforcedev/orizuru'; import { EVENT_TOKEN_INTROSPECTED, EVENT_TOKEN_VALIDATED } from '../..'; import { IntrospectionOptions, IntrospectionParams, IntrospectionResponse } from '../client/oauth2'; import { isSalesforceIntrospectionResponse } from '../client/salesforce/identity'; import { createTokenIntrospector } from '../introspection/introspect'; import { DEFAULT_MIDDLEWARE_OPTIONS, extractAccessToken, MiddlewareOptions, setAccessTokenOnRequest } from './common/accessToken'; import { fail } from './common/fail'; /** * Returns an express middleware that introspects the OpenID Connect access token * passed in an HTTP Authorization header. * * If successful, the token information and the user object are set on the request object. * * @fires EVENT_TOKEN_INTROSPECTED, EVENT_DENIED * @param app The Orizuru server instance. * @param [provider] The name of the auth provider. Defaults to 'salesforce'. * @param [params] The token introspection middleware parameters. * @param [opts] The optional parameters used when introspecting tokens. * @returns An express middleware that introspects an access token. */ export function createMiddleware(app: Orizuru.IServer, provider?: string, params?: IntrospectionParams, opts?: MiddlewareOptions & IntrospectionOptions): RequestHandler { const internalProvider = provider || 'salesforce'; const internalParams = params || app.options.openid[internalProvider]; const { setTokenOnContext, ...grantOptions } = opts || DEFAULT_MIDDLEWARE_OPTIONS; const introspectAccessToken = createTokenIntrospector(app.options.authProvider[internalProvider]); return async function introspectToken(req: Request, res: Response, next: NextFunction) { try { const accessToken = extractAccessToken(req); const tokenInformation = await introspectAccessToken(accessToken, internalParams, grantOptions); setTokenInformationOnRequest(app, req, tokenInformation); setAccessTokenOnRequest(req, accessToken, setTokenOnContext); next(); } catch (error) { fail(app, error, req, res, next); } }; } /** * Sets the token information on the Orizuru context. * * It also sets the user on the request if the username is contained in the introspection * response. * * @fires EVENT_TOKEN_INTROSPECTED, EVENT_TOKEN_VALIDATED * @param app The Orizuru server instance. * @param req The HTTP request. * @param tokenInformation The token information to set on the request. */ function setTokenInformationOnRequest(app: Orizuru.IServer, req: Request, tokenInformation: IntrospectionResponse) { const orizuru = req.orizuru || {}; app.emit(EVENT_TOKEN_INTROSPECTED, `Token introspected for user (${tokenInformation.username || 'unknown'}) [${req.ip}].`); if (tokenInformation.username) { orizuru.user = { username: tokenInformation.username }; if (isSalesforceIntrospectionResponse(tokenInformation)) { orizuru.user.organizationId = tokenInformation.userInfo!.organizationId; } app.emit(EVENT_TOKEN_VALIDATED, `Token validated for user (${tokenInformation.username}) [${req.ip}].`); } orizuru.tokenInformation = tokenInformation; req.orizuru = orizuru; }
financialforcedev/orizuru-auth
src/index/client/openid.ts
<filename>src/index/client/openid.ts /* * Copyright (c) 2019, FinancialForce.com, inc * All rights reserved. * * Redistribution and use in source and binary forms, with or without modification, * are permitted provided that the following conditions are met: * * - Redistributions of source code must retain the above copyright notice, * this list of conditions and the following disclaimer. * - Redistributions in binary form must reproduce the above copyright notice, * this list of conditions and the following disclaimer in the documentation * and/or other materials provided with the distribution. * - Neither the name of the FinancialForce.com, inc nor the names of its contributors * may be used to endorse or promote products derived from this software without * specific prior written permission. * * THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS" AND * ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED WARRANTIES * OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL * THE COPYRIGHT HOLDER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, * EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS * OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY * OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) * ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE. */ /** * @module client/openid */ import axios from 'axios'; import { Environment } from './cache'; import { AccessTokenResponse, GrantParams, OAuth2Client, ResponseFormat } from './oauth2'; import { JWT, JwtGrantOptions, OAuth2JWTClient } from './oauth2Jwt'; import { decodeIdToken, verifyIdToken } from './openid/identity'; import { JsonWebKeyPemFormatMap, retrieveJsonWebKeysInPemFormat } from './openid/jwk'; const DEFAULT_USERINFO_OPTIONS = Object.freeze({ responseFormat: 'application/json' }); export interface OpenIDAccessTokenResponse extends AccessTokenResponse { /** * An [OpenID Token](https://openid.net/specs/openid-connect-core-1_0.html#IDToken) that contains claims about the authentication of an end-user by an * authorization server. */ id_token?: null | string | OpenIDToken | OpenIDTokenWithStandardClaims; } /** * Optional parameters used when requesting grants. */ export interface OpenIdGrantOptions extends JwtGrantOptions { /** * If true, the JWT present in the id_token field of the access token response is parsed. */ decodeIdToken?: boolean; /** * If true, verify the ID token with the retrieved JWKs. */ verifyIdToken?: boolean; } /** * A token that conforms to the [OpenID specification](https://openid.net/specs/openid-connect-core-1_0.html#IDToken). * * It is returned in the `id_token` field of the `AccessTokenResponse`. */ export interface OpenIDToken extends JWT { /** * Authentication Context Class Reference Claim. */ acr?: string; /** * Authentication Methods References Claim. */ amr?: string; /** * Access Token Hash Value Claim. */ at_hash?: string; /** * User Authentication Time Claim; */ auth_time?: string; /** * Authorized Party Claim. */ azp?: string; /** * @inheritdoc */ iat: number; /** * String value used to associate a Client session with an ID Token, and to mitigate replay attacks claim. */ nonce?: string; } /** * [Address claim](https://openid.net/specs/openid-connect-core-1_0.html#AddressClaim) */ export interface OpenIdTokenAddress { /** * Full mailing address, */ formatted?: string; /** * Full street address. */ street_address?: string; /** * City or locality component. */ locality?: string; /** * State, province, prefecture, or region component. */ region?: string; /** * Zip code or postal code component. */ postal_code?: string; /** * Country name component. */ country?: string; } /** * Standard set of claims returned in a userinfo request. * * The standard claims conform to the [OpenID specification](https://openid.net/specs/openid-connect-core-1_0.html#StandardClaims). */ export interface OpenIDTokenWithStandardClaims extends OpenIDToken { /** * End-User's preferred address. * * The value of the address member is a JSON [RFC4627] structure containing some or * all of the members defined [here](https://openid.net/specs/openid-connect-core-1_0.html#AddressClaim). */ address?: OpenIdTokenAddress; /** * End-User's birthday, represented as an ISO 8601:2004 [ISO8601‑2004] YYYY-MM-DD format. * The year MAY be 0000, indicating that it is omitted. * To represent only the year, YYYY format is allowed. */ birthdate?: string; /** * End-User's preferred e-mail address. * * Its value MUST conform to the RFC 5322 [RFC5322] addr-spec syntax. * This value MUST NOT be relied upon to be unique by the RP, as discussed in Section 2.5.3. */ email: string; /** * True if the End-User's e-mail address has been verified; otherwise false. * When this Claim Value is true, this means that the OP took affirmative steps to ensure that * this e-mail address was controlled by the End-User at the time the verification was performed. * The means by which an e-mail address is verified is context-specific, and dependent upon the * trust framework or contractual agreements within which the parties are operating. */ email_verified: boolean; /** * Surname(s) or last name(s) of the End-User. */ family_name: string; /** * End-User's gender. */ gender?: string; /** * Given name(s) or first name(s) of the End-User. */ given_name: string; /** * End-User's locale, represented as a BCP47 [RFC5646] language tag. */ locale: string; /** * Middle name(s) of the End-User. */ middle_name?: string; /** * End-User's full name in displayable form including all name parts, possibly including * titles and suffixes, ordered according to the End-User's locale and preferences. */ name: string; /** * Casual name of the End-User that may or may not be the same as the given_name. * For instance, a nickname value of Mike might be returned alongside a given_name value of Michael. */ nickname: string; /** * End-User's preferred telephone number. * * E.164 [E.164] is recommended as the format of this Claim, for example, +1 (425) 555-1212 or +56 (2) 687 2400. * If the phone number contains an extension, it is recommended that the extension be represented using * the RFC 3966 [RFC3966] extension syntax, for example, +1 (604) 555-1234;ext=5678. */ phone_number: string | null; /** * True if the End-User's phone number has been verified; otherwise false. * * When this Claim Value is true, this means that the OP took affirmative steps to ensure that this phone number * was controlled by the End-User at the time the verification was performed. * The means by which a phone number is verified is context-specific, and dependent upon the trust framework or * contractual agreements within which the parties are operating. When true, the phone_number * Claim MUST be in E.164 format and any extensions MUST be represented in RFC 3966 format. */ phone_number_verified?: boolean; /** * URL of the End-User's profile picture. * * This URL MUST refer to an image file (for example, a PNG, JPEG, or GIF image file), * rather than to a Web page containing an image. Note that this URL should specifically * reference a profile photo of the End-User suitable for displaying when describing * the End-User, rather than an arbitrary photo taken by the End-User. */ picture: string; /** * Shorthand name that the End-User wishes to be referred to at the RP, such as janedoe or j.doe. * This value MAY be any valid JSON string including special characters such as @, /, or whitespace. * This value MUST NOT be relied upon to be unique by the RP. */ preferred_username: string; /** * URL of the End-User's profile page. * * The contents of this Web page should be about the End-User. */ profile: string; /** * Time the End-User's information was last updated. * * The time is represented as the number of seconds from 1970-01-01T0:0:0Z as measured in UTC until the date/time. */ updated_at: number; /** * URL of the End-User's Web page or blog. * * This Web page should contain information published by the End-User or an organization that the End-User is affiliated with. */ website?: string; /** * String from zoneinfo [zoneinfo] time zone database representing the End-User's time zone. * For example, Europe/Paris or America/Los_Angeles. */ zoneinfo: string; } /** * Optional parameters used when requesting user information. */ export interface UserInfoOptions { /** * Returns the response format, either JSON, XML or URL_ENCODED. */ responseFormat?: ResponseFormat; } /** * An OpenID client that implements the [OpenID Connect Specification](https://openid.net/specs/openid-connect-core-1_0.html). */ export class OpenIdClient extends OAuth2JWTClient { /** * [JSON Web Key Set Document](https://openid.net/specs/openid-connect-discovery-1_0.html#ProviderMetadata) */ private jwksEndpoint?: string; /** * [UserInfo endpoint](https://openid.net/specs/openid-connect-core-1_0.html#UserInfo) */ private userinfoEndpoint?: string; /** * Map of the retrieved JSON Web Keys, keyed by the Key ID Parameter, in PEM format. */ private jwkPemFormatMap?: JsonWebKeyPemFormatMap; /** * Creates a new OpenID client with the given environment. * * @param env The OAuth2 environment parameters. */ constructor(env: Environment) { super(env); this.clientType = 'OpenID'; } /** * Initalize the OpenIdClient by requesting the [OpenID provider configuration information](https://openid.net/specs/openid-connect-discovery-1_0.html#ProviderConfig) * for the issuer provided in the environment. */ public async init() { const config = Object.assign({}, OAuth2Client.DEFAULT_REQUEST_CONFIG, { timeout: this.env.httpTimeout }); const uri = `${this.env.issuerURI.replace(/\/$/, '')}/.well-known/openid-configuration`; const response = await axios.get(uri, config); if (response.status !== 200) { throw new Error(`Failed to initialise ${this.clientType} client. OpenID configuration request failed.`); } const data = response.data; this.authorizationEndpoint = data.authorization_endpoint; this.introspectionEndpoint = data.introspection_endpoint || null; this.jwksEndpoint = data.jwks_uri; this.revocationEndpoint = data.revocation_endpoint; this.tokenEndpoint = data.token_endpoint; this.userinfoEndpoint = data.userinfo_endpoint; if (this.jwksEndpoint) { this.jwkPemFormatMap = await retrieveJsonWebKeysInPemFormat(this.jwksEndpoint, config); } } /** * @inheritdoc * @returns The OpenID Access Token Response. */ public async grant(params: GrantParams, opts?: OpenIdGrantOptions): Promise<OpenIDAccessTokenResponse> { return super.grant(params as GrantParams, opts); } /** * Retrieve the user information using the provided token. * * @param token The token to be used. * @param [opts] The user info options to be used. */ public async userinfo(token: string, opts?: UserInfoOptions): Promise<OpenIDTokenWithStandardClaims> { if (!this.userinfoEndpoint) { throw new Error(`${this.clientType} client has not been initialized`); } const internalOpts = Object.assign({}, DEFAULT_USERINFO_OPTIONS, opts); const config = Object.assign({}, OAuth2Client.DEFAULT_REQUEST_CONFIG, { headers: { Accept: internalOpts.responseFormat, Authorization: `Bearer ${token}` } }); const response = await axios.get(this.userinfoEndpoint, config); if (response.status !== 200) { throw new Error(`Failed to obtain user information: ${response.data}.`); } return response.data; } /** * @inheritdoc */ protected handleAccessTokenResponse(accessTokenResponse: AccessTokenResponse, internalOpts: OpenIdGrantOptions) { try { if (internalOpts.verifyIdToken) { verifyIdToken(accessTokenResponse, this.jwkPemFormatMap); } if (internalOpts.decodeIdToken) { decodeIdToken(accessTokenResponse); } } catch (error) { throw new Error(`Failed to obtain grant: ${error.message}.`); } return accessTokenResponse as OpenIDAccessTokenResponse; } }
financialforcedev/orizuru-auth
systemtests/server/common.ts
/* * Copyright (c) 2019, FinancialForce.com, inc * All rights reserved. * * Redistribution and use in source and binary forms, with or without modification, * are permitted provided that the following conditions are met: * * - Redistributions of source code must retain the above copyright notice, * this list of conditions and the following disclaimer. * - Redistributions in binary form must reproduce the above copyright notice, * this list of conditions and the following disclaimer in the documentation * and/or other materials provided with the distribution. * - Neither the name of the FinancialForce.com, inc nor the names of its contributors * may be used to endorse or promote products derived from this software without * specific prior written permission. * * THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS" AND * ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED WARRANTIES * OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL * THE COPYRIGHT HOLDER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, * EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS * OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY * OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) * ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE. */ import config from 'config'; import debug, { Debugger } from 'debug'; import pem, { CertificateCreationResult } from 'pem'; import { SuperAgentRequest } from 'superagent'; import http from 'http'; import https from 'https'; import { ITransport, Server } from '@financialforcedev/orizuru'; import { Environment, EVENT_AUTHORIZATION_HEADER_SET, EVENT_DENIED, EVENT_GRANT_CHECKED, EVENT_TOKEN_INTROSPECTED, EVENT_TOKEN_VALIDATED, OpenIdOptions } from '../../src'; export interface TrustedSuperAgentRequest extends SuperAgentRequest { trustLocalhost: (toggle: boolean) => TrustedSuperAgentRequest; } export class TestServer extends Server { public httpsServer?: https.Server; private readonly setupDebugInstance: Debugger; constructor(providers: string[]) { const authProvider = providers.reduce((results, provider) => { results[provider] = config.get<Environment>(`authProvider.${provider}`); return results; }, {} as { [index: string]: Environment }); const openid = providers.reduce((results, provider) => { results[provider] = config.get(`openid.${provider}`); return results; }, {} as { [index: string]: OpenIdOptions }); super({ authProvider, openid, port: 8080, transport: new Transport() }); this.setupDebugInstance = debug('app:setup'); const testdebugInstance = debug('app:test'); // Add the listeners const setupEvents = [Server.ERROR, Server.INFO]; setupEvents.map((event) => { this.on(event, (args) => { this.setupDebugInstance(args); }); }); const events = [EVENT_AUTHORIZATION_HEADER_SET, EVENT_DENIED, EVENT_GRANT_CHECKED, EVENT_TOKEN_INTROSPECTED, EVENT_TOKEN_VALIDATED]; events.map((event) => { this.on(event, (args) => { testdebugInstance(args); }); }); } public async listen() { const certificate = await createCertificate(); this.setupDebugInstance('Created certificate.'); const serverOptions: https.ServerOptions = { cert: certificate.certificate, key: certificate.clientKey }; this.httpsServer = https.createServer(serverOptions, this.serverImpl); this.httpsServer.listen(this.options.port); this.setupDebugInstance(`Server listening to connections on port: ${this.options.port}.`); return Promise.resolve(this.httpsServer as unknown as http.Server); } public async close() { if (this.httpsServer) { this.httpsServer.close(); } } } /** * Create a dummy transport implementation */ class Transport implements ITransport { public async close() { // Do nothing } public async connect() { // Do nothing } public async publish(buffer: Buffer, options: Orizuru.Transport.IPublish) { return true; } public async subscribe() { // Do nothing } } function createCertificate(): Promise<CertificateCreationResult> { return new Promise((resolve, reject) => { pem.createCertificate({ commonName: 'localhost', days: 1, selfSigned: true }, (err, result) => { if (err) { return reject(err); } return resolve(result); }); }); }
financialforcedev/orizuru-auth
test/index/middleware/common/fail.test.ts
<reponame>financialforcedev/orizuru-auth /* * Copyright (c) 2019, FinancialForce.com, inc * All rights reserved. * * Redistribution and use in source and binary forms, with or without modification, * are permitted provided that the following conditions are met: * * - Redistributions of source code must retain the above copyright notice, * this list of conditions and the following disclaimer. * - Redistributions in binary form must reproduce the above copyright notice, * this list of conditions and the following disclaimer in the documentation * and/or other materials provided with the distribution. * - Neither the name of the FinancialForce.com, inc nor the names of its contributors * may be used to endorse or promote products derived from this software without * specific prior written permission. * * THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS" AND * ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED WARRANTIES * OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL * THE COPYRIGHT HOLDER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, * EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS * OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY * OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) * ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE. */ import chai from 'chai'; import sinon from 'sinon'; import sinonChai from 'sinon-chai'; import { NextFunction, Request, Response } from '@financialforcedev/orizuru'; import { EVENT_DENIED } from '../../../../src'; import { fail } from '../../../../src/index/middleware/common/fail'; const expect = chai.expect; const has = sinon.match.has; chai.use(sinonChai); describe('index/middleware/common/fail', () => { let app: Orizuru.IServer; let req: Request; let res: Response; let next: NextFunction; beforeEach(() => { const partialRequest: Partial<Request> = { ip: '1.1.1.1' }; req = partialRequest as Request; const partialResponse: Partial<Response> = {}; res = partialResponse as Response; const partialApp: Partial<Orizuru.IServer> = { emit: sinon.stub() }; app = partialApp as Orizuru.IServer; next = sinon.stub(); }); afterEach(() => { expect(next).to.have.been.calledOnce; sinon.restore(); }); it('should emit a denied event with the error when no ip is present ', () => { // Given delete req.ip; // When fail(app, new Error('test'), req, res, next); // Then expect(app.emit).to.have.been.calledOnce; expect(app.emit).to.have.been.calledWithExactly(EVENT_DENIED, 'Access denied to: unknown. Error: test'); expect(next).to.have.been.calledWithExactly(has('message', 'Access denied to: unknown. Error: test')); }); it('should emit a denied event with the error', () => { // Given // When fail(app, new Error('test'), req, res, next); // Then expect(app.emit).to.have.been.calledOnce; expect(app.emit).to.have.been.calledWithExactly(EVENT_DENIED, 'Access denied to: 1.1.1.1. Error: test'); expect(next).to.have.been.calledWithExactly(has('message', 'Access denied to: 1.1.1.1. Error: test')); }); });
financialforcedev/orizuru-auth
test/index/client/openid/identity.test.ts
/* * Copyright (c) 2019, FinancialForce.com, inc * All rights reserved. * * Redistribution and use in source and binary forms, with or without modification, * are permitted provided that the following conditions are met: * * - Redistributions of source code must retain the above copyright notice, * this list of conditions and the following disclaimer. * - Redistributions in binary form must reproduce the above copyright notice, * this list of conditions and the following disclaimer in the documentation * and/or other materials provided with the distribution. * - Neither the name of the FinancialForce.com, inc nor the names of its contributors * may be used to endorse or promote products derived from this software without * specific prior written permission. * * THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS" AND * ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED WARRANTIES * OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL * THE COPYRIGHT HOLDER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, * EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS * OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY * OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) * ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE. */ import chai from 'chai'; import sinon from 'sinon'; import sinonChai from 'sinon-chai'; import crypto from 'crypto'; import jwt from 'jsonwebtoken'; import { OpenIDAccessTokenResponse, OpenIDToken } from '../../../../src'; import { decodeIdToken, verifyIdToken } from '../../../../src/index/client/openid/identity'; const expect = chai.expect; chai.use(sinonChai); describe('index/client/openid/identity', () => { let accessTokenResponse: OpenIDAccessTokenResponse; let keyPair: crypto.KeyPairSyncResult<string, string>; beforeEach(() => { keyPair = crypto.generateKeyPairSync('rsa', { modulusLength: 2048, privateKeyEncoding: { format: 'pem', type: 'pkcs8' }, publicKeyEncoding: { format: 'pem', type: 'spki' } }); const idToken = jwt.sign({ aud: 'audience', iat: 1516239022, iss: 'issuer', name: '<NAME>' }, keyPair.privateKey, { algorithm: 'RS256', keyid: '200' }); accessTokenResponse = { access_token: '<KEY>', id_token: idToken, scope: 'web openid api id', token_type: 'Bearer' }; sinon.stub(Date, 'now').returns(1551521526000); }); afterEach(() => { sinon.restore(); }); describe('decodeIdToken', () => { describe('should throw an error', () => { it('if the id_token is not present when validated and openid is present in the scopes', () => { // Given delete accessTokenResponse.id_token; // When // Then expect(() => decodeIdToken(accessTokenResponse)).to.throw('No id_token present'); }); it('if the id_token and scope are not present when validated', () => { // Given delete accessTokenResponse.id_token; delete accessTokenResponse.scope; // When // Then expect(() => decodeIdToken(accessTokenResponse)).to.throw('No id_token present'); }); }); describe('should not throw an error', () => { it('if the id_token is not present and openid is not present in the scopes', () => { // Given delete accessTokenResponse.id_token; accessTokenResponse.scope = 'api'; // When decodeIdToken(accessTokenResponse); // Then expect(accessTokenResponse).to.eql({ access_token: '<KEY>', scope: 'api', token_type: 'Bearer' }); }); it('if the id_token has already been decoded', () => { // Given accessTokenResponse.id_token = { aud: 'audience', iat: 1516239022, iss: 'issuer', name: '<NAME>' } as OpenIDToken; accessTokenResponse.scope = 'api'; // When decodeIdToken(accessTokenResponse); // Then expect(accessTokenResponse).to.eql({ access_token: '<KEY>', id_token: { aud: 'audience', iat: 1516239022, iss: 'issuer', name: '<NAME>' }, scope: 'api', token_type: 'Bearer' }); }); }); it('should decode the JWT from the id_token field', () => { // Given // When decodeIdToken(accessTokenResponse); // Then expect(accessTokenResponse).to.eql({ access_token: '<KEY>', id_token: { aud: 'audience', iat: 1516239022, iss: 'issuer', name: '<NAME>' }, scope: 'web openid api id', token_type: 'Bearer' }); }); }); describe('verifyIdToken', () => { describe('should throw an error', () => { it('if the jwkPemFormatMap is not provided', () => { // Given delete accessTokenResponse.id_token; // When // Then expect(() => verifyIdToken(accessTokenResponse)).to.throw('Unable to verify ID token: No JWKs provided'); }); it('if the id_token is not present when validated and openid is present in the scopes', () => { // Given delete accessTokenResponse.id_token; // When // Then expect(() => verifyIdToken(accessTokenResponse, {})).to.throw('No id_token present'); }); it('if the id_token and scope are not present when validated', () => { // Given delete accessTokenResponse.id_token; delete accessTokenResponse.scope; // When // Then expect(() => verifyIdToken(accessTokenResponse, {})).to.throw('No id_token present'); }); it('if the id_token is not a string', () => { // Given Object.assign(accessTokenResponse, { id_token: {} }); // When // Then expect(() => verifyIdToken(accessTokenResponse, {})).to.throw('Unable to verify ID token: id_token is not a string'); }); it('if the decodedIdToken is not an object', () => { // Given sinon.stub(jwt, 'decode').returns('invalid token'); // When // Then expect(() => verifyIdToken(accessTokenResponse, {})).to.throw('Unable to verify ID token: decoded token is not an object'); }); it('if the decodedIdToken does not contain the header', () => { // Given sinon.stub(jwt, 'decode').returns({ payload: {} }); // When // Then expect(() => verifyIdToken(accessTokenResponse, {})).to.throw('Unable to verify ID token: decoded token does not contain the header'); }); it('if the decodedIdToken does not contain the kid in the header', () => { // Given sinon.stub(jwt, 'decode').returns({ header: {}, payload: {} }); // When // Then expect(() => verifyIdToken(accessTokenResponse, {})).to.throw('Unable to verify ID token: decoded token header does not contain the kid'); }); }); describe('should not throw an error', () => { it('if the id_token is not present and openid is not present in the scopes', () => { // Given delete accessTokenResponse.id_token; accessTokenResponse.scope = 'api'; // When verifyIdToken(accessTokenResponse, {}); // Then expect(accessTokenResponse).to.eql({ access_token: '00Dxx0000<PASSWORD>PL!AR8AQJXg5oj8jXSgxJfA0lBog.39AsX.LVpxezPwuX5VAIrrbbHMuol7GQxnMeYMN7cj8EoWr78nt1u44zU31IbYNNJguseu', scope: 'api', token_type: 'Bearer' }); }); }); it('should verify the JWT from the id_token field', () => { // Given // When // Then expect(verifyIdToken(accessTokenResponse, { 200: keyPair.publicKey })).to.not.throw; }); }); });
financialforcedev/orizuru-auth
src/index/middleware/authCallback.ts
<gh_stars>1-10 /* * Copyright (c) 2019, FinancialForce.com, inc * All rights reserved. * * Redistribution and use in source and binary forms, with or without modification, * are permitted provided that the following conditions are met: * * - Redistributions of source code must retain the above copyright notice, * this list of conditions and the following disclaimer. * - Redistributions in binary form must reproduce the above copyright notice, * this list of conditions and the following disclaimer in the documentation * and/or other materials provided with the distribution. * - Neither the name of the FinancialForce.com, inc nor the names of its contributors * may be used to endorse or promote products derived from this software without * specific prior written permission. * * THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS" AND * ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED WARRANTIES * OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL * THE COPYRIGHT HOLDER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, * EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS * OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY * OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) * ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE. */ /** * @module middleware/authCallback */ import { NextFunction, Request, RequestHandler, Response } from '@financialforcedev/orizuru'; import { AccessTokenResponse, AuthCodeGrantParams, EVENT_AUTHORIZATION_HEADER_SET, GrantOptions, TokenGrantorParams } from '../..'; import { isOpenIdAccessTokenResponse, isOpenIdTokenWithStandardClaims } from '../client/openid/identity'; import { isSalesforceAccessTokenResponse } from '../client/salesforce/identity'; import { createTokenGrantor } from '../flow/webServer'; import { DEFAULT_MIDDLEWARE_OPTIONS, MiddlewareOptions, setAccessTokenOnRequest } from './common/accessToken'; import { fail } from './common/fail'; /** * Returns an express middleware that [exchanges a verification code for an access token](https://help.salesforce.com/articleView?id=remoteaccess_oauth_web_server_flow.htm#vc_for_at). * * This can be used in tandem with the tokenValidator to set the user on the request. * * @fires EVENT_AUTHORIZATION_HEADER_SET * @param app The Orizuru server instance. * @param [provider] The name of the auth provider. Defaults to 'salesforce'. * @param [params] The auth callback middleware parameters. * @param [opts] The optional parameters used when requesting grants. * @returns An express middleware that exchanges a verification code for an access * token. */ export function createMiddleware(app: Orizuru.IServer, provider?: string, params?: TokenGrantorParams, opts?: MiddlewareOptions & GrantOptions): RequestHandler { const internalProvider = provider || 'salesforce'; const internalParams = params || app.options.openid[internalProvider]; const { setTokenOnContext, ...grantOptions } = opts || DEFAULT_MIDDLEWARE_OPTIONS; const requestAccessToken = createTokenGrantor(app.options.authProvider[internalProvider]); // The AuthCallbackMiddlewareParameters interface excludes the grant_type // so that it doesn't have to be set by the caller. Make sure it is set here. const authParams: Partial<AuthCodeGrantParams> = Object.assign({}, internalParams); authParams.grantType = 'authorization_code'; return async function checkUserGrant(req: Request, res: Response, next: NextFunction) { try { validateRequest(req); const tokenResponse = await requestAccessToken(Object.assign({}, authParams, { code: req.query.code }) as AuthCodeGrantParams, grantOptions); setAuthorizationHeaderAndIdentity(app, req, tokenResponse); setAccessTokenOnRequest(req, tokenResponse.access_token, setTokenOnContext); next(); } catch (error) { fail(app, error, req, res, next); } }; } /** * Validates the request contains the verification code. * * @param req The HTTP request. */ function validateRequest(req: Request) { if (!req.query) { throw new Error('Missing required object parameter: query'); } if (req.query.error) { throw new Error(req.query.error); } if (!req.query.code) { throw new Error('Missing required string parameter: query[code]'); } } /** * Sets the authorization header with the access_token from the response and emits * an authorization header set event. * * If present, it also sets the user information in the Orizuru context identity property. * * @fires EVENT_AUTHORIZATION_HEADER_SET * @param app The Orizuru server instance. * @param req The HTTP request. * @param token The access token response. */ function setAuthorizationHeaderAndIdentity(app: Orizuru.IServer, req: Request, token: AccessTokenResponse) { req.headers.authorization = `${token.token_type} ${token.access_token}`; let user = 'unknown'; if (isSalesforceAccessTokenResponse(token)) { if (token.userInfo) { const orizuru = req.orizuru || {}; orizuru.salesforce = orizuru.salesforce || {}; orizuru.salesforce.instanceUrl = token.instance_url; orizuru.salesforce.userInfo = token.userInfo; req.orizuru = orizuru; user = token.userInfo.id || user; } } if (isOpenIdAccessTokenResponse(token)) { if (isOpenIdTokenWithStandardClaims(token.id_token)) { user = token.id_token.email; } } app.emit(EVENT_AUTHORIZATION_HEADER_SET, `Authorization headers set for user (${user}) [${req.ip}].`); }
ljoboy/nestjs-backend
src/phones/phones.service.ts
import { Injectable } from '@nestjs/common'; import {TypeOrmCrudService} from "@nestjsx/crud-typeorm"; import {Phones} from "./entities/Phones"; import {InjectRepository} from "@nestjs/typeorm"; import {PhonesReposity} from "./phones.reposity"; @Injectable() export class PhonesService extends TypeOrmCrudService<Phones>{ constructor(@InjectRepository(PhonesReposity) repo) { super(repo); } }
ljoboy/nestjs-backend
src/emails/emails.repository.ts
<filename>src/emails/emails.repository.ts<gh_stars>0 import {EntityRepository, Repository} from "typeorm"; import {Emails} from "./entities/Emails"; @EntityRepository(Emails) export class EmailsRepository extends Repository<Emails>{ }
ljoboy/nestjs-backend
src/websites/websites.service.ts
<filename>src/websites/websites.service.ts import { Injectable } from '@nestjs/common'; import {TypeOrmCrudService} from "@nestjsx/crud-typeorm"; import {Websites} from "./entities/Websites"; import {InjectRepository} from "@nestjs/typeorm"; @Injectable() export class WebsitesService extends TypeOrmCrudService<Websites>{ constructor(@InjectRepository(Websites) repo) { super(repo); } }
ljoboy/nestjs-backend
src/auth/dtos/register-credentials.dto.ts
import {GenreEnum} from "../genre.enum"; import {IsEmail, IsEnum, IsNotEmpty, IsOptional, IsString, MaxLength, MinLength} from "class-validator"; export class RegisterCredentialsDto { @IsOptional() @IsString() full_name: string; @IsOptional() @IsEmail() email: string; @IsOptional() @IsString() address: string; @IsOptional() @IsString() ville: string; @IsOptional() @IsString() country: string; @IsOptional() @IsString() @IsEnum(GenreEnum) genre: GenreEnum; @IsNotEmpty() @IsString() @MinLength(3) @MaxLength(20) username: string; @IsNotEmpty() @IsString() @MinLength(6) @MaxLength(40) password: string; }
ljoboy/nestjs-backend
src/auth/auth.controller.ts
<reponame>ljoboy/nestjs-backend<gh_stars>0 import {Body, Controller, Post, ValidationPipe} from '@nestjs/common'; import {LoginCredentialsDto} from "./dtos/login-credentials.dto"; import {AuthService} from "./auth.service"; import {RegisterCredentialsDto} from "./dtos/register-credentials.dto"; @Controller('auth') export class AuthController { constructor(private authService: AuthService) { } @Post('/signup') signUp(@Body(ValidationPipe) registerCredentialsDto: RegisterCredentialsDto) { return this.authService.signUp(registerCredentialsDto); } @Post('/signin') signIn(@Body(ValidationPipe) authCredentialsDto: LoginCredentialsDto): Promise<{ accessToken: string }> { return this.authService.signIn(authCredentialsDto); } }
ljoboy/nestjs-backend
src/websites/entities/Websites.ts
<reponame>ljoboy/nestjs-backend<gh_stars>0 import { BaseEntity, Column, Entity, JoinColumn, ManyToOne, PrimaryGeneratedColumn } from "typeorm"; import { Contacts } from "../../contacts/entities/Contacts"; @Entity("websites") export class Websites extends BaseEntity { @PrimaryGeneratedColumn({ type: "integer", name: "id" }) id: number; @Column("text", { name: "site" }) site: string; @Column("text", { name: "type" }) type: string; @ManyToOne( () => Contacts, contacts => contacts.websites, { onDelete: "CASCADE", onUpdate: "CASCADE" } ) @JoinColumn([{ name: "idContact", referencedColumnName: "id" }]) idContact: Contacts; }
ljoboy/nestjs-backend
src/contacts/contacts.service.ts
<filename>src/contacts/contacts.service.ts import { Injectable } from '@nestjs/common'; import { InjectRepository } from "@nestjs/typeorm"; import { TypeOrmCrudService } from "@nestjsx/crud-typeorm"; import {ContactsRepository} from "./contacts.repository"; import {Contacts} from "./entities/Contacts"; @Injectable() export class ContactsService extends TypeOrmCrudService<Contacts>{ constructor(@InjectRepository(ContactsRepository) repo) { super(repo); } }
ljoboy/nestjs-backend
src/auth/get-user.decorator.ts
<filename>src/auth/get-user.decorator.ts<gh_stars>0 import {createParamDecorator} from "@nestjs/common"; import {Users} from "./entities/Users"; const GetUser = createParamDecorator((data, req) : Users => { return req.user; });
ljoboy/nestjs-backend
src/websites/websites.module.ts
import { Module } from '@nestjs/common'; import { WebsitesService } from './websites.service'; import { WebsitesController } from './websites.controller'; import {TypeOrmModule} from "@nestjs/typeorm"; import {Websites} from "./entities/Websites"; import {AuthModule} from "../auth/auth.module"; @Module({ providers: [WebsitesService], controllers: [WebsitesController], imports: [ TypeOrmModule.forFeature([Websites]), AuthModule, ], exports: [WebsitesService] }) export class WebsitesModule {}
ljoboy/nestjs-backend
src/auth/users.repository.ts
import {EntityRepository, Repository} from "typeorm"; import {Users} from "./entities/Users"; import {LoginCredentialsDto} from "./dtos/login-credentials.dto"; import {ConflictException, InternalServerErrorException} from "@nestjs/common"; import * as bcrypt from "bcrypt"; import {RegisterCredentialsDto} from "./dtos/register-credentials.dto"; @EntityRepository(Users) export class UsersRepository extends Repository<Users> { async signUp(registerCredentialsDto: RegisterCredentialsDto): Promise<void> { const {username, password, address, country, email, full_name, genre, ville} = registerCredentialsDto; const user = new Users(); user.username = username; user.salt = await bcrypt.genSalt(); user.password = await this.hashPassword(password, user.salt); user.address = address; user.country = country; user.email = email; user.full_name = full_name; user.genre = genre; user.ville = ville; try { await user.save(); } catch (error) { if (error.code === 'SQLITE_CONSTRAINT') throw new ConflictException('Username already taken'); else throw new InternalServerErrorException(); } } async validateUserPassword(authCredentialsDto: LoginCredentialsDto): Promise<string> { const {username, password} = authCredentialsDto; const user = await this.findOne({username}); if (user && await user.validatePassword(password)) return user.username; else return null; } private async hashPassword(password: string, salt: string): Promise<string> { return bcrypt.hash(password, salt); } }
ljoboy/nestjs-backend
src/auth/jwt.strategy.ts
import {PassportStrategy} from "@nestjs/passport"; import {ExtractJwt, Strategy} from "passport-jwt"; import {Injectable, UnauthorizedException} from "@nestjs/common"; import {JwtPayload} from "./jwt-payload.interface"; import {InjectRepository} from "@nestjs/typeorm"; import {UsersRepository} from "./users.repository"; import {Users} from "./entities/Users"; @Injectable() export class JwtStrategy extends PassportStrategy(Strategy){ constructor( @InjectRepository(UsersRepository) private usersRepository, ) { super({ jwtFromRequest: ExtractJwt.fromAuthHeaderAsBearerToken(), secretOrKey: 'AllegrA1322', }); } async validate(payload: JwtPayload): Promise<Users> { const { username } = payload; const user = await this.usersRepository.findOne({ username }); if (!user) throw new UnauthorizedException() return user; } }
ljoboy/nestjs-backend
src/contacts/entities/Contacts.ts
import { BaseEntity, Column, Entity, Index, JoinColumn, ManyToOne, OneToMany, PrimaryGeneratedColumn } from "typeorm"; import { Emails } from "../../emails/entities/Emails"; import { Phones } from "../../phones/entities/Phones"; import { Websites } from "../../websites/entities/Websites"; import {Users} from "../../auth/entities/Users"; @Index("identity", ["nom", "postnom", "prenom"], {}) @Entity("contacts") export class Contacts extends BaseEntity { @PrimaryGeneratedColumn({ type: "integer", name: "id" }) id: number; @Column("text", { name: "nom" }) nom: string; @Column("text", { name: "prenom", nullable: true }) prenom: string | null; @Column("text", { name: "postnom", nullable: true }) postnom: string | null; @Column("text", { name: "company", nullable: true }) company: string | null; @Column("text", { name: "title", nullable: true }) title: string | null; @Column("text", { name: "img", nullable: true }) img: string | null; @Column("text", { name: "bday", nullable: true }) bday: string | null; @Column("text", { name: "genre", nullable: true }) genre: string | null; @Column("text", { name: "details", nullable: true }) details: string | null; @OneToMany( () => Emails, emails => emails.idContact ) emails: Emails[]; @OneToMany( () => Phones, phones => phones.idContact ) phones: Phones[]; @OneToMany( () => Websites, websites => websites.idContact ) websites: Websites[]; @ManyToOne( () => Users, users => users.contacts, { onDelete: "CASCADE", onUpdate: "CASCADE" } ) @JoinColumn({ name: "user", referencedColumnName: "id" }) user: Users; }
ljoboy/nestjs-backend
src/emails/emails.module.ts
import { Module } from '@nestjs/common'; import { EmailsController } from './emails.controller'; import { EmailsService } from './emails.service'; import {TypeOrmModule} from "@nestjs/typeorm"; import {EmailsRepository} from "./emails.repository"; import {AuthModule} from "../auth/auth.module"; @Module({ imports: [ TypeOrmModule.forFeature([EmailsRepository]), AuthModule, ], exports: [EmailsService], controllers: [EmailsController], providers: [EmailsService] }) export class EmailsModule {}
ljoboy/nestjs-backend
src/emails/emails.controller.ts
import {Controller, UseGuards} from '@nestjs/common'; import {Crud, CrudController} from "@nestjsx/crud"; import {Emails} from "./entities/Emails"; import {EmailsService} from "./emails.service"; import {AuthGuard} from "@nestjs/passport"; @UseGuards(AuthGuard()) @Crud({model: { type: Emails } }) @Controller('emails') export class EmailsController implements CrudController<Emails>{ constructor(public service: EmailsService) { } }
ljoboy/nestjs-backend
src/emails/emails.service.ts
import { Injectable } from '@nestjs/common'; import {TypeOrmCrudService} from "@nestjsx/crud-typeorm"; import {Emails} from "./entities/Emails"; import {InjectRepository} from "@nestjs/typeorm"; import {EmailsRepository} from "./emails.repository"; @Injectable() export class EmailsService extends TypeOrmCrudService<Emails>{ constructor(@InjectRepository(EmailsRepository) repo) { super(repo); } }
ljoboy/nestjs-backend
src/websites/websites.controller.ts
import {Controller, UseGuards} from '@nestjs/common'; import {Crud, CrudController} from "@nestjsx/crud"; import {WebsitesService} from "./websites.service"; import {Websites} from "./entities/Websites"; import {AuthGuard} from "@nestjs/passport"; @UseGuards(AuthGuard()) @Crud({model: { type: Websites } }) @Controller('websites') export class WebsitesController implements CrudController<Websites>{ constructor(public service: WebsitesService) { } }
ljoboy/nestjs-backend
src/contacts/contacts.repository.ts
import {EntityRepository, Repository} from "typeorm"; import {Contacts} from "./entities/Contacts"; @EntityRepository(Contacts) export class ContactsRepository extends Repository<Contacts>{ }
ljoboy/nestjs-backend
src/contacts/contacts.module.ts
<reponame>ljoboy/nestjs-backend import { Module } from '@nestjs/common'; import { ContactsService } from './contacts.service'; import { ContactsController } from './contacts.controller'; import {TypeOrmModule} from "@nestjs/typeorm"; import {ContactsRepository} from "./contacts.repository"; import {AuthModule} from "../auth/auth.module"; @Module({ imports: [ TypeOrmModule.forFeature([ContactsRepository]), AuthModule, ], providers: [ContactsService], exports: [ContactsService], controllers: [ContactsController] }) export class ContactsModule {}
ljoboy/nestjs-backend
src/auth/entities/Users.ts
<gh_stars>0 import {BaseEntity, Column, Entity, OneToMany, PrimaryGeneratedColumn, Unique} from "typeorm"; import * as bcrypt from "bcrypt"; import {Contacts} from "../../contacts/entities/Contacts"; import {GenreEnum} from "../genre.enum"; @Entity("users") @Unique(['username']) export class Users extends BaseEntity { @PrimaryGeneratedColumn({ type: "integer", name: "id" }) id: number; @Column("text", { name: "username" }) username: string; @Column("text", {name: "password"}) password: string; @Column("text", {name: "salt"}) salt: string; @Column("text", {name: "img", nullable: true}) img: string | null; @Column("text", {name: "full_name", nullable: true}) full_name: string | null; @Column("text", {name: "email", nullable: true}) email: string | null; @Column("text", {name: "address", nullable: true}) address: string | null; @Column("text", {name: "ville", nullable: true}) ville: string | null; @Column("text", {name: "country", nullable: true}) country: string | null; @Column("text", {name: "genre", nullable: true}) genre: GenreEnum | null; @OneToMany( type => Contacts, contacts => contacts.user ) contacts: Contacts[]; async validatePassword(password: string): Promise<boolean> { const hash = await bcrypt.hash(password, this.salt); return hash === this.password; } }
ljoboy/nestjs-backend
src/contacts/contacts.controller.ts
import {Controller, UseGuards} from '@nestjs/common'; import {Crud, CrudController} from "@nestjsx/crud/"; import {Contacts} from "./entities/Contacts"; import {ContactsService} from "./contacts.service"; import {AuthGuard} from "@nestjs/passport"; @UseGuards(AuthGuard()) @Crud({model: { type: Contacts } }) @Controller('contacts') export class ContactsController implements CrudController<Contacts>{ constructor(public service: ContactsService) { } }
ljoboy/nestjs-backend
src/phones/phones.module.ts
<filename>src/phones/phones.module.ts<gh_stars>0 import { Module } from '@nestjs/common'; import { PhonesController } from './phones.controller'; import { PhonesService } from './phones.service'; import {TypeOrmModule} from "@nestjs/typeorm"; import {PhonesReposity} from "./phones.reposity"; import {AuthModule} from "../auth/auth.module"; @Module({ imports: [ TypeOrmModule.forFeature([PhonesReposity]), AuthModule, ], controllers: [PhonesController], providers: [PhonesService], exports: [PhonesService] }) export class PhonesModule {}
ljoboy/nestjs-backend
src/auth/genre.enum.ts
export enum GenreEnum { M, F }
ljoboy/nestjs-backend
src/phones/phones.controller.ts
<filename>src/phones/phones.controller.ts import {Controller, UseGuards} from '@nestjs/common'; import {Crud, CrudController} from "@nestjsx/crud"; import {Phones} from "./entities/Phones"; import {PhonesService} from "./phones.service"; import {AuthGuard} from "@nestjs/passport"; @UseGuards(AuthGuard()) @Crud({model: { type: Phones } }) @Controller('phones') export class PhonesController implements CrudController<Phones>{ constructor(public service: PhonesService) { } }
ljoboy/nestjs-backend
src/auth/auth.service.ts
import {Injectable, UnauthorizedException} from '@nestjs/common'; import {InjectRepository} from "@nestjs/typeorm"; import {UsersRepository} from "./users.repository"; import {LoginCredentialsDto} from "./dtos/login-credentials.dto"; import {JwtService} from "@nestjs/jwt"; import {JwtPayload} from "./jwt-payload.interface"; import {RegisterCredentialsDto} from "./dtos/register-credentials.dto"; @Injectable() export class AuthService { constructor( @InjectRepository(UsersRepository) private usersRepository: UsersRepository, private jwtService: JwtService, ) { } async signUp(registerCredentialsDto: RegisterCredentialsDto): Promise<void> { return this.usersRepository.signUp(registerCredentialsDto); } async signIn(authCredentialsDto: LoginCredentialsDto): Promise<{ accessToken: string }> { const username = await this.usersRepository.validateUserPassword(authCredentialsDto); if (!username) throw new UnauthorizedException('Invalid credentials!'); const payload: JwtPayload = {username}; const accessToken = await this.jwtService.sign(payload); return {accessToken}; } }
ljoboy/nestjs-backend
src/phones/phones.reposity.ts
import {EntityRepository, Repository} from "typeorm"; import {Phones} from "./entities/Phones"; @EntityRepository(Phones) export class PhonesReposity extends Repository<Phones>{ }
FullAriza/wallet
shared/contexts/DeFiScanContext.tsx
<reponame>FullAriza/wallet import React, { createContext, useContext, useMemo } from 'react' import { EnvironmentNetwork } from '@environment' import { useNetworkContext } from './NetworkContext' interface DeFiScanContextI { getTransactionUrl: (txid: string, rawtx?: string) => string getBlocksUrl: (blockCount: number) => string getTokenUrl: (tokenId: number | string) => string getAddressUrl: (address: string) => string getVaultsUrl: (vaultId: string) => string } const DeFiScanContext = createContext<DeFiScanContextI>(undefined as any) const baseDefiScanUrl = 'https://defiscan.live' export function useDeFiScanContext (): DeFiScanContextI { return useContext(DeFiScanContext) } export function DeFiScanProvider (props: React.PropsWithChildren<any>): JSX.Element | null { const { network } = useNetworkContext() const context: DeFiScanContextI = useMemo(() => { return { getTransactionUrl: (txid: string, rawtx?: string): string => { return getTxURLByNetwork(network, txid, rawtx) }, getBlocksUrl: (blockCount: number) => { return getURLByNetwork('blocks', network, blockCount) }, getTokenUrl: (tokenId: number | string) => { return getURLByNetwork('tokens', network, tokenId) }, getAddressUrl: (address: string) => { return getURLByNetwork('address', network, address) }, getVaultsUrl: (vaultId: string) => { return getURLByNetwork('vaults', network, vaultId) } } }, [network]) return ( <DeFiScanContext.Provider value={context}> {props.children} </DeFiScanContext.Provider> ) } function getNetworkParams (network: EnvironmentNetwork): string { switch (network) { case EnvironmentNetwork.MainNet: // no-op: network param not required for MainNet return '' case EnvironmentNetwork.TestNet: return `?network=${EnvironmentNetwork.TestNet}` case EnvironmentNetwork.LocalPlayground: case EnvironmentNetwork.RemotePlayground: return `?network=${EnvironmentNetwork.RemotePlayground}` default: return '' } } function getTxURLByNetwork (network: EnvironmentNetwork, txid: string, rawtx?: string): string { let baseUrl = `${baseDefiScanUrl}/transactions/${txid}` baseUrl += getNetworkParams(network) if (typeof rawtx === 'string' && rawtx.length !== 0) { if (network === EnvironmentNetwork.MainNet) { baseUrl += `?rawtx=${rawtx}` } else { baseUrl += `&rawtx=${rawtx}` } } return baseUrl } function getURLByNetwork (path: string, network: EnvironmentNetwork, id: number | string): string { return `${baseDefiScanUrl}/${path}/${id}${getNetworkParams(network)}` }
FullAriza/wallet
mobile-app/cypress/support/commands.ts
import '@testing-library/cypress/add-commands' import './onboardingCommands' import './walletCommands' /* eslint-disable @typescript-eslint/no-var-requires */ const compareSnapshotCommand = require('cypress-image-diff-js/dist/command') compareSnapshotCommand() // *********************************************** // This example commands.js shows you how to // create various custom commands and overwrite // existing commands. // // For more comprehensive examples of custom // commands please read more here: // https://on.cypress.io/custom-commands // *********************************************** // // // -- This is a parent command -- // Cypress.Commands.add('login', (email, password) => { ... }) // // // -- This is a child command -- // Cypress.Commands.add('drag', { prevSubject: 'element'}, (subject, options) => { ... }) // // // -- This is a dual command -- // Cypress.Commands.add('dismiss', { prevSubject: 'optional'}, (subject, options) => { ... }) // // // -- This will overwrite an existing command -- // Cypress.Commands.overwrite('visit', (originalFn, url, options) => { ... }) declare global { namespace Cypress { interface Chainable { /** * @description Custom command to select DOM element by data-testid attribute. * @example cy.getByTestID('settings') */ getByTestID: (value: string, opts?: any) => Chainable<Element> /** * @description Redirects to main page and creates an empty wallet for testing. Useful on starts of tests. * @param {boolean} [isRandom=false] default = false, creates randomly generated mnemonic seed or abandon x23 * @example cy.createEmptyWallet(isRandom?: boolean) */ createEmptyWallet: (isRandom?: boolean) => Chainable<Element> /** * @description Sends UTXO DFI to wallet. * @example cy.sendDFItoWallet().wait(4000) */ sendDFItoWallet: () => Chainable<Element> /** * @description Sends DFI Token to wallet. * @example cy.sendDFITokentoWallet().wait(4000) */ sendDFITokentoWallet: () => Chainable<Element> /** * @description Sends token to wallet. Accepts a list of token symbols to be sent. * @param {string[]} tokens to be sent * @example cy.sendTokenToWallet(['BTC', 'ETH']).wait(4000) */ sendTokenToWallet: (tokens: string[]) => Chainable<Element> /** * @description Wait for the ocean interface to be confirmed then close the drawer * @param {string} pin - accepts optional pin * @example cy.closeOceanInterface('000000') */ closeOceanInterface: (pin?: string) => Chainable<Element> /** * @description Exit current wallet * @example cy.exitWallet() */ exitWallet: () => Chainable<Element> /** * @description Fetch wallet balance * @example cy.fetchWalletBalance() */ fetchWalletBalance: () => Chainable<Element> /** * @description Switch networks via app * @param {string} network to be used * @example cy.switchToMainnet('MainNet') */ switchNetwork: (network: string) => Chainable<Element> /** * @description Stores local storage for dependent tests */ saveLocalStorage: () => Chainable<Element> /** * @description Restores local storage for dependent tests */ restoreLocalStorage: () => Chainable<Element> /** * @description Compare snapshot from image */ compareSnapshot: (element?: string) => Chainable<Element> } } } Cypress.Commands.add('getByTestID', (selector: string, opts?: any) => { /* eslint-disable @typescript-eslint/restrict-template-expressions */ const args = opts != null ? opts : { timeout: 10000 } return cy.get(`[data-testid=${Cypress.$.escapeSelector(selector)}]`, args) }) Cypress.Commands.add('createEmptyWallet', (isRandom: boolean = false) => { cy.visit('/') cy.getByTestID(isRandom ? 'playground_wallet_random' : 'playground_wallet_abandon').click() }) Cypress.Commands.add('sendDFItoWallet', () => { cy.intercept('/v0/playground/rpc/sendtoaddress').as('sendToAddress') cy.getByTestID('playground_wallet_top_up').click() cy.wait(['@sendToAddress']) }) Cypress.Commands.add('sendDFITokentoWallet', () => { cy.intercept('/v0/playground/wallet/tokens/0/send').as('sendToAddress') cy.getByTestID('playground_token_DFI').click() cy.wait(['@sendToAddress']) }) Cypress.Commands.add('sendTokenToWallet', (tokens: string[]) => { cy.intercept('/v0/playground/rpc/sendtokenstoaddress').as('sendTokensToAddress') tokens.forEach((t: string) => { cy.getByTestID(`playground_token_${t}`).click() }) cy.wait(['@sendTokensToAddress']) }) Cypress.Commands.add('closeOceanInterface', (pin?: string) => { const inputPin = pin !== undefined ? pin : '000000' cy.getByTestID('pin_authorize').type(inputPin) cy.wait(5000).getByTestID('oceanInterface_close').click().wait(2000) }) Cypress.Commands.add('exitWallet', () => { cy.getByTestID('playground_wallet_clear').click() }) Cypress.Commands.add('fetchWalletBalance', () => { cy.getByTestID('playground_wallet_fetch_balances').click() }) Cypress.Commands.add('switchNetwork', (network: string) => { cy.getByTestID('bottom_tab_balances').click() cy.getByTestID('header_settings').click() cy.getByTestID('button_selected_network').click() cy.getByTestID(`button_network_${network}`).click() cy.on('window:confirm', () => {}) }) const LOCAL_STORAGE_MEMORY = {} Cypress.Commands.add('saveLocalStorage', () => { Object.keys(localStorage).forEach(key => { LOCAL_STORAGE_MEMORY[key] = localStorage[key] }) }) Cypress.Commands.add('restoreLocalStorage', () => { Object.keys(LOCAL_STORAGE_MEMORY).forEach(key => { localStorage.setItem(key, LOCAL_STORAGE_MEMORY[key]) }) })
FullAriza/wallet
mobile-app/app/screens/AppNavigator/screens/Loans/VaultDetail/components/LoansTab.tsx
import React from 'react' import BigNumber from 'bignumber.js' import { ThemedText, ThemedView } from '@components/themed' import { tailwind } from '@tailwind' import { View } from '@components' import { SymbolIcon } from '@components/SymbolIcon' import { IconButton } from '@components/IconButton' import { translate } from '@translations' import { LoanVault } from '@store/loans' import { LoanVaultActive, LoanVaultState, LoanVaultTokenAmount } from '@defichain/whale-api-client/dist/api/loan' import { VaultSectionTextRow } from '../../components/VaultSectionTextRow' import { EmptyLoan } from './EmptyLoan' import { NavigationProp, useNavigation } from '@react-navigation/native' import { LoanParamList } from '@screens/AppNavigator/screens/Loans/LoansNavigator' import { useLoanOperations } from '@screens/AppNavigator/screens/Loans/hooks/LoanOperations' interface LoanCardProps { symbol: string displaySymbol: string amount: string interestAmount?: string vaultState: LoanVaultState vault?: LoanVaultActive loanToken: LoanVaultTokenAmount } export function LoansTab (props: { vault: LoanVault }): JSX.Element { const { vault } = props return ( <ThemedView style={tailwind('p-4')} > {vault.state === LoanVaultState.ACTIVE && vault.loanValue === '0' && ( <EmptyLoan vaultId={vault.vaultId} /> )} {vault.state === LoanVaultState.IN_LIQUIDATION ? ( vault.batches.map(batch => ( <LoanCard key={batch.loan.id} symbol={batch.loan.id} displaySymbol={batch.loan.displaySymbol} amount={batch.loan.amount} vaultState={LoanVaultState.IN_LIQUIDATION} loanToken={batch.loan} /> )) ) : ( vault.loanAmounts.map(loan => ( <LoanCard key={loan.id} symbol={loan.symbol} displaySymbol={loan.displaySymbol} amount={loan.amount} interestAmount={vault.interestAmounts.find(interest => interest.symbol === loan.symbol)?.amount} vaultState={vault.state} vault={vault} loanToken={loan} /> )) )} </ThemedView> ) } function LoanCard (props: LoanCardProps): JSX.Element { const canUseOperations = useLoanOperations(props.vault?.state) return ( <ThemedView light={tailwind('bg-white border-gray-200')} dark={tailwind('bg-dfxblue-800 border-dfxblue-900')} style={tailwind('p-4 mb-2 border rounded')} > <View style={tailwind('flex flex-row items-center')}> <SymbolIcon symbol={props.displaySymbol} styleProps={{ width: 16, height: 16 }} /> <ThemedText light={tailwind({ 'text-dfxgray-300': props.vaultState === LoanVaultState.IN_LIQUIDATION, 'text-black': props.vaultState !== LoanVaultState.IN_LIQUIDATION })} dark={tailwind({ 'text-gray-700': props.vaultState === LoanVaultState.IN_LIQUIDATION, 'text-white': props.vaultState !== LoanVaultState.IN_LIQUIDATION })} style={tailwind('font-medium ml-2')} > {props.displaySymbol} </ThemedText> </View> <View style={tailwind('mt-3')}> <VaultSectionTextRow value={new BigNumber(props.amount).toFixed(8)} lhs={translate('components/VaultDetailsLoansTab', 'Outstanding balance')} testID='text_outstanding_balance' suffixType='text' suffix={` ${props.displaySymbol}`} style={tailwind('text-sm font-medium')} rhsThemedProps={{ light: tailwind({ 'text-dfxgray-300': props.vaultState === LoanVaultState.IN_LIQUIDATION, 'text-black': props.vaultState !== LoanVaultState.IN_LIQUIDATION }), dark: tailwind({ 'text-gray-700': props.vaultState === LoanVaultState.IN_LIQUIDATION, 'text-white': props.vaultState !== LoanVaultState.IN_LIQUIDATION }) }} /> {props.vaultState !== LoanVaultState.IN_LIQUIDATION && ( <VaultSectionTextRow value={new BigNumber(props.interestAmount ?? 0).toFixed(8)} lhs={translate('components/VaultDetailsLoansTab', 'Interest amount')} testID='text_interest_amount' suffixType='text' suffix={` ${props.displaySymbol}`} info={{ title: 'Interest amount', message: 'This amount is the total interest amount from both vault and token interest rate.' }} /> )} </View> { canUseOperations && props.vault !== undefined && ( <ActionButtons vault={props.vault} loanToken={props.loanToken} /> ) } </ThemedView> ) } function ActionButtons ({ vault, loanToken }: { vault: LoanVaultActive, loanToken: LoanVaultTokenAmount }): JSX.Element { const navigation = useNavigation<NavigationProp<LoanParamList>>() return ( <View style={tailwind('mt-4 -mb-2 flex flex-row justify-between')} > <View style={tailwind('flex flex-row flex-wrap flex-1')}> <IconButton iconLabel={translate('components/VaultDetailsLoansTab', 'PAYBACK LOAN')} style={tailwind('mr-2 mb-2 p-2')} onPress={() => { navigation.navigate({ name: 'PaybackLoanScreen', merge: true, params: { vault, loanToken } }) }} /> <IconButton iconLabel={translate('components/VaultDetailsLoansTab', 'BORROW MORE')} style={tailwind('mr-2 mb-2 p-2')} onPress={() => { navigation.navigate({ name: 'BorrowMoreScreen', merge: true, params: { vault, loanTokenAmount: loanToken } }) }} /> </View> </View> ) }
FullAriza/wallet
mobile-app/app/screens/AppNavigator/screens/Loans/screens/CloseVaultScreen.tsx
<reponame>FullAriza/wallet<gh_stars>0 import { NumberRow } from '@components/NumberRow' import { SubmitButtonGroup } from '@components/SubmitButtonGroup' import { ThemedScrollView, ThemedSectionTitle, ThemedText, ThemedView } from '@components/themed' import { EnvironmentNetwork } from '@environment' import { StackScreenProps } from '@react-navigation/stack' import { useNetworkContext } from '@shared-contexts/NetworkContext' import { tailwind } from '@tailwind' import { translate } from '@translations' import React, { Dispatch, useEffect, useState } from 'react' import { LoanParamList } from '../LoansNavigator' import { hasTxQueued, transactionQueue } from '@store/transaction_queue' import { hasTxQueued as hasBroadcastQueued } from '@store/ocean' import { useDispatch, useSelector } from 'react-redux' import { RootState } from '@store' import { NativeLoggingProps, useLogger } from '@shared-contexts/NativeLoggingProvider' import { onTransactionBroadcast } from '@api/transaction/transaction_commands' import { WhaleWalletAccount } from '@defichain/whale-api-wallet' import { CTransactionSegWit } from '@defichain/jellyfish-transaction/dist' import { InfoText } from '@components/InfoText' import { View } from '@components' type Props = StackScreenProps<LoanParamList, 'CloseVaultScreen'> export function CloseVaultScreen ({ route, navigation }: Props): JSX.Element { const { vaultId } = route.params const hasPendingJob = useSelector((state: RootState) => hasTxQueued(state.transactionQueue)) const hasPendingBroadcastJob = useSelector((state: RootState) => hasBroadcastQueued(state.ocean)) const dispatch = useDispatch() const logger = useLogger() const [isOnPage, setIsOnPage] = useState<boolean>(true) function onCancel (): void { navigation.navigate({ name: 'VaultDetailScreen', params: { vaultId: vaultId }, merge: true }) } async function onSubmit (): Promise<void> { if (hasPendingJob || hasPendingBroadcastJob) { return } await closeVault(vaultId, dispatch, () => { onTransactionBroadcast(isOnPage, navigation.dispatch) }, () => {}, logger) } useEffect(() => { setIsOnPage(true) return () => { setIsOnPage(false) } }, []) return ( <ThemedScrollView> <SummaryHeader vaultId={vaultId} /> <SummaryDetails /> <View style={tailwind('my-4 mx-4')}> <InfoText testID='close_vault_info_text' text={translate('screens/CloseVaultScreen', 'Upon closing, this Vault ID will not be usable anymore. Make sure you don’t need anything from this vault before closing.')} /> </View> <SubmitButtonGroup isDisabled={hasPendingJob || hasPendingBroadcastJob} label={translate('screens/CloseVaultScreen', 'CONFIRM CLOSE VAULT')} isProcessing={hasPendingJob || hasPendingBroadcastJob} processingLabel={translate('screens/CloseVaultScreen', 'CLOSING')} onCancel={onCancel} onSubmit={onSubmit} title='create_vault' /> </ThemedScrollView> ) } function SummaryHeader (props: { vaultId: string }): JSX.Element { return ( <ThemedView light={tailwind('bg-white border-b border-gray-300')} dark={tailwind('bg-dfxblue-800 border-b border-dfxblue-900')} style={tailwind('flex-col px-4 py-6')} > <ThemedText light={tailwind('text-gray-500')} dark={tailwind('text-dfxgray-400')} style={tailwind('mb-1 text-sm')} > {translate('screens/CloseVaultScreen', 'You are closing Vault ID')} </ThemedText> <ThemedText style={tailwind('text-sm font-medium mb-1')} > {props.vaultId} </ThemedText> </ThemedView> ) } function SummaryDetails (): JSX.Element { const { network } = useNetworkContext() return ( <> <ThemedSectionTitle text={translate('screens/CloseVaultScreen', 'DETAILS')} /> <NumberRow lhs={translate('screens/CloseVaultScreen', 'Fees to return')} rhs={{ value: network === EnvironmentNetwork.MainNet || network === EnvironmentNetwork.TestNet ? 1 : 0.5, testID: 'fees_to_return_text', suffixType: 'text', suffix: 'DFI' }} /> <NumberRow lhs={translate('screens/CloseVaultScreen', 'Fees to burn')} rhs={{ value: network === EnvironmentNetwork.MainNet || network === EnvironmentNetwork.TestNet ? 1 : 0.5, testID: 'fees_to_burn_text', suffixType: 'text', suffix: 'DFI' }} /> </> ) } async function closeVault ( vaultId: string, dispatch: Dispatch<any>, onBroadcast: () => void, onConfirmation: () => void, logger: NativeLoggingProps ): Promise<void> { try { const signer = async (account: WhaleWalletAccount): Promise<CTransactionSegWit> => { const script = await account.getScript() const builder = account.withTransactionBuilder() const signed = await builder.loans.closeVault({ vaultId: vaultId, to: script }, script) return new CTransactionSegWit(signed) } dispatch(transactionQueue.actions.push({ sign: signer, title: translate('screens/CloseVaultScreen', 'Closing vault'), description: translate('screens/CloseVaultScreen', 'You are about to close vault {{vaultId}}', { vaultId }), onBroadcast, onConfirmation })) } catch (e) { logger.error(e) } }
FullAriza/wallet
mobile-app/app/screens/AppNavigator/screens/Loans/components/CollateralizationRatioRow.tsx
<filename>mobile-app/app/screens/AppNavigator/screens/Loans/components/CollateralizationRatioRow.tsx<gh_stars>0 import { View } from '@components' import { BottomSheetInfo } from '@components/BottomSheetInfo' import { ThemedText, ThemedView } from '@components/themed' import { tailwind } from '@tailwind' import React from 'react' import NumberFormat from 'react-number-format' import { VaultHealthItem, VaultStatusTag } from './VaultStatusTag' interface CollateralizationRatioRowProps { label: string value: string testId: string type: 'current' | 'next' vaultState: VaultHealthItem } export function CollateralizationRatioRow (props: CollateralizationRatioRowProps): JSX.Element { const alertInfo = { title: 'Collateralization ratio', message: 'The collateralization ratio represents the amount of collaterals deposited in a vault in relation to the loan amount, expressed in percentage.' } const nextAlertInfo = { title: 'Next collateralization', message: 'Next collateralization ratio represents the vault\'s collateralization ratio based on the prices of the collateral/loan token(s) in the next hour.' } return ( <ThemedView dark={tailwind('bg-dfxblue-800 border-dfxblue-900')} light={tailwind('bg-white border-gray-200')} style={tailwind('p-4 flex-row items-start w-full border-b')} > <View style={tailwind('flex-row items-center w-6/12')}> <ThemedText style={tailwind('text-sm mr-1')} testID={`${props.testId}_label`} > {props.label} </ThemedText> <BottomSheetInfo alertInfo={props.type === 'next' ? nextAlertInfo : alertInfo} name={props.type === 'next' ? nextAlertInfo.title : alertInfo.title} /> </View> <View style={tailwind('flex-1 flex-row justify-end flex-wrap items-center')} > <NumberFormat value={props.value} decimalScale={2} thousandSeparator displayType='text' suffix='%' renderText={(val: string) => ( <View style={tailwind('flex flex-row items-center flex-1 flex-wrap justify-end')}> <ThemedText dark={tailwind('text-dfxgray-400')} light={tailwind('text-dfxgray-500')} style={tailwind('text-sm text-right mr-1')} testID={props.testId} > {props.type === 'next' && '~'}{val} </ThemedText> <VaultStatusTag status={props.vaultState.status} vaultStats={props.vaultState.vaultStats} /> </View> )} /> </View> </ThemedView> ) }
FullAriza/wallet
mobile-app/cypress/integration/functional/wallet/settings/knowledgeBase.spec.ts
<reponame>FullAriza/wallet import { EnvironmentNetwork } from '../../../../../../shared/environment' context('Wallet - Settings', () => { before(function () { cy.intercept('**/settings/flags', { body: [ { id: 'loan', name: 'Loan', stage: 'public', version: '>=0.0.0', description: 'Loan', networks: [EnvironmentNetwork.RemotePlayground, EnvironmentNetwork.LocalPlayground], platforms: ['ios', 'android', 'web'] } ] }) cy.createEmptyWallet(true) cy.getByTestID('header_settings').click() cy.getByTestID('setting_navigate_About').click() cy.getByTestID('knowledge_base_link').should('exist').click() }) it('should navigate to knowledge base page', function () { cy.url().should('include', 'app/Settings/KnowledgeBaseScreen') cy.getByTestID('knowledge_base_screen').should('exist') }) it('should navigate to recovery words faq from knowledge base page', function () { cy.getByTestID('recovery_words_faq').should('exist').click() cy.url().should('include', 'app/Settings/RecoveryWordsFaq') cy.go('back') cy.url().should('include', 'app/Settings/KnowledgeBaseScreen') }) it('should navigate to passcode faq from knowledge base page', function () { cy.getByTestID('passcode_faq').should('exist').click() cy.url().should('include', 'app/Settings/PasscodeFaq') cy.go('back') cy.url().should('include', 'app/Settings/KnowledgeBaseScreen') }) it('should navigate to UTXO vs Token faq from knowledge base page', function () { cy.getByTestID('utxo_and_token_faq').should('exist').click() cy.url().should('include', 'app/Settings/TokensVsUtxo') cy.go('back') cy.url().should('include', 'app/Settings/KnowledgeBaseScreen') }) it('should navigate to Loans faq from knowledge base page', function () { cy.getByTestID('loans_faq').should('exist').click() cy.url().should('include', 'app/Settings/LoansFaq') cy.go('back') cy.url().should('include', 'app/Settings/KnowledgeBaseScreen') }) })
FullAriza/wallet
mobile-app/app/screens/AppNavigator/screens/Loans/screens/LoansFaq.tsx
import { ThemedScrollView, ThemedText } from '@components/themed' import { AccordionContent, WalletAccordion } from '@components/WalletAccordion' import { tailwind } from '@tailwind' import { translate } from '@translations' import React from 'react' export function LoansFaq (): JSX.Element { const faqContent: AccordionContent[] = [ { title: translate('components/LoansFaq', 'How is the collateralization ratio calculated?'), content: [{ text: translate('components/LoansFaq', 'The collateralization ratio is calculated by taking the total collateral value deposited in a vault; divided by the amount of loan taken plus total interest, expressed in percentage.'), type: 'paragraph' }] }, { title: translate('components/LoansFaq', 'What is the collateralization ratio used for?'), content: [{ text: translate('components/LoansFaq', 'The collateralization ratio determines the state of the vault. A ratio below the minimum collaterization ratio results in liquidation, upon which, a vault\'s collaterals will be sent for auction.'), type: 'paragraph' }, { text: translate('components/LoansFaq', 'Indicators have been included to help visualise the health of your vault, where:'), type: 'paragraph' }, { text: translate('components/LoansFaq', 'Red: 1x – 1.25x above the minimum collateralization ratio'), type: 'bullet' }, { text: translate('components/LoansFaq', 'Yellow: 1.25x – 1.5x the minimum collateralization ratio'), type: 'bullet' }, { text: translate('components/LoansFaq', 'Green: More than 1.5x the minimum collateralization ratio'), type: 'bullet' }] }, { title: translate('components/LoansFaq', 'What does the different status of a vault mean?'), content: [{ text: translate('components/LoansFaq', 'Active: When a vault has been created but no loan has been taken yet'), type: 'bullet' }, { text: translate('components/LoansFaq', 'At risk: When the collateralization ratio of a vault is between 1x – 1.5x the minimum collateralization ratio'), type: 'bullet' }, { text: translate('components/LoansFaq', 'Healthy: When the collateralization ratio of a vault is more than 1.5x the minimum collateralization ratio'), type: 'bullet' }, { text: translate('components/LoansFaq', 'In liquidation: When a vault\'s collateralization ratio falls below the minimum requirement'), type: 'bullet' }, { text: translate('components/LoansFaq', 'Halted: When any token in the vault (collateral or loan) has fluctuated more than 30% in the past hour'), type: 'bullet' }] }, { title: translate('components/LoansFaq', 'How are interests calculated for loan?'), content: [{ text: translate('components/LoansFaq', 'There are 2 types of interests that applies for loans, namely vault interest rate and token interest rate.'), type: 'paragraph' }, { text: translate('components/LoansFaq', 'The vault interest rate is determined when the vault owner selects the vault scheme, where the higher the minimum collateralization ratio, the lower the vault interest rate.'), type: 'bullet' }, { text: translate('components/LoansFaq', 'The token interest rate is applied on specific loan tokens, and can differ from token to token.'), type: 'bullet' }, { text: translate('components/LoansFaq', 'The total interest rate applied on a loan is derived by taking the vault interest rate + token interest rate, and is calculated on a per annum basis.'), type: 'paragraph' }] }, { title: translate('components/LoansFaq', 'What is collateral factor?'), content: [{ text: translate('components/LoansFaq', 'The collateral factor determines the degree of contribution of each collateral token. For example, if a token is accepted at 70% collateral factor, $100 worth of the token would contribute to $70 of collateral value in a vault.'), type: 'paragraph' }] } ] return ( <ThemedScrollView contentContainerStyle={tailwind('p-6 pb-8')} testID='loans_faq' > <ThemedText style={tailwind('text-lg font-semibold')} > {translate('components/LoansFaq', 'Decentralized Loans')} </ThemedText> <ThemedText style={tailwind('mt-2 text-sm')} > {translate('components/LoansFaq', 'The decentralized loan feature allows you to borrow decentralised tokens by using your cryptocurrency holdings as collateral. To start, you must first create a vault and deposit collaterals before you can take a loan.')} </ThemedText> <WalletAccordion testID='loans_faq_accordion' title={translate('components/LoansFaq', 'FREQUENTLY ASKED QUESTIONS')} content={faqContent} /> </ThemedScrollView> ) }
FullAriza/wallet
mobile-app/app/screens/TransactionAuthorization/TransactionAuthorization.tsx
<gh_stars>0 import { CTransactionSegWit } from '@defichain/jellyfish-transaction/dist' import { JellyfishWallet, WalletHdNodeProvider } from '@defichain/jellyfish-wallet' import { MnemonicHdNode } from '@defichain/jellyfish-wallet-mnemonic' import { WhaleWalletAccount } from '@defichain/whale-api-wallet' import React, { useCallback, useEffect, useRef, useState } from 'react' import { useDispatch, useSelector } from 'react-redux' import { initJellyfishWallet, MnemonicEncrypted, MnemonicUnprotected, PasscodeAttemptCounter } from '../../api/wallet' import { useNetworkContext } from '@shared-contexts/NetworkContext' import { useWalletNodeContext } from '@shared-contexts/WalletNodeProvider' import { useWalletPersistenceContext, WalletType } from '@shared-contexts/WalletPersistenceContext' import { useWhaleApiClient } from '@shared-contexts/WhaleContext' import { RootState } from '@store' import { authentication as authenticationStore } from '@store/authentication' import { ocean } from '@store/ocean' import { DfTxSigner, first, transactionQueue } from '@store/transaction_queue' import { translate } from '@translations' import { PasscodePrompt } from './PasscodePrompt' import { useLogger } from '@shared-contexts/NativeLoggingProvider' import { alertUnlinkWallet, authenticateFor, signTransaction } from '@screens/TransactionAuthorization/api/transaction_signer' import { CANCELED_ERROR, DEFAULT_MESSAGES, INVALID_HASH, MAX_PASSCODE_ATTEMPT, PASSCODE_LENGTH, PromptPromiseI, SUCCESS_DISPLAY_TIMEOUT_IN_MS, TransactionStatus, USER_CANCELED } from '@screens/TransactionAuthorization/api/transaction_types' import { BottomSheetModal, useBottomSheetModal } from '@gorhom/bottom-sheet' /** * @description - Passcode prompt promise that resolves the pin to the wallet * */ let PROMPT_PIN_PROMISE: PromptPromiseI | undefined /** * @description - Main component to handle all authorizations for Transactions. All transaction validation logic happens here. * This file is imported in RootNavigator. * @see - PasscodePrompt.tsx for UI of Prompt */ export function TransactionAuthorization (): JSX.Element | null { const { data: providerData } = useWalletNodeContext() const { clearWallets } = useWalletPersistenceContext() const { network } = useNetworkContext() const whaleApiClient = useWhaleApiClient() const logger = useLogger() const dispatch = useDispatch() const transaction = useSelector((state: RootState) => first(state.transactionQueue)) const authentication = useSelector((state: RootState) => state.authentication.authentication) const [transactionStatus, setTransactionStatus] = useState<TransactionStatus>(TransactionStatus.INIT) const [attemptsRemaining, setAttemptsRemaining] = useState<number>(MAX_PASSCODE_ATTEMPT) const [pin, setPin] = useState<string>('') const [isRetry, setIsRetry] = useState(false) const bottomSheetModalRef = useRef<BottomSheetModal>(null) const { dismiss } = useBottomSheetModal() const modalName = 'PasscodePromptModal' /** * This is one of the most important state of this component. * 1. We initialize a JellyFishWallet and attach a promise to it (https://github.com/DeFiCh/jellyfish/blob/fe270b737705ad33242a9ec3f8896b2f8f5052c8/packages/jellyfish-wallet-encrypted/src/hd_node.ts#L122) * 2. We attach the PROMPT_PIN_PROMISE from this component that will resolve the passcode to the JellyFish wallet * 3. It acts as a "general" promise that gets resolved once passcode input is complete * 4. Take note on the word "complete". Meaning, it's not yet validated/verified that it's the actual passcode. */ const [wallet, setWallet] = useState<JellyfishWallet<WhaleWalletAccount, MnemonicHdNode>>() // messages const [message, setMessage] = useState(DEFAULT_MESSAGES.message) const [loadingMessage, setLoadingMessage] = useState(DEFAULT_MESSAGES.loadingMessage) const closeModal = useCallback(() => { dismiss(modalName) }, []) const openModal = useCallback(() => { bottomSheetModalRef.current?.present() }, []) // generic callbacks const onPinInput = (inputPin: string): void => { if (inputPin.length === PASSCODE_LENGTH && PROMPT_PIN_PROMISE !== undefined) { const resolve = PROMPT_PIN_PROMISE.resolve setTimeout(() => { resolve(inputPin) // remove proxied promised, allow next prompt() call PROMPT_PIN_PROMISE = undefined }, 50) setTransactionStatus(TransactionStatus.SIGNING) } setPin(inputPin) } const onCancel = (): void => { if (PROMPT_PIN_PROMISE !== undefined) { PROMPT_PIN_PROMISE.reject(new Error(USER_CANCELED)) // remove proxied promised, allow next prompt() call PROMPT_PIN_PROMISE = undefined } else if (transactionStatus === TransactionStatus.AUTHORIZED) { PROMPT_PIN_PROMISE = undefined transaction === undefined ? dispatch(authenticationStore.actions.dismiss()) : dispatch(transactionQueue.actions.pop()) onTaskCompletion() } setTimeout(() => { // adding arbitrary timeout to fix modal not closing in Android closeModal() }, 300) } const onRetry = async (attempts: number): Promise<void> => { setPin('') setIsRetry(true) setAttemptsRemaining(MAX_PASSCODE_ATTEMPT - attempts) await PasscodeAttemptCounter.set(attempts) } const onPrompt = async (): Promise<string> => { if (PROMPT_PIN_PROMISE !== undefined) { throw new Error('prompt UI occupied') } return await new Promise<string>((resolve, reject) => { // passphrase prompt is meant for authorizing single transaction regardless // caller should not prompt for next transaction before one is completed // proxy the promise, wait for user input PROMPT_PIN_PROMISE = { resolve, reject } // setPin('') // do not reset, keep pin cached until onTaskCompletion setTransactionStatus(TransactionStatus.PIN) }) } const resetPasscodeCounter = async (): Promise<void> => { setAttemptsRemaining(MAX_PASSCODE_ATTEMPT) await PasscodeAttemptCounter.set(0) } const onTaskCompletion = (): void => { closeModal() setPin('') setIsRetry(false) setMessage(DEFAULT_MESSAGES.message) setLoadingMessage(DEFAULT_MESSAGES.loadingMessage) setTransactionStatus(TransactionStatus.IDLE) // very last step, open up for next task } const setupNewWallet = (passcodePromptPromise: () => Promise<string>): void => { let provider: WalletHdNodeProvider<MnemonicHdNode> if (providerData.type === WalletType.MNEMONIC_UNPROTECTED) { provider = MnemonicUnprotected.initProvider(providerData, network) } else if (providerData.type === WalletType.MNEMONIC_ENCRYPTED) { provider = MnemonicEncrypted.initProvider(providerData, network, { prompt: passcodePromptPromise }) } else { throw new Error('Missing wallet provider data handler') } setWallet(initJellyfishWallet(provider, network, whaleApiClient)) } const onPinSuccess = async (transaction: DfTxSigner, signedTx: CTransactionSegWit): Promise<void> => { setTransactionStatus(TransactionStatus.AUTHORIZED) await resetPasscodeCounter() dispatch(ocean.actions.queueTransaction({ tx: signedTx, onError: transaction.onError, onConfirmation: transaction.onConfirmation, onBroadcast: transaction.onBroadcast, submitButtonLabel: transaction.submitButtonLabel })) // push signed result for broadcasting } // mandatory UI initialization useEffect(() => { setupNewWallet(onPrompt) PasscodeAttemptCounter.get() .then(counter => { setAttemptsRemaining(MAX_PASSCODE_ATTEMPT - counter) setTransactionStatus(TransactionStatus.IDLE) }) .catch(error => { logger.error(error) throw error }) }, [providerData, network, whaleApiClient]) /** * @description This is where the magic happens. It serves two types of transactions * 1. Wallet Transactions (e.g, Send, Add Liquidity, Pool Swap etc.) * 2. Non-wallet transactions (e.g, Reveal recovery words, change app passcode) * If you're curious where the passcode validation is triggered, see - https://github.com/DeFiCh/jellyfish/blob/fe270b737705ad33242a9ec3f8896b2f8f5052c8/packages/jellyfish-wallet-encrypted/src/hd_node.ts#L87 * */ useEffect(() => { if (transactionStatus !== TransactionStatus.IDLE) { // wait for prompt UI is ready again return } if (attemptsRemaining === 0) { return } const retries = MAX_PASSCODE_ATTEMPT - attemptsRemaining // Wallet Transactions if (transaction !== undefined && // any tx queued wallet !== undefined // just in case any data stuck in store ) { setTransactionStatus(TransactionStatus.BLOCK) // prevent any re-render trigger (between IDLE and PIN) signTransaction(transaction, wallet.get(0), onRetry, retries, logger) .then(async signedTx => { // case 1: success await onPinSuccess(transaction, signedTx) }) .catch(async e => { if (e.message === INVALID_HASH) { // case 2: invalid passcode await resetPasscodeCounter() await clearWallets() alertUnlinkWallet() } else if (e.message !== USER_CANCELED) { // case 4: unknown error type dispatch(ocean.actions.setError(e)) } // case 3: canceled throw new Error(CANCELED_ERROR) // pass to last catch so all cases will complete task }) .catch(e => { dispatch(transactionQueue.actions.pop()) // remove job onTaskCompletion() if (e.message !== CANCELED_ERROR) { // no need to log if user cancels logger.error(e) } }) } else if (authentication !== undefined) { // Non-wallet transactions setTransactionStatus(TransactionStatus.BLOCK) // prevent any re-render trigger (between IDLE and PIN) setMessage(authentication.message) setLoadingMessage(authentication.loading) authenticateFor(onPrompt, authentication, onRetry, retries, logger) .then(async () => { // case 1: success setTransactionStatus(TransactionStatus.AUTHORIZED) await resetPasscodeCounter() }) .catch(async e => { if (e.message === INVALID_HASH) { // case 2: invalid passcode await resetPasscodeCounter() await clearWallets() alertUnlinkWallet() } else if (e.message !== USER_CANCELED && authentication.onError !== undefined) { // case 4: unknown error type authentication.onError(e) } // case 3: canceled throw new Error(CANCELED_ERROR) // pass to last catch so all cases will complete task }) .catch(e => { dispatch(authenticationStore.actions.dismiss()) onTaskCompletion() if (e.message !== CANCELED_ERROR) { // no need to log if user cancels logger.error(e) } }) } }, [transaction, wallet, transactionStatus, authentication, attemptsRemaining]) // auto resolve with cached pin if any useEffect(() => { if (transactionStatus === TransactionStatus.PIN && pin.length === PASSCODE_LENGTH) { onPinInput(pin) } }, [transactionStatus, pin]) /** * @description When the transaction has been TransactionStatus.AUTHORIZED, show the completion screen after SUCCESS_DISPLAY_TIMEOUT_IN_MS * */ useEffect(() => { if (transactionStatus === TransactionStatus.AUTHORIZED) { setTimeout(() => { transaction === undefined ? dispatch(authenticationStore.actions.dismiss()) : dispatch(transactionQueue.actions.pop()) PROMPT_PIN_PROMISE = undefined onTaskCompletion() }, SUCCESS_DISPLAY_TIMEOUT_IN_MS) } }, [transactionStatus]) useEffect(() => { if (![TransactionStatus.INIT, TransactionStatus.IDLE, TransactionStatus.BLOCK].includes(transactionStatus)) { openModal() } }, [transactionStatus]) if ([TransactionStatus.INIT, TransactionStatus.IDLE, TransactionStatus.BLOCK].includes(transactionStatus)) { return null } return ( <PasscodePrompt onCancel={onCancel} message={translate('screens/UnlockWallet', message)} transaction={transaction} status={transactionStatus} pinLength={PASSCODE_LENGTH} onPinInput={onPinInput} pin={pin} loadingMessage={translate('screens/TransactionAuthorization', loadingMessage)} authorizedTransactionMessage={ { title: translate('screens/TransactionAuthorization', DEFAULT_MESSAGES.authorizedTransactionMessage.title), description: translate('screens/TransactionAuthorization', DEFAULT_MESSAGES.authorizedTransactionMessage.description) } } grantedAccessMessage={ { title: translate('screens/UnlockWallet', DEFAULT_MESSAGES.grantedAccessMessage.title), description: translate('screens/UnlockWallet', DEFAULT_MESSAGES.grantedAccessMessage.description) } } isRetry={isRetry} attemptsRemaining={attemptsRemaining} maxPasscodeAttempt={MAX_PASSCODE_ATTEMPT} modalRef={bottomSheetModalRef} promptModalName={modalName} onModalCancel={closeModal} /> ) }
FullAriza/wallet
mobile-app/app/screens/AppNavigator/screens/Loans/components/VaultInfo.tsx
<filename>mobile-app/app/screens/AppNavigator/screens/Loans/components/VaultInfo.tsx<gh_stars>0 import { TextProps, View } from '@components' import { ThemedProps, ThemedText } from '@components/themed' import { TokenIconGroup } from '@components/TokenIconGroup' import { tailwind } from '@tailwind' import { translate } from '@translations' import BigNumber from 'bignumber.js' import React from 'react' import { StyleProp } from 'react-native' interface VaultInfoProps { label: string value?: BigNumber tokens: string[] prefix?: string suffix?: string decimalPlace?: number valueThemedProps?: ThemedProps valueStyleProps?: StyleProp<TextProps> } export function VaultInfo (props: VaultInfoProps): JSX.Element { return ( <View style={tailwind('flex-row items-center w-full my-1')}> <View style={tailwind('w-6/12')}> <ThemedText light={tailwind('text-dfxgray-500')} dark={tailwind('text-dfxgray-400')} style={tailwind('text-xs')} > {translate('components/VaultCard', props.label)} </ThemedText> </View> <View style={tailwind('flex-1 flex-row justify-end flex-wrap items-center')}> <TokenIconGroup symbols={props.tokens} maxIconToDisplay={5} /> </View> </View> ) }
FullAriza/wallet
mobile-app/app/components/BottomSheetModal.web.tsx
<reponame>FullAriza/wallet<gh_stars>0 import React, { ReactElement } from 'react' import { View } from 'react-native' import { ThemedProps } from './themed' import Modal from 'react-overlays/Modal' import { BottomSheetNavScreen } from './BottomSheetWithNav' type Props = ThemedProps & { children: ReactElement screenList: BottomSheetNavScreen[] isModalDisplayed: boolean } export const BottomSheetModal = React.forwardRef((props: Props, ref: React.Ref<any>): JSX.Element => { const { children } = props return ( <Modal container={ref as React.RefObject<any>} show={props.isModalDisplayed} renderBackdrop={() => <View style={{ position: 'absolute', top: 0, right: 0, bottom: 0, left: 0, backgroundColor: 'black', opacity: 0.3 }} />} style={{ position: 'fixed', height: '240px', width: '375px', zIndex: 50, top: '50%' }} > {children} </Modal> ) })
FullAriza/wallet
mobile-app/app/screens/AppNavigator/screens/Balances/BalancesScreen.test.tsx
import { configureStore } from '@reduxjs/toolkit' import { fireEvent, render } from '@testing-library/react-native' import * as React from 'react' import { Provider } from 'react-redux' import { RootState } from '@store' import { wallet } from '@store/wallet' import { BalancesScreen } from './BalancesScreen' jest.mock('@react-navigation/bottom-tabs', () => ({ useBottomTabBarHeight: () => 49 })) jest.mock('randomcolor', () => jest.fn().mockReturnValue('#ffffff')) jest.mock('@shared-contexts/ThemeProvider') jest.mock('@shared-contexts/LanguageProvider') jest.mock('@shared-contexts/DeFiScanContext') jest.mock('../../../../hooks/wallet/TokensAPI', () => ({ useTokensAPI: () => [{ id: '0', symbol: 'DFI', symbolKey: 'DFI', isDAT: true, isLPS: false, amount: '23', name: 'Defi' }, { id: '1', symbol: 'BTC', symbolKey: 'BTC', isDAT: true, isLPS: false, amount: '777', name: 'Bitcoin' }, { id: '2', symbol: 'ETH', symbolKey: 'ETH', isDAT: true, isLPS: false, amount: '555', name: 'Ethereum' }] })) jest.mock('@shared-contexts/WalletContext') jest.mock('@shared-contexts/WalletPersistenceContext') jest.mock('../../../../contexts/DisplayBalancesContext') jest.mock('@react-navigation/native', () => ({ useNavigation: jest.fn() })) describe('balances page', () => { it('should match snapshot', async () => { const initialState: Partial<RootState> = { wallet: { utxoBalance: '77', tokens: [], poolpairs: [] } } const store = configureStore({ preloadedState: initialState, reducer: { wallet: wallet.reducer } }) const navigation: any = { navigate: jest.fn() } const route: any = {} const component = ( <Provider store={store}> <BalancesScreen navigation={navigation} route={route} /> </Provider> ) const rendered = render(component) expect(rendered.toJSON()).toMatchSnapshot() }) it('should navigate to token detail page', async () => { const initialState: Partial<RootState> = { wallet: { utxoBalance: '77', tokens: [], poolpairs: [] } } const store = configureStore({ preloadedState: initialState, reducer: { wallet: wallet.reducer } }) const navigation: any = { navigate: jest.fn() } const route: any = {} const spy = jest.spyOn(navigation, 'navigate') const component = ( <Provider store={store}> <BalancesScreen navigation={navigation} route={route} /> </Provider> ) const rendered = render(component) const btcBalanceRow = await rendered.findByTestId('balances_row_1') fireEvent.press(btcBalanceRow) expect(spy).toHaveBeenCalled() }) })
FullAriza/wallet
mobile-app/app/screens/AppNavigator/screens/Dex/CompositeSwap/CompositeSwapScreen.tsx
<reponame>FullAriza/wallet<gh_stars>0 import React, { useCallback, useEffect, useRef, useState } from 'react' import { Platform, TouchableOpacity, View } from 'react-native' import { useDispatch, useSelector } from 'react-redux' import { Control, Controller, useForm } from 'react-hook-form' import BigNumber from 'bignumber.js' import { NavigationProp, useNavigation } from '@react-navigation/native' import { tailwind } from '@tailwind' import { BottomSheetModal } from '@gorhom/bottom-sheet' import { translate } from '@translations' import { RootState } from '@store' import { hasTxQueued as hasBroadcastQueued } from '@store/ocean' import { hasTxQueued } from '@store/transaction_queue' import { DexItem, DFITokenSelector, DFIUtxoSelector } from '@store/wallet' import { usePoolPairsAPI } from '@hooks/wallet/PoolPairsAPI' import { queueConvertTransaction, useConversion } from '@hooks/wallet/Conversion' import { useTokensAPI } from '@hooks/wallet/TokensAPI' import { useLogger } from '@shared-contexts/NativeLoggingProvider' import { useWhaleApiClient } from '@shared-contexts/WhaleContext' import { PoolPairData } from '@defichain/whale-api-client/dist/api/poolpairs' import { StackScreenProps } from '@react-navigation/stack' import { ThemedIcon, ThemedScrollView, ThemedSectionTitle, ThemedText, ThemedTouchableOpacity, ThemedView } from '@components/themed' import { getNativeIcon } from '@components/icons/assets' import { BottomSheetNavScreen, BottomSheetWebWithNav, BottomSheetWithNav } from '@components/BottomSheetWithNav' import { BottomSheetToken, BottomSheetTokenList } from '@components/BottomSheetTokenList' import { Button } from '@components/Button' import { ConversionInfoText } from '@components/ConversionInfoText' import { FeeInfoRow } from '@components/FeeInfoRow' import { InputHelperText } from '@components/InputHelperText' import { NumberRow } from '@components/NumberRow' import { PriceRateProps, PricesSection } from './components/PricesSection' import { AmountButtonTypes, SetAmountButton } from '@components/SetAmountButton' import { TextRow } from '@components/TextRow' import { WalletTextInput } from '@components/WalletTextInput' import { ReservedDFIInfoText } from '@components/ReservedDFIInfoText' import { checkIfPair, findPath, getAdjacentNodes, GraphProps } from '../helpers/path-finding' import { SlippageTolerance } from './components/SlippageTolerance' import { DexParamList } from '../DexNavigator' export interface TokenState { id: string reserve: string displaySymbol: string symbol: string } export interface OwnedTokenState extends TokenState { amount: string } type Props = StackScreenProps<DexParamList, 'CompositeSwapScreen'> export function CompositeSwapScreen ({ route }: Props): JSX.Element { const logger = useLogger() const pairs = usePoolPairsAPI() const tokens = useTokensAPI() const client = useWhaleApiClient() const navigation = useNavigation<NavigationProp<DexParamList>>() const dispatch = useDispatch() const hasPendingJob = useSelector((state: RootState) => hasTxQueued(state.transactionQueue)) const hasPendingBroadcastJob = useSelector((state: RootState) => hasBroadcastQueued(state.ocean)) const DFIToken = useSelector((state: RootState) => DFITokenSelector(state.wallet)) const DFIUtxo = useSelector((state: RootState) => DFIUtxoSelector(state.wallet)) const reservedDfi = 0.1 const [bottomSheetScreen, setBottomSheetScreen] = useState<BottomSheetNavScreen[]>([]) const [fee, setFee] = useState<BigNumber>(new BigNumber(0.0001)) const [selectedTokenA, setSelectedTokenA] = useState<OwnedTokenState>() const [selectedTokenB, setSelectedTokenB] = useState<TokenState>() const [selectedPoolPairs, setSelectedPoolPairs] = useState<PoolPairData[]>() const [priceRates, setPriceRates] = useState<PriceRateProps[]>() const [slippage, setSlippage] = useState<number>(0.03) const [allowedSwapFromTokens, setAllowedSwapFromTokens] = useState<BottomSheetToken[]>() const [allowedSwapToTokens, setAllowedSwapToTokens] = useState<BottomSheetToken[]>() const [allTokens, setAllTokens] = useState<TokenState[]>() const [isModalDisplayed, setIsModalDisplayed] = useState(false) const [isTokenSelectDisabled, setIsTokenSelectDisabled] = useState(false) const containerRef = useRef(null) const bottomSheetRef = useRef<BottomSheetModal>(null) const expandModal = useCallback(() => { if (Platform.OS === 'web') { setIsModalDisplayed(true) } else { bottomSheetRef.current?.present() } }, []) const dismissModal = useCallback(() => { if (Platform.OS === 'web') { setIsModalDisplayed(false) } else { bottomSheetRef.current?.close() } }, []) // component UI state const { control, formState, setValue, trigger, watch } = useForm<{ tokenA: string tokenB: string }>({ mode: 'onChange' }) const { tokenA, tokenB } = watch() const tokenAFormAmount = tokenA === '' ? undefined : tokenA const tokenBFormAmount = tokenB === '' ? undefined : tokenB const { isConversionRequired, conversionAmount } = useConversion({ inputToken: { type: selectedTokenA?.id === '0_unified' ? 'token' : 'others', amount: new BigNumber(tokenA) }, deps: [tokenA, JSON.stringify(tokens)] }) const getMaxAmount = (token: OwnedTokenState): string => { if (token.id !== '0_unified') { return new BigNumber(token.amount).toFixed(8) } const maxAmount = new BigNumber(token.amount).minus(reservedDfi) return maxAmount.isLessThanOrEqualTo(0) ? new BigNumber(0).toFixed(8) : maxAmount.toFixed(8) } const onTokenSelect = ({ tokenId, reserve, token: { displaySymbol, symbol } }: BottomSheetToken, direction: 'FROM' | 'TO'): void => { const ownedToken = tokens?.find(token => token.id === tokenId) const derivedToken = { id: ownedToken !== undefined ? ownedToken.id : tokenId, // retrieve unified token if selected symbol, displaySymbol, reserve: reserve !== undefined ? new BigNumber(reserve).toFixed(8) : new BigNumber(0).toFixed(8) } if (direction === 'FROM') { setSelectedTokenA({ ...derivedToken, amount: ownedToken === undefined ? '0' : ownedToken.amount }) if (selectedTokenB !== undefined) { setSelectedTokenB(undefined) setValue('tokenA', '') setValue('tokenB', '') } } else { setSelectedTokenB(derivedToken) } } const onBottomSheetSelect = ({ direction }: { direction: 'FROM' | 'TO' }): void => { setBottomSheetScreen([ { stackScreenName: 'TokenList', component: BottomSheetTokenList({ tokens: direction === 'FROM' ? allowedSwapFromTokens ?? [] : allowedSwapToTokens ?? [], headerLabel: translate('screens/CompositeSwapScreen', direction === 'FROM' ? 'Choose token for swap' : 'Choose token to swap'), onCloseButtonPress: () => dismissModal(), onTokenPress: (item): void => { onTokenSelect(item, direction) dismissModal() } }), option: { header: () => null } }]) expandModal() } useEffect(() => { client.fee.estimate() .then((f) => setFee(new BigNumber(f))) .catch(logger.error) }, []) useEffect(() => { if (route.params.pair?.id === undefined) { return } setIsTokenSelectDisabled(true) const pair = pairs.find((pair) => pair.data.id === route.params.pair?.id) if (pair !== undefined) { onTokenSelect({ tokenId: pair.data.tokenA.id, available: new BigNumber(pair.data.tokenA.reserve), token: { displaySymbol: pair.data.tokenA.displaySymbol, symbol: pair.data.tokenA.symbol, name: '' // not available in API }, reserve: pair.data.tokenA.reserve }, 'FROM') onTokenSelect({ tokenId: pair.data.tokenB.id, available: new BigNumber(pair.data.tokenB.reserve), token: { displaySymbol: pair.data.tokenB.displaySymbol, symbol: pair.data.tokenB.symbol, name: '' // not available in API }, reserve: pair.data.tokenB.reserve }, 'TO') } }, [route.params.pair]) useEffect(() => { if (pairs === undefined) { return } const tokens = pairs.reduce((tokensInPair: TokenState[], pair: DexItem): TokenState[] => { const hasTokenA = tokensInPair.some(token => pair.data.tokenA.id === token.id) const hasTokenB = tokensInPair.some(token => pair.data.tokenB.id === token.id) const tokensToAdd: TokenState[] = [] if (!hasTokenA) { tokensToAdd.push(pair.data.tokenA) } if (!hasTokenB) { tokensToAdd.push(pair.data.tokenB) } return [...tokensInPair, ...tokensToAdd] }, []) setAllTokens(tokens) }, [pairs]) useEffect(() => { if (allTokens === undefined) { return } const swappableFromTokens: BottomSheetToken[] = allTokens .map((token) => { const tokenId = token.id === '0' ? '0_unified' : token.id const ownedToken = tokens.find(t => t.id === tokenId) return { tokenId: tokenId, available: new BigNumber(ownedToken === undefined ? 0 : ownedToken.amount), token: { displaySymbol: token.displaySymbol, name: '', // not available in API, symbol: token.symbol }, reserve: token.reserve } }).sort((a, b) => b.available.minus(a.available).toNumber()) setAllowedSwapFromTokens(swappableFromTokens) if (selectedTokenA !== undefined && allTokens !== undefined) { setAllowedSwapToTokens(getAllPossibleSwapToTokens(allTokens, pairs, selectedTokenA.id === '0_unified' ? '0' : selectedTokenA.id)) } }, [tokens, selectedTokenA, selectedTokenB]) useEffect(() => { if (selectedTokenA !== undefined && selectedTokenB !== undefined) { const graph: GraphProps[] = pairs.map(pair => { return { pairId: pair.data.id, a: pair.data.tokenA.symbol, b: pair.data.tokenB.symbol } }) // TODO - Handle cheapest path with N hops, currently this logic finds the shortest path const { path } = findPath(graph, selectedTokenA.symbol, selectedTokenB.symbol) const poolPairs = path.reduce((poolPairs: PoolPairData[], token, index): PoolPairData[] => { const pair = pairs.find(pair => checkIfPair({ a: pair.data.tokenA.symbol, b: pair.data.tokenB.symbol }, token, path[index + 1])) if ((pair == null) || index === path.length) { return poolPairs } return [...poolPairs, pair.data] }, []) setSelectedPoolPairs(poolPairs) } }, [selectedTokenA, selectedTokenB]) useEffect(() => { if (selectedTokenA !== undefined && selectedTokenB !== undefined && selectedPoolPairs !== undefined && tokenAFormAmount !== undefined) { const { aToBPrice, bToAPrice, estimated } = calculatePriceRates(selectedTokenA, selectedPoolPairs, tokenAFormAmount) setPriceRates([{ label: translate('screens/CompositeSwapScreen', '{{tokenA}} price in {{tokenB}}', { tokenA: selectedTokenA.displaySymbol, tokenB: selectedTokenB.displaySymbol }), value: aToBPrice.toFixed(8), aSymbol: selectedTokenA.displaySymbol, bSymbol: selectedTokenB.displaySymbol }, { label: translate('screens/CompositeSwapScreen', '{{tokenB}} price in {{tokenA}}', { tokenA: selectedTokenA.displaySymbol, tokenB: selectedTokenB.displaySymbol }), value: bToAPrice.toFixed(8), aSymbol: selectedTokenB.displaySymbol, bSymbol: selectedTokenA.displaySymbol } ]) setValue('tokenB', estimated) } }, [selectedPoolPairs, tokenAFormAmount]) const navigateToConfirmScreen = (): void => { if (selectedPoolPairs === undefined || selectedTokenA === undefined || selectedTokenB === undefined || priceRates === undefined || tokenAFormAmount === undefined || tokenBFormAmount === undefined) { return } const ownedTokenB = tokens.find(token => token.id === selectedTokenB.id) navigation.navigate('ConfirmCompositeSwapScreen', { fee, pairs: selectedPoolPairs, priceRates, slippage, swap: { tokenTo: selectedTokenB, tokenFrom: selectedTokenA, amountFrom: new BigNumber(tokenAFormAmount), amountTo: new BigNumber(tokenBFormAmount) }, tokenA: selectedTokenA, tokenB: ownedTokenB !== undefined ? { ...selectedTokenB, amount: ownedTokenB.amount } : selectedTokenB, ...(isConversionRequired && { conversion: { isConversionRequired, DFIToken, DFIUtxo, conversionAmount } }) }) } const onSubmit = async (): Promise<void> => { if (hasPendingJob || hasPendingBroadcastJob) { return } if (isConversionRequired) { queueConvertTransaction({ mode: 'utxosToAccount', amount: conversionAmount }, dispatch, () => { navigateToConfirmScreen() }, logger) } else { navigateToConfirmScreen() } } const onTokenSwitch = async (): Promise<void> => { if (selectedTokenA !== undefined && selectedTokenB !== undefined) { const tokenBId = selectedTokenB.id === '0' ? '0_unified' : selectedTokenB.id const ownedTokenB = tokens.find(token => token.id === tokenBId) setSelectedTokenA({ ...selectedTokenB, id: tokenBId, amount: ownedTokenB !== undefined ? ownedTokenB.amount : '0' }) setSelectedTokenB(selectedTokenA) setValue('tokenA', '') await trigger('tokenA') setValue('tokenB', '') await trigger('tokenB') } } return ( <View style={tailwind('h-full')} ref={containerRef}> <ThemedScrollView> { (allowedSwapFromTokens !== undefined && allowedSwapFromTokens?.length > 0) && ( <ThemedText dark={tailwind('text-gray-50')} light={tailwind('text-gray-900')} style={tailwind('text-xl font-semibold m-4 mb-0')} > {translate('screens/CompositeSwapScreen', 'Swap tokens')} </ThemedText> ) } <View style={tailwind(['flex flex-row mt-3 mx-2', { hidden: allowedSwapFromTokens?.length === 0 }])}> <TokenSelection label={translate('screens/CompositeSwapScreen', 'FROM')} symbol={selectedTokenA?.displaySymbol} onPress={() => onBottomSheetSelect({ direction: 'FROM' })} disabled={isTokenSelectDisabled || allowedSwapFromTokens === undefined || allowedSwapFromTokens?.length === 0} /> <TokenSelection label={translate('screens/CompositeSwapScreen', 'TO')} symbol={selectedTokenB?.displaySymbol} onPress={() => onBottomSheetSelect({ direction: 'TO' })} disabled={isTokenSelectDisabled || allowedSwapToTokens === undefined || allowedSwapToTokens?.length === 0} /> </View> {(selectedTokenA === undefined || selectedTokenB === undefined) && allowedSwapFromTokens?.length !== 0 && <ThemedText dark={tailwind('text-dfxgray-400')} light={tailwind('text-dfxgray-500')} style={tailwind('mt-10 text-center px-4')} testID='swap_instructions' > {translate('screens/CompositeSwapScreen', 'Select tokens you want to swap to get started')} </ThemedText>} {selectedTokenA !== undefined && selectedTokenB !== undefined && <> <View style={tailwind('mt-10 mx-4')}> <TokenRow control={control} controlName='tokenA' isDisabled={false} title={translate('screens/CompositeSwapScreen', 'How much {{token}} do you want to swap?', { token: selectedTokenA.displaySymbol })} maxAmount={getMaxAmount(selectedTokenA)} enableMaxButton onChangeFromAmount={async (amount) => { amount = isNaN(+amount) ? '0' : amount setValue('tokenA', amount) await trigger('tokenA') }} token={selectedTokenA} /> <InputHelperText testID='text_balance_amount' label={`${translate('screens/CompositeSwapScreen', 'You have')} `} content={getMaxAmount(selectedTokenA)} suffix={` ${selectedTokenA.displaySymbol}`} /> {selectedTokenA.id === '0_unified' && <ReservedDFIInfoText />} <View style={tailwind(['flex flex-row items-center', { 'mb-4': isConversionRequired }])}> <TouchableOpacity onPress={onTokenSwitch} testID='switch_button' > <ThemedIcon name='swap-vert' size={24} iconType='MaterialIcons' style={tailwind('w-8 mx-2 mt-2.5')} dark={tailwind('text-dfxred-500')} light={tailwind('text-primary-500')} /> </TouchableOpacity> <View style={tailwind('flex-1')}> <TokenRow control={control} controlName='tokenB' isDisabled token={selectedTokenB} enableMaxButton={false} /> </View> </View> {isConversionRequired && <ConversionInfoText />} </View> <SlippageTolerance setSlippage={(amount) => setSlippage(amount)} slippage={slippage} /> </>} {(selectedTokenB !== undefined && selectedTokenA !== undefined && priceRates !== undefined && tokenAFormAmount !== undefined && tokenBFormAmount !== undefined) && <> <PricesSection priceRates={priceRates} sectionTitle='PRICES' /> <TransactionDetailsSection conversionAmount={conversionAmount} estimatedAmount={tokenBFormAmount} fee={fee} isConversionRequired={isConversionRequired} slippage={slippage} tokenA={selectedTokenA} tokenB={selectedTokenB} /> </>} {selectedTokenA !== undefined && selectedTokenB !== undefined && ( <Button disabled={!formState.isValid || hasPendingJob || hasPendingBroadcastJob} label={translate('screens/CompositeSwapScreen', 'CONTINUE')} onPress={onSubmit} testID='button_submit' title='CONTINUE' margin='mx-4 mb-2 mt-8' />)} {formState.isValid && selectedTokenA !== undefined && selectedTokenB !== undefined && <ThemedText testID='transaction_details_hint_text' light={tailwind('text-gray-600')} dark={tailwind('text-dfxgray-300')} style={tailwind('pb-8 px-4 text-sm text-center')} > {isConversionRequired ? translate('screens/CompositeSwapScreen', 'Authorize transaction in the next screen to convert') : translate('screens/CompositeSwapScreen', 'Review and confirm transaction in the next screen')} </ThemedText>} {Platform.OS === 'web' && ( <BottomSheetWebWithNav modalRef={containerRef} screenList={bottomSheetScreen} isModalDisplayed={isModalDisplayed} /> )} {Platform.OS !== 'web' && ( <BottomSheetWithNav modalRef={bottomSheetRef} screenList={bottomSheetScreen} /> )} </ThemedScrollView> </View> ) } function TokenSelection (props: { symbol?: string, label: string, onPress: () => void, disabled: boolean }): JSX.Element { const Icon = getNativeIcon(props.symbol ?? '') return ( <View style={[tailwind('flex-grow mx-2'), { flexBasis: 0 }]}> <ThemedText dark={tailwind('text-dfxgray-400')} light={tailwind('text-dfxgray-500')} style={tailwind('text-xs pb-1')} >{props.label} </ThemedText> <ThemedTouchableOpacity onPress={props.onPress} testID={`token_select_button_${props.label}`} dark={tailwind('bg-dfxblue-800 border-dfxblue-900')} light={tailwind({ 'bg-gray-200 border-0': props.disabled, 'bg-white border-gray-300': !props.disabled })} style={tailwind('flex flex-row items-center border rounded p-2')} disabled={props.disabled} > {props.symbol === undefined && <ThemedText dark={tailwind({ 'text-dfxgray-500': !props.disabled, 'text-dfxblue-900': props.disabled })} light={tailwind('text-dfxgray-500')} style={tailwind('text-sm leading-6')} > {translate('screens/CompositeSwapScreen', 'Select token')} </ThemedText>} {props.symbol !== undefined && <> <Icon testID='tokenA_icon' height={17} width={17} /> <ThemedText style={tailwind('ml-2')} dark={tailwind({ 'text-white': !props.disabled, 'text-dfxgray-400': props.disabled })} light={tailwind({ 'text-gray-900': !props.disabled, 'text-gray-500': props.disabled })} >{props.symbol} </ThemedText> </>} <ThemedIcon iconType='MaterialIcons' name='unfold-more' size={20} dark={tailwind({ 'text-dfxred-500': !props.disabled, 'text-transparent': props.disabled })} light={tailwind({ 'text-primary-500': !props.disabled, 'text-gray-500': props.disabled })} style={[tailwind('text-center mt-0.5'), { marginLeft: 'auto' }]} /> </ThemedTouchableOpacity> </View> ) } function TransactionDetailsSection ({ conversionAmount, estimatedAmount, fee, isConversionRequired, slippage, tokenA, tokenB }: { conversionAmount: BigNumber, estimatedAmount: string, fee: BigNumber, isConversionRequired: boolean, slippage: number, tokenA: OwnedTokenState, tokenB: TokenState }): JSX.Element { return ( <> <ThemedSectionTitle testID='title_add_detail' text={translate('screens/CompositeSwapScreen', 'TRANSACTION DETAILS')} style={tailwind('px-4 pt-6 pb-2 text-xs text-dfxgray-500 font-medium')} /> {isConversionRequired && <NumberRow lhs={translate('screens/CompositeSwapScreen', 'Amount to be converted')} rhs={{ testID: 'amount_to_convert', value: conversionAmount.toFixed(8), suffixType: 'text', suffix: tokenA.displaySymbol }} />} <NumberRow lhs={translate('screens/CompositeSwapScreen', 'Estimated to receive')} rhs={{ value: estimatedAmount, suffixType: 'text', suffix: tokenB.displaySymbol, testID: 'estimated_to_receive' }} textStyle={tailwind('text-sm font-normal')} /> <TextRow lhs={translate('screens/CompositeSwapScreen', 'Slippage Tolerance')} rhs={{ value: `${new BigNumber(slippage).times(100).toFixed(2)}%`, testID: 'slippage_tolerance' }} textStyle={tailwind('text-sm font-normal')} /> <FeeInfoRow type='ESTIMATED_FEE' value={fee.toFixed(8)} testID='text_fee' suffix='DFI' /> </> ) } function calculatePriceRates (tokenA: OwnedTokenState, pairs: PoolPairData[], amount: string): { aToBPrice: BigNumber, bToAPrice: BigNumber, estimated: string } { const slippage = new BigNumber(1).minus(new BigNumber(amount).div(tokenA.reserve)) let lastTokenBySymbol = tokenA.symbol let lastAmount = new BigNumber(amount) const priceRates = pairs.reduce((priceRates, pair): { aToBPrice: BigNumber, bToAPrice: BigNumber, estimated: BigNumber } => { const [reserveA, reserveB] = pair.tokenB.symbol === lastTokenBySymbol ? [pair.tokenB.reserve, pair.tokenA.reserve] : [pair.tokenA.reserve, pair.tokenB.reserve] const [tokenASymbol, tokenBSymbol] = pair.tokenB.symbol === lastTokenBySymbol ? [pair.tokenB.symbol, pair.tokenA.symbol] : [pair.tokenA.symbol, pair.tokenB.symbol] const priceRateA = new BigNumber(reserveB).div(reserveA) const priceRateB = new BigNumber(reserveA).div(reserveB) // To sequentially convert the token from its last token const aToBPrice = tokenASymbol === lastTokenBySymbol ? priceRateA : priceRateB const bToAPrice = tokenASymbol === lastTokenBySymbol ? priceRateB : priceRateA const estimated = new BigNumber(lastAmount).times(aToBPrice) lastAmount = estimated lastTokenBySymbol = tokenBSymbol return { aToBPrice: priceRates.aToBPrice.times(aToBPrice), bToAPrice: priceRates.bToAPrice.times(bToAPrice), estimated } }, { aToBPrice: new BigNumber(1), bToAPrice: new BigNumber(1), estimated: new BigNumber(0) }) return { aToBPrice: priceRates.aToBPrice, bToAPrice: priceRates.bToAPrice, estimated: priceRates.estimated.times(slippage).toFixed(8) } } interface TokenForm { control: Control<{ tokenA: string, tokenB: string }> controlName: 'tokenA' | 'tokenB' token: TokenState | OwnedTokenState enableMaxButton: boolean maxAmount?: string onChangeFromAmount?: (amount: string) => void title?: string isDisabled: boolean } function TokenRow (form: TokenForm): JSX.Element { const { token, control, onChangeFromAmount, title, controlName, enableMaxButton, isDisabled, maxAmount } = form const Icon = getNativeIcon(token.displaySymbol) const rules: { required: boolean, pattern: RegExp, validate: any, max?: string } = { required: true, max: maxAmount, pattern: /^\d*\.?\d*$/, validate: { greaterThanZero: (value: string) => new BigNumber(value !== undefined && value !== '' ? value : 0).isGreaterThan(0) } } const defaultValue = '' return ( <Controller control={control} defaultValue={defaultValue} name={controlName} render={({ field: { onChange, value } }) => ( <ThemedView dark={tailwind('bg-transparent')} light={tailwind('bg-transparent')} style={tailwind('flex-row flex-grow')} > <WalletTextInput autoCapitalize='none' editable={!isDisabled} onChange={(e) => { if (!isDisabled) { if (onChangeFromAmount !== undefined) { onChangeFromAmount(e.nativeEvent.text) } else { onChange(e) } } }} placeholder={isDisabled ? undefined : translate('screens/CompositeSwapScreen', 'Enter an amount')} style={tailwind('flex-grow w-2/5')} testID={`text_input_${controlName}`} value={value} displayClearButton={(value !== defaultValue) && !isDisabled} onClearButtonPress={() => onChangeFromAmount?.(defaultValue)} title={title} inputType='numeric' > { (enableMaxButton && onChangeFromAmount !== undefined) && ( <> <SetAmountButton amount={new BigNumber(maxAmount ?? '0')} onPress={onChangeFromAmount} type={AmountButtonTypes.half} /> <SetAmountButton amount={new BigNumber(maxAmount ?? '0')} onPress={onChangeFromAmount} type={AmountButtonTypes.max} /> </> ) } { !enableMaxButton && ( <> <Icon height={20} width={20} /> <ThemedText style={tailwind('pl-2')}> {token.displaySymbol} </ThemedText> </> ) } </WalletTextInput> </ThemedView> )} rules={rules} /> ) } /** * This function finds all the possible adjacent vertices of an undirected graph in the context of tokens and pairs * @param tokens * @param pairs * @param tokenFrom */ function getAllPossibleSwapToTokens (allTokens: TokenState[], pairs: DexItem[], tokenFrom: string): BottomSheetToken[] { const graph: GraphProps[] = pairs.map(pair => { const graphItem: GraphProps = { pairId: pair.data.id, a: pair.data.tokenA.id, b: pair.data.tokenB.id } return graphItem }) const reachableNodes: string[] = [] const reachableNodeIds = new Set<string>([]) // Use Sets to reduce checks if item is unique const visitedNodes = new Set<string>([]) const nodesToVisit = new Set<string>([tokenFrom]) while (nodesToVisit.size !== 0) { const [token] = nodesToVisit // first item in a set const adjacentNodes = getAdjacentNodes(token, graph) if (adjacentNodes.length !== 0) { adjacentNodes.forEach(node => { if (!reachableNodeIds.has(node)) { reachableNodes.push(node) } // If the token hasn't been visited, flag for visit. if (!visitedNodes.has(node)) { nodesToVisit.add(node) } reachableNodeIds.add(node) }) } visitedNodes.add(token) nodesToVisit.delete(token) } return reachableNodes.reduce((tokens: BottomSheetToken[], node: string): BottomSheetToken[] => { const token = allTokens.find(token => token.id === node) if (token !== undefined && node !== tokenFrom) { return [ ...tokens, { tokenId: token.id, available: new BigNumber(token.reserve), token: { name: '', // Not available in API displaySymbol: token.displaySymbol, symbol: token.symbol }, reserve: token.reserve } ] } return tokens }, []) }
FullAriza/wallet
mobile-app/app/screens/AppNavigator/screens/Loans/components/VaultStatusTag.tsx
import { ThemedText, ThemedView } from '@components/themed' import { tailwind } from '@tailwind' import { translate } from '@translations' import React from 'react' import { LoanVaultState } from '@defichain/whale-api-client/dist/api/loan' import BigNumber from 'bignumber.js' import { CollateralizationRatioStats, useCollateralRatioStats } from '@screens/AppNavigator/screens/Loans/hooks/CollateralizationRatio' export enum VaultStatus { Active = 'ACTIVE', Healthy = 'HEALTHY', AtRisk = 'AT RISK', Halted = 'HALTED', NearLiquidation = 'AT RISK', Liquidated = 'IN LIQUIDATION', Unknown = 'UNKNOWN' } export interface VaultHealthItem { vaultStats: CollateralizationRatioStats status: VaultStatus } export function useVaultStatus (status: LoanVaultState, collateralRatio: BigNumber, minColRatio: BigNumber, totalLoanAmount: BigNumber): VaultHealthItem { const colRatio = collateralRatio.gte(0) ? collateralRatio : new BigNumber(0) const stats = useCollateralRatioStats({ colRatio, minColRatio, totalLoanAmount }) let vaultStatus: VaultStatus if (status === LoanVaultState.FROZEN) { vaultStatus = VaultStatus.Halted } else if (status === LoanVaultState.UNKNOWN) { vaultStatus = VaultStatus.Unknown } else if (status === LoanVaultState.IN_LIQUIDATION) { vaultStatus = VaultStatus.Liquidated } else if (stats.isInLiquidation) { vaultStatus = VaultStatus.NearLiquidation } else if (stats.isAtRisk) { vaultStatus = VaultStatus.AtRisk } else if (stats.isHealthy) { vaultStatus = VaultStatus.Healthy } else { vaultStatus = VaultStatus.Active } return { status: vaultStatus, vaultStats: stats } } export function VaultStatusTag ({ status, vaultStats }: VaultHealthItem): JSX.Element { if (status === VaultStatus.Unknown) { return <></> } return ( <ThemedView light={tailwind( { 'bg-blue-100': status === VaultStatus.Active, 'bg-success-100': status === VaultStatus.Healthy, 'bg-warning-100': status === VaultStatus.AtRisk, 'bg-gray-100': status === VaultStatus.Halted, 'bg-error-100': status === VaultStatus.Liquidated || (status === VaultStatus.NearLiquidation && vaultStats.isInLiquidation) } )} dark={tailwind( { 'bg-dfxblue-600': status === VaultStatus.Active, 'bg-darksuccess-100': status === VaultStatus.Healthy, 'bg-dfxyellow-500': status === VaultStatus.AtRisk, 'bg-gray-100': status === VaultStatus.Halted, 'bg-dfxpink-500': status === VaultStatus.Liquidated || (status === VaultStatus.NearLiquidation && vaultStats.isInLiquidation) } )} style={tailwind('flex flex-row items-center')} > <ThemedText light={tailwind( { 'text-blue-500': status === VaultStatus.Active, 'text-success-500': status === VaultStatus.Healthy, 'text-warning-500': status === VaultStatus.AtRisk, 'text-gray-400': status === VaultStatus.Halted, 'text-error-500': status === VaultStatus.Liquidated || (status === VaultStatus.NearLiquidation && vaultStats.isInLiquidation) } )} dark={tailwind( { 'text-dfxblue-500': status === VaultStatus.Active, 'text-darksuccess-500': status === VaultStatus.Healthy, 'text-dfxyellow-300': status === VaultStatus.AtRisk, 'text-gray-500': status === VaultStatus.Halted, 'text-dfxpink-300': status === VaultStatus.Liquidated || (status === VaultStatus.NearLiquidation && vaultStats.isInLiquidation) } )} style={tailwind('px-2 py-0.5 font-medium text-xs')} > {translate('components/VaultCard', status)} </ThemedText> </ThemedView> ) }
FullAriza/wallet
website/src/pages/api/v0/announcements.ts
import { NextApiRequest, NextApiResponse } from 'next' import { AnnouncementData } from '@shared-types/website' import Cors from 'cors' import { runMiddleware } from '../../../utils/middleware' export const cors = Cors({ methods: ['GET', 'HEAD'] }) export default async function handle (req: NextApiRequest, res: NextApiResponse<AnnouncementData[]>): Promise<void> { await runMiddleware(req, res, cors) res.json([{ lang: { en: 'Update to the latest app version to access Decentralized Loan.', de: 'Aktualisiere auf die neueste Version der App, um Zugang zu dezentralen Darlehen zu erhalten.', 'zh-Hans': '请更新至最新版本应用程式使用去中心化贷款。', 'zh-Hant': '請更新至最新版本應用程式使用去中心化貸款。' }, version: '<0.17.0' }, { lang: { en: 'Decentralized loan is now available on the Light Wallet app.', de: 'Dezentrale Darlehen sind jetzt in der Light Wallet App verfügbar.', 'zh-Hans': '去中心化贷款已在清钱包 Light Wallet 正式推出', 'zh-Hant': '去中心化貸款已在清錢包 Light Wallet 正式推出' }, version: '>=0.17.0' }]) }
FullAriza/wallet
website/src/pages/api/v0/settings/flags.ts
import { NextApiRequest, NextApiResponse } from 'next' import { FeatureFlag } from '@shared-types/website' import Cors from 'cors' import { runMiddleware } from '../../../../utils/middleware' import { EnvironmentNetwork } from '../../../../../../shared/environment' export const cors = Cors({ methods: ['GET', 'HEAD'] }) export default async function handle (req: NextApiRequest, res: NextApiResponse<FeatureFlag[]>): Promise<void> { await runMiddleware(req, res, cors) res.json([{ id: 'loan', name: 'Loans', stage: 'public', version: '>=0.17.0', description: 'Browse loan tokens provided by DeFiChain', networks: [EnvironmentNetwork.MainNet, EnvironmentNetwork.TestNet, EnvironmentNetwork.RemotePlayground, EnvironmentNetwork.LocalPlayground], platforms: ['ios', 'android', 'web'] }]) }
FullAriza/wallet
mobile-app/app/screens/PlaygroundNavigator/sections/PlaygroundUTXO.tsx
import React, { useEffect, useState } from 'react' import { useDispatch } from 'react-redux' import { View } from '@components/index' import { usePlaygroundContext } from '@contexts/PlaygroundContext' import { useWalletContext } from '@shared-contexts/WalletContext' import { useWhaleApiClient } from '@shared-contexts/WhaleContext' import { fetchTokens } from '@hooks/wallet/TokensAPI' import { PlaygroundAction } from '../components/PlaygroundAction' import { PlaygroundTitle } from '../components/PlaygroundTitle' import { useLogger } from '@shared-contexts/NativeLoggingProvider' export function PlaygroundUTXO (): JSX.Element { const logger = useLogger() const { wallet } = useWalletContext() const whaleApiClient = useWhaleApiClient() const dispatch = useDispatch() const { api, rpc } = usePlaygroundContext() const [status, setStatus] = useState<string>('loading') useEffect(() => { api.wallet.balances().then(() => { setStatus('online') }).catch(() => { setStatus('error') }) }, [wallet]) return ( <View> <PlaygroundTitle status={{ online: status === 'online', loading: status === 'loading', error: status === 'error' }} title='UTXO' /> {status === 'online' ? ( <> <PlaygroundAction onPress={async () => { const address = await wallet.get(0).getAddress() await rpc.wallet.sendToAddress(address, 10) }} testID='playground_wallet_top_up' title='Top up 10 DFI UTXO to Wallet' /> <PlaygroundAction onPress={async () => { const address = await wallet.get(0).getAddress() fetchTokens(whaleApiClient, address, dispatch, logger) }} testID='playground_wallet_fetch_balances' title='Fetch Balances' /> </> ) : null} </View> ) }
FullAriza/wallet
mobile-app/app/screens/AppNavigator/screens/Settings/screens/KnowledgeBaseScreen.tsx
import * as React from 'react' import { ThemedIcon, ThemedScrollView, ThemedSectionTitle, ThemedText, ThemedTouchableOpacity } from '@components/themed' import { StackScreenProps } from '@react-navigation/stack' import { tailwind } from '@tailwind' import { translate } from '@translations' import { SettingsParamList } from '../SettingsNavigator' import { useFeatureFlagContext } from '@contexts/FeatureFlagContext' type Props = StackScreenProps<SettingsParamList, 'KnowledgeBaseScreen'> export function KnowledgeBaseScreen ({ navigation }: Props): JSX.Element { const { isFeatureAvailable } = useFeatureFlagContext() const knowledgeBaseItems = [ { label: 'Recovery words', testID: 'recovery_words_faq', onPress: () => navigation.navigate('RecoveryWordsFaq') }, { label: 'Passcode', testID: 'passcode_faq', onPress: () => navigation.navigate('PasscodeFaq') }, { label: 'UTXO vs Token', testID: 'utxo_and_token_faq', onPress: () => navigation.navigate('TokensVsUtxo') } ] if (isFeatureAvailable('loan')) { knowledgeBaseItems.push({ label: 'Loans', testID: 'loans_faq', onPress: () => navigation.navigate('LoansFaq') }) } return ( <ThemedScrollView style={tailwind('flex-1 pb-8')} testID='knowledge_base_screen' > <ThemedSectionTitle testID='knowledge_base_title' text={translate('screens/KnowledgeBase', 'LEARN ABOUT')} /> {knowledgeBaseItems.map((each) => <NavigateItemRow key={each.label} {...each} /> )} </ThemedScrollView> ) } function NavigateItemRow ({ testID, label, onPress }: { testID: string, label: string, onPress: () => void }): JSX.Element { return ( <ThemedTouchableOpacity onPress={onPress} style={tailwind('flex p-4 pr-2 flex-row items-center justify-between')} testID={testID} > <ThemedText style={tailwind('font-medium')}> {translate('screens/KnowledgeBase', label)} </ThemedText> <ThemedIcon iconType='MaterialIcons' name='chevron-right' size={24} /> </ThemedTouchableOpacity> ) }
FullAriza/wallet
mobile-app/app/screens/AppNavigator/screens/Loans/hooks/MaxLoanAmount.ts
<reponame>FullAriza/wallet import { BigNumber } from '@defichain/jellyfish-json' interface useMaxLoanAmountProps { totalCollateralValue: BigNumber totalLoanValue: BigNumber minColRatio: BigNumber vaultInterest: BigNumber loanInterest: BigNumber loanActivePrice: BigNumber } export function useMaxLoanAmount ({ totalCollateralValue, totalLoanValue, minColRatio, vaultInterest, loanInterest, loanActivePrice }: useMaxLoanAmountProps): BigNumber { return totalCollateralValue.dividedBy(minColRatio.dividedBy(100)).minus(totalLoanValue).dividedBy( loanActivePrice.multipliedBy(vaultInterest.plus(loanInterest).dividedBy(100).plus(1)) ) }
FullAriza/wallet
mobile-app/app/screens/AppNavigator/screens/Dex/DexAddLiquidity.tsx
<reponame>FullAriza/wallet import { InputHelperText } from '@components/InputHelperText' import { WalletTextInput } from '@components/WalletTextInput' import { PoolPairData } from '@defichain/whale-api-client/dist/api/poolpairs' import { NavigationProp, useNavigation } from '@react-navigation/native' import { StackScreenProps } from '@react-navigation/stack' import BigNumber from 'bignumber.js' import React, { useCallback, useEffect, useState } from 'react' import { View } from '@components' import { Button } from '@components/Button' import { NumberRow } from '@components/NumberRow' import { AmountButtonTypes, SetAmountButton } from '@components/SetAmountButton' import { ThemedScrollView, ThemedSectionTitle, ThemedText, ThemedView } from '@components/themed' import { usePoolPairsAPI } from '@hooks/wallet/PoolPairsAPI' import { useTokensAPI } from '@hooks/wallet/TokensAPI' import { tailwind } from '@tailwind' import { translate } from '@translations' import { DexParamList } from './DexNavigator' import { FeeInfoRow } from '@components/FeeInfoRow' import { useWhaleApiClient } from '@shared-contexts/WhaleContext' import { DFITokenSelector, DFIUtxoSelector, WalletToken } from '@store/wallet' import { ConversionInfoText } from '@components/ConversionInfoText' import { useDispatch, useSelector } from 'react-redux' import { RootState } from '@store' import { hasTxQueued } from '@store/transaction_queue' import { hasTxQueued as hasBroadcastQueued } from '@store/ocean' import { ReservedDFIInfoText } from '@components/ReservedDFIInfoText' import { queueConvertTransaction, useConversion } from '@hooks/wallet/Conversion' import { useLogger } from '@shared-contexts/NativeLoggingProvider' type Props = StackScreenProps<DexParamList, 'AddLiquidity'> type EditingAmount = 'primary' | 'secondary' interface ExtPoolPairData extends PoolPairData { aSymbol: string bSymbol: string aToBRate: BigNumber bToARate: BigNumber } export function AddLiquidityScreen (props: Props): JSX.Element { const logger = useLogger() const pairs = usePoolPairsAPI() const navigation = useNavigation<NavigationProp<DexParamList>>() const tokens = useTokensAPI() const client = useWhaleApiClient() const dispatch = useDispatch() const DFIToken = useSelector((state: RootState) => DFITokenSelector(state.wallet)) const DFIUtxo = useSelector((state: RootState) => DFIUtxoSelector(state.wallet)) const hasPendingJob = useSelector((state: RootState) => hasTxQueued(state.transactionQueue)) const hasPendingBroadcastJob = useSelector((state: RootState) => hasBroadcastQueued(state.ocean)) // this component UI state const [tokenAAmount, setTokenAAmount] = useState<string>('') const [tokenBAmount, setTokenBAmount] = useState<string>('') const [sharePercentage, setSharePercentage] = useState<BigNumber>(new BigNumber(0)) const [canContinue, setCanContinue] = useState(false) const [fee, setFee] = useState<BigNumber>(new BigNumber(0.0001)) // derived from props const [balanceA, setBalanceA] = useState(new BigNumber(0)) const [balanceB, setBalanceB] = useState(new BigNumber(0)) const [pair, setPair] = useState<ExtPoolPairData>() const { isConversionRequired, conversionAmount } = useConversion({ inputToken: { type: 'token', amount: new BigNumber(pair?.tokenA.id === '0' ? tokenAAmount : tokenBAmount) }, deps: [pair, tokenAAmount, tokenBAmount, balanceA, balanceB] }) const buildSummary = useCallback((ref: EditingAmount, amountString: string): void => { const refAmount = amountString.length === 0 || isNaN(+amountString) ? new BigNumber(0) : new BigNumber(amountString) if (pair === undefined) { return } if (ref === 'primary') { setTokenAAmount(amountString) setTokenBAmount(refAmount.times(pair.aToBRate).toFixed(8)) setSharePercentage(refAmount.div(pair.tokenA.reserve)) } else { setTokenBAmount(amountString) setTokenAAmount(refAmount.times(pair.bToARate).toFixed(8)) setSharePercentage(refAmount.div(pair.tokenB.reserve)) } }, [pair]) const getAddressTokenById = (poolpairTokenId: string): WalletToken | undefined => { return tokens.find(token => { if (poolpairTokenId === '0' || poolpairTokenId === '0_utxo') { return token.id === '0_unified' } return token.id === poolpairTokenId }) } async function onSubmit (): Promise<void> { if (hasPendingJob || hasPendingBroadcastJob) { return } if (!canContinue || pair === undefined) { return } if (isConversionRequired) { queueConvertTransaction({ mode: 'utxosToAccount', amount: conversionAmount }, dispatch, () => { navigation.navigate({ name: 'ConfirmAddLiquidity', params: { summary: { fee: new BigNumber(0.0001), tokenAAmount: new BigNumber(tokenAAmount), tokenBAmount: new BigNumber(tokenBAmount), percentage: sharePercentage, tokenABalance: balanceA, tokenBBalance: balanceB }, pair, conversion: { isConversionRequired, DFIToken, DFIUtxo, conversionAmount } }, merge: true }) }, logger) } else { navigation.navigate({ name: 'ConfirmAddLiquidity', params: { summary: { fee: new BigNumber(0.0001), tokenAAmount: new BigNumber(tokenAAmount), tokenBAmount: new BigNumber(tokenBAmount), percentage: sharePercentage, tokenABalance: balanceA, tokenBBalance: balanceB }, pair }, merge: true }) } } useEffect(() => { client.fee.estimate() .then((f) => setFee(new BigNumber(f))) .catch(logger.error) }, []) useEffect(() => { if (pair === undefined) { return } setCanContinue(canAddLiquidity( pair, new BigNumber(tokenAAmount), new BigNumber(tokenBAmount), balanceA, balanceB )) }, [pair, tokenAAmount, tokenBAmount, balanceA, balanceB]) // prop/global state change useEffect(() => { const { pair: poolPairData } = props.route.params const poolpair = pairs.find((p) => p.data.id === poolPairData.id)?.data const reservedDfi = 0.1 if (poolpair !== undefined) { const [aSymbol, bSymbol] = poolpair.symbol.split('-') const addressTokenA = getAddressTokenById(poolpair.tokenA.id) const addressTokenB = getAddressTokenById(poolpair.tokenB.id) // side effect to state setPair({ ...poolpair, aSymbol, bSymbol, aToBRate: new BigNumber(poolpair.tokenB.reserve).div(poolpair.tokenA.reserve), bToARate: new BigNumber(poolpair.tokenA.reserve).div(poolpair.tokenB.reserve) }) if (addressTokenA !== undefined) { setBalanceA(addressTokenA.id === '0_unified' ? new BigNumber(addressTokenA.amount).minus(reservedDfi) : new BigNumber(addressTokenA.amount)) } if (addressTokenB !== undefined) { setBalanceB(addressTokenB.id === '0_unified' ? new BigNumber(addressTokenB.amount).minus(reservedDfi) : new BigNumber(addressTokenB.amount)) } } }, [props.route.params.pair, JSON.stringify(tokens), pairs]) if (pair === undefined) { return <></> } return ( <ThemedScrollView style={tailwind('w-full flex-col flex-1')}> <View style={tailwind('px-4')}> <TokenInput balance={balanceA} current={tokenAAmount} onChange={(amount) => { buildSummary('primary', amount) }} symbol={pair?.tokenA?.displaySymbol} type='primary' /> <TokenInput balance={balanceB} current={tokenBAmount} onChange={(amount) => { buildSummary('secondary', amount) }} symbol={pair?.tokenB?.displaySymbol} type='secondary' /> <ReservedDFIInfoText /> {isConversionRequired && <View style={tailwind('mt-2')}> <ConversionInfoText /> </View>} </View> <PriceDetailsSection pair={pair} /> <TransactionDetailsSection pair={pair} sharePercentage={sharePercentage} fee={fee} isConversionRequired={isConversionRequired} amountToConvert={conversionAmount} /> <ThemedText testID='transaction_details_hint_text' light={tailwind('text-gray-600')} dark={tailwind('text-dfxgray-300')} style={tailwind('pt-4 pb-2 px-4 text-sm')} > {isConversionRequired ? translate('screens/AddLiquidity', 'Authorize transaction in the next screen to convert') : translate('screens/AddLiquidity', 'Review full transaction details in the next screen')} </ThemedText> <ContinueButton enabled={canContinue} onPress={onSubmit} /> </ThemedScrollView> ) } function TokenInput (props: { symbol: string, balance: BigNumber, current: string, type: EditingAmount, onChange: (amount: string) => void }): JSX.Element { return ( <ThemedView dark={tailwind('bg-transparent')} light={tailwind('bg-transparent')} style={tailwind('flex-col w-full')} > <WalletTextInput onChangeText={txt => props.onChange(txt)} placeholder={translate('screens/AddLiquidity', 'Enter an amount')} style={tailwind('flex-grow w-2/5')} testID={`token_input_${props.type}`} value={props.current} title={translate('screens/AddLiquidity', 'How much {{symbol}} to supply?', { symbol: props.symbol })} titleTestID={`token_input_${props.type}_title`} inputType='numeric' displayClearButton={props.current !== ''} onClearButtonPress={() => props.onChange('')} > <SetAmountButton amount={props.balance} onPress={props.onChange} type={AmountButtonTypes.half} /> <SetAmountButton amount={props.balance} onPress={props.onChange} type={AmountButtonTypes.max} /> </WalletTextInput> <InputHelperText testID={`token_balance_${props.type}`} label={`${translate('screens/AddLiquidity', 'Available')}: `} content={BigNumber.max(props.balance, 0).toFixed(8)} suffix={` ${props.symbol}`} /> </ThemedView> ) } function PriceDetailsSection (props: { pair: ExtPoolPairData }): JSX.Element { const { pair } = props return ( <> <ThemedSectionTitle testID='title_price_detail' text={translate('screens/AddLiquidity', 'PRICE DETAILS')} style={tailwind('px-4 pt-6 pb-2 text-xs text-dfxgray-500 font-medium')} /> <NumberRow lhs={translate('screens/AddLiquidity', '{{tokenA}} price per {{tokenB}}', { tokenA: pair.tokenA.displaySymbol, tokenB: pair.tokenB.displaySymbol })} rhs={{ value: pair.aToBRate.toFixed(8), testID: 'a_per_b_price', suffixType: 'text', suffix: pair.tokenA.displaySymbol }} /> <NumberRow lhs={translate('screens/AddLiquidity', '{{tokenA}} price per {{tokenB}}', { tokenA: pair.tokenB.displaySymbol, tokenB: pair.tokenA.displaySymbol })} rhs={{ value: pair.bToARate.toFixed(8), testID: 'b_per_a_price', suffixType: 'text', suffix: pair.tokenB.displaySymbol }} /> </> ) } function TransactionDetailsSection (props: { pair: ExtPoolPairData, sharePercentage: BigNumber, fee: BigNumber, isConversionRequired: boolean, amountToConvert: BigNumber }): JSX.Element { const { pair, sharePercentage, isConversionRequired } = props return ( <> <ThemedSectionTitle testID='title_add_detail' text={translate('screens/AddLiquidity', 'TRANSACTION DETAILS')} /> {isConversionRequired && <NumberRow lhs={translate('screens/AddLiquidity', 'Amount to be converted')} rhs={{ value: props.amountToConvert.toFixed(8), testID: 'text_amount_to_convert', suffixType: 'text', suffix: 'DFI' }} />} <NumberRow lhs={translate('screens/AddLiquidity', 'Share of pool')} rhs={{ value: sharePercentage.times(100).toFixed(8), suffix: '%', testID: 'share_of_pool', suffixType: 'text' }} /> <NumberRow lhs={translate('screens/AddLiquidity', 'Pooled {{symbol}}', { symbol: pair?.tokenA?.displaySymbol })} rhs={{ value: pair.tokenA.reserve, testID: `pooled_${pair?.tokenA?.displaySymbol}`, suffixType: 'text', suffix: pair?.tokenA?.displaySymbol }} /> <NumberRow lhs={translate('screens/AddLiquidity', 'Pooled {{symbol}}', { symbol: pair?.tokenB?.displaySymbol })} rhs={{ value: pair.tokenB.reserve, testID: `pooled_${pair?.tokenB?.displaySymbol}`, suffixType: 'text', suffix: pair?.tokenB?.displaySymbol }} /> <FeeInfoRow type='ESTIMATED_FEE' value={props.fee.toFixed(8)} testID='text_fee' suffix='DFI' /> </> ) } function ContinueButton (props: { enabled: boolean, onPress: () => void }): JSX.Element { return ( <Button disabled={!props.enabled} label={translate('components/Button', 'CONTINUE')} onPress={props.onPress} testID='button_continue_add_liq' title='Continue' margin='m-4' /> ) } // just leave it as it is now, will be moved to network drawer function canAddLiquidity (pair: ExtPoolPairData, tokenAAmount: BigNumber, tokenBAmount: BigNumber, balanceA: BigNumber | undefined, balanceB: BigNumber | undefined): boolean { if (tokenAAmount.isNaN() || tokenBAmount.isNaN()) { // empty string, use still input-ing return false } if (tokenAAmount.lte(0) || tokenBAmount.lte(0)) { return false } if (tokenAAmount.gt(pair.tokenA.reserve) || tokenBAmount.gt(pair.tokenB.reserve)) { return false } return !(balanceA === undefined || balanceA.lt(tokenAAmount) || balanceB === undefined || balanceB.lt(tokenBAmount)) }
FullAriza/wallet
shared/contexts/WalletContext.tsx
import React, { createContext, PropsWithChildren, useContext, useEffect, useMemo, useState } from 'react' import { JellyfishWallet, WalletHdNode } from '@defichain/jellyfish-wallet' import { WhaleWalletAccount } from '@defichain/whale-api-wallet' import { useNetworkContext } from './NetworkContext' import { useWhaleApiClient } from './WhaleContext' import { useWalletNodeContext } from './WalletNodeProvider' import { initJellyfishWallet } from '@api/wallet' import { useLogger } from '@shared-contexts/NativeLoggingProvider' interface WalletContextI { /** * The entire HD Wallet, powered by @defichain/jellyfish-wallet */ wallet: JellyfishWallet<WhaleWalletAccount, WalletHdNode> /** * Default account of the above wallet */ account: WhaleWalletAccount /** * Default address of the above wallet */ address: string } const WalletContext = createContext<WalletContextI>(undefined as any) export function useWalletContext (): WalletContextI { return useContext(WalletContext) } export function WalletContextProvider (props: PropsWithChildren<any>): JSX.Element | null { const logger = useLogger() const { provider } = useWalletNodeContext() const [address, setAddress] = useState<string>() const { network } = useNetworkContext() const client = useWhaleApiClient() const wallet = useMemo(() => { return initJellyfishWallet(provider, network, client) }, [provider, network, client]) useEffect(() => { wallet.get(0).getAddress().then(value => { setAddress(value) }) .catch(logger.error) }, [wallet]) if (address === undefined) { return null } const context: WalletContextI = { wallet: wallet, account: wallet.get(0), address: address } return ( <WalletContext.Provider value={context}> {props.children} </WalletContext.Provider> ) }
FullAriza/wallet
mobile-app/app/constants/Theme.ts
<reponame>FullAriza/wallet<gh_stars>0 import { DarkTheme, DefaultTheme } from '@react-navigation/native' import { Theme } from '@react-navigation/native/lib/typescript/src/types' import { theme } from '../tailwind.config' export function getDefaultTheme (isLight: boolean): Theme { const defaultTheme = isLight ? DefaultTheme : DarkTheme return { ...defaultTheme, colors: { ...defaultTheme.colors, primary: isLight ? theme.extend.colors.primary[500] : theme.extend.colors.dfxred[500], card: isLight ? defaultTheme.colors.card : theme.extend.colors.dfxblue[900], border: isLight ? defaultTheme.colors.border : theme.extend.colors.dfxblue[800] } } }
FullAriza/wallet
mobile-app/app/screens/AppNavigator/screens/Loans/components/VaultInfo.test.tsx
import { render } from '@testing-library/react-native' import React from 'react' import { VaultInfo } from './VaultInfo' jest.mock('@shared-contexts/ThemeProvider') jest.mock('@react-navigation/native', () => ({ useNavigation: jest.fn() })) describe('Vault info', () => { it('should render label with token icon group', async () => { const rendered = render( <VaultInfo label='Foo' tokens={['BTC', 'dLTC', 'dDOGE', 'dETH', 'dBCH', 'DFI']} /> ) expect(rendered.toJSON()).toMatchSnapshot() }) })
FullAriza/wallet
mobile-app/app/screens/AppNavigator/screens/Loans/VaultDetail/VaultDetailScreen.tsx
<filename>mobile-app/app/screens/AppNavigator/screens/Loans/VaultDetail/VaultDetailScreen.tsx import { View } from '@components' import { ThemedIcon, ThemedScrollView, ThemedText, ThemedView } from '@components/themed' import { StackScreenProps } from '@react-navigation/stack' import { tailwind } from '@tailwind' import { translate } from '@translations' import React, { useEffect, useState } from 'react' import { LoanParamList } from '../LoansNavigator' import { TouchableOpacity } from 'react-native' import { ScrollableButton, ScrollButton } from '../components/ScrollableButton' import { VaultDetailTabSection } from './components/VaultDetailTabSection' import { LoanVault, vaultsSelector } from '@store/loans' import { useSelector } from 'react-redux' import { RootState } from '@store' import { LoanVaultState } from '@defichain/whale-api-client/dist/api/loan' import { VaultSectionTextRow } from '../components/VaultSectionTextRow' import BigNumber from 'bignumber.js' import { useDeFiScanContext } from '@shared-contexts/DeFiScanContext' import { openURL } from '@api/linking' import { useVaultStatus, VaultStatus, VaultStatusTag } from '@screens/AppNavigator/screens/Loans/components/VaultStatusTag' import { CollateralizationRatioDisplay } from '@screens/AppNavigator/screens/Loans/components/CollateralizationRatioDisplay' import { useNextCollateralizationRatio } from '@screens/AppNavigator/screens/Loans/hooks/NextCollateralizationRatio' import { useLoanOperations } from '@screens/AppNavigator/screens/Loans/hooks/LoanOperations' type Props = StackScreenProps<LoanParamList, 'VaultDetailScreen'> export function VaultDetailScreen ({ route, navigation }: Props): JSX.Element { const { vaultId, tab } = route.params const [vault, setVault] = useState<LoanVault>() const vaults = useSelector((state: RootState) => vaultsSelector(state.loans)) const canUseOperations = useLoanOperations(vault?.state) const vaultActionButtons: ScrollButton[] = [ { label: 'EDIT COLLATERALS', disabled: !canUseOperations, handleOnPress: () => { if (vault === undefined) { return } navigation.navigate({ name: 'EditCollateralScreen', params: { vaultId: vault.vaultId }, merge: true }) } }, { label: 'EDIT LOAN SCHEME', disabled: !canUseOperations, handleOnPress: () => { if (vault === undefined) { return } navigation.navigate({ name: 'EditLoanSchemeScreen', params: { vaultId: vault.vaultId }, merge: true }) } }, { label: 'CLOSE VAULT', disabled: !(vault?.state === LoanVaultState.ACTIVE && vault.loanValue === '0'), handleOnPress: () => { if (vault === undefined) { return } navigation.navigate({ name: 'CloseVaultScreen', params: { vaultId: vault.vaultId }, merge: true }) } } ] useEffect(() => { const _vault = vaults.find(v => v.vaultId === vaultId) if (_vault !== undefined) { setVault(_vault) } }, [vaults]) if (vault === undefined) { return <></> } return ( <ThemedScrollView light={tailwind('bg-gray-100')} dark={tailwind('bg-dfxblue-900')} > <ThemedView light={tailwind('bg-white')} dark={tailwind('bg-dfxblue-800')} > <View style={tailwind('p-4')}> <VaultIdSection vault={vault} /> <VaultInfoSection vault={vault} /> </View> <ThemedView light={tailwind('border-gray-200')} dark={tailwind('border-dfxblue-900')} style={tailwind('pb-4 border-b')} > <ScrollableButton buttons={vaultActionButtons} containerStyle={tailwind('pl-4')} /> </ThemedView> </ThemedView> <VaultDetailTabSection vault={vault} tab={tab} /> </ThemedScrollView> ) } function VaultIdSection ({ vault }: { vault: LoanVault }): JSX.Element { const { getVaultsUrl } = useDeFiScanContext() const colRatio = vault.state === LoanVaultState.IN_LIQUIDATION ? 0 : vault.collateralRatio const totalLoanAmount = vault.state === LoanVaultState.IN_LIQUIDATION ? 0 : vault.loanValue const vaultState = useVaultStatus(vault.state, new BigNumber(colRatio), new BigNumber(vault.loanScheme.minColRatio), new BigNumber((totalLoanAmount))) const collateralAmounts = vault.state === LoanVaultState.IN_LIQUIDATION ? [] : vault.collateralAmounts const loanAmounts = vault.state === LoanVaultState.IN_LIQUIDATION ? [] : vault.loanAmounts const nextCollateralizationRatio = useNextCollateralizationRatio(collateralAmounts, loanAmounts) return ( <> <ThemedView light={tailwind('bg-white')} dark={tailwind('bg-dfxblue-800')} style={tailwind('flex flex-row items-center')} > <View style={tailwind('flex flex-1')} > <View style={tailwind('flex flex-row mb-2 items-center')}> <ThemedText light={tailwind('text-dfxgray-400')} dark={tailwind('text-dfxgray-500')} style={tailwind('text-xs mr-1')} > {translate('screens/VaultDetailScreen', 'Vault ID')} </ThemedText> <VaultStatusTag status={vaultState.status} vaultStats={vaultState.vaultStats} /> </View> <View style={tailwind('flex flex-row mb-2 items-center')} > <ThemedText style={tailwind('text-sm font-semibold w-8/12 flex-1 mr-2')} > {vault.vaultId} </ThemedText> <TouchableOpacity onPress={async () => await openURL(getVaultsUrl(vault.vaultId ?? ''))}> <ThemedIcon dark={tailwind('text-dfxred-500')} iconType='MaterialIcons' light={tailwind('text-primary-500')} name='open-in-new' size={22} style={tailwind('-mr-1')} /> </TouchableOpacity> </View> </View> </ThemedView> { vault.state !== LoanVaultState.IN_LIQUIDATION && vaultState.status !== VaultStatus.Active && ( <CollateralizationRatioDisplay collateralizationRatio={vault.collateralRatio} minCollateralizationRatio={vault.loanScheme.minColRatio} totalLoanAmount={vault.loanValue} nextCollateralizationRatio={nextCollateralizationRatio?.toFixed(8)} /> ) } </> ) } function VaultInfoSection (props: { vault?: LoanVault }): JSX.Element | null { if (props.vault === undefined) { return null } if (props.vault.state === LoanVaultState.IN_LIQUIDATION) { return ( <View style={tailwind('flex -mb-2')}> <VaultSectionTextRow value={props.vault.batchCount} lhs={translate('screens/VaultDetailScreen', 'Auction batches')} testID='text_auction_batches' /> </View> ) } return ( <View style={tailwind('flex -mb-2')}> {props.vault.state === LoanVaultState.ACTIVE && props.vault.collateralValue === '0' && props.vault.loanValue === '0' ? ( <> <VaultSectionTextRow value={props.vault.loanScheme.minColRatio} lhs={translate('screens/VaultDetailScreen', 'Min. collateralization ratio')} testID='text_min_col_ratio' suffixType='text' suffix='%' info={{ title: 'Min. collateralization ratio', message: 'Minimum required collateralization ratio based on loan scheme selected. A vault will go into liquidation when the collateralization ratio goes below the minimum requirement.' }} /> <VaultSectionTextRow value={props.vault.loanScheme.interestRate} lhs={translate('screens/VaultDetailScreen', 'Vault interest (APR)')} testID='text_vault_interest' suffixType='text' suffix='%' info={{ title: 'Annual vault interest', message: 'Annual vault interest rate based on the loan scheme selected.' }} /> </> ) : ( <> <VaultSectionTextRow value={new BigNumber(props.vault.collateralValue).toFixed(2)} lhs={translate('screens/VaultDetailScreen', 'Total collateral (USD)')} testID='text_total_collateral_value' prefix='$' /> <VaultSectionTextRow value={new BigNumber(props.vault.loanValue).toFixed(2)} lhs={translate('screens/VaultDetailScreen', 'Total loans (USD)')} testID='text_total_loan_value' prefix='$' /> <VaultSectionTextRow value={props.vault.loanScheme.interestRate} lhs={translate('screens/VaultDetailScreen', 'Vault interest (APR)')} testID='text_vault_interest' suffixType='text' suffix='%' info={{ title: 'Annual vault interest', message: 'Annual vault interest rate based on the loan scheme selected.' }} /> </> )} </View> ) }
hamayun-cpu/Angular-toDos
src/app/app.component.ts
import { Component } from '@angular/core'; @Component({ selector: 'app-root', templateUrl: './app.component.html', styleUrls: ['./app.component.css'] }) export class AppComponent { title = 'my-ang-app'; todoArray: string[] = []; addTodo(value: string){ this.todoArray.push(value); console.log(this.todoArray); } deleteItem(todo: string){ for(let i=0 ;i<= this.todoArray.length ;i++){ if(todo== this.todoArray[i]){ this.todoArray.splice(i,1) } } } }
StableTez/BTCtz
src/index.ts
import fetch from 'node-fetch'; import * as log from 'loglevel'; import * as fs from 'fs'; import { registerFetch, registerLogger } from 'conseiljs'; import { TezosNodeReader, TezosNodeWriter, TezosConseilClient, TezosConstants, TezosParameterFormat, TezosMessageUtils, KeyStore, Signer } from 'conseiljs'; import { KeyStoreUtils, SoftSigner } from 'conseiljs-softsigner'; const logger = log.getLogger('conseiljs'); logger.setLevel('debug', false); registerLogger(logger); registerFetch(fetch); const tezosNode = ''; const conseilServer = { url: '', apiKey: '', network: 'florencenet' }; const networkBlockTime = 60 + 1; function clearRPCOperationGroupHash(hash: string) { return hash.replace(/\"/g, '').replace(/\n/, ''); } async function initAccount(server: string, accountKey: string): Promise<{keyStore: KeyStore, signer: Signer, counter: number}> { const keyStore = await KeyStoreUtils.restoreIdentityFromSecretKey(accountKey); const signer = await SoftSigner.createSigner(TezosMessageUtils.writeKeyWithHint(keyStore.secretKey, 'edsk')); const counter = await TezosNodeReader.getCounterForAccount(server, keyStore.publicKeyHash) + 1; return { keyStore, signer, counter }; } async function deployTokenContract(signer: Signer, keyStore: KeyStore) { console.log('deploying token contract'); const code = fs.readFileSync('contracts/btctz.micheline', 'utf8'); const storage = `{ "prim": "Pair", "args": [ { "prim": "Pair", "args": [ { "string": "${keyStore.publicKeyHash}" }, { "prim": "Pair", "args": [ { "int": "0" }, [] ] } ] }, { "prim": "Pair", "args": [ { "prim": "Pair", "args": [ { "prim": "Unit" }, [] ] }, { "prim": "Pair", "args": [ { "prim": "False" }, [] ] } ] } ] }`; const r = await TezosNodeWriter.sendContractOriginationOperation(tezosNode, signer, keyStore, 0, undefined, 0, 0, 0, code, storage, TezosParameterFormat.Micheline, TezosConstants.HeadBranchOffset, true); const groupid = clearRPCOperationGroupHash(r.operationGroupID); console.log(`injected operation ${groupid}`); const s = await TezosConseilClient.awaitOperationConfirmation(conseilServer, conseilServer.network, groupid, 7, networkBlockTime); console.log(`deployed ${s['originated_contracts']} in ${s['block_hash']}`); return s['originated_contracts']; } async function mintMinimumBalance(signer: Signer, keyStore: KeyStore, contractAddress: string, targetAdmin: string) { console.log(`minting minimum balance future admin ${targetAdmin}`); const minTokenBalance = 1; const params = `{ "prim": "Left", "args": [ { "prim": "Right", "args": [ { "prim": "Left", "args": [ { "prim": "Pair", "args": [ { "prim": "Pair", "args": [ { "string": "${targetAdmin}" }, { "prim": "Pair", "args": [ { "int": "${minTokenBalance}" }, { "int": "8" } ] } ] }, { "prim": "Pair", "args": [ { "string": "Token 0" }, { "prim": "Pair", "args": [ { "string": "TK0" }, { "int": "0" } ] } ] } ] } ] } ] } ] }`; const r = await TezosNodeWriter.sendContractInvocationOperation(tezosNode, signer, keyStore, contractAddress, 0, 0, 0, 0, 'default', params, TezosParameterFormat.Micheline, TezosConstants.HeadBranchOffset, true); const groupid = clearRPCOperationGroupHash(r.operationGroupID); console.log(`injected operation ${groupid}`); const s = await TezosConseilClient.awaitOperationConfirmation(conseilServer, conseilServer.network, groupid, 7, networkBlockTime); console.log(`completed in ${s['block_hash']}`); } async function transferAdminRights(signer: Signer, keyStore: KeyStore, contractAddress: string, targetAdmin: string) { console.log(`transferring ownership to ${targetAdmin}`); const r = await TezosNodeWriter.sendContractInvocationOperation(tezosNode, signer, keyStore, contractAddress, 0, 0, 0, 0, 'set_administrator', `"${targetAdmin}"`, TezosParameterFormat.Michelson, TezosConstants.HeadBranchOffset, true); const groupid = clearRPCOperationGroupHash(r.operationGroupID); console.log(`injected operation ${groupid}`); const s = await TezosConseilClient.awaitOperationConfirmation(conseilServer, conseilServer.network, groupid, 7, networkBlockTime); console.log(`completed in ${s['block_hash']}`); } async function run() { let tokenContract = ''; let targetAdmin = ''; const accountInfo = await initAccount(tezosNode, '<KEY>'); // test-net sk if (tokenContract.length === 0) { tokenContract = await deployTokenContract(accountInfo.signer, accountInfo.keyStore); } await mintMinimumBalance(accountInfo.signer, accountInfo.keyStore, tokenContract, targetAdmin); await transferAdminRights(accountInfo.signer, accountInfo.keyStore, tokenContract, targetAdmin); } run();
RSD-MNS/research-software-directory
admin/src/saga.ts
/** * @file Saga to run on INIT, (get settings, JWT, schemas, data) * @todo Scenario where JWT is invalid */ import { put, call, select, all, takeLatest } from "redux-saga/effects"; import fetch, { AxiosRequestConfig } from "axios"; import { actions as toastrActions } from "react-redux-toastr"; import { push } from "react-router-redux"; import { IStoreState } from "./rootReducer"; import config from "./config"; import fixtures from "./fixtures"; // process.env.PUBLIC_URL is /admin when the project is built with yarn build, // otherwise it is "" with yarn start const SETTINGS_URL = `${process.env.PUBLIC_URL}/settings.json`; const errorAction = (message: string) => toastrActions.add({ message: message, options: { timeOut: 10000, showCloseButton: true }, position: "top-center", title: "Error", type: "error" }); /** * Fetch runtime application settings from `SETTINGS_URL`. * @puts SETTINGS_FETCHED action on success. * @puts toastr error failure. */ function* fetchSettings() { try { const response = config.useFixtures ? { data: fixtures.settings } : yield fetch(SETTINGS_URL); yield put({ type: "SETTINGS_FETCHED", data: response.data }); } catch (e) { yield put( errorAction( `Error getting ${e.config.url}: ${e.response.status} ${ e.response.statusText }` ) ); } } /** * Check if current URL contains an JWT (eg http://localhost:3000/?jwt=[JWT_HERE]) and return it * @returns JWT string if in URL, else null */ function getJWTfromURL(): string | null { const splitted = window.location.href.split("?"); if (splitted.length === 2) { const argSplitted = splitted[1].split("="); if (argSplitted[0] === "jwt") { return argSplitted[1]; } } return null; } /** * Get JWT from URL or localStorage, or forward user to authorization URL. * @param authUrl URL to go to for authorization if there is no JWT. * @puts JWT_CHANGED action with JWT. */ const getJWT = (authUrl: string) => function*() { let jwt = localStorage.getItem("jwt"); if (!jwt) { jwt = getJWTfromURL(); if (!jwt) { if (!config.useFixtures) { window.location.href = authUrl; return; } else { jwt = JSON.stringify(fixtures.jwt); } } localStorage.setItem("jwt", jwt); yield put(push("/")); } yield put({ type: "JWT_CHANGED", data: jwt }); }; /** * Wraps axios fetch with authorization header using current JWT * @param url url to fetch * @param requestConfig Axios config * @returns AxiosPromise result */ function* authorizedFetch(url: string, requestConfig?: AxiosRequestConfig) { const jwt = yield select((state: IStoreState) => state.jwt); return yield fetch(url, { headers: { Authorization: `Bearer ${jwt.token}` }, ...requestConfig }); } function* fetchData() { const settings = yield select((state: any) => state.settings); const result = config.useFixtures ? { data: fixtures.data } : yield authorizedFetch(settings.backendUrl + "/"); yield put({ type: "DATA_FETCHED", data: result.data }); } function* fetchSchema() { const settings = yield select((state: any) => state.settings); const result = config.useFixtures ? { data: fixtures.schema } : yield authorizedFetch(settings.backendUrl + "/schema"); yield put({ type: "SCHEMA_FETCHED", data: result.data }); } function* initSaga() { try { yield call(fetchSettings); const settings = yield select((state: any) => state.settings); yield call(getJWT(settings.authUrl)); yield all([call(fetchData), call(fetchSchema)]); yield put({ type: "INIT_DONE" }); yield takeLatest("DATA_FETCH_REQUESTED", fetchData); } catch (e) { if (e.message === "Network Error") { yield put(errorAction("Network error connecting to " + e.config.url)); } else if (e.response) { yield put( errorAction( `Error getting ${e.config.url}: ${e.response.data.class}: ${ e.response.data.error }` ) ); } else { yield put(errorAction("error: " + e)); } } } export default initSaga;
RSD-MNS/research-software-directory
admin/src/components/Resource/index.tsx
import * as React from "react"; import axios from "axios"; import { RouteComponentProps } from "react-router"; import { Button, Message, Modal, Header, Icon } from "semantic-ui-react"; import { Link } from "react-router-dom"; import { IJWT, ISettings } from "../../rootReducer"; import { ISchema } from "../../interfaces/json-schema"; import { IData } from "../../interfaces/resource"; import { IResource } from "../../interfaces/resource"; import Form from "../../containers/Form"; interface IConnectedProps { jwt: IJWT; schema: { [key: string]: ISchema }; data: IData; settings: ISettings; push(location: any): any; messageToastr(message: string): any; errorToastr(message: string): any; resourceUpdated(): any; } type IProps = IConnectedProps & RouteComponentProps<{ resourceType: string; id: string }>; class DeleteModal extends React.PureComponent< IProps, { modalOpen: boolean; links: any[]; error: string | null } > { constructor(props: IProps) { super(props); this.state = { modalOpen: false, links: [], error: null }; } confirmDelete() { const { resourceType, id } = this.props.match.params; const { backendUrl } = this.props.settings; axios .delete(`${backendUrl}/${resourceType}/${id}`, { headers: { Authorization: `Bearer ${this.props.jwt.token}` } }) .then(() => { this.setState({ modalOpen: false, links: [], error: null }); this.props.messageToastr("Deleted"); this.props.resourceUpdated(); }) .catch(response => { const result = response.response; if (result && result.status === 406) { this.setState({ links: result.data.data, error: result.data.error }); } else { this.setState({ links: [], error: result.data.error }); } }); } formatLink(linkArr: any[]): any { const linkParts = [...linkArr]; const resourceType = linkParts.shift(); const id = linkParts.shift(); return ( <div> <Link to={`/${resourceType}/${id}`}>{`/${resourceType}/${id}`}</Link> {linkParts .map(part => (typeof part === "string" ? ` => ${part}` : `[${part}]`)) .join("")} </div> ); } render() { return ( <Modal trigger={ <Button color="red" onClick={() => this.setState({ modalOpen: true })} > Delete </Button> } open={this.state.modalOpen} onClose={() => this.setState({ modalOpen: false })} size="small" style={{ marginTop: "0px !important", marginLeft: "auto", marginRight: "auto" }} > <Header icon="delete" content="Deleting" /> <Modal.Content> <p>Are you sure you want to delete this?</p> {this.state.error && ( <Message error={true} header={this.state.error} list={this.state.links.map(this.formatLink)} /> )} </Modal.Content> <Modal.Actions> <Button color="red" onClick={() => this.confirmDelete()}> <Icon name="remove" /> Yes, delete </Button> <Button onClick={() => this.setState({ modalOpen: false })} inverted={true} color="green" > <Icon name="checkmark" /> No </Button> </Modal.Actions> </Modal> ); } } interface IState { loading: boolean; saving: boolean; data: IResource | null; validationErrors: any[]; } export default class Resource extends React.PureComponent<IProps, IState> { form: any = null; save = () => { this.setState({ saving: true }); const { resourceType, id } = this.props.match.params; const { backendUrl } = this.props.settings; axios .put( `${backendUrl}/${resourceType}/${id}?save_history`, this.state.data, { headers: { Authorization: `Bearer ${this.props.jwt.token}` } } ) .then(() => { this.setState({ saving: false }); this.props.messageToastr("Saved"); this.props.resourceUpdated(); }) .catch(response => { this.setState({ saving: false }); this.props.errorToastr(JSON.stringify(response.response.data)); }); }; constructor(props: IProps) { super(props); this.state = { saving: false, loading: true, data: null, validationErrors: [] }; } asyncSetState = async (newState: any) => { return new Promise(resolve => { this.setState(newState, resolve); }); }; async updateLocalData() { const { resourceType, id } = this.props.match.params; const { backendUrl } = this.props.settings; const result = await axios.get(`${backendUrl}/${resourceType}/${id}`, { headers: { Authorization: `Bearer ${this.props.jwt.token}` } }); await this.asyncSetState({ data: result.data, loading: false }); } async componentDidMount() { await this.updateLocalData(); if (this.form) { this.setState({ validationErrors: this.form.getValidationErrors() }); } } onChange = async (data: any) => { await this.asyncSetState({ data }); await this.asyncSetState({ validationErrors: this.form.getValidationErrors(), data }); }; render() { if (this.state.loading) { return null; } return ( <div> <div> <Form ref={(elm: any) => (this.form = elm && elm.getWrappedInstance())} value={this.state.data!} onChange={this.onChange} /> </div> {this.state.validationErrors.length > 0 && ( <Message error={true}> {this.state.validationErrors.map((error, i) => ( <div key={i}> {error.dataPath} {error.message} </div> ))} </Message> )} <Button primary={true} disabled={this.state.saving || this.state.validationErrors.length > 0} onClick={this.save} > {this.state.saving ? "Saving..." : "Save"} </Button> <DeleteModal {...this.props} /> </div> ); } }
RSD-MNS/research-software-directory
admin/src/components/Form/TypeArray.tsx
import * as React from "react"; import { Button, Label, Icon, ButtonProps } from "semantic-ui-react"; import { IArraySchema } from "../../interfaces/json-schema"; import { IProps } from "./IProps"; import FormPart from "./FormPart"; import { createEmpty } from "../../utils/createEmpty"; import styled, { StyledComponentClass } from "styled-components"; interface IState { collapsed: boolean; } export default class TypeArray extends React.Component< IProps<IArraySchema>, IState > { constructor(props: IProps<IArraySchema>) { super(props); this.state = { collapsed: !(Array.isArray(props.value) || props.value.length === 0) }; if (!Array.isArray(props.value)) { this.props.onChange([]); } } handleChange(index: number, value: any) { const valCopy = [...this.props.value]; valCopy[index] = value; this.props.onChange(valCopy); } onAdd = () => { let value = this.props.value; if (!Array.isArray(value)) { value = []; } this.setState({ collapsed: false }); this.props.onChange([...value, createEmpty(this.props.schema.items)]); }; onDelete = (index: any) => { const valCopy = [...this.props.value]; valCopy.splice(index, 1); this.props.onChange(valCopy); }; onMoveUp = (index: number) => { const valCopy = [...this.props.value]; const swapIndex = index - 1; const item = valCopy[index]; valCopy[index] = valCopy[swapIndex]; valCopy[swapIndex] = item; this.props.onChange(valCopy); } onMoveDown = (index: number) => { const valCopy = [...this.props.value]; const swapIndex = index + 1; const item = valCopy[index]; valCopy[index] = valCopy[swapIndex]; valCopy[swapIndex] = item; this.props.onChange(valCopy); } render() { let value: any[] = this.props.value; if (!Array.isArray(value)) { return null; } let error = !!( this.props.validationErrors && this.props.validationErrors.length > 0 ); return ( <Container> <Header style={{ backgroundColor: error ? "red" : "#2185d0" }}> <HeaderContent> <ArrayButton onClick={() => this.setState({ collapsed: !this.state.collapsed }) } > {(this.props.settings && this.props.settings.label) || this.props.label}{" "} &nbsp; {Array.isArray(this.props.value) && ( <Label color="blue" circular={true}> {this.props.value.length} </Label> )}&nbsp; <Icon name={this.state.collapsed ? "angle down" : "angle up"} /> </ArrayButton> <Button color="blue" onClick={this.onAdd}> + </Button> </HeaderContent> </Header> <Contents> {!this.state.collapsed && value.map((val: any, index: number) => ( <ArrayItem key={JSON.stringify(val)}> <ItemLeft> <Button.Group secondary={true} size="mini"> <DeleteButton title="Delete" onClick={() => this.onDelete(index)} > x </DeleteButton> {!(index === 0 && index + 1 === value.length) && <> <Button disabled={index === 0} icon="long arrow alternate up" title="Move up" onClick={() => this.onMoveUp(index)} /> <Button disabled={index + 1 === value.length} icon="long arrow alternate down" title="Move down" onClick={() => this.onMoveDown(index)} /> </> } </Button.Group> </ItemLeft> <ItemRight> <FormPart value={val} settings={this.props.settings} schema={this.props.schema.items} showLabel={false} readonly={ !!this.props.readonly || !!this.props.settings.readonly } data={this.props.data} label="" onChange={(v: any) => this.handleChange(index, v)} resourceTemplates={this.props.resourceTemplates} /> </ItemRight> </ArrayItem> ))} </Contents> </Container> ); } } const ArrayButton = styled.div` border: none; border-radius: 0 !important; width: 100%; text-align: left; `; const Contents = styled.div` border: 1px solid #2185d0; `; const DeleteButton = styled(Button)`` as StyledComponentClass<ButtonProps, {}>; const ArrayItem = styled.section` display: flex; flex-direction: row; padding: 0.5em; &:nth-child(odd) { background-color: #eee; } &:nth-child(even) { background-color: white; } &:hover { background-color: rgba(0, 0, 65, 0.2); } `; const Header = styled.div` position: relative; min-width: 200px; cursor: pointer; display: inline-block; padding-left: 1em; color: white; font-weight: bold; &:hover { color: #ccc; } `; const HeaderContent = styled.div` display: flex; flex-direction: row; align-items: center; `; const ItemLeft = styled.div` display: flex; align-items: center; justify-content: center; width: 120px; `; const ItemRight = styled.div` flex: 1; `; // interface IContainerProps { // error: boolean; // } const Container = styled.section``;
JeremyBYU/polylidarweb
demo/demo2D/app.ts
<reponame>JeremyBYU/polylidarweb<filename>demo/demo2D/app.ts // This code is modified from Delaunator website import Delaunator from 'delaunator' import { concaveHullTest } from '../../src/d3concave' import { pointList2Edge, pointsOfTriangle, IPolygon } from '../../src/helper' import { extractConcaveHulls, extractPlanes } from '../../src/main' import { points } from './points' let delaunay = Delaunator.from(points) window.delaunay = delaunay let canvas = document.getElementById('canvas') let ctx = canvas.getContext('2d') let minX = Infinity let minY = Infinity let maxX = -Infinity let maxY = -Infinity const PX_BUFFER = 10 const THROTTLE_LIMIT = 1 const AXES_STEPS = 30 for (let i = 0; i < points.length; i++) { const x = points[i][0] const y = points[i][1] if (x < minX) minX = x if (y < minY) minY = y if (x > maxX) maxX = x if (y > maxY) maxY = y } let padding = 20 let w = 1024 let h = 1024 let planes: number[][] = [] let concaveHulls: number[][] = [] const colorPalette = [ '#4878d0', '#ee854a', '#6acc64', '#d65f5f', '#956cb4', '#8c613c', '#dc7ec0', '#797979', '#d5bb67', '#82c6e2', ] canvas.style.width = w + 'px' canvas.style.height = h + 'px' canvas.width = w canvas.height = h if (window.devicePixelRatio >= 2) { canvas.width = w * 2 canvas.height = h * 2 ctx.scale(2, 2) } let ratio = (w - 2 * padding) / Math.max(maxX - minX, maxY - minY) ctx.lineJoin = 'round' ctx.lineCap = 'round' window.updated = true window.points = points canvas.addEventListener("touchmove", (e) => { const touch = e.touches[0]; const mouseEvent = new MouseEvent("mousemove", { clientX: touch.clientX, clientY: touch.clientY }) canvas.dispatchEvent(mouseEvent) }, {passive:true}) // Get the position of a touch relative to the canvas function getTouchPos(canvasDom, touchEvent) { var rect = canvasDom.getBoundingClientRect(); return { x: touchEvent.touches[0].clientX - rect.left, y: touchEvent.touches[0].clientY - rect.top }; } function mouse_over(e) { points.push([ (e.layerX - padding) / ratio + minX, (e.layerY - padding) / ratio + minY, ]) console.time('delaunay') delaunay = Delaunator.from(points) console.timeEnd('delaunay') window.updated = true } canvas.onmousemove = _.throttle(mouse_over, THROTTLE_LIMIT) function getCentroid(p0, p1, p2) { return [(p0[0] + p1[0] + p2[0]) / 3, (p0[1] + p1[1] + p2[1]) / 3] } function getXPad(val) { return padding + ratio * (val - minX) } function getYPad(val) { return padding + ratio * (val - minY) } function getX(i) { return getXPad(points[i][0]) } function getY(i) { return getYPad(points[i][1]) } function frame() { requestAnimationFrame(frame) draw() } frame() function drawEdges( edges, edgeColor: string = '#2EAC36', linewidth: number = 5.0, dashed: boolean = false, ) { ctx.strokeStyle = edgeColor ctx.lineWidth = linewidth if (dashed) { ctx.setLineDash([5, 15]) } else { ctx.setLineDash([]) } for (const edge of edges) { ctx.beginPath() const p0 = edge[0] const p1 = edge[1] ctx.moveTo(getXPad(p0[0]), getYPad(p0[1])) ctx.lineTo(getXPad(p1[0]), getYPad(p1[1])) ctx.stroke() } ctx.setLineDash([]) } function drawPlanesAndHull( planes, hulls: IPolygon[], shellColor = '#008000', holeColor = '#F67C3D', ) { if (planes.length !== hulls.length) { console.error('Planes and Hull should be equal') } else { for (let i = 0; i < planes.length; i++) { const plane = planes[i] const polygon = hulls[i] const colorIndex = i % 10 const color = colorPalette[i] drawPlane(plane, color) const outerShell = pointList2Edge(polygon.shell, delaunay) drawEdges(outerShell, shellColor, 5, false) for (const hole of polygon.holes) { const innerHole = pointList2Edge(hole, delaunay) drawEdges(innerHole, holeColor, 5, false) } } } } function drawPlane(plane, color) { const triangles = delaunay.triangles ctx.beginPath() for (const t of plane) { const tindex = t * 3 const p0 = triangles[tindex] const p1 = triangles[tindex + 1] const p2 = triangles[tindex + 2] ctx.moveTo(getX(p0), getY(p0)) ctx.lineTo(getX(p1), getY(p1)) ctx.lineTo(getX(p2), getY(p2)) ctx.closePath() } ctx.strokeStyle = color ctx.fillStyle = color ctx.lineWidth = 0.5 ctx.stroke() ctx.fill() } function drawAxes() { const xRange = maxX - minX const xStep = xRange / AXES_STEPS const yRange = maxY - minY const yStep = yRange / AXES_STEPS const tickSize = 0.01 const xTickSize = Math.floor(yRange * tickSize) const yTickSize = Math.floor(xRange * tickSize) ctx.beginPath() ctx.fillStyle = 'black' ctx.strokeStyle = 'black' for (let x = Math.ceil(minX); x <= minX + xRange; x += xStep) { const xVal = Math.floor(x) ctx.moveTo(getXPad(xVal), getYPad(maxY) + padding / 2) ctx.lineTo(getXPad(xVal), getYPad(maxY)) ctx.fillText( xVal.toFixed(1), getXPad(xVal - yTickSize), getYPad(maxY) + padding, ) ctx.closePath() } for (let y = minY; y <= minY + yRange; y += yStep) { const yVal = Math.floor(y) ctx.moveTo(getXPad(minX) - padding / 2, getYPad(yVal)) ctx.lineTo(getXPad(minX), getYPad(yVal)) ctx.save() ctx.translate(getXPad(minX) - padding - 1, getYPad(yVal + xTickSize)) ctx.rotate(-Math.PI / 2) ctx.fillText(yVal.toFixed(1), 0, PX_BUFFER) ctx.restore() ctx.closePath() } ctx.stroke() } function draw() { if (!window.updated) return window.updated = false ctx.clearRect(0, 0, w, h) drawAxes() const config = { min_bbox_area: 1000.0, xy_thresh: 20.0, dim: 2, min_triangles: 15, alpha: 0.0, } console.time('Extract Planes') planes = extractPlanes(delaunay, config, points) console.timeEnd('Extract Planes') console.time('Concave Hull Extraction') const concaveList = extractConcaveHulls(planes, delaunay, config) console.timeEnd('Concave Hull Extraction') console.log(`# Points: ${points.length}`) console.log(concaveList) drawPlanesAndHull(planes, concaveList) let triangles = delaunay.triangles // Triangles ctx.beginPath() ctx.fillStyle = 'black' for (let i = 0; i < triangles.length; i += 3) { let p0 = triangles[i] let p1 = triangles[i + 1] let p2 = triangles[i + 2] let pc = getCentroid(points[p0], points[p1], points[p2]) ctx.moveTo(getX(p0), getY(p0)) ctx.lineTo(getX(p1), getY(p1)) ctx.lineTo(getX(p2), getY(p2)) ctx.fillText((i / 3).toString(), getXPad(pc[0]), getYPad(pc[1])) ctx.closePath() } ctx.strokeStyle = 'black' ctx.lineWidth = 0.5 ctx.stroke() // ctx.fillStyle = 'rgba(255,255,0,0.1)'; // ctx.fill(); // Hull ctx.beginPath() for (const i of delaunay.hull) { ctx.lineTo(getX(i), getY(i)) } ctx.closePath() ctx.lineWidth = 1 ctx.strokeStyle = 'red' ctx.stroke() // Points ctx.fillStyle = 'black' ctx.beginPath() for (let i = 0; i < points.length; i++) { ctx.rect(getX(i) - 1.5, getY(i) - 1.5, 3, 3) } ctx.fill() }
JeremyBYU/polylidarweb
src/helper.ts
<gh_stars>1-10 import Delaunator from 'delaunator' // Type Declarations export interface IConfig2D { dim: number xy_thresh?: number alpha?: number min_triangles: number min_bbox_area: number } export interface IConfig3D extends IConfig2D { z_thresh: number norm_thresh: number desired_vector: [number, number, number], points?: Float64Array } export interface IConfig4D extends IConfig3D { allowed_class: number } export interface IPolygon { shell: number[] holes: number[][] } export interface IBbox { xmin: number xmax: number ymin: number ymax: number } export type IValidateTriangle = ( t: number, delaunay: Delaunator<number>, points?: any, ) => boolean export const enum ConcaveResult { Shell = 0, Hole = 1, Placeholder = 2, Broken = 3, } export type TriHash = { [details: number]: number } export type NumberHash = { [details: number]: number } export type ArrayHash = { [details: number]: number[] } export interface IExtremePoint { xr: { he: number val: number pi: number } xl: { he: number val: number pi: number } } export const enum ItemState { Unexplored = 0, Explored = 1, Invalid = 2, } // Helper Functions function getVector( edge: number, delaunay: Delaunator<number>, flip: boolean = false, ): [number, number] { const coords = delaunay.coords const triangles = delaunay.triangles const pi = triangles[edge] const p0 = [coords[pi * 2], coords[pi * 2 + 1]] const piNext = triangles[nextHalfedge(edge)] const p1 = [coords[piNext * 2], coords[piNext * 2 + 1]] if (flip) { return [p0[0] - p1[0], p0[1] - p1[1]] } else { return [p1[0] - p0[0], p1[1] - p0[1]] } } function get360Angle(v1: [number, number], v2: [number, number]) { const dot = dotProduct(v1, v2) const det = determinant(v1, v2) let ang = Math.atan2(det, dot) if (ang < 0) { ang += Math.PI * 2 } return ang } export function bboxArea(bbox: IBbox) { return Math.abs(bbox.xmax - bbox.xmin) * Math.abs(bbox.ymax - bbox.ymin) } export function getBBOXPoints( pointIndices: number[], delaunay: Delaunator<number>, bbox: IBbox, ) { const coords = delaunay.coords pointIndices.forEach(pi => { const x = coords[pi * 2] const y = coords[pi * 2 + 1] if (x < bbox.xmin) { bbox.xmin = x } else if (x > bbox.xmax) { bbox.xmax = x } if (y < bbox.ymin) { bbox.ymin = y } else if (y > bbox.ymax) { bbox.ymax = y } }) } export function getBboxPlane( planePatch: number[], delaunay: Delaunator<number>, ): IBbox { const triangles = delaunay.triangles const bbox = { xmin: Number.POSITIVE_INFINITY, ymin: Number.POSITIVE_INFINITY, xmax: Number.NEGATIVE_INFINITY, ymax: Number.NEGATIVE_INFINITY, } for (const t of planePatch) { const pointIndices = edgesOfTriangle(t).map((e: number) => triangles[e]) getBBOXPoints(pointIndices, delaunay, bbox) } return bbox } export function getHullEdge( incomingEdge: number, outgoingEdges: number[], delaunay: Delaunator<number>, isHole: boolean = false, ) { if (outgoingEdges.length > 2) { console.warn("More than 2 Hull edges!") } // turn incoming edge into a vector // vector should face opposite direction const v1 = getVector(incomingEdge, delaunay, true) // turn outgoing edges into a vector, dont invert const otherVectors = outgoingEdges.map((edge: number) => getVector(edge, delaunay, false), ) // Measure angle (between 0 and 360 degrees) between vectors const angleDist = otherVectors.map(outVector => { return get360Angle(v1, outVector) }) // Select vector with smallest angle difference let edgeIndex = 0 if (isHole) { edgeIndex = angleDist.indexOf(Math.min(...angleDist)) } else { edgeIndex = angleDist.indexOf(Math.max(...angleDist)) } return outgoingEdges[edgeIndex] } export function edgesOfTriangle(t: number): [number, number, number] { return [t * 3, t * 3 + 1, t * 3 + 2] } export function triangleOfEdge(e: number): number { return Math.floor(e / 3) } export function pointsOfTriangle(delaunay: Delaunator<number>, t: number) { return edgesOfTriangle(t).map((e: number) => delaunay.triangles[e]) } export function trianglesAdjacentToTriangle( delaunay: Delaunator<number>, t: number, ): number[] { const adjacentTriangles = [] for (const e of edgesOfTriangle(t)) { const opposite = delaunay.halfedges[e] if (opposite >= 0) { adjacentTriangles.push(triangleOfEdge(opposite)) } } return adjacentTriangles } export function nextHalfedge(e: number) { return e % 3 === 2 ? e - 2 : e + 1 } export function prevHalfedge(e: number) { return e % 3 === 0 ? e + 2 : e - 1 } function determinant(v1: [number, number], v2: [number, number]) { return v1[0] * v2[1] - v1[1] * v2[0] } export function norm(v1: [number, number]): number { return Math.sqrt(Math.pow(v1[0], 2) + Math.pow(v1[1], 2)) } function dotProduct(v1: [number, number], v2: [number, number]) { return v1[0] * v2[0] + v1[1] * v2[1] } export function dotProduct3(v1: [number, number, number], v2: [number, number, number]) { return v1[0] * v2[0] + v1[1] * v2[1] + v1[2] * v2[2] } export function triangleNormal(vv1:[number, number, number], vv2:[number, number, number], vv3: [number, number, number]): [number, number, number] { const u1 = vv2[0] - vv1[0] const u2 = vv2[1] - vv1[1] const u3 = vv2[2] - vv1[2] const v1 = vv3[0] - vv1[0] const v2 = vv3[1] - vv1[1] const v3 = vv3[2] - vv1[2] // # print(u1, u2, u3, v1, v2, v3) const ans = [0,0, 0] ans[0] = u2 * v3 - u3 * v2 ans[1] = u3 * v1 - u1 * v3 ans[2] = u1 * v2 - u2 * v1 const normTemp = Math.sqrt(ans[0] * ans[0] + ans[1] * ans[1] + ans[2] * ans[2]) return [ans[0] / normTemp, ans[1] / normTemp, ans[2] / normTemp] } function pi2Cord(pi: number, coords: Float64Array) { return [coords[pi * 2], coords[pi * 2 + 1]] } export function pointList2Edge( pointList: number[], delaunay: Delaunator<number>, ) { const coords = delaunay.coords const edges = [] for (let i = 0; i < pointList.length - 1; i++) { const p1 = pointList[i] const p2 = pointList[i + 1] edges.push([pi2Cord(p1, coords), pi2Cord(p2, coords)]) } edges.push([ pi2Cord(pointList[pointList.length - 1], coords), pi2Cord(pointList[0], coords), ]) return edges }
JeremyBYU/polylidarweb
demo/demo3D/plotly2d.ts
<gh_stars>1-10 function draw(delaunay, planes, polygons, config) { ctx.clearRect(0, 0, w, h) drawAxes() drawPlanesAndHull(planes, polygons, delaunay) const triangles = delaunay.triangles // Triangles if (config.drawTriangles) { ctx.beginPath() ctx.fillStyle = 'black' for (let i = 0; i < triangles.length; i += 3) { const p0 = triangles[i] const p1 = triangles[i + 1] const p2 = triangles[i + 2] const pc = getCentroid(points[p0], points[p1], points[p2]) ctx.moveTo(getX(p0), getY(p0)) ctx.lineTo(getX(p1), getY(p1)) ctx.lineTo(getX(p2), getY(p2)) // ctx.fillText((i / 3).toString(), getXPad(pc[0]), getYPad(pc[1])) ctx.closePath() } ctx.strokeStyle = 'black' ctx.lineWidth = 0.5 ctx.stroke() } // Hull ctx.beginPath() for (const i of delaunay.hull) { ctx.lineTo(getX(i), getY(i)) } ctx.closePath() ctx.lineWidth = 1 ctx.strokeStyle = 'red' ctx.stroke() // Points if (config.drawPoints) { ctx.fillStyle = 'black' ctx.beginPath() for (let i = 0; i < points.length; i++) { ctx.rect(getX(i) - 1.5, getY(i) - 1.5, 3, 3) } ctx.fill() } }
JeremyBYU/polylidarweb
__tests__/main.spec.ts
<filename>__tests__/main.spec.ts import { add } from '../src/main' describe('greeter function', () => { // Read more about fake timers: http://facebook.github.io/jest/docs/en/timer-mocks.html#content it('Adder add correctly', () => { expect(add(1,2)).toBe(3) }) })
JeremyBYU/polylidarweb
src/main.ts
import Delaunator from 'delaunator' import Denque from 'denque' // Type imports import { ArrayHash, IConfig2D, IConfig3D, IConfig4D, IExtremePoint, IPolygon, ItemState, IValidateTriangle, NumberHash, TriHash, } from './helper' import { bboxArea, dotProduct3, getBboxPlane, getHullEdge, nextHalfedge, norm, pointsOfTriangle, triangleNormal, trianglesAdjacentToTriangle, } from './helper' function instanceOfConfig3D( object: IConfig2D | IConfig3D, ): object is IConfig3D { return 'z_thresh' in object } function instanceOfConfig4D( object: IConfig2D | IConfig3D | IConfig4D, ): object is IConfig4D { return 'allowed_class' in object } function circumscribedRadius(points: number[][]) { const pa = points[0] const pb = points[1] const pc = points[2] const aLength = norm([pa[0] - pb[0], pa[1] - pb[1]]) const bLength = norm([pb[0] - pc[0], pb[1] - pc[1]]) const cLength = norm([pc[0] - pa[0], pc[1] - pa[1]]) const s = (aLength + bLength + cLength) / 2.0 const area = Math.sqrt(s * (s - aLength) * (s - bLength) * (s - cLength)) return (aLength * bLength * cLength) / (area * 4.0) } function validateTriangle2D(config: IConfig2D): IValidateTriangle { // @ts-ignore function validateTriangle2DClosure( t: number, delaunay: Delaunator<number>, _pointsOrig?: any, ) { const coords = delaunay.coords const points = pointsOfTriangle(delaunay, t).map((p: number) => { return [coords[p * 2], coords[p * 2 + 1]] }) if (config.xy_thresh) { if ( Math.abs(points[0][0] - points[1][0]) > config.xy_thresh || Math.abs(points[0][1] - points[1][1]) > config.xy_thresh ) { return false } if ( Math.abs(points[0][0] - points[2][0]) > config.xy_thresh || Math.abs(points[0][1] - points[2][1]) > config.xy_thresh ) { return false } if ( Math.abs(points[1][0] - points[2][0]) > config.xy_thresh || Math.abs(points[1][1] - points[2][1]) > config.xy_thresh ) { return false } } if (config.alpha && circumscribedRadius(points) > 1.0 / config.alpha) { return false } return true } return validateTriangle2DClosure } function validateTriangle3D(config: IConfig3D): IValidateTriangle { // @ts-ignore const validator2D = validateTriangle2D(config) function validateTriangle3DClosure( t: number, delaunay: Delaunator<number>, pointsAll?: any, ) { if (!validator2D(t, delaunay, pointsAll)) { return false } const points = pointsOfTriangle(delaunay, t).map((p: number) => { return [ pointsAll[p * config.dim], pointsAll[p * config.dim + 1], pointsAll[p * config.dim + 2], ] }) // Check if zThresh is met, then automatically allow the triangle if (config.z_thresh) { const zMin = Math.min(points[0][2], points[1][2], points[2][2]) const zMax = Math.max(points[0][2], points[1][2], points[2][2]) const diff = zMax - zMin // We return early here, normal filtering doesn't apply if (diff < config.z_thresh) { return true } } if (config.norm_thresh) { const normal = triangleNormal(points[0], points[1], points[2]) const dotProd = Math.abs(dotProduct3(normal, config.desired_vector)) if (dotProd < config.norm_thresh) { return false } } return true } return validateTriangle3DClosure } function validateTriangle4D(config: IConfig4D): IValidateTriangle { // @ts-ignore const validator3D = validateTriangle3D(config) function validateTriangle4DClosure( t: number, delaunay: Delaunator<number>, pointsAll?: any, ) { // Get all class points const pointsClass = pointsOfTriangle(delaunay, t).map((p: number) => { return pointsAll[p * config.dim + 3] }) // Get all class if (config.allowed_class !== undefined) { if (!pointsClass.every(pc => pc === config.allowed_class)) { return false } } if (!validator3D(t, delaunay, pointsAll)) { return false } return true } return validateTriangle4DClosure } function createTriangleHash( delaunay: Delaunator<number>, triValidator: IValidateTriangle, pointsAll: any, ): TriHash { const numTriangles = Math.floor(delaunay.triangles.length / 3) const triHash: TriHash = {} for (let t = 0; t < numTriangles; t++) { if (triValidator(t, delaunay, pointsAll)) { triHash[t] = ItemState.Unexplored } } return triHash } function extractMeshHash( delaunay: Delaunator<number>, triHash: TriHash, seedIdx: number, ) { // Create a new queue for triangle expansion const queue = new Denque<number>() // Push the seed idx on queue and remove from open set queue.push(seedIdx) // Delete from hash delete triHash[seedIdx] const candidates: number[] = [] while (!queue.isEmpty()) { const tri = queue.pop() candidates.push(tri) const unexploredNeighbors = trianglesAdjacentToTriangle( delaunay, tri, ).filter((triangle: number) => triHash[triangle] !== undefined) for (const triangleNeighbor of unexploredNeighbors) { queue.push(triangleNeighbor) delete triHash[triangleNeighbor] } } return candidates } export function applyPlaneConstraints( planePatch: number[], config: IConfig2D | IConfig3D, delaunay: Delaunator<number>, ) { if (planePatch.length < config.min_triangles) { return false } const bbox = getBboxPlane(planePatch, delaunay) if (bboxArea(bbox) < config.min_bbox_area) { return false } return true } export function create_planes( delaunay: Delaunator<number>, config: IConfig2D | IConfig3D, triValidator: IValidateTriangle, pointsAll: any, ) { // Create hash map // const numTriangles = Math.floor(delaunay.triangles.length / 3) const triHash = createTriangleHash(delaunay, triValidator, pointsAll) let triKeys = [] const allPlanes: number[][] = [] while (true) { triKeys = Object.keys(triHash) if (triKeys.length < 1) { break } const seedIdx = parseFloat(triKeys[0]) // const seedIdx = triKeys[0] const planePatch = extractMeshHash(delaunay, triHash, seedIdx) if (applyPlaneConstraints(planePatch, config, delaunay)) { allPlanes.push(planePatch) } } return allPlanes } export function extractPlanes( delaunay: Delaunator<number>, config: IConfig2D | IConfig2D | IConfig4D, pointsAll?: any, ): number[][] { // Check input dimension let planes: number[][] = [] let triangleValidator = validateTriangle2D(config) if (instanceOfConfig4D(config)) { triangleValidator = validateTriangle4D(config) } else if (instanceOfConfig3D(config)) { triangleValidator = validateTriangle3D(config) } planes = create_planes(delaunay, config, triangleValidator, pointsAll) return planes } function maxPoint( pi: number, delaunay: Delaunator<number>, extremePoint: IExtremePoint, he: number, ) { const points = delaunay.coords if (points[pi * 2] > extremePoint.xr.val) { extremePoint.xr.val = points[pi * 2] extremePoint.xr.he = he extremePoint.xr.pi = pi } if (points[pi * 2] < extremePoint.xl.val) { extremePoint.xl.val = points[pi * 2] extremePoint.xl.he = he extremePoint.xl.pi = pi } } function constructPointHash( plane: number[], delaunay: Delaunator<number>, ): [ArrayHash, NumberHash, NumberHash, IExtremePoint] { const triangles = delaunay.triangles const halfedges = delaunay.halfedges // all incoming half edges to a point index const pointHash: ArrayHash = {} // all valid triangles const triHash: NumberHash = {} // outgoing point indices const edgeHash: NumberHash = {} // create a hash of the triangles for (let i = 0; i < plane.length; i++) { triHash[plane[i]] = ItemState.Explored } const extremePoint = { xr: { he: undefined, val: Number.NEGATIVE_INFINITY, pi: undefined, }, xl: { he: undefined, val: Number.POSITIVE_INFINITY, pi: undefined, }, } // Loop through every triangle in plane for (let k = 0; k < plane.length; k++) { // convert triangle index to starting edge index const heIndex = plane[k] * 3 // iterate through all edges of triangle for (let j = 0; j < 3; j++) { // get correct edge offset const he = heIndex + j // get edge of ADJACENT triangle const oppHe = halfedges[he] // Check if adjacent triangle is NOT in our plane mesh if (oppHe === -1 || triHash[Math.floor(oppHe / 3)] === undefined) { // Record this edge edgeHash[he] = ItemState.Explored // Get the point that corresponds to the START of this edge const pi = triangles[he] // Check if this point is the right most extreme point maxPoint(pi, delaunay, extremePoint, he) // If this is not the first time we have seen this point, create a new array and push it to // the point hash, else just append it if (pointHash[pi] !== undefined) { pointHash[pi].push(he) } else { pointHash[pi] = [he] } } } } // We have returned a point hash, a triangle hash, and edgeHash, and the edge/point that is farthest to right return [pointHash, triHash, edgeHash, extremePoint] } function concaveSection( pointHash: ArrayHash, edgeHash: NumberHash, delaunay: Delaunator<number>, startEdge: number, stopPoint: number, isHole: boolean = false, ): number[] { const triangles = delaunay.triangles // const coords = delaunay.coords let workingEdge = startEdge // hull section that will be extracted, a collection of point INDICES const hullSection: number[] = [] // This will only find one concave hull on mesh while (true) { delete edgeHash[workingEdge] // Get the next EDGE of the SAME triangle const nextHalfEdge = nextHalfedge(workingEdge) // Get the starting point of this edge const nextPi = triangles[nextHalfEdge] // console.log(`Expanding point ${delaunay.coords[2 * nextPi]}, ${delaunay.coords[2 * nextPi + 1]} `) // Add point to hull section hullSection.push(nextPi) if (nextPi === stopPoint) { return hullSection } // Get outgoing edges for this point // filter edges that have already been seen! let nextEdges = pointHash[nextPi] if (nextEdges === undefined || nextEdges.length === 0) { console.error("Error! Possibly incorrect edge labeled as part of the concave hull") return [] } nextEdges = nextEdges.filter(edge => edgeHash[edge] !== undefined) if (nextEdges.length === 1) { workingEdge = nextEdges[0] } else { const newEdge = getHullEdge(workingEdge, nextEdges, delaunay, isHole) workingEdge = newEdge } } } function extractInteriorHoles( pointHash: ArrayHash, edgeHash: NumberHash, delaunay: Delaunator<number>, ) { const triangles = delaunay.triangles // Check if there are leftover **interior** holes of this mesh // We will be using the same extract concave section to get these holes const allHoles = [] let edgeKeys = Object.keys(edgeHash) if (edgeKeys.length == 1){ return allHoles } while (1) { edgeKeys = Object.keys(edgeHash) if (edgeKeys.length === 0) { break } const startEdge = parseFloat(edgeKeys[0]) const startingPointIndex = triangles[startEdge] const stopPoint = startingPointIndex // note the true argument at end. This tells the concave section that this edge is hole edge const hole = concaveSection( pointHash, edgeHash, delaunay, startEdge, stopPoint, false, ) allHoles.push(hole) } return allHoles } export function extractConcaveHull( plane: number[], delaunay: Delaunator<number>, _config?: IConfig2D | IConfig2D, ): IPolygon { if (plane.length < 1) { return undefined } // @ts-ignore const [pointHash, triHash, edgeHash, extremePoint] = constructPointHash( plane, delaunay, ) const startingHalfEdge = extremePoint.xr.he const startingPointIndex = extremePoint.xr.pi const stopPoint = startingPointIndex const shell = concaveSection( pointHash, edgeHash, delaunay, startingHalfEdge, stopPoint, false, ) const interiorHoles = extractInteriorHoles(pointHash, edgeHash, delaunay) return { shell: shell, holes: interiorHoles } } export function extractConcaveHulls( planes: number[][], delaunay: Delaunator<number>, config: IConfig2D | IConfig3D, ): IPolygon[] { // Each plane will be a polygon with possible holes in it const concaveHulls: IPolygon[] = [] for (const plane of planes) { const cHull = extractConcaveHull(plane, delaunay, config) concaveHulls.push(cHull) } return concaveHulls } export function extractPlanesAndPolygons( points: number[][], config: IConfig2D | IConfig3D, pointsAll?: any, ): [Delaunator<number>, number[][], IPolygon[]] { console.log(`Points Length: ${points.length}`) console.time('Delaunay') const delaunay = Delaunator.from(points) console.timeEnd('Delaunay') console.time('Extract Planes') const planes = extractPlanes(delaunay, config, pointsAll) console.timeEnd('Extract Planes') console.time('Extract Polygons') const polygons = extractConcaveHulls(planes, delaunay, config) console.timeEnd('Extract Polygons') return [delaunay, planes, polygons] }
JeremyBYU/polylidarweb
demo/demo3D/app.ts
// function import * as dat from 'dat.gui' import Plotly from 'plotly.js-dist' import {fileURLMapping, initializeGUI, initializePlots} from './utilities' window.addEventListener('load', () => { const [gui, config] = initializeGUI() initializePlots() })
JeremyBYU/polylidarweb
demo/demo3D/utilities.ts
import * as dat from 'dat.gui' import Plotly from 'plotly.js-dist' import { toPath } from 'svg-points' import { getBBOXPoints, IBbox, IConfig2D, IConfig3D, IPolygon } from '../../src/helper' import { extractPlanesAndPolygons } from '../../src/main' // import {initializeCanvas} from './canvas' // import {} from '' // File URLS const building1 = require('../../assets/data/building6_example2_360.csv') const building2 = require('../../assets/data/building6_example2_90.csv') const building3 = require('../../assets/data/building6_example_360.csv') const building4 = require('../../assets/data/building6_example_90.csv') const building5 = require('../../assets/data/building3_example_360.csv') const building6 = require('../../assets/data/building3_example_90.csv') const building7 = require('../../assets/data/building2_example3_360.csv') const building8 = require('../../assets/data/building2_example3_90.csv') const buildingURLS = [building1, building2, building3, building4, building5, building6, building7, building8] export const buildingKeys = ['building1-360', 'building1-90', 'building2-360', 'building2-90', 'building3-360', 'building3-90', 'building4-360', 'building4-90',] interface IRow { X: number Y: number Z: number C: number } export let DATA_ROWS: IRow[] export let points2D export let points4D export const shellColor = '#008000' export const holeColor = '#F67C3D' // this object houses all configuration const CONFIG = <IConfig3D>{ file: buildingKeys[0], pointColor: 'class', // 2D filtering Options min_bbox_area: 100, xy_thresh: 3, dim: 4, min_triangles: 15, alpha: 0.5, // 3D Filtering Options z_thresh: 0.2, norm_thresh: 0.9, desired_vector: [0, 0, 1], // Vis Options drawTriangles: false, drawPoints: false, filterClass: true } const PLOTLY_DIV_3D = 'plotly-div-3d' const PLOTLY_DIV_2D = 'plotly-div-2d' const camera3D = { center: { x: 0, y: 0, z: 0 }, } // Plotly 3D Scatter settings const trace3DPoints = { mode: 'markers', x: [1], y: [1], z: [1], marker: { size: 5, // line: { // color: 'rgba(217, 217, 217, 0.14)', // width: 0.01, // }, opacity: 0.5, color: [1], colorscale: 'Viridis', }, type: 'scatter3d', } const data3DScatter = [trace3DPoints] const layout3DScatter = { autosize: true, height: 500, title: '', font: { size: 12 }, scene: { camera: camera3D, }, } const layout2DShapes = { xaxis: { zeroline: false, autorange:true, range: [0,1] }, yaxis: { showgrid: false, autorange:true, range: [0,1] }, autosize: true, height: 500, shapes: [ //Quadratic Bezier Curves { type: 'path', path: 'M 4,4 Q 6,0 8,4', line: { color: 'rgb(93, 164, 214)', }, }, //Cubic Bezier Curves { type: 'path', path: 'M 1,4 C 2,8 6,4 8,8', line: { color: 'rgb(207, 114, 255)', }, }, //Filled Triangle { type: 'path', path: 'M 1 1 L 1 3 L 4 1 Z', fillcolor: 'rgba(44, 160, 101, 0.5)', line: { color: 'rgb(44, 160, 101)', }, }, //Filled Polygon { type: 'path', path: ' M 3,7 L2,8 L2,9 L3,10, L4,10 L5,9 L5,8 L4,7 Z', fillcolor: 'rgba(255, 140, 184, 0.5)', line: { color: 'rgb(255, 140, 184)', }, }, ], } function updatePointsBuffer() { let n = DATA_ROWS.length points2D = [] points4D = new Float64Array(n * 4) for (let i = 0; i < n; i++) { const p = DATA_ROWS[i] points2D.push([p.X, p.Y]) points4D[i * 4] = p.X points4D[i * 4 + 1] = p.Y points4D[i * 4 + 2] = p.Z points4D[i * 4 + 3] = p.C } } const fileURLS = buildingKeys.map((file: string, index: number) => { return { id: file, url: buildingURLS[index] } }) export const fileURLMapping = new Map(fileURLS.map(i => [i.id, i.url])) function unpack(rows: Object[], key: string) { return rows.map(row => { return row[key] }) } function loadCSV(fileURL: string) { function convertNumbers(row) { const r = {} for (const k in row) { r[k] = +row[k] if (isNaN(r[k])) { r[k] = row[k] } } return r } return new Promise((resolve, reject) => { Plotly.d3.csv(fileURL, convertNumbers, (error, request) => { if (error) { reject(error) } else { resolve(request) } }) }) } function drawTriangles(delaunay) { const triangles = delaunay.triangles const shapes = [] for (let i = 0; i < triangles.length; i += 3) { const p0 = triangles[i] const p1 = triangles[i + 1] const p2 = triangles[i + 2] const piPath = [p0, p1, p2] const polyStr = poly2String(piPath, points2D) shapes.push(createShape(polyStr, '', '#000000')) } return shapes } function poly2String(shell: number[], points2D: number[][]) { const pathString = shell .map((pi: number) => { return `${points2D[pi][0].toFixed(6)},${points2D[pi][1].toFixed(6)}` }) .join(' ') // console.log(pathString) const pathObject = { type: 'polygon', points: pathString } const svgString = toPath(pathObject) return svgString } function createShape(path:string, fillcolor:string='', linecolor:string=''){ return { type: 'path', path: path, fillcolor: fillcolor, line: { color: linecolor } } } export function plot2DShapes( points2D: number[][], delaunay, planes, polygons: IPolygon[], config, ) { const bbox:IBbox = {xmax: Number.NEGATIVE_INFINITY, xmin: Number.POSITIVE_INFINITY, ymax: Number.NEGATIVE_INFINITY, ymin: Number.POSITIVE_INFINITY} const svgPolygons = polygons.map((poly: IPolygon) => { getBBOXPoints(poly.shell, delaunay, bbox) const shell = poly2String(poly.shell, points2D) const holes = poly.holes.map((poly: number[]) => poly2String(poly, points2D), ) return { shell: shell, holes: holes} }) console.log(bbox) let shapes = [] svgPolygons.forEach((svgPoly, index: number) => { shapes.push(createShape(svgPoly.shell, '', shellColor)) svgPoly.holes.forEach(hole => shapes.push(createShape(hole,'',holeColor))) }) // const triShapes = drawTriangles(delaunay) // shapes = shapes.concat(triShapes) layout2DShapes.xaxis.range = [bbox.xmin, bbox.xmax] layout2DShapes.yaxis.range = [bbox.ymin, bbox.ymax] layout2DShapes.shapes = shapes Plotly.react(PLOTLY_DIV_2D, undefined, layout2DShapes) // console.log(shapes) } export function plot3DScatter() { const rows = DATA_ROWS let x = unpack(rows, 'X') let y = unpack(rows, 'Y') let z = unpack(rows, 'Z') let c = unpack(rows, 'C') let maxZ = Math.max(...z) // camera3D.center = [0, 0, 0] layout3DScatter.scene.camera.center.z = 0.15 trace3DPoints.x = x trace3DPoints.y = y trace3DPoints.z = z if (CONFIG.pointColor === 'class') { trace3DPoints.marker.color = c } else { trace3DPoints.marker.color = z } Plotly.react(PLOTLY_DIV_3D, data3DScatter, layout3DScatter, { responsive: true, }) } window.addEventListener('resize', e => { updateAll(true) }) function getConfig(config) { if (config.filterClass) { config.allowed_class = 4.0 } else { config.allowed_class = undefined } return { ...config} } export function updateAll(pointsChanged = true) { if (pointsChanged) { plot3DScatter() updatePointsBuffer() window.points2D = points2D } // perform computation const config = getConfig(CONFIG) console.log(config) const [delaunay, planes, polygons] = extractPlanesAndPolygons( points2D, config, points4D, ) plot2DShapes(points2D, delaunay, planes, polygons, config) // initializeCanvas(points2D, delaunay, planes, polygons, config) } export async function changeDataSource(value) { const url = fileURLMapping.get(value) DATA_ROWS = await loadCSV(url) updateAll() } export function initializeGUI() { const gui = new dat.GUI() const file = gui.add(CONFIG, 'file', buildingKeys) file.onChange(changeDataSource) const visFolder = gui.addFolder('Vis Options') visFolder .add(CONFIG, 'pointColor', ['height', 'class']) .name('Point Color') .onChange(plot3DScatter) visFolder .add(CONFIG, 'drawTriangles') .name('Draw Triangles') .onChange(() => updateAll(false)) visFolder .add(CONFIG, 'drawPoints') .name('Draw Points') .onChange(() => updateAll(false)) const configFolder = gui.addFolder('Algorithm Options') configFolder .add(CONFIG, 'min_bbox_area', 4, 100) .name('Min BBOX Area') .onChange(() => updateAll(false)) configFolder .add(CONFIG, 'xy_thresh', 0.0, 5) .name('Max X/Y Dist') .onChange(() => updateAll(false)) configFolder .add(CONFIG, 'min_triangles', 10, 50) .name('Min # of triangles for plane') .onChange(() => updateAll(false)) configFolder.add(CONFIG, 'alpha', 0.01, 1.0).onChange(() => updateAll(false)) configFolder .add(CONFIG, 'z_thresh', 0.1, 1) .name('Z Threshold') .onChange(() => updateAll(false)) configFolder .add(CONFIG, 'norm_thresh', 0.8, 1.0) .onChange(() => updateAll(false)) configFolder .add(CONFIG, 'filterClass') .name("Filter by Class") .onChange(() => updateAll(false)) const customContainer = document.getElementById('my-gui-container') customContainer.appendChild(gui.domElement) return [gui, CONFIG] } export async function initializePlots() { await changeDataSource(buildingKeys[0]) }
JeremyBYU/polylidarweb
demo/demo3D/canvas.ts
import Delaunator from 'delaunator' import { pointList2Edge, pointsOfTriangle, IPolygon } from '../../src/helper' // Will hold the 2D points let points:number[][] let points4D:Float64Array window.updated = false const padding = 20 const w = 400 let h // const h = 500 // let w let ratio let canvas let ctx let delaunay let planes let polygons let config let minX = Infinity let minY = Infinity let maxX = -Infinity let maxY = -Infinity const PX_BUFFER = 10 const AXES_STEPS = 10 const colorPalette = [ '#4878d0', '#ee854a', '#6acc64', '#d65f5f', '#956cb4', '#8c613c', '#dc7ec0', '#797979', '#d5bb67', '#82c6e2', ] function updateExtent(points) { for (let i = 0; i < points.length; i++) { const x = points[i][0] const y = points[i][1] if (x < minX) { minX = x } if (y < minY) { minY = y } if (x > maxX) { maxX = x } if (y > maxY) { maxY = y } } h = (w - padding * 2) * (maxY - minY) / (maxX - minX) + padding * 2 canvas.style.width = w + 'px' canvas.style.height = h + 'px' canvas.width = w canvas.height = h ratio = (w - padding * 2) / Math.max(maxX - minX, maxY - minY) } export function initializeCanvas(points2D:number[][], delaunay, planes, polygons, config) { points = points2D canvas = document.getElementById('canvas') ctx = canvas.getContext('2d') updateExtent(points) draw(delaunay, planes, polygons, config) } function getCentroid(p0, p1, p2) { return [(p0[0] + p1[0] + p2[0]) / 3, (p0[1] + p1[1] + p2[1]) / 3] } function getXPad(val) { return padding + ratio * (val - minX) } function getYPad(val) { return padding + ratio * (val - minY) } function getX(i) { return getXPad(points[i][0]) } function getY(i) { return getYPad(points[i][1]) } function drawAxes() { const xRange = maxX - minX const xStep = xRange / AXES_STEPS const yRange = maxY - minY const yStep = yRange / AXES_STEPS const tickSize = 0.03 const xTickSize = Math.floor(yRange * tickSize) const yTickSize = Math.floor(xRange * tickSize) ctx.beginPath() ctx.fillStyle = 'black' ctx.strokeStyle = 'black' for (let x = Math.ceil(minX); x <= minX + xRange; x += xStep) { const xVal = Math.floor(x) ctx.moveTo(getXPad(xVal), getYPad(maxY) + padding / 2) ctx.lineTo(getXPad(xVal), getYPad(maxY)) ctx.fillText( xVal.toFixed(1), getXPad(xVal - yTickSize), getYPad(maxY) + padding - 2, ) ctx.closePath() } for (let y = minY; y <= minY + yRange; y += yStep) { const yVal = Math.floor(y) ctx.moveTo(getXPad(minX) - padding / 2, getYPad(yVal)) ctx.lineTo(getXPad(minX), getYPad(yVal)) ctx.save() ctx.translate(getXPad(minX) - padding - 1, getYPad(yVal + xTickSize)) ctx.rotate(-Math.PI / 2) ctx.fillText(yVal.toFixed(1), 0, PX_BUFFER) ctx.restore() ctx.closePath() } ctx.stroke() } function drawEdges( edges, edgeColor: string = '#2EAC36', linewidth: number = 5.0, dashed: boolean = false, ) { ctx.strokeStyle = edgeColor ctx.lineWidth = linewidth if (dashed) { ctx.setLineDash([5, 15]) } else { ctx.setLineDash([]) } for (const edge of edges) { ctx.beginPath() const p0 = edge[0] const p1 = edge[1] ctx.moveTo(getXPad(p0[0]), getYPad(p0[1])) ctx.lineTo(getXPad(p1[0]), getYPad(p1[1])) ctx.stroke() } ctx.setLineDash([]) } function drawPlanesAndHull( planes, hulls: IPolygon[], delaunay, shellColor = '#008000', holeColor = '#F67C3D', ) { if (planes.length !== hulls.length) { console.error('Planes and Hull should be equal') } else { for (let i = 0; i < planes.length; i++) { const plane = planes[i] const polygon = hulls[i] const colorIndex = i % 10 const color = colorPalette[i] drawPlane(plane, color, delaunay) const outerShell = pointList2Edge(polygon.shell, delaunay) drawEdges(outerShell, shellColor, 5, false) for (const hole of polygon.holes) { const innerHole = pointList2Edge(hole, delaunay) drawEdges(innerHole, holeColor, 5, false) } } } } function drawPlane(plane, color, delaunay) { const triangles = delaunay.triangles ctx.beginPath() for (const t of plane) { const tindex = t * 3 const p0 = triangles[tindex] const p1 = triangles[tindex + 1] const p2 = triangles[tindex + 2] ctx.moveTo(getX(p0), getY(p0)) ctx.lineTo(getX(p1), getY(p1)) ctx.lineTo(getX(p2), getY(p2)) ctx.closePath() } ctx.strokeStyle = color ctx.fillStyle = color ctx.lineWidth = 0.5 ctx.stroke() ctx.fill() } function draw(delaunay, planes, polygons, config) { ctx.clearRect(0, 0, w, h) drawAxes() drawPlanesAndHull(planes, polygons, delaunay) const triangles = delaunay.triangles // Triangles if (config.drawTriangles) { ctx.beginPath() ctx.fillStyle = 'black' for (let i = 0; i < triangles.length; i += 3) { const p0 = triangles[i] const p1 = triangles[i + 1] const p2 = triangles[i + 2] const pc = getCentroid(points[p0], points[p1], points[p2]) ctx.moveTo(getX(p0), getY(p0)) ctx.lineTo(getX(p1), getY(p1)) ctx.lineTo(getX(p2), getY(p2)) // ctx.fillText((i / 3).toString(), getXPad(pc[0]), getYPad(pc[1])) ctx.closePath() } ctx.strokeStyle = 'black' ctx.lineWidth = 0.5 ctx.stroke() } // Hull ctx.beginPath() for (const i of delaunay.hull) { ctx.lineTo(getX(i), getY(i)) } ctx.closePath() ctx.lineWidth = 1 ctx.strokeStyle = 'red' ctx.stroke() // Points if (config.drawPoints) { ctx.fillStyle = 'black' ctx.beginPath() for (let i = 0; i < points.length; i++) { ctx.rect(getX(i) - 1.5, getY(i) - 1.5, 3, 3) } ctx.fill() } }
KawPum/domain-driven-hexagon
src/modules/user/dtos/user.response.dto.ts
import { UserEntity } from '@modules/user/domain/entities/user.entity'; import { ResponseBase } from 'src/interface-adapters/base-classes/response.base'; import { User } from 'src/interface-adapters/interfaces/user/user.interface'; import { ApiProperty } from '@nestjs/swagger'; export class UserResponse extends ResponseBase implements User { constructor(user: UserEntity) { super(user); this.email = user.email.value; this.country = user.address.country; this.postalCode = user.address.postalCode; this.street = user.address.street; } @ApiProperty({ example: '<EMAIL>', description: "User's email address", }) email: string; @ApiProperty({ example: 'France', description: "User's country of residence", }) country: string; @ApiProperty({ example: '123456', description: 'Postal code', }) postalCode: string; @ApiProperty({ example: 'Park Avenue', description: 'Street where the user is registered', }) street: string; }
rulonder/cesium-sensors-es6
src/rectangular/rectangular-pyramid-sensor-volume.ts
<reponame>rulonder/cesium-sensors-es6<filename>src/rectangular/rectangular-pyramid-sensor-volume.ts import { clone } from 'cesium'; import { defaultValue } from 'cesium'; import { defined } from 'cesium'; import { destroyObject } from 'cesium'; import { DeveloperError } from 'cesium'; import { Math as CesiumMath } from 'cesium'; import { Spherical } from 'cesium'; import { CustomSensorVolume } from '../custom/custom-sensor-volume'; var defineProperties = Object.defineProperties; function assignSpherical(index, array, clock, cone) { var spherical = array[index]; if (!defined(spherical)) { spherical = new Spherical(); array[index] = spherical; } spherical.clock = clock; spherical.cone = cone; spherical.magnitude = 1.0; } function updateDirections(rectangularSensor) { var directions = rectangularSensor._customSensor.directions; // At 90 degrees the sensor is completely open, and tan() goes to infinity. var tanX = Math.tan( Math.min(rectangularSensor._xHalfAngle, CesiumMath.toRadians(89.0)) ); var tanY = Math.tan( Math.min(rectangularSensor._yHalfAngle, CesiumMath.toRadians(89.0)) ); var theta = Math.atan(tanX / tanY); var cone = Math.atan(Math.sqrt(tanX * tanX + tanY * tanY)); assignSpherical(0, directions, theta, cone); assignSpherical(1, directions, CesiumMath.toRadians(180.0) - theta, cone); assignSpherical(2, directions, CesiumMath.toRadians(180.0) + theta, cone); assignSpherical(3, directions, -theta, cone); directions.length = 4; rectangularSensor._customSensor.directions = directions; } export function RectangularPyramidSensorVolume(this: any, options?) { options = defaultValue(options, (defaultValue as any).EMPTY_OBJECT); var customSensorOptions = clone(options); customSensorOptions._pickPrimitive = defaultValue( options._pickPrimitive, this ); customSensorOptions.directions = undefined; this._customSensor = new CustomSensorVolume(customSensorOptions); this._xHalfAngle = defaultValue(options.xHalfAngle, CesiumMath.PI_OVER_TWO); this._yHalfAngle = defaultValue(options.yHalfAngle, CesiumMath.PI_OVER_TWO); updateDirections(this); } defineProperties(RectangularPyramidSensorVolume.prototype, { xHalfAngle: { get: function() { return this._xHalfAngle; }, set: function(value) { // >>includeStart('debug', pragmas.debug) if (value > CesiumMath.PI_OVER_TWO) { throw new DeveloperError( 'xHalfAngle must be less than or equal to 90 degrees.' ); } // >>includeEnd('debug'); if (this._xHalfAngle !== value) { this._xHalfAngle = value; updateDirections(this); } }, }, yHalfAngle: { get: function() { return this._yHalfAngle; }, set: function(value) { // >>includeStart('debug', pragmas.debug) if (value > CesiumMath.PI_OVER_TWO) { throw new DeveloperError( 'yHalfAngle must be less than or equal to 90 degrees.' ); } // >>includeEnd('debug'); if (this._yHalfAngle !== value) { this._yHalfAngle = value; updateDirections(this); } }, }, show: { get: function() { return this._customSensor.show; }, set: function(value) { this._customSensor.show = value; }, }, showIntersection: { get: function() { return this._customSensor.showIntersection; }, set: function(value) { this._customSensor.showIntersection = value; }, }, showThroughEllipsoid: { get: function() { return this._customSensor.showThroughEllipsoid; }, set: function(value) { this._customSensor.showThroughEllipsoid = value; }, }, modelMatrix: { get: function() { return this._customSensor.modelMatrix; }, set: function(value) { this._customSensor.modelMatrix = value; }, }, radius: { get: function() { return this._customSensor.radius; }, set: function(value) { this._customSensor.radius = value; }, }, lateralSurfaceMaterial: { get: function() { return this._customSensor.lateralSurfaceMaterial; }, set: function(value) { this._customSensor.lateralSurfaceMaterial = value; }, }, intersectionColor: { get: function() { return this._customSensor.intersectionColor; }, set: function(value) { this._customSensor.intersectionColor = value; }, }, intersectionWidth: { get: function() { return this._customSensor.intersectionWidth; }, set: function(value) { this._customSensor.intersectionWidth = value; }, }, id: { get: function() { return this._customSensor.id; }, set: function(value) { this._customSensor.id = value; }, }, }); RectangularPyramidSensorVolume.prototype.update = function(frameState) { this._customSensor.update(frameState); }; RectangularPyramidSensorVolume.prototype.isDestroyed = function() { return false; }; RectangularPyramidSensorVolume.prototype.destroy = function() { this._customSensor = this._customSensor && this._customSensor.destroy(); return destroyObject(this); };
rulonder/cesium-sensors-es6
src/index.ts
import { initialize } from './initialize'; export { ConicSensorGraphics } from './conic/conic-sensor-graphics'; export { ConicSensorVisualizer } from './conic/conic-sensor-visualizer'; export { CustomPatternSensorGraphics } from './custom/custom-pattern-sensor-graphics'; export { CustomPatternSensorVisualizer } from './custom/custom-pattern-sensor-visualizer'; export { CustomSensorVolume } from './custom/custom-sensor-volume'; export { RectangularPyramidSensorVolume } from './rectangular/rectangular-pyramid-sensor-volume'; export { RectangularSensorGraphics } from './rectangular/rectangular-sensor-graphics'; export { RectangularSensorVisualizer } from './rectangular/rectangular-sensor-visualizer'; initialize();
rulonder/cesium-sensors-es6
types/types.d.ts
<filename>types/types.d.ts import "cesium" declare module "cesium" { /** * The interface for all properties, which represent a value that can optionally vary over time. * This type defines an interface and cannot be instantiated directly. */ export class PropertyExtended { constructor(); /** * Gets a value indicating if this property is constant. A property is considered * constant if getValue always returns the same result for the current definition. */ readonly isConstant: boolean; /** * Gets the event that is raised whenever the definition of this property changes. * The definition is considered to have changed if a call to getValue would return * a different result for the same time. */ readonly definitionChanged: Event; /** * Gets the value of the property at the provided time. * @param time - The time for which to retrieve the value. * @param [result] - The object to store the value into, if omitted, a new instance is created and returned. * @returns The modified result parameter or a new instance if the result parameter was not supplied. */ getValue(time: JulianDate, result?: any): any; /** * Compares this property to the provided property and returns * <code>true</code> if they are equal, <code>false</code> otherwise. * @param [other] - The other property. * @returns <code>true</code> if left and right are equal, <code>false</code> otherwise. */ equals(other?: Property): boolean; getValueOrClonedDefault(value, time, defaultValue, cloned); getValueOrDefault(value, time, defaultValue); getValueOrUndefined(value, time, defaultValue?); } }
rulonder/cesium-sensors-es6
src/custom/custom-pattern-sensor-graphics.ts
import { defaultValue } from 'cesium'; import { defined } from 'cesium'; import { DeveloperError } from 'cesium'; import { Event } from 'cesium'; import createMaterialPropertyDescriptor from 'cesium/Source/DataSources/createMaterialPropertyDescriptor'; import createPropertyDescriptor from 'cesium/Source/DataSources/createPropertyDescriptor'; var defineProperties = Object.defineProperties; /** * An optionally time-dynamic custom patterned sensor. * * @alias CustomPatternSensorGraphics * @constructor */ export function CustomPatternSensorGraphics(this: any, options?: any) { this._directions = undefined; this._directionsSubscription = undefined; this._lateralSurfaceMaterial = undefined; this._lateralSurfaceMaterialSubscription = undefined; this._intersectionColor = undefined; this._intersectionColorSubscription = undefined; this._intersectionWidth = undefined; this._intersectionWidthSubscription = undefined; this._showIntersection = undefined; this._showIntersectionSubscription = undefined; this._radius = undefined; this._radiusSubscription = undefined; this._show = undefined; this._showSubscription = undefined; this._definitionChanged = new Event(); this.merge(defaultValue(options, (defaultValue as any).EMPTY_OBJECT)); } defineProperties(CustomPatternSensorGraphics.prototype, { /** * Gets the event that is raised whenever a new property is assigned. * @memberof CustomPatternSensorGraphics.prototype * * @type {Event} * @readonly */ definitionChanged: { get: function() { return this._definitionChanged; }, }, /** * A {@link Property} which returns an array of {@link Spherical} instances representing the sensor's projection. * @memberof CustomPatternSensorGraphics.prototype * @type {Property} */ directions: createPropertyDescriptor('directions'), /** * Gets or sets the {@link MaterialProperty} specifying the the sensor's appearance. * @memberof CustomPatternSensorGraphics.prototype * @type {MaterialProperty} */ lateralSurfaceMaterial: createMaterialPropertyDescriptor( 'lateralSurfaceMaterial' ), /** * Gets or sets the {@link Color} {@link Property} specifying the color of the line formed by the intersection of the sensor and other central bodies. * @memberof CustomPatternSensorGraphics.prototype * @type {Property} */ intersectionColor: createPropertyDescriptor('intersectionColor'), /** * Gets or sets the numeric {@link Property} specifying the width of the line formed by the intersection of the sensor and other central bodies. * @memberof CustomPatternSensorGraphics.prototype * @type {Property} */ intersectionWidth: createPropertyDescriptor('intersectionWidth'), /** * Gets or sets the boolean {@link Property} specifying the visibility of the line formed by the intersection of the sensor and other central bodies. * @memberof CustomPatternSensorGraphics.prototype * @type {Property} */ showIntersection: createPropertyDescriptor('showIntersection'), /** * Gets or sets the numeric {@link Property} specifying the radius of the sensor's projection. * @memberof CustomPatternSensorGraphics.prototype * @type {Property} */ radius: createPropertyDescriptor('radius'), /** * Gets or sets the boolean {@link Property} specifying the visibility of the sensor. * @memberof CustomPatternSensorGraphics.prototype * @type {Property} */ show: createPropertyDescriptor('show'), }); /** * Duplicates a CustomPatternSensorGraphics instance. * * @param {CustomPatternSensorGraphics} [result] The object onto which to store the result. * @returns {CustomPatternSensorGraphics} The modified result parameter or a new instance if one was not provided. */ CustomPatternSensorGraphics.prototype.clone = function(result) { if (!defined(result)) { result = new CustomPatternSensorGraphics(); } result.directions = this.directions; result.radius = this.radius; result.show = this.show; result.showIntersection = this.showIntersection; result.intersectionColor = this.intersectionColor; result.intersectionWidth = this.intersectionWidth; result.lateralSurfaceMaterial = this.lateralSurfaceMaterial; return result; }; /** * Assigns each unassigned property on this object to the value * of the same property on the provided source object. * * @param {CustomPatternSensorGraphics} source The object to be merged into this object. */ CustomPatternSensorGraphics.prototype.merge = function(source) { // >>includeStart('debug', pragmas.debug); if (!defined(source)) { throw new DeveloperError('source is required.'); } // >>includeEnd('debug'); this.directions = defaultValue(this.directions, source.directions); this.radius = defaultValue(this.radius, source.radius); this.show = defaultValue(this.show, source.show); this.showIntersection = defaultValue( this.showIntersection, source.showIntersection ); this.intersectionColor = defaultValue( this.intersectionColor, source.intersectionColor ); this.intersectionWidth = defaultValue( this.intersectionWidth, source.intersectionWidth ); this.lateralSurfaceMaterial = defaultValue( this.lateralSurfaceMaterial, source.lateralSurfaceMaterial ); };
rulonder/cesium-sensors-es6
src/conic/conic-sensor-graphics.ts
import { defaultValue } from 'cesium'; import { defined } from 'cesium'; import { DeveloperError } from 'cesium'; import { Event } from 'cesium'; import createMaterialPropertyDescriptor from 'cesium/Source/DataSources/createMaterialPropertyDescriptor'; import createPropertyDescriptor from 'cesium/Source/DataSources/createPropertyDescriptor'; var defineProperties = Object.defineProperties; /** * An optionally time-dynamic cone. * * @alias ConicSensorGraphics * @constructor */ export function ConicSensorGraphics(this: any, options?: any) { this._minimumClockAngle = undefined; this._minimumClockAngleSubscription = undefined; this._maximumClockAngle = undefined; this._maximumClockAngleSubscription = undefined; this._innerHalfAngle = undefined; this._innerHalfAngleSubscription = undefined; this._outerHalfAngle = undefined; this._outerHalfAngleSubscription = undefined; this._lateralSurfaceMaterial = undefined; this._lateralSurfaceMaterialSubscription = undefined; this._intersectionColor = undefined; this._intersectionColorSubscription = undefined; this._intersectionWidth = undefined; this._intersectionWidthSubscription = undefined; this._showIntersection = undefined; this._showIntersectionSubscription = undefined; this._radius = undefined; this._radiusSubscription = undefined; this._show = undefined; this._showSubscription = undefined; this._definitionChanged = new Event(); this.merge(defaultValue(options, (defaultValue as any).EMPTY_OBJECT)); } defineProperties(ConicSensorGraphics.prototype, { /** * Gets the event that is raised whenever a new property is assigned. * @memberof ConicSensorGraphics.prototype * * @type {Event} * @readonly */ definitionChanged: { get: function() { return this._definitionChanged; }, }, /** * Gets or sets the numeric {@link Property} specifying the the cone's minimum clock angle. * @memberof ConicSensorGraphics.prototype * @type {Property} */ minimumClockAngle: createPropertyDescriptor('minimumClockAngle'), /** * Gets or sets the numeric {@link Property} specifying the the cone's maximum clock angle. * @memberof ConicSensorGraphics.prototype * @type {Property} */ maximumClockAngle: createPropertyDescriptor('maximumClockAngle'), /** * Gets or sets the numeric {@link Property} specifying the the cone's inner half-angle. * @memberof ConicSensorGraphics.prototype * @type {Property} */ innerHalfAngle: createPropertyDescriptor('innerHalfAngle'), /** * Gets or sets the numeric {@link Property} specifying the the cone's outer half-angle. * @memberof ConicSensorGraphics.prototype * @type {Property} */ outerHalfAngle: createPropertyDescriptor('outerHalfAngle'), /** * Gets or sets the {@link MaterialProperty} specifying the the cone's appearance. * @memberof ConicSensorGraphics.prototype * @type {MaterialProperty} */ lateralSurfaceMaterial: createMaterialPropertyDescriptor( 'lateralSurfaceMaterial' ), /** * Gets or sets the {@link Color} {@link Property} specifying the color of the line formed by the intersection of the cone and other central bodies. * @memberof ConicSensorGraphics.prototype * @type {Property} */ intersectionColor: createPropertyDescriptor('intersectionColor'), /** * Gets or sets the numeric {@link Property} specifying the width of the line formed by the intersection of the cone and other central bodies. * @memberof ConicSensorGraphics.prototype * @type {Property} */ intersectionWidth: createPropertyDescriptor('intersectionWidth'), /** * Gets or sets the boolean {@link Property} specifying the visibility of the line formed by the intersection of the cone and other central bodies. * @memberof ConicSensorGraphics.prototype * @type {Property} */ showIntersection: createPropertyDescriptor('showIntersection'), /** * Gets or sets the numeric {@link Property} specifying the radius of the cone's projection. * @memberof ConicSensorGraphics.prototype * @type {Property} */ radius: createPropertyDescriptor('radius'), /** * Gets or sets the boolean {@link Property} specifying the visibility of the cone. * @memberof ConicSensorGraphics.prototype * @type {Property} */ show: createPropertyDescriptor('show'), }); /** * Duplicates a ConicSensorGraphics instance. * * @param {ConicSensorGraphics} [result] The object onto which to store the result. * @returns {ConicSensorGraphics} The modified result parameter or a new instance if one was not provided. */ ConicSensorGraphics.prototype.clone = function(result) { if (!defined(result)) { result = new ConicSensorGraphics(); } result.show = this.show; result.innerHalfAngle = this.innerHalfAngle; result.outerHalfAngle = this.outerHalfAngle; result.minimumClockAngle = this.minimumClockAngle; result.maximumClockAngle = this.maximumClockAngle; result.radius = this.radius; result.showIntersection = this.showIntersection; result.intersectionColor = this.intersectionColor; result.intersectionWidth = this.intersectionWidth; result.lateralSurfaceMaterial = this.lateralSurfaceMaterial; return result; }; /** * Assigns each unassigned property on this object to the value * of the same property on the provided source object. * * @param {ConicSensorGraphics} source The object to be merged into this object. */ ConicSensorGraphics.prototype.merge = function(source: any) { // >>includeStart('debug', pragmas.debug); if (!defined(source)) { throw new DeveloperError('source is required.'); } // >>includeEnd('debug'); this.show = defaultValue(this.show, source.show); this.innerHalfAngle = defaultValue( this.innerHalfAngle, source.innerHalfAngle ); this.outerHalfAngle = defaultValue( this.outerHalfAngle, source.outerHalfAngle ); this.minimumClockAngle = defaultValue( this.minimumClockAngle, source.minimumClockAngle ); this.maximumClockAngle = defaultValue( this.maximumClockAngle, source.maximumClockAngle ); this.radius = defaultValue(this.radius, source.radius); this.showIntersection = defaultValue( this.showIntersection, source.showIntersection ); this.intersectionColor = defaultValue( this.intersectionColor, source.intersectionColor ); this.intersectionWidth = defaultValue( this.intersectionWidth, source.intersectionWidth ); this.lateralSurfaceMaterial = defaultValue( this.lateralSurfaceMaterial, source.lateralSurfaceMaterial ); };
rulonder/cesium-sensors-es6
src/initialize.ts
import { Cartesian3 } from 'cesium'; import { Color } from 'cesium'; import { defined } from 'cesium'; import { Spherical } from 'cesium'; import { TimeInterval } from 'cesium'; import { CzmlDataSource } from 'cesium'; import { DataSourceDisplay } from 'cesium'; import { ConicSensorGraphics } from './conic/conic-sensor-graphics'; import { ConicSensorVisualizer } from './conic/conic-sensor-visualizer'; import { CustomPatternSensorGraphics } from './custom/custom-pattern-sensor-graphics'; import { CustomPatternSensorVisualizer } from './custom/custom-pattern-sensor-visualizer'; import { RectangularSensorGraphics } from './rectangular/rectangular-sensor-graphics'; import { RectangularSensorVisualizer } from './rectangular/rectangular-sensor-visualizer'; var processPacketData = CzmlDataSource.processPacketData; var processMaterialPacketData = CzmlDataSource.processMaterialPacketData; function processDirectionData( customPatternSensor: any, directions: any, interval: any, sourceUri: any, entityCollection: any ) { var i; var len; var values: any[] = []; var unitSphericals = directions.unitSpherical; var sphericals = directions.spherical; var unitCartesians = directions.unitCartesian; var cartesians = directions.cartesian; if (defined(unitSphericals)) { for (i = 0, len = unitSphericals.length; i < len; i += 2) { values.push(new Spherical(unitSphericals[i], unitSphericals[i + 1])); } directions.array = values; } else if (defined(sphericals)) { for (i = 0, len = sphericals.length; i < len; i += 3) { values.push( new Spherical(sphericals[i], sphericals[i + 1], sphericals[i + 2]) ); } directions.array = values; } else if (defined(unitCartesians)) { for (i = 0, len = unitCartesians.length; i < len; i += 3) { var tmp = Spherical.fromCartesian3( new Cartesian3( unitCartesians[i], unitCartesians[i + 1], unitCartesians[i + 2] ) ); Spherical.normalize(tmp, tmp); values.push(tmp); } directions.array = values; } else if (defined(cartesians)) { for (i = 0, len = cartesians.length; i < len; i += 3) { values.push( Spherical.fromCartesian3( new Cartesian3(cartesians[i], cartesians[i + 1], cartesians[i + 2]) ) ); } directions.array = values; } processPacketData( Array, customPatternSensor, 'directions', directions, interval, sourceUri, entityCollection ); } function processCommonSensorProperties( sensor, sensorData, interval, sourceUri, entityCollection ) { processPacketData( Boolean, sensor, 'show', sensorData.show, interval, sourceUri, entityCollection ); processPacketData( Number, sensor, 'radius', sensorData.radius, interval, sourceUri, entityCollection ); processPacketData( Boolean, sensor, 'showIntersection', sensorData.showIntersection, interval, sourceUri, entityCollection ); processPacketData( Color as any, sensor, 'intersectionColor', sensorData.intersectionColor, interval, sourceUri, entityCollection ); processPacketData( Number, sensor, 'intersectionWidth', sensorData.intersectionWidth, interval, sourceUri, entityCollection ); processMaterialPacketData( sensor, 'lateralSurfaceMaterial', sensorData.lateralSurfaceMaterial, interval, sourceUri, entityCollection ); } function processConicSensor(entity, packet, entityCollection, sourceUri) { var conicSensorData = packet.agi_conicSensor; if (!defined(conicSensorData)) { return; } var interval; var intervalString = conicSensorData.interval; if (defined(intervalString)) { const iso8601Scratch = { iso8601: intervalString, }; interval = TimeInterval.fromIso8601(iso8601Scratch); } var conicSensor = entity.conicSensor; if (!defined(conicSensor)) { entity.addProperty('conicSensor'); conicSensor = new ConicSensorGraphics(); entity.conicSensor = conicSensor; } processCommonSensorProperties( conicSensor, conicSensorData, interval, sourceUri, entityCollection ); processPacketData( Number, conicSensor, 'innerHalfAngle', conicSensorData.innerHalfAngle, interval, sourceUri, entityCollection ); processPacketData( Number, conicSensor, 'outerHalfAngle', conicSensorData.outerHalfAngle, interval, sourceUri, entityCollection ); processPacketData( Number, conicSensor, 'minimumClockAngle', conicSensorData.minimumClockAngle, interval, sourceUri, entityCollection ); processPacketData( Number, conicSensor, 'maximumClockAngle', conicSensorData.maximumClockAngle, interval, sourceUri, entityCollection ); } function processCustomPatternSensor( entity, packet, entityCollection, sourceUri ) { var customPatternSensorData = packet.agi_customPatternSensor; if (!defined(customPatternSensorData)) { return; } var interval; var intervalString = customPatternSensorData.interval; if (defined(intervalString)) { const iso8601Scratch = { iso8601: intervalString, }; interval = TimeInterval.fromIso8601(iso8601Scratch); } var customPatternSensor = entity.customPatternSensor; if (!defined(customPatternSensor)) { entity.addProperty('customPatternSensor'); customPatternSensor = new CustomPatternSensorGraphics(); entity.customPatternSensor = customPatternSensor; } processCommonSensorProperties( customPatternSensor, customPatternSensorData, interval, sourceUri, entityCollection ); // The directions property is a special case value that can be an array of unitSpherical or unit Cartesians. // We pre-process this into Spherical instances and then process it like any other array. var directions = customPatternSensorData.directions; if (defined(directions)) { if (Array.isArray(directions)) { var length = directions.length; for (var i = 0; i < length; i++) { processDirectionData( customPatternSensor, directions[i], interval, sourceUri, entityCollection ); } } else { processDirectionData( customPatternSensor, directions, interval, sourceUri, entityCollection ); } } } function processRectangularSensor(entity, packet, entityCollection, sourceUri) { var rectangularSensorData = packet.agi_rectangularSensor; if (!defined(rectangularSensorData)) { return; } var interval; var intervalString = rectangularSensorData.interval; if (defined(intervalString)) { const iso8601Scratch = { iso8601: intervalString, }; interval = TimeInterval.fromIso8601(iso8601Scratch); } var rectangularSensor = entity.rectangularSensor; if (!defined(rectangularSensor)) { entity.addProperty('rectangularSensor'); rectangularSensor = new RectangularSensorGraphics(); entity.rectangularSensor = rectangularSensor; } processCommonSensorProperties( rectangularSensor, rectangularSensorData, interval, sourceUri, entityCollection ); processPacketData( Number, rectangularSensor, 'xHalfAngle', rectangularSensorData.xHalfAngle, interval, sourceUri, entityCollection ); processPacketData( Number, rectangularSensor, 'yHalfAngle', rectangularSensorData.yHalfAngle, interval, sourceUri, entityCollection ); } var initialized = false; export function initialize() { if (initialized) { return; } CzmlDataSource.updaters.push( processConicSensor, processCustomPatternSensor, processRectangularSensor ); var originalDefaultVisualizersCallback: any = DataSourceDisplay.defaultVisualizersCallback; DataSourceDisplay.defaultVisualizersCallback = function( scene, entityCluster, dataSource ) { var entities = dataSource.entities; var array = originalDefaultVisualizersCallback( scene, entityCluster, dataSource ); return array.concat([ new ConicSensorVisualizer(scene, entities), new CustomPatternSensorVisualizer(scene, entities), new RectangularSensorVisualizer(scene, entities), ]); } as any; initialized = true; }
rulonder/cesium-sensors-es6
src/rectangular/rectangular-sensor-graphics.ts
<reponame>rulonder/cesium-sensors-es6 import { defaultValue } from 'cesium'; import { defined } from 'cesium'; import { DeveloperError } from 'cesium'; import { Event } from 'cesium'; import createPropertyDescriptor from 'cesium/Source/DataSources/createPropertyDescriptor'; var defineProperties = Object.defineProperties; /** * An optionally time-dynamic pyramid. * * @alias RectangularSensorGraphics * @constructor */ export function RectangularSensorGraphics(this: any) { this._xHalfAngle = undefined; this._xHalfAngleSubscription = undefined; this._yHalfAngle = undefined; this._yHalfAngleSubscription = undefined; this._lateralSurfaceMaterial = undefined; this._lateralSurfaceMaterialSubscription = undefined; this._intersectionColor = undefined; this._intersectionColorSubscription = undefined; this._intersectionWidth = undefined; this._intersectionWidthSubscription = undefined; this._showIntersection = undefined; this._showIntersectionSubscription = undefined; this._radius = undefined; this._radiusSubscription = undefined; this._show = undefined; this._showSubscription = undefined; this._definitionChanged = new Event(); } defineProperties(RectangularSensorGraphics.prototype, { /** * Gets the event that is raised whenever a new property is assigned. * @memberof RectangularSensorGraphics.prototype * * @type {Event} * @readonly */ definitionChanged: { get: function() { return this._definitionChanged; }, }, /** * A {@link Property} which returns an array of {@link Spherical} instances representing the pyramid's projection. * @memberof RectangularSensorGraphics.prototype * @type {Property} */ xHalfAngle: createPropertyDescriptor('xHalfAngle'), /** * A {@link Property} which returns an array of {@link Spherical} instances representing the pyramid's projection. * @memberof RectangularSensorGraphics.prototype * @type {Property} */ yHalfAngle: createPropertyDescriptor('yHalfAngle'), /** * Gets or sets the {@link MaterialProperty} specifying the the pyramid's appearance. * @memberof RectangularSensorGraphics.prototype * @type {MaterialProperty} */ lateralSurfaceMaterial: createPropertyDescriptor('lateralSurfaceMaterial'), /** * Gets or sets the {@link Color} {@link Property} specifying the color of the line formed by the intersection of the pyramid and other central bodies. * @memberof RectangularSensorGraphics.prototype * @type {Property} */ intersectionColor: createPropertyDescriptor('intersectionColor'), /** * Gets or sets the numeric {@link Property} specifying the width of the line formed by the intersection of the pyramid and other central bodies. * @memberof RectangularSensorGraphics.prototype * @type {Property} */ intersectionWidth: createPropertyDescriptor('intersectionWidth'), /** * Gets or sets the boolean {@link Property} specifying the visibility of the line formed by the intersection of the pyramid and other central bodies. * @memberof RectangularSensorGraphics.prototype * @type {Property} */ showIntersection: createPropertyDescriptor('showIntersection'), /** * Gets or sets the numeric {@link Property} specifying the radius of the pyramid's projection. * @memberof RectangularSensorGraphics.prototype * @type {Property} */ radius: createPropertyDescriptor('radius'), /** * Gets or sets the boolean {@link Property} specifying the visibility of the pyramid. * @memberof RectangularSensorGraphics.prototype * @type {Property} */ show: createPropertyDescriptor('show'), }); /** * Duplicates a RectangularSensorGraphics instance. * * @param {RectangularSensorGraphics} [result] The object onto which to store the result. * @returns {RectangularSensorGraphics} The modified result parameter or a new instance if one was not provided. */ RectangularSensorGraphics.prototype.clone = function(result) { if (!defined(result)) { result = new RectangularSensorGraphics(); } result.xHalfAngle = this.xHalfAngle; result.yHalfAngle = this.yHalfAngle; result.radius = this.radius; result.show = this.show; result.showIntersection = this.showIntersection; result.intersectionColor = this.intersectionColor; result.intersectionWidth = this.intersectionWidth; result.lateralSurfaceMaterial = this.lateralSurfaceMaterial; return result; }; /** * Assigns each unassigned property on this object to the value * of the same property on the provided source object. * * @param {RectangularSensorGraphics} source The object to be merged into this object. */ RectangularSensorGraphics.prototype.merge = function(source) { // >>includeStart('debug', pragmas.debug); if (!defined(source)) { throw new DeveloperError('source is required.'); } // >>includeEnd('debug'); this.xHalfAngle = defaultValue(this.xHalfAngle, source.xHalfAngle); this.yHalfAngle = defaultValue(this.yHalfAngle, source.yHalfAngle); this.radius = defaultValue(this.radius, source.radius); this.show = defaultValue(this.show, source.show); this.showIntersection = defaultValue( this.showIntersection, source.showIntersection ); this.intersectionColor = defaultValue( this.intersectionColor, source.intersectionColor ); this.intersectionWidth = defaultValue( this.intersectionWidth, source.intersectionWidth ); this.lateralSurfaceMaterial = defaultValue( this.lateralSurfaceMaterial, source.lateralSurfaceMaterial ); };
rulonder/cesium-sensors-es6
src/custom/custom-sensor-volume.ts
<reponame>rulonder/cesium-sensors-es6 import { BoundingSphere } from 'cesium'; import { Cartesian3 } from 'cesium'; import { Color } from 'cesium'; import { combine } from 'cesium'; import { ComponentDatatype } from 'cesium'; import { defaultValue } from 'cesium'; import { defined } from 'cesium'; import { destroyObject } from 'cesium'; import { DeveloperError } from 'cesium'; import { Matrix4 } from 'cesium'; import { PrimitiveType } from 'cesium'; import Buffer from 'cesium/Source/Renderer/Buffer'; import BufferUsage from 'cesium/Source/Renderer/BufferUsage'; import DrawCommand from 'cesium/Source/Renderer/DrawCommand'; import Pass from 'cesium/Source/Renderer/Pass'; import RenderState from 'cesium/Source/Renderer/RenderState'; import ShaderProgram from 'cesium/Source/Renderer/ShaderProgram'; import ShaderSource from 'cesium/Source/Renderer/ShaderSource'; import VertexArray from 'cesium/Source/Renderer/VertexArray'; import { BlendingState } from 'cesium'; import { CullFace } from 'cesium'; import { Material } from 'cesium'; import { SceneMode } from 'cesium'; import CustomSensorVolumeFS from './custom-sensor-volume-fs.glsl'; import CustomSensorVolumeVS from './custom-sensor-volume-vs.glsl'; import SensorVolume from './sensor-volume.glsl'; var defineProperties = Object.defineProperties; var attributeLocations = { position: 0, normal: 1, }; var FAR = 5906376272000.0; // distance from the Sun to Pluto in meters. /** * DOC_TBA * * @alias CustomSensorVolume * @constructor */ export var CustomSensorVolume = function(this: any, options?) { options = defaultValue(options, (defaultValue as any).EMPTY_OBJECT); this._pickId = undefined; this._pickPrimitive = defaultValue(options._pickPrimitive, this); this._frontFaceColorCommand = new DrawCommand(); this._backFaceColorCommand = new DrawCommand(); this._pickCommand = new DrawCommand(); this._boundingSphere = new BoundingSphere(); this._boundingSphereWC = new BoundingSphere(); this._frontFaceColorCommand.primitiveType = PrimitiveType.TRIANGLES; this._frontFaceColorCommand.boundingVolume = this._boundingSphereWC; this._frontFaceColorCommand.owner = this; this._backFaceColorCommand.primitiveType = this._frontFaceColorCommand.primitiveType; this._backFaceColorCommand.boundingVolume = this._frontFaceColorCommand.boundingVolume; this._backFaceColorCommand.owner = this; this._pickCommand.primitiveType = this._frontFaceColorCommand.primitiveType; this._pickCommand.boundingVolume = this._frontFaceColorCommand.boundingVolume; this._pickCommand.owner = this; /** * <code>true</code> if this sensor will be shown; otherwise, <code>false</code> * * @type {Boolean} * @default true */ this.show = defaultValue(options.show, true); /** * When <code>true</code>, a polyline is shown where the sensor outline intersections the globe. * * @type {Boolean} * * @default true * * @see CustomSensorVolume#intersectionColor */ this.showIntersection = defaultValue(options.showIntersection, true); /** * <p> * Determines if a sensor intersecting the ellipsoid is drawn through the ellipsoid and potentially out * to the other side, or if the part of the sensor intersecting the ellipsoid stops at the ellipsoid. * </p> * * @type {Boolean} * @default false */ this.showThroughEllipsoid = defaultValue(options.showThroughEllipsoid, false); this._showThroughEllipsoid = this.showThroughEllipsoid; /** * The 4x4 transformation matrix that transforms this sensor from model to world coordinates. In it's model * coordinates, the sensor's principal direction is along the positive z-axis. The clock angle, sometimes * called azimuth, is the angle in the sensor's X-Y plane measured from the positive X-axis toward the positive * Y-axis. The cone angle, sometimes called elevation, is the angle out of the X-Y plane along the positive Z-axis. * <br /><br /> * <div align='center'> * <img src='images/CustomSensorVolume.setModelMatrix.png' /><br /> * Model coordinate system for a custom sensor * </div> * * @type {Matrix4} * @default {@link Matrix4.IDENTITY} * * @example * // The sensor's vertex is located on the surface at -75.59777 degrees longitude and 40.03883 degrees latitude. * // The sensor's opens upward, along the surface normal. * var center = Cesium.Cartesian3.fromDegrees(-75.59777, 40.03883); * sensor.modelMatrix = Cesium.Transforms.eastNorthUpToFixedFrame(center); */ this.modelMatrix = Matrix4.clone( defaultValue(options.modelMatrix, Matrix4.IDENTITY) ); this._modelMatrix = new Matrix4(); /** * DOC_TBA * * @type {Number} * @default {@link Number.POSITIVE_INFINITY} */ this.radius = defaultValue(options.radius, Number.POSITIVE_INFINITY); this._directions = undefined; this._directionsDirty = false; this.directions = defined(options.directions) ? options.directions : []; /** * The surface appearance of the sensor. This can be one of several built-in {@link Material} objects or a custom material, scripted with * {@link https://github.com/AnalyticalGraphicsInc/cesium/wiki/Fabric|Fabric}. * <p> * The default material is <code>Material.ColorType</code>. * </p> * * @type {Material} * @default Material.fromType(Material.ColorType) * * @see {@link https://github.com/AnalyticalGraphicsInc/cesium/wiki/Fabric|Fabric} * * @example * // 1. Change the color of the default material to yellow * sensor.lateralSurfaceMaterial.uniforms.color = new Cesium.Color(1.0, 1.0, 0.0, 1.0); * * // 2. Change material to horizontal stripes * sensor.lateralSurfaceMaterial = Cesium.Material.fromType(Material.StripeType); */ this.lateralSurfaceMaterial = defined(options.lateralSurfaceMaterial) ? options.lateralSurfaceMaterial : Material.fromType(Material.ColorType); this._lateralSurfaceMaterial = undefined; this._translucent = undefined; /** * The color of the polyline where the sensor outline intersects the globe. The default is {@link Color.WHITE}. * * @type {Color} * @default {@link Color.WHITE} * * @see CustomSensorVolume#showIntersection */ this.intersectionColor = Color.clone( defaultValue(options.intersectionColor, Color.WHITE) ); /** * The approximate pixel width of the polyline where the sensor outline intersects the globe. The default is 5.0. * * @type {Number} * @default 5.0 * * @see CustomSensorVolume#showIntersection */ this.intersectionWidth = defaultValue(options.intersectionWidth, 5.0); /** * User-defined object returned when the sensors is picked. * * @type Object * * @default undefined * * @see Scene#pick */ this.id = options.id; this._id = undefined; var that = this; /* eslint-disable camelcase */ this._uniforms = { u_showThroughEllipsoid: function() { return that.showThroughEllipsoid; }, u_showIntersection: function() { return that.showIntersection; }, u_sensorRadius: function() { return isFinite(that.radius) ? that.radius : FAR; }, u_intersectionColor: function() { return that.intersectionColor; }, u_intersectionWidth: function() { return that.intersectionWidth; }, u_normalDirection: function() { return 1.0; }, }; /* eslint-enable camelcase */ this._mode = SceneMode.SCENE3D; }; defineProperties(CustomSensorVolume.prototype, { directions: { get: function() { return this._directions; }, set: function(value) { this._directions = value; this._directionsDirty = true; }, }, }); var n0Scratch = new Cartesian3(); var n1Scratch = new Cartesian3(); var n2Scratch = new Cartesian3(); function computePositions(customSensorVolume) { var directions = customSensorVolume._directions; var length = directions.length; var positions = new Float32Array(3 * length); var r = isFinite(customSensorVolume.radius) ? customSensorVolume.radius : FAR; var boundingVolumePositions = [Cartesian3.ZERO]; for ( var i = length - 2, j = length - 1, k = 0; k < length; i = j++, j = k++ ) { // PERFORMANCE_IDEA: We can avoid redundant operations for adjacent edges. var n0 = Cartesian3.fromSpherical(directions[i], n0Scratch); var n1 = Cartesian3.fromSpherical(directions[j], n1Scratch); var n2 = Cartesian3.fromSpherical(directions[k], n2Scratch); // Extend position so the volume encompasses the sensor's radius. var theta = Math.max( Cartesian3.angleBetween(n0, n1), Cartesian3.angleBetween(n1, n2) ); var distance = r / Math.cos(theta * 0.5); var p = Cartesian3.multiplyByScalar(n1, distance, new Cartesian3()); positions[j * 3] = p.x; positions[j * 3 + 1] = p.y; positions[j * 3 + 2] = p.z; boundingVolumePositions.push(p); } BoundingSphere.fromPoints( boundingVolumePositions, customSensorVolume._boundingSphere ); return positions; } var nScratch = new Cartesian3(); function createVertexArray(customSensorVolume, context) { var positions = computePositions(customSensorVolume); var length = customSensorVolume._directions.length; var vertices = new Float32Array(2 * 3 * 3 * length); var k = 0; for (var i = length - 1, j = 0; j < length; i = j++) { var p0 = new Cartesian3( positions[i * 3], positions[i * 3 + 1], positions[i * 3 + 2] ); var p1 = new Cartesian3( positions[j * 3], positions[j * 3 + 1], positions[j * 3 + 2] ); var n = Cartesian3.normalize(Cartesian3.cross(p1, p0, nScratch), nScratch); // Per-face normals vertices[k++] = 0.0; // Sensor vertex vertices[k++] = 0.0; vertices[k++] = 0.0; vertices[k++] = n.x; vertices[k++] = n.y; vertices[k++] = n.z; vertices[k++] = p1.x; vertices[k++] = p1.y; vertices[k++] = p1.z; vertices[k++] = n.x; vertices[k++] = n.y; vertices[k++] = n.z; vertices[k++] = p0.x; vertices[k++] = p0.y; vertices[k++] = p0.z; vertices[k++] = n.x; vertices[k++] = n.y; vertices[k++] = n.z; } var vertexBuffer = Buffer.createVertexBuffer({ context: context, typedArray: new Float32Array(vertices), usage: BufferUsage.STATIC_DRAW, }); var stride = 2 * 3 * Float32Array.BYTES_PER_ELEMENT; var attributes = [ { index: attributeLocations.position, vertexBuffer: vertexBuffer, componentsPerAttribute: 3, componentDatatype: ComponentDatatype.FLOAT, offsetInBytes: 0, strideInBytes: stride, }, { index: attributeLocations.normal, vertexBuffer: vertexBuffer, componentsPerAttribute: 3, componentDatatype: ComponentDatatype.FLOAT, offsetInBytes: 3 * Float32Array.BYTES_PER_ELEMENT, strideInBytes: stride, }, ]; return new VertexArray({ context: context, attributes: attributes, }); } /** * Called when {@link Viewer} or {@link CesiumWidget} render the scene to * get the draw commands needed to render this primitive. * <p> * Do not call this function directly. This is documented just to * list the exceptions that may be propagated when the scene is rendered: * </p> * * @exception {DeveloperError} this.radius must be greater than or equal to zero. * @exception {DeveloperError} this.lateralSurfaceMaterial must be defined. */ CustomSensorVolume.prototype.update = function(frameState) { this._mode = frameState.mode; if (!this.show || this._mode !== SceneMode.SCENE3D) { return; } var context = frameState.context; var commandList = frameState.commandList; // >>includeStart('debug', pragmas.debug); if (this.radius < 0.0) { throw new DeveloperError( 'this.radius must be greater than or equal to zero.' ); } if (!defined(this.lateralSurfaceMaterial)) { throw new DeveloperError('this.lateralSurfaceMaterial must be defined.'); } // >>includeEnd('debug'); var translucent = this.lateralSurfaceMaterial.isTranslucent(); // Initial render state creation if ( this._showThroughEllipsoid !== this.showThroughEllipsoid || !defined(this._frontFaceColorCommand.renderState) || this._translucent !== translucent ) { this._showThroughEllipsoid = this.showThroughEllipsoid; this._translucent = translucent; var rs; if (translucent) { rs = RenderState.fromCache({ depthTest: { // This would be better served by depth testing with a depth buffer that does not // include the ellipsoid depth - or a g-buffer containing an ellipsoid mask // so we can selectively depth test. enabled: !this.showThroughEllipsoid, }, depthMask: false, blending: BlendingState.ALPHA_BLEND, cull: { enabled: true, face: CullFace.BACK, }, }); this._frontFaceColorCommand.renderState = rs; this._frontFaceColorCommand.pass = Pass.TRANSLUCENT; rs = RenderState.fromCache({ depthTest: { enabled: !this.showThroughEllipsoid, }, depthMask: false, blending: BlendingState.ALPHA_BLEND, cull: { enabled: true, face: CullFace.FRONT, }, }); this._backFaceColorCommand.renderState = rs; this._backFaceColorCommand.pass = Pass.TRANSLUCENT; rs = RenderState.fromCache({ depthTest: { enabled: !this.showThroughEllipsoid, }, depthMask: false, blending: BlendingState.ALPHA_BLEND, }); this._pickCommand.renderState = rs; } else { rs = RenderState.fromCache({ depthTest: { enabled: true, }, depthMask: true, }); this._frontFaceColorCommand.renderState = rs; this._frontFaceColorCommand.pass = Pass.OPAQUE; rs = RenderState.fromCache({ depthTest: { enabled: true, }, depthMask: true, }); this._pickCommand.renderState = rs; } } // Recreate vertex buffer when directions change var directionsChanged = this._directionsDirty; if (directionsChanged) { this._directionsDirty = false; this._va = this._va && this._va.destroy(); var directions = this._directions; if (directions && directions.length >= 3) { this._frontFaceColorCommand.vertexArray = createVertexArray( this, context ); this._backFaceColorCommand.vertexArray = this._frontFaceColorCommand.vertexArray; this._pickCommand.vertexArray = this._frontFaceColorCommand.vertexArray; } } if (!defined(this._frontFaceColorCommand.vertexArray)) { return; } var pass = frameState.passes; var modelMatrixChanged = !Matrix4.equals(this.modelMatrix, this._modelMatrix); if (modelMatrixChanged) { Matrix4.clone(this.modelMatrix, this._modelMatrix); } if (directionsChanged || modelMatrixChanged) { BoundingSphere.transform( this._boundingSphere, this.modelMatrix, this._boundingSphereWC ); } this._frontFaceColorCommand.modelMatrix = this.modelMatrix; this._backFaceColorCommand.modelMatrix = this._frontFaceColorCommand.modelMatrix; this._pickCommand.modelMatrix = this._frontFaceColorCommand.modelMatrix; var materialChanged = this._lateralSurfaceMaterial !== this.lateralSurfaceMaterial; this._lateralSurfaceMaterial = this.lateralSurfaceMaterial; this._lateralSurfaceMaterial.update(context); if (pass.render) { var frontFaceColorCommand = this._frontFaceColorCommand; var backFaceColorCommand = this._backFaceColorCommand; // Recompile shader when material changes if (materialChanged || !defined(frontFaceColorCommand.shaderProgram)) { var fsSource = new ShaderSource({ sources: [ SensorVolume, this._lateralSurfaceMaterial.shaderSource, CustomSensorVolumeFS, ], }); frontFaceColorCommand.shaderProgram = ShaderProgram.replaceCache({ context: context, shaderProgram: frontFaceColorCommand.shaderProgram, vertexShaderSource: CustomSensorVolumeVS, fragmentShaderSource: fsSource, attributeLocations: attributeLocations, }); frontFaceColorCommand.uniformMap = combine( this._uniforms, this._lateralSurfaceMaterial._uniforms ); backFaceColorCommand.shaderProgram = frontFaceColorCommand.shaderProgram; backFaceColorCommand.uniformMap = combine( this._uniforms, this._lateralSurfaceMaterial._uniforms ); // eslint-disable-next-line camelcase backFaceColorCommand.uniformMap.u_normalDirection = function() { return -1.0; }; } if (translucent) { commandList.push(this._backFaceColorCommand, this._frontFaceColorCommand); } else { commandList.push(this._frontFaceColorCommand); } } if (pass.pick) { var pickCommand = this._pickCommand; if (!defined(this._pickId) || this._id !== this.id) { this._id = this.id; this._pickId = this._pickId && this._pickId.destroy(); this._pickId = context.createPickId({ primitive: this._pickPrimitive, id: this.id, }); } // Recompile shader when material changes if (materialChanged || !defined(pickCommand.shaderProgram)) { var pickFS = new ShaderSource({ sources: [ SensorVolume, this._lateralSurfaceMaterial.shaderSource, CustomSensorVolumeFS, ], pickColorQualifier: 'uniform', }); pickCommand.shaderProgram = ShaderProgram.replaceCache({ context: context, shaderProgram: pickCommand.shaderProgram, vertexShaderSource: CustomSensorVolumeVS, fragmentShaderSource: pickFS, attributeLocations: attributeLocations, }); var that = this; var uniforms = { // eslint-disable-next-line camelcase czm_pickColor: function() { return that._pickId.color; }, }; pickCommand.uniformMap = combine( combine(this._uniforms, this._lateralSurfaceMaterial._uniforms), uniforms ); } pickCommand.pass = translucent ? Pass.TRANSLUCENT : Pass.OPAQUE; commandList.push(pickCommand); } }; /** * DOC_TBA */ CustomSensorVolume.prototype.isDestroyed = function() { return false; }; /** * DOC_TBA */ CustomSensorVolume.prototype.destroy = function() { this._frontFaceColorCommand.vertexArray = this._frontFaceColorCommand.vertexArray && this._frontFaceColorCommand.vertexArray.destroy(); this._frontFaceColorCommand.shaderProgram = this._frontFaceColorCommand.shaderProgram && this._frontFaceColorCommand.shaderProgram.destroy(); this._pickCommand.shaderProgram = this._pickCommand.shaderProgram && this._pickCommand.shaderProgram.destroy(); this._pickId = this._pickId && this._pickId.destroy(); return destroyObject(this); };
rulonder/cesium-sensors-es6
src/custom/custom-pattern-sensor-visualizer.ts
import { AssociativeArray } from 'cesium'; import { Cartesian3 } from 'cesium'; import { Color } from 'cesium'; import { defined } from 'cesium'; import { destroyObject } from 'cesium'; import { DeveloperError } from 'cesium'; import { Matrix3 } from 'cesium'; import { Matrix4 } from 'cesium'; import { Quaternion } from 'cesium'; import { MaterialProperty } from 'cesium'; import { Property as _Property, PropertyExtended } from 'cesium'; import { CustomSensorVolume } from '../custom/custom-sensor-volume'; import { removePrimitive } from '../util/remove-primitive'; const Property: PropertyExtended = (_Property as unknown) as PropertyExtended; var defaultIntersectionColor = Color.WHITE; var defaultIntersectionWidth = 1.0; var defaultRadius = Number.POSITIVE_INFINITY; var matrix3Scratch = new Matrix3(); var cachedPosition = new Cartesian3(); var cachedOrientation = new Quaternion(); /** * A {@link Visualizer} which maps {@link Entity#customPatternSensor} to a {@link CustomPatternSensor}. * @alias CustomPatternSensorVisualizer * @constructor * * @param {Scene} scene The scene the primitives will be rendered in. * @param {EntityCollection} entityCollection The entityCollection to visualize. */ export var CustomPatternSensorVisualizer = function( this: any, scene, entityCollection ) { // >>includeStart('debug', pragmas.debug); if (!defined(scene)) { throw new DeveloperError('scene is required.'); } if (!defined(entityCollection)) { throw new DeveloperError('entityCollection is required.'); } // >>includeEnd('debug'); entityCollection.collectionChanged.addEventListener( CustomPatternSensorVisualizer.prototype._onCollectionChanged, this ); this._scene = scene; this._primitives = scene.primitives; this._entityCollection = entityCollection; this._hash = {}; this._entitiesToVisualize = new AssociativeArray(); this._onCollectionChanged(entityCollection, entityCollection.values, [], []); }; /** * Updates the primitives created by this visualizer to match their * Entity counterpart at the given time. * * @param {JulianDate} time The time to update to. * @returns {Boolean} This function always returns true. */ CustomPatternSensorVisualizer.prototype.update = function(time) { // >>includeStart('debug', pragmas.debug); if (!defined(time)) { throw new DeveloperError('time is required.'); } // >>includeEnd('debug'); var entities = this._entitiesToVisualize.values; var hash = this._hash; var primitives = this._primitives; for (var i = 0, len = entities.length; i < len; i++) { var entity = entities[i]; var customPatternSensorGraphics = entity._customPatternSensor; var position; var orientation; var directions; var data = hash[entity.id]; var show = entity.isShowing && entity.isAvailable(time) && Property.getValueOrDefault(customPatternSensorGraphics._show, time, true); if (show) { position = Property.getValueOrUndefined( entity._position, time, cachedPosition ); orientation = Property.getValueOrUndefined( entity._orientation, time, cachedOrientation ); directions = Property.getValueOrUndefined( customPatternSensorGraphics._directions, time ); show = defined(position) && defined(orientation) && defined(directions); } if (!show) { // don't bother creating or updating anything else if (defined(data)) { data.primitive.show = false; } continue; } var primitive = defined(data) ? data.primitive : undefined; if (!defined(primitive)) { primitive = new CustomSensorVolume(); primitive.id = entity; primitives.add(primitive); data = { primitive: primitive, position: undefined, orientation: undefined, }; hash[entity.id] = data; } if ( !Cartesian3.equals(position, data.position) || !Quaternion.equals(orientation, data.orientation) ) { Matrix4.fromRotationTranslation( Matrix3.fromQuaternion(orientation, matrix3Scratch), position, primitive.modelMatrix ); data.position = Cartesian3.clone(position, data.position); data.orientation = Quaternion.clone(orientation, data.orientation); } primitive.show = true; primitive.directions = directions; primitive.radius = Property.getValueOrDefault( customPatternSensorGraphics._radius, time, defaultRadius ); primitive.lateralSurfaceMaterial = (MaterialProperty as any).getValue( time, customPatternSensorGraphics._lateralSurfaceMaterial, primitive.lateralSurfaceMaterial ); primitive.intersectionColor = Property.getValueOrClonedDefault( customPatternSensorGraphics._intersectionColor, time, defaultIntersectionColor, primitive.intersectionColor ); primitive.intersectionWidth = Property.getValueOrDefault( customPatternSensorGraphics._intersectionWidth, time, defaultIntersectionWidth ); } return true; }; /** * Returns true if this object was destroyed; otherwise, false. * * @returns {Boolean} True if this object was destroyed; otherwise, false. */ CustomPatternSensorVisualizer.prototype.isDestroyed = function() { return false; }; /** * Removes and destroys all primitives created by this instance. */ CustomPatternSensorVisualizer.prototype.destroy = function() { var entities = this._entitiesToVisualize.values; var hash = this._hash; var primitives = this._primitives; for (var i = entities.length - 1; i > -1; i--) { removePrimitive(entities[i], hash, primitives); } return destroyObject(this); }; /** * @private */ CustomPatternSensorVisualizer.prototype._onCollectionChanged = function( _, added, removed, changed ) { var i; var entity; var entities = this._entitiesToVisualize; var hash = this._hash; var primitives = this._primitives; for (i = added.length - 1; i > -1; i--) { entity = added[i]; if ( defined(entity._customPatternSensor) && defined(entity._position) && defined(entity._orientation) ) { entities.set(entity.id, entity); } } for (i = changed.length - 1; i > -1; i--) { entity = changed[i]; if ( defined(entity._customPatternSensor) && defined(entity._position) && defined(entity._orientation) ) { entities.set(entity.id, entity); } else { removePrimitive(entity, hash, primitives); entities.remove(entity.id); } } for (i = removed.length - 1; i > -1; i--) { entity = removed[i]; removePrimitive(entity, hash, primitives); entities.remove(entity.id); } };
rulonder/cesium-sensors-es6
src/util/remove-primitive.ts
import Cesium, { defined } from 'cesium'; export function removePrimitive( entity: Cesium.Entity, hash: any, primitives: Cesium.EntityCollection ) { var data = hash[entity.id]; if (defined(data)) { var primitive = data.primitive; primitives.remove(primitive); if (!primitive.isDestroyed()) { primitive.destroy(); } delete hash[entity.id]; } }
tywmick/tymick.me
theme/colors.ts
import { merge } from "lodash"; import chroma from "chroma-js"; import type { ColorScale } from "@emotion/react"; const colors: ColorScale = { white: "#fff", gray100: "#f8f9fa", gray200: "#e9ecef", gray300: "#dee2e6", gray400: "#ced4da", gray500: "#adb5bd", gray600: "#6c757d", gray700: "#495057", gray800: "#343a40", gray900: "#212529", black: "#000", blue: "#007bff", indigo: "#6610f2", purple: "#6f42c1", pink: "#e83e8c", red: "#dc3545", orange: "#fd7e14", yellow: "#ffc107", green: "#28a745", teal: "#20c997", cyan: "#17a2b8", }; merge<ColorScale, ColorScale>(colors, { gray: colors.gray600, grayDark: colors.gray800, primary: colors.blue, secondary: colors.gray600, success: colors.green, info: colors.cyan, warning: colors.yellow, danger: colors.red, light: colors.gray100, dark: colors.gray800, }); merge<ColorScale, ColorScale>(colors, { light: { primary: chroma(colors.primary as string) .brighten() .hex(), }, }); merge(colors, { light: { primaryHoverFocus: chroma(colors.light["primary"]).brighten(0.5).hex(), }, }); export default colors;
tywmick/tymick.me
pages/portfolio.tsx
<filename>pages/portfolio.tsx import React from "react"; import Head from "next/head"; import { Container } from "react-bootstrap"; import TeX from "@matejmazur/react-katex"; import PortfolioSection from "../components/PortfolioSection"; import A from "../components/Link"; export default function Portfolio() { return ( <> <Head> <title>Portfolio – <NAME></title> </Head> <Container className="cap-width-lg"> <h1>Portfolio</h1> <PortfolioSection name="Published papers and articles" id="papers-articles" projects={[ <> <cite className="text-muted">Towards Data Science</cite> <ul className="mb-1"> <li> <a href="https://towardsdatascience.com/loan-risk-neural-network-30c8f65f052e"> Building a Neural Network to Predict Loan Risk </a> </li> <li> <a href="https://towardsdatascience.com/loan-grading-showdown-ba64110c99f2"> Can I Grade Loans Better Than LendingClub? </a> </li> <li> <a href="https://towardsdatascience.com/loan-risk-nlp-d98021613ff3"> Natural Language Processing for Loan Risk </a> </li> </ul> </>, <> <cite className="text-muted"> Defense Technical Information Center </cite> <ul className="mb-1"> <li> <a href="https://apps.dtic.mil/sti/citations/AD1012051"> Readiness Based Sparing: A Research Summary </a> </li> <li> <a href="https://apps.dtic.mil/sti/citations/AD1012101"> The Case for AFMC Social Media Analysis </a> </li> </ul> </>, <> <cite className="text-muted">Hacker Noon</cite> <ul className="mb-1"> <li> <a href="https://hackernoon.com/loan-risk-prediction-using-neural-network-algorithm-gg4q3uu2"> Loan Risk Prediction Using Neural Networks </a> </li> <li> <a href="https://hackernoon.com/can-i-grade-loans-better-than-lendingclub-xgt3wue"> Can I Grade Loans Better Than LendingClub? </a> </li> <li> <a href="https://hackernoon.com/making-a-browser-console-log-wait-until-page-reloads-a-how-to-guide-2j1z3yt9"> Making a Browser Console Log Wait Until Page Reloads [A How-To Guide] </a> </li> </ul> </>, <> <cite className="text-muted">JavaScript in Plain English</cite> <ul> <li> <a href="https://medium.com/javascript-in-plain-english/how-to-make-a-browser-console-log-wait-until-after-a-page-reload-bccc538c9938"> Make a Browser Console Log Wait for a Page Reload </a> </li> </ul> </>, ]} /> <PortfolioSection name="Machine learning models" id="machine-learning" projects={[ <> <a href="https://www.kaggle.com/tywmick/building-a-neural-network-to-predict-loan-risk"> Loan risk prediction using neural network regression </a> <ul> <li> <a href="https://tywmick.pythonanywhere.com"> Flask API serving this model&rsquo;s predictions </a> </li> </ul> </>, <a href="https://www.kaggle.com/tywmick/natural-language-processing-for-loan-risk"> Natural language processing of loan applications </a>, ]} /> <PortfolioSection name="Interactive data visualizations" id="data-visualizations" projects={[ <a href="https://rtsimulator.com"> <TeX as="var">R_t</TeX> Simulator </a>, ]} /> <PortfolioSection name="APIs and microservices" id="apis" projects={[ <> Python/Flask with SQLite <ul className="mb-1"> <li> <a href="https://library-python.tymick.me"> Personal library </a> </li> <li> <a href="https://stock-checker-python.tymick.me"> Stock price checker </a> </li> <li> <a href="https://issue-tracker-python.tymick.me"> Issue tracker </a> </li> <li> <a href="https://message-board-python.tymick.me"> Anonymous message board </a> </li> <li> <a href="https://exercise-tracker-python.tymick.me"> Exercise tracker </a> </li> <li> <a href="https://url-shortener-python.tymick.me"> URL shortener </a> </li> </ul> </>, <> Python/Flask <ul className="mb-1"> <li> <a href="https://ty-metricimpconverter-python.glitch.me"> Metric-imperial converter </a> </li> <li> <a href="https://ty-file-metadata-python.glitch.me"> File metadata microservice </a> </li> <li> <a href="https://ty-timestamp-python.glitch.me"> Timestamp microservice </a> </li> <li> <a href="https://ty-headerparser-python.glitch.me"> Request header parser </a> </li> </ul> </>, <> Node.js/Express with MongoDB <ul className="mb-1"> <li> <a href="https://ty-library.glitch.me">Personal library</a> </li> <li> <a href="https://ty-stockchecker.glitch.me"> Stock price checker </a> </li> <li> <a href="https://ty-issue-tracker.glitch.me">Issue tracker</a> </li> <li> <a href="https://ty-messageboard.glitch.me"> Anonymous message board </a> </li> <li> <a href="https://ty-exercise-tracker.glitch.me"> Exercise tracker </a> </li> <li> <a href="https://ty-urlshortener.glitch.me">URL shortener</a> </li> </ul> </>, <> Node.js/Express <ul> <li> <a href="https://ty-metricimpconverter.glitch.me"> Metric-imperial converter </a> </li> <li> <a href="https://ty-file-metadata.glitch.me"> File metadata microservice </a> </li> <li> <a href="https://ty-timestamp.glitch.me"> Timestamp microservice </a> </li> <li> <a href="https://ty-headerparser.glitch.me"> Request header parser </a> </li> </ul> </>, ]} /> <PortfolioSection name="Data structure implementations" id="data-structures" projects={[ <a href="https://github.com/TyMick/data-structures#readme"> 12 common data structures in C, TypeScript, and Python </a>, ]} /> <PortfolioSection name="Full-stack web apps" id="full-stack" projects={[ <a href="https://real-estate-listing-page.tymick.me"> Real estate listing page </a>, <a href="https://nextjs-local-authentication.tymick.me"> Next.js + MongoDB local authentication boilerplate </a>, <A href="/project/personal-site" title="About this site"> Personal portfolio/blog site </A>, ]} /> <PortfolioSection name="WordPress themes" id="wordpress" projects={[ <a href="https://ty-mick-wordpress-port.000webhostapp.com"> Personal site WordPress port </a>, ]} /> <PortfolioSection name="Single-page apps" id="single-page-apps" projects={[ <> React <ul className="mb-1"> <li> <a href="https://ty-pomodoro-clock.glitch.me/"> Pomodoro clock </a> </li> <li> <a href="https://codepen.io/TyMick/full/BaBVeVO"> Calculator </a> </li> <li> <a href="https://codepen.io/TyMick/full/zYOaPyW"> Drum machine </a> </li> <li> <a href="https://codepen.io/TyMick/full/PoYeapB"> Markdown previewer </a> </li> </ul> </>, <> PHP <ul> <li> <a href="http://php-todo.tymick.me/">To-do list</a> </li> </ul> </>, ]} /> <PortfolioSection name="React hooks" id="react-hooks" projects={[ <a href="https://www.npmjs.com/package/use-window-width-breakpoints"> useWindowWidthBreakpoints </a>, <a href="https://www.npmjs.com/package/use-window-orientation"> useWindowOrientation </a>, ]} /> <PortfolioSection name="Selected open-source contributions" id="open-source" projects={[ <> <a href="https://github.com/pulls?q=user%3AFaithlife+author%3ATyMick+is%3Apr+is%3Amerged"> Feature development and bug fixes </a>{" "} for Faithlife </>, <> <a href="https://github.com/vercel/next.js/pulls?q=author%3ATyMick+is%3Apr+is%3Amerged"> Bug fixes and documentation help </a>{" "} for Next.js </>, <> <a href="https://github.com/MatejBransky/react-katex/pulls?q=author%3ATyMick+is%3Apr+is%3Amerged"> New feature and bug fixes </a>{" "} for react-katex </>, <> <a href="https://github.com/pablopunk/nextjs-redirect/pulls?q=author%3ATyMick+is%3Apr+is%3Amerged"> New features </a>{" "} for nextjs-redirect </>, <> <a href="https://github.com/freeCodeCamp/freeCodeCamp/pulls?q=author%3ATyMick+is%3Apr+is%3Amerged"> Curriculum help </a>{" "} for freeCodeCamp </>, <> <a href="https://github.com/tensorflow/tensorflow/pull/41599"> Documentation help </a>{" "} for TensorFlow </>, <> <a href="https://github.com/pandas-dev/pandas/pull/35337"> Documentation help </a>{" "} for pandas </>, <> <a href="https://github.com/rtcovidlive/covid-model/pull/27"> Formatting help </a>{" "} for R<sub>t</sub> Live&rsquo;s COVID-19 model </>, <> <a href="https://github.com/twbs/bootstrap/pull/30010"> Documentation help </a>{" "} for Bootstrap </>, <> <a href="https://github.com/styled-components/styled-components-website/pull/744"> Documentation help </a>{" "} for styled-components </>, <> <a href="https://github.com/brefphp/bref/pull/760"> Documentation help </a>{" "} for Bref </>, <> <a href="https://github.com/ant-design/ant-design/pull/23917"> Documentation help </a>{" "} for Ant Design </>, <> <a href="https://gitlab.com/codeshelter/codeshelter-web/-/merge_requests/10"> Documentation help </a>{" "} for Code Shelter </>, <> <a href="https://github.com/pulls?q=user%3AVSCodium+author%3ATyMick+is%3Apr+is%3Amerged"> Documentation help </a>{" "} for VSCodium </>, ]} /> </Container> </> ); }
tywmick/tymick.me
pages/_app.tsx
<reponame>tywmick/tymick.me import React from "react"; import Router from "next/router"; import { AppProps } from "next/app"; import { MDXProvider } from "@mdx-js/react"; import NProgress from "nprogress"; import Nav from "../components/Nav"; import Footer from "../components/Footer"; import mdxComponents from "../components/mdxComponents"; import { config } from "@fortawesome/fontawesome-svg-core"; import { ThemeProvider } from "@emotion/react"; import theme from "../theme"; import "../styles/index.scss"; config.autoAddCss = false; Router.events.on("routeChangeStart", () => NProgress.start()); Router.events.on("routeChangeComplete", () => NProgress.done()); Router.events.on("routeChangeError", () => NProgress.done()); export default function App({ Component, pageProps }: AppProps) { return ( <ThemeProvider theme={theme}> <Nav /> <main className="mb-5"> <MDXProvider components={mdxComponents}> <Component {...pageProps} /> </MDXProvider> </main> <Footer /> </ThemeProvider> ); }
tywmick/tymick.me
components/Image.tsx
import React from "react"; import NextImage, { ImageProps as NextImageProps } from "next/image"; import styled from "@emotion/styled"; import { layout, LayoutProps } from "styled-system"; import clsx from "clsx"; import filterProps from "../lib/filterProps"; type WrapperProps = LayoutProps & { className?: string }; type FilteredNextImageProps = Omit< Omit<Omit<Omit<NextImageProps, "width">, "height">, "layout">, "className" >; export type ImageProps = FilteredNextImageProps & WrapperProps & { dimensions?: { width: number; height: number; }; rounded?: boolean; roundedCircle?: boolean; thumbnail?: boolean; border?: boolean; }; /** * A React Bootstrap `Image`–like wrapper around the Next.js `Image` component. * @see {@link https://react-bootstrap.github.io/components/images/ React Bootstrap `Image`} */ export default function Image({ dimensions, rounded = false, roundedCircle = false, thumbnail = false, border = false, ...otherProps }: ImageProps) { /** * @todo Create a way to fetch image dimensions automatically with * [probe-image-size][1] from `_app.tsx` during build with `getStaticProps` * once [that feature][2] is enabled (which they [plan to do][3] eventually). * Then, provide these image dimensions via [context][4] from `_app`, and * [consume that context][5] here. * * Probably keep an array list somewhere of external image sources you wish to * optimize, and then `_app`'s `getStaticProps` will check that list and also * every file in `public/images`. * * [1]: https://github.com/nodeca/probe-image-size * [2]: https://nextjs.org/docs/advanced-features/custom-app#caveats * [3]: https://github.com/vercel/next.js/discussions/10949#discussioncomment-1203 * [4]: https://reactjs.org/docs/context.html * [5]: https://reactjs.org/docs/hooks-reference.html#usecontext */ const [wrapperProps, nextImageProps] = filterProps< WrapperProps, FilteredNextImageProps >(otherProps, [...layout.propNames, "className"]); return ( <ImageWrapper className="image-wrapper" maxWidth={dimensions.width} {...wrapperProps} > <NextImage {...({ ...dimensions, layout: "intrinsic", className: clsx( rounded && "rounded", roundedCircle && "rounded-circle", thumbnail && "img-thumbnail", border && "border" ), ...nextImageProps, } as NextImageProps)} /> </ImageWrapper> ); } const ImageWrapper = styled.div` display: inline-block; ${layout} `;
tywmick/tymick.me
components/SocialLinks.tsx
import React from "react"; import SocialLink from "./SocialLink"; import { faCodepen, faDev, faDiscord, faFacebook, faFreeCodeCamp, faGithub, faGitlab, faInstagram, faKaggle, faLinkedin, faMastodon, faMediumM, faNpm, faPaypal, faSpotify, faStackExchange, faTwitter, faWikipediaW, faYoutube, } from "@fortawesome/free-brands-svg-icons"; export default function SocialLinks() { return ( <div id="social-links" className="d-flex justify-content-center flex-wrap"> <SocialLink brand="GitHub" icon={faGithub} href="https://github.com/TyMick" /> <SocialLink brand="Twitter" icon={faTwitter} href="https://twitter.com/tywmick" /> <SocialLink brand="Mastodon" icon={faMastodon} href="https://mastodon.online/@tywmick" /> <SocialLink brand="Facebook" icon={faFacebook} href="https://www.facebook.com/tywmick" /> <SocialLink brand="LinkedIn" icon={faLinkedin} href="https://www.linkedin.com/in/tymick" /> <SocialLink brand="Kaggle" icon={faKaggle} href="https://www.kaggle.com/tywmick" /> <SocialLink brand="npm" icon={faNpm} href="https://www.npmjs.com/~tywmick" /> <SocialLink brand="freeCodeCamp" icon={faFreeCodeCamp} href="https://www.freecodecamp.org/tymick" /> <SocialLink brand="CodePen" icon={faCodepen} href="https://codepen.io/TyMick" /> <SocialLink brand="GitLab" icon={faGitlab} href="https://gitlab.com/TyMick" /> <SocialLink brand="Instagram" icon={faInstagram} href="https://instagram.com/tywmick" /> <SocialLink brand="Discord" icon={faDiscord} username="Ty Mick#4573" /> <SocialLink brand="Spotify" icon={faSpotify} href="https://open.spotify.com/user/tywmick" /> <SocialLink brand="Medium" icon={faMediumM} href="https://medium.com/@TyMick" /> <SocialLink brand="DEV" icon={faDev} href="https://dev.to/tymick" /> <SocialLink brand="Stack Exchange" icon={faStackExchange} href="https://stackexchange.com/users/3957560/ty-mick?tab=accounts" /> <SocialLink brand="Wikipedia" icon={faWikipediaW} href="https://en.wikipedia.org/wiki/User:TyWMick" /> <SocialLink brand="YouTube" icon={faYoutube} href="https://www.youtube.com/TylerWestinMick" /> <SocialLink brand="PayPal" icon={faPaypal} href="https://www.paypal.me/tymick" /> </div> ); }
tywmick/tymick.me
pages/projects.tsx
import React from "react"; import styled from "@emotion/styled"; import Head from "next/head"; import { Container } from "react-bootstrap"; import TeX from "@matejmazur/react-katex"; import Greeting from "../components/Greeting"; export default function Projects() { return ( <> <Head> <title>Projects – <NAME></title> </Head> <Container className="cap-lg-49"> <Greeting /> <h1 className="h2">A few things I&rsquo;ve made:</h1> <SpacedList> <li> <a href="https://rtsimulator.com"> <TeX as="var">R_t</TeX> Simulator </a>{" "} – An interactive data simulation that demonstrates why it&rsquo;s so important to keep COVID-19&rsquo;s reproduction number below 1. </li> <li> React hooks <SpacedList> <li> <a href="https://www.npmjs.com/package/use-window-width-breakpoints"> useWindowWidthBreakpoints </a> </li> <li> <a href="https://www.npmjs.com/package/use-window-orientation"> useWindowOrientation </a> </li> </SpacedList> </li> </SpacedList> </Container> </> ); } const SpacedList = styled.ul` margin-bottom: ${({ theme }) => theme.space[-1]}; ul { margin-top: ${({ theme }) => theme.space[1]}; } li { margin-bottom: ${({ theme }) => theme.space[1]}; } `;
tywmick/tymick.me
components/InlineFootnote.tsx
<filename>components/InlineFootnote.tsx import { useState } from "react"; import { OverlayTrigger, Tooltip } from "react-bootstrap"; import { nanoid } from "nanoid"; import { parseInlineMarkdown } from "../lib/text-processing"; import { css, useTheme } from "@emotion/react"; type InlineFootnoteProps = { note: string; noteId?: string; children: React.ReactNode; }; /** * @todo Consider using getClientRects() to better position notes on multi-line * spans. * {@link https://developer.mozilla.org/en-US/docs/Web/API/Element/getClientRects} * {@link https://popper.js.org/docs/v2/modifiers/offset} * {@link https://react-bootstrap.netlify.com/components/overlays/#overlay-trigger-props} */ export default function InlineFootnote({ note, noteId, children, }: InlineFootnoteProps) { const id: string = noteId ?? `footnote-${nanoid(8)}`; // Overlay logic const [hovered, setHovered] = useState(false); const [focused, setFocused] = useState(false); const theme = useTheme(); return ( <OverlayTrigger placement="top" show={hovered || focused} overlay={ <Tooltip id={id} css={css` a { color: ${theme.colors.light["primary"]}; &:hover, &:focus { color: ${theme.colors.light["primaryHoverFocus"]}; } } `} > {parseInlineMarkdown(note)} </Tooltip> } > <span tabIndex={0} onMouseEnter={() => setHovered(true)} onMouseLeave={() => setHovered(false)} onFocus={() => setFocused(true)} onBlur={() => setFocused(false)} css={{ textDecoration: "underline dotted", textDecorationSkipInk: "none", cursor: "help", }} > {children} </span> </OverlayTrigger> ); }
tywmick/tymick.me
emotion.d.ts
<reponame>tywmick/tymick.me<gh_stars>0 /// <reference types="@emotion/react/types/css-prop" /> import "@emotion/react"; declare module "@emotion/react" { export interface Theme { colors: ColorScale; space: SpaceScale; } export type ColorScale = { [key: string]: string | ColorScale }; export type SpaceScale = { [key: number]: string }; }
tywmick/tymick.me
theme/space.ts
<gh_stars>0 import type { SpaceScale } from "@emotion/react"; const space: SpaceScale = ["0", "0.25rem", "0.5rem", "1rem", "1.5rem", "3rem"]; const numNonNegativeElements = (space as string[]).length; for (let i = 1; i < numNonNegativeElements; i++) { space[`-${i}`] = `-${space[i]}`; } export default space;
tywmick/tymick.me
lib/text-processing.ts
<filename>lib/text-processing.ts import React, { ReactFragment, ReactElement, ReactNode } from "react"; import remark from "remark"; import smartypants from "@silvenon/remark-smartypants"; import gfm from "remark-gfm"; import remarkReact from "remark-react"; import { VFile } from "vfile"; /** Converts a Markdown string into a parsed React fragment. */ export function parseInlineMarkdown(markdown: string): ReactFragment { const react = remark() .use(smartypants) .use(gfm) .use(remarkReact, { remarkReactComponents: { p: React.Fragment }, }) .processSync(markdown) as VFile & { result: ReactElement }; // VFile typing is outdated here return react.result; } /** Parses Markdown in all string elements of a passed `children` object. */ export function parseChildMarkdown(children: ReactNode): ReactNode[] { return React.Children.toArray(children).map((child) => typeof child === "string" && child !== " " ? parseInlineMarkdown(child) : child ); } /** * A higher-order-component that enables markdown parsing in children of the * wrapped component. */ export function withMarkdownParsing(WrappedComponent: React.ElementType<any>) { return ({ children, ...props }: React.ComponentProps<typeof WrappedComponent>) => React.createElement( WrappedComponent, props, ...parseChildMarkdown(children) ); }
yuanliang/Pharos
app/src/pages/PostsPage.tsx
<reponame>yuanliang/Pharos<filename>app/src/pages/PostsPage.tsx import Posts from '../components/Posts/Posts' function PostsPage() { return <Posts /> } export default PostsPage
yuanliang/Pharos
app/src/pages/HomePage.tsx
import Home from '../components/Home/Home' const HomePage = () => <Home /> export default HomePage
yuanliang/Pharos
app/src/components/Layout/NavigationBar.tsx
<reponame>yuanliang/Pharos import { useContext } from 'react' import { Link, useNavigate } from 'react-router-dom' import AuthContext from '../../store/AuthContext' const NavigationBar = () => { const authContext = useContext(AuthContext) const { loggedIn } = authContext const navigate = useNavigate() const logoutHandler = () => { authContext.logout() navigate('/', { replace: true }) } return ( <nav className='navbar navbar-expand-md navbar-dark fixed-top bg-dark'> <button type='button' className='navbar-toggler' data-toggle='collapse' data-target='#navbarCollapse' aria-controls='navbarCollapse' aria-expanded='false' aria-label='Toggle navigation' > <span className='navbar-toggler-icon'> </span> </button> <div className='collapse navbar-collapse justify-content-between' id='navbarCollapse'> <div className='d-flex flex-row'> <ul className='navbar-nav mr-auto'> <li className='nav-item'> <Link className='nav-link' to='/'> PHAROS </Link> </li> {loggedIn && ( <li className='nav-item'> <Link className='nav-link' to='/posts'> My posts </Link> </li> )} </ul> </div> <div className='d-flex flex-row justify-content-end'> <ul className='navbar-nav mr-auto'> {!loggedIn && ( <li className='nav-item'> <Link className='nav-link' to='/auth'> Login </Link> </li> )} {loggedIn && ( <li className='nav-item'> <button type='button' className='btn btn-dark' onClick={logoutHandler}> LOGOUT </button> </li> )} </ul> </div> </div> </nav> ) } export default NavigationBar
yuanliang/Pharos
app/src/components/Layout/Layout.tsx
import NavigationBar from './NavigationBar' import './Layout.css' const Layout = (props: any) => { const { children } = props return ( <> <NavigationBar /> <main> <div className='container'>{children}</div> </main> </> ) } export default Layout
yuanliang/Pharos
app/src/components/Posts/PostsLists.tsx
import Post from './Post' const PostsList = (props: any) => { const { onEditPost, onDeletePost, posts } = props return ( <ul> {posts.forEach((post: any) => ( <Post onEditPost={onEditPost} onDeletePost={onDeletePost} key={post.ID} post={post} /> ))} </ul> ) } export default PostsList
yuanliang/Pharos
app/src/pages/AuthPage.tsx
<reponame>yuanliang/Pharos<filename>app/src/pages/AuthPage.tsx<gh_stars>10-100 import AuthForm from '../components/Auth/AuthForm' const AuthPage = () => <AuthForm /> export default AuthPage
yuanliang/Pharos
app/src/components/Posts/Posts.tsx
import { useContext, useState, useEffect, useCallback } from 'react' import AuthContext from '../../store/AuthContext' import Errors from '../Errors/Errors' import PostForm from './PostForm' import PostsList from './PostsLists' const Posts = () => { const authContext = useContext(AuthContext) const [posts, setPosts] = useState<any>([]) // ToDo: post Type define const [errors, setErrors] = useState({}) const fetchPostsHandler = useCallback(async () => { setErrors({}) try { const response = await fetch('/api/posts', { headers: { Authorization: `Bearer ${authContext.token}` } }) const data = await response.json() if (!response.ok) { const errorText = 'Fetching posts failed.' if (!Object.prototype.hasOwnProperty.call(data, 'error')) { throw new Error(errorText) } if (typeof data.error === 'string') { setErrors({ unknown: data.error }) } else { setErrors(data.error) } } else { setPosts(data.data) } } catch (error: any) { setErrors({ error: error.message }) } }, [authContext.token]) useEffect(() => { fetchPostsHandler() }, [fetchPostsHandler]) const addPostHandler = (postData: any) => { setPosts((prevState: any) => [...prevState, postData]) } const deletePostHandler = (postID: any) => { // ToDo: post Type define setPosts((prevState: any) => prevState.filter((post: any) => post.ID !== postID)) } const editPostHandler = () => { fetchPostsHandler() } const postsContent = posts.length === 0 ? ( <p>No posts yet</p> ) : ( <PostsList posts={posts} onEditPost={editPostHandler} onDeletePost={deletePostHandler} /> ) const errorContent = Object.keys(errors).length === 0 ? null : Errors(errors) return ( <section> <h1 className='pb-4'>My posts</h1> <PostForm onAddPost={addPostHandler} /> {errorContent} {postsContent} </section> ) } export default Posts
yuanliang/Pharos
app/src/store/AuthContext.tsx
import { useState, createContext } from 'react'; const AuthContext = createContext({ token: null, loggedIn: false, // eslint-disable-next-line no-unused-vars login: (token: string) => {}, logout: () => {} }) export const AuthContextProvider = (props: any) => { const tokenKey = 'pharosToken' const { children } = props const [token, setToken] = useState(localStorage.getItem(tokenKey)) const loggedIn = Boolean(token) const loginHandler = (newToken: string) => { setToken(newToken) localStorage.setItem(tokenKey, newToken) } const logoutHandler = () => { setToken(null) localStorage.removeItem(tokenKey) } // const contextValue = { // token, // loggedIn, // login: loginHandler, // logout: logoutHandler // } return ( <AuthContext.Provider value={{ token: token === null ? token : null, loggedIn, login: loginHandler, logout: logoutHandler }} > {children} </AuthContext.Provider> ) } export default AuthContext
yuanliang/Pharos
app/src/components/Posts/Post.tsx
<filename>app/src/components/Posts/Post.tsx import { useState, useContext } from 'react' import AuthContext from '../../store/AuthContext' import Errors from '../Errors/Errors' import PostForm from './PostForm' const Post = (props: any) => { const [editing, setEditing] = useState(false) const [errors, setErrors] = useState({}) const authContext = useContext(AuthContext) const switchModeHandler = () => { setEditing((prevState) => !prevState) setErrors({}) } const { post, post: { Title, Content, ID }, onDeletePost, onEditPost } = props async function deleteHandler() { try { const response = await fetch(`api/posts/${ID}`, { method: 'DELETE', headers: { Authorization: `Bearer ${authContext.token}` } }) const data = await response.json() if (!response.ok) { const errorText = 'Failed to add new post.' if (!Object.prototype.hasOwnProperty.call(data, 'error')) { throw new Error(errorText) } if (typeof data.error === 'string') { setErrors({ unknown: data.error }) } else { setErrors(data.error) } } else { onDeletePost(ID) } } catch (error: any) { setErrors({ error: error.message }) } } const editPostHandler = () => { setEditing(false) onEditPost() } const cardTitle = editing ? 'Edit post' : Title const cardBody = editing ? <PostForm post={post} onEditPost={editPostHandler} editing /> : Content const switchModeButtonText = editing ? 'Cancel' : 'Edit' const cardButtons = editing ? ( <div className='container'> <button type='button' className='btn btn-link' onClick={switchModeHandler}> {switchModeButtonText} </button> <button type='button' className='btn btn-danger float-right mx-3' onClick={deleteHandler}> Delete </button> </div> ) : ( <div className='container'> <button type='button' className='btn btn-link' onClick={switchModeHandler}> {switchModeButtonText} </button> <button type='button' className='btn btn-danger float-right mx-3' onClick={deleteHandler}> Delete </button> </div> ) const errorContent = Object.keys(errors).length === 0 ? null : Errors(errors) return ( <div className='card mb-5 pb-2'> <div className='card-header'>{cardTitle}</div> <div className='card-body'>{cardBody}</div> {cardButtons} {errorContent} </div> ) } export default Post
yuanliang/Pharos
app/src/components/Posts/Post copy.tsx
import { useState, useContext } from 'react' import AuthContext from '../../store/AuthContext' import Errors from '../Errors/Errors' const Post = (props: any) => { const [errors, setErrors] = useState({}) const authContext = useContext(AuthContext) async function deleteHandler() { try { const response = await fetch(`api/posts/${props.ID}`, { method: 'DELETE', headers: { Authorization: `Bearer ${authContext.token}` } }) const data = await response.json() if (!response.ok) { const errorText = 'Failed to add new post.' if (!Object.prototype.hasOwnProperty.call(data, 'error')) { throw new Error(errorText) } if (typeof data.error === 'string') { setErrors({ unknown: data.error }) } else { setErrors(data.error) } } else { props.onDeletePost(props.ID) } } catch (error: any) { setErrors({ error: error.message }) } } const errorContent = Object.keys(errors).length === 0 ? null : Errors(errors) const { Title, Content } = props return ( <div className='card mb-5 pb-2'> <div className='card-header'>{Title}</div> <div className='card-body'>{Content}</div> <div className='container'> <button type='button' className='btn btn-danger float-right mx-3' onClick={deleteHandler}> Delete </button> </div> {errorContent} </div> ) } export default Post