text
stringlengths
2.5k
6.39M
kind
stringclasses
3 values
import { render, screen } from '@testing-library/react' import userEvent from '@testing-library/user-event' import format from 'date-fns/format' import startOfDay from 'date-fns/startOfDay' import subYears from 'date-fns/subYears' import { createMemoryHistory } from 'history' import React from 'react' import { Router } from 'react-router-dom' import GeneralInformation from '../../patients/GeneralInformation' import Patient from '../../shared/model/Patient' Date.now = jest.fn().mockReturnValue(new Date().valueOf()) // most fields use TextInputWithLabelFormGroup, an uncontrolled <input /> => tests are faster without onChange function setup(patientArg: Patient, isEditable = true, error?: Record<string, unknown>) { return render( <Router history={createMemoryHistory()}> <GeneralInformation patient={patientArg} isEditable={isEditable} error={error} /> </Router>, ) } // however, TextFieldWithLabelFormGroup is controlled and needs explicit onChange function setupControlled(patientArg: Patient, isEditable = true, error?: Record<string, unknown>) { const TestComponent = () => { const [patient, setPatient] = React.useState(patientArg) return ( <GeneralInformation patient={patient} isEditable={isEditable} error={error} onChange={setPatient as (p: Partial<Patient>) => void} /> ) } render( <Router history={createMemoryHistory()}> <TestComponent /> </Router>, ) } const patient = { id: '1234321', prefix: 'MockPrefix', givenName: 'givenName', familyName: 'familyName', suffix: 'MockSuffix', sex: 'male', type: 'charity', bloodType: 'A-', dateOfBirth: startOfDay(subYears(new Date(), 30)).toISOString(), isApproximateDateOfBirth: false, occupation: 'MockOccupationValue', preferredLanguage: 'MockPreferredLanguage', phoneNumbers: [ { value: '123456789', type: undefined, id: '123' }, { value: '789012999', type: undefined, id: '456' }, ], emails: [ { value: 'abc@email.com', type: undefined, id: '789' }, { value: 'xyz@email.com', type: undefined, id: '987' }, ], addresses: [ { value: 'address A', type: undefined, id: '654' }, { value: 'address B', type: undefined, id: '321' }, ], code: 'P00001', } as Patient it('should display errors', () => { const error = { message: 'red alert Error Message', givenName: 'given name Error Message', dateOfBirth: 'date of birth Error Message', phoneNumbers: ['phone number Error Message'], emails: ['email Error Message'], } setup( { phoneNumbers: [{ value: 'not a phone number', id: '123' }], emails: [{ value: 'not an email', id: '456' }], } as Patient, true, error, ) expect(screen.getByRole(/alert/i)).toHaveTextContent(error.message) expect(screen.getByLabelText(/patient\.givenName/i)).toHaveClass('is-invalid') expect(screen.getByText(/given name Error Message/i)).toHaveClass('invalid-feedback') expect(screen.getByText(/date of birth Error Message/i)).toHaveClass('text-danger') expect(screen.getByText(/phone number Error Message/i)).toHaveClass('invalid-feedback') expect(screen.getByText(/email Error Message/i)).toHaveClass('invalid-feedback') expect(screen.getByDisplayValue(/not an email/i)).toHaveClass('is-invalid') expect(screen.getByDisplayValue(/not a phone number/i)).toHaveClass('is-invalid') }) describe('General Information, readonly', () => { function typeReadonlyAssertion(inputElement: HTMLElement, mockValue: any) { expect(inputElement).toHaveDisplayValue(mockValue) userEvent.type(inputElement, 'wontexist') expect(inputElement).toHaveDisplayValue(mockValue) expect(inputElement).not.toHaveDisplayValue('wontexist') } it('should render the prefix', () => { setup(patient, false) typeReadonlyAssertion(screen.getByRole('textbox', { name: /patient\.prefix/i }), patient.prefix) }) it('should render the given name', () => { setup(patient, false) typeReadonlyAssertion(screen.getByLabelText(/patient\.givenName/i), patient.givenName) }) it('should render the family name', () => { setup(patient, false) typeReadonlyAssertion(screen.getByLabelText(/patient\.familyName/i), patient.familyName) }) it('should render the suffix', () => { setup(patient, false) typeReadonlyAssertion(screen.getByLabelText(/patient\.suffix/i), patient.suffix) }) it('should render the date of the birth of the patient', () => { setup(patient, false) const expectedDate = format(new Date(patient.dateOfBirth), 'MM/dd/yyyy') typeReadonlyAssertion(screen.getByDisplayValue(expectedDate), [expectedDate]) }) it('should render the approximate age if patient.isApproximateDateOfBirth is true', () => { const newPatient = { ...patient, isApproximateDateOfBirth: true } setup(newPatient, false) typeReadonlyAssertion(screen.getByLabelText(/patient.approximateAge/i), '30') }) it('should render the occupation of the patient', () => { setup(patient, false) typeReadonlyAssertion(screen.getByLabelText(/patient.occupation/i), patient.occupation) }) it('should render the preferred language of the patient', () => { setup(patient, false) typeReadonlyAssertion( screen.getByLabelText(/patient.preferredLanguage/i), patient.preferredLanguage, ) }) it('should render the phone numbers of the patient', () => { setup(patient, false) const phoneNumberField = screen.getByDisplayValue(/123456789/i) expect(phoneNumberField).toHaveProperty('id', 'phoneNumber0TextInput') typeReadonlyAssertion(phoneNumberField, patient.phoneNumbers[0].value) }) it('should render the emails of the patient', () => { setup(patient, false) const emailsField = screen.getByDisplayValue(/abc@email.com/i) expect(emailsField).toHaveProperty('id', 'email0TextInput') typeReadonlyAssertion(emailsField, patient.emails[0].value) }) it('should render the addresses of the patient', () => { setup(patient, false) const phoneNumberField = screen.getByDisplayValue(/address A/i) expect(phoneNumberField).toHaveProperty('id', 'address0TextField') typeReadonlyAssertion(phoneNumberField, patient.addresses[0].value) }) it('should render the sex select options', () => { setup(patient, false) const patientSex = screen.getByDisplayValue(/sex/) expect(patientSex).toBeDisabled() expect(patientSex).toHaveDisplayValue([/sex.male/i]) }) it('should render the blood type select options', () => { setup(patient, false) const bloodType = screen.getByDisplayValue(/bloodType/) expect(bloodType).toBeDisabled() expect(bloodType).toHaveDisplayValue(['bloodType.anegative']) }) it('should render the patient type select options', () => { setup(patient, false) const patientType = screen.getByDisplayValue(/patient.type/) expect(patientType).toBeDisabled() expect(patientType).toHaveDisplayValue([/patient.types.charity/i]) }) }) describe('General Information, isEditable', () => { function typeWritableAssertion(inputElement: HTMLElement, mockValue: any) { expect(inputElement).toHaveDisplayValue(mockValue) userEvent.type(inputElement, '{selectall}willexist') expect(inputElement).toHaveDisplayValue('willexist') expect(inputElement).not.toHaveDisplayValue(mockValue) } it('should render the prefix', () => { setup(patient) typeWritableAssertion(screen.getByRole('textbox', { name: /patient\.prefix/i }), patient.prefix) }) it('should render the given name', () => { setup(patient) typeWritableAssertion(screen.getByPlaceholderText(/patient\.givenName/i), patient.givenName) }) it('should render the family name', () => { setup(patient) typeWritableAssertion(screen.getByPlaceholderText(/patient\.familyName/i), patient.familyName) }) it('should render the suffix', () => { setup(patient) typeWritableAssertion(screen.getByPlaceholderText(/patient\.suffix/i), patient.suffix) }) it('should render the date of the birth of the patient', () => { setup(patient) const expectedDate = format(new Date(patient.dateOfBirth), 'MM/dd/yyyy') const field = screen.getByDisplayValue(expectedDate) typeWritableAssertion(field, [expectedDate]) // workaround for Warning: `NaN` is an invalid value for the `left` css style property. userEvent.type(field, '{enter}') }) it('should render the occupation of the patient', () => { setup(patient) typeWritableAssertion(screen.getByLabelText(/patient.occupation/i), [patient.occupation]) }) it('should render the preferred language of the patient', () => { setup(patient) typeWritableAssertion( screen.getByLabelText(/patient.preferredLanguage/i), patient.preferredLanguage, ) }) it('should render the phone numbers of the patient', () => { setup(patient) const phoneNumberField = screen.getByDisplayValue(/123456789/i) expect(phoneNumberField).toHaveProperty('id', 'phoneNumber0TextInput') typeWritableAssertion(phoneNumberField, patient.phoneNumbers[0].value) }) it('should render the emails of the patient', () => { setup(patient) const emailsField = screen.getByDisplayValue(/abc@email.com/i) expect(emailsField).toHaveProperty('id', 'email0TextInput') typeWritableAssertion(emailsField, patient.emails[0].value) }) it('should render the addresses of the patient', () => { setupControlled(patient) const addressField = screen.getByDisplayValue(/address A/i) expect(addressField).toHaveProperty('id', 'address0TextField') typeWritableAssertion(addressField, patient.addresses[0].value) }) it('should render the sex select', () => { setup(patient) const patientSex = screen.getByDisplayValue(/sex/) expect(patientSex).not.toBeDisabled() userEvent.click(patientSex) const bloodArr = [/sex.male/i, /sex.female/i, /sex.female/i, /sex.unknown/i] bloodArr.forEach((reg) => { const sexOption = screen.getByRole('option', { name: reg }) userEvent.click(sexOption) expect(sexOption).toBeInTheDocument() }) }) it('should render the blood type select', () => { setup(patient) const bloodType = screen.getByDisplayValue(/bloodType/) expect(bloodType).not.toBeDisabled() userEvent.click(bloodType) const bloodArr = [ /bloodType.apositive/i, /bloodType.anegative/i, /bloodType.abpositive/i, /bloodType.abnegative/i, /bloodType.bpositive/i, /bloodType.bnegative/i, /bloodType.opositive/i, /bloodType.onegative/i, /bloodType.unknown/i, ] bloodArr.forEach((reg) => { const bloodOption = screen.getByRole('option', { name: reg }) userEvent.click(bloodOption) expect(bloodOption).toBeInTheDocument() }) }) it('should render the patient type select', () => { setup(patient) const patientType = screen.getByDisplayValue(/patient.type/) expect(patientType).not.toBeDisabled() userEvent.click(patientType) const bloodArr = [/patient.types.charity/i, /patient.types.private/i] bloodArr.forEach((reg) => { const typeOption = screen.getByRole('option', { name: reg }) userEvent.click(typeOption) expect(typeOption).toBeInTheDocument() }) }) })
the_stack
export class HttpHeaders { /** * The HTTP {@code Accept} header field name. * @see <a href="https://tools.ietf.org/html/rfc7231#section-5.3.2">Section 5.3.2 of RFC 7231</a> */ public static ACCEPT = 'Accept'; /** * The HTTP {@code Accept-Charset} header field name. * @see <a href="https://tools.ietf.org/html/rfc7231#section-5.3.3">Section 5.3.3 of RFC 7231</a> */ public static ACCEPT_CHARSET = 'Accept-Charset'; /** * The HTTP {@code Accept-Encoding} header field name. * @see <a href="https://tools.ietf.org/html/rfc7231#section-5.3.4">Section 5.3.4 of RFC 7231</a> */ public static ACCEPT_ENCODING = 'Accept-Encoding'; /** * The HTTP {@code Accept-Language} header field name. * @see <a href="https://tools.ietf.org/html/rfc7231#section-5.3.5">Section 5.3.5 of RFC 7231</a> */ public static ACCEPT_LANGUAGE = 'Accept-Language'; /** * The HTTP {@code Accept-Ranges} header field name. * @see <a href="https://tools.ietf.org/html/rfc7233#section-2.3">Section 5.3.5 of RFC 7233</a> */ public static ACCEPT_RANGES = 'Accept-Ranges'; /** * The CORS {@code Access-Control-Allow-Credentials} response header field name. * @see <a href="http://www.w3.org/TR/cors/">CORS W3C recommendation</a> */ public static ACCESS_CONTROL_ALLOW_CREDENTIALS = 'Access-Control-Allow-Credentials'; /** * The CORS {@code Access-Control-Allow-Headers} response header field name. * @see <a href="http://www.w3.org/TR/cors/">CORS W3C recommendation</a> */ public static ACCESS_CONTROL_ALLOW_HEADERS = 'Access-Control-Allow-Headers'; /** * The CORS {@code Access-Control-Allow-Methods} response header field name. * @see <a href="http://www.w3.org/TR/cors/">CORS W3C recommendation</a> */ public static ACCESS_CONTROL_ALLOW_METHODS = 'Access-Control-Allow-Methods'; /** * The CORS {@code Access-Control-Allow-Origin} response header field name. * @see <a href="http://www.w3.org/TR/cors/">CORS W3C recommendation</a> */ public static ACCESS_CONTROL_ALLOW_ORIGIN = 'Access-Control-Allow-Origin'; /** * The CORS {@code Access-Control-Expose-Headers} response header field name. * @see <a href="http://www.w3.org/TR/cors/">CORS W3C recommendation</a> */ public static ACCESS_CONTROL_EXPOSE_HEADERS = 'Access-Control-Expose-Headers'; /** * The CORS {@code Access-Control-Max-Age} response header field name. * @see <a href="http://www.w3.org/TR/cors/">CORS W3C recommendation</a> */ public static ACCESS_CONTROL_MAX_AGE = 'Access-Control-Max-Age'; /** * The CORS {@code Access-Control-Request-Headers} request header field name. * @see <a href="http://www.w3.org/TR/cors/">CORS W3C recommendation</a> */ public static ACCESS_CONTROL_REQUEST_HEADERS = 'Access-Control-Request-Headers'; /** * The CORS {@code Access-Control-Request-Method} request header field name. * @see <a href="http://www.w3.org/TR/cors/">CORS W3C recommendation</a> */ public static ACCESS_CONTROL_REQUEST_METHOD = 'Access-Control-Request-Method'; /** * The HTTP {@code Age} header field name. * @see <a href="https://tools.ietf.org/html/rfc7234#section-5.1">Section 5.1 of RFC 7234</a> */ public static AGE = 'Age'; /** * The HTTP {@code Allow} header field name. * @see <a href="https://tools.ietf.org/html/rfc7231#section-7.4.1">Section 7.4.1 of RFC 7231</a> */ public static ALLOW = 'Allow'; /** * The HTTP {@code Authorization} header field name. * @see <a href="https://tools.ietf.org/html/rfc7235#section-4.2">Section 4.2 of RFC 7235</a> */ public static AUTHORIZATION = 'Authorization'; /** * The HTTP {@code Cache-Control} header field name. * @see <a href="https://tools.ietf.org/html/rfc7234#section-5.2">Section 5.2 of RFC 7234</a> */ public static CACHE_CONTROL = 'Cache-Control'; /** * The HTTP {@code Connection} header field name. * @see <a href="https://tools.ietf.org/html/rfc7230#section-6.1">Section 6.1 of RFC 7230</a> */ public static CONNECTION = 'Connection'; /** * The HTTP {@code Content-Encoding} header field name. * @see <a href="https://tools.ietf.org/html/rfc7231#section-3.1.2.2">Section 3.1.2.2 of RFC 7231</a> */ public static CONTENT_ENCODING = 'Content-Encoding'; /** * The HTTP {@code Content-Disposition} header field name. * @see <a href="https://tools.ietf.org/html/rfc6266">RFC 6266</a> */ public static CONTENT_DISPOSITION = 'Content-Disposition'; /** * The HTTP {@code Content-Language} header field name. * @see <a href="https://tools.ietf.org/html/rfc7231#section-3.1.3.2">Section 3.1.3.2 of RFC 7231</a> */ public static CONTENT_LANGUAGE = 'Content-Language'; /** * The HTTP {@code Content-Length} header field name. * @see <a href="https://tools.ietf.org/html/rfc7230#section-3.3.2">Section 3.3.2 of RFC 7230</a> */ public static CONTENT_LENGTH = 'Content-Length'; /** * The HTTP {@code Content-Location} header field name. * @see <a href="https://tools.ietf.org/html/rfc7231#section-3.1.4.2">Section 3.1.4.2 of RFC 7231</a> */ public static CONTENT_LOCATION = 'Content-Location'; /** * The HTTP {@code Content-Range} header field name. * @see <a href="https://tools.ietf.org/html/rfc7233#section-4.2">Section 4.2 of RFC 7233</a> */ public static CONTENT_RANGE = 'Content-Range'; /** * The HTTP {@code Content-Type} header field name. * @see <a href="https://tools.ietf.org/html/rfc7231#section-3.1.1.5">Section 3.1.1.5 of RFC 7231</a> */ public static CONTENT_TYPE = 'Content-Type'; /** * The HTTP {@code Cookie} header field name. * @see <a href="https://tools.ietf.org/html/rfc2109#section-4.3.4">Section 4.3.4 of RFC 2109</a> */ public static COOKIE = 'Cookie'; /** * The HTTP {@code Date} header field name. * @see <a href="https://tools.ietf.org/html/rfc7231#section-7.1.1.2">Section 7.1.1.2 of RFC 7231</a> */ public static DATE = 'Date'; /** * The HTTP {@code ETag} header field name. * @see <a href="https://tools.ietf.org/html/rfc7232#section-2.3">Section 2.3 of RFC 7232</a> */ public static ETAG = 'ETag'; /** * The HTTP {@code Expect} header field name. * @see <a href="https://tools.ietf.org/html/rfc7231#section-5.1.1">Section 5.1.1 of RFC 7231</a> */ public static EXPECT = 'Expect'; /** * The HTTP {@code Expires} header field name. * @see <a href="https://tools.ietf.org/html/rfc7234#section-5.3">Section 5.3 of RFC 7234</a> */ public static EXPIRES = 'Expires'; /** * The HTTP {@code From} header field name. * @see <a href="https://tools.ietf.org/html/rfc7231#section-5.5.1">Section 5.5.1 of RFC 7231</a> */ public static FROM = 'From'; /** * The HTTP {@code Host} header field name. * @see <a href="https://tools.ietf.org/html/rfc7230#section-5.4">Section 5.4 of RFC 7230</a> */ public static HOST = 'Host'; /** * The HTTP {@code If-Match} header field name. * @see <a href="https://tools.ietf.org/html/rfc7232#section-3.1">Section 3.1 of RFC 7232</a> */ public static IF_MATCH = 'If-Match'; /** * The HTTP {@code If-Modified-Since} header field name. * @see <a href="https://tools.ietf.org/html/rfc7232#section-3.3">Section 3.3 of RFC 7232</a> */ public static IF_MODIFIED_SINCE = 'If-Modified-Since'; /** * The HTTP {@code If-None-Match} header field name. * @see <a href="https://tools.ietf.org/html/rfc7232#section-3.2">Section 3.2 of RFC 7232</a> */ public static IF_NONE_MATCH = 'If-None-Match'; /** * The HTTP {@code If-Range} header field name. * @see <a href="https://tools.ietf.org/html/rfc7233#section-3.2">Section 3.2 of RFC 7233</a> */ public static IF_RANGE = 'If-Range'; /** * The HTTP {@code If-Unmodified-Since} header field name. * @see <a href="https://tools.ietf.org/html/rfc7232#section-3.4">Section 3.4 of RFC 7232</a> */ public static IF_UNMODIFIED_SINCE = 'If-Unmodified-Since'; /** * The HTTP {@code Last-Modified} header field name. * @see <a href="https://tools.ietf.org/html/rfc7232#section-2.2">Section 2.2 of RFC 7232</a> */ public static LAST_MODIFIED = 'Last-Modified'; /** * The HTTP {@code Link} header field name. * @see <a href="https://tools.ietf.org/html/rfc5988">RFC 5988</a> */ public static LINK = 'Link'; /** * The HTTP {@code Location} header field name. * @see <a href="https://tools.ietf.org/html/rfc7231#section-7.1.2">Section 7.1.2 of RFC 7231</a> */ public static LOCATION = 'Location'; /** * The HTTP {@code Max-Forwards} header field name. * @see <a href="https://tools.ietf.org/html/rfc7231#section-5.1.2">Section 5.1.2 of RFC 7231</a> */ public static MAX_FORWARDS = 'Max-Forwards'; /** * The HTTP {@code Origin} header field name. * @see <a href="https://tools.ietf.org/html/rfc6454">RFC 6454</a> */ public static ORIGIN = 'Origin'; /** * The HTTP {@code Pragma} header field name. * @see <a href="https://tools.ietf.org/html/rfc7234#section-5.4">Section 5.4 of RFC 7234</a> */ public static PRAGMA = 'Pragma'; /** * The HTTP {@code Proxy-Authenticate} header field name. * @see <a href="https://tools.ietf.org/html/rfc7235#section-4.3">Section 4.3 of RFC 7235</a> */ public static PROXY_AUTHENTICATE = 'Proxy-Authenticate'; /** * The HTTP {@code Proxy-Authorization} header field name. * @see <a href="https://tools.ietf.org/html/rfc7235#section-4.4">Section 4.4 of RFC 7235</a> */ public static PROXY_AUTHORIZATION = 'Proxy-Authorization'; /** * The HTTP {@code Range} header field name. * @see <a href="https://tools.ietf.org/html/rfc7233#section-3.1">Section 3.1 of RFC 7233</a> */ public static RANGE = 'Range'; /** * The HTTP {@code Referer} header field name. * @see <a href="https://tools.ietf.org/html/rfc7231#section-5.5.2">Section 5.5.2 of RFC 7231</a> */ public static REFERER = 'Referer'; /** * The HTTP {@code Retry-After} header field name. * @see <a href="https://tools.ietf.org/html/rfc7231#section-7.1.3">Section 7.1.3 of RFC 7231</a> */ public static RETRY_AFTER = 'Retry-After'; /** * The HTTP {@code Server} header field name. * @see <a href="https://tools.ietf.org/html/rfc7231#section-7.4.2">Section 7.4.2 of RFC 7231</a> */ public static SERVER = 'Server'; /** * The HTTP {@code Set-Cookie} header field name. * @see <a href="https://tools.ietf.org/html/rfc2109#section-4.2.2">Section 4.2.2 of RFC 2109</a> */ public static SET_COOKIE = 'Set-Cookie'; /** * The HTTP {@code Set-Cookie2} header field name. * @see <a href="https://tools.ietf.org/html/rfc2965">RFC 2965</a> */ public static SET_COOKIE2 = 'Set-Cookie2'; /** * The HTTP {@code TE} header field name. * @see <a href="https://tools.ietf.org/html/rfc7230#section-4.3">Section 4.3 of RFC 7230</a> */ public static TE = 'TE'; /** * The HTTP {@code Trailer} header field name. * @see <a href="https://tools.ietf.org/html/rfc7230#section-4.4">Section 4.4 of RFC 7230</a> */ public static TRAILER = 'Trailer'; /** * The HTTP {@code Transfer-Encoding} header field name. * @see <a href="https://tools.ietf.org/html/rfc7230#section-3.3.1">Section 3.3.1 of RFC 7230</a> */ public static TRANSFER_ENCODING = 'Transfer-Encoding'; /** * The HTTP {@code Upgrade} header field name. * @see <a href="https://tools.ietf.org/html/rfc7230#section-6.7">Section 6.7 of RFC 7230</a> */ public static UPGRADE = 'Upgrade'; /** * The HTTP {@code User-Agent} header field name. * @see <a href="https://tools.ietf.org/html/rfc7231#section-5.5.3">Section 5.5.3 of RFC 7231</a> */ public static USER_AGENT = 'User-Agent'; /** * The HTTP {@code Vary} header field name. * @see <a href="https://tools.ietf.org/html/rfc7231#section-7.1.4">Section 7.1.4 of RFC 7231</a> */ public static VARY = 'Vary'; /** * The HTTP {@code Via} header field name. * @see <a href="https://tools.ietf.org/html/rfc7230#section-5.7.1">Section 5.7.1 of RFC 7230</a> */ public static VIA = 'Via'; /** * The HTTP {@code Warning} header field name. * @see <a href="https://tools.ietf.org/html/rfc7234#section-5.5">Section 5.5 of RFC 7234</a> */ public static WARNING = 'Warning'; /** * The HTTP {@code WWW-Authenticate} header field name. * @see <a href="https://tools.ietf.org/html/rfc7235#section-4.1">Section 4.1 of RFC 7235</a> */ public static WWW_AUTHENTICATE = 'WWW-Authenticate'; public static X_REQUESTED_WITH = 'X-Requested-With'; }
the_stack
import { ButtonClassKey, ButtonGroup, ButtonProps, FormControlLabel, Icon, InputLabel, SvgIcon, } from "@material-ui/core" import ArrowDropDownIcon from "@material-ui/icons/ArrowDropDown" import { ClassNameMap } from "@material-ui/styles" import moment from "moment" import { useSnackbar } from "notistack" import React, { PropsWithChildren, useLayoutEffect, useMemo, useRef, useState, } from "react" import { convertFromNode, convertFromString } from "react-from-dom" import { Link } from "react-router-dom" import styled from "styled-components" import { Tags } from "./analytics" import { annotations } from "./annotations" import { ReactComponent as CloseSvg } from "./assets/svg/close.svg" import { usePersistentState } from "./BrowserStorage" import FloatDialog from "./FloatDialog" import { useHudErrorContext } from "./HudErrorContext" import { InstrumentedButton, InstrumentedCheckbox, InstrumentedTextField, } from "./instrumentedComponents" import { usePathBuilder } from "./PathBuilder" import { AnimDuration, Color, Font, FontSize, SizeUnit, ZIndex, } from "./style-helpers" import { apiTimeFormat, tiltApiPut } from "./tiltApi" import { UIButton, UIInputSpec, UIInputStatus } from "./types" /** * Note on nomenclature: both `ApiButton` and `UIButton` are used to refer to * custom action buttons here. On the Tilt backend, these are generally called * `UIButton`s, but to avoid confusion on the frontend, (where there are many * UI buttons,) they're generally called `ApiButton`s. */ // Types type ApiButtonProps = ButtonProps & { className?: string uiButton: UIButton } type ApiIconProps = { iconName?: string; iconSVG?: string } type ApiButtonInputProps = { spec: UIInputSpec status: UIInputStatus | undefined value: any | undefined setValue: (name: string, value: any) => void analyticsTags: Tags } type ApiButtonElementProps = ButtonProps & { text: string confirming: boolean disabled: boolean iconName?: string iconSVG?: string analyticsTags: Tags analyticsName: string } // UIButtons for a location, sorted into types export type ButtonSet = { default: UIButton[] toggleDisable?: UIButton stopBuild?: UIButton } function newButtonSet(): ButtonSet { return { default: [] } } export enum ApiButtonType { Global = "Global", Resource = "Resource", } export enum ApiButtonToggleState { On = "on", Off = "off", } // Constants export const UIBUTTON_SPEC_HASH = "uibuttonspec-hash" export const UIBUTTON_ANNOTATION_TYPE = "tilt.dev/uibutton-type" export const UIBUTTON_GLOBAL_COMPONENT_ID = "nav" export const UIBUTTON_TOGGLE_DISABLE_TYPE = "DisableToggle" export const UIBUTTON_TOGGLE_INPUT_NAME = "action" export const UIBUTTON_STOP_BUILD_TYPE = "StopBuild" // Styles const ApiButtonFormRoot = styled.div` z-index: ${ZIndex.ApiButton}; ` const ApiButtonFormFooter = styled.div` text-align: right; color: ${Color.gray40}; font-size: ${FontSize.smallester}; ` const ApiIconRoot = styled.span`` export const ApiButtonLabel = styled.span`` // MUI makes it tricky to get cursor: not-allowed on disabled buttons // https://material-ui.com/components/buttons/#cursor-not-allowed export const ApiButtonRoot = styled(ButtonGroup)<{ disabled?: boolean }>` ${(props) => props.disabled && ` cursor: not-allowed; `} ${ApiIconRoot} + ${ApiButtonLabel} { margin-left: ${SizeUnit(0.25)}; } ` export const LogLink = styled(Link)` font-size: ${FontSize.smallest}; padding-left: ${SizeUnit(0.5)}; ` export const confirmingButtonStateMixin = ` &.confirming { background-color: ${Color.red}; border-color: ${Color.gray30}; color: ${Color.black}; &:hover, &:active, &:focus { background-color: ${Color.red}; border-color: ${Color.redLight}; color: ${Color.black}; } .fillStd { fill: ${Color.black} !important; /* TODO (lizz): find this style source! */ } } ` /* Manually manage the border that both left and right * buttons share on the edge between them, so border * color changes work as expected */ export const confirmingButtonGroupBorderMixin = ` &.leftButtonInGroup { border-right: 0; &:active + .rightButtonInGroup, &:focus + .rightButtonInGroup, &:hover + .rightButtonInGroup { border-left-color: ${Color.redLight}; } } ` const ApiButtonElementRoot = styled(InstrumentedButton)` ${confirmingButtonStateMixin} ${confirmingButtonGroupBorderMixin} ` const inputLabelMixin = ` font-family: ${Font.monospace}; font-size: ${FontSize.small}; color: ${Color.gray10}; ` const ApiButtonInputLabel = styled(InputLabel)` ${inputLabelMixin} margin-top: ${SizeUnit(1 / 2)}; margin-bottom: ${SizeUnit(1 / 4)}; ` const ApiButtonInputTextField = styled(InstrumentedTextField)` margin-bottom: ${SizeUnit(1 / 2)}; .MuiOutlinedInput-root { background-color: ${Color.offWhite}; } .MuiOutlinedInput-input { ${inputLabelMixin} border: 1px solid ${Color.gray70}; border-radius: ${SizeUnit(0.125)}; transition: border-color ${AnimDuration.default} ease; padding: ${SizeUnit(0.2)} ${SizeUnit(0.4)}; &:hover { border-color: ${Color.gray40}; } &:focus, &:active { border: 1px solid ${Color.gray20}; } } ` const ApiButtonInputFormControlLabel = styled(FormControlLabel)` ${inputLabelMixin} margin-left: unset; ` const ApiButtonInputCheckbox = styled(InstrumentedCheckbox)` &.MuiCheckbox-root, &.Mui-checked { color: ${Color.gray40}; } ` export const ApiButtonInputsToggleButton = styled(InstrumentedButton)` &&&& { margin-left: unset; /* Override any margins passed down through "className" props */ padding: 0 0; } ` function buttonType(b: UIButton): string { return annotations(b)[UIBUTTON_ANNOTATION_TYPE] } const svgElement = (src: string): React.ReactElement => { const node = convertFromString(src, { selector: "svg", type: "image/svg+xml", nodeOnly: true, }) as SVGSVGElement return convertFromNode(node) as React.ReactElement } function ApiButtonInput(props: ApiButtonInputProps) { if (props.spec.text) { return ( <> <ApiButtonInputLabel htmlFor={props.spec.name}> {props.spec.label ?? props.spec.name} </ApiButtonInputLabel> <ApiButtonInputTextField id={props.spec.name} placeholder={props.spec.text?.placeholder} value={props.value ?? props.spec.text?.defaultValue ?? ""} onChange={(e) => props.setValue(props.spec.name!, e.target.value)} analyticsName="ui.web.uibutton.inputValue" analyticsTags={{ inputType: "text", ...props.analyticsTags }} variant="outlined" fullWidth /> </> ) } else if (props.spec.bool) { const isChecked = props.value ?? props.spec.bool.defaultValue ?? false return ( <ApiButtonInputFormControlLabel control={ <ApiButtonInputCheckbox id={props.spec.name} checked={isChecked} analyticsName="ui.web.uibutton.inputValue" analyticsTags={{ inputType: "bool", ...props.analyticsTags }} /> } label={props.spec.label ?? props.spec.name} onChange={(_, checked) => props.setValue(props.spec.name!, checked)} /> ) } else if (props.spec.hidden) { return null } else { return ( <div>{`Error: button input ${props.spec.name} had unsupported type`}</div> ) } } type ApiButtonFormProps = { uiButton: UIButton analyticsTags: Tags setInputValue: (name: string, value: any) => void getInputValue: (name: string) => any | undefined } export function ApiButtonForm(props: ApiButtonFormProps) { return ( <ApiButtonFormRoot> {props.uiButton.spec?.inputs?.map((spec) => { const name = spec.name! const status = props.uiButton.status?.inputs?.find( (status) => status.name === name ) const value = props.getInputValue(name) return ( <ApiButtonInput key={name} spec={spec} status={status} value={value} setValue={props.setInputValue} analyticsTags={props.analyticsTags} /> ) })} <ApiButtonFormFooter>(Changes automatically applied)</ApiButtonFormFooter> </ApiButtonFormRoot> ) } type ApiButtonWithOptionsProps = { submit: JSX.Element uiButton: UIButton analyticsTags: Tags setInputValue: (name: string, value: any) => void getInputValue: (name: string) => any | undefined className?: string text: string } function ApiButtonWithOptions(props: ApiButtonWithOptionsProps & ButtonProps) { const [open, setOpen] = useState(false) const anchorRef = useRef(null) const { submit, uiButton, setInputValue, getInputValue, text, analyticsTags, ...buttonProps } = props return ( <> <ApiButtonRoot ref={anchorRef} className={props.className} disableRipple={true} disabled={buttonProps.disabled} > {props.submit} <ApiButtonInputsToggleButton {...buttonProps} size="small" onClick={() => { setOpen((prevOpen) => !prevOpen) }} analyticsName="ui.web.uibutton.inputMenu" analyticsTags={analyticsTags} aria-label={`Open ${text} options`} > <ArrowDropDownIcon /> </ApiButtonInputsToggleButton> </ApiButtonRoot> <FloatDialog open={open} onClose={() => { setOpen(false) }} anchorEl={anchorRef.current} title={`Options for ${text}`} > <ApiButtonForm {...props} /> </FloatDialog> </> ) } export const ApiIcon = ({ iconName, iconSVG }: ApiIconProps) => { if (iconSVG) { // the material SvgIcon handles accessibility/sizing/colors well but can't accept a raw SVG string // create a ReactElement by parsing the source and then use that as the component, passing through // the props so that it's correctly styled const svgEl = svgElement(iconSVG) const svg = (props: React.PropsWithChildren<any>) => { // merge the props from material-ui while keeping the children of the actual SVG return React.cloneElement(svgEl, { ...props }, ...svgEl.props.children) } return ( <ApiIconRoot> <SvgIcon component={svg} /> </ApiIconRoot> ) } if (iconName) { return ( <ApiIconRoot> <Icon>{iconName}</Icon> </ApiIconRoot> ) } return null } // returns metadata + button status w/ the specified input buttons function buttonStatusWithInputs( button: UIButton, inputValues: { [name: string]: any } ): UIButton { const result = { metadata: { ...button.metadata }, status: { ...button.status }, } as UIButton result.status!.lastClickedAt = apiTimeFormat(moment.utc()) result.status!.inputs = [] button.spec!.inputs?.forEach((spec) => { const value = inputValues[spec.name!] const defined = value !== undefined let status: UIInputStatus = { name: spec.name } // If the value isn't defined, use the default value // This is unfortunate duplication with the default value checks when initializing the // MUI managed input components. It might bee cleaner to initialize `inputValues` with // the default values. However, that breaks a bunch of stuff with persistence (e.g., // if you modify one value, you get a cookie and then never get to see any default values // that get added/changed) if (spec.text) { status.text = { value: defined ? value : spec.text?.defaultValue } } else if (spec.bool) { status.bool = { value: (defined ? value : spec.bool.defaultValue) === true, } } else if (spec.hidden) { status.hidden = { value: spec.hidden.value } } result.status!.inputs!.push(status) }) return result } export async function updateButtonStatus( button: UIButton, inputValues: { [name: string]: any } ) { const toUpdate = buttonStatusWithInputs(button, inputValues) await tiltApiPut("uibuttons", "status", toUpdate) } function getButtonTags(button: UIButton): Tags { const tags: Tags = {} // The location of the button in the UI const component = button.spec?.location?.componentType as ApiButtonType if (component !== undefined) { tags.component = component } const buttonAnnotations = annotations(button) // A unique hash of the button text to help identify which button was clicked const specHash = buttonAnnotations[UIBUTTON_SPEC_HASH] if (specHash !== undefined) { tags.specHash = specHash } // Tilt-specific button annotation, currently only used to differentiate disable toggles const buttonType = buttonAnnotations[UIBUTTON_ANNOTATION_TYPE] if (buttonType !== undefined) { tags.buttonType = buttonType } // A toggle button will have a hidden input field with the current value of the toggle // e.g., when a disable button is clicked, the hidden input will be "on" because that's // the toggle's value when it's clicked, _not_ the value it's being toggled to. let toggleInput: UIInputSpec | undefined if (button.spec?.inputs) { toggleInput = button.spec.inputs.find( (input) => input.name === UIBUTTON_TOGGLE_INPUT_NAME ) } if (toggleInput !== undefined) { const toggleValue = toggleInput.hidden?.value // Only use values defined in `ApiButtonToggleState`, so no user-specific information is saved. // When toggle buttons are exposed in the button extension, this mini allowlist can be revisited. if ( toggleValue === ApiButtonToggleState.On || toggleValue === ApiButtonToggleState.Off ) { tags.toggleValue = toggleValue } } return tags } export function ApiCancelButton(props: ApiButtonElementProps) { const { confirming, onClick, analyticsTags, text, analyticsName, ...buttonProps } = props // Don't display the cancel confirmation button if the button // group's state isn't confirming if (!confirming) { return null } // To pass classes to a MUI component, it's necessary to use `classes`, instead of `className` const classes: Partial<ClassNameMap<ButtonClassKey>> = { root: "confirming rightButtonInGroup", } return ( <ApiButtonElementRoot analyticsName={analyticsName} aria-label={`Cancel ${text}`} analyticsTags={{ confirm: "false", ...analyticsTags }} classes={classes} onClick={onClick} {...buttonProps} > <CloseSvg role="presentation" /> </ApiButtonElementRoot> ) } // The inner content of an ApiSubmitButton export function ApiSubmitButtonContent( props: PropsWithChildren<{ confirming: boolean displayButtonText: string iconName?: string iconSVG?: string }> ) { if (props.confirming) { return <ApiButtonLabel>{props.displayButtonText}</ApiButtonLabel> } if (props.children && props.children !== true) { return <>{props.children}</> } return ( <> <ApiIcon iconName={props.iconName} iconSVG={props.iconSVG} /> <ApiButtonLabel>{props.displayButtonText}</ApiButtonLabel> </> ) } // For a toggle button that requires confirmation to trigger a UIButton's // action, this component will render both the "submit" and the "confirm submit" // HTML buttons. For keyboard navigation and accessibility, this component // intentionally renders both buttons as the same element with different props. // This makes sure that keyboard focus is moved to (or rather, stays on) // the "confirm submit" button when the "submit" button is clicked. People // using assistive tech like screenreaders will know they need to confirm. // (Screenreaders should announce the "confirm submit" button to users because // the `aria-label` changes when the "submit" button is clicked.) export function ApiSubmitButton( props: PropsWithChildren<ApiButtonElementProps> ) { const { analyticsName, analyticsTags, confirming, disabled, onClick, iconName, iconSVG, text, ...buttonProps } = props // Determine display text and accessible button label based on confirmation state const displayButtonText = confirming ? "Confirm" : text const ariaLabel = confirming ? `Confirm ${text}` : `Trigger ${text}` const tags = { ...analyticsTags } if (confirming) { tags.confirm = "true" } // To pass classes to a MUI component, it's necessary to use `classes`, instead of `className` const isConfirmingClass = confirming ? "confirming leftButtonInGroup" : "" const classes: Partial<ClassNameMap<ButtonClassKey>> = { root: isConfirmingClass, } // Note: button text is not included in analytics name since that can be user data return ( <ApiButtonElementRoot analyticsName={analyticsName} analyticsTags={tags} aria-label={ariaLabel} classes={classes} disabled={disabled} onClick={onClick} {...buttonProps} > <ApiSubmitButtonContent confirming={confirming} displayButtonText={displayButtonText} iconName={iconName} iconSVG={iconSVG} > {props.children} </ApiSubmitButtonContent> </ApiButtonElementRoot> ) } // Renders a UIButton. // NB: The `Button` in `ApiButton` refers to a UIButton, not an html <button>. // This can be confusing because each ApiButton consists of one or two <button>s: // 1. A submit <button>, which fires the button's action. // 2. Optionally, an options <button>, which allows the user to configure the // options used on submit. export function ApiButton(props: PropsWithChildren<ApiButtonProps>) { const { className, uiButton, ...buttonProps } = props const buttonName = uiButton.metadata?.name || "" const [inputValues, setInputValues] = usePersistentState<{ [name: string]: any }>(`apibutton-${buttonName}`, {}) const { enqueueSnackbar } = useSnackbar() const pb = usePathBuilder() const { setError } = useHudErrorContext() const [loading, setLoading] = useState(false) const [confirming, setConfirming] = useState(false) // Reset the confirmation state when the button's name changes useLayoutEffect(() => setConfirming(false), [buttonName]) const tags = useMemo(() => getButtonTags(uiButton), [uiButton]) const componentType = uiButton.spec?.location?.componentType as ApiButtonType const disabled = loading || uiButton.spec?.disabled || false const buttonText = uiButton.spec?.text || "Button" const onClick = async (e: React.MouseEvent<HTMLElement>) => { e.preventDefault() e.stopPropagation() if (uiButton.spec?.requiresConfirmation && !confirming) { setConfirming(true) return } if (confirming) { setConfirming(false) } // TODO(milas): currently the loading state just disables the button for the duration of // the AJAX request to avoid duplicate clicks - there is no progress tracking at the // moment, so there's no fancy spinner animation or propagation of result of action(s) // that occur as a result of click right now setLoading(true) try { await updateButtonStatus(uiButton, inputValues) } catch (err) { setError(`Error submitting button click: ${err}`) return } finally { setLoading(false) } // skip snackbar notifications for special buttons (e.g., disable, stop build) if (!buttonType(uiButton)) { const snackbarLogsLink = componentType === ApiButtonType.Global ? ( <LogLink to="/r/(all)/overview">Global Logs</LogLink> ) : ( <LogLink to={pb.encpath`/r/${ uiButton.spec?.location?.componentID || "(all)" }/overview`} > Resource Logs </LogLink> ) enqueueSnackbar( <div> Triggered button: {uiButton.spec?.text || uiButton.metadata?.name} {snackbarLogsLink} </div> ) } } const submitButton = ( <ApiSubmitButton text={buttonText} confirming={confirming} disabled={disabled} iconName={uiButton.spec?.iconName} iconSVG={uiButton.spec?.iconSVG} onClick={onClick} analyticsName="ui.web.uibutton" analyticsTags={tags} {...buttonProps} > {props.children} </ApiSubmitButton> ) // show the options button if there are any non-hidden inputs const visibleInputs = uiButton.spec?.inputs?.filter((i) => !i.hidden) || [] if (visibleInputs.length) { const setInputValue = (name: string, value: any) => { // Copy to a new object so that the reference changes to force a rerender. setInputValues({ ...inputValues, [name]: value }) } const getInputValue = (name: string) => inputValues[name] return ( <ApiButtonWithOptions className={className} submit={submitButton} uiButton={uiButton} setInputValue={setInputValue} getInputValue={getInputValue} aria-label={buttonText} analyticsTags={tags} // use-case-wise, it'd probably be better to leave the options button enabled // regardless of the submit button's state. // However, that's currently a low-impact difference, and this is a really // cheap way to ensure the styling matches. disabled={disabled} text={buttonText} {...buttonProps} /> ) } else { return ( <ApiButtonRoot className={className} disableRipple={true} aria-label={buttonText} disabled={disabled} > {submitButton} <ApiCancelButton analyticsName="ui.web.uibutton" analyticsTags={tags} text={buttonText} confirming={confirming} disabled={disabled} onClick={() => setConfirming(false)} {...buttonProps} /> </ApiButtonRoot> ) } } function addButtonToSet(bs: ButtonSet, b: UIButton) { switch (buttonType(b)) { case UIBUTTON_TOGGLE_DISABLE_TYPE: bs.toggleDisable = b break case UIBUTTON_STOP_BUILD_TYPE: bs.stopBuild = b break default: bs.default.push(b) break } } export function buttonsForComponent( buttons: UIButton[] | undefined, componentType: ApiButtonType, componentID: string | undefined ): ButtonSet { let result = newButtonSet() if (!buttons) { return result } buttons.forEach((b) => { const buttonType = b.spec?.location?.componentType || "" const buttonID = b.spec?.location?.componentID || "" const buttonTypesMatch = buttonType.toUpperCase() === componentType.toUpperCase() const buttonIDsMatch = buttonID === componentID if (buttonTypesMatch && buttonIDsMatch) { addButtonToSet(result, b) } }) return result } export function buttonsByComponent( buttons: UIButton[] | undefined ): Map<string, ButtonSet> { const result = new Map<string, ButtonSet>() if (buttons === undefined) { return result } buttons.forEach((b) => { const componentID = b.spec?.location?.componentID || "" // Disregard any buttons that aren't linked to a specific component or resource if (!componentID.length) { return } let buttonSet = result.get(componentID) if (!buttonSet) { buttonSet = newButtonSet() result.set(componentID, buttonSet) } addButtonToSet(buttonSet, b) }) return result }
the_stack
import { ExecutablePipeline } from '../../index'; import { SitecoreIcon } from './SitecoreIcon'; /** Represents a set of disconnected data to run a JSS app from, or import to Sitecore */ export interface Manifest { /** Processes all the existing manifest input data and transforms it to a manifest JSON format */ getManifest: () => Promise<ManifestInstance>; /** * Adds a component to the manifest. Components are modules that can be * added to a route dynamically based on layout settings. */ addComponent: (...components: ComponentDefinition[]) => void; /** * Adds a template (a content data type) to the manifest. Templates * define a schema of data fields. Explicitly adding templates is generally * reserved for defining base templates to inherit from. In most cases, * addComponent() or addRouteType() should be used instead. */ addTemplate: (...templates: TemplateDefinition[]) => void; /** * Adds a placeholder definition to the manifest. * Explicit placeholder definition is not necessary as it is inferred * from route data usage, however it allows the specification of * additional metadata (i.e. display names), and is recommended. */ addPlaceholder: (...placeholders: PlaceholderDefinition[]) => void; /** * Adds a route type (a template containing a route-level fields definition). * Route types are useful for data that is always present on a route - for example * an article route type might contain a headline, category, and author. Favor * component-level fields when possible, as they are personalizable. However * route level fields are much more easily queryable and filterable for listings. */ addRouteType: (...routeTypes: TemplateDefinition[]) => void; /** * Sets default route type (a template containing a route-level fields definition). */ setDefaultRouteType: (defaultRouteType: TemplateDefinition) => void; /** * Adds a route definition to the manifest. A route contains a set of components, and possibly child routes. */ addRoute: (...routes: RouteDefinition[]) => void; /** * Adds a content item to the manifest. Content items are items with non-route and non-component data, * for example global elements or content list target items. */ addContent: (...contents: ItemDefinition[]) => void; /** * Adds a translation dictionary entry to the manifest. */ addDictionary: (...entries: Array<{ key: string; value: string }>) => void; language: string; } export interface ManifestInstance { appName: string; templates: TemplateDefinition[]; items: { routes: RouteDefinition[]; nonRoutes: ItemDefinition[]; }; placeholders: PlaceholderDefinition[]; media?: any[]; dictionary: DictionaryDefinition[]; language: string; wipeExisting: boolean; rootPlaceholders: string[]; } export interface CreateManifestInstanceArgs { pipelines: any; appName: string; excludeItems: boolean; excludeDictionary: boolean; language: string; debug: boolean; wipe: boolean; rootPlaceholders: string[]; skipPlaceholderBlacklist: boolean; } export enum CommonFieldTypes { SingleLineText = 'Single-Line Text', MultiLineText = 'Multi-Line Text', RichText = 'Rich Text', ContentList = 'Treelist', ItemLink = 'Droptree', GeneralLink = 'General Link', Image = 'Image', File = 'File', Number = 'Number', Checkbox = 'Checkbox', Date = 'Date', DateTime = 'Datetime', } export enum FieldStorage { Versioned = 'versioned', Shared = 'shared', Unversioned = 'unversioned', } /** * Represents a field on a JSS component or template */ export interface FieldDefinition { name: string; /** * The data type of the field used when importing. Either a CommonFieldTypes enum value, or a string of a Sitecore field type name. */ type: CommonFieldTypes | string; displayName?: string; /** * Optionally specify an ID used when importing. Can be either a GUID, or a string. ID values must be unique app-wide if specified. */ id?: string; /** * Specify a sort order for the field to be used when importing. Defaults to the order defined in the manifest. */ sortOrder?: number; /** * The value this field will contain when a new item is created with this field on it in Sitecore. '$name' is the name of the item. */ standardValue?: string; /** * Template section name used in Sitecore. Defaults to 'Data' */ section?: string; /** * Whether the field needs required validation in Sitecore. Note: required fields may still not have a value when previewing. * Default: false */ required?: boolean; /** * A regular expression (evaluated in .NET) to validate the field value in Sitecore. * Example: '^[A-Za-z ]+$' */ validationPattern?: string; /** * When used with validationPattern, the message shown when the field fails regex validation in Sitecore. */ validationMessage?: string; /** * Sets the field source in Sitecore. */ source?: string; /** * Sets how the field value is stored in Sitecore. For advanced Sitecore developers only. * Versioned (default) is almost always what you want. Do not change after importing unless using full wipe. * Content data loss could occur if altered after import. */ storage?: FieldStorage; } /** * Defines a non-content parameter that can be set on a component. * Parameters are more developer-focused options than fields, such as configurable CSS classes. */ export type RenderingParameterDefinition = FieldDefinition; /** * Explicitly defines a placeholder name, and allows setting the display name. * NOTE: placeholders defined on routes that are not explicitly defined are automatically added. * Explicit definition is only needed when you wish to specify a display name. */ export interface PlaceholderDefinition { name: string; displayName?: string; /** * Optionally specify an ID used when importing the rendering item for this component. * Can be either a GUID, or a string. ID values must be unique app-wide if specified. * For Sitecore developers only. */ id?: string; } export interface TemplateDefinition { name: string; displayName?: string; /** * The data fields that provide content data to the component */ fields: FieldDefinition[]; /** * The path to a Sitecore icon to use when the component is imported. * Example: 'People/16x16/alarmclock.png' */ icon?: SitecoreIcon | string; /** * Names of other templates to inherit from. Inheritance inherits fields, but not other component data. */ inherits?: string[]; /** * Optionally specify an ID used when importing the template item. * Can be either a GUID, or a string. ID values must be unique app-wide if specified. * For Sitecore developers only. */ id?: string; /** * The path or GUID of a Sitecore workflow to assign to the component's data. * For Sitecore developers only. */ defaultWorkflow?: string; /** Template names to allow as insert options under this template */ insertOptions?: string[]; } export interface ComponentDefinition { name?: string; displayName?: string; /** * The data fields that provide content data to the component */ fields?: FieldDefinition[]; /** * The names of JSS placeholders that this component exposes * (keys of any placeholder components added to this component's JS view) */ placeholders?: PlaceholderDefinition[] | string[]; /** * Explicit names of Sitecore placeholders that this component is allowed * to be placed into. Normally this is automatically inferred based on * route data definitions (it will be allowed in any placeholders it is placed in * in disconnected definitions automatically), however at times explicit definition * is preferable, i.e. if not defining routes but only defining components. * NOTE: Setting an allowed placeholder name does not register it with the manifest; use `manifest.addPlaceholder()` to register it */ allowedPlaceholders?: string[]; /** * Defines non-content parameters. * Parameters are more developer-focused options than fields, such as configurable CSS classes. */ params?: string[] | RenderingParameterDefinition[]; /** * The path to a Sitecore icon to use when the component is imported. * Example: 'People/16x16/alarmclock.png' */ icon?: SitecoreIcon | string; /** * Names of other templates or components to inherit from. Inheritance inherits fields, but not other component data. */ inherits?: string[]; /** * Whether to show a button in Sitecore that allows editing all fields on the component at once. * Default: true */ displayFieldEditorButton?: boolean; /** * Explicitly specify the names of fields that the displayFieldEditorButton button will show. * If displayFieldEditorButton is false, has no effect. */ fieldEditorFields?: string[]; /** * Optionally specify an ID used when importing the rendering item for this component. * Can be either a GUID, or a string. ID values must be unique app-wide if specified. * For Sitecore developers only. */ renderingId?: string; /** * Optionally specify an ID used when importing the datasource template item for this component. * Can be either a GUID, or a string. ID values must be unique app-wide if specified. * For Sitecore developers only. */ templateId?: string; /** * Optionally specify a name used when importing the datasource template item for this component. * For Sitecore developers only. */ templateName?: string; /** * The path or GUID of a Sitecore workflow to assign to the component's data. * For Sitecore developers only. */ defaultWorkflow?: string; /** * A GraphQL query that will be executed against the JSS app's configured Sitecore GraphQL endpoint * (in-process) to activate _Integrated GraphQL_. iGQL will replace the `fields` collection in the LS response * with the results of this GraphQL query, instead of the default datasource serialization. */ graphQLQuery?: string; /** Template names to allow as insert options under this template */ insertOptions?: string[]; } export interface DictionaryDefinition { key: string; value: string; } export interface ImageFieldValue { src: string; alt: string; id?: string; displayName?: string; title?: string; keywords?: string; description?: string; width?: number; height?: number; class?: string; } export interface LinkFieldValue { /** * The href of the link. If this is a valid route, an internal link is created on import. * Otherwise, the value is used literally. */ href: string; /** * The text shown as the body of the link */ text?: string; /** * The anchor (ie #foo) the link points to * Used for internal links. */ anchor?: string; /** * The CSS class of the link tag */ class?: string; /** * The query string added to the link URL * Used for internal links. */ querystring?: string; /** * The target attribute of the link tag */ target?: string; /** * The title attribute of the link tag */ title?: string; } export interface ContentFieldValue { value: | string | number | boolean | ImageFieldValue | LinkFieldValue | Array<ItemDefinition | ItemReference>; editable?: string; } export interface ItemDefinition { name: string; template: string; displayName?: string; id?: string; fields?: { [key: string]: ContentFieldValue }; children?: Array<ItemDefinition | ItemReference>; layout?: { renderings: { [key: string]: unknown }; }; path?: string; insertOptions?: string[]; } export interface ItemReference { id: string; } /** * @param {ItemDefinition | ItemReference} obj */ export function isItemDefinition(obj: ItemDefinition | ItemReference): obj is ItemDefinition { return (obj as ItemDefinition).name !== undefined; } export interface RouteDefinition extends ItemDefinition { placeholders?: { [key: string]: ComponentInstanceDefinition[] }; } export interface ComponentInstanceDefinition extends ItemDefinition { componentName: string; placeholders?: { [key: string]: ComponentInstanceDefinition[] }; } export interface GeneratePipelineArgs { [key: string]: any; debug: boolean; skipPlaceholderBlacklist: boolean; components: ComponentDefinition[]; routes: RouteDefinition[]; content: ItemDefinition[]; dictionary: DictionaryDefinition[]; templates: TemplateDefinition[]; placeholders: PlaceholderDefinition[]; appName: string; language: string; pipelines: { [key: string]: ExecutablePipeline }; pipelineResult: ManifestInstance & { [key: string]: any }; } export interface GenerateContentItemArgs extends GeneratePipelineArgs { content: any; item?: any; } export interface GeneratePlaceholdersPipelineArgs { items: RouteDefinition[]; renderings: any[]; placeholders: PlaceholderDefinition[]; placeholderNames: string[]; rootPlaceholders: string[]; skipPlaceholderBlacklist: boolean; pipelines: { [key: string]: ExecutablePipeline }; } export interface GenerateRouteItemPipelineArgs { [key: string]: any; route: RouteDefinition; components: ComponentDefinition[]; pipelines: { [key: string]: ExecutablePipeline }; item: any; dynamicPlaceholderKeyGenerator: (key: string, rendering: any, parentKey: string) => string; datasourceNamer: ({ item, placeholder, rendering, index, }: { item: any; placeholder: any; rendering: any; index: number; }) => string; datasourceDisplayNamer: ({ rendering, index, }: { item: any; placeholder: any; rendering: any; index: number; }) => string; onRenderingProcessed?: (rendering: any) => void; }
the_stack
import { PdfAnnotationBaseModel } from './pdf-annotation-model'; import { PointModel, PathElement, Rect, DrawingElement, Point, Size, RotateTransform, TextElement, randomId, Matrix, identityMatrix, rotateMatrix, transformPointByMatrix, DecoratorShapes, Intersection, Segment, intersect3 } from '@syncfusion/ej2-drawings'; import { setElementStype, findPointsLength } from './drawing-util'; import { isNullOrUndefined } from '@syncfusion/ej2-base'; import { MeasureAnnotation, PdfViewer } from '../index'; /** * @private * @param {PdfAnnotationBaseModel} obj - Specified the annotation object. * @param {PointModel[]} points - Specified the annotation points. * @returns {PointModel[]} - Returns the annotation points model array. */ export function getConnectorPoints(obj: PdfAnnotationBaseModel, points?: PointModel[]): PointModel[] { points = obj.vertexPoints; const newPoints: PointModel[] = points.slice(0); if (newPoints && newPoints.length > 0) { obj.sourcePoint = newPoints[0]; obj.targetPoint = newPoints[newPoints.length - 1]; } return newPoints; } /** * @private * @param {PdfAnnotationBaseModel} connector - Specified the annotation connector model. * @param {PointModel[]} points - Specified the annotation points. * @returns {string} - Returns the annotation path value. */ export function getSegmentPath(connector: PdfAnnotationBaseModel, points: PointModel[]): string { let path: string = ''; let getPt: PointModel; let pts: PointModel[] = []; let j: number = 0; while (j < points.length) { pts.push({ x: points[j].x, y: points[j].y }); j++; } pts = clipDecorators(connector, pts); for (let k: number = 0; k < pts.length; k++) { getPt = pts[k]; if (k === 0) { path = 'M' + getPt.x + ' ' + getPt.y; } if (k > 0) { path += ' ' + 'L' + getPt.x + ' ' + getPt.y; } } return path; } /** * @private * @param {PdfAnnotationBaseModel} connector - Specified the annotation connector model. * @param {PointModel[]} points - Specified the annotation points. * @param {PathElement} element - Specified the annotation element. * @returns {PathElement} - Returns the annotation path element. */ export function updateSegmentElement(connector: PdfAnnotationBaseModel, points: PointModel[], element: PathElement): PathElement { let bounds: Rect = new Rect(); const segmentPath: string = getSegmentPath(connector, points); bounds = Rect.toBounds(points); element.width = bounds.width; element.height = bounds.height; element.offsetX = bounds.x + element.width / 2; element.offsetY = bounds.y + element.height / 2; element.data = segmentPath; if (connector.wrapper) { connector.wrapper.offsetX = element.offsetX; connector.wrapper.offsetY = element.offsetY; connector.wrapper.width = bounds.width; connector.wrapper.height = bounds.height; } return element; } /** * @private * @param {PdfAnnotationBaseModel} connector - Specified the annotation connector model. * @param {PathElement} segmentElement - Specified the annotation segment element. * @returns {PathElement} - Returns the annotation path element. */ export function getSegmentElement(connector: PdfAnnotationBaseModel, segmentElement: PathElement): PathElement { let points: PointModel[] = []; points = getConnectorPoints(connector); segmentElement.staticSize = true; segmentElement = updateSegmentElement(connector, points, segmentElement); setElementStype(connector, segmentElement); return segmentElement; } /** * @private * @param {PdfAnnotationBaseModel} obj - Specified the annotation object. * @param {DrawingElement} element - Specified the annotation drawing element. * @param {PointModel} pt - Specified the annotation point. * @param {PointModel} adjacentPoint - Specified the annotation adjacent point. * @param {boolean} isSource - Specified the is source value or not. * @returns {void} */ export function updateDecoratorElement( obj: PdfAnnotationBaseModel, element: DrawingElement, pt: PointModel, adjacentPoint: PointModel, isSource: boolean): void { element.offsetX = pt.x; element.offsetY = pt.y; const angle: number = Point.findAngle(pt, adjacentPoint); const thickness: number = obj.thickness <= 5 ? 5 : obj.thickness; const getPath: string = getDecoratorShape(isSource ? obj.sourceDecoraterShapes : obj.taregetDecoraterShapes); const size: Size = new Size(thickness * 2, thickness * 2); element.transform = RotateTransform.Self; setElementStype(obj, element); element.style.fill = (obj.fillColor !== 'tranparent') ? obj.fillColor : 'white'; element.rotateAngle = angle; (element as PathElement).data = getPath; (element as PathElement).canMeasurePath = true; element.width = size.width; element.height = size.height; if (obj.sourceDecoraterShapes === 'Butt') { element.width = size.width - 10; element.height = size.height + 10; } } /** * @private * @param {PdfAnnotationBaseModel} obj - Specified the annotation object. * @param {PointModel} offsetPoint - Specified the annotation offset point. * @param {PointModel} adjacentPoint - Specified the annotation adjacent point. * @param {boolean} isSource - Specified the is source value or not. * @returns {PathElement} - Returns the annotation path element. */ export function getDecoratorElement( obj: PdfAnnotationBaseModel, offsetPoint: PointModel, adjacentPoint: PointModel, isSource: boolean) : PathElement { const decEle: PathElement = new PathElement(); updateDecoratorElement(obj, decEle, offsetPoint, adjacentPoint, isSource); return decEle; } /** * @private * @param {PdfAnnotationBaseModel} connector - Specified the annotation object. * @param {PointModel[]} pts - Specified the annotation point model array. * @returns {PointModel[]} - Returns the annotation point model array. */ export function clipDecorators(connector: PdfAnnotationBaseModel, pts: PointModel[]): PointModel[] { pts[0] = clipDecorator(connector, pts, true); pts[pts.length - 1] = clipDecorator(connector, pts, false); return pts; } /** * @private * @param {PdfAnnotationBaseModel} connector - Specified the annotation connector object. * @param {PointModel[]} points - Specified the annotation offset point. * @param {boolean} isSource - Specified the is source value or not. * @returns {PointModel} - Returns the annotation point model. */ export function clipDecorator(connector: PdfAnnotationBaseModel, points: PointModel[], isSource: boolean): PointModel { let point: PointModel = { x: 0, y: 0 }; let start: PointModel = { x: 0, y: 0 }; let end: PointModel = { x: 0, y: 0 }; const length: number = points.length; start = !isSource ? points[length - 1] : points[0]; end = !isSource ? points[length - 2] : points[1]; let len: number = Point.distancePoints(start, end); len = (len === 0) ? 1 : len; const width: number = connector.thickness; point.x = (Math.round(start.x + width * (end.x - start.x) / len)); point.y = (Math.round(start.y + width * (end.y - start.y) / len)); const strokeWidth: number = 1; point = Point.adjustPoint(point, end, true, (strokeWidth / 2)); return point; } /** * @param {PdfAnnotationBaseModel} obj - Specified the annotation object. * @param {PointModel[]} points - Specified the annotation point model array. * @param {MeasureAnnotation} measure - Specified the measure annotation object. * @param {PdfViewer} pdfviewer - Specified the pdfviewer element. * @hidden * @returns {TextElement[]} - Returns the text element collections. */ // eslint-disable-next-line max-len export function initDistanceLabel(obj: PdfAnnotationBaseModel, points: PointModel[], measure: MeasureAnnotation, pdfviewer: PdfViewer): TextElement[] { const labels: TextElement[] = []; const angle: number = Point.findAngle(points[0], points[1]); const textele: TextElement = textElement(obj, angle); if (!pdfviewer.enableImportAnnotationMeasurement && obj.notes && obj.notes !== '') { textele.content = obj.notes; } else { textele.content = measure.setConversion(findPointsLength([points[0], points[1]]) * measure.pixelToPointFactor, obj); } textele.rotateValue = { y: -10, angle: angle }; if (obj.enableShapeLabel === true) { textele.style.strokeColor = obj.labelBorderColor; textele.style.fill = obj.labelFillColor; textele.style.fontSize = obj.fontSize; textele.style.color = obj.fontColor; textele.style.fontFamily = obj.fontFamily; } labels.push(textele); return labels; } /** * @param {PdfAnnotationBaseModel} obj - Specified the annotation object. * @param {PointModel[]} points - Specified the annotation point model array. * @param {MeasureAnnotation} measure - Specified the measure annotation object. * @hidden * @returns {string} - Returns the distance value. */ export function updateDistanceLabel(obj: PdfAnnotationBaseModel, points: PointModel[], measure: MeasureAnnotation): string { let distance: string; for (let i: number = 0; i < obj.wrapper.children.length; i++) { const textElement: TextElement = (obj.wrapper.children[i] as TextElement); if (textElement && !isNullOrUndefined(textElement.content)) { distance = measure.setConversion(findPointsLength([points[0], points[1]]) * measure.pixelToPointFactor, obj); textElement.content = distance; textElement.childNodes[0].text = textElement.content; textElement.refreshTextElement(); } } return distance; } /** * @param {PdfAnnotationBaseModel} obj - Specified the annotation object. * @param {MeasureAnnotation} measure - Specified the measure annotation object. * @hidden * @returns {string} - Returns the radius label value. */ export function updateRadiusLabel(obj: PdfAnnotationBaseModel, measure: MeasureAnnotation): string { let radius: string; for (let i: number = 0; i < obj.wrapper.children.length; i++) { const textElement: TextElement = (obj.wrapper.children[i] as TextElement); if (textElement && !isNullOrUndefined(textElement.content)) { radius = measure.setConversion((obj.bounds.width / 2) * measure.pixelToPointFactor, obj); textElement.content = radius; if (textElement.childNodes.length === 2) { textElement.childNodes[0].text = radius; textElement.childNodes.splice(textElement.childNodes.length - 1, 1); } else { textElement.childNodes[0].text = radius; } textElement.refreshTextElement(); } } return radius; } /** * @param {PdfAnnotationBaseModel} obj - Specified the annotation object. * @param {PointModel[]} points - Specified the annotation point model array. * @param {MeasureAnnotation} measure - Specified the measure annotation object. * @param {PdfViewer} pdfviewer - Specified the pdfviewer element. * @hidden * @returns {TextElement[]} - Returns the text element collections. */ // eslint-disable-next-line max-len export function initPerimeterLabel(obj: PdfAnnotationBaseModel, points: PointModel[], measure: MeasureAnnotation, pdfviewer: PdfViewer): TextElement[] { const labels: TextElement[] = []; const angle: number = Point.findAngle(points[0], points[1]); const textele: TextElement = textElement(obj, angle); if (!pdfviewer.enableImportAnnotationMeasurement && obj.notes && obj.notes !== '') { textele.content = obj.notes; } else { textele.content = measure.calculatePerimeter(obj); } if (obj.enableShapeLabel === true) { textele.style.strokeColor = obj.labelBorderColor; textele.style.fill = obj.labelFillColor; textele.style.fontSize = obj.fontSize; textele.style.color = obj.fontColor; textele.style.fontFamily = obj.fontFamily; } textele.rotateValue = { y: -10, angle: angle }; labels.push(textele); return labels; } /** * @param {PdfAnnotationBaseModel} obj - Specified the annotation object. * @param {PointModel[]} points - Specified the annotation point model array. * @param {MeasureAnnotation} measure - Specified the measure annotation object. * @hidden * @returns {string} - Returns the perimeter label value. */ export function updatePerimeterLabel(obj: PdfAnnotationBaseModel, points: PointModel[], measure: MeasureAnnotation): string { let perimeter: string; for (let i: number = 0; i < obj.wrapper.children.length; i++) { const textElement: TextElement = (obj.wrapper.children[i] as TextElement); if (textElement && !isNullOrUndefined(textElement.content)) { perimeter = measure.calculatePerimeter(obj); textElement.content = perimeter; textElement.childNodes[0].text = textElement.content; textElement.refreshTextElement(); } } return perimeter; } /** * @param {PdfAnnotationBaseModel} obj - Specified the annotation object. * @hidden * @returns {void} */ export function removePerimeterLabel(obj: PdfAnnotationBaseModel): void { for (let i: number = 0; i < obj.wrapper.children.length; i++) { const textElement: TextElement = (obj.wrapper.children[i] as TextElement); if (textElement && !isNullOrUndefined(textElement.content)) { obj.wrapper.children.splice(i, 1); } } } /** * @param {PdfAnnotationBaseModel} obj - Specified the annotation object. * @hidden * @returns {void} */ export function updateCalibrateLabel(obj: PdfAnnotationBaseModel): void { if (obj.wrapper && obj.wrapper.children) { for (let i: number = 0; i < obj.wrapper.children.length; i++) { const textElement: TextElement = (obj.wrapper.children[i] as TextElement); if (textElement && !isNullOrUndefined(textElement.content)) { textElement.content = obj.notes; textElement.childNodes[0].text = textElement.content; textElement.refreshTextElement(); } } } } /** * Used to find the path for polygon shapes * * @param {PointModel[]} collection - Specified the polygon annotaion points collection. * @hidden * @returns {string} - Returns the polygon annotation path. */ export function getPolygonPath(collection: PointModel[]): string { let path: string = ''; let seg: PointModel; path = 'M' + collection[0].x + ' ' + collection[0].y; let i: number; for (i = 1; i < collection.length; i++) { seg = collection[i]; path += 'L' + seg.x + ' ' + seg.y; } path += 'Z'; return path; } /** * @param {PdfAnnotationBaseModel} obj - Specified the annotation object. * @param {number} angle - Specified the annotaion rotation angle. * @hidden * @returns {TextElement} - Returns the annotation text element. */ export function textElement(obj: PdfAnnotationBaseModel, angle: number): TextElement { const textele: TextElement = new TextElement(); setElementStype(obj, textele); textele.style.fill = 'transparent'; textele.id = randomId(); textele.horizontalAlignment = 'Center'; textele.rotateValue = { y: 10, angle: angle }; textele.verticalAlignment = 'Top'; textele.relativeMode = 'Object'; textele.setOffsetWithRespectToBounds(.5, .5, 'Absolute'); // eslint-disable-next-line textele.offsetX; textele.style.textWrapping = 'NoWrap'; return textele; } /** * @param {PdfAnnotationBaseModel} obj - Specified the annotation object. * @param {PointModel[]} points - Specified the annotaion leader points. * @hidden * @returns {PathElement[]} - Returns the annotation path elements. */ export function initLeaders(obj: PdfAnnotationBaseModel, points: PointModel[]): PathElement[] { const leaders: PathElement[] = []; let leader: PathElement = initLeader(obj, points[0], points[1]); leaders.push(leader); leader = initLeader(obj, points[1], points[0], true); leaders.push(leader); return leaders; } /** * @param {PdfAnnotationBaseModel} obj - Specified the annotation object. * @param {PointModel} point1 - Specified the annotaion leader point1. * @param {PointModel} point2 - Specified the annotaion leader point2. * @param {boolean} isSecondLeader - Specified the is second leader or not. * @hidden * @returns {PathElement} - Returns the annotation path element. */ export function initLeader( obj: PdfAnnotationBaseModel, point1: PointModel, point2: PointModel, isSecondLeader?: boolean): PathElement { const element: PathElement = new PathElement(); element.offsetX = point1.x; element.offsetY = point1.y; const angle: number = Point.findAngle(point1, point2); const center: PointModel = { x: (point1.x + point2.x) / 2, y: (point1.y + point2.y) / 2 }; let matrix: Matrix = identityMatrix(); rotateMatrix(matrix, 0 - angle, center.x, center.y); let rotatedPoint: PointModel = transformPointByMatrix(matrix, point1); const newPoint1: PointModel = { x: rotatedPoint.x, y: rotatedPoint.y - obj.leaderHeight }; matrix = identityMatrix(); rotateMatrix(matrix, angle, element.offsetX, element.offsetY); rotatedPoint = transformPointByMatrix(matrix, newPoint1); const finalPoint: PointModel = { x: point1.x, y: point1.y }; element.offsetX = finalPoint.x; element.offsetY = finalPoint.y; element.transform = RotateTransform.Self; const getPath: string = 'M' + point1.x + ',' + point1.y + ',L' + rotatedPoint.x + ',' + rotatedPoint.y + 'Z'; const size: Size = new Size(0, obj.leaderHeight); element.pivot.x = .5; if (isSecondLeader) { element.id = 'leader2_' + randomId(); element.pivot.y = 0; } else { element.id = 'leader1_' + randomId(); element.pivot.y = 1; } setElementStype(obj, element); element.rotateAngle = angle; (element as PathElement).data = getPath; (element as PathElement).canMeasurePath = true; element.width = size.width; element.height = size.height; return element; } /** * @private * @param {PdfAnnotationBaseModel} connector - Specified the annotation connector object. * @param {PointModel} reference - Specified the pointer reference value. * @returns {boolean} - Returns true or false. */ export function isPointOverConnector(connector: PdfAnnotationBaseModel, reference: PointModel): boolean { const vertexPoints: PointModel[] = connector.vertexPoints; for (let i: number = 0; i < vertexPoints.length - 1; i++) { const start: PointModel = vertexPoints[i]; const end: PointModel = vertexPoints[i + 1]; const rect: Rect = Rect.toBounds([start, end]); rect.Inflate(10); if (rect.containsPoint(reference)) { const intersectinPt: PointModel = findNearestPoint(reference, start, end); const segment1: Segment = { x1: start.x, x2: end.x, y1: start.y, y2: end.y }; const segment2: Segment = { x1: reference.x, x2: intersectinPt.x, y1: reference.y, y2: intersectinPt.y }; const intersectDetails: Intersection = intersect3(segment1, segment2); if (intersectDetails.enabled) { const distance: number = Point.findLength(reference, intersectDetails.intersectPt); if (Math.abs(distance) < 10) { return true; } } else { const rect: Rect = Rect.toBounds([reference, reference]); rect.Inflate(3); if (rect.containsPoint(start) || rect.containsPoint(end)) { return true; } } if (Point.equals(reference, intersectinPt)) { return true; } } } return false; } /** * @param {PointModel} reference - Specified the pointer reference value. * @param {PointModel} start - Specified the pointer start value. * @param {PointModel} end - Specified the pointer end value. * @private * @returns {PointModel} - Returns annotation point model. */ export function findNearestPoint(reference: PointModel, start: PointModel, end: PointModel): PointModel { let shortestPoint: PointModel; const shortest: number = Point.findLength(start, reference); const shortest1: number = Point.findLength(end, reference); if (shortest > shortest1) { shortestPoint = end; } else { shortestPoint = start; } const angleBWStAndEnd: number = Point.findAngle(start, end); const angleBWStAndRef: number = Point.findAngle(shortestPoint, reference); const r: number = Point.findLength(shortestPoint, reference); const vaAngle: number = angleBWStAndRef + ((angleBWStAndEnd - angleBWStAndRef) * 2); return { x: (shortestPoint.x + r * Math.cos(vaAngle * Math.PI / 180)), y: (shortestPoint.y + r * Math.sin(vaAngle * Math.PI / 180)) }; } /** * @param {DecoratorShapes} shape - Specified the annotation decorator shapes. * @hidden * @returns {string} - Returns the annotation decorator shape value. */ export function getDecoratorShape(shape: DecoratorShapes ): string { // eslint-disable-next-line return (decoratorShapes as any)[shape]; } const decoratorShapes: {} = { 'OpenArrow': 'M15.9,23 L5,16 L15.9,9 L17,10.7 L8.7,16 L17,21.3Z', 'Square': 'M0,0 L10,0 L10,10 L0,10 z', 'Fletch': 'M14.8,10c0,0-3.5,6,0.2,12c0,0-2.5-6-10.9-6C4.1,16,11.3,16,14.8,10z', 'OpenFetch': 'M6,17c-0.6,0-1-0.4-1-1s0.4-1,1-1c10.9,0,11-5,11-5' + 'c0-0.6,0.4-1,1-1s1,0.4,1,1C19,10.3,18.9,17,6,17C6,17,6,17,6,17z ' + 'M18,23c-0.5,0-1-0.4-1-1c0-0.2-0.3-5-11-5c-0.6,0-1-0.5-1-1s0.4-1,1-1c0,0,0,0,0,0' + 'c12.9,0,13,6.7,13,7 C19,22.6,18.6,23,18,23z', 'IndentedArrow': 'M17,10c0,0-4.5,5.5,0,12L5,16L17,10z', 'OutdentedArrow': 'M14.6,10c0,0,5.4,6,0,12L5,16L14.6,10z', 'DoubleArrow': 'M19,10 L19,22 L13,16Z M12,10 L12,22 L6,16Z', 'Arrow': 'M15,10 L15,22 L5,16Z', 'Diamond': 'M12,23l-7-7l7-7l6.9,7L12,23z', 'Circle': 'M0,50 A50,50,0 1 1 100,50 A50,50,0 1 1 0,50 Z', 'Butt': 'M0,0 L0,90' };
the_stack
import { Array1D, CostReduction, FeedEntry, Graph, InCPUMemoryShuffledInputProviderBuilder, NDArrayMath, NDArrayMathGPU, SGDOptimizer, Session, Tensor } from '../deeplearnjs'; class ComplementaryColorModel { // Runs training. session: Session; // Encapsulates math operations on the CPU and GPU. math: NDArrayMath = new NDArrayMathGPU(); // An optimizer with a certain initial learning rate. Used for training. initialLearningRate = 0.042; optimizer: SGDOptimizer; // Each training batch will be on this many examples. batchSize = 300; inputTensor: Tensor; targetTensor: Tensor; costTensor: Tensor; predictionTensor: Tensor; // Maps tensors to InputProviders. feedEntries: FeedEntry[]; constructor() { this.optimizer = new SGDOptimizer(this.initialLearningRate); } /** * Constructs the graph of the model. Call this method before training. */ setupSession(): void { const graph = new Graph(); // This tensor contains the input. In this case, it is a scalar. this.inputTensor = graph.placeholder('input RGB value', [3]); // This tensor contains the target. this.targetTensor = graph.placeholder('output RGB value', [3]); // Create 3 fully connected layers, each with half the number of nodes of // the previous layer. The first one has 16 nodes. let fullyConnectedLayer = this.createFullyConnectedLayer(graph, this.inputTensor, 0, 64); // Create fully connected layer 1, which has 8 nodes. fullyConnectedLayer = this.createFullyConnectedLayer(graph, fullyConnectedLayer, 1, 32); // Create fully connected layer 2, which has 4 nodes. fullyConnectedLayer = this.createFullyConnectedLayer(graph, fullyConnectedLayer, 2, 16); this.predictionTensor = this.createFullyConnectedLayer(graph, fullyConnectedLayer, 3, 3); // We will optimize using mean squared loss. this.costTensor = graph.meanSquaredCost(this.predictionTensor, this.targetTensor); // Create the session only after constructing the graph. this.session = new Session(graph, this.math); // Generate the data that will be used to train the model. this.generateTrainingData(1e5); } /** * Trains one batch for one iteration. Call this method multiple times to * progressively train. Calling this function transfers data from the GPU in * order to obtain the current loss on training data. * * If shouldFetchCost is true, returns the mean cost across examples in the * batch. Otherwise, returns -1. We should only retrieve the cost now and then * because doing so requires transferring data from the GPU. */ train1Batch(shouldFetchCost: boolean): number { // Every 42 steps, lower the learning rate by 15%. const learningRate = this.initialLearningRate * Math.pow(0.85, Math.floor(step / 42)); this.optimizer.setLearningRate(learningRate); // Train 1 batch. let costValue = -1; this.math.scope(() => { const cost = this.session.train( this.costTensor, this.feedEntries, this.batchSize, this.optimizer, shouldFetchCost ? CostReduction.MEAN : CostReduction.NONE); if (!shouldFetchCost) { // We only train. We do not compute the cost. return; } // Compute the cost (by calling get), which requires transferring data // from the GPU. costValue = cost.get(); }); return costValue; } normalizeColor(rgbColor: number[]): number[] { return rgbColor.map(v => v / 255); } denormalizeColor(normalizedRgbColor: number[]): number[] { return normalizedRgbColor.map(v => v * 255); } predict(rgbColor: number[]): number[] { let complementColor: number[] = []; this.math.scope((keep, track) => { const mapping = [{ tensor: this.inputTensor, data: Array1D.new(this.normalizeColor(rgbColor)), }]; const evalOutput = this.session.eval(this.predictionTensor, mapping); const values = evalOutput.getValues(); const colors = this.denormalizeColor(Array.prototype.slice.call(values)); // Make sure the values are within range. complementColor = colors.map( v => Math.round(Math.max(Math.min(v, 255), 0))); }); return complementColor; } private createFullyConnectedLayer( graph: Graph, inputLayer: Tensor, layerIndex: number, sizeOfThisLayer: number) { return graph.layers.dense( 'fully_connected_' + layerIndex, inputLayer, sizeOfThisLayer, (x) => graph.relu(x)); } /** * Generates data used to train. Creates a feed entry that will later be used * to pass data into the model. Generates `exampleCount` data points. */ private generateTrainingData(exampleCount: number) { this.math.scope(() => { const rawInputs = new Array(exampleCount); for (let i = 0; i < exampleCount; i++) { rawInputs[i] = [ this.generateRandomChannelValue(), this.generateRandomChannelValue(), this.generateRandomChannelValue() ]; } // Store the data within Array1Ds so that learnjs can use it. const inputArray: Array1D[] = rawInputs.map(c => Array1D.new(this.normalizeColor(c))); const targetArray: Array1D[] = rawInputs.map( c => Array1D.new( this.normalizeColor(this.computeComplementaryColor(c)))); // This provider will shuffle the training data (and will do so in a way // that does not separate the input-target relationship). const shuffledInputProviderBuilder = new InCPUMemoryShuffledInputProviderBuilder( [inputArray, targetArray]); const [inputProvider, targetProvider] = shuffledInputProviderBuilder.getInputProviders(); // Maps tensors to InputProviders. this.feedEntries = [ {tensor: this.inputTensor, data: inputProvider}, {tensor: this.targetTensor, data: targetProvider} ]; }); } private generateRandomChannelValue() { return Math.floor(Math.random() * 256); } /** * This implementation of computing the complementary color came from an * answer by Edd https://stackoverflow.com/a/37657940 */ computeComplementaryColor(rgbColor: number[]): number[] { let r = rgbColor[0]; let g = rgbColor[1]; let b = rgbColor[2]; // Convert RGB to HSL // Adapted from answer by 0x000f http://stackoverflow.com/a/34946092/4939630 r /= 255.0; g /= 255.0; b /= 255.0; const max = Math.max(r, g, b); const min = Math.min(r, g, b); let h = (max + min) / 2.0; let s = h; const l = h; if (max === min) { h = s = 0; // achromatic } else { const d = max - min; s = (l > 0.5 ? d / (2.0 - max - min) : d / (max + min)); if (max === r && g >= b) { h = 1.0472 * (g - b) / d; } else if (max === r && g < b) { h = 1.0472 * (g - b) / d + 6.2832; } else if (max === g) { h = 1.0472 * (b - r) / d + 2.0944; } else if (max === b) { h = 1.0472 * (r - g) / d + 4.1888; } } h = h / 6.2832 * 360.0 + 0; // Shift hue to opposite side of wheel and convert to [0-1] value h += 180; if (h > 360) { h -= 360; } h /= 360; // Convert h s and l values into r g and b values // Adapted from answer by Mohsen http://stackoverflow.com/a/9493060/4939630 if (s === 0) { r = g = b = l; // achromatic } else { const hue2rgb = (p: number, q: number, t: number) => { if (t < 0) t += 1; if (t > 1) t -= 1; if (t < 1 / 6) return p + (q - p) * 6 * t; if (t < 1 / 2) return q; if (t < 2 / 3) return p + (q - p) * (2 / 3 - t) * 6; return p; }; const q = l < 0.5 ? l * (1 + s) : l + s - l * s; const p = 2 * l - q; r = hue2rgb(p, q, h + 1 / 3); g = hue2rgb(p, q, h); b = hue2rgb(p, q, h - 1 / 3); } return [r, g, b].map(v => Math.round(v * 255)); } } const complementaryColorModel = new ComplementaryColorModel(); // Create the graph of the model. complementaryColorModel.setupSession(); // On every frame, we train and then maybe update the UI. let step = 0; function trainAndMaybeRender() { if (step > 4242) { // Stop training. return; } // Schedule the next batch to be trained. requestAnimationFrame(trainAndMaybeRender); // We only fetch the cost every 5 steps because doing so requires a transfer // of data from the GPU. const localStepsToRun = 5; let cost; for (let i = 0; i < localStepsToRun; i++) { cost = complementaryColorModel.train1Batch(i === localStepsToRun - 1); step++; } // Print data to console so the user can inspect. console.log('step', step - 1, 'cost', cost); // Visualize the predicted complement. const colorRows = document.querySelectorAll('tr[data-original-color]'); for (let i = 0; i < colorRows.length; i++) { const rowElement = colorRows[i]; const tds = rowElement.querySelectorAll('td'); const originalColor = (rowElement.getAttribute('data-original-color') as string) .split(',') .map(v => parseInt(v, 10)); // Visualize the predicted color. const predictedColor = complementaryColorModel.predict(originalColor); populateContainerWithColor( tds[2], predictedColor[0], predictedColor[1], predictedColor[2]); } } function populateContainerWithColor( container: HTMLElement, r: number, g: number, b: number) { const originalColorString = 'rgb(' + [r, g, b].join(',') + ')'; container.textContent = originalColorString; const colorBox = document.createElement('div'); colorBox.classList.add('color-box'); colorBox.style.background = originalColorString; container.appendChild(colorBox); } function initializeUi() { const colorRows = document.querySelectorAll('tr[data-original-color]'); for (let i = 0; i < colorRows.length; i++) { const rowElement = colorRows[i]; const tds = rowElement.querySelectorAll('td'); const originalColor = (rowElement.getAttribute('data-original-color') as string) .split(',') .map(v => parseInt(v, 10)); // Visualize the original color. populateContainerWithColor( tds[0], originalColor[0], originalColor[1], originalColor[2]); // Visualize the complementary color. const complement = complementaryColorModel.computeComplementaryColor(originalColor); populateContainerWithColor( tds[1], complement[0], complement[1], complement[2]); } } // Kick off training. initializeUi(); trainAndMaybeRender();
the_stack
import { BaseList } from '../../../src/peer_book/base_list'; import { P2PEnhancedPeerInfo, P2PPeerInfo } from '../../../src/types'; import { initPeerInfoList } from '../../utils/peers'; import { PEER_TYPE, getBucketId } from '../../../src/utils'; import { DEFAULT_NEW_BUCKET_SIZE, DEFAULT_NEW_BUCKET_COUNT, DEFAULT_RANDOM_SECRET, } from '../../../src/constants'; import { errors } from '../../../src'; import 'jest-extended'; describe('Peers base list', () => { const peerListConfig = { bucketSize: DEFAULT_NEW_BUCKET_SIZE, numOfBuckets: DEFAULT_NEW_BUCKET_COUNT, secret: DEFAULT_RANDOM_SECRET, peerType: PEER_TYPE.TRIED_PEER, }; let peerListObj: BaseList; let samplePeers: ReadonlyArray<P2PPeerInfo>; describe('#constructor', () => { beforeEach(() => { samplePeers = initPeerInfoList(); peerListObj = new BaseList(peerListConfig); }); it(`should set properties correctly and create a map of ${DEFAULT_NEW_BUCKET_COUNT} size with ${DEFAULT_NEW_BUCKET_COUNT} buckets each`, () => { expect((peerListObj as any).peerListConfig).toEqual(peerListConfig); expect((peerListObj as any).peerListConfig.bucketSize).toBe(DEFAULT_NEW_BUCKET_SIZE); expect((peerListObj as any).peerListConfig.numOfBuckets).toBe(DEFAULT_NEW_BUCKET_COUNT); expect((peerListObj as any).peerListConfig.secret).toBe(DEFAULT_RANDOM_SECRET); expect((peerListObj as any).peerListConfig.peerType).toBe(PEER_TYPE.TRIED_PEER); expect((peerListObj as any).bucketIdToBucket).toEqual(expect.any(Map)); expect((peerListObj as any).bucketIdToBucket.size).toBe(DEFAULT_NEW_BUCKET_COUNT); for (const peer of (peerListObj as any).bucketIdToBucket) { expect(peer).toHaveLength(2); expect(peer).toEqual(expect.any(Array)); expect(peer[0]).toSatisfy((n: number): boolean => { return n >= 0 && n <= DEFAULT_NEW_BUCKET_COUNT; }); expect(peer[1]).toBeEmpty(); } }); }); describe('#peerList', () => { beforeEach(() => { samplePeers = initPeerInfoList(); peerListObj = new BaseList(peerListConfig); peerListObj.addPeer(samplePeers[0]); peerListObj.addPeer(samplePeers[1]); peerListObj.addPeer(samplePeers[2]); }); it('should return tried peers list', () => { expect(peerListObj.peerList).toHaveLength(3); expect(peerListObj.peerList.map(peer => peer.peerId)).toEqual( expect.arrayContaining([samplePeers[0].peerId]), ); expect(peerListObj.peerList.map(peer => peer.peerId)).toEqual( expect.arrayContaining([samplePeers[1].peerId]), ); expect(peerListObj.peerList.map(peer => peer.peerId)).toEqual( expect.arrayContaining([samplePeers[2].peerId]), ); }); }); describe('#getPeer', () => { beforeEach(() => { samplePeers = initPeerInfoList(); peerListObj = new BaseList(peerListConfig); peerListObj.addPeer(samplePeers[0]); peerListObj.addPeer(samplePeers[1]); }); describe('when peer exists in the bucketIdToBucket map', () => { it('should get the peer from the incoming peerId', () => { expect(peerListObj.getPeer(samplePeers[0].peerId)).toEqual(samplePeers[0]); }); }); describe('when peer does not exist in the bucketIdToBucket map', () => { it('should return undefined for the given peer that does not exist in bucketIdToBucket map', () => { const randomPeer = initPeerInfoList()[2]; expect(peerListObj.getPeer(randomPeer.peerId)).toBeUndefined(); }); }); }); describe('#hasPeer', () => { beforeEach(() => { samplePeers = initPeerInfoList(); peerListObj = new BaseList(peerListConfig); }); it('should return true if peer exists in peer book', () => { peerListObj.addPeer(samplePeers[0]); expect(peerListObj.hasPeer(samplePeers[0].peerId)).toBe(true); }); it('should return false if peer exists in peer book', () => { expect(peerListObj.hasPeer(samplePeers[0].peerId)).toBe(false); }); }); describe('#addPeer', () => { beforeEach(() => { samplePeers = initPeerInfoList(); peerListObj = new BaseList(peerListConfig); const bucket = new Map<string, P2PEnhancedPeerInfo>(); bucket.set(samplePeers[0].peerId, samplePeers[0]); jest.spyOn(peerListObj, 'calculateBucket').mockReturnValue({ bucketId: 0, bucket }); jest.spyOn(peerListObj, 'makeSpace'); }); it('should add the incoming peer if it does not exist already', () => { peerListObj.addPeer(samplePeers[0]); expect(peerListObj.getPeer(samplePeers[0].peerId)).toEqual(samplePeers[0]); }); it('should throw error if peer already exists', () => { peerListObj.addPeer(samplePeers[0]); // 'Peer already exists' expect(() => peerListObj.addPeer(samplePeers[0])).toThrow(errors.ExistingPeerError); }); it('should call makeSpace method when bucket is full', () => { peerListObj = new BaseList({ bucketSize: 1, numOfBuckets: 1, secret: DEFAULT_RANDOM_SECRET, peerType: PEER_TYPE.TRIED_PEER, }); jest.spyOn(peerListObj, 'makeSpace'); peerListObj.addPeer(samplePeers[0]); peerListObj.addPeer(samplePeers[1]); expect(peerListObj.makeSpace).toHaveBeenCalled(); }); describe('when bucket is not full', () => { it('should return undefined', () => { peerListObj = new BaseList({ ...peerListConfig, bucketSize: 50 }); peerListObj.addPeer(samplePeers[0]); const evictedPeer = peerListObj.addPeer(samplePeers[1]); expect(evictedPeer).toBeUndefined(); }); }); describe('when bucket is full', () => { it('should return evicted peer', () => { peerListObj = new BaseList({ bucketSize: 1, numOfBuckets: 1, secret: DEFAULT_RANDOM_SECRET, peerType: PEER_TYPE.TRIED_PEER, }); peerListObj.addPeer(samplePeers[0]); const evictedPeer = peerListObj.addPeer(samplePeers[1]); expect(samplePeers.map(peer => peer.peerId)).toEqual( expect.arrayContaining([(evictedPeer as any).peerId]), ); }); }); }); describe('#updatePeer', () => { beforeEach(() => { samplePeers = initPeerInfoList(); peerListObj = new BaseList(peerListConfig); peerListObj.addPeer(samplePeers[0]); peerListObj.addPeer(samplePeers[1]); }); describe('when trying to update a peer that exist', () => { it('should update the peer from the incoming peerInfo', () => { const updatedPeer = { ...samplePeers[0], height: 0, version: '1.2.3', }; const success = peerListObj.updatePeer(updatedPeer); expect(success).toBe(true); expect(peerListObj.getPeer(samplePeers[0].peerId)).toEqual(updatedPeer); }); }); describe('when trying to update a peer that does not exist', () => { it('should return false when the peer does not exist', () => { const updatedPeer = { ...samplePeers[2], height: 0, version: '1.2.3', }; const success = peerListObj.updatePeer(updatedPeer); expect(success).toBe(false); }); }); }); describe('#removePeer', () => { beforeEach(() => { samplePeers = initPeerInfoList(); peerListObj = new BaseList(peerListConfig); peerListObj.addPeer(samplePeers[0]); peerListObj.addPeer(samplePeers[1]); }); it('should remove the peer from the incoming peerInfo', () => { peerListObj.removePeer(samplePeers[0]); expect(peerListObj.getPeer(samplePeers[0].peerId)).toBeUndefined(); }); }); describe('#makeSpace', () => { let bucket: any; let calculateBucketStub: any; beforeEach(() => { samplePeers = initPeerInfoList(); peerListObj = new BaseList({ bucketSize: 2, numOfBuckets: 1, secret: DEFAULT_RANDOM_SECRET, peerType: PEER_TYPE.TRIED_PEER, }); peerListObj.addPeer(samplePeers[0]); bucket = new Map<string, P2PEnhancedPeerInfo>(); bucket.set(samplePeers[0].peerId, samplePeers[0]); calculateBucketStub = jest .spyOn(peerListObj, 'calculateBucket') .mockImplementation((input: any) => input); }); describe('when bucket is full', () => { it('should evict one peer randomly', () => { calculateBucketStub({ bucketId: 0, bucket }); const evictedPeer = peerListObj.makeSpace(bucket); expect(samplePeers).toEqual(expect.arrayContaining([evictedPeer as any])); }); }); describe('when bucket is not full', () => { it('should not evict any peer', () => { bucket = new Map<string, P2PEnhancedPeerInfo>(); calculateBucketStub({ bucketId: 1234, bucket }); const evictedPeer = peerListObj.makeSpace(bucket); expect(evictedPeer).toBeUndefined(); }); }); }); describe('#failedConnectionAction', () => { beforeEach(() => { samplePeers = initPeerInfoList(); peerListObj = new BaseList(peerListConfig); peerListObj.addPeer(samplePeers[0]); peerListObj.addPeer(samplePeers[1]); }); describe('when the peer exist and applied failedConnectionAction', () => { it('should delete the peer and for the second call it should return false', () => { const success1 = peerListObj.failedConnectionAction(samplePeers[0]); expect(success1).toBe(true); const success2 = peerListObj.failedConnectionAction(samplePeers[0]); expect(success2).toBe(false); }); }); }); describe('#calculateBucket', () => { beforeEach(() => { samplePeers = initPeerInfoList(); peerListObj = new BaseList(peerListConfig); peerListObj.addPeer(samplePeers[0]); }); it('should get a bucket and bucketId by ipAddress(es)', () => { const bucketId = getBucketId({ bucketCount: DEFAULT_NEW_BUCKET_COUNT, secret: DEFAULT_RANDOM_SECRET, peerType: PEER_TYPE.TRIED_PEER, targetAddress: samplePeers[0].ipAddress, sourceAddress: samplePeers[1].ipAddress, }); const { bucket, bucketId: calculatedBucketId } = peerListObj.calculateBucket( samplePeers[0].ipAddress, samplePeers[1].ipAddress, ); expect(calculatedBucketId).toEqual(bucketId); expect(bucket).toEqual((peerListObj as any).bucketIdToBucket.get(bucketId)); }); }); describe('#getBucket', () => { beforeEach(() => { samplePeers = initPeerInfoList(); peerListObj = new BaseList(peerListConfig); peerListObj.addPeer(samplePeers[0]); }); it('should get bucket based on peerId', () => { const bucket = (peerListObj as any).getBucket(samplePeers[0].peerId); expect(bucket.get(samplePeers[0].peerId).peerId).toEqual(samplePeers[0].peerId); }); it('should return undefined if peer not in bucket', () => { expect((peerListObj as any).getBucket(samplePeers[1].peerId)).toBeUndefined(); }); }); });
the_stack
* @packageDocumentation * @module Parts.W5500 */ /* eslint max-classes-per-file: 0 */ /* eslint rulesdir/non-ascii: 0 */ import Obniz from '../../../obniz'; import PeripheralIO from '../../../obniz/libs/io_peripherals/io'; import PeripheralSPI from '../../../obniz/libs/io_peripherals/spi'; import ObnizPartsInterface, { ObnizPartsInfo, } from '../../../obniz/ObnizPartsInterface'; // Block select bit (BSB) // ブロック選択ビット(BSB) /** 00 Common register 共通レジスタ */ const BSB_COMMON = 0; /** * 01/05/09/13/17/21/25/29 Socket 0\~7 register ソケット 0\~7 レジスタ * * @param socketId ソケットID */ const BSB_SOCKET_REGISTER = (socketId: number) => socketId * 4 + 1; /** * 02/06/10/14/18/22/26/30 Socket 0\~7 TX buffer ソケット 0\~7 TXバッファ * * @param socketId ソケットID */ const BSB_SOCKET_TX_BUFFER = (socketId: number) => socketId * 4 + 2; /** * 03/07/11/15/19/23/27/31 Socket 0\~7 RX buffer ソケット 0\~7 RXバッファ * * @param socketId ソケットID */ const BSB_SOCKET_RX_BUFFER = (socketId: number) => socketId * 4 + 3; /* 04/08/12/16/20/24/28 Reserved 予約済み */ /** Transfer mode 転送モード */ type SendMode = 'Read' | 'Write'; // Common register NumberOfAddressesUsed Read&Write InitialValue Description // 共通レジスタ 使用アドレス数 読み書き 初期値 説明 /** 1byte RW 0x00 Mode モード Reset/\_/WoL/PingBlock/PPPoE/\_/ForceARP/\_ */ const COMMON_MODE = 0x0000; /** 4bytes RW 0x00000000 IPv4 address of default gateway デフォルトゲートウェイのIPv4アドレス */ const COMMON_GATEWAY_ADDRESS = 0x0001; /** 4bytes RW 0x00000000 Subnet mask サブネットマスク */ const COMMON_SOURCE_SUBNET_MASK = 0x0005; /** 6bytes RW 0x000000000000 MAC address MACアドレス */ const COMMON_SOURCE_HARDWARE_ADDRESS = 0x0009; /** 4bytes RW 0x00000000 Local IPv4 address ローカルIPv4アドレス */ const COMMON_SOURCE_IP_ADDRESS = 0x000f; /** * 2byte RW 0x0000 * * Interrupt pin change interval -> Not required because the interrupt pin is not connected * * 割り込みピンの変更間隔 -> 割り込みピン未接続につき使用不要 */ const COMMON_INTERRUPT_LOW_LEVEL_TIMER = 0x0013; /** 1byte RW 0x00 Interrupt 割り込み IPConflict/DestUnreach/PPPoEClose/MagicPacket/\_/\_/\_/\_ */ const COMMON_INTERRUPT = 0x0015; /** * 1byte RW 0x00 * * Interrupt mask (Depending on the initial value, there is no interrupt at the time of initial setting) * * 割り込みマスク(初期値より、初期設定時は割り込みなし) */ const COMMON_INTERRUPT_MASK = 0x0016; /** * 1byte RW 0x00 * * Socket interrupt -> Not implemented this time * * ソケット割り込み -> 今回は未実装 */ const COMMON_SOCKET_INTERRUPT = 0x0017; /** * 1byte RW 0x00 * * Socket interrupt mask (Depending on the initial value, there is no socket interrupt at the time of initial setting) * * ソケット割り込みマスク(初期値より、初期設定時はソケット割り込みなし) */ const COMMON_SOCKET_INTERRUPT_MASK = 0x0018; /** * 2bytes RW 0x07D0 * * Retry interval (Initial value: 100us\*2000=200ms) * * 再試行間隔(初期値: 100us\*2000=200ms) */ const COMMON_RETRY_TIME = 0x0019; /** * 1byte RW 0x08 * * Retry count (If exceeded, the Interrupt timeout for each Socket will be true) * * 再試行回数(超えると各ソケットの割り込みのタイムアウトがtrueに) */ const COMMON_RETRY_COUNT = 0x001b; /** * 1byte RW 0x28 * * Time to send echo request for Link Control Protocol (Initial value: 40\*25ms=1s) * * LinkControlプロトコルのechoリクエストを送っている時間(初期値: 40\*25ms=1s) */ const COMMON_PPP_LCP_REQUEST_TIMER = 0x001c; /** * 1byte RW 0x00 * * 1 byte of the 4 bytes magic number of the Link Control protocol echo request * * LinkControlプロトコルのechoリクエストの4bytesマジックナンバーの1byte */ const COMMON_PPP_LCP_MAGIC_NUMBER = 0x001d; /** 6bytes RW 0x000000000000 MAC address of PPPoE server PPPoEサーバーのMACアドレス */ const COMMON_PPP_DESTINATION_MAC_ADDRESS = 0x001e; /** 2bytes RW 0x0000 Session ID of PPPoE server PPPoEサーバーのセッションID */ const COMMON_PPP_SESSION_IDENTIFICATION = 0x0024; /** 2bytes RW 0xFFFF Maximum receiving unit size of PPPoE PPPoEの最大受信ユニットサイズ */ const COMMON_PPP_MAXIMUM_SEGMENT_SIZE = 0x0026; /** * 4bytes R- 0x00000000 * * IPv4 address when the destination cannot be reached * * 宛先に到達できないときのIPv4アドレス */ const COMMON_UNREACHABLE_IP_ADDRESS = 0x0028; /** * 2bytes R- 0x0000 * * Port number when the destination cannot be reached * * 宛先に到達できないときのポート番号 */ const COMMON_UNREACHABLE_PORT = 0x002c; /** * 1byte RW 0b10111XXX Physical layer settings 物理層の設定 * * Reset(1->0->1)/OperationMode/ConfigBit\*3/Duplex/Speed/Link * * - Reset * * Reset the internal physical layer, need to set this bit to 0 and then back to 1 * * 内部の物理層をリセット、このビットを0にした後、1に戻す必要がある * * - OperationMode * * 1: Use the following 3-bit settings 次の3bitの設定を使用 * * 0: Follow the hardware pin settings ハードウェアピンの設定に従う * * - ConfigBit * * The default setting for both hardware pins and registers is 111 * * ハードウェアピン、レジスタともに初期設定は111 * * - 000 10BT Half duplex 半二重 / 001 10BT Full duplex 全二重 * - 010 100BT Half duplex 半二重 / 011 100BT Full duplex 全二重 * - 100 100BT Half duplex enable auto negotiation 半二重 自動ネゴシエーションオン * - 110 Power Off Mode 電源オフモード * - 111 All available & Enable auto negotiation 全て使用可能 自動ネゴシエーションオン * * - Duplex 1: Full duplex 全二重 0: Half duplex 半二重 * - Speed 1: 100Mbps 0: 10Mbps * - Link 1: Connected 接続済み 0: Disconnected 未接続 */ const COMMON_PHY_CONFIGURATION = 0x002e; /* 0x002F~0x0038 Reserved 予約済み */ /** 1byte R- 0x04 Chip Version チップバージョン */ const COMMON_CHIP_VERSION = 0x0039; // Socket register NumberOfAddressesUsed Read&Write InitialValue Description // ソケットレジスタ 使用アドレス数 読み書き 初期値 説明 /** * 1byte RW 0x00 Mode モード * * Multicast(UDP)·MACFilter(MACRAW)/BroadcastBlock(MACRAW·UDP)/ * * NoDelayACK(TCP)·MulticastVer(UDP)·MulticastBlock(MACRAW)/UnicastBlock(UDP)·IPv6Block(MACRAW)/ * * Protocol\*4 0000: Closed · 0001: TCP · 0010: UDP · 0100: MACRAW */ const SOCKET_MODE = 0x0000; /** * 1byte RW 0x00 Command コマンド * * 0x01: Open · 0x02: Listen(TCP) · 0x04: Connect(TCP) · 0x08: Disconnect(TCP) · 0x10: Close · 0x20: Send · 0x21: SendMAC(UDP) · 0x22: SendKeep(UDP) · 0x40: Receive */ const SOCKET_COMMAND = 0x0001; /** 1byte RCW1 0x00 Interrupt 割り込み \_/\_/\_/SendOK/Timeout/Receive/Disconnect/Connected */ const SOCKET_INTERRUPT = 0x0002; /** * 1byte R- 0x00 Status 状態 * * 0x00: Closed · 0x13: Init(TCP) · 0x14: Listen(TCP) · 0x17: Established(TCP) · 0x1C: CloseWait(TCP) · 0x22: UDP · 0x32: MACRAW * * Temporary Status (Only TCP) 一時的な状態(TCPのみ) * * 0x15: SynSent · 0x16: SynReceive · 0x18: FinWait · 0x1A: Closing · 0x1B: TimeWait · 0x1D: LastACK */ const SOCKET_STATUS = 0x0003; /** 2bytes RW 0x0000 Source port 差出ポート */ const SOCKET_SOURCE_PORT = 0x0004; /** * 6bytes RW 0xFFFFFFFFFFFF * * Destination hardware address (UDP/ARP) -> Not used this time * * 宛先ハードウェアアドレス(UDP/ARP) -> 今回は未使用 */ const SOCKET_DESTINATION_HARDWARE_ADDRESS = 0x0006; /** 4 RW 0x00000000 Destination IPv4 address 宛先IPv4アドレス (TCP/UDP) */ const SOCKET_DESTINATION_IP_ADDRESS = 0x000c; /** 2 RW 0x0000 Destination port 宛先ポート (TCP/UDP) */ const SOCKET_DESTINATION_PORT = 0x0010; /** * 2bytes RW 0x0000 * * Maximum segment size (TCP?) -> Not used this time? * * 最大セグメントサイズ(TCP?) -> 今回は未使用? */ const SOCKET_MAX_SEGMENT_SIZE = 0x0012; /* 0x0014 Reserved 予約済み */ /** * 1byte RW 0x00 * * Set before the Open command Openコマンドより前に設定 * * [http://www.iana.org/assignments/ip-parameters](http://www.iana.org/assignments/ip-parameters) */ const SOCKET_IP_TYPE_OF_SERVICE = 0x0015; /** * 1byte RW 0x00 * * Set before the Open command Openコマンドより前に設定 * * [http://www.iana.org/assignments/ip-parameters](http://www.iana.org/assignments/ip-parameters) */ const SOCKET_TTL = 0x0016; /* 0x0017~0x001D Reserved 予約済み */ /** 1byte RW 0x00 RX buffer size RXバッファサイズ 0/1/2/4/8/16KB */ const SOCKET_RX_BUFFER_SIZE = 0x001e; /** 1byte RW 0x02 TX buffer size TXバッファサイズ 0/1/2/4/8/16KB */ const SOCKET_TX_BUFFER_SIZE = 0x001f; /** 2bytes R- 0x0800 TX free size TX空きサイズ */ const SOCKET_TX_FREE_SIZE = 0x0020; /** 2bytes R- 0x0000 TX read pointer TX読込ポインタ */ const SOCKET_TX_READ_POINTER = 0x0022; /** 2bytes RW 0x0000 TX write pointer TX書込ポインタ */ const SOCKET_TX_WRITE_POINTER = 0x0024; /** 2bytes R- 0x0000 RX receive size RX受信サイズ */ const SOCKET_RX_RECEIVE_SIZE = 0x0026; /** 2bytes RW 0x0000 RX read pointer RX読込ポインタ */ const SOCLET_RX_READ_DATA_POINTER = 0x0028; /** 2bytes R- 0x0000 RX write pointer RX書込ポインタ */ const SOCKET_RX_WRITE_POINTER = 0x002a; /** * 1byte RW 0xFF * * Interrupt mask -> Not going to change * * 割り込みマスク -> 変更しない */ const SOCKET_INTERRUPT_MASK = 0x002c; /** 2bytes RW 0x4000 Fragment of IP header IPヘッダーのフラグメント */ const SOCKET_FRAGMENT = 0x002d; /** 1byte RW 0x0000 keep-alive Timer keep-aliveタイマー (TCP) (Ex. 0x0A->50s) */ const SOCKET_KEEP_ALIVE_TIMER = 0x002f; /* 0x0030~0xFFFF Reserved 予約済み */ /** Wait Xms Xミリ秒待つ @hidden */ const sleep = (msec: number) => new Promise((resolve) => setTimeout(resolve, msec)); /** [43, 227, 213] => '2BE3D5' @hidden */ const byteString = (bytes: number[]) => bytes.map((n) => ('00' + n.toString(16).toUpperCase()).slice(-2)).join(''); /** W5500 type definitions and constants W5500の型定義や定数 */ export namespace W5500Parts { /** Pin assignment and SPI options ピンアサインとSPIオプション */ export interface WiredOptions { /** Reset pin number (initial value: 12) リセットピン番号 (初期値: 12) */ reset?: number; /** SPI MOSI pin number (initial value: 23) SPIのMOSIピン番号 (初期値: 23) */ mosi?: number; /** SPI MISO pin number (initial value: 19) SPIのMISOピン番号 (初期値: 19) */ miso?: number; /** SPI CLK pin number (initial value: 18) SPIのCLKピン番号 (初期値: 18) */ clk?: number; /** SPI CS pin number (initial value: 33) SPIのCSピン番号 (初期値: 33) */ cs?: number; /** * SPI clock frequency (initial value: 20000000(26Mhz)) * * SPIのクロック周波数(初期値: 20000000(26Mhz)) */ frequency?: number; } /** W5500 config W5500の設定内容 */ export interface Config { /** Wait for Wake on LAN WakeOnLANを待ち受ける */ wol?: boolean; /** Do not respond to ping pingを応答しない */ pingBlock?: boolean; /** Use PPPoE PPPoEを使用する */ pppoe?: boolean; /** * Always send an ARP request when sending data * * データを送信した時は必ずARPリクエストを送信する */ forceArp?: boolean; /** * Uses fixed data length (maximum 4 bytes) communication, automatically turned on when CS pin is not specified * * 固定データ長(最大4bytes)通信を使用する、CSピン指定がない場合自動的にオン */ fdm?: boolean; /** IPv4 address of default gateway デフォルトゲートウェイのIPv4アドレス */ gatewayIP: string; /** Subnet mask サブネットマスク */ subnetMask: string; /** MAC address MACアドレス */ macAddress: string; /** Local IPv4 address ローカルIPv4アドレス */ localIP: string; /** Retry interval 再試行間隔 */ retryTime?: number; /** Retry count 再試行回数 */ retryCount?: number; /** * Time to send echo request for Link Control Protocol * * LinkControlプロトコルのechoリクエストを送っている時間 */ linkControlProtocolRequestTimer?: number; /** * 1 byte of the 4 bytes magic number of the Link Control protocol echo request * * LinkControlプロトコルのechoリクエストの4bytesマジックナンバーの1byte */ linkControlProtocolMagicNumber?: number; /** MAC address of PPPoE server PPPoEサーバーのMACアドレス */ pppoeDestMACAddress?: string; /** Session ID of PPPoE Server PPPoEサーバーのセッションID */ pppoeSessionID?: number; /** Maximum receiving unit size of PPPoE PPPoEの最大受信ユニットサイズ */ pppoeMaxSegmentSize?: number; /** Physical layer settings 物理層の設定 */ phyConfig?: PhysicalLayerOptions; /** Do not always check transfer when writing 常に書き込み時に転送チェックを行わない */ forceNoCheckWrite?: boolean; /** Event handler for interrupt "IPConflict" 割り込み「IPConflict」のイベントハンドラー */ onIPConflictInterrupt?: (ethernet: W5500) => Promise<void>; /** Event handler for interrupt "DestUnreach" 割り込み「DestUnreach」のイベントハンドラー */ onDestUnreachInterrupt?: ( ethernet: W5500, extra?: W5500Parts.DestInfo ) => Promise<void>; /** Event handler for interrupt "PPPoEClose" 割り込み「PPPoEClose」のイベントハンドラー */ onPPPoECloseInterrupt?: (ethernet: W5500) => Promise<void>; /** Event handler for interrupt "MagicPacket" 割り込み「MagicPacket」のイベントハンドラー */ onMagicPacketInterrupt?: (ethernet: W5500) => Promise<void>; /** Event handler for all interrupts */ onAllInterrupt?: ( ethernet: W5500, name: W5500Parts.Interrupt, extra?: W5500Parts.DestInfo ) => Promise<void>; } /** Link speed 接続速度(Mbps)(10/100) */ export type LinkSpeed = 10 | 100; /** Physical layer status 物理層のステータス */ export interface PhysicalLayerStatus { /** Whether it is full duplex 全二重かどうか */ duplex: boolean; /** Link speed 接続速度 (Mbps) (10/100) */ speed: LinkSpeed; /** Whether the connection is established 接続が確立されているかどうか */ link: boolean; } /** Physical layer settings 物理層の設定内容 */ export interface PhysicalLayerOptions { /** Physical layer reset 物理層のリセット */ reset?: boolean; /** Auto negotiation 自動ネゴシエーション */ autoNegotiation?: boolean; /** Link speed 接続速度 (Mbps) (10/100) */ speed?: LinkSpeed; /** Whether it is full duplex 全二重かどうか */ duplex?: boolean; /** Whether to turn off the power 電源オフにするかどうか */ powerOff?: boolean; } /** Interrupt type 割り込みの種類 */ export type Interrupt = | 'IPConflict' | 'DestUnreach' | 'PPPoEClose' | 'MagicPacket'; /** Flags corresponding to interrupts 割り込みに対応するフラグ */ export const InterruptFlags: { [key in Interrupt]: number } = { IPConflict: 0b10000000, DestUnreach: 0b01000000, PPPoEClose: 0b00100000, MagicPacket: 0b00010000, } as const; /** Connection destination information 接続先情報 */ export class DestInfo { /** IPv4 address IPv4アドレス */ public readonly ip: string; /** Port number ポート番号 */ public readonly port: number; /** Address アドレス (Ex. 123.234.0.1:12345) */ public readonly address: string; constructor(ip: string, port: number) { this.ip = ip; this.port = port; this.address = `${ip}:${port}`; } } } /** W5500 management class W5500を管理するクラス */ export class W5500 implements ObnizPartsInterface { public static info(): ObnizPartsInfo { return { name: 'W5500', }; } public keys: string[]; public requiredKeys: string[]; public params: any; /** Instance of Obniz Obnizのインスタンス */ protected obniz!: Obniz; /** Instance of PeripheralSPI PeripheralSPIのインスタンス */ protected spi!: PeripheralSPI; /** Instance of reset pin リセットピンのインスタンス */ protected resetPin!: PeripheralIO; /** Instance of chip select pin チップセレクトピンのインスタンス */ protected csPin!: PeripheralIO; /** * Whether to communicate with a fixed length, forces true if no chip select pin is specified * * 固定長通信するかどうか、チップセレクトピンが指定されていない場合、強制的にtrue */ protected fdm = false; /** * Holds a handler that catches interrupts by message * * 割り込みをメッセージ別でキャッチするハンドラーを保持 */ protected interruptHandlers: { [key in W5500Parts.Interrupt]?: | ((ethernet: W5500) => Promise<void>) | ((ethernet: W5500, extra?: W5500Parts.DestInfo) => Promise<void>); } = {}; /** * Holds a handler that catches all interrupts * * 割り込みを全てキャッチするハンドラーを保持 */ protected allInterruptHandler?: ( ethernet: W5500, msg: W5500Parts.Interrupt, extra?: W5500Parts.DestInfo ) => Promise<void>; /** Array of socket instances ソケットのインスタンスの配列 */ protected socketList: W5500Socket[] = []; /** SPI status SPIのステータス */ protected spiStatus = false; /** * Do not always check transfer when writing * * 常に書き込み時に転送チェックを行わない */ protected forceNoCheckWrite = false; constructor() { this.keys = ['frequency', 'reset', 'mosi', 'miso', 'sclk', 'cs']; this.requiredKeys = []; } public wired(obniz: Obniz) { this.obniz = obniz; // W5500 may accept up to 26 Mhz. But it may fail on some devices. Reduce it when spi error occures. Increase it when no spi error occures and want to improve speed. this.params.frequency = this.params.frequency || 20 * 1000 * 1000; this.params.mosi = this.params.mosi || 23; this.params.miso = this.params.miso || 19; this.params.clk = this.params.clk || 18; this.params.drive = '3v'; this.params.mode = 'master'; this.spi = this.params.spi || this.obniz.getSpiWithConfig(this.params); this.spiStatus = true; this.resetPin = this.obniz.getIO(this.params.reset || 12); this.csPin = this.obniz.getIO(this.params.cs || 33); } /** * Initialize W5500 and write common settings * * W5500を初期化、共通設定の書き込み * * @param config W5500 config W5500の設定内容 * @return Write result 書き込み結果 */ public async initWait(config: W5500Parts.Config) { // Reset リセット await this.hardResetWait(); // Use fixed length data mode 固定長通信の使用 this.fdm = config.fdm === true; // SPI chip select SPIのセレクト this.csPin.drive('3v'); this.csPin.output(!this.fdm); // Mode setting モード設定 let result = await this.setModeWait(config); // Network initialization ネットワークの初期化 if (config.gatewayIP) { result = result && (await this.setGatewayWait(config.gatewayIP)); } if (config.subnetMask) { result = result && (await this.setSubnetMask(config.subnetMask)); } if (config.macAddress) { result = result && (await this.setMacAddressWait(config.macAddress)); } if (config.localIP) { result = result && (await this.setLocalIPWait(config.localIP)); } // Turn on all interrupt masks 割り込みマスクを全てオンに result = result && (await this.setInterruptMaskWaut(0xff)); // Other settings その他設定 if (config.retryTime) { result = result && (await this.setRetryTimeWait(config.retryTime)); } if (config.retryCount) { result = result && (await this.setRetryCountWait(config.retryCount)); } if (config.linkControlProtocolRequestTimer) { result = result && (await this.setPPPLinkControlProtocolRequestTimerWait( config.linkControlProtocolRequestTimer )); } if (config.linkControlProtocolMagicNumber) { result = result && (await this.setPPPLinkControlProtocolMagicNumberWait( config.linkControlProtocolMagicNumber )); } if (config.pppoeDestMACAddress) { result = result && (await this.setPPPoEMacAddressWait(config.pppoeDestMACAddress)); } if (config.pppoeSessionID) { result = result && (await this.setPPPoESessionIDWait(config.pppoeSessionID)); } if (config.pppoeMaxSegmentSize) { result = result && (await this.setPPPoEMaxSegmentSizeWait(config.pppoeMaxSegmentSize)); } if (config.phyConfig) { result = result && (await this.setPhysicalConfigWait(config.phyConfig)); } this.forceNoCheckWrite = config.forceNoCheckWrite === true; // Interrupt handlers 割り込みハンドラー設定 if (config.onIPConflictInterrupt) { this.setInterruptHandler('IPConflict', config.onIPConflictInterrupt); } if (config.onDestUnreachInterrupt) { this.setInterruptHandler('DestUnreach', config.onDestUnreachInterrupt); } if (config.onPPPoECloseInterrupt) { this.setInterruptHandler('PPPoEClose', config.onPPPoECloseInterrupt); } if (config.onMagicPacketInterrupt) { this.setInterruptHandler('MagicPacket', config.onMagicPacketInterrupt); } if (config.onAllInterrupt) { this.setAllInterruptHandler(config.onAllInterrupt); } return result; } /** * Terminates each socket and terminates SPI communication * * 各ソケットの終了処理をし、SPI通信を終了 */ public async finalizeWait() { for (const socket of this.socketList) { if (socket !== undefined) { await socket.finalizeWait(); } } this.spi.end(); this.spiStatus = false; } /** * Set a handler to catch a specific interrupt * * Run checkInterruptWait() regularly to actually catch * * 特定の割り込みをキャッチするハンドラーを設定 * * 実際にキャッチするにはcheckInterrupt()を定期的に実行 * * @param name Name of the interrupt to get 取得する割り込みの名前 (IPConflict | DestUnreach | PPPoEClose | MagicPacket) * @param handler Callback function, extra is only when name=DestUnreach * * コールバック関数、extraはname=DestUnreachのときのみ */ public setInterruptHandler( name: W5500Parts.Interrupt, handler: | ((ethernet: W5500) => Promise<void>) | ((ethernet: W5500, extra?: W5500Parts.DestInfo) => Promise<void>) ) { this.interruptHandlers[name] = handler; } /** * Set handler to catch all interrupts * * Run checkInterruptWait() regularly to actually catch * * 全ての割り込みをキャッチするハンドラーを設定 * * 実際にキャッチするにはcheckInterrupt()を定期的に実行 * * @param handler Callback function, name is the name of the interrupt received, extra is only when name=DestUnreach * * コールバック関数、nameには受け取った割り込み名が入ります、extraはname=DestUnreachのときのみ */ public setAllInterruptHandler( handler: ( ethernet: W5500, name: W5500Parts.Interrupt, extra?: W5500Parts.DestInfo ) => Promise<void> ) { this.allInterruptHandler = handler; } /** * Wait until the connection with the router is established * * ルーターとの接続が確立されるまで待機 * * @return Physical layer status 物理層のステータス */ public async waitLinkUpWait() { let phy; while (true) { phy = await this.getPhysicalStatusWait(); if (phy.link) { break; } await sleep(20); } return phy; } /** * Get an instance of W5500Socket, generate if necessary * * W5500Socketのインスタンスを取得、必要ならば生成 * * @param socketId Socket ID (0\~7) ソケットID (0\~7) * @return Instance of W5500Socket W5500Socketのインスタンス */ public getSocket(socketId: number) { if (socketId < 0 || socketId > 7) { throw new Error('Socket id must take a value between 0 and 7.'); } if (!this.socketList[socketId]) { this.socketList[socketId] = new W5500Socket(socketId, this); } return this.socketList[socketId]; } /** * Create an instance of W5500Socket in the frame of the unused socket * * 使っていないソケットの枠にW5500Socketのインスタンスを生成 * * @return Instance of W5500Socket W5500Socketのインスタンス */ public getNewSocket() { let id = 0; while (this.socketList[id] !== undefined) { id++; } if (id > 7) { return null; } else { return (this.socketList[id] = new W5500Socket(id, this)); } } /** * Whether SPI is available * * SPIが利用可能かどうか * * @return SPI status SPIのステータス */ public getSpiStatus() { return this.spiStatus; } /** * Reset W5500 in hardware * * W5500をハードウェア的にリセット */ public async hardResetWait() { this.resetPin.drive('3v'); this.resetPin.output(false); await sleep(10); // > 500ns this.resetPin.output(true); await sleep(100); } /** * Set mode モードを設定 * * @param config WakeOnLAN(WoL), PingBlock, PPPoE and ForceARP * @return Write result 書き込み結果 */ public setModeWait(config: W5500Parts.Config) { return this.numWriteWait( COMMON_MODE, BSB_COMMON, 0b00100000 * (config.wol === true ? 1 : 0) + 0b00010000 * (config.pingBlock === true ? 1 : 0) + 0b00001000 * (config.pppoe === true ? 1 : 0) + 0b00000010 * (config.forceArp === true ? 1 : 0) ); } /** * Set IPv4 address of default gateway * * デフォルトゲートウェイのIPv4アドレスを設定 * * @param ip IPv4 address IPv4アドレス * @return Write result 書き込み結果 */ public setGatewayWait(ip: string) { return this.ipWriteWait(COMMON_GATEWAY_ADDRESS, BSB_COMMON, ip); } /** * Set subnet mask サブネットマスクを設定 * * @param mask Subnet mask サブネットマスク * @return Write result 書き込み結果 */ public setSubnetMask(mask: string) { return this.ipWriteWait(COMMON_SOURCE_SUBNET_MASK, BSB_COMMON, mask); } /** * Set MAC address MACアドレスを設定 * * @param mac MAC address MACアドレス * @return Write result 書き込み結果 */ public setMacAddressWait(mac: string) { return this.macWriteWait(COMMON_SOURCE_HARDWARE_ADDRESS, BSB_COMMON, mac); } /** * Set local IPv4 address ローカルIPv4アドレスを設定 * * @param ip IPv4 address IPv4アドレス * @return Write result 書き込み結果 */ public setLocalIPWait(ip: string) { return this.ipWriteWait(COMMON_SOURCE_IP_ADDRESS, BSB_COMMON, ip); } /** * Check for interrupts (doesn't work properly with VDM) * * Also check socket interrupts * * If there is an interrupt, call the preset handler * * 割り込みをチェック(VDMの時、正常に動作しません) * * ソケットの割り込みもチェックします * * 割り込みがあった場合、事前に設定されたhandlerを呼び出します * * @param disableAllSocketCheck When it's true, do not call checkInterruptWait() for all sockets * * trueの時、全ソケットのcheckInterrupt()呼び出しを行いません * @return Then whether you can check for interrupts * * 次に割り込みをチェックできるかどうか */ public async checkInterruptWait(disableAllSocketCheck?: boolean) { if (!this.spiStatus) { return false; } const interrupt = await this.numReadWait(COMMON_INTERRUPT, BSB_COMMON); if (interrupt !== 0) { // リセット await this.numWriteWait(COMMON_INTERRUPT, BSB_COMMON, interrupt); } const msgList = Object.keys(W5500Parts.InterruptFlags).filter( (msg) => (interrupt & W5500Parts.InterruptFlags[msg as W5500Parts.Interrupt]) !== 0 ); const extra = msgList.indexOf('DestUnreach') >= 0 ? new W5500Parts.DestInfo( await this.getUnreachableIP(), await this.getUnreachablePort() ) : undefined; if (disableAllSocketCheck !== false) { for (const socket of this.socketList) { if (socket !== undefined && socket.getProtocol() !== null) { await socket.checkInterruptWait(); } } } for (const m in msgList) { const msg = msgList[m] as W5500Parts.Interrupt; // console.info(`Found Interrupt: ${msg}` + msg === "DestUnreach" ? ` address=${extra?.address}` : ""); const handler = this.interruptHandlers[msg]; if (handler !== undefined) { await handler(this, extra); } if (this.allInterruptHandler !== undefined) { await this.allInterruptHandler( this, msg, msg === 'DestUnreach' ? extra : undefined ); } } return this.spiStatus; } /** * Set interrupt mask 割り込みマスクを設定 * * @param mask Mask マスク * @return Write result 書き込み結果 */ public setInterruptMaskWaut(mask: number) { return this.numWriteWait(COMMON_INTERRUPT_MASK, BSB_COMMON, mask); } /** * Set retry interval (Initial value: 200ms) 再試行間隔を設定 (初期値: 200ms) * * @param time Retry interval (in 0.2ms increments) 再試行間隔 (0.2ms刻み) (0\~6553.5ms) * @return Write result 書き込み結果 */ public setRetryTimeWait(time: number) { return this.num2WriteWait(COMMON_RETRY_TIME, BSB_COMMON, time * 10); } /** * Set retry count (Initial value: 8 times) 再試行回数を設定 (初期値: 8回) * * @param count retry count 再試行回数 (0\~255) * @return Write result 書き込み結果 */ public setRetryCountWait(count: number) { return this.numWriteWait(COMMON_RETRY_COUNT, BSB_COMMON, count); } /** * Set time to send echo request for Link Control Protocol * * LinkControlプロトコルのechoリクエストを送っている時間を設定 * * @param time time (in 25ms increments) 時間 (25ms刻み) (0\~6375ms) * @return Write result 書き込み結果 */ public setPPPLinkControlProtocolRequestTimerWait(time: number) { return this.numWriteWait( COMMON_PPP_LCP_REQUEST_TIMER, BSB_COMMON, time / 25 ); } /** * Set 1 byte of the 4 bytes magic number of the Link Control protocol echo request * * LinkControlプロトコルのechoリクエストの4bytesマジックナンバーの1byteを設定 * * @param num Magic number マジックナンバー * @return Write result 書き込み結果 */ public setPPPLinkControlProtocolMagicNumberWait(num: number) { return this.numWriteWait(COMMON_PPP_LCP_MAGIC_NUMBER, BSB_COMMON, num); } /** * Set MAC address of PPPoE server PPPoEサーバーのMACアドレスを設定 * * @param mac MAC address MACアドレス * @return Write result 書き込み結果 */ public setPPPoEMacAddressWait(mac: string) { return this.macWriteWait( COMMON_PPP_DESTINATION_MAC_ADDRESS, BSB_COMMON, mac ); } /** * Set session ID of PPPoE server PPPoEサーバーのセッションIDを設定 * * @param id Session ID セッションID * @return Write result 書き込み結果 */ public setPPPoESessionIDWait(id: number) { return this.num2WriteWait( COMMON_PPP_SESSION_IDENTIFICATION, BSB_COMMON, id ); } /** * Set maximum receiving unit size of PPPoE PPPoEの最大受信ユニットサイズを設定 * * @param size Unit size ユニットサイズ * @return Write result 書き込み結果 */ public setPPPoEMaxSegmentSizeWait(size: number) { return this.num2WriteWait( COMMON_PPP_MAXIMUM_SEGMENT_SIZE, BSB_COMMON, size ); } /** * Get the IPv4 address when the destination could not be reached * * 宛先に到達できなかった時のIPv4アドレスを取得 * * @return IPv4 address IPv4アドレス */ public getUnreachableIP() { return this.ipReadWait(COMMON_UNREACHABLE_IP_ADDRESS, BSB_COMMON); } /** * Get the port number when the destination could not be reached * * 宛先に到達できなかった時のポート番号を取得 * * @return Port number ポート番号 */ public getUnreachablePort() { return this.num2ReadWait(COMMON_UNREACHABLE_PORT, BSB_COMMON); } /** * Get physical layer status 物理層のステータス取得 * * @return Physical layer status 物理層のステータス */ public async getPhysicalStatusWait(): Promise<W5500Parts.PhysicalLayerStatus> { const result = await this.numReadWait(COMMON_PHY_CONFIGURATION, BSB_COMMON); return { duplex: (result & 0b100) !== 0, speed: (result & 0b010) !== 0 ? 100 : 10, link: (result & 0b001) !== 0, }; } /** * Set physical layer config 物理層の設定 * * @param config Physical layer config 物理層の設定内容 * @return Write result 書き込み結果 */ public async setPhysicalConfigWait(config: W5500Parts.PhysicalLayerOptions) { if (config.reset) { await this.numWriteWait(COMMON_PHY_CONFIGURATION, BSB_COMMON, 0); await sleep(500); } let value = 0b11111000; if (config.autoNegotiation === false) { value &= 0b11011000; } // 1bit目を0に if (config.speed === 10) { value &= 0b11001000; } // 1,2bit目を0に if (config.duplex === false) { value &= 0b11110000; } // 3bit目を0に if (config.powerOff === true) { value = 0b11110000; } return await this.numWriteWait(COMMON_PHY_CONFIGURATION, BSB_COMMON, value); } /** * Get chip version チップバージョンの取得 * * @return Chip version チップバージョン */ public getVersion() { return this.numReadWait(COMMON_CHIP_VERSION, BSB_COMMON); } /** * Write after validating the IPv4 address of the character string * * 文字列のIPv4アドレスをバリデーションチェックしてから書き込み * * @param address Start address of write destination 書き込み先の先頭アドレス * @param bsb Block select bit ブロック選択ビット * @param ip IPv4 address IPv4アドレス * @return Write result 書き込み結果 * @hidden */ public ipWriteWait(address: number, bsb: number, ip: string) { return this.addressWriteWait( address, bsb, ip, 'IP Address', '123.234.0.1', '.', 4, 10 ); } /** * Write after validating the MAC address of the character string * * 文字列のMACアドレスをバリデーションチェックしてから書き込み * * @param address Start address of write destination 書き込み先の先頭アドレス * @param bsb Block select bit ブロック選択ビット * @param mac MAC address MACアドレス * @return Write result 書き込み結果 * @hidden */ public macWriteWait(address: number, bsb: number, mac: string) { return this.addressWriteWait( address, bsb, mac, 'MAC Address', '12:34:56:78:90:AB', ':', 6, 16 ); } /** * Writing large data * * Used when the length is larger than 4 in FDM * * Used when the length is greater than 1021 for VDM * * 大きいデータの書き込み * * FDMのとき、長さが4より大きいときに使用 * * VDMのとき、長さが1021より大きいときに使用 * * @param address Start address of write destination 書き込み先の先頭アドレス * @param bsb Block select bit ブロック選択ビット * @param data Raw byte data Raw byte data バイト列データ * @param noWait Do not use spi.writeWait() when writing data データ書き込み時、spi.writeWait()を使用しない * @return Write result 書き込み結果 * @hidden */ public async bigWriteWait( address: number, bsb: number, data: number[], noWait?: boolean ) { const maxLength = this.fdm ? 4 : 1021; // FDM(4) / VDM(1024-3) let result = true; for (let i = 0; i < data.length; i += maxLength) { const size = i + maxLength <= data.length ? maxLength : data.length - i; result = result && (await this.writeWait( address + i, bsb, data.slice(i, i + size), noWait )); } return result; } /** * Writing a value to the area for one address * * 1アドレス分の領域への値の書き込み * * @param address Start address of write destination 書き込み先の先頭アドレス * @param bsb Block select bit ブロック選択ビット * @param num Value 値 (0\~255) * @return Write result 書き込み結果 * @hidden */ public numWriteWait(address: number, bsb: number, num: number) { return this.writeWait(address, bsb, [num]); } /** * Writing a value to the area for two addresses * * 2アドレス分の領域への値の書き込み * * @param address Start address of write destination 書き込み先の先頭アドレス * @param bsb Block select bit ブロック選択ビット * @param num Value 値 (0\~65535) * @return Write result 書き込み結果 * @hidden */ public num2WriteWait(address: number, bsb: number, num: number) { return this.writeWait(address, bsb, [(num & 0xff00) >> 8, num & 0xff]); } /** * Read IPv4 address data IPv4アドレスデータの読み込み * * @param address Start address of read destination 読み込み先の先頭アドレス * @param bsb Block select bit ブロック選択ビット * @return IPv4 address IPv4アドレス * @hidden */ public async ipReadWait(address: number, bsb: number) { return (await this.readWait(address, bsb, 4)).join('.'); } /** * Reading large data * * Used when the length is larger than 4 in FDM * * Used when the length is greater than 1021 for VDM * * 大きいデータの読み込み * * FDMのとき、長さが4より大きいときに使用 * * VDMのとき、長さが1021より大きいときに使用 * * @param address Start address of read destination 読み込み先の先頭アドレス * @param bsb Block select bit ブロック選択ビット * @param length Data length (byte length) データの長さ (バイト長) * @return Read data 読み込みデータ * @hidden */ public async bigReadWait(address: number, bsb: number, length: number) { const maxLength = this.fdm ? 4 : 1021; // FDM(4) / VDM(1024-3) let data: number[] = []; for (let i = 0; i < length; i += maxLength) { const size = i + maxLength <= length ? maxLength : length - i; data = data.concat(await this.readWait(address + i, bsb, size)); } return data; } /** * Reading values from the area for one address * * 1アドレス分の領域からの値の読み込み * * @param address Start address of read destination 読み込み先の先頭アドレス * @param bsb Block select bit ブロック選択ビット * @return Value 値 (0\~255) * @hidden */ public async numReadWait(address: number, bsb: number) { const result = await this.readWait(address, bsb, 1); return result[0]; } /** * Reading values from the area for two addresses * * 2アドレス分の領域からの値の読み込み * * @param address Start address of read destination 読み込み先の先頭アドレス * @param bsb Block select bit ブロック選択ビット * @return Value 値 (0\~65535) * @hidden */ public async num2ReadWait(address: number, bsb: number) { const result = await this.readWait(address, bsb, 2); return (result[0] << 8) + result[1]; } /** * Validate and write the address based on the definition * * アドレスを定義に基づいてバリデーションチェックして書き込み * * @param address Start address of write destination 書き込み先の先頭アドレス * @param bsb Block select bit ブロック選択ビット * @param val String of the address to write 書き込むアドレスの文字列 * @param name Type name of the address アドレスの種類名 * @param example Sample string of the address, for errors アドレスのサンプル文字列、エラー用 * @param splitVal Address split character アドレスの分割文字 * @param length Length when the address is divided by the split character アドレスを分割文字で分割した時の長さ * @param radix Description format of numbers in the address (N-ary) アドレス内の数字の記述形式 (N進数) * @hidden */ private async addressWriteWait( address: number, bsb: number, val: string, name: string, example: string, splitVal: string, length: number, radix: number ) { if (typeof val !== 'string') { throw new Error(`Given ${name} must be string.`); } const valList = val.split(splitVal).map((addr) => parseInt(addr, radix)); if (valList.filter((addr) => typeof addr === 'number').length !== length) { throw new Error(`${name} format must be '${example}'.`); } if (length > 4 && this.fdm) { return await this.bigWriteWait(address, bsb, valList); } else { return await this.writeWait(address, bsb, valList); } // const func = length > 4 && this.fdm ? this.bigWriteWait : this.writeWait; // return func(address, bsb, valList); } /** * Writing normal data * * For FDM, the length is up to 4 * * For VDM, the length is up to 1021 * * 通常データの書き込み * * FDMのとき、長さは4まで * * VDMのとき、長さは1021まで * * @param address Start address of write destination 書き込み先の先頭アドレス * @param bsb Block select bit ブロック選択ビット * @param data Raw byte data バイト列データ * @param noWait Do not use spi.writeWait() when writing data データ書き込み時、spi.writeWait()を使用しない * @return Write result 書き込み結果 * @hidden */ private async writeWait( address: number, bsb: number, data: number[], noWait?: boolean ) { if (!Array.isArray(data)) { throw new Error('Given data must be array.'); } if (data.length === 3 && this.fdm) { data[3] = 0; } if (data.length === 0) { throw new Error('Given data is empty.'); } if (data.length > 4 && this.fdm) { throw new Error('Given data length must be 1, 2 or 4.'); } if (data.length > 1021 && !this.fdm) { throw new Error('Given data length must be 1021 or less.'); } if ( data.filter((addr) => 0x00 <= addr && addr <= 0xff).length !== data.length ) { throw new Error( 'Given data field must take a value between 0(0x00) and 255(0xFF).' ); } if (this.forceNoCheckWrite === true && noWait === undefined) { noWait = true; } const result = await this.sendWait(address, bsb, 'Write', data, noWait); if (typeof result === 'object') { throw new Error('Unexpected Result'); } else { return result; } } /** * Reading normal data * * 通常データの読み込み * * @param address Start address of read destination 読み込み先の先頭アドレス * @param bsb Block select bit ブロック選択ビット * @param length Data length (byte length) データの長さ (バイト長) * @return Read data 読み込みデータ * @hidden */ private async readWait(address: number, bsb: number, length: number) { const result = await this.sendWait( address, bsb, 'Read', Array(length).fill(0) ); if (typeof result === 'boolean') { throw new Error('Unexpected Result'); } else { return result; } } /** * 読み書き共通のメソッド、返却されたデータを検証 * * Common read / write method, verify returned data * * @param address Start address of operation destination 操作先の先頭アドレス (0x0000\~0xFFFF) * @param bsb Block select bit ブロック選択ビット (0b00000\~0b11111) * @param mode Read or write 読み込みか書き込みか (Read|Write) * @param data Raw byte data バイト列データ (0xFF\*1\~4(FDM), \*1\~1021(VDM)) * @param noWait Do not use spi.writeWait for communication 通信にspi.writeWaitを使用しない * @return Write: Write result Read: Read data * * 書込: 書き込み結果 読込: 読み込みデータ * @hidden */ private async sendWait( address: number, bsb: number, mode: SendMode, data: number[], noWait?: boolean ) { const write = [ (address & 0xff00) >> 8, address & 0x00ff, (bsb << 3) + (mode === 'Write' ? 0b0100 : 0b0000) + (this.fdm ? (data.length < 4 ? data.length : 0b11) : 0), ...data, ]; if (!this.fdm && this.csPin) { this.csPin.output(true); this.csPin.output(false); } const result = noWait === true ? this.spi.write(write) : await this.spi.writeWait(write); if (!this.fdm && this.csPin) { this.csPin.output(true); this.csPin.output(false); } if (typeof result === 'undefined') { return true; } if (result[0] === 1 && result[1] === 2 && result[2] === 3) { return mode === 'Write' ? true : result.slice(3); } else { throw new Error( `${mode} Error\n address: 0x${( '0000' + address.toString(16).toUpperCase() ).slice(-4)} bsb: ${bsb}\n send: 0x${byteString( write )}\n receive: 0x${byteString(result)}\n` ); } } } /** W5500 socket definitions and constants W5500のソケットの定義や定数 */ export namespace W5500SocketParts { /** Socket config ソケットの設定内容 */ export interface Config { /** Protocol to use 使用プロトコル (TCPClient/TCPServer/UDP/null) */ protocol: Protocol; /** * Use multicast (UDP Only) (Set Before Open Command) * * マルチキャストの使用(UDPのみ)(Openコマンドの前で設定) */ multicast?: boolean; /** * Do not receive broadcast packets (UDP only) * * ブロードキャストされたパケットを受信しない(UDPのみ) */ broardcastBlock?: boolean; /** * Send an ACK immediately when data is received (TCP only) * * データを受信したときにACKをすぐに送信する(TCPのみ) */ noDelayACK?: boolean; /** * Use IGMPv1 for multicast (UDP only) * * マルチキャストでIGMPv1を使う(UDPのみ) */ multicastVer1?: boolean; /** * Do not receive unicast packets (UDP only) * * ユニキャストされたパケットを受信しない(UDPのみ) */ unicastBlock?: boolean; /** Source port number 接続元ポート番号 */ sourcePort?: number; /** Connection destination IPv4 address 接続先IPv4アドレス */ destIP?: string; /** Connection destination port number 接続先ポート番号 */ destPort?: number; /** Maximum segment size (TCP only) 最大セグメントサイズ (TCPのみ) (0\~65535) */ maxSegmentSize?: number; /** IP service type IPサービスタイプ (1byte) */ ipType?: number; /** TTL (0\~65535) */ ttl?: number; /** * Receive buffer size (KB) only to the power of 2, up to 16 * * 受信バッファサイズ(KB) 2の累乗のみ、16まで */ rxBufferSize?: BufferSize; /** * Send buffer size (KB) only to the power of 2, up to 16 * * 送信バッファサイズ(KB) 2の累乗のみ、16まで */ txBufferSize?: BufferSize; /** IP header fragment IPヘッダーのフラグメント (0x0000\~0xFFFF) */ ipFragment?: number; /** * keep-alive transmission interval (sec) (TCP only) (0\~1275) * * keep-alive 送信間隔(秒)(TCPのみ)(0\~1275) */ keepAliveTimer?: number; /** * Treat received data as string (UTF-8) * * 受信データを文字列(UTF-8)として扱う */ stringMode?: boolean; /** Event handler for interrupt "SendOK" 割り込み「SendOK」のイベントハンドラー */ onSendOKInterrupt?: (socket: W5500Socket) => Promise<void>; /** Event handler for interrupt "Timeout" 割り込み「Timeout」のイベントハンドラー */ onTimeoutInterrupt?: (socket: W5500Socket) => Promise<void>; /** Event handler for interrupt "ReceiveData" 割り込み「ReceiveData」のイベントハンドラー */ onReceiveDataInterrupt?: ( socket: W5500Socket, extra?: number[] | string | W5500Parts.DestInfo ) => Promise<void>; /** Event handler for interrupt "Disconnect" 割り込み「Disconnect」のイベントハンドラー */ onDisconnectInterrupt?: (socket: W5500Socket) => Promise<void>; /** Event handler for interrupt "ConnectSuccess" 割り込み「ConnectSuccess」のイベントハンドラー */ onConnectSuccessInterrupt?: ( socket: W5500Socket, extra?: number[] | string | W5500Parts.DestInfo ) => Promise<void>; /** Event handler for all interrupts 全ての割り込みのイベントハンドラー */ onAllInterrupt?: ( socket: W5500Socket, name: W5500SocketParts.Interrupt, extra?: number[] | string | W5500Parts.DestInfo ) => Promise<void>; } /** Socket available protocol ソケットの使用可能プロトコル */ export type Protocol = 'TCPClient' | 'TCPServer' | 'UDP' | null; /** Buffer size バッファサイズ */ export type BufferSize = 0 | 1 | 2 | 4 | 8 | 16; /** Socket available commands ソケットの使用可能コマンド */ export type Command = | 'Open' | 'Listen' | 'Connect' | 'Disconnect' | 'Close' | 'Send' | 'SendMAC' | 'SendKeep' | 'Receive'; /** * Value corresponding to socket command * * ソケットのコマンドに対応する値 */ export const CommandCodes: { [key in Command]: number } = { Open: 0x01, Listen: 0x02, Connect: 0x04, Disconnect: 0x08, Close: 0x10, Send: 0x20, SendMAC: 0x21, SendKeep: 0x22, Receive: 0x40, } as const; /** Socket status ソケットのステータス */ export type Status = | 'Closed' | 'Init' | 'Listen' | 'SynSent' | 'SynReceive' | 'Established' | 'FinWait' | 'Closing' | 'TimeWait' | 'CloseWait' | 'LastACK' | 'UDP' | 'MACRAW'; /** * Value corresponding to socket status * * ソケットのステータスに対応する値 */ export const StatusCodes: { [key in Status]: number } = { Closed: 0x00, Init: 0x13, Listen: 0x14, SynSent: 0x15, // Temporary 一時的 SynReceive: 0x16, // Temporary 一時的 Established: 0x17, FinWait: 0x18, // Temporary 一時的 Closing: 0x1a, // Temporary 一時的 TimeWait: 0x1b, // Temporary 一時的 CloseWait: 0x1c, LastACK: 0x1d, UDP: 0x22, MACRAW: 0x32, } as const; /** Socket interrupt ソケットの割り込み */ export type Interrupt = | 'SendOK' | 'Timeout' | 'ReceiveData' | 'Disconnect' | 'ConnectSuccess'; /** * Flags corresponding to socket interrupts * * ソケットの割り込みに対応するフラグ */ export const InterruptFlags: { [key in Interrupt]: number } = { SendOK: 0b10000, Timeout: 0b01000, ReceiveData: 0b00100, Disconnect: 0b00010, ConnectSuccess: 0b00001, } as const; } /** * Class that performs and manages socket communication * * ソケット通信を行い管理するクラス */ export class W5500Socket { /** Socket ID ソケットID */ public readonly id: number; /** * Treat received data as string (UTF-8) * * 受信データを文字列(UTF-8)として扱う */ public stringMode = false; /** Current protocol 現在のプロトコル */ protected protocol: W5500SocketParts.Protocol = null; /** Instance of W5500 W5500のインスタンス */ protected ethernet: W5500; /** * Holds a handler that catches interrupts by message * * 割り込みをメッセージ別でキャッチするハンドラーを保持 */ protected interruptHandlers: { [key in W5500SocketParts.Interrupt]?: | ((socket: W5500Socket) => Promise<void>) | (( socket: W5500Socket, extra?: number[] | string | W5500Parts.DestInfo ) => Promise<void>); } = {}; /** * Holds a handler that catches all interrupts * * 割り込みを全てキャッチするハンドラーを保持 */ protected allInterruptHandler?: ( socket: W5500Socket, msg: W5500SocketParts.Interrupt, extra?: number[] | string | W5500Parts.DestInfo ) => Promise<void>; /** Hold data read address データ読み込みのアドレスを保持 */ protected rxReadDataPointer = 0; constructor(id: number, ethernet: W5500) { this.id = id; this.ethernet = ethernet; } /** * Write the socket settings and open the socket (Connect / Listen is also executed for TCP) * * ソケット設定の書き込みをし、ソケットをOpenに(TCPの時はConnect/Listenも実行) * * @param config Socket config ソケットの設定内容 * @return Write result 書き込み結果 */ public async initWait(config: W5500SocketParts.Config) { // モード設定 let result = await this.setModeWait(config); // 基本設定 if (config.sourcePort) { result = result && (await this.setSourcePortWait(config.sourcePort)); } if (config.destIP) { result = result && (await this.setDestIPWait(config.destIP)); } if (config.destPort) { result = result && (await this.setDestPortWait(config.destPort)); } if (config.ipType) { result = result && (await this.setIPTypeOfServiceWait(config.ipType)); } if (config.ttl) { result = result && (await this.setTTLWait(config.ttl)); } if (config.rxBufferSize) { result = result && (await this.setRXBufferSizeWait(config.rxBufferSize)); } if (config.txBufferSize) { result = result && (await this.setTXBufferSizeWait(config.txBufferSize)); } // Open socket ソケットのオープン result = result && (await this.sendCommandWait('Open')); if (this.protocol === 'TCPClient') { result = result && (await this.sendCommandWait('Connect')); } if (this.protocol === 'TCPServer') { result = result && (await this.sendCommandWait('Listen')); } // Remember the value of rxReadDataPointer in advance // 事前にrxReadDataPointerの値を記憶 this.rxReadDataPointer = await this.getRXReadDataPointerWait(); // Interrupt handler settings 割り込みハンドラー設定 if (config.onSendOKInterrupt) { this.setInterruptHandler('SendOK', config.onSendOKInterrupt); } if (config.onTimeoutInterrupt) { this.setInterruptHandler('Timeout', config.onTimeoutInterrupt); } if (config.onReceiveDataInterrupt) { this.setInterruptHandler('ReceiveData', config.onReceiveDataInterrupt); } if (config.onDisconnectInterrupt) { this.setInterruptHandler('Disconnect', config.onDisconnectInterrupt); } if (config.onConnectSuccessInterrupt) { this.setInterruptHandler( 'ConnectSuccess', config.onConnectSuccessInterrupt ); } if (config.onAllInterrupt) { this.setAllInterruptHandler(config.onAllInterrupt); } return result; } /** * Socket termination process ソケットの終了処理 */ public async finalizeWait() { switch (this.protocol) { case 'TCPClient': await this.sendCommandWait('Disconnect'); while ((await this.getStatusWait()) !== 'Closed'); break; case 'TCPServer': await this.sendCommandWait('Disconnect'); await this.sendCommandWait('Close'); break; case 'UDP': await this.sendCommandWait('Close'); break; } this.protocol = null; } /** * Send data データを送信 * * @param data Raw byte data or string to send 送信するバイトデータまたは文字列 * @return Write result 書き込み結果 */ public sendDataWait(data: number[] | string) { return this.sendDataBaseWait(data); } /** * Send data, no write check データを送信、書き込みチェックなし * * @param data Raw byte data or string to send 送信するバイトデータまたは文字列 * @return Write result 書き込み結果 */ public sendDataFastWait(data: number[] | string) { return this.sendDataBaseWait(data, true); } /** * Read the received data 受信されたデータを読取 * * @return Raw byte data or string to receive 受信データまたは文字列 */ public async receiveDataWait() { const rxRecieveSize = await this.getRXReceiveSizeWait(); // const rxReadDataPointer = await this.getRXReadDataPointerWait(); const data = await this.ethernet.bigReadWait( this.rxReadDataPointer, BSB_SOCKET_RX_BUFFER(this.id), rxRecieveSize ); this.rxReadDataPointer += rxRecieveSize; await this.setRXReadDataPointerWait(this.rxReadDataPointer); await this.sendCommandWait('Receive'); return this.stringMode ? new TextDecoder().decode(Uint8Array.from(data)) : data; } /** * Set a handler to catch a specific interrupt * * Run checkInterruptWait() regularly to actually catch * * 特定の割り込みをキャッチするハンドラーを設定 * * 実際にキャッチするにはcheckInterrupt()を定期的に実行 * * @param name The name of the interrupt to get 取得する割り込みの名前 (SendOK | Timeout | ReceiveData | Disconnect | ConnectSuccess) * @param handler Callback function, extra is only when name=ReceiveData and when name=ConnectSuccess and protocol=TCPServer * * コールバック関数、extraはname=ReceiveDataの時とname=ConnectSuccessかつprotocol=TCPServerの時のみ */ public setInterruptHandler( name: W5500SocketParts.Interrupt, handler: | ((socket: W5500Socket) => Promise<void>) | (( socket: W5500Socket, extra?: number[] | string | W5500Parts.DestInfo ) => Promise<void>) ) { return (this.interruptHandlers[name] = handler); } /** * Set a handler to catch all interrupts * * Run checkInterruptWait() regularly to actually catch * * 全ての割り込みをキャッチするハンドラーを設定 * * 実際にキャッチするにはcheckInterrupt()を定期的に実行 * * @param handler Callback function, name is the type of interrupt, extra is only when name=ReceiveData and when name=ConnectSuccess and protocol=TCPServer * * コールバック関数、nameは割り込みの種類、extraはname=ReceiveDataの時とname=ConnectSuccessかつprotocol=TCPServerの時のみ */ public setAllInterruptHandler( handler: ( socket: W5500Socket, name: W5500SocketParts.Interrupt, extra?: number[] | string | W5500Parts.DestInfo ) => Promise<void> ) { return (this.allInterruptHandler = handler); } /** * Get the current protocol 現在のプロトコルを取得 * * @return Protocol プロトコル */ public getProtocol() { return this.protocol; } /** * Set mode モードを設定 * * @param config Multicast, BroardcastBlock, NoDelayACK, MulticastVer1, UnicastBlock and Protocol * @return Write result 書き込み結果 */ public setModeWait(config: W5500SocketParts.Config) { this.protocol = config.protocol; this.stringMode = config.stringMode || false; return this.ethernet.numWriteWait( SOCKET_MODE, BSB_SOCKET_REGISTER(this.id), config.protocol === null ? 0 : 0b10000000 * (config.multicast === true && config.protocol === 'UDP' ? 1 : 0) + 0b01000000 * (config.broardcastBlock === true && config.protocol === 'UDP' ? 1 : 0) + 0b00100000 * (config.noDelayACK === true && config.protocol.indexOf('TCP') >= 0 ? 1 : 0) + 0b00100000 * (config.multicastVer1 === true && config.protocol === 'UDP' ? 1 : 0) + 0b00010000 * (config.unicastBlock === true && config.protocol === 'UDP' ? 1 : 0) + 0b00000001 * (config.protocol.indexOf('TCP') >= 0 ? 1 : 0) + 0b00000010 * (config.protocol === 'UDP' ? 1 : 0) ); } /** * Send command コマンドを送信 * * @param command Command コマンド * @return Write result 書き込み結果 */ public async sendCommandWait(command: W5500SocketParts.Command) { const code = W5500SocketParts.CommandCodes[command]; if (!code) { throw new Error(`Unknown Command '${command}'.`); } if (this.protocol === null) { throw new Error('Must set Socket Mode before send the command.'); } if (this.protocol.indexOf('TCP') >= 0 && 0x20 < code && code < 0x30) { throw new Error(`'${command}' command is only available in UDP mode.`); } if (this.protocol === 'UDP' && 0x01 < code && code < 0x10) { throw new Error(`'${command}' command is only available in TCP mode.`); } return await this.ethernet.numWriteWait( SOCKET_COMMAND, BSB_SOCKET_REGISTER(this.id), code ); } /** * Check for interrupts * * If there is an interrupt, call the preset handler * * 割り込みをチェック * * 割り込みがあった場合、事前に設定されたhandlerを呼び出します * * @return Then whether you can check for interrupts * * 次に割り込みをチェックできるかどうか */ public async checkInterruptWait() { if (!this.ethernet.getSpiStatus()) { return; } const interrupt = await this.ethernet.numReadWait( SOCKET_INTERRUPT, BSB_SOCKET_REGISTER(this.id) ); if (interrupt === 0) { return this.protocol !== null; } else { await this.ethernet.numWriteWait( SOCKET_INTERRUPT, BSB_SOCKET_REGISTER(this.id), interrupt ); } // リセット const msgList = Object.keys(W5500SocketParts.InterruptFlags).filter( (msg) => (interrupt & W5500SocketParts.InterruptFlags[ msg as W5500SocketParts.Interrupt ]) !== 0 ); for (const m in msgList) { const msg = msgList[m] as W5500SocketParts.Interrupt; const handler = this.interruptHandlers[msg]; if (msg === 'Timeout') { this.protocol = null; } console.info(`Found Interrupt on Socket ${this.id}: ${msg}\n`); if (handler === undefined && this.allInterruptHandler === undefined) { continue; } let extra; if (msg === 'ReceiveData') { extra = await this.receiveDataWait(); } if (msg === 'ConnectSuccess' && this.protocol === 'TCPServer') { extra = new W5500Parts.DestInfo( await this.getDestIPWait(), await this.getDestPortWait() ); } if (handler !== undefined) { await handler(this, extra); } if (this.allInterruptHandler !== undefined) { await this.allInterruptHandler(this, msg, extra); } return true; } return this.protocol !== null && this.ethernet.getSpiStatus(); } /** * Get Status ステータスを取得 * * @return Status ステータス */ public async getStatusWait(): Promise<W5500SocketParts.Status | 'UNKNOWN'> { const status = await this.ethernet.numReadWait( SOCKET_STATUS, BSB_SOCKET_REGISTER(this.id) ); const index = Object.values(W5500SocketParts.StatusCodes).indexOf(status); return index < 0 ? 'UNKNOWN' : (Object.keys(W5500SocketParts.StatusCodes)[ index ] as W5500SocketParts.Status); } /** * Set the connection source port 接続元ポートを設定 * * @param port Port number ポート番号 * @return Write result 書き込み結果 */ public setSourcePortWait(port: number) { return this.ethernet.num2WriteWait( SOCKET_SOURCE_PORT, BSB_SOCKET_REGISTER(this.id), port ); } /** * Set the MAC address of the connection destination (only if required by UDP) * * 接続先のMACアドレスを設定(UDPで必要な場合のみ) * * @param mac MAC address MACアドレス * @return Write result 書き込み結果 */ public setDestMacAddressWait(mac: string) { return this.ethernet.macWriteWait( SOCKET_DESTINATION_HARDWARE_ADDRESS, BSB_SOCKET_REGISTER(this.id), mac ); } /** * Set the IPv4 address of the connection destination * * 接続先のIPv4アドレスを設定 * * @param ip IPv4 address IPv4アドレス * @return Write result 書き込み結果 */ public setDestIPWait(ip: string) { return this.ethernet.ipWriteWait( SOCKET_DESTINATION_IP_ADDRESS, BSB_SOCKET_REGISTER(this.id), ip ); } /** * Get the IPv4 address of the connection source (only for TCP server) * * 接続元のIPv4アドレスを取得(TCPサーバーのときのみ) * * @return IPv4 address IPv4アドレス */ public getDestIPWait() { return this.ethernet.ipReadWait( SOCKET_DESTINATION_IP_ADDRESS, BSB_SOCKET_REGISTER(this.id) ); } /** * Set the port number of the connection destination * * 接続先のポート番号を設定 * * @param port Port number ポート番号 * @return Write result 書き込み結果 */ public setDestPortWait(port: number) { return this.ethernet.num2WriteWait( SOCKET_DESTINATION_PORT, BSB_SOCKET_REGISTER(this.id), port ); } /** * Get the port number of the connection source (only for TCP server) * * 接続元のポート番号を取得(TCPサーバーのときのみ) * * @return Port number ポート番号 */ public getDestPortWait() { return this.ethernet.num2ReadWait( SOCKET_DESTINATION_PORT, BSB_SOCKET_REGISTER(this.id) ); } /** * Set maximum segment size (only if required by TCP) * * 最大セグメントサイズを設定(TCPで必要な場合のみ) * * @param size 最大セグメントサイズ * @return Write result 書き込み結果 */ public setMaxSegmentSizeWait(size: number) { return this.ethernet.num2WriteWait( SOCKET_MAX_SEGMENT_SIZE, BSB_SOCKET_REGISTER(this.id), size ); } /** * Set IP service type IPサービスタイプを設定 * * @param type IP service type IPサービスタイプ (1byte) * @return Write result 書き込み結果 */ public setIPTypeOfServiceWait(type: number) { return this.ethernet.numWriteWait( SOCKET_IP_TYPE_OF_SERVICE, BSB_SOCKET_REGISTER(this.id), type ); } /** * Set TTL TTLを設定 * * @param ttl TTL (0\~65535) * @return Write result 書き込み結果 */ public setTTLWait(ttl: number) { return this.ethernet.numWriteWait( SOCKET_TTL, BSB_SOCKET_REGISTER(this.id), ttl ); } /** * Set buffer size バッファサイズを設定 * * @param size Buffer size バッファサイズ(KB) * @param address Start address of write destination 書き込み先の先頭アドレス * @return Write result 書き込み結果 * @hidden */ public setBufferSizeWait(size: W5500SocketParts.BufferSize, address: number) { if ([0, 1, 2, 4, 8, 16].indexOf(size) < 0) { throw new Error('Given buffer size must be 0, 1, 2, 4, 8 or 16.'); } return this.ethernet.numWriteWait( address, BSB_SOCKET_REGISTER(this.id), size ); } /** * Set receive buffer size 受信バッファサイズを設定 * * @param size Buffer size (KB) only to the power of 2, up to 16 * * バッファサイズ(KB) 2の累乗のみ、16まで * @return Write result 書き込み結果 */ public setRXBufferSizeWait(size: W5500SocketParts.BufferSize) { return this.setBufferSizeWait(size, SOCKET_RX_BUFFER_SIZE); } /** * Set send buffer size 送信バッファサイズを設定 * * @param size Buffer size (KB) only to the power of 2, up to 16 * * バッファサイズ(KB) 2の累乗のみ、16まで * @return Write result 書き込み結果 */ public setTXBufferSizeWait(size: W5500SocketParts.BufferSize) { return this.setBufferSizeWait(size, SOCKET_TX_BUFFER_SIZE); } /** * Get free size of send buffer 送信バッファの空きサイズを取得 * * @return Free size 空きサイズ */ public getTXFreeSizeWait() { return this.ethernet.num2ReadWait( SOCKET_TX_FREE_SIZE, BSB_SOCKET_REGISTER(this.id) ); } /** * Get the write start address of the send buffer * * 送信バッファの書き込み開始アドレスを取得 * * @return Address アドレス */ public getTXReadPointerWait() { return this.ethernet.num2ReadWait( SOCKET_TX_READ_POINTER, BSB_SOCKET_REGISTER(this.id) ); } /** * Set the next write start address of the send buffer * * 送信バッファの次の書き込み開始アドレスを設定 * * @param pointer Address アドレス * @return Write result 書き込み結果 */ public setTXWritePointerWait(pointer: number) { return this.ethernet.num2WriteWait( SOCKET_TX_WRITE_POINTER, BSB_SOCKET_REGISTER(this.id), pointer ); } /** * Get the length of received data 受信データの長さを取得 * * @return Length 長さ */ public getRXReceiveSizeWait() { return this.ethernet.num2ReadWait( SOCKET_RX_RECEIVE_SIZE, BSB_SOCKET_REGISTER(this.id) ); } /** * Get the read start address of the receive buffer * * 受信バッファの読み込み開始アドレスを取得 * * @return Address アドレス */ public getRXReadDataPointerWait() { return this.ethernet.num2ReadWait( SOCLET_RX_READ_DATA_POINTER, BSB_SOCKET_REGISTER(this.id) ); } /** * Set the next read start address of the receive buffer * * 受信バッファの次の読み込み開始アドレスを設定 * * @param pointer Address アドレス * @return Write result 書き込み結果 */ public setRXReadDataPointerWait(pointer: number) { return this.ethernet.num2WriteWait( SOCLET_RX_READ_DATA_POINTER, BSB_SOCKET_REGISTER(this.id), pointer ); } /** * Get the write start address of the receive buffer * * 受信バッファの書き込み開始アドレスを取得 * * @return Address アドレス */ public getRXWritePointerWait() { return this.ethernet.num2ReadWait( SOCKET_RX_WRITE_POINTER, BSB_SOCKET_REGISTER(this.id) ); } /** * Set IP header fragment IPヘッダーのフラグメントを設定 * * @param fragment IP header fragment IPヘッダーのフラグメント (0x0000\~0xFFFF) * @return Write result 書き込み結果 */ public setFragmentWait(fragment: number) { return this.ethernet.num2WriteWait( SOCKET_FRAGMENT, BSB_SOCKET_REGISTER(this.id), fragment ); } /** * Set keep-alive transmission interval (only if TCP requires) * * keep-aliveの送信間隔を設定(TCPで必要な場合のみ) * * @param time keep-alive transmission interval (sec) (0\~1275) * * keep-alive 送信間隔(秒)(0\~1275) * @return Write result 書き込み結果 */ public setKeepAliveTimerWait(time: number) { return this.ethernet.numWriteWait( SOCKET_KEEP_ALIVE_TIMER, BSB_SOCKET_REGISTER(this.id), time / 5 ); } /** * Send data データを送信 * * @param data Raw byte data to send or string 送信するバイトデータまたは文字列 * @param noWait Do not use spi.writeWait() when writing data * * データ書き込み時、spi.writeWait()を使用しない * @hidden */ protected async sendDataBaseWait(data: number[] | string, noWait?: boolean) { const d = typeof data === 'string' ? Array.from(new TextEncoder().encode(data)) : data; const txReadPointer = await this.getTXReadPointerWait(); const result = await this.ethernet.bigWriteWait( txReadPointer, BSB_SOCKET_TX_BUFFER(this.id), d, noWait ); await this.setTXWritePointerWait(txReadPointer + d.length); await this.sendCommandWait('Send'); return result; } } export default W5500;
the_stack
import { EDGE_MAX_VALUE, PACKING_LOGIC, IOption } from "./maxrects-packer"; import { Rectangle, IRectangle } from "./geom/Rectangle"; import { Bin } from "./abstract-bin"; export class MaxRectsBin<T extends IRectangle = Rectangle> extends Bin<T> { public width: number; public height: number; public freeRects: Rectangle[] = []; public rects: T[] = []; private verticalExpand: boolean = false; private stage: Rectangle; private border: number; public options: IOption = { smart: true, pot: true, square: true, allowRotation: false, tag: false, exclusiveTag: true, border: 0, logic: PACKING_LOGIC.MAX_EDGE } constructor( public maxWidth: number = EDGE_MAX_VALUE, public maxHeight: number = EDGE_MAX_VALUE, public padding: number = 0, options: IOption = {} ) { super(); this.options = { ...this.options, ...options }; this.width = this.options.smart ? 0 : maxWidth; this.height = this.options.smart ? 0 : maxHeight; this.border = this.options.border ? this.options.border : 0; this.freeRects.push(new Rectangle( this.maxWidth + this.padding - this.border * 2, this.maxHeight + this.padding - this.border * 2, this.border, this.border)); this.stage = new Rectangle(this.width, this.height); } public add (rect: T): T | undefined; public add (width: number, height: number, data: any): T | undefined; public add (...args: any[]): any { let data: any; let rect: IRectangle; if (args.length === 1) { if (typeof args[0] !== 'object') throw new Error("MacrectsBin.add(): Wrong parameters"); rect = args[0] as T; // Check if rect.tag match bin.tag, if bin.tag not defined, it will accept any rect let tag = (rect.data && rect.data.tag) ? rect.data.tag : rect.tag ? rect.tag : undefined; if (this.options.tag && this.options.exclusiveTag && this.tag !== tag) return undefined; } else { data = args.length > 2 ? args[2] : null; // Check if data.tag match bin.tag, if bin.tag not defined, it will accept any rect if (this.options.tag && this.options.exclusiveTag) { if (data && this.tag !== data.tag) return undefined; if (!data && this.tag) return undefined; } rect = new Rectangle(args[0], args[1]); rect.data = data; rect.setDirty(false); } const result = this.place(rect); if (result) this.rects.push(result); return result; } public repack (): T[] | undefined { let unpacked: T[] = []; this.reset(); // re-sort rects from big to small this.rects.sort((a, b) => { const result = Math.max(b.width, b.height) - Math.max(a.width, a.height); if (result === 0 && a.hash && b.hash) { return a.hash > b.hash ? -1 : 1; } else return result; }); for (let rect of this.rects) { if (!this.place(rect)) { unpacked.push(rect); } } for (let rect of unpacked) this.rects.splice(this.rects.indexOf(rect), 1); return unpacked.length > 0 ? unpacked : undefined; } public reset (deepReset: boolean = false, resetOption: boolean = false): void { if (deepReset) { if (this.data) delete this.data; if (this.tag) delete this.tag; this.rects = []; if (resetOption) { this.options = { smart: true, pot: true, square: true, allowRotation: false, tag: false, border: 0 }; } } this.width = this.options.smart ? 0 : this.maxWidth; this.height = this.options.smart ? 0 : this.maxHeight; this.border = this.options.border ? this.options.border : 0; this.freeRects = [new Rectangle( this.maxWidth + this.padding - this.border * 2, this.maxHeight + this.padding - this.border * 2, this.border, this.border)]; this.stage = new Rectangle(this.width, this.height); this._dirty = 0; } public clone (): MaxRectsBin<T> { let clonedBin: MaxRectsBin<T> = new MaxRectsBin<T>(this.maxWidth, this.maxHeight, this.padding, this.options); for (let rect of this.rects) { clonedBin.add(rect); } return clonedBin; } private place (rect: IRectangle): T | undefined { // recheck if tag matched let tag = (rect.data && rect.data.tag) ? rect.data.tag : rect.tag ? rect.tag : undefined; if (this.options.tag && this.options.exclusiveTag && this.tag !== tag) return undefined; let node: IRectangle | undefined; let allowRotation: boolean | undefined; // getter/setter do not support hasOwnProperty() if (rect.hasOwnProperty("_allowRotation") && rect.allowRotation !== undefined) { allowRotation = rect.allowRotation; // Per Rectangle allowRotation override packer settings } else { allowRotation = this.options.allowRotation; } node = this.findNode(rect.width + this.padding, rect.height + this.padding, allowRotation); if (node) { this.updateBinSize(node); let numRectToProcess = this.freeRects.length; let i: number = 0; while (i < numRectToProcess) { if (this.splitNode(this.freeRects[i], node)) { this.freeRects.splice(i, 1); numRectToProcess--; i--; } i++; } this.pruneFreeList(); this.verticalExpand = this.width > this.height ? true : false; rect.x = node.x; rect.y = node.y; if (rect.rot === undefined) rect.rot = false; rect.rot = node.rot ? !rect.rot : rect.rot; this._dirty ++; return rect as T; } else if (!this.verticalExpand) { if (this.updateBinSize(new Rectangle( rect.width + this.padding, rect.height + this.padding, this.width + this.padding - this.border, this.border )) || this.updateBinSize(new Rectangle( rect.width + this.padding, rect.height + this.padding, this.border, this.height + this.padding - this.border ))) { return this.place(rect); } } else { if (this.updateBinSize(new Rectangle( rect.width + this.padding, rect.height + this.padding, this.border, this.height + this.padding - this.border )) || this.updateBinSize(new Rectangle( rect.width + this.padding, rect.height + this.padding, this.width + this.padding - this.border, this.border ))) { return this.place(rect); } } return undefined; } private findNode (width: number, height: number, allowRotation?: boolean): Rectangle | undefined { let score: number = Number.MAX_VALUE; let areaFit: number; let r: Rectangle; let bestNode: Rectangle | undefined; for (let i in this.freeRects) { r = this.freeRects[i]; if (r.width >= width && r.height >= height) { areaFit = (this.options.logic === PACKING_LOGIC.MAX_AREA) ? r.width * r.height - width * height : Math.min(r.width - width, r.height - height); if (areaFit < score) { bestNode = new Rectangle(width, height, r.x, r.y); score = areaFit; } } if (!allowRotation) continue; // Continue to test 90-degree rotated rectangle if (r.width >= height && r.height >= width) { areaFit = (this.options.logic === PACKING_LOGIC.MAX_AREA) ? r.width * r.height - height * width : Math.min(r.height - width, r.width - height); if (areaFit < score) { bestNode = new Rectangle(height, width, r.x, r.y, true); // Rotated node score = areaFit; } } } return bestNode; } private splitNode (freeRect: IRectangle, usedNode: IRectangle): boolean { // Test if usedNode intersect with freeRect if (!freeRect.collide(usedNode)) return false; // Do vertical split if (usedNode.x < freeRect.x + freeRect.width && usedNode.x + usedNode.width > freeRect.x) { // New node at the top side of the used node if (usedNode.y > freeRect.y && usedNode.y < freeRect.y + freeRect.height) { let newNode: Rectangle = new Rectangle(freeRect.width, usedNode.y - freeRect.y, freeRect.x, freeRect.y); this.freeRects.push(newNode); } // New node at the bottom side of the used node if (usedNode.y + usedNode.height < freeRect.y + freeRect.height) { let newNode = new Rectangle( freeRect.width, freeRect.y + freeRect.height - (usedNode.y + usedNode.height), freeRect.x, usedNode.y + usedNode.height ); this.freeRects.push(newNode); } } // Do Horizontal split if (usedNode.y < freeRect.y + freeRect.height && usedNode.y + usedNode.height > freeRect.y) { // New node at the left side of the used node. if (usedNode.x > freeRect.x && usedNode.x < freeRect.x + freeRect.width) { let newNode = new Rectangle(usedNode.x - freeRect.x, freeRect.height, freeRect.x, freeRect.y); this.freeRects.push(newNode); } // New node at the right side of the used node. if (usedNode.x + usedNode.width < freeRect.x + freeRect.width) { let newNode = new Rectangle( freeRect.x + freeRect.width - (usedNode.x + usedNode.width), freeRect.height, usedNode.x + usedNode.width, freeRect.y ); this.freeRects.push(newNode); } } return true; } private pruneFreeList () { // Go through each pair of freeRects and remove any rects that is redundant let i: number = 0; let j: number = 0; let len: number = this.freeRects.length; while (i < len) { j = i + 1; let tmpRect1 = this.freeRects[i]; while (j < len) { let tmpRect2 = this.freeRects[j]; if (tmpRect2.contain(tmpRect1)) { this.freeRects.splice(i, 1); i--; len--; break; } if (tmpRect1.contain(tmpRect2)) { this.freeRects.splice(j, 1); j--; len--; } j++; } i++; } } private updateBinSize (node: IRectangle): boolean { if (!this.options.smart) return false; if (this.stage.contain(node)) return false; let tmpWidth: number = Math.max(this.width, node.x + node.width - this.padding + this.border); let tmpHeight: number = Math.max(this.height, node.y + node.height - this.padding + this.border); if (this.options.allowRotation) { // do extra test on rotated node whether it's a better choice const rotWidth: number = Math.max(this.width, node.x + node.height - this.padding + this.border); const rotHeight: number = Math.max(this.height, node.y + node.width - this.padding + this.border); if (rotWidth * rotHeight < tmpWidth * tmpHeight) { tmpWidth = rotWidth; tmpHeight = rotHeight; } } if (this.options.pot) { tmpWidth = Math.pow(2, Math.ceil(Math.log(tmpWidth) * Math.LOG2E)); tmpHeight = Math.pow(2, Math.ceil(Math.log(tmpHeight) * Math.LOG2E)); } if (this.options.square) { tmpWidth = tmpHeight = Math.max(tmpWidth, tmpHeight); } if (tmpWidth > this.maxWidth + this.padding || tmpHeight > this.maxHeight + this.padding) { return false; } this.expandFreeRects(tmpWidth + this.padding, tmpHeight + this.padding); this.width = this.stage.width = tmpWidth; this.height = this.stage.height = tmpHeight; return true; } private expandFreeRects (width: number, height: number) { this.freeRects.forEach((freeRect, index) => { if (freeRect.x + freeRect.width >= Math.min(this.width + this.padding - this.border, width)) { freeRect.width = width - freeRect.x - this.border; } if (freeRect.y + freeRect.height >= Math.min(this.height + this.padding - this.border, height)) { freeRect.height = height - freeRect.y - this.border; } }, this); this.freeRects.push(new Rectangle( width - this.width - this.padding, height - this.border * 2, this.width + this.padding - this.border, this.border)); this.freeRects.push(new Rectangle( width - this.border * 2, height - this.height - this.padding, this.border, this.height + this.padding - this.border)); this.freeRects = this.freeRects.filter(freeRect => { return !(freeRect.width <= 0 || freeRect.height <= 0 || freeRect.x < this.border || freeRect.y < this.border); }); this.pruneFreeList(); } }
the_stack
import {ScopeFn} from './engine'; import * as tf from './index'; import {ALL_ENVS, describeWithFlags} from './jasmine_util'; import {backpropagateGradients, getFilteredNodesXToY, TapeNode} from './tape'; import {expectArraysClose} from './test_util'; describeWithFlags('getFilteredNodesXToY', ALL_ENVS, () => { it('no paths from x to y', () => { const x = tf.scalar(1); const intermediate1 = tf.scalar(0); const intermediate2 = tf.scalar(0); const y = tf.scalar(2); const tape: TapeNode[] = [ { id: 0, name: 'node0', inputs: {x}, outputs: [intermediate1], gradient: null }, { id: 1, name: 'node1', inputs: {intermediate2}, outputs: [y], gradient: null } ]; const filteredTapeNodes = getFilteredNodesXToY(tape, [x], y); expect(filteredTapeNodes.length).toBe(0); expect(filteredTapeNodes).toEqual([]); }); it('one operation x => y', () => { const x = tf.scalar(1); const y = tf.scalar(2); const tape: TapeNode[] = [{id: 0, name: 'node0', inputs: {x}, outputs: [y], gradient: null}]; const filteredTapeNodes = getFilteredNodesXToY(tape, [x], y); expect(filteredTapeNodes.length).toBe(1); expect(filteredTapeNodes).toEqual(tape); }); it('1 operation [x0, x1] => y, all input paths', () => { const x0 = tf.scalar(0); const x1 = tf.scalar(1); const y = tf.scalar(2); const tape: TapeNode[] = [ {id: 0, name: 'node0', inputs: {x0, x1}, outputs: [y], gradient: null} ]; const filteredTapeNodes = getFilteredNodesXToY(tape, [x0, x1], y); expect(filteredTapeNodes.length).toBe(1); expect(filteredTapeNodes).toEqual(tape); }); it('one operation [x0, x1] => y, one input paths', () => { const x0 = tf.scalar(0); const x1 = tf.scalar(1); const y = tf.scalar(2); const tape: TapeNode[] = [ {id: 0, name: 'node0', inputs: {x0, x1}, outputs: [y], gradient: null} ]; const filteredTapeNodes = getFilteredNodesXToY(tape, [x0], y); expect(filteredTapeNodes.length).toBe(1); // x1 input should be pruned, we don't ask for the gradient of x1. expect(filteredTapeNodes[0]) .toEqual( {id: 0, name: 'node0', inputs: {x0}, outputs: [y], gradient: null}); }); it('two operations x => intermediate => y', () => { const x = tf.scalar(1); const intermediate = tf.scalar(0); const y = tf.scalar(2); const tape: TapeNode[] = [ { id: 0, name: 'node0', inputs: {x}, outputs: [intermediate], gradient: null }, { id: 1, name: 'node1', inputs: {intermediate}, outputs: [y], gradient: null } ]; const filteredTapeNodes = getFilteredNodesXToY(tape, [x], y); expect(filteredTapeNodes.length).toBe(2); expect(filteredTapeNodes).toEqual(tape); }); it('two operations [x0, x1], [x2] => ' + 'intermediate => y', () => { const x0 = tf.scalar(1); const x1 = tf.scalar(2); const x2 = tf.scalar(3); const intermediate = tf.scalar(4); const y = tf.scalar(2); const tape: TapeNode[] = [ { id: 0, name: 'node0', inputs: {x0, x1}, outputs: [intermediate], gradient: null }, { id: 1, name: 'node1', inputs: {x2, intermediate}, outputs: [y], gradient: null } ]; const filteredTapeNodes = getFilteredNodesXToY(tape, [x0, x1, x2], y); expect(filteredTapeNodes.length).toBe(2); expect(filteredTapeNodes).toEqual(tape); }); it('x => y and x => orphan', () => { const x = tf.scalar(1); const orphan = tf.scalar(0); const y = tf.scalar(2); const tape: TapeNode[] = [ {id: 0, name: 'node0', inputs: {x}, outputs: [orphan], gradient: null}, {id: 1, name: 'node1', inputs: {x}, outputs: [y], gradient: null} ]; const filteredTapeNodes = getFilteredNodesXToY(tape, [x], y); expect(filteredTapeNodes.length).toBe(1); // The orphan should be removed. expect(filteredTapeNodes[0]).toEqual(tape[1]); }); it('x => y and orphan => y', () => { const x = tf.scalar(1); const orphan = tf.scalar(0); const y = tf.scalar(2); const tape: TapeNode[] = [ {id: 0, name: 'node0', inputs: {x, orphan}, outputs: [y], gradient: null} ]; const filteredTapeNodes = getFilteredNodesXToY(tape, [x], y); expect(filteredTapeNodes.length).toBe(1); // The orphan should be pruned from the node's input. expect(filteredTapeNodes[0]) .toEqual( {id: 0, name: 'node0', inputs: {x}, outputs: [y], gradient: null}); }); it('1 op with 3 outputs x => y1, y2, y3', () => { const x = tf.scalar(1); const y1 = tf.scalar(2); const y2 = tf.scalar(2); const y3 = tf.scalar(2); const tape: TapeNode[] = [ {id: 0, name: 'node0', inputs: {x}, outputs: [y1, y2, y3], gradient: null} ]; const filteredNodes1 = getFilteredNodesXToY(tape, [x], y1); expect(filteredNodes1.length).toBe(1); expect(filteredNodes1).toEqual(tape); const filteredNodes2 = getFilteredNodesXToY(tape, [x], y2); expect(filteredNodes2.length).toBe(1); expect(filteredNodes2).toEqual(tape); const filteredNodes3 = getFilteredNodesXToY(tape, [x], y3); expect(filteredNodes3.length).toBe(1); expect(filteredNodes3).toEqual(tape); }); }); describeWithFlags('backpropagateGradients', ALL_ENVS, () => { it('Throws if gradient is not defined', () => { const x = tf.scalar(0); const y = tf.scalar(1); const dy = tf.scalar(1); const accumulatedGradientsMap: {[tensorId: number]: tf.Tensor} = {}; accumulatedGradientsMap[y.id] = dy; const tape: TapeNode[] = [{id: 0, name: 'node0', inputs: {x}, outputs: [y], gradient: null}]; expect( () => backpropagateGradients( accumulatedGradientsMap, tape, f => tf.tidy(f as ScopeFn<tf.Tensor>))) .toThrowError(); }); it('basic backprop with 1 node', async () => { const x = tf.scalar(0); const y = tf.scalar(1); const dy = tf.scalar(1); const accumulatedGradientsMap: {[tensorId: number]: tf.Tensor} = {}; accumulatedGradientsMap[y.id] = dy; const tape: TapeNode[] = [{ id: 0, name: 'node0', inputs: {x}, outputs: [y], gradient: (dy: tf.Scalar) => { return {x: () => dy.add(tf.scalar(1))}; } }]; backpropagateGradients( accumulatedGradientsMap, tape, f => tf.tidy(f as ScopeFn<tf.Tensor>)); expectArraysClose(await accumulatedGradientsMap[x.id].data(), [2]); }); it('basic backprop with 2 nodes', async () => { const x = tf.scalar(0); const intermediate = tf.scalar(1); const y = tf.scalar(2); const dy = tf.scalar(1); const accumulatedGradientsMap: {[tensorId: number]: tf.Tensor} = {}; accumulatedGradientsMap[y.id] = dy; const tape: TapeNode[] = [ { id: 0, name: 'node0', inputs: {x}, outputs: [intermediate], gradient: (dy: tf.Scalar) => { return {x: () => dy.add(tf.scalar(1))}; } }, { id: 1, name: 'node1', inputs: {intermediate}, outputs: [y], gradient: (dy: tf.Scalar) => { return {intermediate: () => dy.add(tf.scalar(1))}; } } ]; backpropagateGradients( accumulatedGradientsMap, tape, f => tf.tidy(f as ScopeFn<tf.Tensor>)); // dx = dy + 1 + 1 expectArraysClose(await accumulatedGradientsMap[x.id].data(), [3]); }); it('basic backprop with a split node accumulates gradients', async () => { const x = tf.scalar(0); const intermediate1 = tf.scalar(1); const intermediate2 = tf.scalar(2); const y = tf.scalar(3); const dy = tf.scalar(1); const accumulatedGradientsMap: {[tensorId: number]: tf.Tensor} = {}; accumulatedGradientsMap[y.id] = dy; const tape: TapeNode[] = [ { id: 0, name: 'node0', inputs: {x}, outputs: [intermediate1], gradient: (dy: tf.Scalar) => { return {x: () => dy.add(tf.scalar(1))}; } }, { id: 1, name: 'node1', inputs: {x}, outputs: [intermediate2], gradient: (dy: tf.Scalar) => { return {x: () => dy.add(tf.scalar(1))}; } }, { id: 2, name: 'node2', inputs: {intermediate1, intermediate2}, outputs: [y], gradient: (dy: tf.Scalar) => { return { intermediate1: () => dy.add(tf.scalar(1)), intermediate2: () => dy.add(tf.scalar(1)) }; } } ]; backpropagateGradients( accumulatedGradientsMap, tape, f => tf.tidy(f as ScopeFn<tf.Tensor>)); // dx = dy + 1 + 1 + 1 + 1 + 1 expectArraysClose( await accumulatedGradientsMap[x.id].data(), [(await dy.data())[0] + 5]); }); it('backprop over 1 node with 3 outputs, w.r.t to the 2nd output', async () => { const x = tf.tensor1d([1, 1, 1]); const y1 = tf.scalar(1); const y2 = tf.scalar(1); const y3 = tf.scalar(1); const accumulatedGradientsMap: {[tensorId: number]: tf.Tensor} = {}; // Backproping through the 2nd output. const dy2 = tf.scalar(5); accumulatedGradientsMap[y2.id] = dy2; let dys: tf.Scalar[]; const tape: TapeNode[] = [{ id: 0, name: 'node0', inputs: {x}, outputs: [y1, y2, y3], gradient: (dys_: tf.Scalar[]) => { dys = dys_; return {x: () => tf.stack(dys_)}; } }]; backpropagateGradients( accumulatedGradientsMap, tape, f => tf.tidy(f as ScopeFn<tf.Tensor>)); expectArraysClose(await accumulatedGradientsMap[x.id].data(), [0, 5, 0]); expectArraysClose(await dys[0].data(), [0]); expectArraysClose(await dys[1].data(), [5]); expectArraysClose(await dys[2].data(), [0]); }); });
the_stack
import invariant from 'invariant'; import { Platform } from 'react-native'; import * as Base64 from './Base64'; import * as ServiceConfig from './Discovery'; import { ResponseErrorConfig, TokenError } from './Errors'; import { Headers, requestAsync } from './Fetch'; import { AccessTokenRequestConfig, GrantType, RefreshTokenRequestConfig, RevokeTokenRequestConfig, ServerTokenResponseConfig, TokenRequestConfig, TokenResponseConfig, TokenType, TokenTypeHint, } from './TokenRequest.types'; /** * Returns the current time in seconds. */ export function getCurrentTimeInSeconds(): number { return Math.floor(Date.now() / 1000); } /** * Token Response. * * [Section 5.1](https://tools.ietf.org/html/rfc6749#section-5.1) */ export class TokenResponse implements TokenResponseConfig { /** * Determines whether a token refresh request must be made to refresh the tokens * * @param token * @param secondsMargin */ static isTokenFresh( token: Pick<TokenResponse, 'expiresIn' | 'issuedAt'>, /** * -10 minutes in seconds */ secondsMargin: number = 60 * 10 * -1 ): boolean { if (!token) { return false; } if (token.expiresIn) { const now = getCurrentTimeInSeconds(); return now < token.issuedAt + token.expiresIn + secondsMargin; } // if there is no expiration time but we have an access token, it is assumed to never expire return true; } /** * Creates a `TokenResponse` from query parameters returned from an `AuthRequest`. * * @param params */ static fromQueryParams(params: Record<string, any>): TokenResponse { return new TokenResponse({ accessToken: params.access_token, refreshToken: params.refresh_token, scope: params.scope, state: params.state, idToken: params.id_token, tokenType: params.token_type, expiresIn: params.expires_in, issuedAt: params.issued_at, }); } accessToken: string; tokenType: TokenType; expiresIn?: number; refreshToken?: string; scope?: string; state?: string; idToken?: string; issuedAt: number; constructor(response: TokenResponseConfig) { this.accessToken = response.accessToken; this.tokenType = response.tokenType ?? 'bearer'; this.expiresIn = response.expiresIn; this.refreshToken = response.refreshToken; this.scope = response.scope; this.state = response.state; this.idToken = response.idToken; this.issuedAt = response.issuedAt ?? getCurrentTimeInSeconds(); } private applyResponseConfig(response: TokenResponseConfig) { this.accessToken = response.accessToken ?? this.accessToken; this.tokenType = response.tokenType ?? this.tokenType ?? 'bearer'; this.expiresIn = response.expiresIn ?? this.expiresIn; this.refreshToken = response.refreshToken ?? this.refreshToken; this.scope = response.scope ?? this.scope; this.state = response.state ?? this.state; this.idToken = response.idToken ?? this.idToken; this.issuedAt = response.issuedAt ?? this.issuedAt ?? getCurrentTimeInSeconds(); } getRequestConfig(): TokenResponseConfig { return { accessToken: this.accessToken, idToken: this.idToken, refreshToken: this.refreshToken, scope: this.scope, state: this.state, tokenType: this.tokenType, issuedAt: this.issuedAt, expiresIn: this.expiresIn, }; } async refreshAsync( config: Omit<TokenRequestConfig, 'grantType' | 'refreshToken'>, discovery: Pick<ServiceConfig.DiscoveryDocument, 'tokenEndpoint'> ): Promise<TokenResponse> { const request = new RefreshTokenRequest({ ...config, refreshToken: this.refreshToken, }); const response = await request.performAsync(discovery); // Custom: reuse the refresh token if one wasn't returned response.refreshToken = response.refreshToken ?? this.refreshToken; const json = response.getRequestConfig(); this.applyResponseConfig(json); return this; } shouldRefresh(): boolean { // no refresh token available and token has expired return !(TokenResponse.isTokenFresh(this) || !this.refreshToken); } } class Request<T, B> { constructor(protected request: T) {} async performAsync(discovery: ServiceConfig.DiscoveryDocument): Promise<B> { throw new Error('performAsync must be extended'); } getRequestConfig(): T { throw new Error('getRequestConfig must be extended'); } getQueryBody(): Record<string, string> { throw new Error('getQueryBody must be extended'); } } /** * A generic token request. */ class TokenRequest<T extends TokenRequestConfig> extends Request<T, TokenResponse> { readonly clientId: string; readonly clientSecret?: string; readonly scopes?: string[]; readonly extraParams?: Record<string, string>; constructor(request, public grantType: GrantType) { super(request); this.clientId = request.clientId; this.clientSecret = request.clientSecret; this.extraParams = request.extraParams; this.scopes = request.scopes; } getHeaders(): Headers { const headers: Headers = { 'Content-Type': 'application/x-www-form-urlencoded' }; if (typeof this.clientSecret !== 'undefined') { // If client secret exists, it should be converted to base64 // https://tools.ietf.org/html/rfc6749#section-2.3.1 const encodedClientId = encodeURIComponent(this.clientId); const encodedClientSecret = encodeURIComponent(this.clientSecret); const credentials = `${encodedClientId}:${encodedClientSecret}`; const basicAuth = Base64.encodeNoWrap(credentials); headers.Authorization = `Basic ${basicAuth}`; } return headers; } async performAsync(discovery: Pick<ServiceConfig.DiscoveryDocument, 'tokenEndpoint'>) { // redirect URI must not be nil invariant( discovery.tokenEndpoint, `Cannot invoke \`performAsync()\` without a valid tokenEndpoint` ); const response = await requestAsync<ServerTokenResponseConfig | ResponseErrorConfig>( discovery.tokenEndpoint, { dataType: 'json', method: 'POST', headers: this.getHeaders(), body: this.getQueryBody(), } ); if ('error' in response) { throw new TokenError(response); } return new TokenResponse({ accessToken: response.access_token, tokenType: response.token_type, expiresIn: response.expires_in, refreshToken: response.refresh_token, scope: response.scope, idToken: response.id_token, issuedAt: response.issued_at, }); } getQueryBody() { const queryBody: Record<string, string> = { grant_type: this.grantType, }; if (!this.clientSecret) { // Only add the client ID if client secret is not present, otherwise pass the client id with the secret in the request body. queryBody.client_id = this.clientId; } if (this.scopes) { queryBody.scope = this.scopes.join(' '); } if (this.extraParams) { for (const extra in this.extraParams) { if (extra in this.extraParams && !(extra in queryBody)) { queryBody[extra] = this.extraParams[extra]; } } } return queryBody; } } /** * Access token request. Exchange an authorization code for a user access token. * * [Section 4.1.3](https://tools.ietf.org/html/rfc6749#section-4.1.3) */ export class AccessTokenRequest extends TokenRequest<AccessTokenRequestConfig> implements AccessTokenRequestConfig { readonly code: string; readonly redirectUri: string; constructor(options: AccessTokenRequestConfig) { invariant( options.redirectUri, `\`AccessTokenRequest\` requires a valid \`redirectUri\` (it must also match the one used in the auth request). Example: ${Platform.select( { web: 'https://yourwebsite.com/redirect', default: 'myapp://redirect', } )}` ); invariant( options.code, `\`AccessTokenRequest\` requires a valid authorization \`code\`. This is what's received from the authorization server after an auth request.` ); super(options, GrantType.AuthorizationCode); this.code = options.code; this.redirectUri = options.redirectUri; } getQueryBody() { const queryBody: Record<string, string> = super.getQueryBody(); if (this.redirectUri) { queryBody.redirect_uri = this.redirectUri; } if (this.code) { queryBody.code = this.code; } return queryBody; } getRequestConfig() { return { clientId: this.clientId, clientSecret: this.clientSecret, grantType: this.grantType, code: this.code, redirectUri: this.redirectUri, extraParams: this.extraParams, scopes: this.scopes, }; } } /** * Refresh request. * * [Section 6](https://tools.ietf.org/html/rfc6749#section-6) */ export class RefreshTokenRequest extends TokenRequest<RefreshTokenRequestConfig> implements RefreshTokenRequestConfig { readonly refreshToken?: string; constructor(options: RefreshTokenRequestConfig) { invariant(options.refreshToken, `\`RefreshTokenRequest\` requires a valid \`refreshToken\`.`); super(options, GrantType.RefreshToken); this.refreshToken = options.refreshToken; } getQueryBody() { const queryBody = super.getQueryBody(); if (this.refreshToken) { queryBody.refresh_token = this.refreshToken; } return queryBody; } getRequestConfig() { return { clientId: this.clientId, clientSecret: this.clientSecret, grantType: this.grantType, refreshToken: this.refreshToken, extraParams: this.extraParams, scopes: this.scopes, }; } } /** * Revocation request for a given token. * * [Section 2.1](https://tools.ietf.org/html/rfc7009#section-2.1) */ export class RevokeTokenRequest extends Request<RevokeTokenRequestConfig, boolean> implements RevokeTokenRequestConfig { readonly clientId?: string; readonly clientSecret?: string; readonly token: string; readonly tokenTypeHint?: TokenTypeHint; constructor(request: RevokeTokenRequestConfig) { super(request); invariant(request.token, `\`RevokeTokenRequest\` requires a valid \`token\` to revoke.`); this.clientId = request.clientId; this.clientSecret = request.clientSecret; this.token = request.token; this.tokenTypeHint = request.tokenTypeHint; } getHeaders(): Headers { const headers: Headers = { 'Content-Type': 'application/x-www-form-urlencoded' }; if (typeof this.clientSecret !== 'undefined' && this.clientId) { // If client secret exists, it should be converted to base64 // https://tools.ietf.org/html/rfc6749#section-2.3.1 const encodedClientId = encodeURIComponent(this.clientId); const encodedClientSecret = encodeURIComponent(this.clientSecret); const credentials = `${encodedClientId}:${encodedClientSecret}`; const basicAuth = Base64.encodeNoWrap(credentials); headers.Authorization = `Basic ${basicAuth}`; } return headers; } /** * Perform a token revocation request. * * @param discovery The `revocationEndpoint` for a provider. */ async performAsync(discovery: Pick<ServiceConfig.DiscoveryDocument, 'revocationEndpoint'>) { invariant( discovery.revocationEndpoint, `Cannot invoke \`performAsync()\` without a valid revocationEndpoint` ); await requestAsync<boolean>(discovery.revocationEndpoint, { method: 'POST', headers: this.getHeaders(), body: this.getQueryBody(), }); return true; } getRequestConfig() { return { clientId: this.clientId, clientSecret: this.clientSecret, token: this.token, tokenTypeHint: this.tokenTypeHint, }; } getQueryBody(): Record<string, string> { const queryBody: Record<string, string> = { token: this.token }; if (this.tokenTypeHint) { queryBody.token_type_hint = this.tokenTypeHint; } // Include client creds https://tools.ietf.org/html/rfc6749#section-2.3.1 if (this.clientId) { queryBody.client_id = this.clientId; } if (this.clientSecret) { queryBody.client_secret = this.clientSecret; } return queryBody; } } /** * Exchange an auth code for an access token that can be used to get data from the provider. * * @param config * @param discovery The `tokenEndpoint` for a provider. */ export function exchangeCodeAsync( config: AccessTokenRequestConfig, discovery: Pick<ServiceConfig.DiscoveryDocument, 'tokenEndpoint'> ): Promise<TokenResponse> { const request = new AccessTokenRequest(config); return request.performAsync(discovery); } /** * Refresh an access token. Often this just requires the `refreshToken` and `scopes` parameters. * * [Section 6](https://tools.ietf.org/html/rfc6749#section-6) * * @param config * @param discovery The `tokenEndpoint` for a provider. */ export function refreshAsync( config: RefreshTokenRequestConfig, discovery: Pick<ServiceConfig.DiscoveryDocument, 'tokenEndpoint'> ): Promise<TokenResponse> { const request = new RefreshTokenRequest(config); return request.performAsync(discovery); } /** * Revoke a token with a provider. * This makes the token unusable, effectively requiring the user to login again. * * @param config * @param discovery The `revocationEndpoint` for a provider. */ export function revokeAsync( config: RevokeTokenRequestConfig, discovery: Pick<ServiceConfig.DiscoveryDocument, 'revocationEndpoint'> ): Promise<boolean> { const request = new RevokeTokenRequest(config); return request.performAsync(discovery); } /** * Fetch generic user info from the provider's OpenID Connect `userInfoEndpoint` (if supported). * * [UserInfo](https://openid.net/specs/openid-connect-core-1_0.html#UserInfo) * * @param config The `accessToken` for a user, returned from a code exchange or auth request. * @param discovery The `userInfoEndpoint` for a provider. */ export function fetchUserInfoAsync( config: Pick<TokenResponse, 'accessToken'>, discovery: Pick<ServiceConfig.DiscoveryDocument, 'userInfoEndpoint'> ): Promise<Record<string, any>> { if (!discovery.userInfoEndpoint) { throw new Error('User info endpoint is not defined in the service config discovery document'); } return requestAsync<Record<string, any>>(discovery.userInfoEndpoint, { headers: { 'Content-Type': 'application/x-www-form-urlencoded', Authorization: `Bearer ${config.accessToken}`, }, dataType: 'json', method: 'GET', }); }
the_stack
import Bottleneck from 'bottleneck' import { Headers } from 'cross-fetch' import OAuth from 'oauth-1.0a' import { CurrenciesEnum, EditOrderStatusesEnum, FolderIdsEnum, InventorySortEnum, InventoryStatusesEnum, ListingStatusesEnum, OrderSortEnum, OrderStatusesEnum, ReleaseConditionsEnum, ReleaseSortEnum, SearchTypeEnum, SleeveConditionsEnum, UserSortEnum, } from './constants' import { addQueryToUri, createLimiter, fetch, HTTPVerbsEnum, paginate, Pagination, sortBy, SortOptions, transformData, } from './utils' import { AddToFolderResponse, AddToWantlistResponse, Artist, ArtistReleasesResponse, CollectionValueResponse, CommunityReleaseRatingResponse, CreateListingResponse, CustomFieldsResponse, EditUserProfileResponse, EmptyResponse, Fee, Folder, FolderReleasesResponse, FoldersResponse, IdentityResponse, InventoryResponse, Label, LabelReleasesResponse, Listing, MarketplaceStatisticsResponse, Master, MasterVersionsResponse, Order, OrderMessage, OrderMessagesResponse, OrdersResponse, PriceSuggestionsResponse, Release, ReleaseRatingResponse, SearchResponse, UserContributionsResponse, UserListItemsResponse, UserListsResponse, UserProfileResponse, UserSubmissionsResponse, WantlistResponse, } from '../models' /** * Base API URL to which URI will be appended. * * @internal */ const API_BASE_URL = 'https://api.discogs.com' /** * Base URL dedicated to Discogs images. * * @internal */ const IMG_BASE_URL = 'https://img.discogs.com' /** * Discogs API version. * * @internal */ const API_VERSION = 'v2' /** * Default user-agent to be used in requests. * * @internal */ const DEFAULT_USER_AGENT = `Discojs/__packageVersion__` type UserTokenAuth = { /** User token. */ userToken: string } type ConsumerKeyAuth = { /** Consumer key. */ consumerKey: string /** Consumer secret. */ consumerSecret: string /** OAuth token. */ oAuthToken: string /** OAuth token secret. */ oAuthTokenSecret: string } // @TODO: Make a better limiter (one limit, no interval, should use headers from Discogs). type LimiterOptions = { /** Number of requests per interval for unauthenticated requests. Defaults to 25. */ requestLimit?: number /** Number of requests per interval for authenticated requests. Defaults to 60. */ requestLimitAuth?: number /** Interval to use to throttle requests. Defaults to 60 seconds. */ requestLimitInterval?: number } /** * Available output formats. * * @todo Edit types depending on chosen output format. */ enum OutputFormatsEnum { DISCOGS = 'discogs', // PLAIN = 'plaintext', // HTML = 'html', } interface DiscojsOptions extends Partial<UserTokenAuth>, Partial<ConsumerKeyAuth>, LimiterOptions { /** * User-agent to be used in requests. * * @default Discojs/{packageVersion} */ userAgent?: string /** * Output format. * * @default discogs */ outputFormat?: OutputFormatsEnum fetchOptions?: RequestInit } type SearchOptions = { query?: string type?: SearchTypeEnum title?: string releaseTitle?: string credit?: string artist?: string anv?: string label?: string genre?: string style?: string country?: string year?: string | number format?: string catno?: string barcode?: string track?: string submitter?: string contributor?: string } type ProfileOptions = { username?: string name?: string homePage?: string location?: string profile?: string currAbbr?: CurrenciesEnum } type ListingOptions = { releaseId: number condition: ReleaseConditionsEnum sleeveCondition?: SleeveConditionsEnum price: number comments?: string allowOffers?: boolean status: ListingStatusesEnum externalId?: string location?: string weight?: 'auto' | number formatQuantity?: 'auto' | number } type RatingValues = 0 | 1 | 2 | 3 | 4 | 5 /** * Type guard to check if authenticated thanks to user token. * * @internal */ function isAuthenticatedWithToken(options?: Partial<UserTokenAuth>): options is UserTokenAuth { return Boolean(options) && typeof options!.userToken === 'string' } /** * Type guard to check if authenticated thanks to consumer key. * * @internal */ function isAuthenticatedWithConsumerKey(options?: Partial<ConsumerKeyAuth>): options is ConsumerKeyAuth { return ( Boolean(options) && typeof options!.consumerKey === 'string' && typeof options!.consumerSecret === 'string' && typeof options!.oAuthToken === 'string' && typeof options!.oAuthTokenSecret === 'string' ) } /** * Type guard to check whether requests are authenticated or not. * * @internal */ function isAuthenticated(options?: DiscojsOptions) { return isAuthenticatedWithToken(options) || isAuthenticatedWithConsumerKey(options) } /** * Discojs. */ export class Discojs { public userAgent: string public outputFormat: OutputFormatsEnum private limiter: Bottleneck private fetchHeaders: Headers private setAuthorizationHeader?: (url?: string, method?: HTTPVerbsEnum) => string private fetchOptions: RequestInit constructor(options?: DiscojsOptions) { const { userAgent = DEFAULT_USER_AGENT, outputFormat = OutputFormatsEnum.DISCOGS, requestLimit = 25, requestLimitAuth = 60, requestLimitInterval = 60 * 1000, fetchOptions = {}, } = options || {} this.userAgent = userAgent this.outputFormat = outputFormat this.limiter = createLimiter({ maxRequests: isAuthenticated(options) ? requestLimitAuth : requestLimit, requestLimitInterval, }) this.fetchOptions = fetchOptions this.fetchHeaders = new Headers({ Accept: `application/vnd.discogs.${API_VERSION}.${this.outputFormat}+json`, 'Accept-Encoding': 'gzip,deflate', Connection: 'close', 'Content-Type': 'application/json', 'User-Agent': this.userAgent, }) if (isAuthenticatedWithToken(options)) this.setAuthorizationHeader = () => `Discogs token=${options.userToken}` if (isAuthenticatedWithConsumerKey(options)) { const oAuth = new OAuth({ consumer: { key: options.consumerKey, secret: options.consumerSecret }, signature_method: 'PLAINTEXT', version: '1.0', }) this.setAuthorizationHeader = (url?: string, method?: HTTPVerbsEnum) => { if (!url || !method) return '' const authObject = oAuth.authorize( { url, method }, { key: options.oAuthToken, secret: options.oAuthTokenSecret }, ) return oAuth.toHeader(authObject).Authorization } } } /** * Return currencies supported by Discogs. * * @category Helpers * * @static */ static getSupportedCurrencies() { return Object.values(CurrenciesEnum) } /** * Return release conditions supported by Discogs. * * @category Helpers * * @static */ static getReleaseConditions() { return Object.values(ReleaseConditionsEnum) } /** * Return slevve conditions supported by Discogs. * * @category Helpers * * @static */ static getSleeveConditions() { return Object.values(SleeveConditionsEnum) } /** * Private method used within other methods. * * @private * @internal */ private async fetch<T>(uri: string, query?: Record<string, any>, method?: HTTPVerbsEnum, data?: Record<string, any>) { const isImgEndpoint = uri.startsWith(IMG_BASE_URL) const endpoint = isImgEndpoint ? uri : API_BASE_URL + (query && typeof query === 'object' ? addQueryToUri(uri, query) : uri) const options = { ...this.fetchOptions, method: method || HTTPVerbsEnum.GET, } // Set Authorization header. if (this.setAuthorizationHeader) this.fetchHeaders.set('Authorization', this.setAuthorizationHeader(uri, method || HTTPVerbsEnum.GET)) const clonedHeaders = new Map(this.fetchHeaders) if (data) { const stringifiedData = JSON.stringify(transformData(data)) options.body = stringifiedData clonedHeaders.set('Content-Type', 'application/json') clonedHeaders.set('Content-Length', Buffer.byteLength(stringifiedData, 'utf8').toString()) } options.headers = Object.fromEntries(clonedHeaders) return this.limiter.schedule(() => fetch<T>(endpoint, options, isImgEndpoint)) } /** * Retrieve basic information about the authenticated user. * * @remarks * You can use this resource to find out who you’re authenticated as, and it also doubles as a good sanity check to ensure that you’re using OAuth correctly. * * @category User Identity * * @link https://www.discogs.com/developers#page:user-identity,header:user-identity-identity */ async getIdentity() { return this.fetch<IdentityResponse>('/oauth/identity') } /** * Retrieve authenticated user's username. * * @remarks * Used internally within methods that use `username` as a param. * * @category User Identity * * @private */ private async getUsername() { const { username } = await this.getIdentity() return username } /** * Retrieve user's profile by username. * * @remarks * If authenticated as the requested user, the `email` key will be visible, and the `num_list count` will include the user’s private lists. * If authenticated as the requested user or the user’s collection/wantlist is public, the `num_collection` / `num_wantlist` keys will be visible. * * @category User Profile * * @link https://www.discogs.com/developers#page:user-identity,header:user-identity-profile */ async getProfileForUser(username: string) { return this.fetch<UserProfileResponse>(`/users/${username}`) } /** * Retrieve authenticated user's profile. * * @category User Profile * * @link https://www.discogs.com/developers#page:user-identity,header:user-identity-profile */ async getProfile() { const username = await this.getUsername() return this.getProfileForUser(username) } /** * Edit a user’s profile data. * * @category User Profile * * @link https://www.discogs.com/developers#page:user-identity,header:user-identity-profile */ async editProfile(options: ProfileOptions) { const username = await this.getUsername() return this.fetch<EditUserProfileResponse>(`/users/${username}`, {}, HTTPVerbsEnum.POST, { username, ...options }) } /** * Retrieve a user’s submissions by username. * * @category User Submissions * * @link https://www.discogs.com/developers#page:user-identity,header:user-identity-user-submissions */ async getSubmissionsForUser(username: string, pagination?: Pagination) { return this.fetch<UserSubmissionsResponse>(`/users/${username}/submissions`, paginate(pagination)) } /** * Retrieve authenticated user’s submissions. * * @category User Submissions * * @link https://www.discogs.com/developers#page:user-identity,header:user-identity-user-submissions */ async getSubmissions(pagination?: Pagination) { const username = await this.getUsername() return this.getSubmissionsForUser(username, pagination) } /** * Retrieve a user’s contributions by username. * * @category User Contributions * * @link https://www.discogs.com/developers#page:user-identity,header:user-identity-user-contributions */ async getContributionsForUser(username: string, sort?: SortOptions<UserSortEnum>, pagination?: Pagination) { return this.fetch<UserContributionsResponse>(`/users/${username}/contributions`, { ...sortBy(UserSortEnum.ADDED, sort), ...paginate(pagination), }) } /** * Retrieve authenticated user’s contributions. * * @category User Contributions * * @link https://www.discogs.com/developers#page:user-identity,header:user-identity-user-contributions */ async getContributions(sort?: SortOptions<UserSortEnum>, pagination?: Pagination) { const username = await this.getUsername() return this.getContributionsForUser(username, sort, pagination) } /** * Retrieve a list of folders in a user’s collection. * * @remarks * If the collection has been made private by its owner, authentication as the collection owner is required. * If you are not authenticated as the collection owner, only folder ID 0 (the “All” folder) will be visible (if the requested user’s collection is public). * * @category User Collection * * @link https://www.discogs.com/developers#page:user-collection,header:user-collection-collection */ async listFoldersForUser(username: string) { return this.fetch<FoldersResponse>(`/users/${username}/collection/folders`) } /** * Retrieve a list of folders in authenticated user’s collection. * * @category User Collection * * @link https://www.discogs.com/developers#page:user-collection,header:user-collection-collection */ async listFolders() { const username = await this.getUsername() return this.listFoldersForUser(username) } /** * Create a new folder in authenticated user’s collection. * * @category User Collection * * @link https://www.discogs.com/developers#page:user-collection,header:user-collection-collection */ async createFolder(name: string) { const username = await this.getUsername() return this.fetch<Folder>(`/users/${username}/collection/folders`, {}, HTTPVerbsEnum.POST, { name }) } /** * Retrieve metadata about a folder in a user’s collection. * * @remarks * If folder_id is not 0, authentication as the collection owner is required. * * @category User Folder * * @link https://www.discogs.com/developers#page:user-collection,header:user-collection-collection-folder */ async getFolderForUser(username: string, folderId: FolderIdsEnum | number) { return this.fetch<Folder>(`/users/${username}/collection/folders/${folderId}`) } /** * Retrieve metadata about a folder in authenticated user’s collection. * * @category User Folder * * @link https://www.discogs.com/developers#page:user-collection,header:user-collection-collection-folder */ async getFolder(folderId: FolderIdsEnum | number) { const username = await this.getUsername() return this.getFolderForUser(username, folderId) } /** * Edit a folder’s metadata. * * @remarks * Folders 0 and 1 cannot be renamed. * * @category User Folder * * @link https://www.discogs.com/developers#page:user-collection,header:user-collection-collection-folder */ async editFolder(folderId: FolderIdsEnum | number, name: string) { const username = await this.getUsername() return this.fetch<Folder>(`/users/${username}/collection/folders/${folderId}`, {}, HTTPVerbsEnum.POST, { name, }) } /** * Delete a folder from a user’s collection. * * @remarks * A folder must be empty before it can be deleted. * * @category User Folder * * @link https://www.discogs.com/developers#page:user-collection,header:user-collection-collection-folder */ async deleteFolder(folderId: FolderIdsEnum | number) { const username = await this.getUsername() return this.fetch<EmptyResponse>(`/users/${username}/collection/folders/${folderId}`, {}, HTTPVerbsEnum.DELETE) } /** * View the user’s collection folders which contain a specified release. This will also show information about each release instance. * * @remarks * Authentication as the collection owner is required if the owner’s collection is private. * * @category User * @label Items By Release * * @link https://www.discogs.com/developers#page:user-collection,header:user-collection-collection-items-by-release */ async listItemsByReleaseForUser(username: string, release_id: number, pagination?: Pagination) { return this.fetch<FolderReleasesResponse>( `/users/${username}/collection/releases/${release_id}`, paginate(pagination), ) } /** * View authenticated user’s collection folders which contain a specified release. This will also show information about each release instance. * * @category User * @label Items By Release * * @link https://www.discogs.com/developers#page:user-collection,header:user-collection-collection-items-by-release */ async listItemsByRelease(release_id: number, pagination?: Pagination) { const username = await this.getUsername() return this.listItemsByReleaseForUser(username, release_id, pagination) } /** * Returns the list of item in a folder in a user’s collection. * * @remarks * Basic information about each release is provided, suitable for display in a list. For detailed information, make another API call to fetch the corresponding release. * If folder_id is not 0, or the collection has been made private by its owner, authentication as the collection owner is required. * If you are not authenticated as the collection owner, only public notes fields will be visible. * * @category User * @label Collection Items By Folder * * @link https://www.discogs.com/developers#page:user-collection,header:user-collection-collection-items-by-folder */ async listItemsInFolderForUser( username: string, folderId: FolderIdsEnum | number, sort?: SortOptions<UserSortEnum>, pagination?: Pagination, ) { return this.fetch<FolderReleasesResponse>(`/users/${username}/collection/folders/${folderId}/releases`, { ...sortBy(UserSortEnum.ADDED, sort), ...paginate(pagination), }) } /** * Returns the list of item in a folder in authenticated user’s collection. * * @remarks * Basic information about each release is provided, suitable for display in a list. For detailed information, make another API call to fetch the corresponding release. * * @category User * @label Collection Items By Folder * * @link https://www.discogs.com/developers#page:user-collection,header:user-collection-collection-items-by-folder */ async listItemsInFolder(folderId: FolderIdsEnum | number, sort?: SortOptions<UserSortEnum>, pagination?: Pagination) { const username = await this.getUsername() return this.listItemsInFolderForUser(username, folderId, sort, pagination) } /** * Add a release to a folder in authenticated user’s collection. * * @category User * @label Add To Collection Folder * * @link https://www.discogs.com/developers#page:user-collection,header:user-collection-add-to-collection-folder */ async addReleaseToFolder(releaseId: number, folderId: FolderIdsEnum | number = FolderIdsEnum.UNCATEGORIZED) { const username = await this.getUsername() return this.fetch<AddToFolderResponse>( `/users/${username}/collection/folders/${folderId}/releases/${releaseId}`, {}, HTTPVerbsEnum.POST, ) } /** * Change the rating on a release. * * @category User * @label Change Rating Of Release * * @link https://www.discogs.com/developers#page:user-collection,header:user-collection-change-rating-of-release */ async editReleaseInstanceRating( folderId: FolderIdsEnum | number, releaseId: number, instanceId: number, rating: RatingValues, ) { const username = await this.getUsername() return this.fetch<EmptyResponse>( `/users/${username}/collection/folders/${folderId}/releases/${releaseId}/instances/${instanceId}`, {}, HTTPVerbsEnum.POST, { rating }, ) } /** * Move the instance of a release to another folder. * * @category User * @label Change Rating Of Release * * @link https://www.discogs.com/developers#page:user-collection,header:user-collection-change-rating-of-release */ async moveReleaseInstanceToFolder( oldFolderId: FolderIdsEnum | number, releaseId: number, instanceId: number, newFolderId: FolderIdsEnum | number, ) { const username = await this.getUsername() return this.fetch<EmptyResponse>( `/users/${username}/collection/folders/${oldFolderId}/releases/${releaseId}/instances/${instanceId}`, {}, HTTPVerbsEnum.POST, { folderId: newFolderId }, ) } /** * Remove an instance of a release from authenticated user’s collection folder. * * @category User * @label Delete Instance From Folder * * @link https://www.discogs.com/developers#page:user-collection,header:user-collection-delete-instance-from-folder */ async deleteReleaseInstanceFromFolder(folderId: FolderIdsEnum | number, releaseId: number, instanceId: number) { const username = await this.getUsername() return this.fetch<EmptyResponse>( `/users/${username}/collection/folders/${folderId}/releases/${releaseId}/instances/${instanceId}`, {}, HTTPVerbsEnum.DELETE, ) } /** * Retrieve a list of user-defined collection notes fields. These fields are available on every release in the collection. * * @remarks * If the collection has been made private by its owner, authentication as the collection owner is required. * If you are not authenticated as the collection owner, only fields with `public` set to true will be visible. * * @category User * @label List Custom Fields * * @link https://www.discogs.com/developers#page:user-collection,header:user-collection-list-custom-fields */ async listCustomFieldsForUser(username: string) { return this.fetch<CustomFieldsResponse>(`/users/${username}/collection/fields`) } /** * Retrieve a list of authenticated user-defined collection notes fields. These fields are available on every release in the collection. * * @category User * @label List Custom Fields * * @link https://www.discogs.com/developers#page:user-collection,header:user-collection-list-custom-fields */ async listCustomFields() { const username = await this.getUsername() return this.listCustomFieldsForUser(username) } /** * Change the value of a notes field on a particular instance. * * @category User * @label Edit Fields Instance * * @link https://www.discogs.com/developers#page:user-collection,header:user-collection-edit-fields-instance */ async editCustomFieldForInstance( folderId: FolderIdsEnum | number, releaseId: number, instanceId: number, fieldId: number, value: string, ) { const username = await this.getUsername() return this.fetch<EmptyResponse>( `/users/${username}/collection/folders/${folderId}/releases/${releaseId}/instances/${instanceId}/fields/${fieldId}`, { value }, HTTPVerbsEnum.POST, ) } /** * Returns the minimum, median, and maximum value of authenticated user’s collection. * * @requires authentication * * @category User * @label Collection Value * * @link https://www.discogs.com/developers#page:user-collection,header:user-collection-collection-value */ async getCollectionValue() { const username = await this.getUsername() return this.fetch<CollectionValueResponse>(`/users/${username}/collection/value`) } /** * Returns the list of releases in a user’s wantlist. * Basic information about each release is provided, suitable for display in a list. * For detailed information, make another API call to fetch the corresponding release. * * @remarks * If the wantlist has been made private by its owner, you must be authenticated as the owner to view it. * The `notes` field will be visible if you are authenticated as the wantlist owner. * * @category User * @label Wantlist * * @link https://www.discogs.com/developers#page:user-wantlist,header:user-wantlist-wantlist */ async getWantlistForUser(username: string, pagination?: Pagination) { return this.fetch<WantlistResponse>(`/users/${username}/wants`, paginate(pagination)) } /** * Returns the list of releases in authenticated user’s wantlist. * Basic information about each release is provided, suitable for display in a list. * For detailed information, make another API call to fetch the corresponding release. * * @category User * @label Wantlist * * @link https://www.discogs.com/developers#page:user-wantlist,header:user-wantlist-wantlist */ async getWantlist(pagination?: Pagination) { const username = await this.getUsername() return this.getWantlistForUser(username, pagination) } /** * Add a release to authenticated user’s wantlist. * * @category User * @label Add to wantlist * * @link https://www.discogs.com/developers#page:user-wantlist,header:user-wantlist-add-to-wantlist */ async addToWantlist(releaseId: number, notes?: string, rating?: RatingValues) { const username = await this.getUsername() return this.fetch<AddToWantlistResponse>( `/users/${username}/wants/${releaseId}`, { notes, rating }, HTTPVerbsEnum.PUT, ) } /** * Remove a release to authenticated user’s wantlist. * * @category User * @label Add to wantlist * * @link https://www.discogs.com/developers#page:user-wantlist,header:user-wantlist-add-to-wantlist */ async removeFromWantlist(releaseId: number) { const username = await this.getUsername() return this.fetch<EmptyResponse>(`/users/${username}/wants/${releaseId}`, {}, HTTPVerbsEnum.DELETE) } /** * Returns user’s lists. * * @remarks * Private lists will only display when authenticated as the owner. * * @category User * @label Lists * * @link https://www.discogs.com/developers#page:user-lists,header:user-lists-user-lists */ async getListsForUser(username: string, pagination?: Pagination) { return this.fetch<UserListsResponse>(`/users/${username}/lists`, paginate(pagination)) } /** * Returns authenticated user’s lists. * * @category User * @label Lists * * @link https://www.discogs.com/developers#page:user-lists,header:user-lists-user-lists */ async getLists(pagination?: Pagination) { const username = await this.getUsername() return this.getListsForUser(username, pagination) } /** * Returns items from a specified list. * * @remarks * Private lists will only display when authenticated as the owner. * * @category User * @label Lists * * @link https://www.discogs.com/developers#page:user-lists,header:user-lists-user-lists */ async getListItems(listId: number) { return this.fetch<UserListItemsResponse>(`/lists/${listId}`) } /** * Issue a search query to Discogs database. * * @category Database * @label Search * * @link https://www.discogs.com/developers#page:database,header:database-search */ async searchDatabase(options: SearchOptions = {}, pagination?: Pagination) { return this.fetch<SearchResponse>('/database/search', { ...options, ...paginate(pagination) }) } /** * Search for a release. * * @category Database * @label Search * * @link https://www.discogs.com/developers#page:database,header:database-search */ async searchRelease(query: string, options: SearchOptions = {}, pagination?: Pagination) { return this.searchDatabase({ ...options, query, type: SearchTypeEnum.RELEASE }, pagination) } /** * Get a release. * * @category Database * @label Release * * @link https://www.discogs.com/developers#page:database,header:database-release */ async getRelease(releaseId: number, currency?: CurrenciesEnum) { return this.fetch<Release>(`/releases/${releaseId}`, { currency }) } /** * Retrieves the release’s rating for a given user. * * @category Database * @label Release Rating * * @link https://www.discogs.com/developers#page:database,header:database-release-rating-by-user */ async getReleaseRatingForUser(username: string, releaseId: number) { return this.fetch<ReleaseRatingResponse>(`/releases/${releaseId}/rating/${username}`) } /** * Retrieves the release’s rating for the authenticated user. * * @category Database * @label Release Rating * * @link https://www.discogs.com/developers#page:database,header:database-release-rating-by-user */ async getReleaseRating(releaseId: number) { const username = await this.getUsername() return this.getReleaseRatingForUser(username, releaseId) } /** * Updates the release’s rating for the authenticated user. * * @category Database * @label Release Rating * * @link https://www.discogs.com/developers#page:database,header:database-release-rating-by-user */ async updateReleaseRating(releaseId: number, rating: RatingValues) { const username = await this.getUsername() return this.fetch<ReleaseRatingResponse>(`/releases/${releaseId}/rating/${username}`, {}, HTTPVerbsEnum.PUT, { rating, }) } /** * Deletes the release’s rating for the authenticated user. * * @category Database * @label Release Rating * * @link https://www.discogs.com/developers#page:database,header:database-release-rating-by-user */ async deleteReleaseRating(releaseId: number) { const username = await this.getUsername() return this.fetch<EmptyResponse>(`/releases/${releaseId}/rating/${username}`, {}, HTTPVerbsEnum.DELETE) } /** * Retrieves the community release rating average and count. * * @category Database * @label Community Release Rating * * @link https://www.discogs.com/developers#page:database,header:database-community-release-rating */ async getCommunityReleaseRating(releaseId: number) { return this.fetch<CommunityReleaseRatingResponse>(`/releases/${releaseId}/rating`) } /** * Search for a master release. * * @category Database * @label Search * * @link https://www.discogs.com/developers#page:database,header:database-search */ async searchMaster(query: string, options: SearchOptions = {}, pagination?: Pagination) { return this.searchDatabase({ ...options, query, type: SearchTypeEnum.MASTER }, pagination) } /** * Get a master release. * * @category Database * @label Master Release * * @link https://www.discogs.com/developers#page:database,header:database-master-release */ async getMaster(masterId: number) { return this.fetch<Master>(`/masters/${masterId}`) } /** * Retrieves a list of all releases that are versions of a master. * * @category Database * @label Master Release Versions * * @link https://www.discogs.com/developers#page:database,header:database-master-release-versions */ // @TODO: There are a lot of parameters not handled here async getMasterVersions(masterId: number, pagination?: Pagination) { return this.fetch<MasterVersionsResponse>(`/masters/${masterId}/versions`, paginate(pagination)) } /** * Search for an artist. * * @category Database * @label Search * * @link https://www.discogs.com/developers#page:database,header:database-search */ async searchArtist(query: string, options: SearchOptions = {}, pagination?: Pagination) { return this.searchDatabase({ ...options, query, type: SearchTypeEnum.ARTIST }, pagination) } /** * Get an artist. * * @category Database * @label Artist * * @link https://www.discogs.com/developers#page:database,header:database-artist */ async getArtist(artistId: number) { return this.fetch<Artist>(`/artists/${artistId}`) } /** * Returns a list of releases and masters associated with an artist. * * @category Database * @label Artist Releases * * @link https://www.discogs.com/developers#page:database,header:database-artist-releases */ async getArtistReleases(artistId: number, sort?: SortOptions<ReleaseSortEnum>, pagination?: Pagination) { return this.fetch<ArtistReleasesResponse>(`/artists/${artistId}/releases`, { ...sortBy(ReleaseSortEnum.YEAR, sort), ...paginate(pagination), }) } /** * Search for a label. * * @category Database * @label Search * * @link https://www.discogs.com/developers#page:database,header:database-search */ async searchLabel(query: string, options: SearchOptions = {}, pagination?: Pagination) { return this.searchDatabase({ ...options, query, type: SearchTypeEnum.LABEL }, pagination) } /** * Get a label. * * @category Database * @label Label * * @link https://www.discogs.com/developers#page:database,header:database-label */ async getLabel(labelId: number) { return this.fetch<Label>(`/labels/${labelId}`) } /** * Returns a list of releases associated with the label. * * @category Database * @label Label Releases * * @link https://www.discogs.com/developers#page:database,header:database-all-label-releases */ async getLabelReleases(labelId: number, pagination?: Pagination) { return this.fetch<LabelReleasesResponse>(`/labels/${labelId}/releases`, paginate(pagination)) } /** * Get a seller’s inventory. * * @remarks * If you are not authenticated as the inventory owner, only items that have a status of For Sale will be visible. * If you are authenticated as the inventory owner you will get additional weight, format_quantity, external_id, and location keys. * If the user is authorized, the listing will contain a `in_cart` boolean field indicating whether or not this listing is in their cart. * * @category Marketplace * @label Inventory * * @link https://www.discogs.com/developers#page:marketplace,header:marketplace-inventory */ async getInventoryForUser( username: string, status: InventoryStatusesEnum = InventoryStatusesEnum.ALL, sort?: SortOptions<InventorySortEnum>, pagination?: Pagination, ) { return this.fetch<InventoryResponse>(`/users/${username}/inventory`, { status, ...sortBy(InventorySortEnum.LISTED, sort), ...paginate(pagination), }) } /** * Get authenticated user’s inventory. * * @category Marketplace * @label Inventory * * @link https://www.discogs.com/developers#page:marketplace,header:marketplace-inventory */ async getInventory(status?: InventoryStatusesEnum, sort?: SortOptions<InventorySortEnum>, pagination?: Pagination) { const username = await this.getUsername() return this.getInventoryForUser(username, status, sort, pagination) } /** * View the data associated with a listing. * * @remarks * If the authorized user is the listing owner the listing will include the weight, format_quantity, external_id, and location keys. * If the user is authorized, the listing will contain a in_cart boolean field indicating whether or not this listing is in their cart. * * @category Marketplace * @label Listing * * @link https://www.discogs.com/developers#page:marketplace,header:marketplace-listing */ async getListing(listingId: number, currency?: CurrenciesEnum) { return this.fetch<Listing>(`/marketplace/listings/${listingId}`, { currency }) } /** * Edit the data associated with a listing. * * @remarks * If the listing’s status is not For Sale, Draft, or Expired, it cannot be modified – only deleted. * * @category Marketplace * @label Listing * * @link https://www.discogs.com/developers#page:marketplace,header:marketplace-listing */ async editListing(listingId: number, options: ListingOptions, currency?: CurrenciesEnum) { return this.fetch<EmptyResponse>(`/marketplace/listings/${listingId}`, { currency }, HTTPVerbsEnum.POST, options) } /** * Permanently remove a listing from the Marketplace. * * @category Marketplace * @label Listing * * @link https://www.discogs.com/developers#page:marketplace,header:marketplace-listing */ async deleteListing(listingId: number) { return this.fetch<EmptyResponse>(`/marketplace/listings/${listingId}`, {}, HTTPVerbsEnum.DELETE) } /** * Create a Marketplace listing. * * @category Marketplace * @label Listing * * @link https://www.discogs.com/developers#page:marketplace,header:marketplace-new-listing */ async createListing(options: ListingOptions) { return this.fetch<CreateListingResponse>('/marketplace/listings/', {}, HTTPVerbsEnum.POST, options) } /** * View the data associated with an order. * * @category Marketplace * @label Order * * @link https://www.discogs.com/developers#page:marketplace,header:marketplace-order */ async getOrder(orderId: number) { return this.fetch<Order>(`/marketplace/orders/${orderId}`) } /** * Edit the data associated with an order. * * @category Marketplace * @label Order * * @link https://www.discogs.com/developers#page:marketplace,header:marketplace-order */ async editOrder(orderId: number, status?: EditOrderStatusesEnum, shipping?: number) { return this.fetch<Order>(`/marketplace/orders/${orderId}`, {}, HTTPVerbsEnum.POST, { status, shipping }) } /** * Returns a list of the authenticated user’s orders. * * @category Marketplace * @label Order * * @link https://www.discogs.com/developers#page:marketplace,header:marketplace-list-orders */ async listOrders( status?: OrderStatusesEnum, archived?: boolean, sort?: SortOptions<OrderSortEnum>, pagination?: Pagination, ) { return this.fetch<OrdersResponse>('/marketplace/orders', { status, archived, ...sortBy(OrderSortEnum.ID, sort), ...paginate(pagination), }) } /** * Returns a list of the order’s messages with the most recent first. * * @category Marketplace * @label Order Messages * * @link https://www.discogs.com/developers#page:marketplace,header:marketplace-list-order-messages */ async listOrderMessages(orderId: number) { return this.fetch<OrderMessagesResponse>(`/marketplace/orders/${orderId}/messages`) } /** * Adds a new message to the order’s message log. * * @remarks * When posting a new message, you can simultaneously change the order status. * If you do, the message will automatically be prepended with: "Seller changed status from `Old Status` to `New Status`" * While message and status are each optional, one or both must be present. * * @category Marketplace * @label Order Messages * * @link https://www.discogs.com/developers#page:marketplace,header:marketplace-list-order-messages */ async sendOrderMessage(orderId: number, message?: string, status?: OrderStatusesEnum) { return this.fetch<OrderMessage>(`/marketplace/orders/${orderId}/messages`, {}, HTTPVerbsEnum.POST, { message, status, }) } /** * The Fee resource allows you to quickly calculate the fee for selling an item on the Marketplace. * * @category Marketplace * @label Fee * * @link https://www.discogs.com/developers#page:marketplace,header:marketplace-fee */ async getFee(price: number, currency?: CurrenciesEnum) { let uri = `/marketplace/fee/${price}` if (currency) uri += `/${currency}` return this.fetch<Fee>(uri) } /** * Retrieve price suggestions for the provided Release ID. * * @remarks * Suggested prices will be denominated in the user’s selling currency. * * @category Marketplace * @label Price Suggestions * * @link https://www.discogs.com/developers#page:marketplace,header:marketplace-price-suggestions */ async getPriceSuggestions(releaseId: number) { return this.fetch<PriceSuggestionsResponse>(`/marketplace/price_suggestions/${releaseId}`) } /** * Retrieve marketplace statistics for the provided Release ID. * * @remarks * These statistics reflect the state of the release in the marketplace currently, and include the number of items currently for sale, * lowest listed price of any item for sale, and whether the item is blocked for sale in the marketplace. * * * @category Marketplace * @label Release Statistics * * @link https://www.discogs.com/developers#page:marketplace,header:marketplace-release-statistics */ async getMarketplaceStatistics(releaseId: number, currency?: CurrenciesEnum) { return this.fetch<MarketplaceStatisticsResponse>(`/marketplace/stats/${releaseId}`, { currency }) } /** * Retrieve an image retrieved in another response. * * @requires authentication * * @category Helpers * * @link https://www.discogs.com/developers#page:images */ async fetchImage(imageUrl: string) { return this.fetch<Blob>(imageUrl) } }
the_stack
import {Request} from '../lib/request'; import {Response} from '../lib/response'; import {AWSError} from '../lib/error'; import {Service} from '../lib/service'; import {ServiceConfigurationOptions} from '../lib/service'; import {ConfigBase as Config} from '../lib/config-base'; interface Blob {} declare class MediaPackageVod extends Service { /** * Constructs a service object. This object has one method for each API operation. */ constructor(options?: MediaPackageVod.Types.ClientConfiguration) config: Config & MediaPackageVod.Types.ClientConfiguration; /** * Changes the packaging group's properities to configure log subscription */ configureLogs(params: MediaPackageVod.Types.ConfigureLogsRequest, callback?: (err: AWSError, data: MediaPackageVod.Types.ConfigureLogsResponse) => void): Request<MediaPackageVod.Types.ConfigureLogsResponse, AWSError>; /** * Changes the packaging group's properities to configure log subscription */ configureLogs(callback?: (err: AWSError, data: MediaPackageVod.Types.ConfigureLogsResponse) => void): Request<MediaPackageVod.Types.ConfigureLogsResponse, AWSError>; /** * Creates a new MediaPackage VOD Asset resource. */ createAsset(params: MediaPackageVod.Types.CreateAssetRequest, callback?: (err: AWSError, data: MediaPackageVod.Types.CreateAssetResponse) => void): Request<MediaPackageVod.Types.CreateAssetResponse, AWSError>; /** * Creates a new MediaPackage VOD Asset resource. */ createAsset(callback?: (err: AWSError, data: MediaPackageVod.Types.CreateAssetResponse) => void): Request<MediaPackageVod.Types.CreateAssetResponse, AWSError>; /** * Creates a new MediaPackage VOD PackagingConfiguration resource. */ createPackagingConfiguration(params: MediaPackageVod.Types.CreatePackagingConfigurationRequest, callback?: (err: AWSError, data: MediaPackageVod.Types.CreatePackagingConfigurationResponse) => void): Request<MediaPackageVod.Types.CreatePackagingConfigurationResponse, AWSError>; /** * Creates a new MediaPackage VOD PackagingConfiguration resource. */ createPackagingConfiguration(callback?: (err: AWSError, data: MediaPackageVod.Types.CreatePackagingConfigurationResponse) => void): Request<MediaPackageVod.Types.CreatePackagingConfigurationResponse, AWSError>; /** * Creates a new MediaPackage VOD PackagingGroup resource. */ createPackagingGroup(params: MediaPackageVod.Types.CreatePackagingGroupRequest, callback?: (err: AWSError, data: MediaPackageVod.Types.CreatePackagingGroupResponse) => void): Request<MediaPackageVod.Types.CreatePackagingGroupResponse, AWSError>; /** * Creates a new MediaPackage VOD PackagingGroup resource. */ createPackagingGroup(callback?: (err: AWSError, data: MediaPackageVod.Types.CreatePackagingGroupResponse) => void): Request<MediaPackageVod.Types.CreatePackagingGroupResponse, AWSError>; /** * Deletes an existing MediaPackage VOD Asset resource. */ deleteAsset(params: MediaPackageVod.Types.DeleteAssetRequest, callback?: (err: AWSError, data: MediaPackageVod.Types.DeleteAssetResponse) => void): Request<MediaPackageVod.Types.DeleteAssetResponse, AWSError>; /** * Deletes an existing MediaPackage VOD Asset resource. */ deleteAsset(callback?: (err: AWSError, data: MediaPackageVod.Types.DeleteAssetResponse) => void): Request<MediaPackageVod.Types.DeleteAssetResponse, AWSError>; /** * Deletes a MediaPackage VOD PackagingConfiguration resource. */ deletePackagingConfiguration(params: MediaPackageVod.Types.DeletePackagingConfigurationRequest, callback?: (err: AWSError, data: MediaPackageVod.Types.DeletePackagingConfigurationResponse) => void): Request<MediaPackageVod.Types.DeletePackagingConfigurationResponse, AWSError>; /** * Deletes a MediaPackage VOD PackagingConfiguration resource. */ deletePackagingConfiguration(callback?: (err: AWSError, data: MediaPackageVod.Types.DeletePackagingConfigurationResponse) => void): Request<MediaPackageVod.Types.DeletePackagingConfigurationResponse, AWSError>; /** * Deletes a MediaPackage VOD PackagingGroup resource. */ deletePackagingGroup(params: MediaPackageVod.Types.DeletePackagingGroupRequest, callback?: (err: AWSError, data: MediaPackageVod.Types.DeletePackagingGroupResponse) => void): Request<MediaPackageVod.Types.DeletePackagingGroupResponse, AWSError>; /** * Deletes a MediaPackage VOD PackagingGroup resource. */ deletePackagingGroup(callback?: (err: AWSError, data: MediaPackageVod.Types.DeletePackagingGroupResponse) => void): Request<MediaPackageVod.Types.DeletePackagingGroupResponse, AWSError>; /** * Returns a description of a MediaPackage VOD Asset resource. */ describeAsset(params: MediaPackageVod.Types.DescribeAssetRequest, callback?: (err: AWSError, data: MediaPackageVod.Types.DescribeAssetResponse) => void): Request<MediaPackageVod.Types.DescribeAssetResponse, AWSError>; /** * Returns a description of a MediaPackage VOD Asset resource. */ describeAsset(callback?: (err: AWSError, data: MediaPackageVod.Types.DescribeAssetResponse) => void): Request<MediaPackageVod.Types.DescribeAssetResponse, AWSError>; /** * Returns a description of a MediaPackage VOD PackagingConfiguration resource. */ describePackagingConfiguration(params: MediaPackageVod.Types.DescribePackagingConfigurationRequest, callback?: (err: AWSError, data: MediaPackageVod.Types.DescribePackagingConfigurationResponse) => void): Request<MediaPackageVod.Types.DescribePackagingConfigurationResponse, AWSError>; /** * Returns a description of a MediaPackage VOD PackagingConfiguration resource. */ describePackagingConfiguration(callback?: (err: AWSError, data: MediaPackageVod.Types.DescribePackagingConfigurationResponse) => void): Request<MediaPackageVod.Types.DescribePackagingConfigurationResponse, AWSError>; /** * Returns a description of a MediaPackage VOD PackagingGroup resource. */ describePackagingGroup(params: MediaPackageVod.Types.DescribePackagingGroupRequest, callback?: (err: AWSError, data: MediaPackageVod.Types.DescribePackagingGroupResponse) => void): Request<MediaPackageVod.Types.DescribePackagingGroupResponse, AWSError>; /** * Returns a description of a MediaPackage VOD PackagingGroup resource. */ describePackagingGroup(callback?: (err: AWSError, data: MediaPackageVod.Types.DescribePackagingGroupResponse) => void): Request<MediaPackageVod.Types.DescribePackagingGroupResponse, AWSError>; /** * Returns a collection of MediaPackage VOD Asset resources. */ listAssets(params: MediaPackageVod.Types.ListAssetsRequest, callback?: (err: AWSError, data: MediaPackageVod.Types.ListAssetsResponse) => void): Request<MediaPackageVod.Types.ListAssetsResponse, AWSError>; /** * Returns a collection of MediaPackage VOD Asset resources. */ listAssets(callback?: (err: AWSError, data: MediaPackageVod.Types.ListAssetsResponse) => void): Request<MediaPackageVod.Types.ListAssetsResponse, AWSError>; /** * Returns a collection of MediaPackage VOD PackagingConfiguration resources. */ listPackagingConfigurations(params: MediaPackageVod.Types.ListPackagingConfigurationsRequest, callback?: (err: AWSError, data: MediaPackageVod.Types.ListPackagingConfigurationsResponse) => void): Request<MediaPackageVod.Types.ListPackagingConfigurationsResponse, AWSError>; /** * Returns a collection of MediaPackage VOD PackagingConfiguration resources. */ listPackagingConfigurations(callback?: (err: AWSError, data: MediaPackageVod.Types.ListPackagingConfigurationsResponse) => void): Request<MediaPackageVod.Types.ListPackagingConfigurationsResponse, AWSError>; /** * Returns a collection of MediaPackage VOD PackagingGroup resources. */ listPackagingGroups(params: MediaPackageVod.Types.ListPackagingGroupsRequest, callback?: (err: AWSError, data: MediaPackageVod.Types.ListPackagingGroupsResponse) => void): Request<MediaPackageVod.Types.ListPackagingGroupsResponse, AWSError>; /** * Returns a collection of MediaPackage VOD PackagingGroup resources. */ listPackagingGroups(callback?: (err: AWSError, data: MediaPackageVod.Types.ListPackagingGroupsResponse) => void): Request<MediaPackageVod.Types.ListPackagingGroupsResponse, AWSError>; /** * Returns a list of the tags assigned to the specified resource. */ listTagsForResource(params: MediaPackageVod.Types.ListTagsForResourceRequest, callback?: (err: AWSError, data: MediaPackageVod.Types.ListTagsForResourceResponse) => void): Request<MediaPackageVod.Types.ListTagsForResourceResponse, AWSError>; /** * Returns a list of the tags assigned to the specified resource. */ listTagsForResource(callback?: (err: AWSError, data: MediaPackageVod.Types.ListTagsForResourceResponse) => void): Request<MediaPackageVod.Types.ListTagsForResourceResponse, AWSError>; /** * Adds tags to the specified resource. You can specify one or more tags to add. */ tagResource(params: MediaPackageVod.Types.TagResourceRequest, callback?: (err: AWSError, data: {}) => void): Request<{}, AWSError>; /** * Adds tags to the specified resource. You can specify one or more tags to add. */ tagResource(callback?: (err: AWSError, data: {}) => void): Request<{}, AWSError>; /** * Removes tags from the specified resource. You can specify one or more tags to remove. */ untagResource(params: MediaPackageVod.Types.UntagResourceRequest, callback?: (err: AWSError, data: {}) => void): Request<{}, AWSError>; /** * Removes tags from the specified resource. You can specify one or more tags to remove. */ untagResource(callback?: (err: AWSError, data: {}) => void): Request<{}, AWSError>; /** * Updates a specific packaging group. You can't change the id attribute or any other system-generated attributes. */ updatePackagingGroup(params: MediaPackageVod.Types.UpdatePackagingGroupRequest, callback?: (err: AWSError, data: MediaPackageVod.Types.UpdatePackagingGroupResponse) => void): Request<MediaPackageVod.Types.UpdatePackagingGroupResponse, AWSError>; /** * Updates a specific packaging group. You can't change the id attribute or any other system-generated attributes. */ updatePackagingGroup(callback?: (err: AWSError, data: MediaPackageVod.Types.UpdatePackagingGroupResponse) => void): Request<MediaPackageVod.Types.UpdatePackagingGroupResponse, AWSError>; } declare namespace MediaPackageVod { export type AdMarkers = "NONE"|"SCTE35_ENHANCED"|"PASSTHROUGH"|string; export interface AssetShallow { /** * The ARN of the Asset. */ Arn?: __string; /** * The time the Asset was initially submitted for Ingest. */ CreatedAt?: __string; /** * The unique identifier for the Asset. */ Id?: __string; /** * The ID of the PackagingGroup for the Asset. */ PackagingGroupId?: __string; /** * The resource ID to include in SPEKE key requests. */ ResourceId?: __string; /** * ARN of the source object in S3. */ SourceArn?: __string; /** * The IAM role ARN used to access the source S3 bucket. */ SourceRoleArn?: __string; Tags?: Tags; } export interface Authorization { /** * The Amazon Resource Name (ARN) for the secret in AWS Secrets Manager that is used for CDN authorization. */ CdnIdentifierSecret: __string; /** * The Amazon Resource Name (ARN) for the IAM role that allows MediaPackage to communicate with AWS Secrets Manager. */ SecretsRoleArn: __string; } export interface CmafEncryption { /** * An optional 128-bit, 16-byte hex value represented by a 32-character string, used in conjunction with the key for encrypting blocks. If you don't specify a value, then MediaPackage creates the constant initialization vector (IV). */ ConstantInitializationVector?: __string; SpekeKeyProvider: SpekeKeyProvider; } export interface CmafPackage { Encryption?: CmafEncryption; /** * A list of HLS manifest configurations. */ HlsManifests: __listOfHlsManifest; /** * When includeEncoderConfigurationInSegments is set to true, MediaPackage places your encoder's Sequence Parameter Set (SPS), Picture Parameter Set (PPS), and Video Parameter Set (VPS) metadata in every video segment instead of in the init fragment. This lets you use different SPS/PPS/VPS settings for your assets during content playback. */ IncludeEncoderConfigurationInSegments?: __boolean; /** * Duration (in seconds) of each fragment. Actual fragments will be rounded to the nearest multiple of the source fragment duration. */ SegmentDurationSeconds?: __integer; } export interface ConfigureLogsRequest { EgressAccessLogs?: EgressAccessLogs; /** * The ID of a MediaPackage VOD PackagingGroup resource. */ Id: __string; } export interface ConfigureLogsResponse { /** * The ARN of the PackagingGroup. */ Arn?: __string; Authorization?: Authorization; /** * The fully qualified domain name for Assets in the PackagingGroup. */ DomainName?: __string; EgressAccessLogs?: EgressAccessLogs; /** * The ID of the PackagingGroup. */ Id?: __string; Tags?: Tags; } export interface CreateAssetRequest { /** * The unique identifier for the Asset. */ Id: __string; /** * The ID of the PackagingGroup for the Asset. */ PackagingGroupId: __string; /** * The resource ID to include in SPEKE key requests. */ ResourceId?: __string; /** * ARN of the source object in S3. */ SourceArn: __string; /** * The IAM role ARN used to access the source S3 bucket. */ SourceRoleArn: __string; Tags?: Tags; } export interface CreateAssetResponse { /** * The ARN of the Asset. */ Arn?: __string; /** * The time the Asset was initially submitted for Ingest. */ CreatedAt?: __string; /** * The list of egress endpoints available for the Asset. */ EgressEndpoints?: __listOfEgressEndpoint; /** * The unique identifier for the Asset. */ Id?: __string; /** * The ID of the PackagingGroup for the Asset. */ PackagingGroupId?: __string; /** * The resource ID to include in SPEKE key requests. */ ResourceId?: __string; /** * ARN of the source object in S3. */ SourceArn?: __string; /** * The IAM role_arn used to access the source S3 bucket. */ SourceRoleArn?: __string; Tags?: Tags; } export interface CreatePackagingConfigurationRequest { CmafPackage?: CmafPackage; DashPackage?: DashPackage; HlsPackage?: HlsPackage; /** * The ID of the PackagingConfiguration. */ Id: __string; MssPackage?: MssPackage; /** * The ID of a PackagingGroup. */ PackagingGroupId: __string; Tags?: Tags; } export interface CreatePackagingConfigurationResponse { /** * The ARN of the PackagingConfiguration. */ Arn?: __string; CmafPackage?: CmafPackage; DashPackage?: DashPackage; HlsPackage?: HlsPackage; /** * The ID of the PackagingConfiguration. */ Id?: __string; MssPackage?: MssPackage; /** * The ID of a PackagingGroup. */ PackagingGroupId?: __string; Tags?: Tags; } export interface CreatePackagingGroupRequest { Authorization?: Authorization; EgressAccessLogs?: EgressAccessLogs; /** * The ID of the PackagingGroup. */ Id: __string; Tags?: Tags; } export interface CreatePackagingGroupResponse { /** * The ARN of the PackagingGroup. */ Arn?: __string; Authorization?: Authorization; /** * The fully qualified domain name for Assets in the PackagingGroup. */ DomainName?: __string; EgressAccessLogs?: EgressAccessLogs; /** * The ID of the PackagingGroup. */ Id?: __string; Tags?: Tags; } export interface DashEncryption { SpekeKeyProvider: SpekeKeyProvider; } export interface DashManifest { /** * Determines the position of some tags in the Media Presentation Description (MPD). When set to FULL, elements like SegmentTemplate and ContentProtection are included in each Representation. When set to COMPACT, duplicate elements are combined and presented at the AdaptationSet level. */ ManifestLayout?: ManifestLayout; /** * An optional string to include in the name of the manifest. */ ManifestName?: __string; /** * Minimum duration (in seconds) that a player will buffer media before starting the presentation. */ MinBufferTimeSeconds?: __integer; /** * The Dynamic Adaptive Streaming over HTTP (DASH) profile type. When set to "HBBTV_1_5", HbbTV 1.5 compliant output is enabled. */ Profile?: Profile; StreamSelection?: StreamSelection; } export interface DashPackage { /** * A list of DASH manifest configurations. */ DashManifests: __listOfDashManifest; Encryption?: DashEncryption; /** * When includeEncoderConfigurationInSegments is set to true, MediaPackage places your encoder's Sequence Parameter Set (SPS), Picture Parameter Set (PPS), and Video Parameter Set (VPS) metadata in every video segment instead of in the init fragment. This lets you use different SPS/PPS/VPS settings for your assets during content playback. */ IncludeEncoderConfigurationInSegments?: __boolean; /** * A list of triggers that controls when the outgoing Dynamic Adaptive Streaming over HTTP (DASH) Media Presentation Description (MPD) will be partitioned into multiple periods. If empty, the content will not be partitioned into more than one period. If the list contains "ADS", new periods will be created where the Asset contains SCTE-35 ad markers. */ PeriodTriggers?: __listOf__PeriodTriggersElement; /** * Duration (in seconds) of each segment. Actual segments will be rounded to the nearest multiple of the source segment duration. */ SegmentDurationSeconds?: __integer; /** * Determines the type of SegmentTemplate included in the Media Presentation Description (MPD). When set to NUMBER_WITH_TIMELINE, a full timeline is presented in each SegmentTemplate, with $Number$ media URLs. When set to TIME_WITH_TIMELINE, a full timeline is presented in each SegmentTemplate, with $Time$ media URLs. When set to NUMBER_WITH_DURATION, only a duration is included in each SegmentTemplate, with $Number$ media URLs. */ SegmentTemplateFormat?: SegmentTemplateFormat; } export interface DeleteAssetRequest { /** * The ID of the MediaPackage VOD Asset resource to delete. */ Id: __string; } export interface DeleteAssetResponse { } export interface DeletePackagingConfigurationRequest { /** * The ID of the MediaPackage VOD PackagingConfiguration resource to delete. */ Id: __string; } export interface DeletePackagingConfigurationResponse { } export interface DeletePackagingGroupRequest { /** * The ID of the MediaPackage VOD PackagingGroup resource to delete. */ Id: __string; } export interface DeletePackagingGroupResponse { } export interface DescribeAssetRequest { /** * The ID of an MediaPackage VOD Asset resource. */ Id: __string; } export interface DescribeAssetResponse { /** * The ARN of the Asset. */ Arn?: __string; /** * The time the Asset was initially submitted for Ingest. */ CreatedAt?: __string; /** * The list of egress endpoints available for the Asset. */ EgressEndpoints?: __listOfEgressEndpoint; /** * The unique identifier for the Asset. */ Id?: __string; /** * The ID of the PackagingGroup for the Asset. */ PackagingGroupId?: __string; /** * The resource ID to include in SPEKE key requests. */ ResourceId?: __string; /** * ARN of the source object in S3. */ SourceArn?: __string; /** * The IAM role_arn used to access the source S3 bucket. */ SourceRoleArn?: __string; Tags?: Tags; } export interface DescribePackagingConfigurationRequest { /** * The ID of a MediaPackage VOD PackagingConfiguration resource. */ Id: __string; } export interface DescribePackagingConfigurationResponse { /** * The ARN of the PackagingConfiguration. */ Arn?: __string; CmafPackage?: CmafPackage; DashPackage?: DashPackage; HlsPackage?: HlsPackage; /** * The ID of the PackagingConfiguration. */ Id?: __string; MssPackage?: MssPackage; /** * The ID of a PackagingGroup. */ PackagingGroupId?: __string; Tags?: Tags; } export interface DescribePackagingGroupRequest { /** * The ID of a MediaPackage VOD PackagingGroup resource. */ Id: __string; } export interface DescribePackagingGroupResponse { /** * The ARN of the PackagingGroup. */ Arn?: __string; Authorization?: Authorization; /** * The fully qualified domain name for Assets in the PackagingGroup. */ DomainName?: __string; EgressAccessLogs?: EgressAccessLogs; /** * The ID of the PackagingGroup. */ Id?: __string; Tags?: Tags; } export interface EgressAccessLogs { /** * Customize the log group name. */ LogGroupName?: __string; } export interface EgressEndpoint { /** * The ID of the PackagingConfiguration being applied to the Asset. */ PackagingConfigurationId?: __string; /** * The current processing status of the asset used for the packaging configuration. The status can be either QUEUED, PROCESSING, PLAYABLE, or FAILED. Status information won't be available for most assets ingested before 2021-09-30. */ Status?: __string; /** * The URL of the parent manifest for the repackaged Asset. */ Url?: __string; } export type EncryptionMethod = "AES_128"|"SAMPLE_AES"|string; export interface HlsEncryption { /** * A constant initialization vector for encryption (optional). When not specified the initialization vector will be periodically rotated. */ ConstantInitializationVector?: __string; /** * The encryption method to use. */ EncryptionMethod?: EncryptionMethod; SpekeKeyProvider: SpekeKeyProvider; } export interface HlsManifest { /** * This setting controls how ad markers are included in the packaged OriginEndpoint. "NONE" will omit all SCTE-35 ad markers from the output. "PASSTHROUGH" causes the manifest to contain a copy of the SCTE-35 ad markers (comments) taken directly from the input HTTP Live Streaming (HLS) manifest. "SCTE35_ENHANCED" generates ad markers and blackout tags based on SCTE-35 messages in the input source. */ AdMarkers?: AdMarkers; /** * When enabled, an I-Frame only stream will be included in the output. */ IncludeIframeOnlyStream?: __boolean; /** * An optional string to include in the name of the manifest. */ ManifestName?: __string; /** * The interval (in seconds) between each EXT-X-PROGRAM-DATE-TIME tag inserted into manifests. Additionally, when an interval is specified ID3Timed Metadata messages will be generated every 5 seconds using the ingest time of the content. If the interval is not specified, or set to 0, then no EXT-X-PROGRAM-DATE-TIME tags will be inserted into manifests and no ID3Timed Metadata messages will be generated. Note that irrespective of this parameter, if any ID3 Timed Metadata is found in HTTP Live Streaming (HLS) input, it will be passed through to HLS output. */ ProgramDateTimeIntervalSeconds?: __integer; /** * When enabled, the EXT-X-KEY tag will be repeated in output manifests. */ RepeatExtXKey?: __boolean; StreamSelection?: StreamSelection; } export interface HlsPackage { Encryption?: HlsEncryption; /** * A list of HLS manifest configurations. */ HlsManifests: __listOfHlsManifest; /** * When enabled, MediaPackage passes through digital video broadcasting (DVB) subtitles into the output. */ IncludeDvbSubtitles?: __boolean; /** * Duration (in seconds) of each fragment. Actual fragments will be rounded to the nearest multiple of the source fragment duration. */ SegmentDurationSeconds?: __integer; /** * When enabled, audio streams will be placed in rendition groups in the output. */ UseAudioRenditionGroup?: __boolean; } export interface ListAssetsRequest { /** * Upper bound on number of records to return. */ MaxResults?: MaxResults; /** * A token used to resume pagination from the end of a previous request. */ NextToken?: __string; /** * Returns Assets associated with the specified PackagingGroup. */ PackagingGroupId?: __string; } export interface ListAssetsResponse { /** * A list of MediaPackage VOD Asset resources. */ Assets?: __listOfAssetShallow; /** * A token that can be used to resume pagination from the end of the collection. */ NextToken?: __string; } export interface ListPackagingConfigurationsRequest { /** * Upper bound on number of records to return. */ MaxResults?: MaxResults; /** * A token used to resume pagination from the end of a previous request. */ NextToken?: __string; /** * Returns MediaPackage VOD PackagingConfigurations associated with the specified PackagingGroup. */ PackagingGroupId?: __string; } export interface ListPackagingConfigurationsResponse { /** * A token that can be used to resume pagination from the end of the collection. */ NextToken?: __string; /** * A list of MediaPackage VOD PackagingConfiguration resources. */ PackagingConfigurations?: __listOfPackagingConfiguration; } export interface ListPackagingGroupsRequest { /** * Upper bound on number of records to return. */ MaxResults?: MaxResults; /** * A token used to resume pagination from the end of a previous request. */ NextToken?: __string; } export interface ListPackagingGroupsResponse { /** * A token that can be used to resume pagination from the end of the collection. */ NextToken?: __string; /** * A list of MediaPackage VOD PackagingGroup resources. */ PackagingGroups?: __listOfPackagingGroup; } export interface ListTagsForResourceRequest { /** * The Amazon Resource Name (ARN) for the resource. You can get this from the response to any request to the resource. */ ResourceArn: __string; } export interface ListTagsForResourceResponse { /** * A collection of tags associated with a resource */ Tags?: __mapOf__string; } export type ManifestLayout = "FULL"|"COMPACT"|string; export type MaxResults = number; export interface MssEncryption { SpekeKeyProvider: SpekeKeyProvider; } export interface MssManifest { /** * An optional string to include in the name of the manifest. */ ManifestName?: __string; StreamSelection?: StreamSelection; } export interface MssPackage { Encryption?: MssEncryption; /** * A list of MSS manifest configurations. */ MssManifests: __listOfMssManifest; /** * The duration (in seconds) of each segment. */ SegmentDurationSeconds?: __integer; } export interface PackagingConfiguration { /** * The ARN of the PackagingConfiguration. */ Arn?: __string; CmafPackage?: CmafPackage; DashPackage?: DashPackage; HlsPackage?: HlsPackage; /** * The ID of the PackagingConfiguration. */ Id?: __string; MssPackage?: MssPackage; /** * The ID of a PackagingGroup. */ PackagingGroupId?: __string; Tags?: Tags; } export interface PackagingGroup { /** * The ARN of the PackagingGroup. */ Arn?: __string; Authorization?: Authorization; /** * The fully qualified domain name for Assets in the PackagingGroup. */ DomainName?: __string; EgressAccessLogs?: EgressAccessLogs; /** * The ID of the PackagingGroup. */ Id?: __string; Tags?: Tags; } export type Profile = "NONE"|"HBBTV_1_5"|string; export type SegmentTemplateFormat = "NUMBER_WITH_TIMELINE"|"TIME_WITH_TIMELINE"|"NUMBER_WITH_DURATION"|string; export interface SpekeKeyProvider { /** * An Amazon Resource Name (ARN) of an IAM role that AWS Elemental MediaPackage will assume when accessing the key provider service. */ RoleArn: __string; /** * The system IDs to include in key requests. */ SystemIds: __listOf__string; /** * The URL of the external key provider service. */ Url: __string; } export type StreamOrder = "ORIGINAL"|"VIDEO_BITRATE_ASCENDING"|"VIDEO_BITRATE_DESCENDING"|string; export interface StreamSelection { /** * The maximum video bitrate (bps) to include in output. */ MaxVideoBitsPerSecond?: __integer; /** * The minimum video bitrate (bps) to include in output. */ MinVideoBitsPerSecond?: __integer; /** * A directive that determines the order of streams in the output. */ StreamOrder?: StreamOrder; } export interface TagResourceRequest { /** * The Amazon Resource Name (ARN) for the resource. You can get this from the response to any request to the resource. */ ResourceArn: __string; /** * A collection of tags associated with a resource */ Tags: __mapOf__string; } export type Tags = {[key: string]: __string}; export interface UntagResourceRequest { /** * The Amazon Resource Name (ARN) for the resource. You can get this from the response to any request to the resource. */ ResourceArn: __string; /** * A comma-separated list of the tag keys to remove from the resource. */ TagKeys: __listOf__string; } export interface UpdatePackagingGroupRequest { Authorization?: Authorization; /** * The ID of a MediaPackage VOD PackagingGroup resource. */ Id: __string; } export interface UpdatePackagingGroupResponse { /** * The ARN of the PackagingGroup. */ Arn?: __string; Authorization?: Authorization; /** * The fully qualified domain name for Assets in the PackagingGroup. */ DomainName?: __string; EgressAccessLogs?: EgressAccessLogs; /** * The ID of the PackagingGroup. */ Id?: __string; Tags?: Tags; } export type __PeriodTriggersElement = "ADS"|string; export type __boolean = boolean; export type __integer = number; export type __listOfAssetShallow = AssetShallow[]; export type __listOfDashManifest = DashManifest[]; export type __listOfEgressEndpoint = EgressEndpoint[]; export type __listOfHlsManifest = HlsManifest[]; export type __listOfMssManifest = MssManifest[]; export type __listOfPackagingConfiguration = PackagingConfiguration[]; export type __listOfPackagingGroup = PackagingGroup[]; export type __listOf__PeriodTriggersElement = __PeriodTriggersElement[]; export type __listOf__string = __string[]; export type __mapOf__string = {[key: string]: __string}; export type __string = string; /** * A string in YYYY-MM-DD format that represents the latest possible API version that can be used in this service. Specify 'latest' to use the latest possible version. */ export type apiVersion = "2018-11-07"|"latest"|string; export interface ClientApiVersions { /** * A string in YYYY-MM-DD format that represents the latest possible API version that can be used in this service. Specify 'latest' to use the latest possible version. */ apiVersion?: apiVersion; } export type ClientConfiguration = ServiceConfigurationOptions & ClientApiVersions; /** * Contains interfaces for use with the MediaPackageVod client. */ export import Types = MediaPackageVod; } export = MediaPackageVod;
the_stack
import type { ChattyHostConnection } from '@looker/chatty' import intersects from 'semver/ranges/intersects' import { FetchProxyImpl } from './fetch_proxy' import type { ExtensionInitializationResponse, ExtensionHostApi, ExtensionHostApiConfiguration, ExtensionNotification, FetchCustomParameters, FetchResponseBodyType, LookerHostData, ApiVersion, RouteChangeData, } from './types' import { ExtensionEvent, ExtensionNotificationType, ExtensionRequestType, } from './types' export const EXTENSION_SDK_VERSION = '0.10.5' export class ExtensionHostApiImpl implements ExtensionHostApi { private _configuration: ExtensionHostApiConfiguration private _lookerHostData?: Readonly<LookerHostData> private chattyHost: ChattyHostConnection private setInitialRoute?: (route: string, routeState?: any) => void private hostChangedRoute?: (route: string, routeState?: any) => void private contextData?: string constructor(configuration: ExtensionHostApiConfiguration) { this._configuration = configuration const { chattyHost, setInitialRoute, hostChangedRoute } = this._configuration this.chattyHost = chattyHost this.setInitialRoute = setInitialRoute this.hostChangedRoute = hostChangedRoute } get lookerHostData() { return this._lookerHostData } handleNotification( message?: ExtensionNotification ): ExtensionInitializationResponse | undefined { const { type, payload } = message || {} switch (type) { case ExtensionNotificationType.ROUTE_CHANGED: if (this.hostChangedRoute && payload) { const { route, routeState } = payload as RouteChangeData if (route) { this.hostChangedRoute(route, routeState) } } return undefined case ExtensionNotificationType.INITIALIZE: { this._lookerHostData = payload as LookerHostData if (this._lookerHostData) { this.contextData = this._lookerHostData.contextData } let errorMessage if ( this._configuration.requiredLookerVersion && this._lookerHostData && this._lookerHostData.lookerVersion ) { errorMessage = this.verifyLookerVersion( this._configuration.requiredLookerVersion ) if (errorMessage) { console.error(errorMessage) } } if (this.setInitialRoute && payload) { const { route, routeState } = payload as LookerHostData if (route) { this.setInitialRoute(route, routeState) } } return { extensionSdkVersion: EXTENSION_SDK_VERSION, errorMessage, } } default: console.error('Unrecognized extension notification', message) throw new Error(`Unrecognized extension notification type ${type}`) } } createSecretKeyTag(keyName: string): string { const errorMessage = this.verifyLookerVersion('>=7.11') if (errorMessage) { throw new Error(errorMessage) } if (!keyName.match(/^[A-Za-z0-9_.]+$/)) { throw new Error('Unsupported characters in key name') } return `{{${this._lookerHostData!.extensionId.replace( /::|-/g, '_' )}_${keyName}}}` } async verifyHostConnection() { return this.sendAndReceive(ExtensionRequestType.VERIFY_HOST) } async invokeCoreSdk( httpMethod: string, path: string, params?: any, body?: any, authenticator?: any, options?: any, apiVersion?: ApiVersion ): Promise<any> { return this.sendAndReceive(ExtensionRequestType.INVOKE_CORE_SDK, { httpMethod, path, params, body, authenticator, options, apiVersion, }) } async invokeCoreSdkRaw( httpMethod: string, path: string, params?: any, body?: any, apiVersion?: ApiVersion ): Promise<any> { return this.sendAndReceive(ExtensionRequestType.RAW_INVOKE_CORE_SDK, { httpMethod, path, params, body, apiVersion, }) } updateTitle(title: string) { this.send(ExtensionRequestType.UPDATE_TITLE, { title }) } updateLocation(url: string, state?: any, target?: string) { this.send(ExtensionRequestType.UPDATE_LOCATION, { url, state, target }) } spartanLogout() { this.send(ExtensionRequestType.SPARTAN_LOGOUT) } openBrowserWindow(url: string, target?: string) { this.send(ExtensionRequestType.UPDATE_LOCATION, { url, undefined, target: target || '_blank', }) } closeHostPopovers() { this.send(ExtensionRequestType.CLOSE_HOST_POPOVERS) } clientRouteChanged(route: string, routeState?: any) { this.send(ExtensionRequestType.ROUTE_CHANGED, { route, routeState, }) } async localStorageSetItem(name: string, value = ''): Promise<boolean> { if (this._lookerHostData && !this._lookerHostData.lookerVersion) { return Promise.reject( new Error( 'localStorageSetItem not supported by the current Looker host' ) ) } return this.sendAndReceive(ExtensionRequestType.LOCAL_STORAGE, { type: 'set', name, value, }) } async localStorageGetItem(name: string): Promise<string | null> { if (this._lookerHostData && !this._lookerHostData.lookerVersion) { return Promise.reject( new Error( 'localStorageGetItem not supported by the current Looker host' ) ) } return this.sendAndReceive(ExtensionRequestType.LOCAL_STORAGE, { type: 'get', name, }) } async localStorageRemoveItem(name: string): Promise<boolean> { if (this._lookerHostData && !this._lookerHostData.lookerVersion) { return Promise.reject( new Error( 'localStorageRemoveItem not supported by the current Looker host' ) ) } return this.sendAndReceive(ExtensionRequestType.LOCAL_STORAGE, { type: 'remove', name, }) } async clipboardWrite(value: string): Promise<void> { const errorMessage = this.verifyLookerVersion('>=21.7') if (errorMessage) { return Promise.reject(new Error(errorMessage)) } return this.sendAndReceive(ExtensionRequestType.CLIPBOARD, { type: 'write', value, }) } async userAttributeSetItem(name: string, value = ''): Promise<boolean> { // User attributes added in Looker version 7.13, updated in 7.15 const errorMessage = this.verifyLookerVersion('>=7.15') if (errorMessage) { return Promise.reject(new Error(errorMessage)) } return this.sendAndReceive(ExtensionRequestType.USER_ATTRIBUTE, { type: 'set', name, value, }) } async userAttributeGetItem(name: string): Promise<string | null> { // User attributes added in Looker version 7.13, updated in 7.15 const errorMessage = this.verifyLookerVersion('>=7.15') if (errorMessage) { return Promise.reject(new Error(errorMessage)) } return this.sendAndReceive(ExtensionRequestType.USER_ATTRIBUTE, { type: 'get', name, }) } async userAttributeResetItem(name: string): Promise<void> { // User attributes added in Looker version 7.13, updated in 7.15 const errorMessage = this.verifyLookerVersion('>=7.15') if (errorMessage) { return Promise.reject(new Error(errorMessage)) } return this.sendAndReceive(ExtensionRequestType.USER_ATTRIBUTE, { type: 'reset', name, }) } getContextData() { const errorMessage = this.verifyLookerVersion('>=7.13') if (errorMessage) { throw new Error(errorMessage) } if (this.contextData) { return JSON.parse(this.contextData) } else { return undefined } } async saveContextData(context: any): Promise<any> { const errorMessage = this.verifyLookerVersion('>=7.13') if (errorMessage) { return Promise.reject(new Error(errorMessage)) } let contextData: string | undefined if (context) { try { contextData = JSON.stringify(context) } catch (err) { return Promise.reject(new Error('context cannot be serialized')) } } else { contextData = undefined } await this.sendAndReceive(ExtensionRequestType.CONTEXT_DATA, { type: 'save', contextData, }) return this.getContextData() } async refreshContextData(): Promise<any> { const errorMessage = this.verifyLookerVersion('>=7.13') if (errorMessage) { return Promise.reject(new Error(errorMessage)) } this.contextData = await this.sendAndReceive( ExtensionRequestType.CONTEXT_DATA, { type: 'refresh', } ) return this.getContextData() } track(name: string, trackAction: string, attributes?: Record<string, any>) { this.send(ExtensionRequestType.TRACK_ACTION, { name, trackAction, attributes, }) } error(errorEvent: ErrorEvent) { if (this._lookerHostData) { const { message, filename, lineno, colno, error } = errorEvent || {} this.send(ExtensionRequestType.ERROR_EVENT, { message, filename, lineno, colno, error: error && error.toString ? error.toString() : error, }) } else { console.error( 'Unhandled error but Looker host connection not established', errorEvent ) } } unloaded() { this.send(ExtensionRequestType.EXTENSION_UNLOADED, {}) } createFetchProxy( baseUrl?: string, init?: FetchCustomParameters, responseBodyType?: FetchResponseBodyType ) { return new FetchProxyImpl(this, baseUrl, init, responseBodyType) } async fetchProxy( resource: string, init?: FetchCustomParameters, responseBodyType?: FetchResponseBodyType ) { // Fetch proxy support added to Looker 7.9 const errorMessage = this.verifyLookerVersion('>=7.9') if (errorMessage) { return Promise.reject(new Error(errorMessage)) } return this.sendAndReceive(ExtensionRequestType.INVOKE_EXTERNAL_API, { type: 'fetch', payload: { resource, init, responseBodyType, }, }) } async serverProxy( resource: string, init?: FetchCustomParameters, responseBodyType?: FetchResponseBodyType ) { // Server proxy support added to Looker 7.11 const errorMessage = this.verifyLookerVersion('>=7.11') if (errorMessage) { return Promise.reject(new Error(errorMessage)) } return this.sendAndReceive(ExtensionRequestType.INVOKE_EXTERNAL_API, { type: 'server-proxy', payload: { resource, init, responseBodyType, }, }) } async oauth2Authenticate( authEndpoint: string, authParameters: Record<string, string>, httpMethod = 'POST' ) { // oauth2Authenticate proxy support added to Looker 7.9 let errorMessage = this.verifyLookerVersion('>=7.9') if (errorMessage) { return Promise.reject(new Error(errorMessage)) } errorMessage = this.validateAuthParameters(authParameters) if (errorMessage) { return Promise.reject(new Error(errorMessage)) } return this.sendAndReceive(ExtensionRequestType.INVOKE_EXTERNAL_API, { type: 'oauth2_authenticate', payload: { authEndpoint, authParameters, httpMethod, }, }) } async oauth2ExchangeCodeForToken( authEndpoint: string, authParameters: Record<string, string> ) { const errorMessage = this.verifyLookerVersion('>=7.11') if (errorMessage) { return Promise.reject(new Error(errorMessage)) } return this.sendAndReceive(ExtensionRequestType.INVOKE_EXTERNAL_API, { type: 'oauth2_exchange_code', payload: { authEndpoint, authParameters, }, }) } private async sendAndReceive(type: string, payload?: any): Promise<any> { if (!this._lookerHostData) { return Promise.reject(new Error('Looker host connection not established')) } return this.chattyHost .sendAndReceive(ExtensionEvent.EXTENSION_API_REQUEST, { type, payload, }) .then((values) => values[0]) } private send(type: string, payload?: any) { if (!this._lookerHostData) { throw new Error('Looker host connection not established') } this.chattyHost.send(ExtensionEvent.EXTENSION_API_REQUEST, { type, payload, }) } private verifyLookerVersion(version: string): string | undefined { // Default version to 7.0 as that's the first Looker version that officially // supported extensions. Version 6.24 has some support for extensions but most // likely will fail before reaching this point const lookerVersion = this._lookerHostData ? this._lookerHostData.lookerVersion || '7.0' : '7.0' if (!this._lookerHostData || !intersects(version, lookerVersion, true)) { return `Extension requires Looker version ${version}, got ${lookerVersion}` } return undefined } private validateAuthParameters(authParameters: Record<string, string>) { if (!authParameters.client_id) { return 'client_id missing' } if (authParameters.redirect_uri) { return 'redirect_uri must NOT be included' } if ( authParameters.response_type !== 'token' && authParameters.response_type !== 'id_token' && authParameters.response_type !== 'code' ) { return `invalid response_type, must be token, id_token or code, ${authParameters.response_type}` } return undefined } }
the_stack
declare var d3; declare var Tablesort; interface Map<T> { [key: string]: T} namespace profile { import CallNode = data.CallNode; import ProfileState = data.ProfileState; namespace calltable { const scoreColumns: analysis.AnalysisColumn[] = [ {type: "excl", column: "time", name: "Time (ms)", description: "Total time spent in this function (but not in descendent calls)", score: true}, {type: "excl", column: "term-count", name: "Term Count", description: "Number of symbolic terms created", score: true}, {type: "excl", column: "unused-terms", name: "Unused Terms", description: "Number of symbolic terms created that were never used for solving", score: true}, {type: "excl", column: "union-size", name: "Union Size", description: "Total number of branches in all symbolic unions created", score: true}, {type: "excl", column: "merge-cases", name: "Merge Cases", description: "Number of branches used during merging", score: true}, ]; const DOM_ROW_KEY = "symproRowObject"; const PRUNE_SCORE_FACTOR = 0.01; // < 1% of max score = pruned const colorScheme = makeScoreColorScheme(["#000000", "#FD893C", "#D9002C"]); var tableSorter; var contextDepth = 0; var useSignatures = false; var useCallsites = false; var pruneSmallRows = true; var idToRow: Map<HTMLTableRowElement> = {}; export function initCallTable() { renderTableHeaders(); analysis.setAggregate(true); analysis.setColumns(scoreColumns); analysis.registerAnalysisCallback(receiveData); } function renderTableHeaders(): void { let thead = document.querySelector("#calltable thead"); let tr = document.createElement("tr"); makeCell("Function", tr, "th"); let scoreCell = makeCell("Score", tr, "th"); scoreCell.className = "sort-default score"; scoreCell.id = "calltable-score-header"; let keys = []; for (let i = 0; i < scoreColumns.length; i++) { let c = scoreColumns[i]; let cell = makeCell(c.name, tr, "th"); if (c.description) { cell.dataset["title"] = c.description; cell.addEventListener("mouseover", (evt) => tooltip.showWithDelay("", <HTMLElement>evt.target, "top", 100)); cell.addEventListener("mouseout", (evt) => tooltip.hide()); } let checkbox = document.createElement("input"); checkbox.type = "checkbox"; checkbox.checked = true; checkbox.className = "score-checkbox"; checkbox.value = i.toString(); checkbox.addEventListener("change", scoreSelectCallback); checkbox.addEventListener("click", (evt) => evt.stopPropagation()); // prevent tablesorter from firing cell.insertAdjacentElement("beforeend", checkbox); } thead.insertAdjacentElement("beforeend", tr); // set up configuration controls let config = <HTMLTableHeaderCellElement>document.getElementById("calltable-config")!; // aggregate checkbox let agg = <HTMLInputElement>config.querySelector("#calltable-aggregate"); agg.checked = true; agg.addEventListener("change", configChangeCallback); // context slider let ctx = <HTMLInputElement>config.querySelector("#calltable-context"); ctx.value = "0"; let isIE = !!navigator.userAgent.match(/Trident/g) || !!navigator.userAgent.match(/MSIE/g); ctx.addEventListener(isIE ? "change" : "input", configChangeCallback); // context count let ctxn = config.querySelector("#calltable-context-n"); ctxn.textContent = "0"; // filter checkbox let fil = <HTMLInputElement>config.querySelector("#calltable-prune"); fil.checked = true; fil.addEventListener("change", configChangeCallback); // collapse rosette checkbox let clr = <HTMLInputElement>config.querySelector("#calltable-collapse-rosette"); clr.checked = false; clr.addEventListener("change", configChangeCallback); // collapse solver checkbox let cls = <HTMLInputElement>config.querySelector("#calltable-collapse-solver"); cls.checked = false; cls.addEventListener("change", configChangeCallback); // signature checkbox let sig = <HTMLInputElement>config.querySelector("#calltable-signature"); sig.checked = false; sig.addEventListener("change", configChangeCallback); // callsites checkbox let css = <HTMLInputElement>config.querySelector("#calltable-callsites"); css.checked = false; css.parentElement.style.display = "none"; css.addEventListener("change", configChangeCallback); // score checkbox let sco = <HTMLInputElement>config.querySelector("#calltable-show-scoreboxes"); sco.checked = false; sco.addEventListener("change", configChangeCallback); // more config let more = <HTMLDivElement>config.querySelector("#calltable-config-more"); more.style.display = "none"; let moreLink = <HTMLInputElement>config.querySelector("#calltable-config-toggle-more"); moreLink.addEventListener("click", toggleMoreCallback); // attach event handler for table body let tbody = document.querySelector("#calltable tbody"); tbody.addEventListener("mouseover", hoverCallback); tbody.addEventListener("mouseout", hoverCallback); tableSorter = new Tablesort(document.getElementById("calltable"), { descending: true }); } function configChangeCallback(evt: Event) { let elt: HTMLInputElement = this; if (elt.id == "calltable-aggregate") { let lbl = document.getElementById("calltable-callsites").parentElement; lbl.style.display = (elt.checked ? "none" : ""); analysis.setAggregate(elt.checked); } else if (elt.id == "calltable-context") { contextDepth = elt.value == elt.max ? -1 : parseInt(elt.value); let ctxn = document.getElementById("calltable-context-n"); ctxn.textContent = contextDepth >= 0 ? elt.value : "∞"; analysis.setContextDepth(contextDepth); } else if (elt.id == "calltable-prune") { pruneSmallRows = elt.checked; analysis.refresh(); } else if (elt.id == "calltable-collapse-rosette") { analysis.setCollapseRosette(elt.checked); } else if (elt.id == "calltable-collapse-solver") { stackgraph.setCollapseSolverTime(elt.checked); analysis.setCollapseSolver(elt.checked); } else if (elt.id == "calltable-signature") { useSignatures = elt.checked; analysis.setSignatures(elt.checked); } else if (elt.id == "calltable-callsites") { useCallsites = elt.checked; analysis.refresh(); } else if (elt.id == "calltable-show-scoreboxes") { let boxes = <NodeListOf<HTMLElement>>document.querySelectorAll("#calltable .score-checkbox"); for (let i = 0; i < boxes.length; i++) { boxes[i].style.display = elt.checked ? "initial" : "none"; if (!elt.checked) { scoreColumns[i].score = true; } } if (!elt.checked) { analysis.setColumns(scoreColumns); } } windowResizeCallback(); } function toggleMoreCallback(evt: Event) { evt.preventDefault(); let more = document.getElementById("calltable-config-more"); let elt: HTMLAnchorElement = this; if (more.style.display == "none") { more.style.display = "block"; this.textContent = "[Less]"; } else { more.style.display = "none"; this.textContent = "[More]"; } } function hoverCallback(evt: Event) { if (evt.type == "mouseover") { let tgt = <HTMLElement>evt.target; while (tgt && tgt.tagName != "TR") tgt = tgt.parentElement; stackgraph.calltableHoverCallback(tgt[DOM_ROW_KEY].allNodes); } else { stackgraph.calltableHoverCallback([]); } } function scoreSelectCallback(evt: Event) { let elt: HTMLInputElement = this; let idx = parseInt(elt.value); scoreColumns[idx].score = elt.checked; analysis.setColumns(scoreColumns); } export function stackgraphHoverCallback(node: CallNode, enter: boolean) { let rows = document.querySelectorAll("#calltable tbody tr"); for (let i = 0; i < rows.length; i++) { let row = rows[i]; row.className = ""; } if (enter) { let hiRow = idToRow[node.id]; if (hiRow) { hiRow.className = "calltable-highlight"; } } } function receiveData(state: analysis.ProfileData) { renderTableRows(state.rows, state.aggregate, state.maxScore); } function renderPrettySource(source: string, cell: HTMLElement, iscallsite=false) { if (source) { let prettySource = getPrettySource(source); if (iscallsite) prettySource = "from " + prettySource; let sourceSpan = makeCell(prettySource, cell, "span"); sourceSpan.className = "source"; sourceSpan.title = source; } } function getPrettySource(source: string) { let sourceParts = source.split(":"); if (sourceParts.length != 3) return source; let [file, line, col] = sourceParts; let fileParts = file.split("/"); return fileParts[fileParts.length-1] + ":" + line; } function renderTableRows(rows: analysis.AnalysisRow[], aggregate: boolean, maxScore: number) { // remove old rows let tbody = document.querySelector("#calltable tbody"); while (tbody.firstChild) tbody.removeChild(tbody.firstChild); idToRow = {}; // create new rows for (let r of rows) { let row = document.createElement("tr"); if (pruneSmallRows && r.score < maxScore*PRUNE_SCORE_FACTOR) { continue; } // render the function name let nameCell = makeCell(r.function, row); nameCell.className = "name"; if (useCallsites && !aggregate) { renderPrettySource(r.node.callsite, nameCell, true); } else { renderPrettySource(r.node.source, nameCell); } if (aggregate) { let txt = r.allNodes.length > 1 ? formatNum(r.allNodes.length) + " calls" : "1 call"; let numCallsSpan = makeCell(txt, nameCell, "span"); numCallsSpan.className = "numcalls"; } // maybe render the signature if (useSignatures) { let inputs: string[] = r.node.inputs["signature"] || []; let outputs: string[] = r.node.outputs["signature"] || []; let istr = inputs.map((s) => s[0].toUpperCase()).join(""); let ostr = outputs.map((s) => s[0].toUpperCase()).join(""); let span = makeCell(istr + "→" + ostr, nameCell, "span"); span.className = "signature"; } // render the call context if requested if (contextDepth != 0) { let contextList = document.createElement("ul"); contextList.className = "context-list"; let n = contextDepth, curr = r.node; if (n == -1) { // if "infinite", collapse recursion let count = 0; while (curr = curr.parent) { if (curr.parent && curr.parent.name == curr.name && curr.parent.source == curr.source) { count += 1; } else { let name = curr.name + (count > 0 ? " ×" + (count+1) : ""); let li = makeCell(name, contextList, "li"); count = 0; renderPrettySource(curr.source, li); } } } else { while (n-- != 0 && (curr = curr.parent)) { let li = makeCell(curr.name, contextList, "li"); renderPrettySource(curr.source, li); } } nameCell.insertAdjacentElement("beforeend", contextList); } // score cell let scoreBar = document.createElement("div"); scoreBar.className = "scorebar"; scoreBar.style.width = (r.score/scoreColumns.length * 100) + "%"; scoreBar.style.backgroundColor = colorScheme(r.score); let scoreBarCell = document.createElement("div"); scoreBarCell.className = "scorecell-bar"; scoreBarCell.insertAdjacentElement("beforeend", scoreBar); let scoreSpan = document.createElement("span"); scoreSpan.textContent = formatNum(r.score, 1, false, true); scoreSpan.style.color = colorScheme(r.score); let scoreSpanCell = document.createElement("div"); scoreSpanCell.className = "scorecell-score"; scoreSpanCell.insertAdjacentElement("beforeend", scoreSpan); let scoreCell = makeCell("", row); scoreCell.dataset["sort"] = r.score.toFixed(16); scoreCell.insertAdjacentElement("beforeend", scoreSpanCell); scoreCell.insertAdjacentElement("beforeend", scoreBarCell); // data columns for (let k of r.columns) { makeCell(formatNum(k, 0), row); } // attach row object to the row row[DOM_ROW_KEY] = r; // record IDs for (let n of r.allNodes) { idToRow[n.id] = row; } tbody.insertAdjacentElement("beforeend", row); } // refresh the sort tableSorter.refresh(); } function makeCell(str: string, row: HTMLElement, type: string = "td"): HTMLElement { let elt = document.createElement(type); elt.textContent = str; row.insertAdjacentElement('beforeend', elt); return elt; } } namespace stackgraph { var stackgraph: d3_stackgraph.StackGraph; const colorScheme = makeScoreColorScheme(["#ffeda0","#fed976","#feb24c","#fd8d3c","#fc4e2a","#e31a1c","#bd0026"]); var solverHighlightColor = "#E3F2FF"; var lastWidth = 0; var useDiscontinuities = false; export function initStackGraph() { // build stackgraph const STACK_WIDTH = document.getElementById("stackgraph")!.clientWidth; const STACK_HEIGHT = 270; lastWidth = STACK_WIDTH; stackgraph = d3_stackgraph.stackGraph("#stackgraph"); stackgraph.width(STACK_WIDTH).height(STACK_HEIGHT); stackgraph.clickHandler(clickCallback); stackgraph.hoverHandler(hoverCallback); stackgraph.color(nodeColorCallback); stackgraph.textColor(nodeTextColorCallback); stackgraph.render(); analysis.registerAnalysisCallback(receiveData); analysis.registerZoomCallback(receiveZoom); } function makeHighlightList(state: analysis.ProfileData) { let ret = []; for (let call of state.solverCalls) { let finish = typeof call.finish === "undefined" ? state.root.finish : call.finish; let dt = formatNum(finish - call.start, 1); let summary = ""; if (call.type == data.SolverCallType.SOLVE) { let sat = typeof call.sat === "undefined" ? " (pending)" : (call.sat ? " (SAT)" : " (UNSAT)"); summary = `Solver call${sat}: ${dt}ms`; } else if (call.type == data.SolverCallType.ENCODE) { summary = `Solver encoding: ${dt}ms`; } else if (call.type == data.SolverCallType.FINITIZE) { summary = `Solver finitization: ${dt}ms`; } ret.push({ start: call.start, finish: finish, color: solverHighlightColor, summary: summary }); } return ret; } function makeDiscontinuityList(state: analysis.ProfileData) { let ret = [] for (let call of state.solverCalls) { let finish = typeof call.finish === "undefined" ? state.root.finish : call.finish; ret.push([call.start, finish]); } return ret; } function receiveData(state: analysis.ProfileData) { if (state.root) stackgraph.data(state.root); stackgraph.highlights(makeHighlightList(state)); let discs = useDiscontinuities ? makeDiscontinuityList(state) : []; stackgraph.discontinuities(discs); stackgraph.render(); } function receiveZoom(node: CallNode) { stackgraph.zoom(node); } function clickCallback(node: CallNode): void { analysis.zoomTo(node); } export function windowResizeCallback() { // caller should handle debouncing let width = document.getElementById("stackgraph")!.clientWidth; if (width != lastWidth) { stackgraph.width(width).render(); lastWidth = width; } } export function calltableHoverCallback(nodes: CallNode[]): void { stackgraph.highlightData(nodes); } export function setCollapseSolverTime(use: boolean) { useDiscontinuities = use; } function hoverCallback(node: CallNode, enter: boolean): void { calltable.stackgraphHoverCallback(node, enter); } function nodeColorCallback(node: CallNode): string { return colorScheme(node.score); } function nodeTextColorCallback(node: CallNode): string { let col = d3.color(colorScheme(node.score)).rgb(); let yiq = ((col.r*299) + (col.g*587) + (col.b*114)) / 1000; return (yiq >= 128) ? "#222222" : "#eeeeee"; } } function formatNum(v: number, places: number = 6, sig: boolean = false, always: boolean = false): string { let pl = sig ? (v < 10 ? 1 : 0) : places; return (v % 1 == 0 && !always) ? v.toString() : v.toFixed(pl); } var metadataSet = false; function setMetadata(state: ProfileState) { if (!metadataSet && state.metadata != null) { document.getElementById("profile-source").textContent = state.metadata["source"]; document.getElementById("profile-time").textContent = state.metadata["time"]; document.title = "Profile for " + state.metadata["source"] + " generated at " + state.metadata["time"]; metadataSet = true; } } var spinnerVisible = false; function toggleStreamingSpinner(state: ProfileState) { let elt = document.getElementById("progress"); if (state.streaming && !spinnerVisible) { elt.style.display = "block"; spinnerVisible = true; } else if (!state.streaming && spinnerVisible) { elt.style.display = "none"; spinnerVisible = false; } } var resizing = false; function windowResizeCallback() { if (!resizing) { resizing = true; stackgraph.windowResizeCallback(); window.setTimeout(() => { resizing = false; }, 50); } } // make a color scheme reflecting that scores > 4 are "very bad" function makeScoreColorScheme(colors: string[]) { let cs = d3.interpolateRgbBasis(colors); return function(x) { if (x > 4.0) return colors[colors.length-1]; return cs(x/4.0); }; } function bindHelpEventHandlers() { var helps = document.querySelectorAll(".help"); for (var i = 0; i < helps.length; i++) { let elt = helps[i]; elt.addEventListener("mouseover", (evt) => tooltip.showWithDelay("", <HTMLElement>evt.target, "top", 100)); elt.addEventListener("mouseout", (evt) => tooltip.hide()); } } function init() { // set up tooltips tooltip.init(); bindHelpEventHandlers(); // set up analysis analysis.init(); // initialize UI components stackgraph.initStackGraph(); calltable.initCallTable(); // set up UI callbacks for data state changes data.registerUpdateCallback(setMetadata); data.registerUpdateCallback(toggleStreamingSpinner); // receive all the data data.readyForData(); // set initial widths correctly now that data is rendered windowResizeCallback(); window.addEventListener("resize", windowResizeCallback); } document.addEventListener("DOMContentLoaded", init); }
the_stack
import { expect } from 'chai'; import Helper from '../../src/e2e-helper/e2e-helper'; import * as fixtures from '../../src/fixtures/fixtures'; import { MergeConflict, MergeConflictOnRemote } from '../../src/scope/exceptions'; describe('merge functionality', function () { this.timeout(0); let helper: Helper; before(() => { helper = new Helper(); helper.command.setFeatures('legacy-workspace-config'); }); after(() => { helper.scopeHelper.destroy(); }); describe('re-exporting/importing an existing version', () => { before(() => { helper.scopeHelper.setNewLocalAndRemoteScopes(); helper.fixtures.createComponentBarFoo(); helper.fixtures.addComponentBarFoo(); helper.fixtures.tagComponentBarFoo(); helper.fs.createFile('bar2', 'foo2.js'); helper.command.addComponent('bar2/foo2.js', { i: 'bar2/foo2' }); helper.command.tagComponent('bar2/foo2'); helper.command.exportAllComponents(); helper.scopeHelper.reInitLocalScope(); helper.scopeHelper.addRemoteScope(); helper.command.importComponent('bar/foo'); helper.command.importComponent('bar2/foo2'); const scopeWithV1 = helper.scopeHelper.cloneLocalScope(); helper.command.tagComponent('bar/foo', 'msg', '-f'); helper.command.tagComponent('bar2/foo2', 'msg', '-f'); helper.command.exportAllComponents(); // v2 is exported helper.scopeHelper.getClonedLocalScope(scopeWithV1); helper.command.tagComponent('bar/foo', 'msg', '-f'); helper.command.tagComponent('bar2/foo2', 'msg', '-f'); }); it('should throw MergeConflictOnRemote error when exporting the component', () => { const exportFunc = () => helper.command.exportAllComponents(); // v2 is exported again const idsAndVersions = [ { id: `${helper.scopes.remote}/bar/foo`, versions: ['0.0.2'] }, { id: `${helper.scopes.remote}/bar2/foo2`, versions: ['0.0.2'] }, ]; const error = new MergeConflictOnRemote(idsAndVersions, []); helper.general.expectToThrow(exportFunc, error); }); it('should throw MergeConflict error when importing the component', () => { const importFunc = () => helper.command.importComponent('bar/foo'); const error = new MergeConflict(`${helper.scopes.remote}/bar/foo`, ['0.0.2']); expect(importFunc).to.throw(error.message); expect(importFunc).to.not.throw('unhandled rejection found'); }); }); describe('importing a component with --merge flag', () => { let beforeImport; before(() => { helper.scopeHelper.setNewLocalAndRemoteScopes(); helper.fs.createFile('utils', 'is-type.js', fixtures.isType); helper.fs.createFile('utils', 'is-string.js', fixtures.isString); helper.fixtures.addComponentUtilsIsType(); helper.fixtures.addComponentUtilsIsString(); helper.command.tagAllComponents(); helper.fs.createFile('utils', 'is-type.js', fixtures.isTypeV2); helper.fixtures.addComponentUtilsIsType(); helper.command.tagAllComponents(); helper.command.exportAllComponents(); helper.scopeHelper.reInitLocalScope(); helper.scopeHelper.addRemoteScope(); beforeImport = helper.scopeHelper.cloneLocalScope(); helper.command.importComponent('utils/is-type@0.0.1'); }); describe('using invalid value for merge flag', () => { let output; before(() => { output = helper.general.runWithTryCatch('bit import utils/is-type --merge=invalid'); }); it('should throw an error', () => { expect(output).to.have.string('merge must be one of the following'); }); }); describe('modifying the component so it will get conflict upon importing', () => { let localScope; before(() => { helper.fs.createFile('components/utils/is-type', 'is-type.js', fixtures.isTypeV3); localScope = helper.scopeHelper.cloneLocalScope(); }); describe('merge with strategy=manual', () => { let output; let fileContent; before(() => { output = helper.command.importComponent('utils/is-type --merge=manual'); fileContent = helper.fs.readFile('components/utils/is-type/is-type.js'); }); it('should indicate that there were files with conflicts', () => { expect(output).to.have.string('conflicts'); }); it('should rewrite the file with the conflict with the conflicts segments', () => { expect(fileContent).to.have.string('<<<<<<<'); expect(fileContent).to.have.string('>>>>>>>'); expect(fileContent).to.have.string('======='); }); it('should label the conflicts segments according to the versions', () => { expect(fileContent).to.have.string('<<<<<<< 0.0.2'); // current-change expect(fileContent).to.have.string('>>>>>>> 0.0.1 modified'); // incoming-change }); it('should show the component as modified', () => { const statusOutput = helper.command.runCmd('bit status'); expect(statusOutput).to.have.string('modified components'); }); it('should update bitmap with the imported version', () => { const bitMap = helper.bitMap.read(); expect(bitMap).to.have.property(`${helper.scopes.remote}/utils/is-type@0.0.2`); expect(bitMap).to.not.have.property(`${helper.scopes.remote}/utils/is-type@0.0.1`); }); }); describe('merge with strategy=theirs', () => { let output; let fileContent; before(() => { helper.scopeHelper.getClonedLocalScope(localScope); output = helper.command.importComponent('utils/is-type --merge=theirs'); fileContent = helper.fs.readFile('components/utils/is-type/is-type.js'); }); it('should not indicate that there were files with conflicts', () => { expect(output).to.not.have.string('conflicts'); }); it('should rewrite the file according to the imported version', () => { expect(fileContent).to.have.string(fixtures.isTypeV2); }); it('should not show the component as modified', () => { const statusOutput = helper.command.runCmd('bit status'); expect(statusOutput).to.not.have.string('modified components'); }); it('should update bitmap with the imported version', () => { const bitMap = helper.bitMap.read(); expect(bitMap).to.have.property(`${helper.scopes.remote}/utils/is-type@0.0.2`); expect(bitMap).to.not.have.property(`${helper.scopes.remote}/utils/is-type@0.0.1`); }); }); describe('merge with strategy=ours', () => { let output; let fileContent; before(() => { helper.scopeHelper.getClonedLocalScope(localScope); output = helper.command.importComponent('utils/is-type --merge=ours'); fileContent = helper.fs.readFile('components/utils/is-type/is-type.js'); }); it('should not indicate that there were files with conflicts', () => { expect(output).to.not.have.string('conflicts'); }); it('should leave the modified file intact', () => { expect(fileContent).to.have.string(fixtures.isTypeV3); }); it('should show the component as modified', () => { const statusOutput = helper.command.runCmd('bit status'); expect(statusOutput).have.string('modified components'); }); it('should update bitmap with the imported version', () => { const bitMap = helper.bitMap.read(); expect(bitMap).to.have.property(`${helper.scopes.remote}/utils/is-type@0.0.2`); expect(bitMap).to.not.have.property(`${helper.scopes.remote}/utils/is-type@0.0.1`); }); }); }); describe('modifying the component to be the same as the imported component (so the merge will succeed with no conflicts)', () => { before(() => { helper.fs.createFile('components/utils/is-type', 'is-type.js', fixtures.isTypeV2); }); describe('merge with strategy=manual', () => { // strategies of ours and theirs are leading to the same results let output; let fileContent; before(() => { output = helper.command.importComponent('utils/is-type --merge=manual'); fileContent = helper.fs.readFile('components/utils/is-type/is-type.js'); }); it('should not indicate that there were files with conflicts', () => { expect(output).to.not.have.string('conflicts'); }); it('should rewrite the file according to both the imported version and modified version', () => { expect(fileContent).to.have.string(fixtures.isTypeV2); }); it('should not show the component as modified', () => { const statusOutput = helper.command.runCmd('bit status'); expect(statusOutput).to.not.have.string('modified components'); }); it('should update bitmap with the imported version', () => { const bitMap = helper.bitMap.read(); expect(bitMap).to.have.property(`${helper.scopes.remote}/utils/is-type@0.0.2`); expect(bitMap).to.not.have.property(`${helper.scopes.remote}/utils/is-type@0.0.1`); }); }); }); describe('modifying the dependency then import --merge of the dependent', () => { before(() => { helper.scopeHelper.getClonedLocalScope(beforeImport); helper.command.importComponent('utils/is-type'); helper.command.importComponent('utils/is-string'); helper.fs.createFile('components/utils/is-type', 'is-type.js', fixtures.isTypeV3); // an intermediate step, make sure bit status shows as modified expect(helper.command.statusComponentIsModified(`${helper.scopes.remote}/utils/is-type@0.0.2`)).to.be.true; helper.command.importComponent('utils/is-string --merge'); }); it('should not remove the dependency changes', () => { const isTypeContent = helper.fs.readFile('components/utils/is-type/is-type.js'); expect(isTypeContent).to.equal(fixtures.isTypeV3); expect(helper.command.statusComponentIsModified(`${helper.scopes.remote}/utils/is-type@0.0.2`)).to.be.true; }); }); }); });
the_stack
export namespace ScriptEditor { // Default Application export interface Application {} // Class /** * This file was automatically generated by json-schema-to-typescript. * DO NOT MODIFY IT BY HAND. Instead, modify the source JSONSchema file, * and run json-schema-to-typescript to regenerate this file. */ /** * An application's top level scripting object. */ export interface Application { /** * Is this the frontmost (active) application? */ frontmost(): boolean; /** * The name of the application. */ name(): string; /** * The version of the application. */ version(): string; } /** * This file was automatically generated by json-schema-to-typescript. * DO NOT MODIFY IT BY HAND. Instead, modify the source JSONSchema file, * and run json-schema-to-typescript to regenerate this file. */ /** * A color. */ export interface Color {} /** * This file was automatically generated by json-schema-to-typescript. * DO NOT MODIFY IT BY HAND. Instead, modify the source JSONSchema file, * and run json-schema-to-typescript to regenerate this file. */ /** * A document. */ export interface Document { /** * Has the document been modified since the last save? */ modified(): boolean; /** * The document's name. */ name(): string; /** * The document's path. */ path(): string; } /** * This file was automatically generated by json-schema-to-typescript. * DO NOT MODIFY IT BY HAND. Instead, modify the source JSONSchema file, * and run json-schema-to-typescript to regenerate this file. */ /** * A scriptable object. */ export interface Item { /** * The class of the object. */ class(): any; /** * All of the object's properties. */ properties(): any; } /** * This file was automatically generated by json-schema-to-typescript. * DO NOT MODIFY IT BY HAND. Instead, modify the source JSONSchema file, * and run json-schema-to-typescript to regenerate this file. */ /** * A window. */ export interface Window { /** * The bounding rectangle of the window. */ bounds(): any; /** * Whether the window has a close box. */ closeable(): boolean; /** * The document whose contents are being displayed in the window. */ document(): any; /** * Whether the window floats. */ floating(): boolean; /** * The unique identifier of the window. */ id(): number; /** * The index of the window, ordered front to back. */ index(): number; /** * Whether the window can be miniaturized. */ miniaturizable(): boolean; /** * Whether the window is currently miniaturized. */ miniaturized(): boolean; /** * Whether the window is the application's current modal window. */ modal(): boolean; /** * The full title of the window. */ name(): string; /** * Whether the window can be resized. */ resizable(): boolean; /** * Whether the window has a title bar. */ titled(): boolean; /** * Whether the window is currently visible. */ visible(): boolean; /** * Whether the window can be zoomed. */ zoomable(): boolean; /** * Whether the window is currently zoomed. */ zoomed(): boolean; } /** * This file was automatically generated by json-schema-to-typescript. * DO NOT MODIFY IT BY HAND. Instead, modify the source JSONSchema file, * and run json-schema-to-typescript to regenerate this file. */ /** * Represents an inline text attachment. This class is used mainly for make commands. */ export interface Attachment { /** * The path to the file for the attachment */ fileName(): string; } /** * This file was automatically generated by json-schema-to-typescript. * DO NOT MODIFY IT BY HAND. Instead, modify the source JSONSchema file, * and run json-schema-to-typescript to regenerate this file. */ /** * This subdivides the text into chunks that all have the same attributes. */ export interface AttributeRun { /** * The color of the first character. */ color(): any; /** * The name of the font of the first character. */ font(): string; /** * The size in points of the first character. */ size(): number; } /** * This file was automatically generated by json-schema-to-typescript. * DO NOT MODIFY IT BY HAND. Instead, modify the source JSONSchema file, * and run json-schema-to-typescript to regenerate this file. */ /** * This subdivides the text into characters. */ export interface Character { /** * The color of the first character. */ color(): any; /** * The name of the font of the first character. */ font(): string; /** * The size in points of the first character. */ size(): number; } /** * This file was automatically generated by json-schema-to-typescript. * DO NOT MODIFY IT BY HAND. Instead, modify the source JSONSchema file, * and run json-schema-to-typescript to regenerate this file. */ /** * This subdivides the text into paragraphs. */ export interface Paragraph { /** * The color of the first character. */ color(): any; /** * The name of the font of the first character. */ font(): string; /** * The size in points of the first character. */ size(): number; } /** * This file was automatically generated by json-schema-to-typescript. * DO NOT MODIFY IT BY HAND. Instead, modify the source JSONSchema file, * and run json-schema-to-typescript to regenerate this file. */ /** * Rich (styled) text */ export interface Text { /** * The color of the first character. */ color(): any; /** * The name of the font of the first character. */ font(): string; /** * The size in points of the first character. */ size(): number; } /** * This file was automatically generated by json-schema-to-typescript. * DO NOT MODIFY IT BY HAND. Instead, modify the source JSONSchema file, * and run json-schema-to-typescript to regenerate this file. */ /** * This subdivides the text into words. */ export interface Word { /** * The color of the first character. */ color(): any; /** * The name of the font of the first character. */ font(): string; /** * The size in points of the first character. */ size(): number; } /** * This file was automatically generated by json-schema-to-typescript. * DO NOT MODIFY IT BY HAND. Instead, modify the source JSONSchema file, * and run json-schema-to-typescript to regenerate this file. */ /** * A class */ export interface Class {} /** * This file was automatically generated by json-schema-to-typescript. * DO NOT MODIFY IT BY HAND. Instead, modify the source JSONSchema file, * and run json-schema-to-typescript to regenerate this file. */ /** * An insertion point between two objects. */ export interface InsertionPoint { /** * The contents of the insertion point. */ contents(): any; } /** * This file was automatically generated by json-schema-to-typescript. * DO NOT MODIFY IT BY HAND. Instead, modify the source JSONSchema file, * and run json-schema-to-typescript to regenerate this file. */ /** * A scripting language. */ export interface Language { /** * The description */ description(): string; /** * The unique id of the language. */ id(): string; /** * The name of the language. */ name(): string; /** * Is the language compilable? */ supportsCompiling(): boolean; /** * Is the language recordable? */ supportsRecording(): boolean; } /** * This file was automatically generated by json-schema-to-typescript. * DO NOT MODIFY IT BY HAND. Instead, modify the source JSONSchema file, * and run json-schema-to-typescript to regenerate this file. */ /** * A way to refer to the state of the current selection. */ export interface SelectionObject { /** * The range of characters in the selection. */ characterRange(): any; /** * The contents of the selection. */ contents(): any; } /** * This file was automatically generated by json-schema-to-typescript. * DO NOT MODIFY IT BY HAND. Instead, modify the source JSONSchema file, * and run json-schema-to-typescript to regenerate this file. */ export interface PrintSettings { /** * the number of copies of a document to be printed */ copies(): number; /** * Should printed copies be collated? */ collating(): boolean; /** * the first page of the document to be printed */ startingPage(): number; /** * the last page of the document to be printed */ endingPage(): number; /** * number of logical pages laid across a physical page */ pagesAcross(): number; /** * number of logical pages laid out down a physical page */ pagesDown(): number; /** * the time at which the desktop printer should print the document */ requestedPrintTime(): any; /** * how errors are handled */ errorHandling(): any; /** * for fax number */ faxNumber(): string; /** * for target printer */ targetPrinter(): string; } // CLass Extension /** * This file was automatically generated by json-schema-to-typescript. * DO NOT MODIFY IT BY HAND. Instead, modify the source JSONSchema file, * and run json-schema-to-typescript to regenerate this file. */ /** * Script Editor's top level scripting object. */ export interface Application { /** * The current selection. */ selection(): any; } /** * This file was automatically generated by json-schema-to-typescript. * DO NOT MODIFY IT BY HAND. Instead, modify the source JSONSchema file, * and run json-schema-to-typescript to regenerate this file. */ /** * A script document. */ export interface Document { /** * The contents of the document. */ contents(): any; /** * The description of the document. */ description(): any; /** * The event log of the document. */ eventLog(): any; /** * The scripting language. */ language(): any; /** * The current selection. */ selection(): any; /** * The text of the document. */ text(): any; } /** * This file was automatically generated by json-schema-to-typescript. * DO NOT MODIFY IT BY HAND. Instead, modify the source JSONSchema file, * and run json-schema-to-typescript to regenerate this file. */ /** * Rich (styled) text */ export interface TextCtxt { /** * The color of the first character. */ color(): any; /** * The name of the font of the first character. */ font(): string; /** * The size in points of the first character. */ size(): number; } /** * This file was automatically generated by json-schema-to-typescript. * DO NOT MODIFY IT BY HAND. Instead, modify the source JSONSchema file, * and run json-schema-to-typescript to regenerate this file. */ /** * A window. */ export interface Window { /** * The full title of the window. */ name(): string; } // Records // Function options /** * This file was automatically generated by json-schema-to-typescript. * DO NOT MODIFY IT BY HAND. Instead, modify the source JSONSchema file, * and run json-schema-to-typescript to regenerate this file. */ export interface CloseOptionalParameter { /** * Specifies whether changes should be saved before closing. */ saving?: any; /** * The file in which to save the object. */ savingIn?: any; } /** * This file was automatically generated by json-schema-to-typescript. * DO NOT MODIFY IT BY HAND. Instead, modify the source JSONSchema file, * and run json-schema-to-typescript to regenerate this file. */ export interface CountOptionalParameter { /** * The class of objects to be counted. */ each?: any; } /** * This file was automatically generated by json-schema-to-typescript. * DO NOT MODIFY IT BY HAND. Instead, modify the source JSONSchema file, * and run json-schema-to-typescript to regenerate this file. */ export interface DuplicateOptionalParameter { /** * The location for the new object(s). */ to?: any; /** * Properties to be set in the new duplicated object(s). */ withProperties?: any; } /** * This file was automatically generated by json-schema-to-typescript. * DO NOT MODIFY IT BY HAND. Instead, modify the source JSONSchema file, * and run json-schema-to-typescript to regenerate this file. */ export interface MakeOptionalParameter { /** * The class of the new object. */ new: any; /** * The location at which to insert the object. */ at?: any; /** * The initial data for the object. */ withData?: any; /** * The initial values for properties of the object. */ withProperties?: any; } /** * This file was automatically generated by json-schema-to-typescript. * DO NOT MODIFY IT BY HAND. Instead, modify the source JSONSchema file, * and run json-schema-to-typescript to regenerate this file. */ export interface MoveOptionalParameter { /** * The new location for the object(s). */ to: any; } /** * This file was automatically generated by json-schema-to-typescript. * DO NOT MODIFY IT BY HAND. Instead, modify the source JSONSchema file, * and run json-schema-to-typescript to regenerate this file. */ export interface PrintOptionalParameter { /** * Should the application show the Print dialog? */ printDialog?: boolean; /** * the print settings */ withProperties?: any; } /** * This file was automatically generated by json-schema-to-typescript. * DO NOT MODIFY IT BY HAND. Instead, modify the source JSONSchema file, * and run json-schema-to-typescript to regenerate this file. */ export interface QuitOptionalParameter { /** * Specifies whether changes should be saved before quitting. */ saving?: any; } /** * This file was automatically generated by json-schema-to-typescript. * DO NOT MODIFY IT BY HAND. Instead, modify the source JSONSchema file, * and run json-schema-to-typescript to regenerate this file. */ export interface SaveOptionalParameter { /** * The file type in which to save the data. */ as?: string; /** * The file in which to save the object. */ in?: any; } /** * This file was automatically generated by json-schema-to-typescript. * DO NOT MODIFY IT BY HAND. Instead, modify the source JSONSchema file, * and run json-schema-to-typescript to regenerate this file. */ export interface SetOptionalParameter { /** * The new value. */ to: any; } /** * This file was automatically generated by json-schema-to-typescript. * DO NOT MODIFY IT BY HAND. Instead, modify the source JSONSchema file, * and run json-schema-to-typescript to regenerate this file. */ export interface SaveOptionalParameter1 { /** * The file type in which to save the data. Use one of the following strings: "script", "script bundle", "application", "text". */ as?: string; /** * The file in which to save the object. */ in?: any; /** * Should the script be saved as Run-Only? If it is, you will not be able to edit the contents of the script again. The default is not to save as run only. (Applies to all script types except for "text"). */ runOnly?: boolean; /** * Show the startup screen? The default is not to show the startup screen. (Only applies to scripts saved as "application"). */ startupScreen?: boolean; /** * Should the application remain open after it is launched? The default is not to stay open. (Only applies to scripts saved as "application"). */ stayOpen?: boolean; } } export interface ScriptEditor extends ScriptEditor.Application { // Functions /** * Close an object. * @param directParameter the object for the command * @param option * */ close(directParameter: any, option?: ScriptEditor.CloseOptionalParameter): void; /** * Return the number of elements of a particular class within an object. * @param directParameter the object for the command * @param option * @return undefined */ count(directParameter: any, option?: ScriptEditor.CountOptionalParameter): number; /** * Delete an object. * @param directParameter the object for the command * */ delete(directParameter: any, ): void; /** * Copy object(s) and put the copies at a new location. * @param directParameter the object for the command * @param option * */ duplicate(directParameter: any, option?: ScriptEditor.DuplicateOptionalParameter): void; /** * Verify if an object exists. * @param directParameter the object for the command * @return undefined */ exists(directParameter: any, ): boolean; /** * Get the data for an object. * @param directParameter the object for the command * @return undefined */ get(directParameter: any, ): any; /** * Make a new object. * @param option * @return undefined */ make(option?: ScriptEditor.MakeOptionalParameter): any; /** * Move object(s) to a new location. * @param directParameter the object for the command * @param option * */ move(directParameter: any, option?: ScriptEditor.MoveOptionalParameter): void; /** * Open an object. * @param directParameter The file(s) to be opened. * @return undefined */ open(directParameter: any, ): ScriptEditor.Document; /** * Print an object. * @param directParameter The file(s) or document(s) to be printed. * @param option * */ print(directParameter: any, option?: ScriptEditor.PrintOptionalParameter): void; /** * Quit an application. * @param option * */ quit(option?: ScriptEditor.QuitOptionalParameter): void; /** * Save an object. * @param directParameter the object for the command * @param option * */ save(directParameter: any, option?: ScriptEditor.SaveOptionalParameter): void; /** * Set an object's data. * @param directParameter the object for the command * @param option * */ set(directParameter: any, option?: ScriptEditor.SetOptionalParameter): void; /** * Check the syntax of a document. * @param directParameter the object for the command * */ checkSyntax(directParameter: any, ): void; /** * Compile the script of a document. * @param directParameter the object for the command * @return undefined */ compile(directParameter: any, ): boolean; /** * Execute the document. * @param directParameter the object for the command * @return undefined */ execute(directParameter: any, ): any; /** * Save an object. * @param directParameter the object for the command * @param option * */ save(directParameter: any, option?: ScriptEditor.SaveOptionalParameter1): void; }
the_stack
import { AnyFactorType, ComputedParameter, ConstantParameter, DeclaredVariable, DeclaredVariables, Parameter, ParameterComputeType, ParameterExpression, ParameterExpressionOperator, ParameterInvalidReason, ParameterJoint, ParameterKind, TopicFactorParameter, ValueTypes } from './factor-calculator-types'; import { computeParameterTypes, computeValidTypesByExpressionOperator, computeValidTypesForSubParameter, isComputeTypeValid, isFactorTypeCompatibleWith } from './factor-calculator-utils'; import {FactorType} from './factor-types'; import { isComputedParameter, isConstantParameter, isExpressionParameter, isJointParameter, isTopicFactorParameter, ParameterCalculatorDefsMap } from './parameter-utils'; import {PipelineStage} from './pipeline-stage-types'; import {PipelineStageUnitAction} from './pipeline-stage-unit-action/pipeline-stage-unit-action-types'; import { isCopyToMemoryAction, isExistsAction, isReadFactorAction, isReadFactorsAction, isReadRowAction, isReadRowsAction, isReadTopicAction } from './pipeline-stage-unit-action/pipeline-stage-unit-action-utils'; import {PipelineStageUnit} from './pipeline-stage-unit-types'; import {Pipeline} from './pipeline-types'; import {Topic} from './topic-types'; export const isJointValid4Pipeline = (options: { joint: ParameterJoint; allTopics: Array<Topic>; triggerTopic?: Topic; variables: DeclaredVariables; reasons: (reason: ParameterInvalidReason) => void; }): boolean => { const {joint, allTopics, triggerTopic, variables, reasons} = options; const {jointType, filters} = joint; if (!jointType) { reasons(ParameterInvalidReason.JOINT_TYPE_NOT_DEFINED); return false; } if (!filters || filters.length === 0) { reasons(ParameterInvalidReason.JOINT_FILTERS_NOT_DEFINED); return false; } return !filters.some(filter => { if (isJointParameter(filter)) { return !isJointValid4Pipeline({joint: filter, allTopics, triggerTopic, variables, reasons}); } else if (isExpressionParameter(filter)) { return !isExpressionValid4Pipeline({expression: filter, allTopics, triggerTopic, variables, reasons}); } return true; }); }; const isExpressionValid4Pipeline = (options: { expression: ParameterExpression; allTopics: Array<Topic>; triggerTopic?: Topic; variables: DeclaredVariables; reasons: (reason: ParameterInvalidReason) => void; }): boolean => { const {expression, allTopics, triggerTopic, variables, reasons} = options; const {left, operator, right} = expression; if (!operator) { reasons(ParameterInvalidReason.EXPRESSION_OPERATOR_NOT_DEFINED); return false; } const expectedTypes = computeValidTypesByExpressionOperator(operator); if (!left) { reasons(ParameterInvalidReason.EXPRESSION_LEFT_NOT_DEFINED); return false; } if (!isParameterValid4Pipeline({ parameter: left, allTopics, triggerTopic, variables, expectedTypes, array: false, reasons })) { return false; } if (operator !== ParameterExpressionOperator.NOT_EMPTY && operator !== ParameterExpressionOperator.EMPTY) { const array = operator === ParameterExpressionOperator.IN || operator === ParameterExpressionOperator.NOT_IN; if (!right) { reasons(ParameterInvalidReason.EXPRESSION_RIGHT_NOT_DEFINED); return false; } if (!isParameterValid4Pipeline({ parameter: right, allTopics, triggerTopic, variables, expectedTypes, array, reasons })) { return false; } } return true; }; export const isParameterValid4Pipeline = (options: { parameter: Parameter; allTopics: Array<Topic>; triggerTopic?: Topic; variables: DeclaredVariables; expectedTypes: ValueTypes; array?: boolean; reasons: (reason: ParameterInvalidReason) => void; }): boolean => { const {parameter, allTopics, triggerTopic, variables, expectedTypes, array = false, reasons} = options; if (!parameter) { return false; } if (isTopicFactorParameter(parameter)) { // a factor with type of primitive array is never existed // therefore any return value will be treated as an array which contains only one element return isTopicFactorParameterValid({parameter, topics: allTopics, expectedTypes, reasons}); } else if (isConstantParameter(parameter)) { return isConstantParameterValid({parameter, allTopics, triggerTopic, variables, expectedTypes, array, reasons}); } else if (isComputedParameter(parameter)) { return isComputedParameterValid({parameter, allTopics, triggerTopic, variables, expectedTypes, array, reasons}); } else { return false; } }; // noinspection JSUnusedLocalSymbols export const isConstantParameterValid = (options: { parameter: ConstantParameter; allTopics: Array<Topic>; triggerTopic?: Topic; variables: DeclaredVariables; expectedTypes: ValueTypes; // true only when // 1. parameter is right part of an expression and expression operator is in/not in // 2. parameter is in case-then // in these cases, only constant values are supported, which means anything if fine, validation ignored. array: boolean; reasons: (reason: ParameterInvalidReason) => void; }): boolean => { const {parameter, allTopics, triggerTopic, variables, expectedTypes, array, reasons} = options; if (array) { // constant return true; } const types = computeParameterTypes(parameter, allTopics, variables, triggerTopic) .filter(type => type.array === array); if (types.every(type => type.type === AnyFactorType.ERROR)) { // none of computed types is correct reasons(ParameterInvalidReason.CONSTANT_TYPE_NOT_MATCHED); return false; } if (expectedTypes.some(expectedType => expectedType === AnyFactorType.ANY)) { // one of expected types is any type return true; } if (types.some(type => type.type === AnyFactorType.ANY)) { // one of computed types is any type return true; } const actualExpectedTypes = expectedTypes.filter(expectedType => expectedType !== AnyFactorType.ERROR && expectedType !== AnyFactorType.ANY); return types.filter(type => type.type !== AnyFactorType.ERROR) .filter(type => type.array === array) .some(type => isFactorTypeCompatibleWith({ factorType: type.type as FactorType, expectedTypes: actualExpectedTypes, reasons: () => reasons(ParameterInvalidReason.CONSTANT_TYPE_NOT_MATCHED) })); }; const isTopicFactorParameterValid = (options: { parameter: TopicFactorParameter; topics: Array<Topic>; expectedTypes: ValueTypes; reasons: (reason: ParameterInvalidReason) => void; }): boolean => { const {parameter, topics, expectedTypes, reasons} = options; if (!parameter.topicId) { // no topic, failure reasons(ParameterInvalidReason.TOPIC_NOT_DEFINED); return false; } if (!parameter.factorId) { reasons(ParameterInvalidReason.FACTOR_NOT_DEFINED); return false; } // eslint-disable-next-line const topic = topics.find(topic => topic.topicId == parameter.topicId); if (!topic) { // topic not found, failure reasons(ParameterInvalidReason.TOPIC_NOT_FOUND); return false; } // eslint-disable-next-line const factor = topic.factors.find(factor => factor.factorId == parameter.factorId); if (!factor) { // factor not found, failure reasons(ParameterInvalidReason.FACTOR_NOT_FOUND); return false; } return isFactorTypeCompatibleWith({factorType: factor.type, expectedTypes, reasons}); }; const isComputedParameterValid = (options: { parameter: ComputedParameter; allTopics: Array<Topic>; triggerTopic?: Topic; variables: DeclaredVariables; expectedTypes: ValueTypes; array: boolean; reasons: (reason: ParameterInvalidReason) => void; }): boolean => { const {parameter, allTopics, triggerTopic, variables, expectedTypes, array, reasons} = options; const {type: computeType, parameters} = parameter; if (!computeType) { // type must exists reasons(ParameterInvalidReason.COMPUTE_TYPE_NOT_DEFINED); return false; } const calculatorDef = ParameterCalculatorDefsMap[computeType]; // no calculator if (calculatorDef.parameterCount && parameters.length !== calculatorDef.parameterCount) { // parameters length mismatch reasons(ParameterInvalidReason.COMPUTE_PARAMETER_COUNT_NOT_MATCHED); return false; } if (calculatorDef.minParameterCount && parameters.length < calculatorDef.minParameterCount) { // parameters length mismatch reasons(ParameterInvalidReason.COMPUTE_PARAMETER_COUNT_NOT_MATCHED); return false; } if (calculatorDef.maxParameterCount && parameters.length > calculatorDef.maxParameterCount) { // parameters length mismatch reasons(ParameterInvalidReason.COMPUTE_PARAMETER_COUNT_NOT_MATCHED); return false; } const hasEmptyParameter = parameters.some(param => !param); if (hasEmptyParameter) { reasons(ParameterInvalidReason.COMPUTE_PARAMETER_HAS_NOT_DEFINED); return false; } if (computeType === ParameterComputeType.CASE_THEN) { if (parameters.filter(parameter => !parameter.conditional || !parameter.on).length > 1) { // only one anyway route in case-then reasons(ParameterInvalidReason.COMPUTE_CASES_TOO_MANY_UNCONDITIONAL); return false; } } if (!isComputeTypeValid({ computeType, expectedTypes, reasons: () => reasons(ParameterInvalidReason.COMPUTE_RETURN_TYPE_NOT_MATCHED) })) { return false; } const subTypes = computeValidTypesForSubParameter(computeType, expectedTypes); return parameters.every(parameter => { if (parameter.conditional) { if (!parameter.on || parameter.on.filters.length === 0) { return false; } if (!isJointValid4Pipeline({joint: parameter.on, allTopics, triggerTopic, variables, reasons})) { return false; } } return isParameterValid4Pipeline({ parameter, allTopics, triggerTopic, variables, expectedTypes: subTypes, // only case-then should return an array // therefore any return value will be treated as an array which contains only one element // then true is passed only when compute type is case-then array: array && computeType === ParameterComputeType.CASE_THEN, reasons }); }); }; export const buildVariable = (options: { action: PipelineStageUnitAction; variables: DeclaredVariables; topics: Array<Topic>; triggerTopic?: Topic; }): DeclaredVariable | undefined => { const {action, variables, topics, triggerTopic} = options; if (isReadFactorAction(action)) { return { name: action.variableName.trim(), types: computeParameterTypes({ kind: ParameterKind.TOPIC, topicId: action.topicId, factorId: action.factorId } as TopicFactorParameter, topics, variables, triggerTopic) }; } else if (isReadFactorsAction(action)) { return { name: action.variableName.trim(), types: computeParameterTypes({ kind: ParameterKind.TOPIC, topicId: action.topicId, factorId: action.factorId } as TopicFactorParameter, topics, variables, triggerTopic).map(t => { t.array = true; return t; }) }; } else if (isReadRowAction(action)) { return { name: action.variableName.trim(), types: computeParameterTypes({ kind: ParameterKind.TOPIC, topicId: action.topicId } as TopicFactorParameter, topics, variables, triggerTopic) }; } else if (isReadRowsAction(action)) { return { name: action.variableName.trim(), types: computeParameterTypes({ kind: ParameterKind.TOPIC, topicId: action.topicId } as TopicFactorParameter, topics, variables, triggerTopic).map(t => { t.array = true; return t; }) }; } else if (isExistsAction(action)) { return { name: action.variableName.trim(), types: [{type: FactorType.BOOLEAN, array: false}] }; } else if (isCopyToMemoryAction(action)) { return { name: action.variableName.trim(), types: computeParameterTypes(action.source, topics, variables, triggerTopic) }; } }; export const buildVariables = ( topics: Array<Topic>, pipeline: Pipeline, stage?: PipelineStage, unit?: PipelineStageUnit, action?: PipelineStageUnitAction ): DeclaredVariables => { let actions: Array<PipelineStageUnitAction>; // compute actions before me if (stage && unit && action) { actions = pipeline.stages.slice(0, pipeline.stages.indexOf(stage) + 1).map(currentStage => { let units = currentStage.units || []; if (currentStage === stage) { units = units.slice(0, stage.units.indexOf(unit) + 1); } return units.map(currentUnit => { let actions = currentUnit.do || []; if (currentUnit === unit) { actions = actions.slice(0, unit.do.indexOf(action)); } return actions.filter(action => isReadTopicAction(action) || isCopyToMemoryAction(action)); }).flat(); }).flat(); } else if (stage && unit) { actions = pipeline.stages.slice(0, pipeline.stages.indexOf(stage) + 1).map(currentStage => { let units = currentStage.units || []; if (currentStage === stage) { units = units.slice(0, stage.units.indexOf(unit)); } return units.map(unit => { return (unit.do || []).filter(action => isReadTopicAction(action) || isCopyToMemoryAction(action)); }).flat(); }).flat(); } else if (stage) { actions = pipeline.stages.slice(0, pipeline.stages.indexOf(stage)).map(stage => { return (stage.units || []).map(unit => { return (unit.do || []).filter(action => isReadTopicAction(action) || isCopyToMemoryAction(action)); }).flat(); }).flat(); } else { // in pipeline, no variable yet actions = []; } const variables: DeclaredVariables = []; // eslint-disable-next-line const triggerTopic = topics.find(t => t.topicId == pipeline.topicId); actions.forEach(action => { const variable = buildVariable({action, variables, topics, triggerTopic}); if (variable) { variables.push(variable); } }); return variables.reduceRight((temp, v) => { if (!v.name || !v.name.trim()) { // ignore noname return temp; } v.name = v.name.trim(); // variable might be replaced if (!temp.exists[v.name]) { temp.all.push(v); temp.exists[v.name] = true; } return temp; }, {exists: {}, all: []} as { exists: Record<string, any>, all: DeclaredVariables }).all.reverse(); };
the_stack
import { BaseType } from "d3"; import { map as d3Map } from "d3-collection"; import { D3DragEvent, drag } from "d3-drag"; import { forceCollide, forceLink, forceManyBody, forceSimulation } from "d3-force"; import { interpolate, interpolateNumber } from "d3-interpolate"; import { scaleOrdinal } from "d3-scale"; import { schemeCategory10 } from "d3-scale-chromatic"; import { select, selectAll } from "d3-selection"; import { zoom, zoomIdentity } from "d3-zoom"; import * as ko from "knockout"; import Q from "q"; import _ from "underscore"; import * as Constants from "../../../Common/Constants"; import { NeighborType } from "../../../Contracts/ViewModels"; import { logConsoleError } from "../../../Utils/NotificationConsoleUtils"; import { IGraphConfig } from "./../../Tabs/GraphTab"; import { D3Link, D3Node, GraphData } from "./GraphData"; import { GraphExplorer } from "./GraphExplorer"; export interface D3GraphIconMap { [key: string]: { data: string; format: string }; } export interface D3GraphNodeData { g: any; // TODO needs this? id: string; } export enum PAGE_ACTION { FIRST_PAGE, PREVIOUS_PAGE, NEXT_PAGE, } export interface LoadMoreDataAction { nodeId: string; pageAction: PAGE_ACTION; } interface Point2D { x: number; y: number; } interface ZoomTransform extends Point2D { k: number; } export interface D3ForceGraphParameters { // Graph to parent igraphConfig: IGraphConfig; onHighlightedNode?: (highlightedNode: D3GraphNodeData) => void; // a new node has been highlighted in the graph onLoadMoreData?: (action: LoadMoreDataAction) => void; // parent to graph onInitialized?: (instance: GraphRenderer) => void; // For unit testing purposes onGraphUpdated?: (timestamp: number) => void; } export interface GraphRenderer { selectNode(id: string): void; resetZoom(): void; updateGraph(graphData: GraphData<D3Node, D3Link>, igraphConfigParam?: IGraphConfig): void; enableHighlight(enable: boolean): void; } /** This is the custom Knockout handler for the d3 graph */ export class D3ForceGraph implements GraphRenderer { // Some constants private static readonly GRAPH_WIDTH_PX = 900; private static readonly GRAPH_HEIGHT_PX = 700; private static readonly TEXT_DX = 12; private static readonly FORCE_COLLIDE_RADIUS = 40; private static readonly FORCE_COLLIDE_STRENGTH = 0.2; private static readonly FORCE_COLLIDE_ITERATIONS = 1; private static readonly NODE_LABEL_MAX_CHAR_LENGTH = 16; private static readonly FORCE_LINK_DISTANCE = 100; private static readonly FORCE_LINK_STRENGTH = 0.005; private static readonly INITIAL_POSITION_RADIUS = 150; private static readonly TRANSITION_STEP1_MS = 1000; private static readonly TRANSITION_STEP2_MS = 1000; private static readonly TRANSITION_STEP3_MS = 700; private static readonly PAGINATION_LINE1_Y_OFFSET_PX = 4; private static readonly PAGINATION_LINE2_Y_OFFSET_PX = 14; // We limit the number of different colors to 20 private static readonly COLOR_SCHEME = scaleOrdinal(schemeCategory10); private static readonly MAX_COLOR_NB = 20; // Some state variables private static instanceCount = 1; private instanceIndex: number; private svg: d3.Selection<Element, any, any, any>; private g: d3.Selection<Element, any, any, any>; private simulation: d3.Simulation<D3Node, D3Link>; private width: number; private height: number; private selectedNode: d3.BaseType; private isDragging: boolean; private rootVertex: D3Node; private nodeSelection: any; private linkSelection: any; private zoomTransform: ZoomTransform; private zoom: d3.ZoomBehavior<any, any>; private zoomBackground: d3.Selection<BaseType, any, any, any>; private viewCenter: Point2D; // Map a property to a graph node attribute (such as color) private uniqueValues: (string | number)[] = []; // keep track of unique values private graphDataWrapper: GraphData<D3Node, D3Link>; // Communication with outside // Graph -> outside public params: D3ForceGraphParameters; public errorMsgs: ko.ObservableArray<string>; // errors happen in graph // outside -> Graph private idToSelect: ko.Observable<string>; // Programmatically select node by id outside graph private isHighlightDisabled: boolean; public igraphConfig: IGraphConfig; public constructor(params: D3ForceGraphParameters) { this.params = params; this.igraphConfig = this.params.igraphConfig; this.idToSelect = ko.observable(null); this.errorMsgs = ko.observableArray([]); this.graphDataWrapper = null; this.width = D3ForceGraph.GRAPH_WIDTH_PX; this.height = D3ForceGraph.GRAPH_HEIGHT_PX; this.rootVertex = null; this.isHighlightDisabled = false; this.zoomTransform = { x: 0, y: 0, k: 1 }; this.viewCenter = { x: this.width / 2, y: this.height / 2 }; this.instanceIndex = D3ForceGraph.instanceCount++; } public init(element: Element): void { this.initializeGraph(element); this.params.onInitialized(this); } public destroy(): void { this.simulation.stop(); this.simulation = null; this.graphDataWrapper = null; this.linkSelection = null; this.nodeSelection = null; this.g.remove(); } public updateGraph(newGraph: GraphData<D3Node, D3Link>, igraphConfigParam?: IGraphConfig): void { if (igraphConfigParam) { this.igraphConfig = igraphConfigParam; } if (!newGraph || !this.simulation) { return; } // Build new GraphData object from it this.graphDataWrapper = new GraphData<D3Node, D3Link>(); this.graphDataWrapper.setData(newGraph); const key = this.igraphConfig.nodeColorKey; if (key !== GraphExplorer.NONE_CHOICE) { this.updateUniqueValues(key); } // d3 expects source and target properties for each link (edge) $.each(this.graphDataWrapper.edges, (i, e) => { e.target = e.inV; e.source = e.outV; }); this.onGraphDataUpdate(this.graphDataWrapper); } public resetZoom(): void { this.zoomBackground.call(this.zoom.transform, zoomIdentity); this.viewCenter = { x: this.width / 2, y: this.height / 2 }; } public enableHighlight(enable: boolean): void { this.isHighlightDisabled = enable; } public selectNode(id: string): void { this.idToSelect(id); } public getArrowHeadSymbolId(): string { return `triangle-${this.instanceIndex}`; } /** * Count edges and store in a hashmap: vertex id <--> number of links * @param linkSelection */ public static countEdges(links: D3Link[]): Map<string, number> { const countMap = new Map<string, number>(); links.forEach((l: D3Link) => { let val = countMap.get(l.inV) || 0; val += 1; countMap.set(l.inV, val); val = countMap.get(l.outV) || 0; val += 1; countMap.set(l.outV, val); }); return countMap; } /** * Construct the graph * @param graphData */ private initializeGraph(element: Element): void { this.zoom = zoom() .scaleExtent([1 / 2, 4]) .on("zoom", this.zoomed.bind(this)); this.svg = select(element) .attr("viewBox", `0 0 ${this.width} ${this.height}`) .attr("preserveAspectRatio", "xMidYMid slice"); this.zoomBackground = this.svg.call(this.zoom); element.addEventListener("click", (e: Event) => { // IE 11 doesn't support el.classList and there's no polyfill for it // Don't auto-deselect when not clicking on a node if (!(<any>e.target).classList) { return; } if ( !D3ForceGraph.closest(e.target, (el: any) => { return !!el && el !== document && el.classList.contains("node"); }) ) { this.deselectNode(); } }); this.g = this.svg.append("g"); this.linkSelection = this.g.append("g").attr("class", "links").selectAll(".link"); this.nodeSelection = this.g.append("g").attr("class", "nodes").selectAll(".node"); // Reset state variables this.selectedNode = null; this.isDragging = false; this.idToSelect.subscribe((newVal) => { if (!newVal) { this.deselectNode(); return; } var self = this; // Select this node id selectAll(".node") .filter(function (d: D3Node, i) { return d.id === newVal; }) .each(function (d: D3Node) { self.onNodeClicked(this, d); }); }); this.redrawGraph(); this.instantiateSimulation(); } // initialize private updateUniqueValues(key: string) { for (var i = 0; i < this.graphDataWrapper.vertices.length; i++) { let vertex = this.graphDataWrapper.vertices[i]; let props = D3ForceGraph.getNodeProperties(vertex); if (props.indexOf(key) === -1) { // Vertex doesn't have the property continue; } let val = GraphData.getNodePropValue(vertex, key); if (typeof val !== "string" && typeof val !== "number") { // Not a type we can map continue; } // Map this value if new if (this.uniqueValues.indexOf(val) === -1) { this.uniqueValues.push(val); } if (this.uniqueValues.length === D3ForceGraph.MAX_COLOR_NB) { this.errorMsgs.push( `Number of unique values for property ${key} exceeds maximum (${D3ForceGraph.MAX_COLOR_NB})` ); // ignore rest of values break; } } } /** * Retrieve all node properties * NOTE: This is DocDB specific. We expect to have 'id' and 'label' and a bunch of 'properties' * @param node */ private static getNodeProperties(node: D3Node): string[] { let props = ["id", "label"]; if (node.hasOwnProperty("properties")) { props = props.concat(Object.keys(node.properties)); } return props; } // Click on non-nodes deselects private static closest(el: any, predicate: any) { do { if (predicate(el)) { return el; } } while ((el = el && el.parentNode)); } private zoomed(event: any) { this.zoomTransform = { x: event.transform.x, y: event.transform.y, k: event.transform.k, }; this.g.attr("transform", event.transform); } private instantiateSimulation() { this.simulation = forceSimulation<D3Node, D3Link>() .force( "link", forceLink() .id((d: D3Node) => { return d.id; }) .distance(D3ForceGraph.FORCE_LINK_DISTANCE) .strength(D3ForceGraph.FORCE_LINK_STRENGTH) ) .force("charge", forceManyBody()) .force( "collide", forceCollide(D3ForceGraph.FORCE_COLLIDE_RADIUS) .strength(D3ForceGraph.FORCE_COLLIDE_STRENGTH) .iterations(D3ForceGraph.FORCE_COLLIDE_ITERATIONS) ); } /** * Shift graph to make this targetPosition as new center * @param targetPosition * @return promise with shift offset */ private shiftGraph(targetPosition: Point2D): Q.Promise<Point2D> { const deferred: Q.Deferred<Point2D> = Q.defer<Point2D>(); const offset = { x: this.width / 2 - targetPosition.x, y: this.height / 2 - targetPosition.y, }; this.viewCenter = targetPosition; if (Math.abs(offset.x) > 0.5 && Math.abs(offset.y) > 0.5) { const transform = () => { return zoomIdentity .translate(this.width / 2, this.height / 2) .scale(this.zoomTransform.k) .translate(-targetPosition.x, -targetPosition.y); }; this.zoomBackground .transition() .duration(D3ForceGraph.TRANSITION_STEP1_MS) .call(this.zoom.transform, transform) .on("end", () => { deferred.resolve(offset); }); } else { deferred.resolve(null); } return deferred.promise; } private onGraphDataUpdate(graph: GraphData<D3Node, D3Link>) { // shift all nodes so that new clicked on node is in the center this.isHighlightDisabled = true; this.unhighlightNode(); this.simulation.stop(); // Find root node position const rootId = graph.findRootNodeId(); // Remember nodes current position const posMap = new Map<string, Point2D>(); this.simulation.nodes().forEach((d: D3Node) => { if (d.x == undefined || d.y == undefined) { return; } posMap.set(d.id, { x: d.x, y: d.y }); }); const restartSimulation = () => { this.restartSimulation(graph, posMap); this.isHighlightDisabled = false; }; if (rootId && posMap.has(rootId)) { this.shiftGraph(posMap.get(rootId)).then(restartSimulation); } else { restartSimulation(); } } private animateRemoveExitSelections(): Q.Promise<void> { const deferred1 = Q.defer<void>(); const deferred2 = Q.defer<void>(); const linkExitSelection = this.linkSelection.exit(); let linkCounter = linkExitSelection.size(); if (linkCounter > 0) { if (D3ForceGraph.useSvgMarkerEnd()) { this.svg .select(`#${this.getArrowHeadSymbolId()}-marker`) .transition() .duration(D3ForceGraph.TRANSITION_STEP2_MS) .attr("fill-opacity", 0) .attr("stroke-opacity", 0); } else { this.svg.select(`#${this.getArrowHeadSymbolId()}-nonMarker`).classed("hidden", true); } linkExitSelection.select(".link").transition().duration(D3ForceGraph.TRANSITION_STEP2_MS).attr("stroke-width", 0); linkExitSelection .transition() .delay(D3ForceGraph.TRANSITION_STEP2_MS) .remove() .on("end", () => { if (--linkCounter <= 0) { deferred1.resolve(); } }); } else { deferred1.resolve(); } const nodeExitSelection = this.nodeSelection.exit(); let nodeCounter = nodeExitSelection.size(); if (nodeCounter > 0) { nodeExitSelection.selectAll("circle").transition().duration(D3ForceGraph.TRANSITION_STEP2_MS).attr("r", 0); nodeExitSelection .selectAll(".iconContainer") .transition() .duration(D3ForceGraph.TRANSITION_STEP2_MS) .attr("opacity", 0); nodeExitSelection .selectAll(".loadmore") .transition() .duration(D3ForceGraph.TRANSITION_STEP2_MS) .attr("opacity", 0); nodeExitSelection.selectAll("text").transition().duration(D3ForceGraph.TRANSITION_STEP2_MS).style("opacity", 0); nodeExitSelection .transition() .delay(D3ForceGraph.TRANSITION_STEP2_MS) .remove() .on("end", () => { if (--nodeCounter <= 0) { deferred2.resolve(); } }); } else { deferred2.resolve(); } return Q.allSettled([deferred1.promise, deferred2.promise]).then(undefined); } /** * All non-fixed nodes start from the center and spread them away from the center like fireworks. * Then fade in the nodes labels and Load More icon. * @param nodes * @param newNodes */ private animateBigBang(nodes: D3Node[], newNodes: d3.Selection<Element, any, any, any>) { if (!nodes || nodes.length === 0) { return; } const nodeFinalPositionMap = new Map<string, Point2D>(); const viewCenter = this.viewCenter; const nonFixedNodes = _.filter(nodes, (node: D3Node) => { return !node._isFixedPosition && node.x === viewCenter.x && node.y === viewCenter.y; }); const n = nonFixedNodes.length; const da = (Math.PI * 2) / n; const daOffset = Math.random() * Math.PI * 2; for (let i = 0; i < n; i++) { const d = nonFixedNodes[i]; const angle = da * i + daOffset; d.fx = viewCenter.x; d.fy = viewCenter.y; const x = viewCenter.x + Math.cos(angle) * D3ForceGraph.INITIAL_POSITION_RADIUS; const y = viewCenter.y + Math.sin(angle) * D3ForceGraph.INITIAL_POSITION_RADIUS; nodeFinalPositionMap.set(d.id, { x: x, y: y }); } // Animate nodes newNodes .transition() .duration(D3ForceGraph.TRANSITION_STEP3_MS) .attrTween("transform", (d: D3Node) => { const finalPos = nodeFinalPositionMap.get(d.id) || { x: viewCenter.x, y: viewCenter.y, }; const ix = interpolateNumber(viewCenter.x, finalPos.x); const iy = interpolateNumber(viewCenter.y, finalPos.y); return (t: number) => { d.fx = ix(t); d.fy = iy(t); return this.positionNode(d); }; }) .on("end", (d: D3Node) => { if (!d._isFixedPosition) { d.fx = null; d.fy = null; } }); // Delay appearance of text and loadMore newNodes .selectAll(".caption") .attr("fill", "#ffffff") .transition() .delay(D3ForceGraph.TRANSITION_STEP3_MS - 100) .duration(D3ForceGraph.TRANSITION_STEP3_MS) .attrTween("fill", (t: any) => { const ic = interpolate("#ffffff", "#000000"); return (t: number) => { return ic(t); }; }); newNodes.selectAll(".loadmore").attr("visibility", "hidden").transition().delay(600).attr("visibility", "visible"); } private restartSimulation(graph: GraphData<D3Node, D3Link>, posMap: Map<string, Point2D>) { if (!graph) { return; } const viewCenter = this.viewCenter; // Distribute nodes initial position before simulation const nodes = graph.vertices; for (let i = 0; i < nodes.length; i++) { let v = nodes[i]; if (v._isRoot) { this.rootVertex = v; } if (v._isFixedPosition && posMap.has(v.id)) { const pos = posMap.get(v.id); v.fx = pos.x; v.fy = pos.y; } else if (v._isRoot) { v.fx = viewCenter.x; v.fy = viewCenter.y; } else if (posMap.has(v.id)) { const pos = posMap.get(v.id); v.x = pos.x; v.y = pos.y; } else { v.x = viewCenter.x; v.y = viewCenter.y; } } const nodeById = d3Map(nodes, (d: D3Node) => { return d.id; }); const links = graph.edges; links.forEach((link: D3Link) => { link.source = nodeById.get(<string>link.source); link.target = nodeById.get(<string>link.target); }); this.linkSelection = this.linkSelection.data(links, (l: D3Link) => { return `${(<D3Node>l.source).id}_${(<D3Node>l.target).id}`; }); this.nodeSelection = this.nodeSelection.data(nodes, (d: D3Node) => { return d.id; }); const removePromise = this.animateRemoveExitSelections(); const self = this; this.simulation.nodes(nodes).on("tick", ticked); this.simulation.force<d3.ForceLink<D3Node, D3Link>>("link").links(graph.edges); removePromise.then(() => { if (D3ForceGraph.useSvgMarkerEnd()) { this.svg.select(`#${this.getArrowHeadSymbolId()}-marker`).attr("fill-opacity", 1).attr("stroke-opacity", 1); } else { this.svg.select(`#${this.getArrowHeadSymbolId()}-nonMarker`).classed("hidden", false); } const newNodes = this.addNewNodes(); this.updateLoadMore(this.nodeSelection); this.addNewLinks(); const nodes1 = this.simulation.nodes(); this.redrawGraph(); this.animateBigBang(nodes1, newNodes); this.simulation.alpha(1).restart(); this.params.onGraphUpdated(new Date().getTime()); }); function ticked() { self.linkSelection.select(".link").attr("d", (l: D3Link) => { return self.positionLink(l); }); if (!D3ForceGraph.useSvgMarkerEnd()) { self.linkSelection.select(".markerEnd").attr("transform", (l: D3Link) => { return self.positionLinkEnd(l); }); } self.nodeSelection.attr("transform", (d: D3Node) => { return self.positionNode(d); }); } } private addNewLinks(): d3.Selection<Element, any, any, any> { const newLinks = this.linkSelection.enter().append("g").attr("class", "markerEndContainer"); const line = newLinks .append("path") .attr("class", "link") .attr("fill", "none") .attr("stroke-width", this.igraphConfig.linkWidth) .attr("stroke", this.igraphConfig.linkColor); if (D3ForceGraph.useSvgMarkerEnd()) { line.attr("marker-end", `url(#${this.getArrowHeadSymbolId()}-marker)`); } else { newLinks .append("g") .append("use") .attr("xlink:href", `#${this.getArrowHeadSymbolId()}-nonMarker`) .attr("class", "markerEnd link") .attr("fill", this.igraphConfig.linkColor) .classed(`${this.getArrowHeadSymbolId()}`, true); } this.linkSelection = newLinks.merge(this.linkSelection); return newLinks; } private addNewNodes(): d3.Selection<Element, any, any, any> { var self = this; const newNodes = this.nodeSelection .enter() .append("g") .attr("class", (d: D3Node) => { return d._isRoot ? "node root" : "node"; }) .call( drag() .on("start", ((e: D3DragEvent<SVGGElement, D3Node, unknown>, d: D3Node) => { return this.dragstarted(d, e); }) as any) .on("drag", ((e: D3DragEvent<SVGGElement, D3Node, unknown>, d: D3Node) => { return this.dragged(d, e); }) as any) .on("end", ((e: D3DragEvent<SVGGElement, D3Node, unknown>, d: D3Node) => { return this.dragended(d, e); }) as any) ) .on("mouseover", (_: MouseEvent, d: D3Node) => { if (this.isHighlightDisabled || this.selectedNode || this.isDragging) { return; } this.highlightNode(this, d); this.simulation.stop(); }) .on("mouseout", (_: MouseEvent, d: D3Node) => { if (this.isHighlightDisabled || this.selectedNode || this.isDragging) { return; } this.unhighlightNode(); this.simulation.restart(); }) .each((d: D3Node) => { // Initial position for nodes. This prevents blinking as following the tween transition doesn't always start right away d.x = self.viewCenter.x; d.y = self.viewCenter.y; }); newNodes .append("circle") .attr("fill", this.getNodeColor.bind(this)) .attr("class", "main") .attr("r", this.igraphConfig.nodeSize); var iconGroup = newNodes .append("g") .attr("class", "iconContainer") .attr("tabindex", 0) .attr("aria-label", (d: D3Node) => { return this.retrieveNodeCaption(d); }) .on("dblclick", function (this: Element, _: MouseEvent, d: D3Node) { // https://stackoverflow.com/a/41945742 ('this' implicitly has type 'any' because it does not have a type annotation) // this is the <g> element self.onNodeClicked(this.parentNode, d); }) .on("click", function (this: Element, _: MouseEvent, d: D3Node) { // this is the <g> element self.onNodeClicked(this.parentNode, d); }) .on("keypress", function (this: Element, event: KeyboardEvent, d: D3Node) { if (event.charCode === Constants.KeyCodes.Space || event.charCode === Constants.KeyCodes.Enter) { event.stopPropagation(); // this is the <g> element self.onNodeClicked(this.parentNode, d); } }); var nodeSize = this.igraphConfig.nodeSize; var bgsize = nodeSize + 1; iconGroup .append("rect") .attr("x", -bgsize) .attr("y", -bgsize) .attr("width", bgsize * 2) .attr("height", bgsize * 2) .attr("fill-opacity", (d: D3Node) => { return this.igraphConfig.nodeIconKey ? 1 : 0; }) .attr("class", "icon-background"); // Possible icon: if xlink:href is undefined, the image won't show iconGroup .append("svg:image") .attr("xlink:href", (d: D3Node) => { return D3ForceGraph.computeImageData(d, this.igraphConfig); }) .attr("x", -nodeSize) .attr("y", -nodeSize) .attr("height", nodeSize * 2) .attr("width", nodeSize * 2) .attr("class", "icon"); newNodes .append("text") .attr("class", "caption") .attr("dx", D3ForceGraph.TEXT_DX) .attr("dy", ".35em") .text((d: D3Node) => { return this.retrieveNodeCaption(d); }); this.nodeSelection = newNodes.merge(this.nodeSelection); return newNodes; } /** * Pagination display and buttons * @param parent * @param nodeSize */ private createPaginationControl(parent: d3.Selection<BaseType, any, any, any>, nodeSize: number) { const self = this; const gaugeWidth = 50; const btnXOffset = gaugeWidth / 2; const yOffset = 10 + nodeSize; const gaugeYOffset = yOffset + 3; const gaugeHeight = 14; parent .append("line") .attr("x1", 0) .attr("y1", nodeSize) .attr("x2", 0) .attr("y2", gaugeYOffset) .style("stroke-width", 1) .style("stroke", this.igraphConfig.linkColor); parent .append("use") .attr("xlink:href", "#triangleRight") .attr("class", "pageButton") .attr("y", yOffset) .attr("x", btnXOffset) .attr("aria-label", (d: D3Node) => { return `Next page of nodes for ${this.retrieveNodeCaption(d)}`; }) .attr("tabindex", 0) .on("click", ((_: MouseEvent, d: D3Node) => { self.loadNeighbors(d, PAGE_ACTION.NEXT_PAGE); }) as any) .on("dblclick", ((_: MouseEvent, d: D3Node) => { self.loadNeighbors(d, PAGE_ACTION.NEXT_PAGE); }) as any) .on("keypress", ((event: KeyboardEvent, d: D3Node) => { if (event.charCode === Constants.KeyCodes.Space || event.charCode === Constants.KeyCodes.Enter) { event.stopPropagation(); self.loadNeighbors(d, PAGE_ACTION.NEXT_PAGE); } }) as any) .on("mouseover", ((e: MouseEvent, d: D3Node) => { select(e.target as any).classed("active", true); }) as any) .on("mouseout", ((e: MouseEvent, d: D3Node) => { select(e.target as any).classed("active", false); }) as any) .attr("visibility", (d: D3Node) => (!d._outEAllLoaded || !d._inEAllLoaded ? "visible" : "hidden")); parent .append("use") .attr("xlink:href", "#triangleRight") .attr("class", "pageButton") .attr("y", yOffset) .attr("transform", `translate(${-btnXOffset}), scale(-1, 1)`) .attr("aria-label", (d: D3Node) => { return `Previous page of nodes for ${this.retrieveNodeCaption(d)}`; }) .attr("tabindex", 0) .on("click", ((_: MouseEvent, d: D3Node) => { self.loadNeighbors(d, PAGE_ACTION.PREVIOUS_PAGE); }) as any) .on("dblclick", ((_: MouseEvent, d: D3Node) => { self.loadNeighbors(d, PAGE_ACTION.PREVIOUS_PAGE); }) as any) .on("keypress", ((event: KeyboardEvent, d: D3Node) => { if (event.charCode === Constants.KeyCodes.Space || event.charCode === Constants.KeyCodes.Enter) { event.stopPropagation(); self.loadNeighbors(d, PAGE_ACTION.PREVIOUS_PAGE); } }) as any) .on("mouseover", ((e: MouseEvent, d: D3Node) => { select(e.target as any).classed("active", true); }) as any) .on("mouseout", ((e: MouseEvent, d: D3Node) => { select(e.target as any).classed("active", false); }) as any) .attr("visibility", (d: D3Node) => !d._pagination || d._pagination.currentPage.start !== 0 ? "visible" : "hidden" ); parent .append("rect") .attr("x", -btnXOffset) .attr("y", gaugeYOffset) .attr("width", gaugeWidth) .attr("height", gaugeHeight) .style("fill", "white") .style("stroke-width", 1) .style("stroke", this.igraphConfig.linkColor); parent .append("rect") .attr("x", (d: D3Node) => { const pageInfo = d._pagination; return pageInfo && pageInfo.total ? -btnXOffset + (gaugeWidth * pageInfo.currentPage.start) / pageInfo.total : 0; }) .attr("y", gaugeYOffset) .attr("width", (d: D3Node) => { const pageInfo = d._pagination; return pageInfo && pageInfo.total ? (gaugeWidth * (pageInfo.currentPage.end - pageInfo.currentPage.start)) / pageInfo.total : 0; }) .attr("height", gaugeHeight) .style("fill", this.igraphConfig.nodeColor) .attr("visibility", (d: D3Node) => (d._pagination && d._pagination.total ? "visible" : "hidden")); parent .append("text") .attr("x", 0) .attr("y", gaugeYOffset + gaugeHeight / 2 + D3ForceGraph.PAGINATION_LINE1_Y_OFFSET_PX) .text((d: D3Node) => { const pageInfo = d._pagination; /* * pageInfo is zero-based but for the purpose of user display, current page start and end are 1-based. * current page end is the upper-bound (not included), but for the purpose user display we show included upper-bound * For example: start = 0, end = 11 will display 1-10. */ // pageInfo is zero-based, but for the purpose of user display, current page start and end are 1-based. // return `${pageInfo.currentPage.start + 1}-${pageInfo.currentPage.end}`; }) .attr("text-anchor", "middle") .style("font-size", "10px"); parent .append("text") .attr("x", 0) .attr( "y", gaugeYOffset + gaugeHeight / 2 + D3ForceGraph.PAGINATION_LINE1_Y_OFFSET_PX + D3ForceGraph.PAGINATION_LINE2_Y_OFFSET_PX ) .text((d: D3Node) => { const pageInfo = d._pagination; return `total: ${pageInfo.total}`; }) .attr("text-anchor", "middle") .style("font-size", "10px") .attr("visibility", (d: D3Node) => (d._pagination && d._pagination.total ? "visible" : "hidden")); } private createLoadMoreControl(parent: d3.Selection<d3.BaseType, any, any, any>, nodeSize: number) { const self = this; parent .append("use") .attr("class", "loadMoreIcon") .attr("xlink:href", "#loadMoreIcon") .attr("x", -15) .attr("y", nodeSize) .attr("aria-label", (d: D3Node) => { return `Load adjacent nodes for ${this.retrieveNodeCaption(d)}`; }) .attr("tabindex", 0) .on("click", ((_: MouseEvent, d: D3Node) => { self.loadNeighbors(d, PAGE_ACTION.FIRST_PAGE); }) as any) .on("dblclick", ((_: MouseEvent, d: D3Node) => { self.loadNeighbors(d, PAGE_ACTION.FIRST_PAGE); }) as any) .on("keypress", ((event: KeyboardEvent, d: D3Node) => { if (event.charCode === Constants.KeyCodes.Space || event.charCode === Constants.KeyCodes.Enter) { event.stopPropagation(); self.loadNeighbors(d, PAGE_ACTION.FIRST_PAGE); } }) as any) .on("mouseover", ((e: MouseEvent, d: D3Node) => { select(e.target as any).classed("active", true); }) as any) .on("mouseout", ((e: MouseEvent, d: D3Node) => { select(e.target as any).classed("active", false); }) as any); } /** * Remove LoadMore subassembly for existing nodes that show all their children in the graph */ private updateLoadMore(nodeSelection: d3.Selection<Element, any, any, any>) { const self = this; nodeSelection.selectAll(".loadmore").remove(); var nodeSize = this.igraphConfig.nodeSize; const rootSelectionG = nodeSelection .filter((d: D3Node) => { return !!d._isRoot && !!d._pagination; }) .append("g") .attr("class", "loadmore"); this.createPaginationControl(rootSelectionG, nodeSize); const nodeNeighborMap = D3ForceGraph.countEdges(this.linkSelection.data()); const missingNeighborNonRootG = nodeSelection .filter((d: D3Node) => { return !( d._isRoot || (d._outEAllLoaded && d._inEAllLoaded && nodeNeighborMap.get(d.id) >= d._outEdgeIds.length + d._inEdgeIds.length) ); }) .append("g") .attr("class", "loadmore"); this.createLoadMoreControl(missingNeighborNonRootG, nodeSize); // Don't color icons individually, just the definitions this.svg.selectAll("#loadMoreIcon ellipse").attr("fill", this.igraphConfig.nodeColor); } /** * Load neighbors of this node */ private loadNeighbors(v: D3Node, pageAction: PAGE_ACTION) { if (!this.graphDataWrapper.hasVertexId(v.id)) { logConsoleError(`Clicked node not in graph data. id: ${v.id}`); return; } this.params.onLoadMoreData({ nodeId: v.id, pageAction: pageAction, }); } /** * If not mapped, return max Color * @param key */ private lookupColorFromKey(key: string): string { let index = this.uniqueValues.indexOf(key); if (index < 0 || index >= D3ForceGraph.MAX_COLOR_NB) { index = D3ForceGraph.MAX_COLOR_NB - 1; } return D3ForceGraph.COLOR_SCHEME(index.toString()); } /** * Get node color * If nodeColorKey is defined, lookup the node color from uniqueStrings. * Otherwise use nodeColor. * @param d */ private getNodeColor(d: D3Node): string { if (this.igraphConfig.nodeColorKey) { const val = GraphData.getNodePropValue(d, this.igraphConfig.nodeColorKey); return this.lookupColorFromKey(<string>val); } else { return this.igraphConfig.nodeColor; } } private dragstarted(d: D3Node, event: D3DragEvent<SVGGElement, D3Node, unknown>) { this.isDragging = true; if (!event.active) { this.simulation.alphaTarget(0.3).restart(); } d.fx = d.x; d.fy = d.y; } private dragged(d: D3Node, event: D3DragEvent<SVGGElement, D3Node, unknown>) { d.fx = event.x; d.fy = event.y; } private dragended(d: D3Node, event: D3DragEvent<SVGGElement, D3Node, unknown>) { this.isDragging = false; if (!event.active) { this.simulation.alphaTarget(0); } d.fx = null; d.fy = null; } private highlightNode(g: any, d: D3Node) { this.fadeNonNeighbors(d.id); this.params.onHighlightedNode({ g: g, id: d.id }); } private unhighlightNode() { this.g.selectAll(".node").classed("inactive", false); this.g.selectAll(".link").classed("inactive", false); this.params.onHighlightedNode(null); this.setRootAsHighlighted(); } /** * Set the root node as highlighted, but don't fade neighbors. * We use this to show the root properties */ private setRootAsHighlighted() { if (!this.rootVertex) { return; } this.params.onHighlightedNode({ g: null, id: this.rootVertex.id }); } private fadeNonNeighbors(nodeId: string) { this.g.selectAll(".node").classed("inactive", (d: D3Node) => { var neighbors = ((showNeighborType) => { switch (showNeighborType) { case NeighborType.SOURCES_ONLY: return this.graphDataWrapper.getSourcesForId(nodeId); case NeighborType.TARGETS_ONLY: return this.graphDataWrapper.getTargetsForId(nodeId); default: case NeighborType.BOTH: return (this.graphDataWrapper.getSourcesForId(nodeId) || []).concat( this.graphDataWrapper.getTargetsForId(nodeId) ); } })(this.igraphConfig.showNeighborType); return (!neighbors || neighbors.indexOf(d.id) === -1) && d.id !== nodeId; }); this.g.selectAll(".link").classed("inactive", (l: D3Link) => { switch (this.igraphConfig.showNeighborType) { case NeighborType.SOURCES_ONLY: return (<D3Node>l.target).id !== nodeId; case NeighborType.TARGETS_ONLY: return (<D3Node>l.source).id !== nodeId; default: case NeighborType.BOTH: return (<D3Node>l.target).id !== nodeId && (<D3Node>l.source).id !== nodeId; } }); } private onNodeClicked(g: d3.BaseType, d: D3Node) { if (this.isHighlightDisabled) { return; } if (g === this.selectedNode) { this.deselectNode(); return; } // unselect old none select(this.selectedNode).classed("selected", false); this.unhighlightNode(); // select new one select(g).classed("selected", true); this.selectedNode = g; this.highlightNode(g, d); } private deselectNode() { if (!this.selectedNode) { return; } // Unselect select(this.selectedNode).classed("selected", false); this.selectedNode = null; this.unhighlightNode(); } private retrieveNodeCaption(d: D3Node) { let key = this.igraphConfig.nodeCaption; let value: string = d.id || d.label; if (key) { value = <string>GraphData.getNodePropValue(d, key) || ""; } // Manually ellipsize if (value.length > D3ForceGraph.NODE_LABEL_MAX_CHAR_LENGTH) { value = value.substr(0, D3ForceGraph.NODE_LABEL_MAX_CHAR_LENGTH) + "\u2026"; } return value; } private static calculateClosestPIOver2(angle: number): number { const CURVATURE_FACTOR = 40; const result = Math.atan(CURVATURE_FACTOR * (angle - Math.PI / 4)) / 2 + Math.PI / 4; return result; } private static calculateClosestPIOver4(angle: number): number { const CURVATURE_FACTOR = 100; const result = Math.atan(CURVATURE_FACTOR * (angle - Math.PI / 8)) / 4 + Math.PI / 8; return result; } private static calculateControlPoint(start: Point2D, end: Point2D): Point2D { const alpha = Math.atan2(end.y - start.y, end.x - start.x); const n = Math.floor(alpha / (Math.PI / 2)); const reducedAlpha = alpha - (n * Math.PI) / 2; const reducedBeta = D3ForceGraph.calculateClosestPIOver2(reducedAlpha); const beta = reducedBeta + (n * Math.PI) / 2; const length = Math.sqrt((end.y - start.y) * (end.y - start.y) + (end.x - start.x) * (end.x - start.x)) / 2; const result = { x: start.x + Math.cos(beta) * length, y: start.y + Math.sin(beta) * length, }; return result; } private positionLinkEnd(l: D3Link) { const source: Point2D = { x: (<D3Node>l.source).x, y: (<D3Node>l.source).y, }; const target: Point2D = { x: (<D3Node>l.target).x, y: (<D3Node>l.target).y, }; const d1 = D3ForceGraph.calculateControlPoint(source, target); var radius = this.igraphConfig.nodeSize + 3; // End const dx = target.x - d1.x; const dy = target.y - d1.y; const angle = Math.atan2(dy, dx); var ux = target.x - Math.cos(angle) * radius; var uy = target.y - Math.sin(angle) * radius; return `translate(${ux},${uy}) rotate(${(angle * 180) / Math.PI})`; } private positionLink(l: D3Link) { const source: Point2D = { x: (<D3Node>l.source).x, y: (<D3Node>l.source).y, }; const target: Point2D = { x: (<D3Node>l.target).x, y: (<D3Node>l.target).y, }; const d1 = D3ForceGraph.calculateControlPoint(source, target); var radius = this.igraphConfig.nodeSize + 3; // Start var dx = d1.x - source.x; var dy = d1.y - source.y; var angle = Math.atan2(dy, dx); var tx = source.x + Math.cos(angle) * radius; var ty = source.y + Math.sin(angle) * radius; // End dx = target.x - d1.x; dy = target.y - d1.y; angle = Math.atan2(dy, dx); var ux = target.x - Math.cos(angle) * radius; var uy = target.y - Math.sin(angle) * radius; return "M" + tx + "," + ty + "S" + d1.x + "," + d1.y + " " + ux + "," + uy; } private positionNode(d: D3Node) { return "translate(" + d.x + "," + d.y + ")"; } private redrawGraph() { if (!this.simulation) { return; } this.g.selectAll(".node").attr("class", (d: D3Node) => { return d._isRoot ? "node root" : "node"; }); this.applyConfig(this.igraphConfig); } private static computeImageData(d: D3Node, config: IGraphConfig): string { let propValue = <string>GraphData.getNodePropValue(d, config.nodeIconKey) || ""; // Trim leading and trailing spaces to make comparison more forgiving. let value = config.iconsMap[propValue.trim()]; if (!value) { return undefined; } return `data:image/${value.format};base64,${value.data}`; } /** * Update graph according to configuration or use default */ private applyConfig(config: IGraphConfig) { if (config.nodeIconKey) { this.g .selectAll(".node .icon") .attr("xlink:href", (d: D3Node) => { return D3ForceGraph.computeImageData(d, config); }) .attr("x", -config.nodeSize) .attr("y", -config.nodeSize) .attr("height", config.nodeSize * 2) .attr("width", config.nodeSize * 2) .attr("class", "icon"); } else { // clear icons this.g.selectAll(".node .icon").attr("xlink:href", undefined); } this.g.selectAll(".node .icon-background").attr("fill-opacity", (d: D3Node) => { return config.nodeIconKey ? 1 : 0; }); this.g.selectAll(".node text.caption").text((d: D3Node) => { return this.retrieveNodeCaption(d); }); this.g.selectAll(".node circle.main").attr("r", config.nodeSize); this.g.selectAll(".node text.caption").attr("dx", config.nodeSize + 2); this.g.selectAll(".node circle").attr("fill", this.getNodeColor.bind(this)); // Can't color nodes individually if using defs this.svg.selectAll("#loadMoreIcon ellipse").attr("fill", config.nodeColor); this.g.selectAll(".link").attr("stroke-width", config.linkWidth); this.g.selectAll(".link").attr("stroke", config.linkColor); if (D3ForceGraph.useSvgMarkerEnd()) { this.svg .select(`#${this.getArrowHeadSymbolId()}-marker`) .attr("fill", config.linkColor) .attr("stroke", config.linkColor); } else { this.svg.select(`#${this.getArrowHeadSymbolId()}-nonMarker`).attr("fill", config.linkColor); } // Reset highlight this.g.selectAll(".node circle").attr("opacity", null); } /** * On Edge browsers, there's a bug when using the marker-end attribute. * It make the whole app reload when zooming and panning. * So we draw the arrow heads manually and must also reposition manually. * In this case, the UX is slightly degraded (no animation when removing arrow) */ private static useSvgMarkerEnd(): boolean { // Use for all browsers except Edge return window.navigator.userAgent.indexOf("Edge") === -1; } }
the_stack
import { ActionEvent, Actor, ActorLike, Animation, AnimationLike, Asset, AssetContainer, AssetContainerIterable, AssetLike, BehaviorType, CollisionEvent, CollisionLayer, Context, Guid, log, MediaCommand, MediaInstance, newGuid, PerformanceStats, Permissions, SetMediaStateOptions, TriggerEvent, User, UserLike, ZeroGuid, } from '..'; import { ExportedPromise, OperatingModel, Patchable, Payloads, Protocols, } from '../internal'; import { PhysicsBridgeTransformUpdate, PhysicsUploadServerTransformsUpdate } from '../actor/physics/physicsBridge'; /** * @hidden */ export class ContextInternal { public actorSet = new Map<Guid, Actor>(); public userSet = new Map<Guid, User>(); public userGroupMapping: { [id: string]: number } = { default: 1 }; public assetContainers = new Set<AssetContainer>(); public animationSet: Map<Guid, Animation> = new Map<Guid, Animation>(); public protocol: Protocols.Protocol; public interval: NodeJS.Timer; public generation = 0; public prevGeneration = 0; public __rpc: any; public _rigidBodyOwnerMap = new Map<Guid, Guid>(); public _rigidBodyOrphanSet = new Set<Guid>(); private _rigidBodyDefaultOwner: Guid; constructor(public context: Context) { // Handle connection close events. this.onClose = this.onClose.bind(this); this.context.conn.on('close', this.onClose); // keep track of authoritative simulation user id this.onSetAuthoritative = this.onSetAuthoritative.bind(this); } public onSetAuthoritative = (userId: Guid) => { this._rigidBodyOrphanSet.forEach( (value) => { if (value === this._rigidBodyDefaultOwner) { const actor = this.actorSet.get(value); actor.owner = userId; this._rigidBodyOwnerMap.set(value, userId); } }) this._rigidBodyOrphanSet.clear(); this._rigidBodyDefaultOwner = userId; }; public Create(options?: { actor?: Partial<ActorLike>; }): Actor { return this.createActorFromPayload({ ...options, actor: { ...(options && options.actor), id: newGuid() }, type: 'create-empty' } as Payloads.CreateEmpty); } public CreateFromLibrary(options: { resourceId: string; actor?: Partial<ActorLike>; }): Actor { return this.createActorFromPayload({ ...options, actor: { ...(options && options.actor), id: newGuid() }, type: 'create-from-library' } as Payloads.CreateFromLibrary); } public CreateFromPrefab(options: { prefabId: Guid; collisionLayer?: CollisionLayer; actor?: Partial<ActorLike>; }): Actor { return this.createActorFromPayload({ ...options, actor: { ...(options && options.actor), id: newGuid() }, type: 'create-from-prefab' } as Payloads.CreateFromPrefab); } private createActorFromPayload( payload: Payloads.CreateActorCommon ): Actor { // Resolve by-reference values now, ensuring they won't change in the // time between now and when this message is actually sent. payload.actor = Actor.sanitize(payload.actor); // Create the actor locally. this.updateActors(payload.actor); // Get a reference to the new actor. const actor = this.context.actor(payload.actor.id); // check permission for exclusive actors let user: User; if (actor.exclusiveToUser) { user = this.userSet.get(actor.exclusiveToUser); if (user.hasGrantedPermissions && !(user.grantedPermissions.includes(Permissions.UserInteraction))) { actor.internal.notifyCreated(false, `Permission denied on user ${user.id} (${user.name}). Either this MRE did not ` + "request the UserInteraction permission, or it was denied by the user."); } } // check permission for attachments if (actor.attachment?.userId) { user = this.userSet.get(actor.attachment?.userId); if (user.hasGrantedPermissions && !(user.grantedPermissions.includes(Permissions.UserInteraction))) { actor.internal.notifyCreated(false, `Permission denied on user ${user.id} (${user.name}). Either this MRE did not ` + "request the UserInteraction permission, or it was denied by the user."); } } this.protocol.sendPayload( payload, { resolve: (replyPayload: Payloads.ObjectSpawned | Payloads.OperationResult) => { this.protocol.recvPayload(replyPayload); let success: boolean; let message: string; if (replyPayload.type === 'operation-result') { success = replyPayload.resultCode !== 'error'; message = replyPayload.message; } else { success = replyPayload.result.resultCode !== 'error'; message = replyPayload.result.message; for (const createdAnimLike of replyPayload.animations) { if (!this.animationSet.has(createdAnimLike.id)) { const createdAnim = new Animation(this.context, createdAnimLike.id); createdAnim.copy(createdAnimLike); this.animationSet.set(createdAnimLike.id, createdAnim); } } for (const createdActorLike of replyPayload.actors) { const createdActor = this.actorSet.get(createdActorLike.id); if (createdActor) { createdActor.internal.notifyCreated(success, replyPayload.result.message); } } } if (success) { if (!actor.collider && actor.internal.behavior) { log.warning('app', 'Behaviors will not function on Unity host apps without adding a' + ' collider to this actor first. Recommend adding a primitive collider' + ' to this actor.'); } actor.internal.notifyCreated(true); } else { actor.internal.notifyCreated(false, message); } }, reject: (reason?: any) => { actor.internal.notifyCreated(false, reason); } }); return actor; } public CreateFromGltf(container: AssetContainer, options: { uri: string; colliderType?: 'box' | 'mesh'; actor?: Partial<ActorLike>; }): Actor { // create actor locally options.actor = Actor.sanitize({ ...options.actor, id: newGuid() }); this.updateActors(options.actor); const actor = this.context.actor(options.actor.id); // reserve actor so the pending actor is ready for commands this.protocol.sendPayload({ type: 'x-reserve-actor', actor: options.actor } as Payloads.XReserveActor); // kick off asset loading container.loadGltf(options.uri, options.colliderType) .then(assets => { if (!this.context.actor(actor.id)) { // actor was destroyed, stop loading return; } // once assets are done, find first prefab... const prefab = assets.find(a => !!a.prefab); if (!prefab) { actor.internal.notifyCreated(false, `glTF contains no prefabs: ${options.uri}`); return; } // ...and spawn it this.createActorFromPayload({ type: 'create-from-prefab', prefabId: prefab.id, actor: options.actor } as Payloads.CreateFromPrefab); }) .catch(reason => actor.internal.notifyCreated(false, reason)); return actor; } public async createAnimationFromData( dataId: Guid, targets: { [placeholder: string]: Guid }, initialState?: Partial<AnimationLike> ): Promise<Animation> { // generate the anim immediately const data = this.lookupAsset(dataId)?.animationData; if (!data) { throw new Error(`No animation data with id "${dataId}" found.`); } const createdAnim = new Animation(this.context, newGuid()); createdAnim.copy({ name: data.name, ...initialState, dataId, targetIds: Object.values(targets), }); this.animationSet.set(createdAnim.id, createdAnim); data.addReference(createdAnim); const reply = await this.sendPayloadAndGetReply<Payloads.CreateAnimation2, Payloads.ObjectSpawned>({ type: 'create-animation-2', animation: createdAnim.toJSON(), targets }); if (reply.result.resultCode !== 'error') { createdAnim.copy(reply.animations[0]); return createdAnim; } else { throw new Error(reply.result.message); } } public setMediaState( mediaInstance: MediaInstance, command: MediaCommand, options?: SetMediaStateOptions, mediaAssetId?: Guid, ) { this.protocol.sendPayload({ type: 'set-media-state', id: mediaInstance.id, actorId: mediaInstance.actor.id, mediaAssetId, mediaCommand: command, options } as Payloads.SetMediaState); } public async startListening() { try { // Startup the handshake protocol. const handshake = this.protocol = new Protocols.Handshake(this.context.conn, this.context.sessionId, OperatingModel.ServerAuthoritative); await handshake.run(); // Switch to execution protocol. const execution = this.protocol = new Protocols.Execution(this.context); execution.on('protocol.update-actors', this.updateActors.bind(this)); execution.on('protocol.destroy-actors', this.localDestroyActors.bind(this)); execution.on('protocol.user-joined', this.userJoined.bind(this)); execution.on('protocol.user-left', this.userLeft.bind(this)); execution.on('protocol.update-user', this.updateUser.bind(this)); execution.on('protocol.perform-action', this.performAction.bind(this)); execution.on('protocol.physicsbridge-update-transforms', this.updatePhysicsBridgeTransforms.bind(this)); execution.on('protocol.physicsbridge-server-transforms-upload', this.updatePhysicsServerTransformsUpload.bind(this)); execution.on('protocol.receive-rpc', this.receiveRPC.bind(this)); execution.on('protocol.collision-event-raised', this.collisionEventRaised.bind(this)); execution.on('protocol.trigger-event-raised', this.triggerEventRaised.bind(this)); execution.on('protocol.update-animations', this.updateAnimations.bind(this)); // Startup the execution protocol execution.startListening(); } catch (e) { log.error('app', e); } } public start() { if (!this.interval) { this.interval = setInterval(() => this.update(), 0); this.context.emitter.emit('started'); } } public stop() { try { if (this.interval) { this.protocol.stopListening(); clearInterval(this.interval); this.interval = undefined; this.context.emitter.emit('stopped'); this.context.emitter.removeAllListeners(); } } catch { } } public incrementGeneration() { this.generation++; } private assetsIterable() { return new AssetContainerIterable([...this.assetContainers]); } public update() { // Early out if no state changes occurred. if (this.generation === this.prevGeneration) { return; } this.prevGeneration = this.generation; const syncObjects = [ ...this.actorSet.values(), ...this.assetsIterable(), ...this.userSet.values(), ...this.animationSet.values() ] as Array<Patchable<any>>; const maxUpdatesPerTick = parseInt(process.env.MRE_MAX_UPDATES_PER_TICK) || 300; let updates = 0; for (const patchable of syncObjects) { if (updates >= maxUpdatesPerTick) { break; } const patch = patchable.internal.getPatchAndReset(); if (!patch) { continue; } else { updates++; } if (patchable instanceof User) { this.protocol.sendPayload({ type: 'user-update', user: patch as UserLike } as Payloads.UserUpdate); } else if (patchable instanceof Actor) { this.protocol.sendPayload({ type: 'actor-update', actor: patch as ActorLike } as Payloads.ActorUpdate); } else if (patchable instanceof Animation) { this.protocol.sendPayload({ type: 'animation-update', animation: patch as Partial<AnimationLike> } as Payloads.AnimationUpdate) } else if (patchable instanceof Asset) { this.protocol.sendPayload({ type: 'asset-update', asset: patch as AssetLike } as Payloads.AssetUpdate); } } // only run if we finished sending all pending updates if (updates < maxUpdatesPerTick && this.nextUpdatePromise) { this.resolveNextUpdatePromise(); this.nextUpdatePromise = null; this.resolveNextUpdatePromise = null; } } private nextUpdatePromise: Promise<void>; private resolveNextUpdatePromise: () => void; /** @hidden */ public nextUpdate(): Promise<void> { if (this.nextUpdatePromise) { return this.nextUpdatePromise; } return this.nextUpdatePromise = new Promise(resolve => { this.resolveNextUpdatePromise = resolve; }); } public sendDestroyActors(actorIds: Guid[]) { if (actorIds.length) { this.protocol.sendPayload({ type: 'destroy-actors', actorIds, } as Payloads.DestroyActors); } } public updateActors(sactors: Partial<ActorLike> | Array<Partial<ActorLike>>) { if (!sactors) { return; } if (!Array.isArray(sactors)) { sactors = [sactors]; } const newActorIds: Guid[] = []; // Instantiate and store each actor. sactors.forEach(sactor => { const isNewActor = !this.actorSet.get(sactor.id); const actor = isNewActor ? Actor.alloc(this.context, sactor.id) : this.actorSet.get(sactor.id); this.actorSet.set(sactor.id, actor); actor.copy(sactor); if (isNewActor) { newActorIds.push(actor.id); if (actor.rigidBody) { if (!actor.owner) { actor.owner = this._rigidBodyDefaultOwner; } this._rigidBodyOwnerMap.set(actor.id, actor.owner); } } }); newActorIds.forEach(actorId => { const actor = this.actorSet.get(actorId); this.context.emitter.emit('actor-created', actor); }); } public updatePhysicsBridgeTransforms(transforms: Partial<PhysicsBridgeTransformUpdate>) { if (!transforms) { return; } this.context.emitter.emit('physicsbridge-transforms-update', transforms); } public updatePhysicsServerTransformsUpload(transforms: Partial<PhysicsUploadServerTransformsUpdate>){ if (!transforms) { return; } this.context.emitter.emit('physicsbridge-server-transforms-upload', transforms); } public updateAnimations(animPatches: Array<Partial<AnimationLike>>) { if (!animPatches) { return; } const newAnims: Animation[] = []; for (const patch of animPatches) { if (this.animationSet.has(patch.id)) { this.animationSet.get(patch.id).copy(patch); continue; } const newAnim = new Animation(this.context, patch.id); this.animationSet.set(newAnim.id, newAnim); newAnim.copy(patch); newAnims.push(newAnim); } for (const anim of newAnims) { this.context.emitter.emit('animation-created', anim); } } public sendPayload(payload: Payloads.Payload, promise?: ExportedPromise): void { this.protocol.sendPayload(payload, promise); } public sendPayloadAndGetReply<T extends Payloads.Payload, U extends Payloads.Payload>(payload: T): Promise<U> { return new Promise<U>((resolve, reject) => { this.protocol.sendPayload( payload, { resolve, reject } ); }); } public receiveRPC(payload: Payloads.EngineToAppRPC) { this.context.receiveRPC(payload); } public onClose = () => { this.stop(); }; public userJoined(suser: Partial<UserLike>) { if (!this.userSet.has(suser.id)) { const user = new User(this.context, suser.id); this.userSet.set(suser.id, user); user.copy(suser); this.context.emitter.emit('user-joined', user); } } public userLeft(userId: Guid) { const user = this.userSet.get(userId); if (user) { this.userSet.delete(userId); this.context.emitter.emit('user-left', user); if (userId !== this._rigidBodyDefaultOwner) { this._rigidBodyOwnerMap.forEach( (value, key) => { if (value === userId) { const actor = this.actorSet.get(key); actor.owner = this._rigidBodyDefaultOwner; this._rigidBodyOwnerMap.set(key, this._rigidBodyDefaultOwner); } }) } else { this._rigidBodyOwnerMap.forEach( (value, key) => { if (value === userId) { const actor = this.actorSet.get(key); actor.owner = this._rigidBodyDefaultOwner; this._rigidBodyOrphanSet.add(key); } }) } } } public updateUser(suser: Partial<UserLike>) { let user = this.userSet.get(suser.id); if (!user) { user = new User(this.context, suser.id); user.copy(suser); this.userSet.set(user.id, user); this.context.emitter.emit('user-joined', user); } else { user.copy(suser); this.context.emitter.emit('user-updated', user); } } public performAction(actionEvent: ActionEvent) { if (actionEvent.user) { const targetActor = this.actorSet.get(actionEvent.targetId); if (targetActor) { if (actionEvent.actionName === 'grab' && targetActor.rigidBody) { if (targetActor.owner !== actionEvent.user.id) { targetActor.owner = actionEvent.user.id; this._rigidBodyOwnerMap.set(targetActor.id, targetActor.owner); } } targetActor.internal.performAction(actionEvent); } } } public collisionEventRaised(collisionEvent: CollisionEvent) { const actor = this.actorSet.get(collisionEvent.colliderOwnerId); const otherActor = this.actorSet.get((collisionEvent.collisionData.otherActorId)); if (actor && otherActor) { // Update the collision data to contain the actual other actor. collisionEvent.collisionData = { ...collisionEvent.collisionData, otherActor }; actor.internal.collisionEventRaised( collisionEvent.eventType, collisionEvent.collisionData); } } public triggerEventRaised(triggerEvent: TriggerEvent) { const actor = this.actorSet.get(triggerEvent.colliderOwnerId); const otherActor = this.actorSet.get(triggerEvent.otherColliderOwnerId); if (actor && otherActor) { actor.internal.triggerEventRaised( triggerEvent.eventType, otherActor); } } public localDestroyActors(actorIds: Guid[]) { for (const actorId of actorIds) { if (this.actorSet.has(actorId)) { this.localDestroyActor(this.actorSet.get(actorId)); } if (this._rigidBodyOwnerMap.has(actorId)) { this._rigidBodyOwnerMap.delete(actorId); } } } public localDestroyActor(actor: Actor) { // Recursively destroy children first (actor.children || []).forEach(child => { this.localDestroyActor(child); }); // Remove actor from _actors this.actorSet.delete(actor.id); if (this._rigidBodyOwnerMap.has(actor.id)) { this._rigidBodyOwnerMap.delete(actor.id); } // Check targeting animations for orphans for (const anim of actor.targetingAnimations.values()) { if (anim.isOrphan()) { this.destroyAnimation(anim.id); } } // Raise event this.context.emitter.emit('actor-destroyed', actor); } public destroyActor(actorId: Guid) { const actor = this.actorSet.get(actorId); if (actor) { // Tell engine to destroy the actor (will destroy all children too) this.sendDestroyActors([actorId]); // Clean up the actor locally this.localDestroyActor(actor); } } public destroyAnimation(animationId: Guid, cascadeIds: Guid[] = []) { const shouldSendDestroyMessage = cascadeIds.length === 0; cascadeIds.push(animationId); /*const anim = this.animationSet.get(animationId);*/ this.animationSet.delete(animationId); /*for (const targetingAnim of anim.targetingAnimations.values()) { if (targetingAnim.isOrphan()) { this.destroyAnimation(targetingAnim.id, cascadeIds); } }*/ if (shouldSendDestroyMessage) { this.protocol.sendPayload({ type: 'destroy-animations', animationIds: cascadeIds } as Partial<Payloads.DestroyAnimations>); } } public sendRigidBodyCommand(actorId: Guid, payload: Payloads.Payload) { this.protocol.sendPayload({ type: 'rigidbody-commands', actorId, commandPayloads: [payload] } as Payloads.RigidBodyCommands); } public setBehavior(actorId: Guid, newBehaviorType: BehaviorType) { const actor = this.actorSet.get(actorId); if (actor) { this.protocol.sendPayload({ type: 'set-behavior', actorId, behaviorType: newBehaviorType || 'none' } as Payloads.SetBehavior); } } public lookupAsset(id: Guid): Asset { if (id === ZeroGuid) { return null; } for (const c of this.assetContainers) { if (c.assetsById.has(id)) { return c.assetsById.get(id); } } } public getStats(): PerformanceStats { const networkStats = this.protocol.conn.statsReport; const stats: PerformanceStats = { actorCount: this.actorSet.size, actorWithMeshCount: 0, prefabCount: 0, materialCount: 0, textureCount: 0, texturePixelsTotal: 0, texturePixelsAverage: 0, meshCount: 0, meshVerticesTotal: 0, meshTrianglesTotal: 0, soundCount: 0, soundSecondsTotal: 0, ...networkStats }; for (const container of this.assetContainers) { stats.prefabCount += container.prefabs.length; stats.materialCount += container.materials.length; stats.textureCount += container.textures.length; stats.meshCount += container.meshes.length; stats.soundCount += container.sounds.length; for (const tex of container.textures) { stats.texturePixelsTotal += (tex.texture.resolution.x || 0) * (tex.texture.resolution.y || 0); } for (const mesh of container.meshes) { stats.meshTrianglesTotal += mesh.mesh.triangleCount || 0; stats.meshVerticesTotal += mesh.mesh.vertexCount || 0; } for (const sound of container.sounds) { stats.soundSecondsTotal += sound.sound.duration || 0; } } stats.texturePixelsAverage = stats.texturePixelsTotal / (stats.textureCount || 1); for (const actor of this.actorSet.values()) { if (actor.appearance.activeAndEnabled && actor.appearance.mesh) { stats.actorWithMeshCount += 1; } } return stats; } }
the_stack
import { t, Trans } from '@lingui/macro' import { DatePicker, Form, InputNumber, Modal, Radio } from 'antd' import { useForm } from 'antd/lib/form/Form' import { FormItems } from 'components/shared/formItems' import { ModalMode, validateEthAddress, validatePercentage, } from 'components/shared/formItems/formHelpers' import { defaultSplit, Split } from 'models/v2/splits' import { useContext, useEffect, useLayoutEffect, useState } from 'react' import { parseWad } from 'utils/formatNumber' import { round } from 'lodash' import { adjustedSplitPercents, getDistributionPercentFromAmount, getNewDistributionLimit, } from 'utils/v2/distributions' import { ThemeContext } from 'contexts/themeContext' import FormattedNumberInput from 'components/shared/inputs/FormattedNumberInput' import InputAccessoryButton from 'components/shared/InputAccessoryButton' import { useETHPaymentTerminalFee } from 'hooks/v2/contractReader/ETHPaymentTerminalFee' import { formatFee, formatSplitPercent, MAX_DISTRIBUTION_LIMIT, preciseFormatSplitPercent, splitPercentFrom, SPLITS_TOTAL_PERCENT, } from 'utils/v2/math' import NumberSlider from 'components/shared/inputs/NumberSlider' import { amountFromPercent } from 'utils/v2/distributions' import { BigNumber } from '@ethersproject/bignumber' import { stringIsDigit } from 'utils/math' import CurrencySymbol from 'components/shared/CurrencySymbol' import * as Moment from 'moment' import moment from 'moment' import TooltipLabel from 'components/shared/TooltipLabel' import CurrencySwitch from 'components/shared/CurrencySwitch' import TooltipIcon from 'components/shared/TooltipIcon' import { CurrencyName } from 'constants/currency' type AddOrEditSplitFormFields = { projectId: string beneficiary: string percent: number lockedUntil: Moment.Moment | undefined | null } type SplitType = 'project' | 'address' type DistributionType = 'amount' | 'percent' // Using both state and a form in this modal. I know it seems over the top, // but the state is necessary to link the percent and amount fields, and the form // is useful for its features such as field validation. export default function DistributionSplitModal({ visible, mode, splits, // Locked and editable splits onSplitsChanged, distributionLimit, setDistributionLimit, editableSplitIndex, // index in editingSplits list (Only in the case mode==='Edit') onClose, currencyName, onCurrencyChange, editableSplits, }: { visible: boolean mode: ModalMode // 'Add' or 'Edit' or 'Undefined' splits: Split[] onSplitsChanged: (splits: Split[]) => void distributionLimit: string | undefined setDistributionLimit: (distributionLimit: string) => void editableSplitIndex?: number onClose: VoidFunction currencyName: CurrencyName onCurrencyChange?: (currencyName: CurrencyName) => void editableSplits: Split[] }) { const { theme: { colors }, } = useContext(ThemeContext) const [form] = useForm<AddOrEditSplitFormFields>() let split: Split = defaultSplit let initialProjectId: number | undefined let initialLockedUntil: Moment.Moment | undefined const distributionLimitIsInfinite = !distributionLimit || parseWad(distributionLimit).eq(MAX_DISTRIBUTION_LIMIT) const isFirstSplit = editableSplits.length === 0 || (editableSplits.length === 1 && editableSplitIndex === 0) // If editing, format the lockedUntil and projectId if (editableSplits.length && editableSplitIndex !== undefined) { split = editableSplits[editableSplitIndex] initialLockedUntil = split.lockedUntil ? Moment.default(split.lockedUntil * 1000) : undefined if (split.projectId) { initialProjectId = BigNumber.from(split.projectId).toNumber() } } const [editingSplitType, setEditingSplitType] = useState<SplitType>( initialProjectId ? 'project' : 'address', ) const [distributionType, setDistributionType] = useState<DistributionType>( distributionLimitIsInfinite ? 'percent' : 'amount', ) const [projectId, setProjectId] = useState<string | undefined>( initialProjectId?.toString(), ) const [beneficiary, setBeneficiary] = useState<string | undefined>( split.beneficiary, ) const [newDistributionLimit, setNewDistributionLimit] = useState<string>() const [percent, setPercent] = useState<number>(split.percent) const [amount, setAmount] = useState<number | undefined>( !distributionLimitIsInfinite ? amountFromPercent({ percent: preciseFormatSplitPercent(split.percent), amount: distributionLimit, }) : undefined, ) const [lockedUntil, setLockedUntil] = useState< Moment.Moment | undefined | null >(initialLockedUntil) useLayoutEffect(() => form.setFieldsValue({ percent: parseFloat(formatSplitPercent(BigNumber.from(percent))), beneficiary, projectId, lockedUntil, }), ) useEffect(() => { if (editingSplitType === 'address') { form.setFieldsValue({ projectId: undefined }) setProjectId(undefined) } }, [editingSplitType, form]) const ETHPaymentTerminalFee = useETHPaymentTerminalFee() const feePercentage = ETHPaymentTerminalFee ? formatFee(ETHPaymentTerminalFee) : undefined useEffect(() => { if ( editableSplits.length === 0 || editableSplitIndex === undefined || !distributionLimit ) { return } const percentPerBillion = editableSplits[editableSplitIndex].percent const amount = amountFromPercent({ percent: preciseFormatSplitPercent(percentPerBillion), amount: distributionLimit, }) setAmount(amount) setPercent(percentPerBillion) }, [distributionLimit, editableSplits, editableSplitIndex, isFirstSplit]) useEffect(() => { setDistributionType(distributionLimitIsInfinite ? 'percent' : 'amount') }, [distributionLimitIsInfinite]) const resetStates = () => { setProjectId(undefined) setBeneficiary(undefined) setPercent(0) setAmount(undefined) setLockedUntil(undefined) } // Validates new or newly edited split, then adds it to or edits the splits list const setSplit = async () => { await form.validateFields() const roundedLockedUntil = lockedUntil ? Math.round(lockedUntil.valueOf() / 1000) : undefined const newSplit = { beneficiary: beneficiary, percent: percent, lockedUntil: roundedLockedUntil, preferClaimed: true, projectId: projectId, allocator: undefined, // TODO: new v2 feature } as Split let adjustedSplits: Split[] = editableSplits // If an amount and therefore the distribution limit has been changed, // recalculate all split percents based on newly added split amount if (newDistributionLimit && !distributionLimitIsInfinite) { adjustedSplits = adjustedSplitPercents({ splits: editableSplits, oldDistributionLimit: distributionLimit, newDistributionLimit, }) setDistributionLimit(newDistributionLimit) } const newSplits = mode === 'Edit' ? adjustedSplits.map((m, i) => i === editableSplitIndex ? { ...m, ...newSplit, } : m, ) : [...adjustedSplits, newSplit] onSplitsChanged(newSplits) if (mode === 'Add') { resetStates() form.resetFields() } onClose() } const onAmountChange = (newAmount: number) => { if (distributionLimitIsInfinite || !newAmount) return const newDistributionLimit = getNewDistributionLimit({ currentDistributionLimit: distributionLimit, newSplitAmount: newAmount, editingSplitPercent: mode === 'Add' ? 0 : splits[editableSplitIndex ?? 0].percent, //percentPerBillion, }) const newPercent = getDistributionPercentFromAmount({ amount: newAmount, distributionLimit: newDistributionLimit, }) setNewDistributionLimit(newDistributionLimit.toString()) setAmount(newAmount) setPercent(newPercent) form.setFieldsValue({ percent: parseFloat(formatSplitPercent(BigNumber.from(newPercent))), }) } // Validates new payout receiving address const validatePayoutAddress = () => { if ( editableSplitIndex !== undefined && beneficiary === editableSplits[editableSplitIndex].beneficiary ) { return Promise.resolve() } return validateEthAddress( beneficiary ?? '', splits, mode, editableSplitIndex, ) } const validateProjectId = () => { if (!stringIsDigit(form.getFieldValue('projectId'))) { return Promise.reject(t`Project ID must be a number.`) } // TODO: check if projectId exists return Promise.resolve() } const validatePayoutPercentage = () => { return validatePercentage(form.getFieldValue('percent')) } // Cannot select days before today or today with lockedUntil const disabledDate = (current: moment.Moment) => current && current < moment().endOf('day') const amountSubFee = amount ? amount - (amount * parseFloat(feePercentage ?? '0')) / 100 : undefined function AfterFeeMessage() { return amountSubFee && amountSubFee > 0 ? ( <TooltipLabel label={ <Trans> <CurrencySymbol currency={currencyName} /> {round(amountSubFee, 4)} after {feePercentage}% JBX membership fee </Trans> } tip={ <Trans> Payouts to Ethereum addresses incur a {feePercentage}% fee. Your project will receive JBX in return at the current issuance rate. </Trans> } /> ) : null } const formattedSplitPercent = formatSplitPercent(BigNumber.from(percent)) return ( <Modal title={mode === 'Edit' ? t`Edit payout` : t`Add new payout`} visible={visible} onOk={setSplit} okText={mode === 'Edit' ? t`Save payout` : t`Add payout`} onCancel={onClose} destroyOnClose > <Form form={form} layout="vertical" scrollToFirstError={{ behavior: 'smooth' }} onKeyDown={e => { if (e.key === 'Enter') setSplit() }} > <Form.Item label={t`Recipient`}> <Radio.Group value={editingSplitType} onChange={e => setEditingSplitType(e.target.value)} > <Radio value="address" style={{ fontWeight: 400 }}> <Trans>Wallet address</Trans> </Radio> <Radio value="project" style={{ fontWeight: 400 }}> <Trans>Juicebox project</Trans> </Radio> </Radio.Group> </Form.Item> {editingSplitType === 'address' ? ( <FormItems.EthAddress name="beneficiary" defaultValue={beneficiary} formItemProps={{ label: t`Address`, rules: [ { validator: validatePayoutAddress, }, ], required: true, }} onAddressChange={(beneficiary: string) => setBeneficiary(beneficiary) } /> ) : ( <Form.Item name={'projectId'} rules={[{ validator: validateProjectId }]} label={t`Juicebox Project ID`} required > <InputNumber value={parseInt(projectId ?? '')} style={{ width: '100%' }} placeholder={t`ID`} onChange={(projectId: number) => { setProjectId(projectId?.toString()) }} /> </Form.Item> )} {editingSplitType === 'project' ? ( <FormItems.EthAddress name="beneficiary" defaultValue={beneficiary} formItemProps={{ label: t`Token beneficiary address`, required: true, extra: t`The address that should receive the tokens minted from paying this project.`, }} onAddressChange={beneficiary => { setBeneficiary(beneficiary) }} /> ) : null} {/* Only show amount input if project distribution limit is not infinite */} {distributionLimit && distributionType === 'amount' ? ( <Form.Item className="ant-form-item-extra-only" label={t`Distribution`} required extra={ feePercentage && percent && !(percent > SPLITS_TOTAL_PERCENT) ? ( <> {editingSplitType === 'address' ? ( <div> <AfterFeeMessage /> </div> ) : ( <Trans> Distributing funds to Juicebox projects won't incur fees. </Trans> )} </> ) : null } > <div style={{ display: 'flex', color: colors.text.primary, alignItems: 'center', }} > <FormattedNumberInput value={amount?.toFixed(4)} placeholder={'0'} onChange={amount => onAmountChange(parseFloat(amount || '0'))} formItemProps={{ rules: [{ validator: validatePayoutPercentage }], required: true, }} accessory={ isFirstSplit && onCurrencyChange ? ( <CurrencySwitch onCurrencyChange={onCurrencyChange} currency={currencyName} /> ) : ( <InputAccessoryButton content={currencyName} /> ) } /> <div style={{ display: 'flex', alignItems: 'center', marginLeft: 10, }} > <Trans>{formattedSplitPercent}%</Trans> <TooltipIcon tip={ <Trans> If you don't raise the sum of all your payouts ( <CurrencySymbol currency={currencyName} /> {distributionLimit}), this address will receive{' '} {formattedSplitPercent}% of all the funds you raise. </Trans> } placement={'topLeft'} iconStyle={{ marginLeft: 5 }} /> </div> </div> </Form.Item> ) : ( <Form.Item> <div style={{ display: 'flex', alignItems: 'center', }} > <span style={{ flex: 1 }}> <NumberSlider onChange={(percent: number | undefined) => { setPercent(splitPercentFrom(percent ?? 0).toNumber()) }} step={0.01} defaultValue={0} sliderValue={form.getFieldValue('percent')} suffix="%" name="percent" formItemProps={{ rules: [{ validator: validatePayoutPercentage }], }} /> </span> </div> </Form.Item> )} <Form.Item name="lockedUntil" label={t`Lock until`} extra={ <Trans> If locked, this split can't be edited or removed until the lock expires or the funding cycle is reconfigured. </Trans> } > <DatePicker disabledDate={disabledDate} onChange={lockedUntil => setLockedUntil(lockedUntil)} /> </Form.Item> </Form> </Modal> ) }
the_stack
import 'chrome://resources/polymer/v3_0/iron-list/iron-list.js'; import 'chrome://resources/cr_elements/cr_action_menu/cr_action_menu.js'; import 'chrome://resources/cr_elements/cr_button/cr_button.m.js'; import 'chrome://resources/cr_elements/cr_lazy_render/cr_lazy_render.m.js'; import 'chrome://resources/cr_elements/shared_style_css.m.js'; import 'chrome://resources/cr_elements/shared_vars_css.m.js'; import './shared_style.js'; import './synced_device_card.js'; import './strings.m.js'; import {CrActionMenuElement} from 'chrome://resources/cr_elements/cr_action_menu/cr_action_menu.js'; import {CrLazyRenderElement} from 'chrome://resources/cr_elements/cr_lazy_render/cr_lazy_render.m.js'; import {assert} from 'chrome://resources/js/assert.m.js'; import {FocusGrid} from 'chrome://resources/js/cr/ui/focus_grid.js'; import {FocusRow} from 'chrome://resources/js/cr/ui/focus_row.m.js'; import {loadTimeData} from 'chrome://resources/js/load_time_data.m.js'; import {Debouncer, html, microTask, PolymerElement} from 'chrome://resources/polymer/v3_0/polymer/polymer_bundled.min.js'; import {BrowserService} from './browser_service.js'; import {SYNCED_TABS_HISTOGRAM_NAME, SyncedTabsHistogram} from './constants.js'; import {ForeignSession, ForeignSessionTab} from './externs.js'; import {HistorySyncedDeviceCardElement} from './synced_device_card.js'; type ForeignDeviceInternal = { device: string, lastUpdateTime: string, opened: boolean, separatorIndexes: Array<number>, timestamp: number, tabs: Array<ForeignSessionTab>, tag: string, }; declare global { interface HTMLElementEventMap { 'synced-device-card-open-menu': CustomEvent<{tag: string, target: HTMLElement}>; } } export interface HistorySyncedDeviceManagerElement { $: { 'menu': CrLazyRenderElement<CrActionMenuElement>, }; } export class HistorySyncedDeviceManagerElement extends PolymerElement { static get is() { return 'history-synced-device-manager'; } static get properties() { return { sessionList: { type: Array, observer: 'updateSyncedDevices', }, searchTerm: { type: String, observer: 'searchTermChanged', }, /** * An array of synced devices with synced tab data. */ syncedDevices_: Array, signInState: { type: Boolean, observer: 'signInStateChanged_', }, guestSession_: Boolean, signInAllowed_: Boolean, fetchingSyncedTabs_: Boolean, hasSeenForeignData_: Boolean, /** * The session ID referring to the currently active action menu. */ actionMenuModel_: String, }; } private focusGrid_: FocusGrid|null = null; private syncedDevices_: Array<ForeignDeviceInternal> = []; private hasSeenForeignData_: boolean; private fetchingSyncedTabs_: boolean = false; private actionMenuModel_: string|null = null; private guestSession_: boolean = loadTimeData.getBoolean('isGuestSession'); private signInAllowed_: boolean = loadTimeData.getBoolean('isSignInAllowed'); private debouncer_: Debouncer|null = null; private signInState: boolean; searchTerm: string; sessionList: Array<ForeignSession>; ready() { super.ready(); this.addEventListener('synced-device-card-open-menu', this.onOpenMenu_); this.addEventListener('update-focus-grid', this.updateFocusGrid_); } /** @override */ connectedCallback() { super.connectedCallback(); this.focusGrid_ = new FocusGrid(); // Update the sign in state. BrowserService.getInstance().otherDevicesInitialized(); BrowserService.getInstance().recordHistogram( SYNCED_TABS_HISTOGRAM_NAME, SyncedTabsHistogram.INITIALIZED, SyncedTabsHistogram.LIMIT); } /** @override */ disconnectedCallback() { super.disconnectedCallback(); this.focusGrid_!.destroy(); } /** @return {HTMLElement} */ getContentScrollTarget() { return this; } private createInternalDevice_(session: ForeignSession): ForeignDeviceInternal { let tabs: Array<ForeignSessionTab> = []; const separatorIndexes = []; for (let i = 0; i < session.windows.length; i++) { const windowId = session.windows[i].sessionId; const newTabs = session.windows[i].tabs; if (newTabs.length === 0) { continue; } newTabs.forEach(function(tab) { tab.windowId = windowId; }); let windowAdded = false; if (!this.searchTerm) { // Add all the tabs if there is no search term. tabs = tabs.concat(newTabs); windowAdded = true; } else { const searchText = this.searchTerm.toLowerCase(); for (let j = 0; j < newTabs.length; j++) { const tab = newTabs[j]; if (tab.title.toLowerCase().indexOf(searchText) !== -1) { tabs.push(tab); windowAdded = true; } } } if (windowAdded && i !== session.windows.length - 1) { separatorIndexes.push(tabs.length - 1); } } return { device: session.name, lastUpdateTime: '– ' + session.modifiedTime, opened: true, separatorIndexes: separatorIndexes, timestamp: session.timestamp, tabs: tabs, tag: session.tag, }; } private onSignInTap_() { BrowserService.getInstance().startSignInFlow(); } private onOpenMenu_(e: CustomEvent<{tag: string, target: HTMLElement}>) { this.actionMenuModel_ = e.detail.tag; this.$['menu'].get().showAt(e.detail.target); BrowserService.getInstance().recordHistogram( SYNCED_TABS_HISTOGRAM_NAME, SyncedTabsHistogram.SHOW_SESSION_MENU, SyncedTabsHistogram.LIMIT); } private onOpenAllTap_() { const menu = assert(this.$['menu'].getIfExists()); const browserService = BrowserService.getInstance(); browserService.recordHistogram( SYNCED_TABS_HISTOGRAM_NAME, SyncedTabsHistogram.OPEN_ALL, SyncedTabsHistogram.LIMIT); browserService.openForeignSessionAllTabs( assert(this.actionMenuModel_) as string); this.actionMenuModel_ = null; menu!.close(); } private updateFocusGrid_() { if (!this.focusGrid_) { return; } this.focusGrid_.destroy(); this.debouncer_ = Debouncer.debounce(this.debouncer_, microTask, () => { const cards = this.shadowRoot!.querySelectorAll('history-synced-device-card'); Array.from(cards) .reduce( (prev: Array<FocusRow>, cur: HistorySyncedDeviceCardElement) => prev.concat(cur.createFocusRows()), []) .forEach((row) => { this.focusGrid_!.addRow(row); }); this.focusGrid_!.ensureRowActive(1); }); } private onDeleteSessionTap_() { const menu = assert(this.$['menu'].getIfExists()) as CrActionMenuElement; const browserService = BrowserService.getInstance(); browserService.recordHistogram( SYNCED_TABS_HISTOGRAM_NAME, SyncedTabsHistogram.HIDE_FOR_NOW, SyncedTabsHistogram.LIMIT); browserService.deleteForeignSession( assert(this.actionMenuModel_) as string); this.actionMenuModel_ = null; menu!.close(); } private clearDisplayedSyncedDevices_() { this.syncedDevices_ = []; } /** * Decide whether or not should display no synced tabs message. */ showNoSyncedMessage( signInState: boolean, syncedDevicesLength: number, guestSession: boolean): boolean { if (guestSession) { return true; } return signInState && syncedDevicesLength === 0; } /** * Shows the signin guide when the user is not signed in, signin is allowed * and not in a guest session. */ showSignInGuide( signInState: boolean, guestSession: boolean, signInAllowed: boolean): boolean { const show = !signInState && !guestSession && signInAllowed; if (show) { BrowserService.getInstance().recordAction( 'Signin_Impression_FromRecentTabs'); } return show; } /** * Decide what message should be displayed when user is logged in and there * are no synced tabs. */ noSyncedTabsMessage(): string { let stringName = this.fetchingSyncedTabs_ ? 'loading' : 'noSyncedResults'; if (this.searchTerm !== '') { stringName = 'noSearchResults'; } return loadTimeData.getString(stringName); } /** * Replaces the currently displayed synced tabs with |sessionList|. It is * common for only a single session within the list to have changed, We try to * avoid doing extra work in this case. The logic could be more intelligent * about updating individual tabs rather than replacing whole sessions, but * this approach seems to have acceptable performance. */ updateSyncedDevices(sessionList: Array<ForeignSession>) { this.fetchingSyncedTabs_ = false; if (!sessionList) { return; } if (sessionList.length > 0 && !this.hasSeenForeignData_) { this.hasSeenForeignData_ = true; BrowserService.getInstance().recordHistogram( SYNCED_TABS_HISTOGRAM_NAME, SyncedTabsHistogram.HAS_FOREIGN_DATA, SyncedTabsHistogram.LIMIT); } const devices: Array<ForeignDeviceInternal> = []; sessionList.forEach((session) => { const device = this.createInternalDevice_(session); if (device.tabs.length !== 0) { devices.push(device); } }); this.syncedDevices_ = devices; } /** * Get called when user's sign in state changes, this will affect UI of synced * tabs page. Sign in promo gets displayed when user is signed out, and * different messages are shown when there are no synced tabs. */ signInStateChanged_(_current: boolean, previous?: boolean) { if (previous === undefined) { return; } this.dispatchEvent(new CustomEvent( 'history-view-changed', {bubbles: true, composed: true})); // User signed out, clear synced device list and show the sign in promo. if (!this.signInState) { this.clearDisplayedSyncedDevices_(); return; } // User signed in, show the loading message when querying for synced // devices. this.fetchingSyncedTabs_ = true; } searchTermChanged() { this.clearDisplayedSyncedDevices_(); this.updateSyncedDevices(this.sessionList); } static get template() { return html`{__html_template__}`; } } customElements.define( HistorySyncedDeviceManagerElement.is, HistorySyncedDeviceManagerElement);
the_stack
/// <reference types="node" /> import http = require('http'); import https = require('https'); import Logger = require('bunyan'); import url = require('url'); import spdy = require('spdy'); import stream = require('stream'); export interface ServerOptions { ca?: string | Buffer | ReadonlyArray<string | Buffer> | undefined; certificate?: string | Buffer | ReadonlyArray<string | Buffer> | undefined; key?: string | Buffer | ReadonlyArray<string | Buffer> | undefined; passphrase?: string | undefined; requestCert?: boolean | undefined; ciphers?: string | undefined; formatters?: Formatters | undefined; log?: Logger | undefined; name?: string | undefined; spdy?: spdy.ServerOptions | undefined; version?: string | undefined; versions?: string[] | undefined; handleUpgrades?: boolean | undefined; httpsServerOptions?: https.ServerOptions | undefined; handleUncaughtExceptions?: boolean | undefined; router?: Router | undefined; socketio?: boolean | undefined; noWriteContinue?: boolean | undefined; rejectUnauthorized?: boolean | undefined; } export interface AddressInterface { port: number; family: string; address: string; } export interface Server extends http.Server { /** * Returns the server address. Wraps node's address(). */ address(): AddressInterface; /** * Gets the server up and listening. Wraps node's listen(). * * You can call like: * server.listen(80) * server.listen(80, '127.0.0.1') * server.listen('/tmp/server.sock') * * @throws {TypeError} * @param callback optionally get notified when listening. */ listen(...args: any[]): any; /** * Shuts down this server, and invokes callback (optionally) when done. * Wraps node's close(). * @param callback optional callback to invoke when done. */ close(...args: any[]): any; /** * Returns the number of currently inflight requests. */ inflightRequests(): number; /** * Mounts a chain on the given path against this HTTP verb * * @param opts if string, the URL to handle. * if options, the URL to handle, at minimum. * @returns the newly created route. */ del(opts: string | RegExp | RouteOptions, ...handlers: RequestHandlerType[]): Route | boolean; /** * Mounts a chain on the given path against this HTTP verb * * @param opts if string, the URL to handle. * if options, the URL to handle, at minimum. * @returns the newly created route. */ get(opts: string | RegExp | RouteOptions, ...handlers: RequestHandlerType[]): Route | boolean; /** * Mounts a chain on the given path against this HTTP verb * * @param opts if string, the URL to handle. * if options, the URL to handle, at minimum. * @returns the newly created route. */ head(opts: string | RegExp | RouteOptions, ...handlers: RequestHandlerType[]): Route | boolean; /** * Mounts a chain on the given path against this HTTP verb * * @param opts if string, the URL to handle. * if options, the URL to handle, at minimum. * @returns the newly created route. */ opts(opts: string | RegExp | RouteOptions, ...handlers: RequestHandlerType[]): Route | boolean; /** * Mounts a chain on the given path against this HTTP verb * * @param opts if string, the URL to handle. * if options, the URL to handle, at minimum. * @returns the newly created route. */ post(opts: string | RegExp | RouteOptions, ...handlers: RequestHandlerType[]): Route | boolean; /** * Mounts a chain on the given path against this HTTP verb * * @param opts if string, the URL to handle. * if options, the URL to handle, at minimum. * @returns the newly created route. */ put(opts: string | RegExp | RouteOptions, ...handlers: RequestHandlerType[]): Route | boolean; /** * Mounts a chain on the given path against this HTTP verb * * @param opts if string, the URL to handle. * if options, the URL to handle, at minimum. * @returns the newly created route. */ patch(opts: string | RegExp | RouteOptions, ...handlers: RequestHandlerType[]): Route | boolean; /** * Minimal port of the functionality offered by Express.js Route Param * Pre-conditions * @link http://expressjs.com/guide.html#route-param%20pre-conditions * * This basically piggy-backs on the `server.use` method. It attaches a * new middleware function that only fires if the specified parameter exists * in req.params * * Exposes an API: * server.param("user", function (req, res, next) { * // load the user's information here, always making sure to call next() * }); * * @param name The name of the URL param to respond to * @param fn The middleware function to execute * @returns returns self */ param(name: string, fn: RequestHandler): Server; /** * Piggy-backs on the `server.use` method. It attaches a new middleware * function that only fires if the specified version matches the request. * * Note that if the client does not request a specific version, the middleware * function always fires. If you don't want this set a default version with a * pre handler on requests where the client omits one. * * Exposes an API: * server.versionedUse("version", function (req, res, next, ver) { * // do stuff that only applies to routes of this API version * }); * * @param versions the version(s) the URL to respond to * @param fn the middleware function to execute, the * fourth parameter will be the selected * version */ versionedUse(versions: string | string[], fn: RequestHandler): Server; /** * Removes a route from the server. * You pass in the route 'blob' you got from a mount call. * @throws {TypeError} on bad input. * @param route the route name. * @returns true if route was removed, false if not. */ rm(route: string): boolean; /** * Installs a list of handlers to run _before_ the "normal" handlers of all * routes. * * You can pass in any combination of functions or array of functions. * @returns returns self */ use(...handlers: RequestHandlerType[]): Server; /** * Gives you hooks to run _before_ any routes are located. This gives you * a chance to intercept the request and change headers, etc., that routing * depends on. Note that req.params will _not_ be set yet. * @returns returns self */ pre(...pre: RequestHandlerType[]): Server; /** * toString() the server for easy reading/output. */ toString(): string; /** * Return debug information about the server. */ getDebugInfo(): any; /** Name of the server. */ name: string; /** Default version(s) to use in all routes. */ versions: string[]; /** bunyan instance. */ log: Logger; /** List of content-types this server can respond with. */ acceptable: string[]; /** Once listen() is called, this will be filled in with where the server is running. */ url: string; /** Node server instance */ server: http.Server; /** Router instance */ router: Router; } export interface RouterOptions { contentType?: string | string[] | undefined; strictRouting?: boolean | undefined; log?: Logger | undefined; version?: string | undefined; versions?: string[] | undefined; } export interface Router { /** * takes an object of route params and query params, and 'renders' a URL. * @param routeName the route name * @param params an object of route params * @param query an object of query params */ render(routeName: string, params: any, query?: any): string; /** * adds a route. * @param options an options object * @returns returns the route name if creation is successful. */ mount(options: MountOptions): string | boolean; /** * unmounts a route. * @param name the route name * @returns the name of the deleted route. */ unmount(name: string): string; /** * get a route from the router. * @param name the name of the route to retrieve * @param req the request object * @param cb callback function */ get(name: string, req: Request, cb: FindRouteCallback): void; /** * find a route from inside the router, handles versioned routes. * @param req the request object * @param res the response object * @param callback callback function */ find(req: Request, res: Response, callback: FindRouteCallback): void; /** * Find a route by path. Scans the route list for a route with the same RegEx. * i.e. /foo/:param1/:param2 would match an existing route with different * parameter names /foo/:id/:name since the compiled RegExs match. * @param path a path to find a route for. * @param options an options object * @returns returns the route if a match is found */ findByPath(path: string | RegExp): Route; /** * toString() serialization. */ toString(): string; /** * Return information about the routes registered in the router. * @returns The routes in the router. */ getDebugInfo(): any; name: string; mounts: { [routeName: string]: Route }; versions: string[]; contentType: string[]; routes: { DELETE: Route[]; GET: Route[]; HEAD: Route[]; OPTIONS: Route[]; PATCH: Route[]; POST: Route[]; PUT: Route[]; }; log?: Logger | undefined; } export interface RequestFileInterface { path: string; type: string; } export interface RequestAuthorization { scheme: string; credentials: string; basic?: { username: string; password: string; } | undefined; } export interface Request extends http.IncomingMessage { /** * checks if the accept header is present and has the value requested. * e.g., req.accepts('html'); * @param types an array of accept type headers */ accepts(types: string | string[]): boolean; /** * checks if the request accepts the encoding types. * @param types an array of accept type headers */ acceptsEncoding(types: string | string[]): boolean; /** * gets the content-length header off the request. */ getContentLength(): number; /** * pass through to getContentLength. */ contentLength(): number; /** * gets the content-type header. */ getContentType(): string; /** * pass through to getContentType. */ contentType(): string; /** * retrieves the complete URI requested by the client. */ getHref(): string; /** * pass through to getHref. */ href(): string; /** * retrieves the request uuid. was created when the request was setup. */ getId(): string; /** * pass through to getId. */ id(): string; /** * retrieves the cleaned up url path. * e.g., /foo?a=1 => /foo */ getPath(): string; /** * pass through to getPath. */ path(): string; /** * returns the raw query string */ getQuery(): string; // /** // * pass through to getQuery. // * @public // * @function query // * @returns {String} // */ // query(): string; /** * returns ms since epoch when request was setup. */ time(): number; /** * returns a parsed URL object. */ getUrl(): url.Url; /** * returns the accept-version header. */ getVersion(): string; /** * pass through to getVersion. */ version(): string; /** * returns the version of the route that matched. */ matchedVersion(): string; /** * returns any header off the request. also, 'correct' any * correctly spelled 'referrer' header to the actual spelling used. * @param name the name of the header * @param value default value if header isn't found on the req */ header(name: string, value?: string): string; /** * returns any trailer header off the request. also, 'correct' any * correctly spelled 'referrer' header to the actual spelling used. * @param name the name of the header * @param value default value if header isn't found on the req */ trailer(name: string, value?: string): string; /** * Check if the incoming request contains the Content-Type header field, and * if it contains the given mime type. * @param type a content-type header value */ is(type: string): boolean; /** * Check if the incoming request is chunked. */ isChunked(): boolean; /** * Check if the incoming request is kept alive. */ isKeepAlive(): boolean; /** * Check if the incoming request is encrypted. */ isSecure(): boolean; /** * Check if the incoming request has been upgraded. */ isUpgradeRequest(): boolean; /** * Check if the incoming request is an upload verb. */ isUpload(): boolean; /** * toString serialization */ toString(): string; /** * retrieves the user-agent header. */ userAgent(): string; /** * Start the timer for a request handler function. You must explicitly invoke * endHandlerTimer() after invoking this function. Otherwise timing information * will be inaccurate. * @param handlerName The name of the handler. */ startHandlerTimer(handlerName: string): void; /** * Stop the timer for a request handler function. * @param handlerName The name of the handler. */ endHandlerTimer(handlerName: string): void; /** * returns the connection state of the request. current valid values are * 'close' and 'aborted'. */ connectionState(): string; /** * returns the route object to which the current request was matched to. * Route info object structure: * { * path: '/ping/:name', * method: 'GET', * versions: [], * name: 'getpingname' * } */ getRoute(): RouteSpec; /** bunyan logger you can piggyback on. */ log: Logger; /** available when queryParser plugin is used. */ query?: any; /** available when bodyParser plugin is used. */ body?: any; /** available when queryParser or bodyParser plugin is used with mapParams enabled. */ params?: any; /** available when serveStatic plugin is used. */ files?: { [name: string]: RequestFileInterface } | undefined; /** available when authorizationParser plugin is used */ username?: string | undefined; /** available when authorizationParser plugin is used */ authorization?: RequestAuthorization | undefined; } export interface CacheOptions { maxAge: number; } export interface Response extends http.ServerResponse { /** * sets the cache-control header. `type` defaults to _public_, * and options currently only takes maxAge. * @param type value of the header * @param [options] an options object * @returns the value set to the header */ cache(type: string, options?: CacheOptions): string; /** * sets the cache-control header. `type` defaults to _public_, * and options currently only takes maxAge. * @param [options] an options object * @returns the value set to the header */ cache(options?: CacheOptions): string; /** * turns off all cache related headers. * @returns self, the response object */ noCache(): Response; /** * Appends the provided character set to the response's Content-Type. * e.g., res.charSet('utf-8'); * @param type char-set value * @returns self, the response object */ charSet(type: string): Response; /** * retrieves a header off the response. * @param name the header name */ get(name: string): string; /** * retrieves all headers off the response. */ getHeaders(): any; /** * pass through to getHeaders. */ headers(): any; /** * sets headers on the response. * @param name the name of the header * @param value the value of the header */ header(name: string, value?: any): any; /** * short hand method for: * res.contentType = 'json'; * res.send({hello: 'world'}); * @param code http status code * @param object value to json.stringify * @param [headers] headers to set on the response */ json(code: number, object: any, headers?: { [header: string]: string }): any; /** * short hand method for: * res.contentType = 'json'; * res.send({hello: 'world'}); * @param object value to json.stringify * @param [headers] headers to set on the response */ json(object: any, headers?: { [header: string]: string }): any; /** * sets the link heaader. * @param l the link key * @param rel the link value * @returns the header value set to res */ link(l: string, rel: string): string; /** * sends the response object. pass through to internal __send that uses a * formatter based on the content-type header. * @param [code] http status code * @param [body] the content to send * @param [headers] any add'l headers to set * @returns the response object */ send(code?: any, body?: any, headers?: { [header: string]: string }): any; /** * sends the response object. pass through to internal __send that skips * formatters entirely and sends the content as is. * @param [code] http status code * @param [body] the content to send * @param [headers] any add'l headers to set * @returns the response object */ sendRaw(code?: any, body?: any, headers?: { [header: string]: string }): any; /** * sets a header on the response. * @param name name of the header * @param val value of the header * @returns self, the response object */ set(name: string, val: string): Response; /** * sets the http status code on the response. * @param code http status code * @returns the status code passed in */ status(code: number): number; /** * toString() serialization. */ toString(): string; /** * redirect is sugar method for redirecting. * res.redirect(301, 'www.foo.com', next); * `next` is mandatory, to complete the response and trigger audit logger. * @param code the status code * @param url to redirect to * @param next fn * @emits redirect */ redirect(code: number, url: string, next: Next): void; /** * redirect is sugar method for redirecting. * res.redirect({...}, next); * `next` is mandatory, to complete the response and trigger audit logger. * @param options the options or url to redirect to * @param next fn * @emits redirect */ redirect(options: object | string, next: Next): void; /** HTTP status code. */ code: number; /** short hand for the header content-length. */ contentLength: number; /** short hand for the header content-type. */ contentType: string; /** A unique request id (x-request-id). */ id: string; } export interface Next { (err?: any): void; ifError(err?: any): void; } export interface RoutePathRegex extends RegExp { restifyParams: string[]; } export interface RouteSpec { method: string; name: string; path: string | RegExp; versions: string[]; } export interface Route { name: string; method: string; path: RoutePathRegex; spec: RouteSpec; types: string[]; versions: string[]; } export interface RouteOptions { name?: string | undefined; path?: string | RegExp | undefined; url?: string | RegExp | undefined; urlParamPattern?: RegExp | undefined; contentType?: string | string[] | undefined; version?: string | undefined; versions?: string[] | undefined; } export interface MountOptions { name: string; method: string; path?: string | RegExp | undefined; url?: string | RegExp | undefined; urlParamPattern?: RegExp | undefined; contentType?: string | string[] | undefined; version?: string | undefined; versions?: string[] | undefined; } export type FindRouteCallback = (err: Error, route?: Route, params?: any) => void; export type RequestHandler = (req: Request, res: Response, next: Next) => any; export type RequestHandlerType = RequestHandler | RequestHandler[]; export namespace bunyan { interface RequestCaptureOptions { /** The stream to which to write when dumping captured records. */ stream?: Logger.Stream | undefined; /** The streams to which to write when dumping captured records. */ streams?: ReadonlyArray<Logger.Stream> | undefined; /** * The level at which to trigger dumping captured records. Defaults to * bunyan.WARN. */ level?: Logger.LogLevel | undefined; /** Number of records to capture. Default 100. */ maxRecords?: number | undefined; /** * Number of simultaneous request id capturing buckets to maintain. * Default 1000. */ maxRequestIds?: number | undefined; /** * If true, then dump captured records on the *default* request id when * dumping. I.e. dump records logged without "req_id" field. Default * false. */ dumpDefault?: boolean | undefined; } /** * A Bunyan stream to capture records in a ring buffer and only pass through * on a higher-level record. E.g. buffer up all records but only dump when * getting a WARN or above. */ class RequestCaptureStream extends stream.Stream { constructor(opts: RequestCaptureOptions); /** write to the stream */ write(record: any): void; } const serializers: Logger.Serializers & { err: Logger.Serializer, req: Logger.Serializer, res: Logger.Serializer, client_req: Logger.Serializer, client_res: Logger.Serializer }; /** create a bunyan logger */ function createLogger(name: string): Logger; } export function createServer(options?: ServerOptions): Server; export type Formatter = (req: Request, res: Response, body: any) => string | null; export interface Formatters { [contentType: string]: Formatter; } export const formatters: Formatters; export namespace plugins { namespace pre { /** * Provide req.set(key, val) and req.get(key) methods for setting and retrieving context to a specific request. */ function context(): RequestHandler; function dedupeSlashes(): RequestHandler; /** * This pre handler fixes issues with node hanging when an asyncHandler is used prior to bodyParser. */ function pause(): RequestHandler; /** * Cleans up duplicate or trailing / on the URL */ function sanitizePath(): RequestHandler; /** * Automatically reuse incoming request header as the request id. */ function reqIdHeaders(options: { headers: string[] }): RequestHandler; /** * Checks req.urls query params with strict key/val format and rejects non-strict requests with status code 400. */ function strictQueryParams(options?: { message: string }): RequestHandler; /** * Regexp to capture curl user-agents */ function userAgentConnection(options?: { userAgentRegExp: any }): RequestHandler; } // *************** This module includes the following header parser plugins: /** * Check the client's Accept header can be handled by this server. */ function acceptParser(accepts: string[]): RequestHandler; interface AuditLoggerOptions { /** * Bunyan logger */ log: Logger; /** * The event from the server which initiates the * log, one of 'pre', 'routed', or 'after' */ event: 'pre' | 'routed' | 'after'; /** * Restify server. If passed in, causes server to emit 'auditlog' event after audit logs are flushed */ server?: Server | undefined; /** * Ringbuffer which is written to if passed in */ logBuffer?: any; /** * When true, prints audit logs. default true. */ printLog?: boolean | undefined; body?: boolean | undefined; } /** * An audit logger for recording all handled requests */ function auditLogger(options: AuditLoggerOptions): (...args: any[]) => void; /** * Authorization header */ function authorizationParser(options?: any): RequestHandler; interface HandlerCandidate { handler: RequestHandler | RequestHandler[]; version?: string | string[] | undefined; contentType?: string | string[] | undefined; } /** * Runs first handler that matches to the condition */ function conditionalHandler(candidates: HandlerCandidate | HandlerCandidate[]): RequestHandler; /** * Conditional headers (If-*) */ function conditionalRequest(): RequestHandler[]; /** * Handles disappeared CORS headers */ function fullResponse(): RequestHandler; // ************ This module includes the following data parsing plugins: interface BodyParserOptions { /** * The maximum size in bytes allowed in the HTTP body. Useful for limiting clients from hogging server memory. */ maxBodySize?: number | undefined; /** * If req.params should be filled with parsed parameters from HTTP body. */ mapParams?: boolean | undefined; /** * If req.params should be filled with the contents of files sent through a multipart request. * Formidable is used internally for parsing, and a file is denoted as a multipart part with the filename option set in its Content-Disposition. * This will only be performed if mapParams is true. */ mapFiles?: boolean | undefined; /** * If an entry in req.params should be overwritten by the value in the body if the names are the same. * For instance, if you have the route /:someval, and someone posts an x-www-form-urlencoded Content-Type with the body someval=happy to /sad, * the value will be happy if overrideParams is true, sad otherwise. */ overrideParams?: boolean | undefined; /** * A callback to handle any multipart part which is not a file. * If this is omitted, the default handler is invoked which may or may not map the parts into req.params, depending on the mapParams-option. */ multipartHandler?(): void; /** * A callback to handle any multipart file. * It will be a file if the part have a Content-Disposition with the filename parameter set. * This typically happens when a browser sends a form and there is a parameter similar to <input type="file" />. * If this is not provided, the default behaviour is to map the contents into req.params. */ multipartFileHandler?(): void; /** * If you want the uploaded files to include the extensions of the original files (multipart uploads only). Does nothing if multipartFileHandler is defined. */ keepExtensions?: boolean | undefined; /** * Where uploaded files are intermediately stored during transfer before the contents is mapped into req.params. Does nothing if multipartFileHandler is defined. */ uploadDir?: string | undefined; /** * If you want to support html5 multiple attribute in upload fields. */ multiples?: boolean | undefined; /** * If you want checksums calculated for incoming files, set this to either sha1 or md5. */ hash?: string | undefined; /** * Set to true if you want to end the request with a UnsupportedMediaTypeError when none of the supported content types was given. */ rejectUnknown?: boolean | undefined; reviver?: any; maxFieldsSize?: number | undefined; } /** * Parses POST bodies to req.body. automatically uses one of the following parsers based on content type. */ function bodyParser(options?: BodyParserOptions): RequestHandler[]; /** * Reads the body of the request. */ function bodyReader(options?: { maxBodySize?: number | undefined }): RequestHandler; interface UrlEncodedBodyParser { mapParams?: boolean | undefined; overrideParams?: boolean | undefined; } /** * Parse the HTTP request body IFF the contentType is application/x-www-form-urlencoded. * * If req.params already contains a given key, that key is skipped and an * error is logged. */ function urlEncodedBodyParser(options?: UrlEncodedBodyParser): RequestHandler[]; /** * Parses JSON POST bodies */ function jsonBodyParser(options?: { mapParams?: boolean | undefined, reviver?: any, overrideParams?: boolean | undefined }): RequestHandler[]; /** * Parses JSONP callback */ function jsonp(): RequestHandler; interface MultipartBodyParser { overrideParams?: boolean | undefined; multiples?: boolean | undefined; keepExtensions?: boolean | undefined; uploadDir?: string | undefined; maxFieldsSize?: number | undefined; hash?: string | undefined; multipartFileHandler?: any; multipartHandler?: any; mapParams?: boolean | undefined; mapFiles?: boolean | undefined; } /** * Parses JSONP callback */ function multipartBodyParser(options?: MultipartBodyParser): RequestHandler; interface QueryParserOptions { /** * Default `false`. Copies parsed query parameters into `req.params`. */ mapParams?: boolean | undefined; /** * Default `false`. Only applies when if mapParams true. When true, will stomp on req.params field when existing value is found. */ overrideParams?: boolean | undefined; /** * Default false. Transform `?foo.bar=baz` to a nested object: `{foo: {bar: 'baz'}}`. */ allowDots?: boolean | undefined; /** * Default 20. Only transform `?a[$index]=b` to an array if `$index` is less than `arrayLimit`. */ arrayLimit?: number | undefined; /** * Default 5. The depth limit for parsing nested objects, e.g. `?a[b][c][d][e][f][g][h][i]=j`. */ depth?: number | undefined; /** * Default 1000. Maximum number of query params parsed. Additional params are silently dropped. */ parameterLimit?: number | undefined; /** * Default true. Whether to parse `?a[]=b&a[1]=c` to an array, e.g. `{a: ['b', 'c']}`. */ parseArrays?: boolean | undefined; /** * Default false. Whether `req.query` is a "plain" object -- does not inherit from `Object`. * This can be used to allow query params whose names collide with Object methods, e.g. `?hasOwnProperty=blah`. */ plainObjects?: boolean | undefined; /** * Default false. If true, `?a&b=` results in `{a: null, b: ''}`. Otherwise, `{a: '', b: ''}`. */ strictNullHandling?: boolean | undefined; } /** * Parses URL query parameters into `req.query`. Many options correspond directly to option defined for the underlying [qs.parse](https://github.com/ljharb/qs) */ function queryParser(options?: QueryParserOptions): RequestHandler; interface RequestLogger { properties?: any; serializers?: any; headers?: any; log?: any; } /** * Adds timers for each handler in your request chain * * `options.properties` properties to pass to bunyan's `log.child()` method */ function requestLogger(options?: RequestLogger): RequestHandler; // ******************** The module includes the following response plugins: /** * expires requests based on current time + delta * @param delta - age in seconds */ function dateParser(delta?: number): RequestHandler; /** * gzips the response if client send `accept-encoding: gzip` * @param options options to pass to gzlib */ function gzipResponse(options?: any): RequestHandler; interface ServeStatic { appendRequestPath?: boolean | undefined; directory?: string | undefined; maxAge?: number | undefined; match?: any; charSet?: string | undefined; file?: string | undefined; etag?: string | undefined; default?: any; gzip?: boolean | undefined; } /** * Used to serve static files */ function serveStatic(options?: ServeStatic): RequestHandler; interface ThrottleOptions { burst?: number | undefined; rate?: number | undefined; ip?: boolean | undefined; username?: boolean | undefined; xff?: boolean | undefined; tokensTable?: any; maxKeys?: number | undefined; overrides?: any; // any } interface MetricsCallback { /** * An error if the request had an error */ err: Error; metrics: MetricsCallbackOptions; req: Request; res: Response; /** * The route obj that serviced the request */ route: Route; } type TMetricsCallback = 'close' | 'aborted' | undefined; interface MetricsCallbackOptions { /** * Status code of the response. Can be undefined in the case of an `uncaughtException`. * Otherwise, in most normal scenarios, even calling `res.send()` or `res.end()` should result in a 200 by default. */ statusCode: number; /** * HTTP request verb */ method: string; /** * Request latency */ latency: number; /** * req.path() value */ path: string; /** * If this value is set, err will be a corresponding `RequestCloseError` or `RequestAbortedError`. * * If connectionState is either 'close' or 'aborted', then the statusCode is not applicable since the connection was severed before a response was written. */ connectionState: TMetricsCallback; } /** * Listens to the server's after event and emits information about that request (5.x compatible only). * * ``` * server.on('after', plugins.metrics({ server }, (err, metrics, req, res, route) => * { * // metrics is an object containing information about the request * })); * ``` */ function metrics(opts: { server: Server }, callback: MetricsCallback): (...args: any[]) => void; /** * Parse the client's request for an OAUTH2 access tokensTable * * Subsequent handlers will see `req.oauth2`, which looks like: * ``` * { * oauth2: {accessToken: 'mF_9.B5f-4.1JqM&p=q'} * } * ``` */ function oauth2TokenParser(): RequestHandler; /** * throttles responses */ function throttle(options?: ThrottleOptions): RequestHandler; interface RequestExpiryOptions { /** * Header name of the absolute time for request expiration */ absoluteHeader?: string | undefined; /** * Header name for the start time of the request */ startHeader?: string | undefined; /** * The header name for the time in milliseconds that should ellapse before the request is considered expired. */ timeoutHeader?: string | undefined; } /** * A request expiry will use headers to tell if the incoming request has expired or not. * * There are two options for this plugin: * 1. Absolute Time * * Time in Milliseconds since the Epoch when this request should be considered expired * 2. Timeout * * The request start time is supplied * * A timeout, in milliseconds, is given * * The timeout is added to the request start time to arrive at the absolute time * in which the request is considered expires */ function requestExpiry(options?: RequestExpiryOptions): RequestHandler; } export namespace pre { /** * Provide req.set(key, val) and req.get(key) methods for setting and retrieving context to a specific request. */ function context(): RequestHandler; function dedupeSlashes(): RequestHandler; /** * This pre handler fixes issues with node hanging when an asyncHandler is used prior to bodyParser. */ function pause(): RequestHandler; /** * Cleans up duplicate or trailing / on the URL */ function sanitizePath(): RequestHandler; /** * Automatically reuse incoming request header as the request id. */ function reqIdHeaders(options: { headers: string[] }): RequestHandler; /** * Checks req.urls query params with strict key/val format and rejects non-strict requests with status code 400. */ function strictQueryParams(options?: { message: string }): RequestHandler; /** * Regexp to capture curl user-agents */ function userAgentConnection(options?: { userAgentRegExp: any }): RequestHandler; }
the_stack
import * as React from 'react'; import { Dispatch, ActionCreator, Reducer } from 'redux'; export const actionTypes: { [actionName: string]: string }; export type FieldValue = any; export interface FormData { [fieldName: string]: FieldValue; } export interface FieldProp<T> { /** * true if this field currently has focus. It will only work if you are * passing onFocus to your input element. */ active: boolean; /** * An alias for value only when value is a boolean. Provided for * convenience of destructuring the whole field object into the props of a * form element. */ checked?: boolean | undefined; /** * true if the field value has changed from its initialized value. * Opposite of pristine. */ dirty: boolean; /** * The error for this field if its value is not passing validation. Both * synchronous and asynchronous validation errors will be reported here. */ error?: any; /** * The value for this field as supplied in initialValues to the form. */ initialValue: FieldValue; /** * true if the field value fails validation (has a validation error). * Opposite of valid. */ invalid: boolean; /** * The name of the field. It will be the same as the key in the fields * Object, but useful if bundling up a field to send down to a specialized * input component. */ name: string; /** * A function to call when the form field loses focus. It expects to * either receive the React SyntheticEvent or the current value of the * field. */ onBlur(eventOrValue: React.SyntheticEvent<T> | FieldValue): void; /** * A function to call when the form field is changed. It expects to either * receive the React SyntheticEvent or the new value of the field. * @param eventOrValue */ onChange(eventOrValue: React.SyntheticEvent<T> | FieldValue): void; /** * A function to call when the form field receives a 'dragStart' event. * Saves the field value in the event for giving the field it is dropped * into. */ onDragStart(): void; /** * A function to call when the form field receives a drop event. */ onDrop(): void; /** * A function to call when the form field receives focus. */ onFocus(): void; /** * An alias for onChange. Provided for convenience of destructuring the * whole field object into the props of a form element. Added to provide * out-of-the-box support for Belle components' onUpdate API. */ onUpdate(): void; /** * true if the field value is the same as its initialized value. Opposite * of dirty. */ pristine: boolean; /** * true if the field has been touched. By default this will be set when * the field is blurred. */ touched: boolean; /** * true if the field value passes validation (has no validation errors). * Opposite of invalid. */ valid: boolean; /** * The value of this form field. It will be a boolean for checkboxes, and * a string for all other input types. */ value: FieldValue; /** * true if this field has ever had focus. It will only work if you are * passing onFocus to your input element. */ visited: boolean; } export interface ReduxFormProps<T> { /** * The name of the currently active (with focus) field. */ active?: string | undefined; /** * A function that may be called to initiate asynchronous validation if * asynchronous validation is enabled. */ asyncValidate?(): void; /** * true if the asynchronous validation function has been called but has not * yet returned. */ asyncValidating?: boolean | undefined; /** * Destroys the form state in the Redux store. By default, this will be * called for you in componentWillUnmount(). */ destroyForm?(): void; /** * true if the form data has changed from its initialized values. Opposite * of pristine. */ dirty?: boolean | undefined; /** * A generic error for the entire form given by the _error key in the * result from the synchronous validation function, the asynchronous * validation, or the rejected promise from onSubmit. */ error?: any; /** * The form data, in the form { field1: <Object>, field2: <Object> }. The * field objects are meant to be destructured into your input component as * props, e.g. <input type="text" {...field.name}/>. Each field Object has * the following properties: */ fields?: { [field: string]: FieldProp<T> } | undefined; /** * A function meant to be passed to <form onSubmit={handleSubmit}> or to * <button onClick={handleSubmit}>. It will run validation, both sync and * async, and, if the form is valid, it will call * this.props.onSubmit(data) with the contents of the form data. * Optionally, you may also pass your onSubmit function to handleSubmit * which will take the place of the onSubmit prop. For example: <form * onSubmit={handleSubmit(this.save.bind(this))}> If your onSubmit * function returns a promise, the submitting property will be set to true * until the promise has been resolved or rejected. If it is rejected with * an object matching { field1: 'error', field2: 'error' } then the * submission errors will be added to each field (to the error prop) just * like async validation errors are. If there is an error that is not * specific to any field, but applicable to the entire form, you may pass * that as if it were the error for a field called _error, and it will be * given as the error prop. */ handleSubmit?(event: React.SyntheticEvent<T>): void; handleSubmit?(event: React.MouseEvent<HTMLButtonElement>): void; handleSubmit?(submit: (data: FormData, dispatch?: Dispatch<any>) => Promise<any> | void): React.FormEventHandler<T>; /** * Initializes the form data to the given values. All dirty and pristine * state will be determined by comparing the current data with these * initialized values. * @param data */ initializeForm?(data: FormData): void; /** * true if the form has validation errors. Opposite of valid. */ invalid?: boolean | undefined; /** * true if the form data is the same as its initialized values. Opposite * of dirty. */ pristine?: boolean | undefined; /** * Resets all the values in the form to the initialized state, making it * pristine again. */ resetForm?(): void; /** * The same formKey prop that was passed in. See Editing Multiple Records. */ formKey?: string | undefined; /** * Whether or not your form is currently submitting. This prop will only * work if you have passed an onSubmit function that returns a promise. It * will be true until the promise is resolved or rejected. */ submitting?: boolean | undefined; /** * Starts as false. If onSubmit is called, and fails to submit for any * reason, submitFailed will be set to true. A subsequent successful * submit will set it back to false. */ submitFailed?: boolean | undefined; /** * Marks the given fields as "touched" to show errors. * @param field */ touch?(...field: string[]): void; /** * Marks all fields as "touched" to show errors. This will automatically * happen on form submission. */ touchAll?(): void; /** * Clears the "touched" flag for the given fields * @param field */ untouch?(...field: string[]): void; /** * Clears the "touched" flag for the all fields */ untouchAll?(): void; /** * true if the form passes validation (has no validation errors). Opposite * of invalid. */ valid?: boolean | undefined; /** * All of your values in the form { field1: <string>, field2: <string> }. */ values?: FormData | undefined; } declare class ElementClass extends React.Component<any> { } interface ClassDecorator { <T extends (typeof ElementClass)>(component: T): T; } interface MapStateToProps { (state: any, ownProps?: any): any; } interface MapDispatchToPropsFunction { (dispatch: Dispatch<any>, ownProps?: any): any; } interface MapDispatchToPropsObject { [name: string]: ActionCreator<any>; } export declare function reduxForm(config: ReduxFormConfig, mapStateToProps?: MapStateToProps, mapDispatchToProps?: MapDispatchToPropsFunction | MapDispatchToPropsObject): ClassDecorator; export interface ReduxFormConfig { /** * a list of all your fields in your form. You may change these dynamically * at runtime. */ fields: string[]; /** * the name of your form and the key to where your form's state will be * mounted under the redux-form reducer */ form: string; /** * By default, async blur validation is only triggered if synchronous * validation passes, and the form is dirty or was never initialized (or if * submitting). Sometimes it may be desirable to trigger asynchronous * validation even in these cases, for example if all validation is performed * asynchronously and you want to display validation messages if a user does * not change a field, but does touch and blur it. Setting * alwaysAsyncValidate to true will always run asynchronous validation on * blur, even if the form is pristine or sync validation fails. */ alwaysAsyncValidate?: boolean | undefined; /** * field names for which onBlur should trigger a call to the asyncValidate * function. Defaults to []. * * See Asynchronous Blur Validation Example for more details. */ asyncBlurFields?: string[] | undefined; /** * a function that takes all the form values, the dispatch function, and * the props given to your component, and returns a Promise that will * resolve if the validation is passed, or will reject with an object of * validation errors in the form { field1: <String>, field2: <String> }. * * See Asynchronous Blur Validation Example for more details. */ asyncValidate?(values: FormData, dispatch: Dispatch<any>, props: {}): Promise<any>; /** * Whether or not to automatically destroy your form's state in the Redux * store when your component is unmounted. Defaults to true. */ destroyOnUnmount?: boolean | undefined; /** * The key for your sub-form. * * See Multirecord Example for more details. */ formKey?: string | undefined; /** * A function that takes the entire Redux state and the reduxMountPoint * (which defaults to "form"). It defaults to: * (state, reduxMountPoint) => state[reduxMountPoint]. * The only reason you should provide this is if you are keeping your Redux * state as something other than plain javascript objects, e.g. an * Immutable.Map. */ getFormState?(state: any, reduxMountPoint: string): any; /** * The values with which to initialize your form in componentWillMount(). * Particularly useful when Editing Multiple Records, but can also be used * with single-record forms. The values should be in the form * { field1: 'value1', field2: 'value2' }. */ initialValues?: { [field: string]: FieldValue } | undefined; /** * The function to call with the form data when the handleSubmit() is fired * from within the form component. If you do not specify it as a prop here, * you must pass it as a parameter to handleSubmit() inside your form * component. */ onSubmit?(values: FormData, dispatch?: Dispatch<any>): any; /** * If true, the form values will be overwritten whenever the initialValues * prop changes. If false, the values will not be overwritten if the form has * previously been initialized. Defaults to true. */ overwriteOnInitialValuesChange?: boolean | undefined; /** * If specified, all the props normally passed into your decorated * component directly will be passed under the key specified. Useful if * using other decorator libraries on the same component to avoid prop * namespace collisions. */ propNamespace?: string | undefined; /** * if true, the decorated component will not be passed any of the onX * functions as props that will allow it to mutate the state. Useful for * decorating another component that is not your form, but that needs to * know about the state of your form. */ readonly?: boolean | undefined; /** * The use of this property is highly discouraged, but if you absolutely * need to mount your redux-form reducer at somewhere other than form in * your Redux state, you will need to specify the key you mounted it under * with this property. Defaults to 'form'. * * See Alternate Mount Point Example for more details. */ reduxMountPoint?: string | undefined; /** * If set to true, a failed submit will return a rejected promise. Defaults * to false. Only use this if you need to detect submit failures and run * some code when a submit fails. */ returnRejectedSubmitPromise?: boolean | undefined; /** * marks fields as touched when the blur action is fired. Defaults to true. */ touchOnBlur?: boolean | undefined; /** * marks fields as touched when the change action is fired. Defaults to * false. */ touchOnChange?: boolean | undefined; /** * a synchronous validation function that takes the form values and props * passed into your component. If validation passes, it should return {}. * If validation fails, it should return the validation errors in the form * { field1: <String>, field2: <String> }. * Defaults to (values, props) => ({}). */ validate?(values: FormData, props: { [fieldName: string]: FieldProp<any> }): {}; } /** * @param value The current value of the field. * @param previousValue The previous value of the field before the current * action was dispatched. * @param allValues All the values of the current form. * @param previousAllValues All the values of the form before the current * change. Useful to change one field based on a change in another. */ export type Normalizer = (value: FieldValue, previousValue: FieldValue, allValues: FormData, previousAllValues: FormData) => any; export declare const reducer: { (state: any, action: any): any; /** * Returns a form reducer that will also pass each form value through the * normalizing functions provided. The parameter is an object mapping from * formName to an object mapping from fieldName to a normalizer function. * The normalizer function is given four parameters and expected to return * the normalized value of the field. */ normalize(normalizers: { [formName: string]: { [fieldName: string]: Normalizer } }): Reducer<any>; /** * Returns a form reducer that will also pass each action through * additional reducers specified. The parameter should be an object mapping * from formName to a (state, action) => nextState reducer. The state * passed to each reducer will only be the slice that pertains to that * form. */ plugin(reducers: { [formName: string]: Reducer<any> }): Reducer<any>; };
the_stack
import * as ComponentConstructors from '../../components'; import { SlideMatcher } from '../../components/Slides/Slides'; import { CLASS_INITIALIZED } from '../../constants/classes'; import { DEFAULTS } from '../../constants/defaults'; import { EVENT_DESTROY, EVENT_MOUNTED, EVENT_READY, EVENT_REFRESH, EVENT_UPDATED } from '../../constants/events'; import { DEFAULT_USER_EVENT_PRIORITY } from '../../constants/priority'; import { CREATED, DESTROYED, IDLE, STATES } from '../../constants/states'; import { FADE } from '../../constants/types'; import { EventBus, EventBusCallback, EventBusObject, State, StateObject } from '../../constructors'; import { Fade, Slide } from '../../transitions'; import { ComponentConstructor, Components, EventMap, Options } from '../../types'; import { addClass, assert, assign, empty, forOwn, isString, merge, query, slice } from '../../utils'; /** * The frontend class for the Splide slider. * * @since 3.0.0 */ export class Splide { /** * Changes the default options for all Splide instances. */ static defaults: Options = {}; /** * The collection of state numbers. */ static readonly STATES = STATES; /** * The root element where the Splide is applied. */ readonly root: HTMLElement; /** * The EventBusObject object. */ readonly event: EventBusObject = EventBus(); /** * The collection of all component objects. */ readonly Components: Components = {} as Components; /** * The StateObject object. */ readonly state: StateObject = State( CREATED ); /** * Splide instances to sync with. */ readonly splides: Splide[] = []; /** * The collection of options. */ private readonly _options: Options = {}; /** * The collection of all components. */ private _Components: Components; /** * The collection of extensions. */ private _Extensions: Record<string, ComponentConstructor> = {}; /** * The Transition component. */ private _Transition: ComponentConstructor; /** * The Splide constructor. * * @param target - The selector for the target element, or the element itself. * @param options - Optional. An object with options. */ constructor( target: string | HTMLElement, options?: Options ) { const root = isString( target ) ? query<HTMLElement>( document, target ) : target; assert( root, `${ root } is invalid.` ); this.root = root; merge( DEFAULTS, Splide.defaults ); merge( merge( this._options, DEFAULTS ), options || {} ); } /** * Initializes the instance. * * @param Extensions - Optional. An object with extensions. * @param Transition - Optional. A Transition component. * * @return `this` */ mount( Extensions?: Record<string, ComponentConstructor>, Transition?: ComponentConstructor ): this { const { state, Components } = this; assert( state.is( [ CREATED, DESTROYED ] ), 'Already mounted!' ); state.set( CREATED ); this._Components = Components; this._Transition = Transition || this._Transition || ( this.is( FADE ) ? Fade : Slide ); this._Extensions = Extensions || this._Extensions; const Constructors = assign( {}, ComponentConstructors, this._Extensions, { Transition: this._Transition } ); forOwn( Constructors, ( Component, key ) => { const component = Component( this, Components, this._options ); Components[ key ] = component; component.setup && component.setup(); } ); forOwn( Components, component => { component.mount && component.mount(); } ); this.emit( EVENT_MOUNTED ); addClass( this.root, CLASS_INITIALIZED ); state.set( IDLE ); this.emit( EVENT_READY ); return this; } /** * Syncs the slider with the provided one. * This method must be called before the `mount()`. * * @example * ```ts * var primary = new Splide(); * var secondary = new Splide(); * * primary.sync( secondary ); * primary.mount(); * secondary.mount(); * ``` * * @param splide - A Splide instance to sync with. * * @return `this` */ sync( splide: Splide ): this { this.splides.push( splide ); splide.splides.push( this ); return this; } /** * Moves the slider with the following control pattern. * * | Pattern | Description | * |---|---| * | `i` | Goes to the slide `i` | * | `'+${i}'` | Increments the slide index by `i` | * | `'-${i}'` | Decrements the slide index by `i` | * | `'>'` | Goes to the next page | * | `'<'` | Goes to the previous page | * | `>${i}` | Goes to the page `i` | * * In most cases, `'>'` and `'<'` notations are enough to control the slider * because they respect `perPage` and `perMove` options. * * @example * ```ts * var splide = new Splide(); * * // Goes to the slide 1: * splide.go( 1 ); * * // Increments the index: * splide.go( '+2' ); * * // Goes to the next page: * splide.go( '>' ); * * // Goes to the page 2: * splide.go( '>2' ); * ``` * * @param control - A control pattern. * * @return `this` */ go( control: number | string ): this { this._Components.Controller.go( control ); return this; } /** * Registers an event handler. * * @example * ```ts * var splide = new Splide(); * * // Listens to a single event: * splide.on( 'move', function() {} ); * * // Listens to multiple events: * splide.on( 'move resize', function() {} ); * * // Appends a namespace: * splide.on( 'move.myNamespace resize.myNamespace', function() {} ); * ``` * * @param events - An event name or names separated by spaces. Use a dot(.) to append a namespace. * @param callback - A callback function. * * @return `this` */ on<K extends keyof EventMap>( events: K, callback: EventMap[ K ] ): this; on( events: string | string[], callback: EventBusCallback ): this { this.event.on( events, callback, null, DEFAULT_USER_EVENT_PRIORITY ); return this; } /** * Removes the registered all handlers for the specified event or events. * If you want to only remove a particular handler, use namespace to identify it. * * @example * ```ts * var splide = new Splide(); * * // Removes all handlers assigned to "move": * splide.off( 'move' ); * * // Only removes handlers that belong to the specified namespace: * splide.off( 'move.myNamespace' ); * ``` * * @param events - An event name or names separated by spaces. Use a dot(.) to append a namespace. * * @return `this` */ off<K extends keyof EventMap>( events: K | K[] | string | string[] ): this { this.event.off( events ); return this; } /** * Emits an event and triggers registered handlers. * * @param event - An event name to emit. * @param args - Optional. Any number of arguments to pass to handlers. * * @return `this` */ emit<K extends keyof EventMap>( event: K, ...args: Parameters<EventMap[ K ]> ): this; emit( event: string, ...args: any[] ): this; emit( event: string ): this { // eslint-disable-next-line prefer-rest-params, prefer-spread this.event.emit( event, ...slice( arguments, 1 ) ); return this; } /** * Inserts a slide at the specified position. * * @example * ```ts * var splide = new Splide(); * splide.mount(); * * // Adds the slide by the HTML: * splide.add( '<li></li> ); * * // or adds the element: * splide.add( document.createElement( 'li' ) ); * ``` * * @param slides - A slide element, an HTML string that represents a slide, or an array with them. * @param index - Optional. An index to insert a slide at. * * @return `this` */ add( slides: string | HTMLElement | Array<string | HTMLElement>, index?: number ): this { this._Components.Slides.add( slides, index ); return this; } /** * Removes slides that match the matcher * that can be an index, an array with indices, a selector, or an iteratee function. * * @param matcher - An index, an array with indices, a selector string, or an iteratee function. */ remove( matcher: SlideMatcher ): this { this._Components.Slides.remove( matcher ); return this; } /** * Checks the slider type. * * @param type - A type to test. * * @return `true` if the type matches the current one, or otherwise `false`. */ is( type: string ): boolean { return this._options.type === type; } /** * Refreshes the slider. * * @return `this` */ refresh(): this { this.emit( EVENT_REFRESH ); return this; } /** * Destroys the slider. * * @param completely - Optional. If `true`, Splide will not remount the slider by breakpoints. * * @return `this` */ destroy( completely = true ): this { const { event, state } = this; if ( state.is( CREATED ) ) { // Postpones destruction requested before the slider becomes ready. event.on( EVENT_READY, this.destroy.bind( this, completely ), this ); } else { forOwn( this._Components, component => { component.destroy && component.destroy( completely ); }, true ); event.emit( EVENT_DESTROY ); event.destroy(); completely && empty( this.splides ); state.set( DESTROYED ); } return this; } /** * Returns options. * * @return An object with the latest options. */ get options(): Options { return this._options; } /** * Merges options to the current options and emits `updated` event. * * @param options - An object with new options. */ set options( options: Options ) { const { _options } = this; merge( _options, options ); if ( ! this.state.is( CREATED ) ) { this.emit( EVENT_UPDATED, _options ); } } /** * Returns the number of slides without clones. * * @return The number of slides. */ get length(): number { return this._Components.Slides.getLength( true ); } /** * Returns the active slide index. * * @return The active slide index. */ get index(): number { return this._Components.Controller.getIndex(); } }
the_stack
import * as msRest from "@azure/ms-rest-js"; import * as msRestAzure from "@azure/ms-rest-azure-js"; import * as Models from "../models"; import * as Mappers from "../models/experimentsMappers"; import * as Parameters from "../models/parameters"; import { BatchAIManagementClientContext } from "../batchAIManagementClientContext"; /** Class representing a Experiments. */ export class Experiments { private readonly client: BatchAIManagementClientContext; /** * Create a Experiments. * @param {BatchAIManagementClientContext} client Reference to the service client. */ constructor(client: BatchAIManagementClientContext) { this.client = client; } /** * Gets a list of Experiments within the specified Workspace. * @param resourceGroupName Name of the resource group to which the resource belongs. * @param workspaceName The name of the workspace. Workspace names can only contain a combination * of alphanumeric characters along with dash (-) and underscore (_). The name must be from 1 * through 64 characters long. * @param [options] The optional parameters * @returns Promise<Models.ExperimentsListByWorkspaceResponse> */ listByWorkspace(resourceGroupName: string, workspaceName: string, options?: Models.ExperimentsListByWorkspaceOptionalParams): Promise<Models.ExperimentsListByWorkspaceResponse>; /** * @param resourceGroupName Name of the resource group to which the resource belongs. * @param workspaceName The name of the workspace. Workspace names can only contain a combination * of alphanumeric characters along with dash (-) and underscore (_). The name must be from 1 * through 64 characters long. * @param callback The callback */ listByWorkspace(resourceGroupName: string, workspaceName: string, callback: msRest.ServiceCallback<Models.ExperimentListResult>): void; /** * @param resourceGroupName Name of the resource group to which the resource belongs. * @param workspaceName The name of the workspace. Workspace names can only contain a combination * of alphanumeric characters along with dash (-) and underscore (_). The name must be from 1 * through 64 characters long. * @param options The optional parameters * @param callback The callback */ listByWorkspace(resourceGroupName: string, workspaceName: string, options: Models.ExperimentsListByWorkspaceOptionalParams, callback: msRest.ServiceCallback<Models.ExperimentListResult>): void; listByWorkspace(resourceGroupName: string, workspaceName: string, options?: Models.ExperimentsListByWorkspaceOptionalParams | msRest.ServiceCallback<Models.ExperimentListResult>, callback?: msRest.ServiceCallback<Models.ExperimentListResult>): Promise<Models.ExperimentsListByWorkspaceResponse> { return this.client.sendOperationRequest( { resourceGroupName, workspaceName, options }, listByWorkspaceOperationSpec, callback) as Promise<Models.ExperimentsListByWorkspaceResponse>; } /** * Creates an Experiment. * @param resourceGroupName Name of the resource group to which the resource belongs. * @param workspaceName The name of the workspace. Workspace names can only contain a combination * of alphanumeric characters along with dash (-) and underscore (_). The name must be from 1 * through 64 characters long. * @param experimentName The name of the experiment. Experiment names can only contain a * combination of alphanumeric characters along with dash (-) and underscore (_). The name must be * from 1 through 64 characters long. * @param [options] The optional parameters * @returns Promise<Models.ExperimentsCreateResponse> */ create(resourceGroupName: string, workspaceName: string, experimentName: string, options?: msRest.RequestOptionsBase): Promise<Models.ExperimentsCreateResponse> { return this.beginCreate(resourceGroupName,workspaceName,experimentName,options) .then(lroPoller => lroPoller.pollUntilFinished()) as Promise<Models.ExperimentsCreateResponse>; } /** * Deletes an Experiment. * @param resourceGroupName Name of the resource group to which the resource belongs. * @param workspaceName The name of the workspace. Workspace names can only contain a combination * of alphanumeric characters along with dash (-) and underscore (_). The name must be from 1 * through 64 characters long. * @param experimentName The name of the experiment. Experiment names can only contain a * combination of alphanumeric characters along with dash (-) and underscore (_). The name must be * from 1 through 64 characters long. * @param [options] The optional parameters * @returns Promise<msRest.RestResponse> */ deleteMethod(resourceGroupName: string, workspaceName: string, experimentName: string, options?: msRest.RequestOptionsBase): Promise<msRest.RestResponse> { return this.beginDeleteMethod(resourceGroupName,workspaceName,experimentName,options) .then(lroPoller => lroPoller.pollUntilFinished()); } /** * Gets information about an Experiment. * @param resourceGroupName Name of the resource group to which the resource belongs. * @param workspaceName The name of the workspace. Workspace names can only contain a combination * of alphanumeric characters along with dash (-) and underscore (_). The name must be from 1 * through 64 characters long. * @param experimentName The name of the experiment. Experiment names can only contain a * combination of alphanumeric characters along with dash (-) and underscore (_). The name must be * from 1 through 64 characters long. * @param [options] The optional parameters * @returns Promise<Models.ExperimentsGetResponse> */ get(resourceGroupName: string, workspaceName: string, experimentName: string, options?: msRest.RequestOptionsBase): Promise<Models.ExperimentsGetResponse>; /** * @param resourceGroupName Name of the resource group to which the resource belongs. * @param workspaceName The name of the workspace. Workspace names can only contain a combination * of alphanumeric characters along with dash (-) and underscore (_). The name must be from 1 * through 64 characters long. * @param experimentName The name of the experiment. Experiment names can only contain a * combination of alphanumeric characters along with dash (-) and underscore (_). The name must be * from 1 through 64 characters long. * @param callback The callback */ get(resourceGroupName: string, workspaceName: string, experimentName: string, callback: msRest.ServiceCallback<Models.Experiment>): void; /** * @param resourceGroupName Name of the resource group to which the resource belongs. * @param workspaceName The name of the workspace. Workspace names can only contain a combination * of alphanumeric characters along with dash (-) and underscore (_). The name must be from 1 * through 64 characters long. * @param experimentName The name of the experiment. Experiment names can only contain a * combination of alphanumeric characters along with dash (-) and underscore (_). The name must be * from 1 through 64 characters long. * @param options The optional parameters * @param callback The callback */ get(resourceGroupName: string, workspaceName: string, experimentName: string, options: msRest.RequestOptionsBase, callback: msRest.ServiceCallback<Models.Experiment>): void; get(resourceGroupName: string, workspaceName: string, experimentName: string, options?: msRest.RequestOptionsBase | msRest.ServiceCallback<Models.Experiment>, callback?: msRest.ServiceCallback<Models.Experiment>): Promise<Models.ExperimentsGetResponse> { return this.client.sendOperationRequest( { resourceGroupName, workspaceName, experimentName, options }, getOperationSpec, callback) as Promise<Models.ExperimentsGetResponse>; } /** * Creates an Experiment. * @param resourceGroupName Name of the resource group to which the resource belongs. * @param workspaceName The name of the workspace. Workspace names can only contain a combination * of alphanumeric characters along with dash (-) and underscore (_). The name must be from 1 * through 64 characters long. * @param experimentName The name of the experiment. Experiment names can only contain a * combination of alphanumeric characters along with dash (-) and underscore (_). The name must be * from 1 through 64 characters long. * @param [options] The optional parameters * @returns Promise<msRestAzure.LROPoller> */ beginCreate(resourceGroupName: string, workspaceName: string, experimentName: string, options?: msRest.RequestOptionsBase): Promise<msRestAzure.LROPoller> { return this.client.sendLRORequest( { resourceGroupName, workspaceName, experimentName, options }, beginCreateOperationSpec, options); } /** * Deletes an Experiment. * @param resourceGroupName Name of the resource group to which the resource belongs. * @param workspaceName The name of the workspace. Workspace names can only contain a combination * of alphanumeric characters along with dash (-) and underscore (_). The name must be from 1 * through 64 characters long. * @param experimentName The name of the experiment. Experiment names can only contain a * combination of alphanumeric characters along with dash (-) and underscore (_). The name must be * from 1 through 64 characters long. * @param [options] The optional parameters * @returns Promise<msRestAzure.LROPoller> */ beginDeleteMethod(resourceGroupName: string, workspaceName: string, experimentName: string, options?: msRest.RequestOptionsBase): Promise<msRestAzure.LROPoller> { return this.client.sendLRORequest( { resourceGroupName, workspaceName, experimentName, options }, beginDeleteMethodOperationSpec, options); } /** * Gets a list of Experiments within the specified Workspace. * @param nextPageLink The NextLink from the previous successful call to List operation. * @param [options] The optional parameters * @returns Promise<Models.ExperimentsListByWorkspaceNextResponse> */ listByWorkspaceNext(nextPageLink: string, options?: msRest.RequestOptionsBase): Promise<Models.ExperimentsListByWorkspaceNextResponse>; /** * @param nextPageLink The NextLink from the previous successful call to List operation. * @param callback The callback */ listByWorkspaceNext(nextPageLink: string, callback: msRest.ServiceCallback<Models.ExperimentListResult>): void; /** * @param nextPageLink The NextLink from the previous successful call to List operation. * @param options The optional parameters * @param callback The callback */ listByWorkspaceNext(nextPageLink: string, options: msRest.RequestOptionsBase, callback: msRest.ServiceCallback<Models.ExperimentListResult>): void; listByWorkspaceNext(nextPageLink: string, options?: msRest.RequestOptionsBase | msRest.ServiceCallback<Models.ExperimentListResult>, callback?: msRest.ServiceCallback<Models.ExperimentListResult>): Promise<Models.ExperimentsListByWorkspaceNextResponse> { return this.client.sendOperationRequest( { nextPageLink, options }, listByWorkspaceNextOperationSpec, callback) as Promise<Models.ExperimentsListByWorkspaceNextResponse>; } } // Operation Specifications const serializer = new msRest.Serializer(Mappers); const listByWorkspaceOperationSpec: msRest.OperationSpec = { httpMethod: "GET", path: "subscriptions/{subscriptionId}/resourceGroups/{resourceGroupName}/providers/Microsoft.BatchAI/workspaces/{workspaceName}/experiments", urlParameters: [ Parameters.resourceGroupName, Parameters.workspaceName, Parameters.subscriptionId ], queryParameters: [ Parameters.apiVersion, Parameters.maxResults2 ], headerParameters: [ Parameters.acceptLanguage ], responses: { 200: { bodyMapper: Mappers.ExperimentListResult }, default: { bodyMapper: Mappers.CloudError } }, serializer }; const getOperationSpec: msRest.OperationSpec = { httpMethod: "GET", path: "subscriptions/{subscriptionId}/resourceGroups/{resourceGroupName}/providers/Microsoft.BatchAI/workspaces/{workspaceName}/experiments/{experimentName}", urlParameters: [ Parameters.resourceGroupName, Parameters.workspaceName, Parameters.experimentName, Parameters.subscriptionId ], queryParameters: [ Parameters.apiVersion ], headerParameters: [ Parameters.acceptLanguage ], responses: { 200: { bodyMapper: Mappers.Experiment }, default: { bodyMapper: Mappers.CloudError } }, serializer }; const beginCreateOperationSpec: msRest.OperationSpec = { httpMethod: "PUT", path: "subscriptions/{subscriptionId}/resourceGroups/{resourceGroupName}/providers/Microsoft.BatchAI/workspaces/{workspaceName}/experiments/{experimentName}", urlParameters: [ Parameters.resourceGroupName, Parameters.workspaceName, Parameters.experimentName, Parameters.subscriptionId ], queryParameters: [ Parameters.apiVersion ], headerParameters: [ Parameters.acceptLanguage ], responses: { 200: { bodyMapper: Mappers.Experiment }, 202: {}, default: { bodyMapper: Mappers.CloudError } }, serializer }; const beginDeleteMethodOperationSpec: msRest.OperationSpec = { httpMethod: "DELETE", path: "subscriptions/{subscriptionId}/resourceGroups/{resourceGroupName}/providers/Microsoft.BatchAI/workspaces/{workspaceName}/experiments/{experimentName}", urlParameters: [ Parameters.resourceGroupName, Parameters.workspaceName, Parameters.experimentName, Parameters.subscriptionId ], queryParameters: [ Parameters.apiVersion ], headerParameters: [ Parameters.acceptLanguage ], responses: { 200: {}, 202: {}, 204: {}, default: { bodyMapper: Mappers.CloudError } }, serializer }; const listByWorkspaceNextOperationSpec: msRest.OperationSpec = { httpMethod: "GET", baseUrl: "https://management.azure.com", path: "{nextLink}", urlParameters: [ Parameters.nextPageLink ], headerParameters: [ Parameters.acceptLanguage ], responses: { 200: { bodyMapper: Mappers.ExperimentListResult }, default: { bodyMapper: Mappers.CloudError } }, serializer };
the_stack
import { CardObject } from '../types'; let shortestPermittedCardLength; interface CardType { __NO_BRAND?: string; cards?: CardObject[]; } const CardType: CardType = {}; CardType.__NO_BRAND = 'noBrand'; CardType.cards = []; CardType.cards.push({ cardType: 'mc', startingRules: [51, 52, 53, 54, 55, 22, 23, 24, 25, 26, 27], permittedLengths: [16], pattern: /^(5[1-5][0-9]{0,14}|2[2-7][0-9]{0,14})$/, securityCode: 'CVC' }); CardType.cards.push({ cardType: 'visadankort', startingRules: [4571], permittedLengths: [16], pattern: /^(4571)[0-9]{0,12}$/ }); CardType.cards.push({ cardType: 'visa', startingRules: [4], permittedLengths: [13, 16, 19], pattern: /^4[0-9]{0,18}$/, securityCode: 'CVV' }); CardType.cards.push({ cardType: 'amex', startingRules: [34, 37], permittedLengths: [15], pattern: /^3[47][0-9]{0,13}$/, securityCode: 'CID' }); CardType.cards.push({ cardType: 'diners', startingRules: [36], permittedLengths: [14], pattern: /^(36)[0-9]{0,12}$/ }); CardType.cards.push({ cardType: 'maestrouk', startingRules: [6759], permittedLengths: [16, 18, 19], pattern: /^(6759)[0-9]{0,15}$/ }); CardType.cards.push({ cardType: 'solo', startingRules: [6767], permittedLengths: [16, 18, 19], pattern: /^(6767)[0-9]{0,15}$/ }); CardType.cards.push({ cardType: 'laser', startingRules: [6304, 6706, 677117, 677120], permittedLengths: [16, 17, 18, 19], pattern: /^(6304|6706|6709|6771)[0-9]{0,15}$/, cvcPolicy: 'optional' }); CardType.cards.push({ cardType: 'discover', startingRules: [6011, 644, 645, 646, 647, 648, 649, 65], permittedLengths: [16], pattern: /^(6011[0-9]{0,12}|(644|645|646|647|648|649)[0-9]{0,13}|65[0-9]{0,14})$/ }); CardType.cards.push({ cardType: 'jcb', startingRules: [3528, 3529, 353, 354, 355, 356, 357, 358], permittedLengths: [16, 19], pattern: /^(352[8,9]{1}[0-9]{0,15}|35[4-8]{1}[0-9]{0,16})$/, securityCode: 'CAV' }); CardType.cards.push({ cardType: 'bcmc', startingRules: [6703, 479658, 606005], permittedLengths: [16, 17, 18, 19], pattern: /^((6703)[0-9]{0,15}|(479658|606005)[0-9]{0,13})$/, cvcPolicy: 'hidden' }); CardType.cards.push({ cardType: 'bijcard', startingRules: [5100081], permittedLengths: [16], pattern: /^(5100081)[0-9]{0,9}$/ }); CardType.cards.push({ cardType: 'dankort', startingRules: [5019], permittedLengths: [16], pattern: /^(5019)[0-9]{0,12}$/ }); CardType.cards.push({ cardType: 'hipercard', startingRules: [606282], permittedLengths: [16], pattern: /^(606282)[0-9]{0,10}$/ }); // Moved above maestro (from position below uatp) to stop maestro being recognised over cup CardType.cards.push({ cardType: 'cup', startingRules: [62, 81], permittedLengths: [14, 15, 16, 17, 18, 19], pattern: /^(62|81)[0-9]{0,17}$/ }); // orig & android v1 + modified to include our test cards (81...) CardType.cards.push({ cardType: 'maestro', startingRules: [50, 56, 57, 58, 6], permittedLengths: [16, 17, 18, 19], pattern: /^(5[0|6-8][0-9]{0,17}|6[0-9]{0,18})$/, cvcPolicy: 'optional' }); CardType.cards.push({ cardType: 'elo', // prettier-ignore startingRules: [506699, 50670, 50671, 50672, 50673, 50674, 50675, 50676, 506770, 506771, 506772, 506773, 506774, 506775, 506776, 506777, 506778, 401178, 438935, 451416, 457631, 457632, 504175, 627780, 636297, 636368], // eslint-disable-line max-len permittedLengths: [16], pattern: /^((((506699)|(506770)|(506771)|(506772)|(506773)|(506774)|(506775)|(506776)|(506777)|(506778)|(401178)|(438935)|(451416)|(457631)|(457632)|(504175)|(627780)|(636368)|(636297))[0-9]{0,10})|((50676)|(50675)|(50674)|(50673)|(50672)|(50671)|(50670))[0-9]{0,11})$/ // eslint-disable-line max-len }); CardType.cards.push({ cardType: 'uatp', startingRules: [1], permittedLengths: [15], pattern: /^1[0-9]{0,14}$/, cvcPolicy: 'optional' }); CardType.cards.push({ cardType: 'cartebancaire', startingRules: [4, 5, 6], permittedLengths: [16], pattern: /^[4-6][0-9]{0,15}$/ }); CardType.cards.push({ cardType: 'visaalphabankbonus', startingRules: [450903], permittedLengths: [16], pattern: /^(450903)[0-9]{0,10}$/ }); CardType.cards.push({ cardType: 'mcalphabankbonus', startingRules: [510099], permittedLengths: [16], pattern: /^(510099)[0-9]{0,10}$/ }); CardType.cards.push({ cardType: 'hiper', startingRules: [637095, 637568, 637599, 637609, 637612], permittedLengths: [16], pattern: /^(637095|637568|637599|637609|637612)[0-9]{0,10}$/ }); CardType.cards.push({ cardType: 'oasis', startingRules: [982616], permittedLengths: [16], pattern: /^(982616)[0-9]{0,10}$/, cvcPolicy: 'optional' }); CardType.cards.push({ cardType: 'karenmillen', startingRules: [98261465], permittedLengths: [16], pattern: /^(98261465)[0-9]{0,8}$/, cvcPolicy: 'optional' }); CardType.cards.push({ cardType: 'warehouse', startingRules: [982633], permittedLengths: [16], pattern: /^(982633)[0-9]{0,10}$/, cvcPolicy: 'optional' }); CardType.cards.push({ cardType: 'mir', startingRules: [220], permittedLengths: [16, 17, 18, 19], pattern: /^(220)[0-9]{0,16}$/ }); CardType.cards.push({ cardType: 'codensa', startingRules: [590712], permittedLengths: [16], pattern: /^(590712)[0-9]{0,10}$/ }); CardType.cards.push({ cardType: 'naranja', startingRules: [377798, 377799, 402917, 402918, 527571, 527572, 589562], permittedLengths: [16, 17, 18, 19], pattern: /^(37|40|5[28])([279])\d*$/ }); // TODO: 589657 clashes with naranja, rest ok CardType.cards.push({ cardType: 'cabal', startingRules: [589657, 600691, 603522, 6042, 6043, 636908], permittedLengths: [16, 17, 18, 19], pattern: /^(58|6[03])([03469])\d*$/ }); CardType.cards.push({ cardType: 'shopping', startingRules: [2799, 589407, 603488], permittedLengths: [16, 17, 18, 19], pattern: /^(27|58|60)([39])\d*$/ }); CardType.cards.push({ cardType: 'argencard', startingRules: [501], permittedLengths: [16, 17, 18, 19], pattern: /^(50)(1)\d*$/ }); // NOTE: starting rule changed, from 501105, to not clash with dankort. Plus it now matches its regEx! CardType.cards.push({ cardType: 'troy', startingRules: [9792], permittedLengths: [16], pattern: /^(97)(9)\d*$/ }); // TODO: clashes with cabal CardType.cards.push({ cardType: 'forbrugsforeningen', startingRules: [600722], permittedLengths: [16], pattern: /^(60)(0)\d*$/ }); CardType.cards.push({ cardType: 'vpay', startingRules: [401, 408, 413, 434, 435, 437, 439, 441, 442, 443, 444, 446, 447, 455, 458, 460, 461, 463, 466, 471, 479, 482, 483, 487], permittedLengths: [13, 14, 15, 16, 17, 18, 19], pattern: /^(40[1,8]|413|43[4,5]|44[1,2,3,4,6,7]|45[5,8]|46[0,1,3,6]|47[1,9]|48[2,3,7])[0-9]{0,16}$/ // ^(4[0-1|3-8][0-9]{1,17})$ }); CardType.cards.push({ cardType: 'rupay', startingRules: [508528], permittedLengths: [16], pattern: /^(100003|508(2|[5-9])|60(69|[7-8])|652(1[5-9]|[2-5][0-9]|8[5-9])|65300[3-4]|8172([0-1]|[3-5]|7|9)|817(3[3-8]|40[6-9]|410)|35380([0-2]|[5-6]|9))[0-9]{0,12}$/ // eslint-disable-line max-len }); const detectCard = (pCardNumber, pAvailableCards?) => { let matchedCards; let i; let len; if (pAvailableCards) { // Filter CardType.cards down to those that are found in pAvailableCards matchedCards = CardType.cards .filter(card => pAvailableCards.includes(card.cardType)) // Further filter them to those with a regEx pattern that matches pCardNumber .filter(card => Object.prototype.hasOwnProperty.call(card, 'pattern') && pCardNumber.match(card.pattern)); // If we have matched cards: if there's only one - return it; else return the one with the longest startingRule if (matchedCards.length) { if (matchedCards.length === 1) { return matchedCards[0]; } // Find longest rule for each matched card & store it as a property on the card for (i = 0, len = matchedCards.length; i < len; i += 1) { if (!matchedCards[i].longestRule) { const longestRule = matchedCards[i].startingRules.reduce((a, b) => (a > b ? a : b)); // What we actually store is how many chars are in the rule matchedCards[i].longestRule = String(longestRule).length; } } // Based on each matched cards longest rule - find the card with the longest one! return matchedCards.reduce((a, b) => (a.longestRule >= b.longestRule ? a : b)); } return { cardType: CardType.__NO_BRAND }; } return { cardType: CardType.__NO_BRAND }; }; const detectCardLength = (pCard, pUnformattedVal) => { let maxLength; let shortenedNewValue; let lengthDiff = 0; let reachedValidLength = false; let unformattedVal = pUnformattedVal; // Find the longest of the permitted card number lengths for this card brand const maxPermittedLength = pCard.cardType !== CardType.__NO_BRAND ? pCard.permittedLengths[pCard.permittedLengths.length - 1] : 0; // If the input value is longer than it's max permitted length then shorten it to that length if (maxPermittedLength && unformattedVal > maxPermittedLength) { lengthDiff = unformattedVal.length - maxPermittedLength; if (lengthDiff > 0) { unformattedVal = unformattedVal.substring(0, unformattedVal.length - lengthDiff); shortenedNewValue = unformattedVal; } } // If cardNumber has reached one of the cardBrand's 'permitted lengths' - mark it as 'valid' pCard.permittedLengths.forEach(pItem => { if (unformattedVal.length === pItem) { reachedValidLength = true; } }); // If cardNumber is as long as the cardBrand's maximum permitted length then set the maxLength var if (unformattedVal.length === maxPermittedLength) { // Set maxlength to max + the right amount of spaces (one for every 4 digits, but not on the last block) const div = Math.floor(unformattedVal.length / 4); const mod = unformattedVal.length % 4; const numSpaces = mod > 0 ? div : div - 1; maxLength = maxPermittedLength + numSpaces; if (pCard.cardType.toLowerCase() === 'amex') { maxLength = maxPermittedLength + 2; // = 17 = 15 digits with space after 4th & 10th } } return { shortenedNewValue, maxLength, reachedValidLength }; }; const getShortestPermittedCardLength = () => { if (!shortestPermittedCardLength) { let permittedLengthsArray = []; CardType.cards.forEach(pItem => { permittedLengthsArray = permittedLengthsArray.concat(pItem.permittedLengths); }); shortestPermittedCardLength = Math.min.apply(null, permittedLengthsArray); } return shortestPermittedCardLength; }; const getCardByBrand = pBrand => { const cardType = CardType.cards.filter(card => card.cardType === pBrand); return cardType[0]; }; const isGenericCardType = (type = 'card') => type === 'card' || type === 'scheme'; export default { detectCard, detectCardLength, getShortestPermittedCardLength, getCardByBrand, isGenericCardType, __NO_BRAND: CardType.__NO_BRAND, allCards: CardType.cards };
the_stack
* Provide asynchronous network communications to a TAXII 2.0 server. * */ export class TaxiiConnect { baseURL: string; user: string; password: string; hash: string; timeout: number; version: string; getConfig: any; postConfig: any; getStixConfig: any; /** * provide network communication to a Taxii 2.0 server. * @param {String} url - the base url of the Taxii2 server, for example https://example.com/ * @param {String} user - the user name required for authentication. * @param {String} password - the user password required for authentication. * @param {Integer} timeout - the connection timeout in millisec */ constructor(url, user, password, timeout) { this.baseURL = TaxiiConnect.withoutLastSlash(url); this.user = user; this.password = password; this.hash = btoa(this.user + ":" + this.password); this.timeout = timeout ? timeout : 10000; // default timeout this.version = '2.0'; // default headers configurations this.getConfig = { 'method': 'get', 'headers': new Headers({ 'Accept': 'application/vnd.oasis.taxii+json', 'version': this.version, 'Authorization': 'Basic ' + this.hash }) }; this.postConfig = { 'method': 'post', 'headers': new Headers({ 'Accept': 'application/vnd.oasis.taxii+json', 'Content-Type': 'application/vnd.oasis.stix+json', 'version': this.version, 'Authorization': 'Basic ' + this.hash }) }; this.getStixConfig = { 'method': 'get', 'headers': new Headers({ 'Accept': 'application/vnd.oasis.stix+json', 'version': this.version, 'Authorization': 'Basic ' + this.hash }) }; } // original code from: https://github.com/jkomyno/fetch-timeout timeoutPromise(promise, timeout, error) { return new Promise((resolve, reject) => { setTimeout(() => reject(error), timeout); promise.then(resolve, reject); }); } // original code from: https://github.com/jkomyno/fetch-timeout fetchTimeout(url, options, timeout, error) { error = error || 'Timeout error'; options = options || {}; timeout = timeout || 10000; return this.timeoutPromise(fetch(url, options), timeout, error); } /** * send an async request (GET or POST) to the taxii2 server. * * @param {String} path - the full path to connect to. * @param {Object} config - the request configuration, see getConfig and postConfig for examples * @param {Object} filter - the filter object describing the filtering requested, this is added to the path as a query string * @returns {Promise} the server response in json. */ async asyncFetch(path, config, filter?) { //CHANGED let fullPath = (filter === undefined) ? path : path + "?" + TaxiiConnect.asQueryString(filter); return await (await ( this.fetchTimeout(fullPath, config, this.timeout, 'connection timeout') .then((res: Response) => res.json()) .catch(err => { throw new Error("fetch error: " + err); } ) )); } /** * send a GET async request to the taxii2 server. * * The server response is assigned to the cache attribute of the options object, and * the options flag attribute is set to true if a server request was performed. * Otherwise if the options.flag is initially true, the cached response (options.cache) is returned and * no server request is performed. * To force a server request used invalidate(), for example: server.invalidate() * * @param {String} path - the path to connect to. * @param {Object} options - an option object of the form: { "cache": {}, "flag": false } * @param {Object} filter - the filter object describing the filtering requested, this is added to the path as a query string * @param {Object} config - the request configuration * @returns {Promise} the server response object */ async fetchThis(path, options, filter?, config?) { //CHANGED let conf = config === undefined ? this.getConfig : config; if (!options.flag) { options.cache = await (this.asyncFetch(path, conf, filter)); options.flag = true; } return options.cache; } /** * return the url without the last slash. * @param {String} url - the URL string to process. * @returns {String} the url without the last slash. */ static withoutLastSlash(url) { return (url.substr(-1) === '/') ? url.substr(0, url.length - 1) : url; } /** * return the url with a terminating slash. * @param {String} url - the URL string to process. * @returns {String} the url with a terminating slash. */ static withLastSlash(url) { return (url.substr(-1) === '/') ? url : url + "/"; } /** * convert a filter object into a query string. * @param {Object} filter - the filter object to process. * @returns {String} the query string corresponding to the filter object. */ static asQueryString(filter) { return Object.keys(filter).map(k => { let value = (k === "added_after") ? k : "match[" + k + "]"; return encodeURIComponent(value) + '=' + encodeURIComponent(filter[k]); }).join('&'); } } /** * Server encapsulates a discovery and api roots endpoints. */ export class Server { path: string; conn: TaxiiConnect; disOptions: any; apiOptions: any; /** * A TAXII Server endpoint representation. * @param {String} path - the path to the server discovery endpoint, for example "/taxii/" * @param {TaxiiConnect} conn - a TaxiiConnection instance providing network communications. */ constructor(path, conn) { this.path = TaxiiConnect.withLastSlash(path); this.conn = conn; // cache represents the cached results and flag determines if it needs a re-fetch this.disOptions = {"cache": {}, "flag": false}; this.apiOptions = {"cache": [], "flag": false}; } /** * determine if the obj is empty, {} * @param {Object} obj - the object to test * @returns {Boolean} - true if empty else false */ static isEmpty(obj) { return Object.keys(obj).length === 0 && obj.constructor === Object; } /** * reset the internal options flags so that the next method call of this class will * send a request to the server rather than retreive the results from cache. */ invalidate() { this.disOptions.flag = false; this.apiOptions.flag = false; } /** * retrieve the information about a TAXII Server and the list of API Roots. * @returns {Promise} the server discovery information object. */ async discovery() { return this.conn.fetchThis(this.conn.baseURL + this.path, this.disOptions); } /** * retrieve the api roots information objects. * Note: unreachable roots are not part of the results. * * API Roots are logical groupings of TAXII Channels, Collections, and related functionality. * Each API Root contains a set of Endpoints that a TAXII Client contacts in order to interact with the TAXII Server. * This returns the api roots information objects from the string urls. * @returns {Promise} the Array of api roots information objects */ async api_roots() { return this.discovery().then(discovery => this._getApiRoots(discovery)); } /** * retrieve a map of key=the api root url and value=the api root object. * * API Roots are logical groupings of TAXII Channels, Collections, and related functionality. * Each API Root contains a set of Endpoints that a TAXII Client contacts in order to interact with the TAXII Server. * @returns {Promise} a Map of key=the url and value=the api root object. */ async api_rootsMap() { var apiRootMap = new Map(); await this.discovery().then(discovery => this._getApiRoots(discovery, apiRootMap)); return apiRootMap; } /** * private function to retrieve the api roots * @param {discovery} discovery - a discovery object * @param {Map} apiRootMap - a map of key=url, value=api root object * @returns {Promise} the Array of api roots information objects */ async _getApiRoots(discovery, apiRootMap?) { //CHANGED if (!this.apiOptions.flag) { // clear the cache this.apiOptions.cache = []; // fetch all the api_roots in parallel await Promise.all(discovery.api_roots.map(async url => { let apiroot = await this.conn.asyncFetch(url, this.conn.getConfig); // add to the map if (apiRootMap !== undefined) { apiRootMap.set(url, apiroot); } // add to the array of results this.apiOptions.cache.push(apiroot); })); // remove the undefined and empty elements, that is those we could not connect to. this.apiOptions.cache = this.apiOptions.cache.filter(element => (element !== undefined && !Server.isEmpty(element))); this.apiOptions.flag = true; } return this.apiOptions.cache; } } /** * Collections resource endpoint. * A TAXII Collections is an interface to a logical repository of CTI objects * provided by a TAXII Server and is used by TAXII Clients to send information * to the TAXII Server or request information from the TAXII Server. * A TAXII Server can host multiple Collections per API Root, and Collections * are used to exchange information in a request–response manner. */ export class Collections { api_root_path: string; conn: TaxiiConnect; options: any; collectionsFlag: boolean; // hash: string; /** * A TAXII Collections for a specific api root path. * The collections resource is a simple wrapper around a list of collection resources. * @param {String} api_root_path - the full path to the desired api root endpoint * @param {TaxiiConnection} conn a TaxiiConnection class instance. */ constructor(api_root_path, conn) { this.api_root_path = TaxiiConnect.withLastSlash(api_root_path); this.conn = conn; // cache represents the cached results and flag determines if it needs a re-fetch this.options = {"cache": {}, "flag": false}; } /** * reset the internal options flags so that the next method call of this class will * send a request to the server rather than retreive the results from cache. */ invalidate() { this.options.flag = false; } /** * provide information about a specific Collection hosted under this API Root. * * @param {Integer} index - the index of the desired collection object. * @returns {Object} a specific collection object. */ async get(index) { if (Number.isInteger(index) && index >= 0) { // return a specific collection info if (!this.collectionsFlag) { return this.collections().then(cols => { if (index < this.options.cache.collections.length) { return this.options.cache.collections[index]; } else { console.log("----> in Collections get(index) invalid index value: " + index); } }); } else { if (index < this.options.cache.collections.length) { return this.options.cache.collections[index]; } else { console.log("----> in Collections get(index) invalid index value: " + index); } } } else { console.log("----> in Collections get(index) invalid index value: " + index); } } /** * provide information about the Collections hosted under this API Root. * * @param {String} range - a pagination range string, for example "0-10" * @returns {Array} an array of collection objects */ async collections(range?) { //CHANGED var theConfig = this.conn.getConfig; if (range !== undefined) { theConfig = { 'method': 'get', 'headers': new Headers({ 'Accept': 'application/vnd.oasis.taxii+json', 'version': this.conn.version, 'Authorization': 'Basic ' + this.conn.hash, //CHANGED 'Range': 'items=' + range }) }; } // return a list of collection info await this.conn.fetchThis(this.api_root_path + "collections/", this.options, "", theConfig); return this.options.cache.collections; } } /** * A Collection resource endpoint. */ export class Collection { collectionInfo: any; api_root_path: string; conn: TaxiiConnect; path: string; colOptions: any; objsOptions: any; objOptions: any; manOptions: any; /** * Collection resource endpoint. * @param {CollectionInfoObject} collectionInfo - the collection object of this endpoint. * @param {String} api_root_path - the full path to the desired api root endpoint. * @param {TaxiiConnection} conn - a TaxiiConnection class instance. */ constructor(collectionInfo, api_root_path, conn) { this.collectionInfo = collectionInfo; this.api_root_path = TaxiiConnect.withLastSlash(api_root_path); this.conn = conn; // construct the path this.path = this.api_root_path + "collections/" + collectionInfo.id + "/"; // cache represents the cached results and flag determines if it needs a re-fetch this.colOptions = {"cache": {}, "flag": false}; this.objsOptions = {"cache": {}, "flag": false}; this.objOptions = {"cache": {}, "flag": false}; this.manOptions = {"cache": {}, "flag": false}; } /** * reset the internal options flags so that the next method call of this class will * send a request to the server rather than retreive the results from cache. */ invalidate() { this.colOptions.flag = false; this.objsOptions.flag = false; this.objOptions.flag = false; this.manOptions.flag = false; } /** * check that the collection allows reading, if true then return the function passed in * else log an error * @param {Function} func - the function to return if the collection allows reading it * @returns {Function} the function if this collection allow reading else undefined */ ifCanRead(func) { if (this.collectionInfo.can_read) { return func; } else { console.log("this collection does not allow reading: \n" + JSON.stringify(this.collectionInfo)); } } /** * check that the collection allows writing, if true then return the function passed in else log an error * @param {Function} func - the function to return if the collection allows writing it * @returns {Function} the function if this collection allow writing else undefined */ ifCanWrite(func) { if (this.collectionInfo.can_write) { return func; } else { console.log("this collection does not allow writing: \n" + JSON.stringify(this.collectionInfo)); } } /** * retrieve this Collection object. * @returns {Promise} the Collection object */ async get() { return this.ifCanRead(this.conn.fetchThis(this.path, this.colOptions)); } /** * retrieve a STIX-2 bundle from this Collection. * * @param {Object} filter - the filter object describing the filtering requested, this is added to the path as a query string. * For example: {"added_after": "2016-02-01T00:00:01.000Z"} * {"type": ["incident","ttp","actor"]} * @param {String} range - a pagination range string, for example "0-10" * @returns {Promise} the Bundle with the STIX-2 objects of this collection */ async getObjects(filter, range) { var theConfig = this.conn.getStixConfig; if (range !== undefined) { theConfig = { 'method': 'get', 'headers': new Headers({ 'Accept': 'application/vnd.oasis.stix+json', 'version': this.conn.version, 'Authorization': 'Basic ' + this.conn.hash, //CHANGED 'Range': 'items=' + range }) }; } return this.ifCanRead(this.conn.fetchThis(this.path + "objects/", this.objsOptions, filter, theConfig)); } /** * retrieve a specific STIX-2 object from this collection objects bundle. * * @param {String} obj_id - the STIX-2 object id to retrieve * @param {Object} filter - the filter object describing the filtering requested, this is added to the path as a query string. * For example: {"version": "2016-01-01T01:01:01.000Z"} */ async getObject(obj_id, filter) { return await (await (this.ifCanRead(this.conn.fetchThis(this.path + "objects/" + obj_id + "/", this.objOptions, filter, this.conn.getStixConfig) .then(bundle => bundle.objects.find(obj => obj.id === obj_id) )))); } /** * add a STIX-2 bundle object to this Collection objects. * @param {Bundle} bundle - the STIX-2 bundle object to add * @return {Status} a status object */ async addObject(bundle) { return this.ifCanWrite(this.conn.asyncFetch(this.path + "objects/", this.conn.postConfig)); } /** * retrieve all manifests about objects from this Collection. * Manifests are metadata about the objects. * * @param {Object} filter - the filter object describing the filtering requested, this is added to the path as a query string. * @param {String} range - a pagination range string, for example "0-10" * @return {Array} an array of manifest entries object */ async getManifests(filter, range?) { var theConfig = this.conn.getConfig; if (range !== undefined) { theConfig = { 'method': 'get', 'headers': new Headers({ 'Accept': 'application/vnd.oasis.taxii+json', 'version': this.conn.version, 'Authorization': 'Basic ' + this.conn.hash, //CHANGED 'Range': 'items=' + range }) }; } this.ifCanRead(await this.conn.fetchThis(this.path + "manifest/", this.manOptions, filter, theConfig)); return this.manOptions.cache.objects; } /** * retrieve the manifest about a specific object (obj_id) from this Collection. * Manifests are metadata about the objects. * * @param {String} obj_id - the STIX-2 object id of the manifest to retrieve. * @param {Object} filter - the filter object describing the filtering requested, this is added to the path as a query string. * @return {Object} a manifest entry of the desired STIX-2 object. */ async getManifest(obj_id, filter) { return await (this.getManifests(filter).then(objects => objects.find(obj => obj.id === obj_id))); } } /** * This Endpoint provides information about the status of a previous request. * In TAXII 2.0, the only request that can be monitored is one to add objects to a Collection. */ export class Status { api_root_path: string; status_id: string; conn: TaxiiConnect; path: string; /** * provide information about the status of a previous request. * @param {String} api_root_path - the full path to the desired api root * @param {String} status_id - the identifier of the status message being requested, for STIX objects, their id. * @param {TaxiiConnection} conn - a TaxiiConnection class instance. */ constructor(api_root_path, status_id, conn) { this.api_root_path = TaxiiConnect.withLastSlash(api_root_path); this.status_id = status_id; this.conn = conn; this.path = this.api_root_path + "status/" + status_id + "/"; } /** * retrieve the Status information about a request to add objects to a Collection. * @return {Promise} the status object */ async get() { return this.conn.asyncFetch(this.path, this.conn.getConfig); } }
the_stack
import * as xml2js from 'xml2js'; import { AbstractTest, AbstractTestEvent, SharedWithTest } from '../AbstractTest'; import { TestEventBuilder } from '../TestEventBuilder'; import { Suite } from '../Suite'; import { AbstractRunnable } from '../AbstractRunnable'; interface XmlObject { [prop: string]: any; //eslint-disable-line } interface Frame { name: string; filename: string; line: number; } export class DOCSection implements Frame { public constructor(name: string, filename: string, line: number) { this.name = name; // some debug adapter on ubuntu starts debug session in shell, // this prevents the SECTION("`pwd`") to be executed this.name = this.name.replace(/`/g, '\\`'); this.filename = filename; this.line = line; } public readonly name: string; public readonly filename: string; public readonly line: number; public readonly children: DOCSection[] = []; public failed = false; } export class DOCTest extends AbstractTest { public constructor( shared: SharedWithTest, runnable: AbstractRunnable, parent: Suite, testNameAsId: string, skipped: boolean, file: string | undefined, line: number | undefined, tags: string[], description: string | undefined, ) { super( shared, runnable, parent, testNameAsId, testNameAsId.startsWith(' Scenario:') ? '⒮' + testNameAsId.substr(11) : testNameAsId, file, line, skipped, undefined, tags, description, undefined, undefined, ); this._isSecnario = testNameAsId.startsWith(' Scenario:'); } public update(file: string | undefined, line: number | undefined, tags: string[], skipped: boolean): boolean { return this._updateBase( this._label, file, line, skipped, tags, this._testDescription, this._typeParam, this._valueParam, this._staticEvent, ); } public compare(testNameAsId: string): boolean { return this.testNameAsId === testNameAsId; } private _sections: undefined | DOCSection[]; private _isSecnario: boolean; public get sections(): undefined | DOCSection[] { return this._sections; } public getEscapedTestName(): string { /* ',' has special meaning */ return this.testNameAsId.replace(/,/g, '?'); } public parseAndProcessTestCase( testRunId: string, output: string, rngSeed: number | undefined, timeout: number | null, stderr: string | undefined, ): AbstractTestEvent { if (timeout !== null) { const ev = this.getTimeoutEvent(testRunId, timeout); this.lastRunEvent = ev; return ev; } let res: XmlObject = {}; new xml2js.Parser({ explicitArray: true }).parseString(output, (err: Error, result: XmlObject) => { if (err) { throw err; } else { res = result; } }); const testEventBuilder = new TestEventBuilder(this, testRunId); if (rngSeed) testEventBuilder.appendTooltip(`🔀 Randomness seeded to: ${rngSeed.toString()}`); this._processXmlTagTestCaseInner(res.TestCase, testEventBuilder); if (stderr) { testEventBuilder.appendMessage('stderr arrived during running this test', null); testEventBuilder.appendMessage('⬇ std::cerr:', null); testEventBuilder.appendMessage(stderr, 1); testEventBuilder.appendMessage('⬆ std::cerr', null); } const testEvent = testEventBuilder.build(); return testEvent; } private _processXmlTagTestCaseInner(testCase: XmlObject, testEventBuilder: TestEventBuilder): void { const durationSec = Number(testCase.OverallResultsAsserts[0].$.duration) || undefined; if (durationSec === undefined) this._shared.log.errorS('doctest: duration is NaN', testCase.OverallResultsAsserts[0].$.duration); else testEventBuilder.setDurationMilisec(durationSec * 1000); testEventBuilder.appendMessage(testCase._, 0); const title: DOCSection = new DOCSection(testCase.$.name, testCase.$.filename, testCase.$.line); const mayFail = testCase.$.may_fail === 'true'; const shouldFail = testCase.$.should_fail === 'true'; const failures = parseInt(testCase.OverallResultsAsserts[0].$.failures) || 0; const expectedFailures = parseInt(testCase.OverallResultsAsserts[0].$.expected_failures) || 0; const hasException = testCase.Exception !== undefined; const timeoutSec = Number(testCase.$.timeout) || undefined; const hasTimedOut = timeoutSec !== undefined && durationSec !== undefined ? durationSec > timeoutSec : false; // The logic is coming from the console output of ./doctest1.exe if (shouldFail) { if (failures > 0 || hasException || hasTimedOut) testEventBuilder.passed(); else testEventBuilder.failed(); } else if (mayFail) { testEventBuilder.passed(); } else { if (expectedFailures !== failures || hasException || hasTimedOut) testEventBuilder.failed(); else testEventBuilder.passed(); } this._processTags(testCase, title, [], testEventBuilder); this._processXmlTagSubcase(testCase, title, [], testEventBuilder, title); this._sections = title.children; if (this._sections.length) { let failedBranch = 0; let succBranch = 0; const traverse = (section: DOCSection): void => { if (section.children.length === 0) { section.failed ? ++failedBranch : ++succBranch; } else { for (let i = 0; i < section.children.length; ++i) { traverse(section.children[i]); } } }; this._sections.forEach(section => traverse(section)); const branchMsg = (failedBranch ? '✘' + failedBranch + '|' : '') + '✔︎' + succBranch; testEventBuilder.appendDescription(`ᛦ${branchMsg}ᛦ`); testEventBuilder.appendTooltip(`ᛦ ${branchMsg} branches`); } } private static readonly _expectedPropertyNames = new Set([ '_', '$', 'SubCase', 'OverallResultsAsserts', 'Message', 'Expression', 'Exception', ]); private _processTags(xml: XmlObject, title: Frame, stack: DOCSection[], testEventBuilder: TestEventBuilder): void { { Object.getOwnPropertyNames(xml).forEach(n => { if (!DOCTest._expectedPropertyNames.has(n)) { this._shared.log.error('unexpected doctest tag: ' + n); testEventBuilder.appendMessage('unexpected doctest tag:' + n, 0); testEventBuilder.errored(); } }); } if (xml._) { testEventBuilder.appendMessage('⬇ std::cout:', 1); testEventBuilder.appendMessage(xml._.trim(), 2); testEventBuilder.appendMessage('⬆ std::cout', 1); } try { if (xml.Message) { for (let j = 0; j < xml.Message.length; ++j) { const msg = xml.Message[j]; testEventBuilder.appendMessage(msg.$.type, 0); msg.Text.forEach((m: string) => testEventBuilder.appendMessage(m, 1)); testEventBuilder.appendDecorator( msg.$.filename, Number(msg.$.line) - 1, msg.Text.map((x: string) => x.trim()).join(' | '), ); } } } catch (e) { this._shared.log.exceptionS(e); } try { if (xml.Exception) { for (let j = 0; j < xml.Exception.length; ++j) { const e = xml.Exception[j]; testEventBuilder.appendMessage('Exception was thrown: ' + e._.trim(), 0); } } } catch (e) { this._shared.log.exceptionS(e); } try { if (xml.Expression) { for (let j = 0; j < xml.Expression.length; ++j) { const expr = xml.Expression[j]; const file = expr.$.filename; const line = Number(expr.$.line); const location = `(at ${file}:${line})`; testEventBuilder.appendMessage(`Expression failed ${location}:`, 1); testEventBuilder.appendMessage('❕Original: ' + expr.Original.map((x: string) => x.trim()).join('\n'), 2); try { for (let j = 0; expr.Expanded && j < expr.Expanded.length; ++j) { testEventBuilder.appendMessage( '❗️Expanded: ' + expr.Expanded.map((x: string) => x.trim()).join('\n'), 2, ); testEventBuilder.appendDecorator(file, line - 1, expr.Expanded.map((x: string) => x.trim()).join(' | ')); } } catch (e) { this._shared.log.exceptionS(e); } try { for (let j = 0; expr.Exception && j < expr.Exception.length; ++j) { testEventBuilder.appendMessage( ' ❗️Exception: ' + expr.Exception.map((x: string) => x.trim()).join('\n'), 2, ); testEventBuilder.appendDecorator(file, line, expr.Exception.map((x: string) => x.trim()).join(' | ')); } } catch (e) { this._shared.log.exceptionS(e); } try { for (let j = 0; expr.ExpectedException && j < expr.ExpectedException.length; ++j) { testEventBuilder.appendMessage( '❗️ExpectedException: ' + expr.ExpectedException.map((x: string) => x.trim()).join('\n'), 2, ); testEventBuilder.appendDecorator( file, line, expr.ExpectedException.map((x: string) => x.trim()).join(' | '), ); } } catch (e) { this._shared.log.exceptionS(e); } try { for (let j = 0; expr.ExpectedExceptionString && j < expr.ExpectedExceptionString.length; ++j) { testEventBuilder.appendMessage( '❗️ExpectedExceptionString ' + expr.ExpectedExceptionString[j]._.trim(), 2, ); testEventBuilder.appendDecorator( file, line, expr.ExpectedExceptionString.map((x: string) => x.trim()).join(' | '), ); } } catch (e) { this._shared.log.exceptionS(e); } } } } catch (e) { this._shared.log.exceptionS(e); } } private _processXmlTagSubcase( xml: XmlObject, title: Frame, stack: DOCSection[], testEventBuilder: TestEventBuilder, parentSection: DOCSection, ): void { for (let j = 0; xml.SubCase && j < xml.SubCase.length; ++j) { const subcase = xml.SubCase[j]; try { let currSection = parentSection.children.find( v => v.name === subcase.$.name && v.filename === subcase.$.filename && v.line === subcase.$.line, ); if (currSection === undefined) { currSection = new DOCSection(subcase.$.name || '', subcase.$.filename, subcase.$.line); parentSection.children.push(currSection); } const isLeaf = subcase.SubCase === undefined || subcase.SubCase.length === 0; if ( isLeaf && subcase.Expression && subcase.Expression.length > 0 && // eslint-disable-next-line subcase.Expression.some((x: any) => x.$ && x.$.success && x.$.success == 'false') ) { currSection.failed = true; } const name = this._isSecnario ? subcase.$.name.trimLeft() : subcase.$.name; const msg = ' '.repeat(stack.length) + '⮑ ' + (isLeaf ? (currSection.failed ? '❌' : '✅') : '') + `"${name}"`; testEventBuilder.appendMessage(msg, null); const currStack = stack.concat(currSection); this._processTags(subcase, title, currStack, testEventBuilder); this._processXmlTagSubcase(subcase, title, currStack, testEventBuilder, currSection); } catch (error) { testEventBuilder.appendMessage('Fatal error processing subcase', 1); this._shared.log.exceptionS(error); } } } }
the_stack
import { Setoid, Monad } from "funland" import * as std from "./std" import { HK, HK2 } from "./kinds" import { Throwable, NoSuchElementError } from "./errors" import { fantasyLandRegister } from "./internals" /** * Represents a value of one of two possible types (a disjoint union). * * A common use of Either is as an alternative to [[Option]] for dealing * with possible missing values. In this usage [[Option.none]] is replaced * with [[Either.left]] which can contain useful information and * [[Option.some]] is replaced with [[Either.right]]. * * Convention dictates that `left` is used for failure and `right` is used * for success. Note that this `Either` type is right-biased, meaning that * operations such as `map`, `flatMap` and `filter` work on the `right` value * and if you want to work on the `left` value, then you need to do a `swap`. * * For example, you could use `Either<String, Int>` to detect whether an * input is a string or an number: * * ```typescript * function tryParseInt(str: string): Either<string, number> { * const i = parseInt(value) * return isNaN(i) ? Left(str) : Right(i) * } * * const result = tryParseInt("not an int") * if (result.isRight()) { * console.log(`Increment: ${result.get}`) * } else { * console.log(`ERROR: could not parse ${result.swap.get}`) * } * ``` * * @final */ export class Either<L, R> implements std.IEquals<Either<L, R>>, HK2<"funfix/either", L, R> { public readonly value: L | R private readonly _isRight: boolean protected constructor(value: L | R, tag: "left" | "right") { this._isRight = tag === "right" this.value = value } /** * Returns `true` if this is a `left`, `false` otherwise. * * ```typescript * Left("hello").isLeft() // true * Right(10).isLeft() // false * ``` */ isLeft(): this is TLeft<L> { return !this._isRight } /** * Returns `true` if this is a `right`, `false` otherwise. * * ```typescript * Left("hello").isRight() // false * Right(10).isRight() // true * ``` */ isRight(): this is TRight<R> { return this._isRight } /** * Returns true if this is a Right and its value is equal to `elem` * (as determined by the `equals` protocol), returns `false` otherwise. * * ```typescript * // True * Right("something").contains("something") * * // False because the values are different * Right("something").contains("anything") // false * * // False because the source is a `left` * Left("something").contains("something") // false * ``` */ contains(elem: R): this is TRight<R> { return this._isRight && std.is(this.value, elem) } /** * Returns `false` if the source is a `left`, or returns the result * of the application of the given predicate to the `right` value. * * ```typescript * // True, because it is a right and predicate holds * Right(20).exists(n => n > 10) * * // False, because the predicate returns false * Right(10).exists(n => n % 2 != 0) * * // False, because it is a left * Left(10).exists(n => n == 10) * ``` */ exists(p: (r: R) => boolean): this is TRight<R> { return this._isRight && p(this.value as R) } /** * Filters `right` values with the given predicate, returning * the value generated by `zero` in case the source is a `right` * value and the predicate doesn't hold. * * Possible outcomes: * * - Returns the existing value of `right` if this is a `right` value and the * given predicate `p` holds for it * - Returns `Left(zero())` if this is a `right` value * and the given predicate `p` does not hold * - Returns the current "left" value, if the source is a `Left` * * ```typescript * Right(12).filterOrElse(x => x > 10, () => -1) // Right(12) * Right(7).filterOrElse(x => x > 10, () => -1) // Left(-1) * Left(7).filterOrElse(x => false, () => -1) // Left(7) * ``` */ filterOrElse<LL>(p: (r: R) => boolean, zero: () => LL): Either<L | LL, R> { return this._isRight ? (p(this.value as R) ? this as any : Left(zero())) : this as any } /** * Binds the given function across `right` values. * * This operation is the monadic "bind" operation. * It can be used to *chain* multiple `Either` references. */ flatMap<S>(f: (r: R) => Either<L, S>): Either<L, S> { return this._isRight ? f(this.value as R) : (this as any) } /** Alias for [[flatMap]]. */ chain<S>(f: (r: R) => Either<L, S>): Either<L, S> { return this.flatMap(f) } /** * `Applicative` apply operator. * * Resembles {@link map}, but the passed mapping function is * lifted in the `Either` context. */ ap<S>(ff: Either<L, (a: R) => S>): Either<L, S> { return ff.flatMap(f => this.map(f)) } /** * Applies the `left` function to [[Left]] values, and the * `right` function to [[Right]] values and returns the result. * * ```typescript * const maybeNum: Either<string, number> = * tryParseInt("not a number") * * const result: string = * maybeNum.fold( * str => `Could not parse string: ${str}`, * num => `Success: ${num}` * ) * ``` */ fold<S>(left: (l: L) => S, right: (r: R) => S): S { return this._isRight ? right(this.value as R) : left(this.value as L) } /** * Returns true if the source is a `left` or returns * the result of the application of the given predicate to the * `right` value. * * ```typescript * // True, because it is a `left` * Left("hello").forAll(x => x > 10) * * // True, because the predicate holds * Right(20).forAll(x => x > 10) * * // False, it's a right and the predicate doesn't hold * Right(7).forAll(x => x > 10) * ``` */ forAll(p: (r: R) => boolean): boolean { return !this._isRight || p(this.value as R) } /** * Returns the `Right` value, if the source has one, * otherwise throws an exception. * * WARNING! * * This function is partial, the `Either` must be a `Right`, otherwise * a runtime exception will get thrown. Use with care. * * @throws [[NoSuchElementError]] in case the the `Either` is a `Left` */ get(): R { if (this._isRight) return this.value as R throw new NoSuchElementError("left.get()") } /** * Returns the value from this `right` or the given `fallback` * value if this is a `left`. * * ```typescript * Right(10).getOrElse(27) // 10 * Left(10).getOrElse(27) // 27 * ``` */ getOrElse<RR>(fallback: RR): R | RR { return this._isRight ? this.value as R : fallback } /** * Returns the value from this `right` or a value generated * by the given `thunk` if this is a `left`. * * ```typescript * Right(10).getOrElseL(() => 27) // 10 * Left(10).getOrElseL(() => 27) // 27 * ``` */ getOrElseL<RR>(thunk: () => RR): R | RR { return this._isRight ? this.value as R : thunk() } /** * Transform the source if it is a `right` with the given * mapping function. * * ```typescript * Right(10).map(x => x + 17) // right(27) * Left(10).map(x => x + 17) // left(10) * ``` */ map<C>(f: (r: R) => C): Either<L, C> { return this._isRight ? Right(f(this.value as R)) : (this as any) } /** * Executes the given side-effecting function if the * source is a `right` value. * * ```typescript * Right(12).forAll(console.log) // prints 12 * Left(10).forAll(console.log) // silent * ``` */ forEach(cb: (r: R) => void): void { if (this._isRight) cb(this.value as R) } /** * If this is a `left`, then return the left value as a `right` * or vice versa. * * ```typescript * Right(10).swap() // left(10) * Left(20).swap() // right(20) * ``` */ swap(): Either<R, L> { return this._isRight ? Left(this.value as R) : Right(this.value as L) } /** * Returns an `Option.some(right)` if the source is a `right` value, * or `Option.none` in case the source is a `left` value. */ toOption(): Option<R> { return this._isRight ? Some(this.value as R) : None } /** * Implements {@link IEquals.equals}. * * @param that is the right hand side of the equality check */ equals(that: Either<L, R>): boolean { // tslint:disable-next-line:strict-type-predicates if (that == null) return false return this._isRight === that._isRight && std.is(this.value, that.value) } /** Implements {@link IEquals.hashCode}. */ hashCode(): number { return this._isRight ? std.hashCode(this.value as R) << 2 : std.hashCode(this.value as L) << 3 } // Implements HK<F, A> /** @hidden */ readonly _URI!: "funfix/either" /** @hidden */ readonly _A!: R /** @hidden */ readonly _L!: L // Implements Constructor<T> /** @hidden */ static readonly _Class: Either<any, any> /** * Builds a pure `Either` value. * * This operation is the pure `Applicative` operation for lifting * a value in the `Either` context. */ static pure<A>(value: A): Either<never, A> { return new TRight(value) } /** * Builds a left value, equivalent with {@link Left}. */ static left<L, R>(value: L): Either<L, R> { return Left(value) } /** * Builds a right value, equivalent with {@link Right}. */ static right<L, R>(value: R): Either<L, R> { return Right(value) } /** * Maps 2 `Either` values by the mapping function, returning a new * `Either` reference that is a `Right` only if both `Either` values are * `Right` values, otherwise it returns the first `Left` value noticed. * * ```typescript * // Yields Right(3) * Try.map2(Right(1), Right(2), * (a, b) => a + b * ) * * // Yields Left, because the second arg is a Left * Try.map2(Right(1), Left("error"), * (a, b) => a + b * ) * ``` * * This operation is the `Applicative.map2`. */ static map2<A1, A2, L, R>( fa1: Either<L,A1>, fa2: Either<L,A2>, f: (a1: A1, a2: A2) => R): Either<L, R> { if (fa1.isLeft()) return fa1 if (fa2.isLeft()) return fa2 return Right(f(fa1.value as A1, fa2.value as A2)) } /** * Maps 3 `Either` values by the mapping function, returning a new * `Either` reference that is a `Right` only if all 3 `Either` values are * `Right` values, otherwise it returns the first `Left` value noticed. * * ```typescript * // Yields Right(6) * Try.map3(Right(1), Right(2), Right(3), * (a, b, c) => a + b + c * ) * * // Yields Left, because the second arg is a Left * Try.map3(Right(1), Left("error"), Right(3), * (a, b, c) => a + b + c * ) * ``` */ static map3<A1, A2, A3, L, R>( fa1: Either<L, A1>, fa2: Either<L, A2>, fa3: Either<L, A3>, f: (a1: A1, a2: A2, a3: A3) => R): Either<L, R> { if (fa1.isLeft()) return fa1 if (fa2.isLeft()) return fa2 if (fa3.isLeft()) return fa3 return Right(f(fa1.value as A1, fa2.value as A2, fa3.value as A3)) } /** * Maps 4 `Either` values by the mapping function, returning a new * `Either` reference that is a `Right` only if all 4 `Either` values are * `Right` values, otherwise it returns the first `Left` value noticed. * * ```typescript * // Yields Right(10) * Try.map4(Right(1), Right(2), Right(3), Right(4), * (a, b, c, d) => a + b + c + d * ) * * // Yields Left, because the second arg is a Left * Try.map4(Right(1), Left("error"), Right(3), Right(4), * (a, b, c, d) => a + b + c + d * ) * ``` */ static map4<A1, A2, A3, A4, L, R>( fa1: Either<L,A1>, fa2: Either<L,A2>, fa3: Either<L,A3>, fa4: Either<L,A4>, f: (a1: A1, a2: A2, a3: A3, a4: A4) => R): Either<L, R> { if (fa1.isLeft()) return fa1 if (fa2.isLeft()) return fa2 if (fa3.isLeft()) return fa3 if (fa4.isLeft()) return fa4 return Right(f(fa1.value as A1, fa2.value as A2, fa3.value as A3, fa4.value as A4)) } /** * Maps 5 `Either` values by the mapping function, returning a new * `Either` reference that is a `Right` only if all 5 `Either` values are * `Right` values, otherwise it returns the first `Left` value noticed. * * ```typescript * // Yields Right(15) * Try.map5(Right(1), Right(2), Right(3), Right(4), Right(5), * (a, b, c, d, e) => a + b + c + d + e * ) * * // Yields Left, because the second arg is a Left * Try.map5(Right(1), Left("error"), Right(3), Right(4), Right(5), * (a, b, c, d, e) => a + b + c + d + e * ) * ``` */ static map5<A1, A2, A3, A4, A5, L, R>( fa1: Either<L,A1>, fa2: Either<L,A2>, fa3: Either<L,A3>, fa4: Either<L,A4>, fa5: Either<L,A5>, f: (a1: A1, a2: A2, a3: A3, a4: A4, a5: A5) => R): Either<L, R> { if (fa1.isLeft()) return fa1 if (fa2.isLeft()) return fa2 if (fa3.isLeft()) return fa3 if (fa4.isLeft()) return fa4 if (fa5.isLeft()) return fa5 return Right(f(fa1.value as A1, fa2.value as A2, fa3.value as A3, fa4.value as A4, fa5.value as A5)) } /** * Maps 6 `Either` values by the mapping function, returning a new * `Either` reference that is a `Right` only if all 6 `Either` values are * `Right` values, otherwise it returns the first `Left` value noticed. * * ```typescript * // Yields Right(21) * Try.map5(Right(1), Right(2), Right(3), Right(4), Right(5), Right(6), * (a, b, c, d, e, f) => a + b + c + d + e + f * ) * * // Yields Left, because the second arg is a Left * Try.map5(Right(1), Left("error"), Right(3), Right(4), Right(5), Right(6), * (a, b, c, d, e, f) => a + b + c + d + e + f * ) * ``` */ static map6<A1, A2, A3, A4, A5, A6, L, R>( fa1: Either<L,A1>, fa2: Either<L,A2>, fa3: Either<L,A3>, fa4: Either<L,A4>, fa5: Either<L,A5>, fa6: Either<L,A6>, f: (a1: A1, a2: A2, a3: A3, a4: A4, a5: A5, a6: A6) => R): Either<L, R> { if (fa1.isLeft()) return fa1 if (fa2.isLeft()) return fa2 if (fa3.isLeft()) return fa3 if (fa4.isLeft()) return fa4 if (fa5.isLeft()) return fa5 if (fa6.isLeft()) return fa6 return Right(f(fa1.value as A1, fa2.value as A2, fa3.value as A3, fa4.value as A4, fa5.value as A5, fa6.value as A6)) } /** * Keeps calling `f` until a `Right(b)` is returned. * * Based on Phil Freeman's * [Stack Safety for Free]{@link http://functorial.com/stack-safety-for-free/index.pdf}. * * Described in `FlatMap.tailRecM`. */ static tailRecM<L, A, B>(a: A, f: (a: A) => Either<L, Either<A, B>>): Either<L, B> { let cursor = a while (true) { const result = f(cursor) if (!result.isRight()) return result as any const some = result.value if (some.isRight()) return Right(some.value) cursor = some.value as A } } } /** * Result of the [[Left]] data constructor, representing * "left" values in the [[Either]] disjunction. * * @final */ export class TLeft<L> extends Either<L, never> { public readonly value!: L constructor(value: L) { super(value, "left") } } /** * The `Left` data constructor represents the left side of the * [[Either]] disjoint union, as opposed to the [[Right]] side. */ export function Left<L>(value: L): TLeft<L> { return new TLeft(value) } /** * Result of the [[Right]] data constructor, representing * "right" values in the [[Either]] disjunction. * * @final */ export class TRight<R> extends Either<never, R> { public readonly value!: R constructor(value: R) { super(value, "right") } } /** * The `Right` data constructor represents the right side of the * [[Either]] disjoint union, as opposed to the [[Left]] side. */ export function Right<R>(value: R): TRight<R> { return new TRight(value) } /** * Type enumerating the type-classes that `Either` implements. */ export type EitherTypes = Setoid<Either<any, any>> & Monad<"funfix/either"> /** * Type-class implementations, compatible with the `static-land` * and `funland` specifications. * * See [funland-js.org](https://funland-js.org). */ export const EitherModule: EitherTypes = { // Setoid equals: (x, y) => x ? x.equals(y) : !y, // Functor map: <L, A, B>(f: (a: A) => B, fa: Either<L, A>) => fa.map(f), // Apply ap: <L, A, B>(ff: Either<L, (a: A) => B>, fa: Either<L, A>): Either<L, B> => fa.ap(ff), // Applicative of: Either.pure, // Chain chain: <L, A, B>(f: (a: A) => Either<L, B>, fa: Either<L, A>): Either<L, B> => fa.flatMap(f), // ChainRec chainRec: <L, A, B>(f: <C>(next: (a: A) => C, done: (b: B) => C, a: A) => Either<L, C>, a: A): Either<L, B> => Either.tailRecM(a, a => f(Either.left as any, Either.right as any, a)) } // Registers Fantasy-Land compatible symbols fantasyLandRegister(Either, EitherModule, EitherModule) /** * Represents optional values, inspired by Scala's `Option` and by * Haskell's `Maybe` data types. * * Option is an immutable data type, represented as a sum type, being * either a [[Some]], in case it contains a single element, or a [[None]], * in case it is empty. * * The most idiomatic way to use an `Option` instance is to treat it * as a collection or monad and use `map`,`flatMap`, `filter`, * or `forEach`. * * @final */ export class Option<A> implements std.IEquals<Option<A>>, HK<"funfix/option", A> { // tslint:disable-next-line:variable-name private readonly _isEmpty: boolean public readonly value: undefined | A protected constructor(ref: A | undefined, isEmpty?: boolean) { /* tslint:disable-next-line:strict-type-predicates */ this._isEmpty = isEmpty != null ? isEmpty : (ref === null || ref === undefined) this.value = ref } /** * Returns the option's value. * * WARNING! * * This function is partial, the option must be non-empty, otherwise * a runtime exception will get thrown. Use with care. * * @throws [[NoSuchElementError]] in case the option is empty */ get(): A { if (!this._isEmpty) return this.value as A throw new NoSuchElementError("Option.get") } /** * Returns the option's value if the option is nonempty, otherwise * return the given `fallback`. * * See [[Option.getOrElseL]] for a lazy alternative. */ getOrElse<AA>(fallback: AA): A | AA { if (!this._isEmpty) return this.value as A else return fallback } /** * Returns the option's value if the option is nonempty, otherwise * return `null`. * ``` */ orNull(): A | null { return !this._isEmpty ? this.value as A : null } /** * Returns the option's value if the option is nonempty, otherwise * return `undefined`. */ orUndefined(): A | undefined { return !this._isEmpty ? this.value : undefined } /** * Returns the option's value if the option is nonempty, otherwise * return the result of evaluating `thunk`. * * See [[Option.getOrElse]] for a strict alternative. */ getOrElseL<AA>(thunk: () => AA): A | AA { if (!this._isEmpty) return this.value as A else return thunk() } /** * Returns this option if it is nonempty, otherwise returns the * given `fallback`. */ orElse<AA>(fallback: Option<AA>): Option<A | AA> { if (!this._isEmpty) return this else return fallback } /** * Returns this option if it is nonempty, otherwise returns the * given result of evaluating the given `thunk`. * * @param thunk a no-params function that gets evaluated and * whose result is returned in case this option is empty */ orElseL<AA>(thunk: () => Option<AA>): Option<A | AA> { if (!this._isEmpty) return this else return thunk() } /** * Returns `true` if the option is empty, `false` otherwise. */ isEmpty(): this is TNone { return this._isEmpty } /** * Returns `true` if the option is not empty, `false` otherwise. */ nonEmpty(): this is TSome<A> { return !this._isEmpty } /** * Returns an option containing the result of applying `f` to * this option's value, or an empty option if the source is empty. * * NOTE: this is similar with `flatMap`, except with `map` the * result of `f` doesn't need to be wrapped in an `Option`. * * @param f the mapping function that will transform the value * of this option if nonempty. * * @return a new option instance containing the value of the * source mapped by the given function */ map<B>(f: (a: A) => B): Option<B> { return this._isEmpty ? None : Some(f(this.value as A)) } /** * Returns the result of applying `f` to this option's value if * the option is nonempty, otherwise returns an empty option. * * NOTE: this is similar with `map`, except that `flatMap` the * result returned by `f` is expected to be boxed in an `Option` * already. * * Example: * * ```typescript * const opt = Option.of(10) * * opt.flatMap(num => { * if (num % 2 == 0) * Some(num + 1) * else * None * }) * ``` * * @param f the mapping function that will transform the value * of this option if nonempty. * * @return a new option instance containing the value of the * source mapped by the given function */ flatMap<B>(f: (a: A) => Option<B>): Option<B> { if (this._isEmpty) return None else return f(this.value as A) } /** Alias for [[flatMap]]. */ chain<B>(f: (a: A) => Option<B>): Option<B> { return this.flatMap(f) } /** * `Applicative` apply operator. * * Resembles {@link map}, but the passed mapping function is * lifted in the `Either` context. */ ap<B>(ff: Option<(a: A) => B>): Option<B> { return ff.flatMap(f => this.map(f)) } /** * Returns this option if it is nonempty AND applying the * predicate `p` to the underlying value yields `true`, * otherwise return an empty option. * * @param p is the predicate function that is used to * apply filtering on the option's value * * @return a new option instance containing the value of the * source filtered with the given predicate */ filter<B extends A>(p: (a: A) => a is B): Option<B> filter(p: (a: A) => boolean): Option<A> filter(p: (a: A) => boolean): Option<A> { if (this._isEmpty || !p(this.value as A)) return None else return this } /** * Returns the result of applying `f` to this option's value, * or in case the option is empty, the return the result of * evaluating the `fallback` function. * * This function is equivalent with: * * ```typescript * opt.map(f).getOrElseL(fallback) * ``` * * @param fallback is the function to be evaluated in case this * option is empty * * @param f is the mapping function for transforming this option's * value in case it is nonempty */ fold<B>(fallback: () => B, f: (a: A) => B): B { if (this._isEmpty) return fallback() return f(this.value as A) } /** * Returns true if this option is nonempty and the value it * holds is equal to the given `elem`. */ contains(elem: A): boolean { return !this._isEmpty && std.is(this.value, elem) } /** * Returns `true` if this option is nonempty and the given * predicate returns `true` when applied on this option's value. * * @param p is the predicate function to test */ exists(p: (a: A) => boolean): boolean { return !this._isEmpty && p(this.value as A) } /** * Returns true if this option is empty or the given predicate * returns `true` when applied on this option's value. * * @param p is the predicate function to test */ forAll(p: (a: A) => boolean): boolean { return this._isEmpty || p(this.value as A) } /** * Apply the given procedure `cb` to the option's value if * this option is nonempty, otherwise do nothing. * * @param cb the procedure to apply */ forEach(cb: (a: A) => void): void { if (!this._isEmpty) cb(this.value as A) } /** * Implements {@link IEquals.equals}. * * @param that is the right hand side of the equality check */ equals(that: Option<A>): boolean { // tslint:disable-next-line:strict-type-predicates if (that == null) return false if (this.nonEmpty() && that.nonEmpty()) { return std.is(this.value, that.value) } return this.isEmpty() && that.isEmpty() } // Implemented from IEquals hashCode(): number { if (this._isEmpty) return 2433880 // tslint:disable-next-line:strict-type-predicates else if (this.value == null) return 2433881 << 2 else return std.hashCode(this.value) << 2 } // Implements HK<F, A> /** @hidden */ readonly _URI!: "funfix/option" /** @hidden */ readonly _A!: A // Implements Constructor<T> /** @hidden */ static readonly _Class: Option<any> /** * Builds an [[Option]] reference that contains the given value. * * If the given value is `null` or `undefined` then the returned * option will be empty. */ static of<A>(value: A | null | undefined): Option<A> { return value != null ? Some(value) : None } /** * Builds an [[Option]] reference that contains the given reference. * * Note that `value` is allowed to be `null` or `undefined`, the * returned option will still be non-empty. Use [[Option.of]] * if you want to avoid this problem. This means: * * ```typescript * const opt = Some<number | null>(null) * * opt.isEmpty() * //=> false * * opt.get() * //=> null * ``` */ static some<A>(value: A): Option<A> { return new Option(value, false) } /** * Returns an empty [[Option]]. * * NOTE: Because `Option` is immutable, this function returns the * same cached reference is on different calls. */ static none<A = never>(): Option<A> { return None } /** * Returns an empty [[Option]]. * * Similar to [[Option.none]], but this one allows specifying a * type parameter (in the context of TypeScript or Flow or other * type system). * * NOTE: Because `Option` is immutable, this function returns the * same cached reference is on different calls. */ static empty<A>(): Option<A> { return None } /** * Alias for [[Some]]. */ static pure<A>(value: A): Option<A> { return Some(value) } /** * Maps 2 optional values by the mapping function, returning a new * optional reference that is `Some` only if both option values are * `Some`, otherwise it returns a `None`. * * ```typescript * // Yields Some(3) * Option.map2(Some(1), Some(2), * (a, b) => a + b * ) * * // Yields None, because the second arg is None * Option.map2(Some(1), None, * (a, b) => a + b * ) * ``` * * This operation is the `Applicative.map2`. */ static map2<A1,A2,R>( fa1: Option<A1>, fa2: Option<A2>, f: (a1: A1, a2: A2) => R): Option<R> { return fa1.nonEmpty() && fa2.nonEmpty() ? Some(f(fa1.value, fa2.value)) : None } /** * Maps 3 optional values by the mapping function, returning a new * optional reference that is `Some` only if all 3 option values are * `Some`, otherwise it returns a `None`. * * ```typescript * // Yields Some(6) * Option.map3(Some(1), Some(2), Some(3), * (a, b, c) => a + b + c * ) * * // Yields None, because the second arg is None * Option.map3(Some(1), None, Some(3), * (a, b, c) => a + b + c * ) * ``` */ static map3<A1,A2,A3,R>( fa1: Option<A1>, fa2: Option<A2>, fa3: Option<A3>, f: (a1: A1, a2: A2, a3: A3) => R): Option<R> { return fa1.nonEmpty() && fa2.nonEmpty() && fa3.nonEmpty() ? Some(f(fa1.value, fa2.value, fa3.value)) : None } /** * Maps 4 optional values by the mapping function, returning a new * optional reference that is `Some` only if all 4 option values are * `Some`, otherwise it returns a `None`. * * ```typescript * // Yields Some(10) * Option.map4(Some(1), Some(2), Some(3), Some(4), * (a, b, c, d) => a + b + c + d * ) * * // Yields None, because the second arg is None * Option.map4(Some(1), None, Some(3), Some(4), * (a, b, c, d) => a + b + c + d * ) * ``` */ static map4<A1,A2,A3,A4,R>( fa1: Option<A1>, fa2: Option<A2>, fa3: Option<A3>, fa4: Option<A4>, f: (a1: A1, a2: A2, a3: A3, a4: A4) => R): Option<R> { return fa1.nonEmpty() && fa2.nonEmpty() && fa3.nonEmpty() && fa4.nonEmpty() ? Some(f(fa1.value, fa2.value, fa3.value, fa4.value)) : None } /** * Maps 5 optional values by the mapping function, returning a new * optional reference that is `Some` only if all 5 option values are * `Some`, otherwise it returns a `None`. * * ```typescript * // Yields Some(15) * Option.map5(Some(1), Some(2), Some(3), Some(4), Some(5), * (a, b, c, d, e) => a + b + c + d + e * ) * * // Yields None, because the second arg is None * Option.map5(Some(1), None, Some(3), Some(4), Some(5), * (a, b, c, d, e) => a + b + c + d + e * ) * ``` */ static map5<A1,A2,A3,A4,A5,R>( fa1: Option<A1>, fa2: Option<A2>, fa3: Option<A3>, fa4: Option<A4>, fa5: Option<A5>, f: (a1: A1, a2: A2, a3: A3, a4: A4, a5: A5) => R): Option<R> { return fa1.nonEmpty() && fa2.nonEmpty() && fa3.nonEmpty() && fa4.nonEmpty() && fa5.nonEmpty() ? Some(f(fa1.value, fa2.value, fa3.value, fa4.value, fa5.value)) : None } /** * Maps 6 optional values by the mapping function, returning a new * optional reference that is `Some` only if all 6 option values are * `Some`, otherwise it returns a `None`. * * ```typescript * // Yields Some(21) * Option.map6(Some(1), Some(2), Some(3), Some(4), Some(5), Some(6), * (a, b, c, d, e, f) => a + b + c + d + e + f * ) * * // Yields None, because the second arg is None * Option.map6(Some(1), None, Some(3), Some(4), Some(5), Some(6), * (a, b, c, d, e, f) => a + b + c + d + e + f * ) * ``` */ static map6<A1,A2,A3,A4,A5,A6,R>( fa1: Option<A1>, fa2: Option<A2>, fa3: Option<A3>, fa4: Option<A4>, fa5: Option<A5>, fa6: Option<A6>, f: (a1: A1, a2: A2, a3: A3, a4: A4, a5: A5, a6: A6) => R): Option<R> { return fa1.nonEmpty() && fa2.nonEmpty() && fa3.nonEmpty() && fa4.nonEmpty() && fa5.nonEmpty() && fa6.nonEmpty() ? Some(f(fa1.value, fa2.value, fa3.value, fa4.value, fa5.value, fa6.value)) : None } /** * Keeps calling `f` until a `Right(b)` is returned. * * Based on Phil Freeman's * [Stack Safety for Free]{@link http://functorial.com/stack-safety-for-free/index.pdf}. * * Described in `FlatMap.tailRecM`. */ static tailRecM<A, B>(a: A, f: (a: A) => Option<Either<A, B>>): Option<B> { let cursor = a while (true) { const result = f(cursor) if (result.nonEmpty()) { const some = result.value if (some.isRight()) return Some(some.value) cursor = some.value as A } else { return None } } } } /** * Result of the [[Some]] data constructor, representing * non-empty values in the [[Option]] disjunction. */ export class TSome<A> extends Option<A> { public readonly value!: A constructor(value: A) { super(value, false) } } /** * The `Some<A>` data constructor for [[Option]] represents existing * values of type `A`. * * Using this function is equivalent with [[Option.some]]. */ export function Some<A>(value: A): TSome<A> { return new TSome(value) } /** * Result of the [[Some]] data constructor, representing * non-empty values in the [[Option]] disjunction. */ export class TNone extends Option<never> { public readonly value!: never private constructor() { super(undefined, true) } } /** * The `None` data constructor for [[Option]] represents non-existing * values for any type. * * Using this reference directly is equivalent with [[Option.none]]. */ export const None: TNone = new (TNone as any)() /** * Type enumerating the type classes implemented by `Option`. */ export type OptionTypes = Setoid<Option<any>> & Monad<"funfix/option"> /** * Type-class implementations, compatible with the `static-land` * and `funland` specification. * * See [funland-js.org](https://funland-js.org). */ export const OptionModule: OptionTypes = { // Setoid equals: (x, y) => x ? x.equals(y) : !y, // Functor map: <A, B>(f: (a: A) => B, fa: Option<A>) => fa.map(f), // Apply ap: <A, B>(ff: Option<(a: A) => B>, fa: Option<A>): Option<B> => fa.ap(ff), // Applicative of: Option.pure, // Chain chain: <A, B>(f: (a: A) => Option<B>, fa: Option<A>): Option<B> => fa.flatMap(f), // ChainRec chainRec: <A, B>(f: <C>(next: (a: A) => C, done: (b: B) => C, a: A) => Option<C>, a: A): Option<B> => Option.tailRecM(a, a => f(Either.left as any, Either.right as any, a)) } // Registers Fantasy-Land compatible symbols fantasyLandRegister(Option, OptionModule, OptionModule) /** * The `Try` type represents a computation that may either result in an * exception, or return a successfully computed value. It's similar to, * but semantically different from the [[Either]] type. * * `Try` is a sum type and so instances of `Try` are either instances * of [[Success]] or of [[Failure]]. * * For example, `Try` can be used to perform division on a user-defined * input, without the need to do explicit exception-handling in all of * the places that an exception might occur. * * Example: * * ```typescript * function divide(dividendS: string, divisorS: string): string { * const dividend = Try(() => parseInt(dividendS)) * .filter(_ => _ === _) // filter out NaN * const divisor = Try(() => parseInt(divisorS)) * .filter(_ => _ === _) // filter out NaN * * // map2 executes the given function only if both results are * // successful; we could also express this with flatMap / chain * const result = Try.map2(dividend, divisor, * (a, b) => a / b * ) * * result.fold( * error => `failure: ${error}` * result => `result: ${result}` * ) * } * ``` * * An important property of `Try` is its ability to pipeline, or chain, * operations, catching exceptions along the way. The `flatMap` and `map` * combinators each essentially pass off either their successfully completed * value, wrapped in the [[Success]] type for it to be further operated upon * by the next combinator in the chain, or the exception wrapped in the * [[Failure]] type usually to be simply passed on down the chain. * Combinators such as `recover` and `recoverWith` are designed to provide * some type of global behavior in the case of failure. * * NOTE: all `Try` combinators will catch exceptions and return failure * unless otherwise specified in the documentation. */ export class Try<A> implements std.IEquals<Try<A>>, HK<"funfix/try", A> { private _isSuccess: boolean public readonly value: Throwable | A protected constructor(value: Throwable | A, tag: "failure" | "success") { this._isSuccess = tag === "success" this.value = value } /** * Returns `true` if the source is a [[Success]] result, * or `false` in case it is a [[Failure]]. */ isSuccess(): this is TSuccess<A> { return this._isSuccess } /** * Returns `true` if the source is a [[Failure]], * or `false` in case it is a [[Success]] result. */ isFailure(): this is TFailure { return !this._isSuccess } /** * Returns a Try's successful value if it's a [[Success]] reference, * otherwise throws an exception if it's a [[Failure]]. * * WARNING! * * This function is partial, the option must be non-empty, otherwise * a runtime exception will get thrown. Use with care. */ get(): A { if (!this._isSuccess) throw this.value return this.value as A } /** * Returns the value from a `Success` or the given `fallback` * value if this is a `Failure`. * * ```typescript * Success(10).getOrElse(27) // 10 * Failure("error").getOrElse(27) // 27 * ``` */ getOrElse<AA>(fallback: AA): A | AA { return this._isSuccess ? this.value as A : fallback } /** * Returns the value from a `Success` or the value generated * by a given `thunk` in case this is a `Failure`. * * ```typescript * Success(10).getOrElseL(() => 27) // 10 * Failure("error").getOrElseL(() => 27) // 27 * ``` */ getOrElseL<AA>(thunk: () => AA): A | AA { return this._isSuccess ? this.value as A : thunk() } /** * Returns the current value if it's a [[Success]], or * if the source is a [[Failure]] then return `null`. * * ```typescript * Success(10).orNull() // 10 * Failure("error").orNull() // null * ``` * * This can be useful for use-cases such as: * * ```typescript * Try.of(() => dict.user.profile.name).orNull() * ``` */ orNull(): A | null { return this._isSuccess ? this.value as A : null } /** * Returns the current value if it's a [[Success]], or * if the source is a [[Failure]] then return `undefined`. * * ```typescript * Success(10).orUndefined() // 10 * Failure("error").orUndefined() // undefined * ``` * * This can be useful for use-cases such as: * * ```typescript * Try.of(() => dict.user.profile.name).orUndefined() * ``` */ orUndefined(): A | undefined { return this._isSuccess ? this.value as A : undefined } /** * Returns the current value if it's a [[Success]], or if * the source is a [[Failure]] then return the `fallback`. * * ```typescript * Success(10).orElse(Success(17)) // 10 * Failure("error").orElse(Success(17)) // 17 * ``` */ orElse<AA>(fallback: Try<AA>): Try<A | AA> { if (this._isSuccess) return this return fallback } /** * Returns the current value if it's a [[Success]], or if the source * is a [[Failure]] then return the value generated by the given * `thunk`. * * ```typescript * Success(10).orElseL(() => Success(17)) // 10 * Failure("error").orElseL(() => Success(17)) // 17 * ``` */ orElseL<AA>(thunk: () => Try<AA>): Try<A | AA> { if (this._isSuccess) return this return thunk() } /** * Inverts this `Try`. If this is a [[Failure]], returns its exception wrapped * in a [[Success]]. If this is a `Success`, returns a `Failure` containing a * [[NoSuchElementError]]. */ failed(): Try<Throwable> { return this._isSuccess ? Failure(new NoSuchElementError("try.failed()")) : Success(this.value as Throwable) } /** * Applies the `failure` function to [[Failure]] values, and the * `success` function to [[Success]] values and returns the result. * * ```typescript * const maybeNum: Try<number> = * tryParseInt("not a number") * * const result: string = * maybeNum.fold( * error => `Could not parse string: ${error}`, * num => `Success: ${num}` * ) * ``` */ fold<R>(failure: (error: Throwable) => R, success: (a: A) => R): R { return this._isSuccess ? success(this.value as A) : failure(this.value as Throwable) } /** * Returns a [[Failure]] if the source is a [[Success]], but the * given `p` predicate is not satisfied. * * @throws NoSuchElementError in case the predicate doesn't hold */ filter<B extends A>(p: (a: A) => a is B): Try<B> filter(p: (a: A) => boolean): Try<A> filter(p: (a: A) => boolean): Try<A> { if (!this._isSuccess) return this try { if (p(this.value as A)) return this return Failure( new NoSuchElementError( `Predicate does not hold for ${this.value as A}` )) } catch (e) { return Failure(e) } } /** * Returns the given function applied to the value if this is * a [[Success]] or returns `this` if this is a [[Failure]]. * * This operation is the monadic "bind" operation. * It can be used to *chain* multiple `Try` references. * * ```typescript * Try.of(() => parse(s1)).flatMap(num1 => * Try.of(() => parse(s2)).map(num2 => * num1 / num2 * )) * ``` */ flatMap<B>(f: (a: A) => Try<B>): Try<B> { if (!this._isSuccess) return this as any try { return f(this.value as A) } catch (e) { return Failure(e) } } /** Alias for [[flatMap]]. */ chain<B>(f: (a: A) => Try<B>): Try<B> { return this.flatMap(f) } /** * `Applicative` apply operator. * * Resembles {@link map}, but the passed mapping function is * lifted in the `Either` context. */ ap<B>(ff: Try<(a: A) => B>): Try<B> { return ff.flatMap(f => this.map(f)) } /** * Returns a `Try` containing the result of applying `f` to * this option's value, but only if it's a `Success`, or * returns the current `Failure` without any modifications. * * NOTE: this is similar with `flatMap`, except with `map` the * result of `f` doesn't need to be wrapped in a `Try`. * * @param f the mapping function that will transform the value * of this `Try` if successful. * * @return a new `Try` instance containing the value of the * source mapped by the given function */ map<B>(f: (a: A) => B): Try<B> { return this._isSuccess ? Try.of(() => f(this.value as A)) : ((this as any) as Try<B>) } /** * Applies the given function `cb` if this is a [[Success]], otherwise * returns `void` if this is a [[Failure]]. */ forEach(cb: (a: A) => void): void { if (this._isSuccess) cb(this.value as A) } /** * Applies the given function `f` if this is a `Failure`, otherwise * returns `this` if this is a `Success`. * * This is like `map` for the exception. * * In the following example, if the `user.profile.email` exists, * then it is returned as a successful value, otherwise * * ```typescript * Try.of(() => user.profile.email).recover(e => { * // Access error? Default to empty. * if (e instanceof TypeError) return "" * throw e // We don't know what it is, rethrow * }) * * Note that on rethrow, the error is being caught in `recover` and * it still returns it as a `Failure(e)`. * ``` */ recover<AA>(f: (error: Throwable) => AA): Try<A | AA> { return this._isSuccess ? this : Try.of(() => f(this.value as Throwable)) } /** * Applies the given function `f` if this is a `Failure`, otherwise * returns `this` if this is a `Success`. * * This is like `map` for the exception. * * In the following example, if the `user.profile.email` exists, * then it is returned as a successful value, otherwise * * ```typescript * Try.of(() => user.profile.email).recover(e => { * // Access error? Default to empty. * if (e instanceof TypeError) return "" * throw e // We don't know what it is, rethrow * }) * * Note that on rethrow, the error is being caught in `recover` and * it still returns it as a `Failure(e)`. * ``` */ recoverWith<AA>(f: (error: Throwable) => Try<AA>): Try<A | AA> { try { return this._isSuccess ? this : f(this.value as Throwable) } catch (e) { return Failure(e) } } /** * Transforms the source into an [[Option]]. * * In case the source is a `Success(v)`, then it gets translated * into a `Some(v)`. If the source is a `Failure(e)`, then a `None` * value is returned. * * ```typescript * Success("value").toOption() // Some("value") * Failure("error").toOption() // None * ``` */ toOption(): Option<A> { return this._isSuccess ? Some(this.value as A) : None } /** * Transforms the source into an [[Either]]. * * In case the source is a `Success(v)`, then it gets translated * into a `Right(v)`. If the source is a `Failure(e)`, then a `Left(e)` * value is returned. * * ```typescript * Success("value").toEither() // Right("value") * Failure("error").toEither() // Left("error") * ``` */ toEither(): Either<Throwable, A> { return this._isSuccess ? Right(this.value as A) : Left(this.value as Throwable) } /** * Implements {@link IEquals.equals} with overridable equality for `A`. */ equals(that: Try<A>): boolean { // tslint:disable-next-line:strict-type-predicates if (that == null) return false return this._isSuccess ? that._isSuccess && std.is(this.value as A, that.value as A) : !that._isSuccess && std.is(this.value, that.value) } // Implemented from IEquals hashCode(): number { return this._isSuccess ? std.hashCode(this.value as A) : std.hashCode(this.value as Throwable) } // Implements HK<F, A> /** @hidden */ readonly _URI!: "funfix/try" /** @hidden */ readonly _A!: A // Implements Constructor<T> /** @hidden */ static readonly _Class: Try<any> /** * Evaluates the given `thunk` and returns either a [[Success]], * in case the evaluation succeeded, or a [[Failure]], in case * an exception was thrown. * * Example: * * ```typescript * let effect = 0 * * const e = Try.of(() => { effect += 1; return effect }) * e.get() // 1 * ``` */ static of<A>(thunk: () => A): Try<A> { try { return Success(thunk()) } catch (e) { return Failure(e) } } /** Alias of [[Try.success]]. */ static pure<A>(value: A): Try<A> { return Try.success(value) } /** * Shorthand for `now(undefined as void)`, always returning * the same reference as optimization. */ static unit(): Try<void> { return tryUnitRef } /** * Returns a [[Try]] reference that represents a successful result * (i.e. wrapped in [[Success]]). */ static success<A>(value: A): Try<A> { return Success(value) } /** * Returns a [[Try]] reference that represents a failure * (i.e. an exception wrapped in [[Failure]]). */ static failure<A = never>(e: Throwable): Try<A> { return Failure(e) } /** * Alias for {@link Try.failure} and {@link Failure}, * wrapping any throwable into a `Try` value. */ static raise<A = never>(e: Throwable): Try<A> { return Failure(e) } /** * Maps 2 `Try` values by the mapping function, returning a new * `Try` reference that is a `Success` only if both `Try` values are * a `Success`, otherwise it returns the first `Failure` noticed. * * ```typescript * // Yields Success(3) * Try.map2(Success(1), Success(2), * (a, b) => a + b * ) * * // Yields Failure, because the second arg is a Failure * Try.map2(Success(1), Failure("error"), * (a, b) => a + b * ) * ``` * * This operation is the `Applicative.map2`. */ static map2<A1,A2,R>( fa1: Try<A1>, fa2: Try<A2>, f: (a1: A1, a2: A2) => R): Try<R> { if (fa1.isFailure()) return fa1 if (fa2.isFailure()) return fa2 try { return Success(f(fa1.value as A1, fa2.value as A2)) } catch (e) { return Failure(e) } } /** * Maps 3 `Try` values by the mapping function, returning a new * `Try` reference that is a `Success` only if all 3 `Try` values are * a `Success`, otherwise it returns the first `Failure` noticed. * * ```typescript * // Yields Success(6) * Try.map3(Success(1), Success(2), Success(3), * (a, b, c) => { * return a + b + c * } * ) * * // Yields Failure, because the second arg is a Failure * Try.map3( * Success(1), * Failure("error"), * Success(3), * * (a, b, c) => { * return a + b + c * } * ) * ``` */ static map3<A1,A2,A3,R>( fa1: Try<A1>, fa2: Try<A2>, fa3: Try<A3>, f: (a1: A1, a2: A2, a3: A3) => R): Try<R> { if (fa1.isFailure()) return fa1 if (fa2.isFailure()) return fa2 if (fa3.isFailure()) return fa3 try { return Success(f( fa1.value as A1, fa2.value as A2, fa3.value as A3 )) } catch (e) { return Failure(e) } } /** * Maps 4 `Try` values by the mapping function, returning a new * `Try` reference that is a `Success` only if all 4 `Try` values are * a `Success`, otherwise it returns the first `Failure` noticed. * * ```typescript * // Yields Success(10) * Try.map4(Success(1), Success(2), Success(3), Success(4), * (a, b, c, d) => { * return a + b + c + d * } * ) * * // Yields Failure, because the second arg is a Failure * Try.map3( * Success(1), * Failure("error"), * Success(3), * Success(4), * * (a, b, c, d) => { * return a + b + c + d * } * ) * ``` */ static map4<A1,A2,A3,A4,R>( fa1: Try<A1>, fa2: Try<A2>, fa3: Try<A3>, fa4: Try<A4>, f: (a1: A1, a2: A2, a3: A3, a4: A4) => R): Try<R> { if (fa1.isFailure()) return fa1 if (fa2.isFailure()) return fa2 if (fa3.isFailure()) return fa3 if (fa4.isFailure()) return fa4 try { return Success(f( fa1.value as A1, fa2.value as A2, fa3.value as A3, fa4.value as A4 )) } catch (e) { return Failure(e) } } /** * Maps 5 `Try` values by the mapping function, returning a new * `Try` reference that is a `Success` only if all 5 `Try` values are * a `Success`, otherwise it returns the first `Failure` noticed. * * ```typescript * // Yields Success(15) * Try.map5( * Success(1), * Success(2), * Success(3), * Success(4), * Success(5), * * (a, b, c, d, e) => { * return a + b + c + d + e * } * ) * * // Yields Failure, because the second arg is a Failure * Try.map5( * Success(1), * Failure("error"), * Success(3), * Success(4), * Success(5), * * (a, b, c, d, e) => { * return a + b + c + d + e * } * ) * ``` */ static map5<A1,A2,A3,A4,A5,R>( fa1: Try<A1>, fa2: Try<A2>, fa3: Try<A3>, fa4: Try<A4>, fa5: Try<A5>, f: (a1: A1, a2: A2, a3: A3, a4: A4, a5: A5) => R): Try<R> { if (fa1.isFailure()) return fa1 if (fa2.isFailure()) return fa2 if (fa3.isFailure()) return fa3 if (fa4.isFailure()) return fa4 if (fa5.isFailure()) return fa5 try { return Success(f( fa1.value as A1, fa2.value as A2, fa3.value as A3, fa4.value as A4, fa5.value as A5 )) } catch (e) { return Failure(e) } } /** * Maps 6 `Try` values by the mapping function, returning a new * `Try` reference that is a `Success` only if all 6 `Try` values are * a `Success`, otherwise it returns the first `Failure` noticed. * * ```typescript * // Yields Success(21) * Try.map6( * Success(1), * Success(2), * Success(3), * Success(4), * Success(5), * Success(6), * * (a, b, c, d, e, f) => { * return a + b + c + d + e + f * } * ) * * // Yields Failure, because the second arg is a Failure * Try.map6( * Success(1), * Failure("error"), * Success(3), * Success(4), * Success(5), * Success(6), * * (a, b, c, d, e, f) => { * return a + b + c + d + e + f * } * ) * ``` */ static map6<A1,A2,A3,A4,A5,A6,R>( fa1: Try<A1>, fa2: Try<A2>, fa3: Try<A3>, fa4: Try<A4>, fa5: Try<A5>, fa6: Try<A6>, f: (a1: A1, a2: A2, a3: A3, a4: A4, a5: A5, a6: A6) => R): Try<R> { if (fa1.isFailure()) return fa1 if (fa2.isFailure()) return fa2 if (fa3.isFailure()) return fa3 if (fa4.isFailure()) return fa4 if (fa5.isFailure()) return fa5 if (fa6.isFailure()) return fa6 try { return Success(f( fa1.value as A1, fa2.value as A2, fa3.value as A3, fa4.value as A4, fa5.value as A5, fa6.value as A6 )) } catch (e) { return Failure(e) } } /** * Keeps calling `f` until a `Right(b)` is returned. * * Based on Phil Freeman's * [Stack Safety for Free]{@link http://functorial.com/stack-safety-for-free/index.pdf}. * * Described in `FlatMap.tailRecM`. */ static tailRecM<A, B>(a: A, f: (a: A) => Try<Either<A, B>>): Try<B> { let cursor = a while (true) { try { const result = f(cursor) if (result.isFailure()) return result as any const some = result.get() if (some.isRight()) return Success(some.value) cursor = some.value as A } catch (e) { return Failure(e) } } } } /** * Result of the [[Success]] data constructor, representing * successful values in the [[Try]] disjunction. * * @final */ export class TSuccess<A> extends Try<A> { public readonly value!: A constructor(value: A) { super(value, "success") } } /** * The `Success` data constructor is for building [[Try]] values that * are successful results of computations, as opposed to [[Failure]]. */ export function Success<A>(value: A): Try<A> { return new TSuccess(value) } /** * The `Success` data constructor is for building [[Try]] values that * are successful results of computations, as opposed to [[Failure]]. * * @final */ export class TFailure extends Try<never> { public readonly value!: Throwable constructor(value: Throwable) { super(value, "failure") } } /** * The `Failure` data constructor is for building [[Try]] values that * represent failures, as opposed to [[Success]]. */ export function Failure(e: Throwable): Try<never> { return new TFailure(e) } /** * Type enumerating the type classes implemented by `Try`. */ export type TryTypes = Setoid<Try<any>> & Monad<"funfix/try"> /** * Type-class implementations, compatible with the `static-land` * and `funland` specifications. * * See [funland-js.org](https://funland-js.org). */ export const TryModule: TryTypes = { // Setoid equals: (x, y) => x ? x.equals(y) : !y, // Functor map: <A, B>(f: (a: A) => B, fa: Try<A>) => fa.map(f), // Apply ap: <A, B>(ff: Try<(a: A) => B>, fa: Try<A>): Try<B> => fa.ap(ff), // Applicative of: Try.pure, // Chain chain: <A, B>(f: (a: A) => Try<B>, fa: Try<A>): Try<B> => fa.flatMap(f), // ChainRec chainRec: <A, B>(f: <C>(next: (a: A) => C, done: (b: B) => C, a: A) => Try<C>, a: A): Try<B> => Try.tailRecM(a, a => f(Either.left as any, Either.right as any, a)) } // Registers Fantasy-Land compatible symbols fantasyLandRegister(Try, TryModule, TryModule) /** * Reusable reference, to use in {@link Try.unit}. * * @private * @hidden */ const tryUnitRef: Try<void> = Success(undefined)
the_stack
import { DummyManager, MockComm } from './dummy-manager'; import { expect } from 'chai'; import { IBackboneModelOptions } from '../../lib/'; import * as widgets from '../../lib/'; const WidgetModel = widgets.WidgetModel; import * as chai from 'chai'; import * as sinon from 'sinon'; import sinonChai from 'sinon-chai'; chai.use(sinonChai); describe('unpack_models', function () { beforeEach(async function () { this.manager = new DummyManager(); this.widgetA = await this.manager.new_widget({ model_name: 'WidgetModel', model_module: '@jupyter-widgets/base', model_module_version: '1.2.0', view_name: 'WidgetView', view_module: '@jupyter-widgets/base', view_module_version: '1.2.0', model_id: 'widgetA', }); this.widgetB = await this.manager.new_widget({ model_name: 'WidgetModel', model_module: '@jupyter-widgets/base', model_module_version: '1.2.0', view_name: 'WidgetView', view_module: '@jupyter-widgets/base', view_module_version: '1.2.0', model_id: 'widgetB', }); }); it('unpacks strings', async function () { const serialized = 'IPY_MODEL_widgetA'; const deserialized = this.widgetA; const value = await widgets.unpack_models(serialized, this.manager); expect(value).to.deep.equal(deserialized); }); it('recurses in arrays', async function () { const serialized = [ 'IPY_MODEL_widgetA', 'IPY_MODEL_widgetB', 'IPY_MODEL_widgetA', ]; const deserialized = [this.widgetA, this.widgetB, this.widgetA]; const value = await widgets.unpack_models(serialized, this.manager); expect(value).to.deep.equal(deserialized); }); it('recurses in objects', async function () { const serialized = { a: 'IPY_MODEL_widgetA', b: 'IPY_MODEL_widgetB' }; const deserialized = { a: this.widgetA, b: this.widgetB }; const value = await widgets.unpack_models(serialized, this.manager); expect(value).to.deep.equal(deserialized); }); it('recurses in nested objects', async function () { const serialized = { a: 'IPY_MODEL_widgetA', b: ['IPY_MODEL_widgetA', 'IPY_MODEL_widgetB', 'IPY_MODEL_widgetA'], c: { d: ['IPY_MODEL_widgetA'], e: 'IPY_MODEL_widgetB' }, }; const deserialized = { a: this.widgetA, b: [this.widgetA, this.widgetB, this.widgetA], c: { d: [this.widgetA], e: this.widgetB }, }; const value = await widgets.unpack_models(serialized, this.manager); expect(value).to.deep.equal(deserialized); }); }); describe('WidgetModel', function () { before(async function () { this.setup = async function (): Promise<void> { this.manager = new DummyManager(); this.comm = new MockComm(); sinon.spy(this.comm, 'send'); this.widget = new WidgetModel({}, { model_id: 'widget', widget_manager: this.manager, comm: this.comm, } as IBackboneModelOptions); // Create some dummy deserializers. One returns synchronously, and the // other asynchronously using a promise. this.serializeToJSON = sinon.spy(() => { return 'serialized'; }); this.widget.constructor.serializers = { times3: { deserialize: (value: number, manager: any): number => { return value * 3.0; }, }, halve: { deserialize: (value: number, manager: any): Promise<number> => { return Promise.resolve(value / 2.0); }, }, spy: { deserialize: sinon.spy((value: any, manager: any) => { return 'deserialized'; }), serialize: sinon.spy((value: any, widget: any) => { return { toJSON: this.serializeToJSON, }; }), }, }; sinon.reset(); }; await this.setup(); sinon.spy(this.widget.constructor, '_deserialize_state'); }); describe('constructor', function () { beforeEach(async function () { await this.setup(); }); it('can take initial state', function () { const widget = new WidgetModel({ a: 1, b: 'b state' }, { model_id: 'widget', widget_manager: this.manager, } as IBackboneModelOptions); expect(widget.attributes).to.deep.equal({ ...widget.defaults(), a: 1, b: 'b state', }); }); it('sets the widget_manager, id, comm, and comm_live properties', function () { const widgetDead = new WidgetModel({}, { model_id: 'widgetDead', widget_manager: this.manager, } as IBackboneModelOptions); expect(widgetDead.model_id).to.equal('widgetDead'); expect(widgetDead.widget_manager).to.equal(this.manager); expect(widgetDead.comm).to.be.undefined; expect(widgetDead.comm_live).to.be.false; const comm = new MockComm(); const widgetLive = new WidgetModel({}, { model_id: 'widgetLive', widget_manager: this.manager, comm: comm, } as IBackboneModelOptions); expect(widgetLive.model_id).to.equal('widgetLive'); expect(widgetLive.widget_manager).to.equal(this.manager); expect(widgetLive.comm).to.equal(comm); expect(widgetLive.comm_live).to.be.true; }); it('initializes state_change and views attributes', async function () { const widget = new WidgetModel({ a: 1, b: 'b state' }, { model_id: 'widget', widget_manager: this.manager, } as IBackboneModelOptions); const x = await widget.state_change; expect(x).to.be.undefined; expect(widget.views).to.deep.equal({}); }); }); describe('send', function () { beforeEach(async function () { await this.setup(); }); it('sends custom messages with the right format', function () { const comm = new MockComm(); const send = sinon.spy(comm, 'send'); const widget = new WidgetModel({}, { model_id: 'widget', widget_manager: this.manager, comm: comm, } as IBackboneModelOptions); const data1 = { a: 1, b: 'state' }; const data2 = { a: 2, b: 'state' }; const callbacks = { iopub: {} }; const buffers = [new Int8Array([1, 2, 3])]; // send two messages to make sure the throttle does not affect sending. widget.send(data1, callbacks, buffers); widget.send(data2, callbacks, buffers); expect(send).to.be.calledTwice; expect(send.getCall(0)).to.be.calledWithExactly( { method: 'custom', content: data1 }, callbacks, {}, buffers ); expect(send.getCall(1)).to.be.calledWithExactly( { method: 'custom', content: data2 }, callbacks, {}, buffers ); }); }); describe('close', function () { beforeEach(async function () { await this.setup(); }); it('calls destroy', function () { const destroyed = sinon.spy(); this.widget.on('destroy', destroyed); this.widget.close(); expect(destroyed).to.be.calledOnce; }); it('deletes the reference to the comm', function () { this.widget.close(); expect(this.widget.comm).to.be.undefined; }); it('removes views', function () { this.widget.close(); expect(this.widget.views).to.be.undefined; }); it('closes and deletes the comm', function () { const close = sinon.spy(this.comm, 'close'); this.widget.close(); expect(close).to.be.calledOnce; expect(this.widget.comm).to.be.undefined; }); it('triggers a destroy event', function () { const destroyEventCallback = sinon.spy(); this.widget.on('destroy', destroyEventCallback); this.widget.close(); expect(destroyEventCallback).to.be.calledOnce; }); it('can be called twice', function () { this.widget.close(); this.widget.close(); }); }); describe('_handle_comm_closed', function () { beforeEach(async function () { await this.setup(); }); it('closes model', function () { const closeSpy = sinon.spy(this.widget, 'close'); this.widget._handle_comm_closed({}); expect(closeSpy).to.be.calledOnce; }); it('listens to the widget close event', function () { const closeSpy = sinon.spy(this.widget, 'close'); this.widget.comm.close(); expect(closeSpy).to.be.calledOnce; }); it('triggers a comm:close model event', function () { const closeEventCallback = sinon.spy(); this.widget.on('comm:close', closeEventCallback); this.widget._handle_comm_closed({}); expect(closeEventCallback).to.be.calledOnce; }); }); describe('_handle_comm_msg', function () { beforeEach(async function () { await this.setup(); }); it('listens to widget messages', async function () { await this.widget.comm._process_msg({ content: { data: { method: 'update', state: { a: 5 }, }, }, }); console.log(this.widget.get('a')); expect(this.widget.get('a')).to.equal(5); }); it('handles update messages', async function () { const deserialize = this.widget.constructor._deserialize_state; const setState = sinon.spy(this.widget, 'set_state'); const state_change = this.widget._handle_comm_msg({ content: { data: { method: 'update', state: { a: 5 }, }, }, }); expect(this.widget.state_change).to.equal(state_change); await state_change; expect(deserialize).to.be.calledOnce; expect(setState).to.be.calledOnce; expect(deserialize).to.be.calledBefore(setState); expect(this.widget.get('a')).to.equal(5); }); it('updates handle various types of binary buffers', async function () { const buffer1 = new Uint8Array([1, 2, 3]); const buffer2 = new Float64Array([2.3, 6.4]); const buffer3 = new Int16Array([10, 20, 30]); await this.widget._handle_comm_msg({ content: { data: { method: 'update', state: { a: 5, c: ['start', null, {}] }, buffer_paths: [['b'], ['c', 1], ['c', 2, 'd']], }, }, buffers: [buffer1, buffer2.buffer, new DataView(buffer3.buffer)], }); expect(this.widget.get('a')).to.equal(5); expect(this.widget.get('b')).to.deep.equal(new DataView(buffer1.buffer)); expect(this.widget.get('c')).to.deep.equal([ 'start', new DataView(buffer2.buffer), { d: new DataView(buffer3.buffer) }, ]); }); it('handles custom deserialization', async function () { await this.widget._handle_comm_msg({ content: { data: { method: 'update', state: { halve: 10, times3: 4 }, }, }, }); expect(this.widget.get('halve')).to.equal(5); expect(this.widget.get('times3')).to.equal(12); }); it('handles custom messages', function () { const customEventCallback = sinon.spy(); this.widget.on('msg:custom', customEventCallback); this.widget._handle_comm_msg({ content: { data: { method: 'custom' }, }, }); expect(customEventCallback).to.be.calledOnce; }); }); describe('_deserialize_state', function () { beforeEach(async function () { await this.setup(); }); it('deserializes simple JSON state', async function () { const state = await this.widget.constructor._deserialize_state( { a: 10, b: [{ c: 'test1', d: ['test2'] }, 20] }, this.manager ); expect(state.a).to.equal(10); expect(state.b).to.deep.equal([{ c: 'test1', d: ['test2'] }, 20]); }); it('respects custom serializers', async function () { const state = await this.widget.constructor._deserialize_state( { times3: 2.0, halve: 2.0, c: 2.0 }, this.manager ); expect(state.times3).to.equal(6.0); expect(state.halve).to.equal(1.0); expect(state.c).to.equal(2.0); }); it('calls the deserializer with appropriate arguments', async function () { await this.widget.constructor._deserialize_state( { spy: 'value' }, this.manager ); const spy = this.widget.constructor.serializers.spy.deserialize; expect(spy).to.be.calledOnce; expect(spy).to.be.calledWithExactly('value', this.manager); }); }); describe('serialize', function () { beforeEach(async function () { await this.setup(); }); it('does simple serialization by copying values', function () { const b = { c: 'start' }; const state = { a: 5, b: b, }; const serialized_state = this.widget.serialize(state); // b state was copied expect(serialized_state.b).to.not.equal(b); expect(serialized_state).to.deep.equal({ a: 5, b: b }); }); it('serializes null values', function () { const state_with_null = { a: 5, b: null as any, }; const serialized_state = this.widget.serialize(state_with_null); expect(serialized_state.b).to.equal(null); }); it('calls custom serializers with appropriate arguments', function () { this.widget.serialize({ spy: 'value' }); const spy = this.widget.constructor.serializers.spy.serialize; expect(spy).to.be.calledWithExactly('value', this.widget); }); it('calls toJSON method if possible', function () { const serialized_state = this.widget.serialize({ spy: 'value' }); const spy = this.serializeToJSON; expect(spy).to.be.calledOnce; expect(serialized_state).to.deep.equal({ spy: 'serialized' }); }); }); describe('_handle_comm_msg', function () { beforeEach(async function () { await this.setup(); }); it('handles update messages', async function () { const deserialize = this.widget.constructor._deserialize_state; const setState = sinon.spy(this.widget, 'set_state'); const state_change = this.widget._handle_comm_msg({ content: { data: { method: 'update', state: { a: 5 }, }, }, }); expect(this.widget.state_change).to.equal(state_change); await state_change; expect(deserialize).to.be.calledOnce; expect(setState).to.be.calledOnce; expect(deserialize).to.be.calledBefore(setState); expect(this.widget.get('a')).to.equal(5); }); it('updates handle various types of binary buffers', async function () { const buffer1 = new Uint8Array([1, 2, 3]); const buffer2 = new Float64Array([2.3, 6.4]); const buffer3 = new Int16Array([10, 20, 30]); await this.widget._handle_comm_msg({ content: { data: { method: 'update', state: { a: 5, c: ['start', null, {}] }, buffer_paths: [['b'], ['c', 1], ['c', 2, 'd']], }, }, buffers: [buffer1, buffer2.buffer, new DataView(buffer3.buffer)], }); expect(this.widget.get('a')).to.equal(5); expect(this.widget.get('b')).to.deep.equal(new DataView(buffer1.buffer)); expect(this.widget.get('c')).to.deep.equal([ 'start', new DataView(buffer2.buffer), { d: new DataView(buffer3.buffer) }, ]); }); it('handles custom deserialization', async function () { await this.widget._handle_comm_msg({ content: { data: { method: 'update', state: { halve: 10, times3: 4 }, }, }, }); expect(this.widget.get('halve')).to.equal(5); expect(this.widget.get('times3')).to.equal(12); }); it('handles custom messages', function () { const customEventCallback = sinon.spy(); this.widget.on('msg:custom', customEventCallback); this.widget._handle_comm_msg({ content: { data: { method: 'custom' }, }, }); expect(customEventCallback).to.be.calledOnce; }); }); describe('set_state', function () { beforeEach(async function () { await this.setup(); }); it('sets the state of the widget', function () { expect(this.widget.get('a')).to.be.undefined; expect(this.widget.get('b')).to.be.undefined; this.widget.set_state({ a: 2, b: 3 }); expect(this.widget.get('a')).to.equal(2); expect(this.widget.get('b')).to.equal(3); }); }); describe('set', function () { beforeEach(async function () { await this.setup(); }); it('triggers change events', async function () { const changeA = sinon.spy(function changeA() { return; }); const change = sinon.spy(function change() { return; }); this.widget.on('change:a', changeA); this.widget.on('change', change); this.widget.set('a', 100); expect(changeA).to.be.calledOnce; expect(changeA).to.be.calledWith(this.widget, 100); expect(changeA).to.be.calledBefore(change); expect(change).to.be.calledWith(this.widget); }); it('handles multiple values to set', function () { expect(this.widget.get('a')).to.be.undefined; expect(this.widget.get('b')).to.be.undefined; this.widget.set({ a: 2, b: 3 }); expect(this.widget.get('a')).to.equal(2); expect(this.widget.get('b')).to.equal(3); }); }); describe('save_changes', function () { beforeEach(async function () { await this.setup(); }); it('remembers changes across multiple set calls', function () { sinon.spy(this.widget, 'save'); expect(this.widget.get('a')).to.be.undefined; expect(this.widget.get('b')).to.be.undefined; this.widget.set('a', 2); this.widget.set('b', 5); this.widget.save_changes(); expect(this.widget.save).to.be.calledWith({ a: 2, b: 5 }); }); it('will not sync changes done by set_state', function () { sinon.spy(this.widget, 'save'); expect(this.widget.get('a')).to.be.undefined; expect(this.widget.get('b')).to.be.undefined; this.widget.on('change:a', () => { this.widget.set('b', 15); }); this.widget.set_state({ a: 10 }); expect(this.widget.get('a')).to.equal(10); expect(this.widget.get('b')).to.equal(15); this.widget.save_changes(); expect(this.widget.save).to.be.calledWith({ b: 15 }); }); }); describe('get_state', function () { beforeEach(async function () { await this.setup(); }); it('gets all of the state', function () { this.widget.set('a', 'get_state test'); expect(this.widget.get_state()).to.deep.equal({ _model_module: '@jupyter-widgets/base', _model_name: 'WidgetModel', _model_module_version: '2.0.0', _view_module: '@jupyter-widgets/base', _view_name: null, _view_module_version: '2.0.0', _view_count: null, a: 'get_state test', }); }); it('drop_defaults is respected', function () { this.widget.set('a', 'get_state test'); expect(this.widget.get_state(true)).to.deep.equal({ a: 'get_state test', }); }); }); describe('callbacks', function () { beforeEach(async function () { await this.setup(); }); it('returns a blank object', function () { expect(this.widget.callbacks()).to.deep.equal({}); }); }); describe('sync', function () { beforeEach(async function () { await this.setup(); }); it('respects the message throttle', function () { const send = sinon.spy(this.widget, 'send_sync_message'); this.widget.set('a', 'sync test'); this.widget.save_changes(); this.widget.set('a', 'another sync test'); this.widget.set('b', 'change b'); this.widget.save_changes(); this.widget.set('b', 'change b again'); this.widget.save_changes(); // check that one sync message went through expect(send).to.be.calledOnce; expect(send).to.be.calledWith({ a: 'sync test', }); // have the comm send a status idle message this.widget._handle_status({ content: { execution_state: 'idle', }, }); // check that the other sync message went through with the updated values expect(send.secondCall).to.be.calledWith({ a: 'another sync test', b: 'change b again', }); }); it('Initial values are *not* sent on creation', function () { expect(this.comm.send.callCount).to.equal(0); }); }); describe('send_sync_message', function () { beforeEach(async function () { await this.setup(); }); it('sends a message', function () { this.widget.send_sync_message( { a: 'send sync message', b: 'b value', }, {} ); expect(this.comm.send).to.be.calledWith({ method: 'update', state: { a: 'send sync message', b: 'b value', }, buffer_paths: [], }); }); it('handles buffers in messages', function () { const buffer = new Uint8Array([1, 2, 3]); this.widget.send_sync_message({ a: buffer, }); expect(this.comm.send.args[0][0]).to.deep.equal({ method: 'update', state: {}, buffer_paths: [['a']], }); expect(this.comm.send.args[0][3]).to.deep.equal([buffer.buffer]); }); }); describe('on_some_change', function () { beforeEach(async function () { await this.setup(); }); it('is called once for multiple change notifications', async function () { const changeCallback = sinon.spy(); const someChangeCallback = sinon.spy(); this.widget.on('change:a change:b', changeCallback); this.widget.on_some_change(['a', 'b'], someChangeCallback); this.widget.set_state({ a: true, b: true }); expect(changeCallback.callCount).to.equal(2); expect(someChangeCallback).to.be.calledOnce; }); }); describe('toJSON', function () { beforeEach(async function () { await this.setup(); }); it('encodes the widget', function () { expect(this.widget.toJSON()).to.equal( `IPY_MODEL_${this.widget.model_id}` ); }); }); });
the_stack
import { FontProps } from '..' // Unit tests forked from https://github.com/bramstein/css-font-FontProps.fromr/blob/master/test/FontProps.fromr-test.js describe('FontProps', function () { test('returns null on invalid css font values', function () { expect(FontProps.from.bind(null, (''))).toThrowError() expect(FontProps.from.bind(null, 'Arial')).toThrowError() expect(FontProps.from.bind(null, '12px')).toThrowError() expect(FontProps.from.bind(null, '12px/16px')).toThrowError() expect(FontProps.from.bind(null, 'bold 12px/16px')).toThrowError() }) test('ignores non-terminated strings', function () { expect(FontProps.from.bind(null, '12px "Comic')).toThrowError() expect(FontProps.from.bind(null, '12px "Comic, serif')).toThrowError() expect(FontProps.from.bind(null, '12px \'Comic')).toThrowError() expect(FontProps.from.bind(null, '12px \'Comic, serif')).toThrowError() }) test('FontProps.froms a simple font specification correctly', function () { expect(FontProps.from('12px serif')).toEqual({ 'font-size': '12px', 'font-family': ['serif'] }) }) test('returns multiple font families', function () { expect(FontProps.from('12px Arial, Verdana, serif')).toEqual({ 'font-size': '12px', 'font-family': ['Arial', 'Verdana', 'serif'] }) }) test('handles quoted family names correctly', function () { expect(FontProps.from('12px "Times New Roman"')).toEqual({ 'font-size': '12px', 'font-family': ['"Times New Roman"'] }) expect(FontProps.from('12px \'Times New Roman\'')).toEqual({ 'font-size': '12px', 'font-family': ['\'Times New Roman\''] }) expect(FontProps.from('12px "Times\\\' New Roman"')).toEqual({ 'font-size': '12px', 'font-family': ['"Times\\\' New Roman"'] }) expect(FontProps.from('12px \'Times\\" New Roman\'')).toEqual({ 'font-size': '12px', 'font-family': ['\'Times\\" New Roman\''] }) expect(FontProps.from('12px "Times\\" New Roman"')).toEqual({ 'font-size': '12px', 'font-family': ['"Times\\" New Roman"'] }) expect(FontProps.from('12px \'Times\\\' New Roman\'')).toEqual({ 'font-size': '12px', 'font-family': ['\'Times\\\' New Roman\''] }) }) test('handles unquoted identifiers correctly', function () { expect(FontProps.from('12px Times New Roman')).toEqual({ 'font-size': '12px', 'font-family': ['Times New Roman'] }) expect(FontProps.from('12px Times New Roman, Comic Sans MS')).toEqual({ 'font-size': '12px', 'font-family': ['Times New Roman', 'Comic Sans MS'] }) }) // Examples taken from: http://mathiasbynens.be/notes/unquoted-font-family test('correctly returns null on invalid identifiers', function () { expect(FontProps.from.bind(null, '12px Red/Black')).toThrowError() expect(FontProps.from.bind(null, '12px \'Lucida\' Grande')).toThrowError() expect(FontProps.from.bind(null, '12px Ahem!')).toThrowError() expect(FontProps.from.bind(null, '12px Hawaii 5-0')).toThrowError() expect(FontProps.from.bind(null, '12px $42')).toThrowError() }) test('correctly FontProps.froms escaped characters in identifiers', function () { expect(FontProps.from('12px Red\\/Black')).toEqual({ 'font-size': '12px', 'font-family': ['Red\\/Black'] }) expect(FontProps.from('12px Lucida Grande')).toEqual({ 'font-size': '12px', 'font-family': ['Lucida Grande'] }) expect(FontProps.from('12px Ahem\\!')).toEqual({ 'font-size': '12px', 'font-family': ['Ahem\\!'] }) expect(FontProps.from('12px \\$42')).toEqual({ 'font-size': '12px', 'font-family': ['\\$42'] }) expect(FontProps.from('12px €42')).toEqual({ 'font-size': '12px', 'font-family': ['€42'] }) }) test('correctly FontProps.froms font-size', function () { expect(FontProps.from('12px serif')).toEqual({ 'font-size': '12px', 'font-family': ['serif'] }) expect(FontProps.from('xx-small serif')).toEqual({ 'font-size': 'xx-small', 'font-family': ['serif'] }) expect(FontProps.from('s-small serif')).toEqual({ 'font-size': 's-small', 'font-family': ['serif'] }) expect(FontProps.from('small serif')).toEqual({ 'font-size': 'small', 'font-family': ['serif'] }) expect(FontProps.from('medium serif')).toEqual({ 'font-size': 'medium', 'font-family': ['serif'] }) expect(FontProps.from('large serif')).toEqual({ 'font-size': 'large', 'font-family': ['serif'] }) expect(FontProps.from('x-large serif')).toEqual({ 'font-size': 'x-large', 'font-family': ['serif'] }) expect(FontProps.from('xx-large serif')).toEqual({ 'font-size': 'xx-large', 'font-family': ['serif'] }) expect(FontProps.from('larger serif')).toEqual({ 'font-size': 'larger', 'font-family': ['serif'] }) expect(FontProps.from('smaller serif')).toEqual({ 'font-size': 'smaller', 'font-family': ['serif'] }) }) test('correctly FontProps.froms lengths', function () { expect(FontProps.from('1px serif')).toEqual({ 'font-size': '1px', 'font-family': ['serif'] }) expect(FontProps.from('1em serif')).toEqual({ 'font-size': '1em', 'font-family': ['serif'] }) expect(FontProps.from('1ex serif')).toEqual({ 'font-size': '1ex', 'font-family': ['serif'] }) expect(FontProps.from('1ch serif')).toEqual({ 'font-size': '1ch', 'font-family': ['serif'] }) expect(FontProps.from('1rem serif')).toEqual({ 'font-size': '1rem', 'font-family': ['serif'] }) expect(FontProps.from('1vh serif')).toEqual({ 'font-size': '1vh', 'font-family': ['serif'] }) expect(FontProps.from('1vw serif')).toEqual({ 'font-size': '1vw', 'font-family': ['serif'] }) expect(FontProps.from('1vmin serif')).toEqual({ 'font-size': '1vmin', 'font-family': ['serif'] }) expect(FontProps.from('1vmax serif')).toEqual({ 'font-size': '1vmax', 'font-family': ['serif'] }) expect(FontProps.from('1mm serif')).toEqual({ 'font-size': '1mm', 'font-family': ['serif'] }) expect(FontProps.from('1cm serif')).toEqual({ 'font-size': '1cm', 'font-family': ['serif'] }) expect(FontProps.from('1in serif')).toEqual({ 'font-size': '1in', 'font-family': ['serif'] }) expect(FontProps.from('1pt serif')).toEqual({ 'font-size': '1pt', 'font-family': ['serif'] }) expect(FontProps.from('1pc serif')).toEqual({ 'font-size': '1pc', 'font-family': ['serif'] }) }) test('returns null when it fails to FontProps.from a font-size', function () { expect(FontProps.from.bind(null, '1 serif')).toThrowError() expect(FontProps.from.bind(null, 'xxx-small serif')).toThrowError() expect(FontProps.from.bind(null, '1bs serif')).toThrowError() expect(FontProps.from.bind(null, '100 % serif')).toThrowError() }) test('correctly FontProps.froms percentages', function () { expect(FontProps.from('100% serif')).toEqual({ 'font-size': '100%', 'font-family': ['serif'] }) }) test('correctly FontProps.froms numbers', function () { expect(FontProps.from('1px serif')).toEqual({ 'font-size': '1px', 'font-family': ['serif'] }) expect(FontProps.from('1.1px serif')).toEqual({ 'font-size': '1.1px', 'font-family': ['serif'] }) expect(FontProps.from('-1px serif')).toEqual({ 'font-size': '-1px', 'font-family': ['serif'] }) expect(FontProps.from('-1.1px serif')).toEqual({ 'font-size': '-1.1px', 'font-family': ['serif'] }) expect(FontProps.from('+1px serif')).toEqual({ 'font-size': '+1px', 'font-family': ['serif'] }) expect(FontProps.from('+1.1px serif')).toEqual({ 'font-size': '+1.1px', 'font-family': ['serif'] }) expect(FontProps.from('.1px serif')).toEqual({ 'font-size': '.1px', 'font-family': ['serif'] }) expect(FontProps.from('+.1px serif')).toEqual({ 'font-size': '+.1px', 'font-family': ['serif'] }) expect(FontProps.from('-.1px serif')).toEqual({ 'font-size': '-.1px', 'font-family': ['serif'] }) }) test('returns null when it fails to FontProps.from a number', function () { expect(FontProps.from.bind(null, '12.px serif')).toThrowError() expect(FontProps.from.bind(null, '+---12.2px serif')).toThrowError() expect(FontProps.from.bind(null, '12.1.1px serif')).toThrowError() expect(FontProps.from.bind(null, '10e3px serif')).toThrowError() }) test('correctly FontProps.froms line-height', function () { expect(FontProps.from('12px/16px serif')).toEqual({ 'font-size': '12px', 'line-height': '16px', 'font-family': ['serif'] }) expect(FontProps.from('12px/1.5 serif')).toEqual({ 'font-size': '12px', 'line-height': '1.5', 'font-family': ['serif'] }) expect(FontProps.from('12px/normal serif')).toEqual({ 'font-size': '12px', 'font-family': ['serif'] }) expect(FontProps.from('12px/105% serif')).toEqual({ 'font-size': '12px', 'line-height': '105%', 'font-family': ['serif'] }) }) test('correctly FontProps.froms font-style', function () { expect(FontProps.from('italic 12px serif')).toEqual({ 'font-size': '12px', 'font-style': 'italic', 'font-family': ['serif'] }) expect(FontProps.from('oblique 12px serif')).toEqual({ 'font-size': '12px', 'font-style': 'oblique', 'font-family': ['serif'] }) expect(FontProps.from('oblique 20deg 12px serif')).toEqual({ 'font-size': '12px', 'font-style': 'oblique 20deg', 'font-family': ['serif'] }) expect(FontProps.from('oblique 0.02turn 12px serif')).toEqual({ 'font-size': '12px', 'font-style': 'oblique 0.02turn', 'font-family': ['serif'] }) expect(FontProps.from('oblique .04rad 12px serif')).toEqual({ 'font-size': '12px', 'font-style': 'oblique .04rad', 'font-family': ['serif'] }) }) test('correctly FontProps.froms font-variant', function () { expect(FontProps.from('small-caps 12px serif')).toEqual({ 'font-size': '12px', 'font-variant': 'small-caps', 'font-family': ['serif'] }) }) test('correctly FontProps.froms font-weight', function () { expect(FontProps.from('bold 12px serif')).toEqual({ 'font-size': '12px', 'font-weight': 'bold', 'font-family': ['serif'] }) expect(FontProps.from('bolder 12px serif')).toEqual({ 'font-size': '12px', 'font-weight': 'bolder', 'font-family': ['serif'] }) expect(FontProps.from('lighter 12px serif')).toEqual({ 'font-size': '12px', 'font-weight': 'lighter', 'font-family': ['serif'] }) for (let i = 1; i <= 10; i += 1) { expect(FontProps.from(i * 100 + ' 12px serif')).toEqual({ 'font-size': '12px', 'font-weight': String(i * 100), 'font-family': ['serif'] }) } expect(FontProps.from('1 12px serif')).toEqual({ 'font-size': '12px', 'font-weight': '1', 'font-family': ['serif'] }) expect(FontProps.from('723 12px serif')).toEqual({ 'font-size': '12px', 'font-weight': '723', 'font-family': ['serif'] }) expect(FontProps.from('1000 12px serif')).toEqual({ 'font-size': '12px', 'font-weight': '1000', 'font-family': ['serif'] }) expect(FontProps.from('1000.00 12px serif')).toEqual({ 'font-size': '12px', 'font-weight': '1000.00', 'font-family': ['serif'] }) expect(FontProps.from('1e3 12px serif')).toEqual({ 'font-size': '12px', 'font-weight': '1e3', 'font-family': ['serif'] }) expect(FontProps.from('1e+1 12px serif')).toEqual({ 'font-size': '12px', 'font-weight': '1e+1', 'font-family': ['serif'] }) expect(FontProps.from('200e-2 12px serif')).toEqual({ 'font-size': '12px', 'font-weight': '200e-2', 'font-family': ['serif'] }) expect(FontProps.from('123.456 12px serif')).toEqual({ 'font-size': '12px', 'font-weight': '123.456', 'font-family': ['serif'] }) expect(FontProps.from('+123 12px serif')).toEqual({ 'font-size': '12px', 'font-weight': '+123', 'font-family': ['serif'] }) expect(FontProps.from('0 12px serif')).toEqual({ 'font-size': '12px', 'font-family': ['serif'] }) expect(FontProps.from('-1 12px serif')).toEqual({ 'font-size': '12px', 'font-family': ['serif'] }) expect(FontProps.from('1000. 12px serif')).toEqual({ 'font-size': '12px', 'font-family': ['serif'] }) expect(FontProps.from('1000.1 12px serif')).toEqual({ 'font-size': '12px', 'font-family': ['serif'] }) expect(FontProps.from('1001 12px serif')).toEqual({ 'font-size': '12px', 'font-family': ['serif'] }) expect(FontProps.from('1.1e3 12px serif')).toEqual({ 'font-size': '12px', 'font-family': ['serif'] }) expect(FontProps.from('1e-2 12px serif')).toEqual({ 'font-size': '12px', 'font-family': ['serif'] }) }) test('correctly FontProps.froms font-stretch', function () { expect(FontProps.from('ultra-condensed 12px serif')).toEqual({ 'font-size': '12px', 'font-stretch': 'ultra-condensed', 'font-family': ['serif'] }) expect(FontProps.from('extra-condensed 12px serif')).toEqual({ 'font-size': '12px', 'font-stretch': 'extra-condensed', 'font-family': ['serif'] }) expect(FontProps.from('condensed 12px serif')).toEqual({ 'font-size': '12px', 'font-stretch': 'condensed', 'font-family': ['serif'] }) expect(FontProps.from('semi-condensed 12px serif')).toEqual({ 'font-size': '12px', 'font-stretch': 'semi-condensed', 'font-family': ['serif'] }) expect(FontProps.from('semi-expanded 12px serif')).toEqual({ 'font-size': '12px', 'font-stretch': 'semi-expanded', 'font-family': ['serif'] }) expect(FontProps.from('expanded 12px serif')).toEqual({ 'font-size': '12px', 'font-stretch': 'expanded', 'font-family': ['serif'] }) expect(FontProps.from('extra-expanded 12px serif')).toEqual({ 'font-size': '12px', 'font-stretch': 'extra-expanded', 'font-family': ['serif'] }) expect(FontProps.from('ultra-expanded 12px serif')).toEqual({ 'font-size': '12px', 'font-stretch': 'ultra-expanded', 'font-family': ['serif'] }) }) describe('getLengthValue', () => { test('可以测量 FontMetrics', () => { expect(FontProps.getLengthValue('1px', 'px')).toEqual(1) }) test('不支持除了 px 的其他单位', () => { for (const unit of 'pt|pc|in|cm|mm|%|em|ex|ch|rem|q'.split('|')) { expect(FontProps.getLengthValue.bind(null, `1${unit}`, 'px')).toThrowError(new TypeError(`Support 'px' only, got '${unit}'`)) } }) }) })
the_stack
/** * @license Copyright © 2013 onwards, Andrew Whewell * All rights reserved. * * Redistribution and use of this software 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 author nor the names of the program's 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 AUTHORS OF THE SOFTWARE 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. */ /** * @fileoverview Menu UI abstractions. */ namespace VRS { /** * The settings that can be passed when creating a new instance of a MenuItem. */ export interface MenuItem_Settings { /** * The unique name of the menu item. */ name: string; /** * The name of a VRS.$$ item to show for the label, or a function that returns the label text. */ labelKey?: string | VoidFuncReturning<string>; /** * The name of the jQuery UI icon (without the leading 'ui-icon-') to show against the item if labelKey has been supplied. */ jqIcon?: string | VoidFuncReturning<string>; /** * The name of the vrsIcon icon (without the leading 'vrsIcon-') to show against the item if labelKey has been supplied. */ vrsIcon?: string | VoidFuncReturning<string>; /** * A value indicating that the menu entry should be shown with a checkmark against it, or a function that returns a bool indicating same. */ checked?: boolean | VoidFuncReturning<boolean>; /** * The URL of the image to use as the label icon. */ labelImageUrl?: string | VoidFuncReturning<string>; /** * The classes to apply to the image used as a label icon. */ labelImageClasses?: string | VoidFuncReturning<string>; /** * The function that is called when the menu item is clicked. Optional if subItems are supplied. */ clickCallback?: (menuItem?: MenuItem) => void; /** * A value indicating that the menu entry should be shown with a slider against it, or a function that returns a bool indicating the same. */ showSlider?: boolean | VoidFuncReturning<boolean>; /** * The minimum value for the slider's range or a function that returns the minimum value. */ sliderMinimum?: number | VoidFuncReturning<number>; /** * The maximum value for the slider's range or a function that returns the maximum value. */ sliderMaximum?: number | VoidFuncReturning<number>; /** * The interval to jump when sliding the slider. */ sliderStep?: number | VoidFuncReturning<number>; /** * The initial value for the slider. Defaults to sliderMinimum if not supplied. */ sliderInitialValue?: number | VoidFuncReturning<number>; /** * The default value for the slider. If this is not supplied then the reset button is not shown. */ sliderDefaultValue?: number | VoidFuncReturning<number>; /** * The function that is called when the slider value changes. */ sliderCallback?: (value: number) => void; /** * An optional method called just before the menu item is used. */ initialise?: () => void; /** * Either a bool indicating whether the menu item is disabled or a method that returns a bool indicating whether the menu item is disabled. Defaults to false. */ disabled?: boolean | VoidFuncReturning<boolean>; /** * An optional array of sub-items. */ subItems?: MenuItem[]; /** * An optional object attached to the menu item. */ tag?: any; /** * An optional flag that prevents the menu from closing when the item is clicked. */ noAutoClose?: boolean; /** * An optional callback that can return true to prevent the menu option from appearing. Defaults to function that returns false. */ suppress?: () => boolean; } /** * Describes a single item within a menu. */ export class MenuItem { private _Initialise: () => void; private _Disabled: boolean | VoidFuncReturning<boolean>; private _LabelKey: string | VoidFuncReturning<string>; private _JqIcon: string | VoidFuncReturning<string>; private _VrsIcon: string | VoidFuncReturning<string>; private _Checked: boolean | VoidFuncReturning<boolean>; private _ShowSlider: boolean | VoidFuncReturning<boolean>; private _SliderMinimum: number | VoidFuncReturning<number>; private _SliderMaximum: number | VoidFuncReturning<number>; private _SliderStep: number | VoidFuncReturning<number>; private _SliderInitialValue: number | VoidFuncReturning<number>; private _SliderDefaultValue: number | VoidFuncReturning<number>; private _SliderCallback: (value: number) => void; private _LabelImageUrl: string | VoidFuncReturning<string>; private _LabelImageClasses: string | VoidFuncReturning<string>; // Kept as public fields for backwards compatibility name: string; clickCallback: (menuItem?: MenuItem) => void; subItems: MenuItem[]; subItemsNormalised: MenuItem[]; noAutoClose: boolean; tag: any; suppress: () => boolean; constructor(settings: MenuItem_Settings) { if(!settings) throw 'You must supply a settings object'; if(!settings.name) throw 'You must supply a unique name for the menu item'; if(!settings.labelKey) throw 'You must supply a label key'; this._Initialise = settings.initialise; this._Disabled = settings.disabled; this._LabelKey = settings.labelKey; this._JqIcon = settings.jqIcon; this._VrsIcon = settings.vrsIcon; this._Checked = settings.checked; this._LabelImageUrl = settings.labelImageUrl; this._LabelImageClasses = settings.labelImageClasses; this._ShowSlider = settings.showSlider; this._SliderMinimum = settings.sliderMinimum; this._SliderMaximum = settings.sliderMaximum; this._SliderStep = settings.sliderStep; this._SliderInitialValue = settings.sliderInitialValue; this._SliderDefaultValue = settings.sliderDefaultValue; this._SliderCallback = settings.sliderCallback; this.name = settings.name; this.clickCallback = settings.clickCallback; this.subItems = settings.subItems || []; this.subItemsNormalised = []; this.noAutoClose = !!settings.noAutoClose; this.tag = settings.tag; this.suppress = settings.suppress || function() { return false; }; } /** * Initialises the menu item. */ initialise() { if(this._Initialise) { this._Initialise(); } } /** * Returns true if the menu item is disabled. */ isDisabled() : boolean { return Utility.ValueOrFuncReturningValue(this._Disabled, false); } /** * Returns the label text to use. */ getLabelText() { return VRS.globalisation.getText(this._LabelKey); } /** * Returns the jQueryUI icon or null if there is no jQueryUI icon. */ getJQueryIcon() : string { return Utility.ValueOrFuncReturningValue(this._JqIcon, null); } /** * Returns the VRS icon or null if there is no VRS icon. */ getVrsIcon() : string { var result = Utility.ValueOrFuncReturningValue(this._VrsIcon, null); if(!this._VrsIcon && this._Checked !== undefined) { var isChecked = Utility.ValueOrFuncReturningValue(this._Checked, false); if(isChecked) { result = 'checkmark'; } } return result; } /** * Returns the label image URL or null if there is no label image URL. */ getLabelImageUrl() : string { return Utility.ValueOrFuncReturningValue(this._LabelImageUrl, null); } /** * Returns the label image classes or null if there are no label image classes. */ getLabelImageClasses() : string { return Utility.ValueOrFuncReturningValue(this._LabelImageClasses, null); } /** * Returns a jQuery object wrapping a newly created img element for the label image or null if the menu has no * label image URL. Note that the image has no explicit width or height. */ getLabelImageElement() : JQuery { var result = null; var url = this.getLabelImageUrl(); if(url) { result = $('<img/>').attr('src', url); var classes = this.getLabelImageClasses(); if(classes) { result.addClass(classes); } } return result; } showSlider() : boolean { return this._ShowSlider !== undefined && Utility.ValueOrFuncReturningValue(this._ShowSlider, false); } getSliderMinimum() : number { return this._SliderMinimum !== undefined ? Utility.ValueOrFuncReturningValue(this._SliderMinimum, 0) : 0; } getSliderMaximum() : number { return this._SliderMaximum !== undefined ? Utility.ValueOrFuncReturningValue(this._SliderMaximum, 100) : 100; } getSliderStep() : number { return this._SliderStep !== undefined ? Utility.ValueOrFuncReturningValue(this._SliderStep, 1) : 1; } getSliderInitialValue() : number { return this._SliderInitialValue !== undefined ? Utility.ValueOrFuncReturningValue(this._SliderInitialValue, this.getSliderMinimum()) : this.getSliderMinimum(); } getSliderDefaultValue() : number { return this._SliderDefaultValue !== undefined ? Utility.ValueOrFuncReturningValue(this._SliderDefaultValue, this.getSliderMinimum()) : null; } callSliderCallback(value: number) { if(this._SliderCallback) { this._SliderCallback(value); } } } /** * The settings to use when creating a new instance of Menu. */ export interface Menu_Settings { items: MenuItem[]; } /** * A class that collects together a bunch of menu items to form a menu structure. */ export class Menu { private _Dispatcher = new VRS.EventHandler({ name: 'VRS.Menu' }); private _Events = { beforeAddingFixedMenuItems: 'beforeAddingFixedMenuItems', afterAddingFixedMenuItems: 'afterAddingFixedMenuItems' }; /** * The settings used to initialise the class. */ private _Settings: Menu_Settings; /** * The top-level items to show when the user asks for the menu. Null entries in the list represent separators. */ private _TopLevelMenuItems: MenuItem[] = []; getTopLevelMenuItems() : MenuItem[] { return this._TopLevelMenuItems; } /** * Raised before buildMenuItems adds the fixed top-level menu items to the menu structure that it returns. Gets * passed the array of menu items as currently constructed - you can modify this array but you must not call * buildMenuItems in the handler. Note that multiple consecutive separators will be removed before buildMenuItems * returns, you don't need to remove them yourself. */ hookBeforeAddingFixedMenuItems(callback: (menu: Menu, menuItems: MenuItem[]) => void, forceThis?: Object) : IEventHandle { return this._Dispatcher.hook(this._Events.beforeAddingFixedMenuItems, callback, forceThis); } /** * Raised after buildMenuItems adds the fixed top-level menu items to the menu structure that it returns. Gets * passed the array of menu items as currently constructed - you can modify this array but you must not call * buildMenuItems in the handler. Note that multiple consecutive separators will be removed before buildMenuItems * returns, you don't need to remove them yourself. */ hookAfterAddingFixedMenuItems(callback: (menu: Menu, menuItems: MenuItem[]) => void, forceThis?: Object) : IEventHandle { return this._Dispatcher.hook(this._Events.afterAddingFixedMenuItems, callback, forceThis); } /** * Unhooks a previously hooked event on the object. */ unhook(hookResult: IEventHandle) { this._Dispatcher.unhook(hookResult); } /** * Creates a new object. */ constructor(settings?: Menu_Settings) { this._Settings = $.extend({ items: [] }, settings); var self = this; $.each(this._Settings.items, function(idx, menuItem) { self._TopLevelMenuItems.push(menuItem); }); } /** * Constructs the set of menu items to display to the user. */ buildMenuItems() : MenuItem[] { var rawItems: MenuItem[] = []; this._Dispatcher.raise(this._Events.beforeAddingFixedMenuItems, [ this, rawItems ]); rawItems = rawItems.concat(this._TopLevelMenuItems); this._Dispatcher.raise(this._Events.afterAddingFixedMenuItems, [ this, rawItems ]); return this.normaliseMenu(rawItems); } /** * Returns a copy of the array passed across with unwanted duplicates etc. filtered out. */ private normaliseMenu(rawItems: MenuItem[]) : MenuItem[] { var result: MenuItem[] = []; var previousIsSeparator = true; var length = rawItems.length; for(var i = 0;i < length;++i) { var menuItem = rawItems[i]; var suppress = menuItem ? menuItem.suppress() : false; if(!suppress) { if(menuItem) { previousIsSeparator = false; menuItem.subItemsNormalised = this.normaliseMenu(menuItem.subItems); } else { if(previousIsSeparator) continue; previousIsSeparator = true; } result.push(menuItem); } } if(result.length && previousIsSeparator) result.splice(result.length - 1, 1); return result; } /** * Returns the menu item with the given name. If a menuItems array is supplied then the search is constrained * to that array (including sub-items in the array), otherwise the top-level menu items are searched. If the * menu cannot be found then null is returned. */ findMenuItemForName(name: string, menuItems?: MenuItem[], useNormalisedSubItems?: boolean) : MenuItem { var result: MenuItem = null; if(!menuItems) menuItems = this.getTopLevelMenuItems(); var length = menuItems.length; for(var i = 0;i < length;++i) { var menuItem = menuItems[i]; if(!menuItem) continue; if(menuItem.name === name) { result = menuItem; break; } var subItems = useNormalisedSubItems ? menuItem.subItemsNormalised : menuItem.subItems; if(subItems.length) { result = this.findMenuItemForName(name, subItems, useNormalisedSubItems); if(result) break; } } return result; } } }
the_stack
import { FocusMonitor, FocusOrigin } from '@angular/cdk/a11y'; import { coerceBooleanProperty } from '@angular/cdk/coercion'; import { UniqueSelectionDispatcher } from '@angular/cdk/collections'; import { AfterContentInit, AfterViewInit, ChangeDetectionStrategy, ChangeDetectorRef, Component, ContentChildren, Directive, ElementRef, EventEmitter, forwardRef, HostListener, Input, OnDestroy, OnInit, Optional, Output, QueryList, ViewChild, ViewEncapsulation, } from '@angular/core'; import { ControlValueAccessor, NG_VALUE_ACCESSOR } from '@angular/forms'; export class RadioChange { constructor( public source: RadioButtonComponent, public value: any, ) { } } export const RADIO_GROUP_CONTROL_VALUE_ACCESSOR: any = { provide: NG_VALUE_ACCESSOR, useExisting: forwardRef(() => RadioGroupDirective), multi: true, }; let uniqueId = 0; @Directive({ selector: 'gd-radio-group', providers: [RADIO_GROUP_CONTROL_VALUE_ACCESSOR], host: { 'class': 'RadioGroup', 'role': 'radiogroup', }, }) export class RadioGroupDirective implements AfterContentInit, ControlValueAccessor { _controlValueAccessorChangeFn: (value: any) => void = () => {}; onTouched: () => any = () => {}; @Output() readonly change: EventEmitter<RadioChange> = new EventEmitter<RadioChange>(); @ContentChildren(forwardRef(() => RadioButtonComponent), { descendants: true }) _radios: QueryList<RadioButtonComponent>; /** Whether the `value` has been set to its initial value. */ private _isInitialized: boolean = false; constructor(private changeDetector: ChangeDetectorRef) { } /** Selected value for the radio group. */ private _value: any = null; @Input() get value(): any { return this._value; } set value(newValue: any) { if (this._value !== newValue) { // Set this before proceeding to ensure no circular loop occurs with selection. this._value = newValue; this.updateSelectedRadioFromValue(); this._checkSelectedRadioButton(); } } /** The HTML name attribute applied to radio buttons in this group. */ private _name: string = `gd-radio-group-${uniqueId++}`; @Input() get name(): string { return this._name; } set name(value: string) { this._name = value; this.updateRadioButtonNames(); } /** The currently selected radio button. Should match value. */ private _selected: RadioButtonComponent | null = null; @Input() get selected() { return this._selected; } set selected(selected: any | null) { this._selected = selected; this.value = selected ? selected.value : null; this._checkSelectedRadioButton(); } private _disabled: boolean; /** Whether the radio group is disabled */ @Input() get disabled(): boolean { return this._disabled; } set disabled(value) { this._disabled = coerceBooleanProperty(value); this._markRadiosForCheck(); } _checkSelectedRadioButton(): void { if (this._selected && !this._selected.checked) { this._selected.checked = true; } } ngAfterContentInit(): void { // Mark this component as initialized in AfterContentInit because the initial value can // possibly be set by NgModel on MatRadioGroup, and it is possible that the OnInit of the // NgModel occurs *after* the OnInit of the MatRadioGroup. this._isInitialized = true; } _touch(): void { if (this.onTouched) { this.onTouched(); } } /** Dispatch change event with current selection and group value. */ _emitChangeEvent(): void { if (this._isInitialized) { this.change.emit(new RadioChange(this._selected, this._value)); } } /** * Sets the model value. Implemented as part of ControlValueAccessor. * @param value */ writeValue(value: any) { this.value = value; this.changeDetector.markForCheck(); } /** * Registers a callback to be triggered when the model value changes. * Implemented as part of ControlValueAccessor. * @param fn Callback to be registered. */ registerOnChange(fn: (value: any) => void) { this._controlValueAccessorChangeFn = fn; } /** * Registers a callback to be triggered when the control is touched. * Implemented as part of ControlValueAccessor. * @param fn Callback to be registered. */ registerOnTouched(fn: any) { this.onTouched = fn; } /** * Sets the disabled state of the control. Implemented as a part of ControlValueAccessor. * @param isDisabled Whether the control should be disabled. */ setDisabledState(isDisabled: boolean) { this.disabled = isDisabled; this.changeDetector.markForCheck(); } _markRadiosForCheck() { if (this._radios) { this._radios.forEach(radio => radio._markForCheck()); } } private updateRadioButtonNames(): void { if (this._radios) { this._radios.forEach(radio => { radio.name = this.name; }); } } /** Updates the `selected` radio button from the internal _value state. */ private updateSelectedRadioFromValue(): void { // If the value already matches the selected radio, do nothing. const isAlreadySelected = this._selected !== null && this._selected.value === this._value; if (this._radios && !isAlreadySelected) { this._selected = null; this._radios.forEach(radio => { radio.checked = this.value === radio.value; if (radio.checked) { this._selected = radio; } }); } } } @Component({ selector: 'gd-radio-button', templateUrl: './radio.html', styleUrls: ['./radio.scss'], changeDetection: ChangeDetectionStrategy.OnPush, encapsulation: ViewEncapsulation.None, host: { 'class': 'RadioButton', '[class.RadioButton--checked]': 'checked', '[attr.id]': 'id', }, }) export class RadioButtonComponent implements AfterViewInit, OnInit, OnDestroy { @Input() name: string; radioGroup: RadioGroupDirective; @Output() readonly change: EventEmitter<RadioChange> = new EventEmitter<RadioChange>(); @ViewChild('input') _inputElement: ElementRef; private removeUniqueSelectionListener: () => void = () => {}; constructor( @Optional() radioGroup: RadioGroupDirective, public _elementRef: ElementRef, private changeDetector: ChangeDetectorRef, private focusMonitor: FocusMonitor, private radioDispatcher: UniqueSelectionDispatcher, ) { this.radioGroup = radioGroup; this.removeUniqueSelectionListener = radioDispatcher.listen((id: string, name: string) => { if (id !== this.id && name === this.name) { this.checked = false; } }); } private _id: string = `gd-radio-button-${uniqueId++}`; @Input() get id() { return this._id; } set id(value) { this._id = value; } get inputId(): string { return `${this._id}-input`; } private _checked: boolean = false; @Input() get checked(): boolean { return this._checked; } set checked(value: boolean) { const newCheckedState = coerceBooleanProperty(value); if (this._checked !== newCheckedState) { this._checked = newCheckedState; if (newCheckedState && this.radioGroup && this.radioGroup.value !== this.value) { this.radioGroup.selected = this; } else if (!newCheckedState && this.radioGroup && this.radioGroup.value === this.value) { // When unchecking the selected radio button, update the selected radio // property on the group. this.radioGroup.selected = null; } if (newCheckedState) { // Notify all radio buttons with the same name to un-check. this.radioDispatcher.notify(this.id, this.name); } this.changeDetector.markForCheck(); } } private _value: any = null; @Input() get value(): any { return this._value; } set value(value: any) { if (this._value !== value) { this._value = value; if (this.radioGroup !== null) { if (!this.checked) { // Update checked when the value changed to match the radio group's value this.checked = this.radioGroup.value === value; } if (this.checked) { this.radioGroup.selected = this; } } } } ngOnInit(): void { if (this.radioGroup) { // If the radio is inside a radio group, determine if it should be checked this.checked = this.radioGroup.value === this._value; // Copy name from parent radio group this.name = this.radioGroup.name; } } ngAfterViewInit(): void { this.focusMonitor .monitor(this._inputElement.nativeElement) .subscribe(focusOrigin => this._onInputFocusChange(focusOrigin)); } ngOnDestroy(): void { this.focusMonitor.stopMonitoring(this._inputElement.nativeElement); this.removeUniqueSelectionListener(); } _onInputClick(event: Event): void { // We have to stop propagation for click events on the visual hidden input element. // By default, when a user clicks on a label element, a generated click event will be // dispatched on the associated input element. Since we are using a label element as our // root container, the click event on the `radio-button` will be executed twice. // The real click event will bubble up, and the generated click event also tries to bubble up. // This will lead to multiple click events. // Preventing bubbling for the second event will solve that issue. event.stopPropagation(); } _onInputChange(event: Event): void { // We always have to stop propagation on the change event. // Otherwise the change event, from the input element, will bubble up and // emit its event object to the `change` output. event.stopPropagation(); const groupValueChanged = this.radioGroup && this.value !== this.radioGroup.value; this.checked = true; this._emitChangeEvent(); if (this.radioGroup) { this.radioGroup._controlValueAccessorChangeFn(this.value); this.radioGroup._touch(); if (groupValueChanged) { this.radioGroup._emitChangeEvent(); } } } _markForCheck(): void { this.changeDetector.markForCheck(); } private _emitChangeEvent(): void { this.change.emit(new RadioChange(this, this._value)); } @HostListener('focus') private onHostFocus(): void { this._inputElement.nativeElement.focus(); } private _onInputFocusChange(origin: FocusOrigin): void { if (origin) { this._elementRef.nativeElement.classList.add('RadioButton--focused'); } else { if (this.radioGroup) { this.radioGroup._touch(); } this._elementRef.nativeElement.classList.remove('RadioButton--focused'); } } }
the_stack
import { CdmCorpusDefinition, CdmEntityAttributeDefinition, CdmEntityDefinition, CdmEntityReference, CdmOperationCombineAttributes, CdmProjection, CdmTypeAttributeDefinition } from '../../../internal'; import { testHelper } from '../../testHelper'; import { projectionTestUtils } from '../../Utilities/projectionTestUtils'; import { TypeAttributeParam } from './TypeAttributeParam'; import { ProjectionOMTestUtil } from './ProjectionOMTestUtil'; /** * A test class for testing the CombineAttributes operation in a projection as well as Select 'one' in a resolution guidance */ describe('Cdm/Projection/ProjectionCombineTest', () => { /** * All possible combinations of the different resolution directives */ const resOptsCombinations: string[][] = [ [], ['referenceOnly'], ['normalized'], ['structured'], ['referenceOnly', 'normalized'], ['referenceOnly', 'structured'], ['normalized', 'structured'], ['referenceOnly', 'normalized', 'structured'] ]; /** * The path between TestDataPath and TestName. */ const testsSubpath: string = 'Cdm/Projection/ProjectionCombineTest'; /** * Test Entity Extends with a Resolution Guidance that selects 'one' */ it('TestExtends', async () => { const testName: string = 'TestExtends'; const entityName: string = 'Customer'; const corpus: CdmCorpusDefinition = testHelper.getLocalCorpus(testsSubpath, testName); for (const resOpt of resOptsCombinations) { await projectionTestUtils.loadEntityForResolutionOptionAndSave(corpus, testName, testsSubpath, entityName, resOpt); } }); /** * Test Entity Extends with a Combine Attributes operation */ it('TestExtendsProj', async () => { const testName: string = 'TestExtendsProj'; const entityName: string = 'Customer'; const corpus: CdmCorpusDefinition = testHelper.getLocalCorpus(testsSubpath, testName); for (const resOpt of resOptsCombinations) { await projectionTestUtils.loadEntityForResolutionOptionAndSave(corpus, testName, testsSubpath, entityName, resOpt); } }); /** * Test Entity Attribute with a Resolution Guidance that selects 'one' */ it('TestEA', async () => { const testName: string = 'TestEA'; const entityName: string = 'Customer'; const corpus: CdmCorpusDefinition = testHelper.getLocalCorpus(testsSubpath, testName); for (const resOpt of resOptsCombinations) { await projectionTestUtils.loadEntityForResolutionOptionAndSave(corpus, testName, testsSubpath, entityName, resOpt); } }); /** * Test Entity Attribute with a Combine Attributes operation */ it('TestEAProj', async () => { const testName: string = 'TestEAProj'; const entityName: string = 'Customer'; const corpus: CdmCorpusDefinition = testHelper.getLocalCorpus(testsSubpath, testName); for (const resOpt of resOptsCombinations) { await projectionTestUtils.loadEntityForResolutionOptionAndSave(corpus, testName, testsSubpath, entityName, resOpt); } }); /** * Test Entity Attribute with a Combine Attributes operation but IsPolymorphicSource flag set to false */ it('TestNonPolymorphicProj', async () => { const testName: string = 'TestNonPolymorphicProj'; const entityName: string = 'NewPerson'; const corpus: CdmCorpusDefinition = testHelper.getLocalCorpus(testsSubpath, testName); const entity: CdmEntityDefinition = await corpus.fetchObjectAsync<CdmEntityDefinition>(`local:/${entityName}.cdm.json/${entityName}`); const resolvedEntity: CdmEntityDefinition = await projectionTestUtils.getResolvedEntity(corpus, entity, []); // Original set of attributes: ['name', 'age', 'address', 'phoneNumber', 'email'] // Combined attributes ['phoneNumber', 'email'] into 'contactAt' expect(resolvedEntity.attributes.length) .toEqual(4); expect((resolvedEntity.attributes.allItems[0] as CdmTypeAttributeDefinition).name) .toEqual('name'); expect((resolvedEntity.attributes.allItems[1] as CdmTypeAttributeDefinition).name) .toEqual('age'); expect((resolvedEntity.attributes.allItems[2] as CdmTypeAttributeDefinition).name) .toEqual('address'); expect((resolvedEntity.attributes.allItems[3] as CdmTypeAttributeDefinition).name) .toEqual('contactAt'); }); /** * Test a Combine Attributes operation with an empty select list */ it('TestEmptyProj', async () => { const testName: string = 'TestEmptyProj'; const entityName: string = 'Customer'; const corpus: CdmCorpusDefinition = testHelper.getLocalCorpus(testsSubpath, testName); for (const resOpt of resOptsCombinations) { await projectionTestUtils.loadEntityForResolutionOptionAndSave(corpus, testName, testsSubpath, entityName, resOpt); } }); /** * Test a collection of Combine Attributes operation */ it('TestCollProj', async () => { const testName: string = 'TestCollProj'; const entityName: string = 'Customer'; const corpus: CdmCorpusDefinition = testHelper.getLocalCorpus(testsSubpath, testName); for (const resOpt of resOptsCombinations) { await projectionTestUtils.loadEntityForResolutionOptionAndSave(corpus, testName, testsSubpath, entityName, resOpt); } }); /** * Test Nested Combine Attributes operations */ it('TestNestedProj', async () => { const testName: string = 'TestNestedProj'; const entityName: string = 'Customer'; const corpus: CdmCorpusDefinition = testHelper.getLocalCorpus(testsSubpath, testName); for (const resOpt of resOptsCombinations) { await projectionTestUtils.loadEntityForResolutionOptionAndSave(corpus, testName, testsSubpath, entityName, resOpt); } }); /** * Test Multiple Nested Operations with Combine including ArrayExpansion and Rename */ it('TestMultiProj', async () => { const testName: string = 'TestMultiProj'; const entityName: string = 'Customer'; const corpus: CdmCorpusDefinition = testHelper.getLocalCorpus(testsSubpath, testName); for (const resOpt of resOptsCombinations) { if (resOpt.includes('structured')) { // Array expansion is not supported on an attribute group yet. continue; } await projectionTestUtils.loadEntityForResolutionOptionAndSave(corpus, testName, testsSubpath, entityName, resOpt); } }); /** * Test a Combine Attributes operation with condition set to false */ it('TestCondProj', async () => { const testName: string = 'TestCondProj'; const entityName: string = 'Customer'; const corpus: CdmCorpusDefinition = testHelper.getLocalCorpus(testsSubpath, testName); for (const resOpt of resOptsCombinations) { await projectionTestUtils.loadEntityForResolutionOptionAndSave(corpus, testName, testsSubpath, entityName, resOpt); } }); /** * Test Nested Combine with Rename Operation */ it('TestRenProj', async () => { const testName: string = 'TestRenProj'; const entityName: string = 'Customer'; const corpus: CdmCorpusDefinition = testHelper.getLocalCorpus(testsSubpath, testName); for (const resOpt of resOptsCombinations) { if (resOpt.includes('structured')) { // Rename attributes is not supported on an attribute group yet. continue; } await projectionTestUtils.loadEntityForResolutionOptionAndSave(corpus, testName, testsSubpath, entityName, resOpt); } }); /** * Test Entity Attribute with a Combine Attributes operation that selects a common already 'merged' attribute (e.g. IsPrimary) */ it('TestCommProj', async () => { const testName: string = 'TestCommProj'; const entityName: string = 'Customer'; const corpus: CdmCorpusDefinition = testHelper.getLocalCorpus(testsSubpath, testName); for (const resOpt of resOptsCombinations) { await projectionTestUtils.loadEntityForResolutionOptionAndSave(corpus, testName, testsSubpath, entityName, resOpt); } }); /** * Test a Combine Attributes operation by selecting missing attributes */ it('TestMissProj', async () => { const testName: string = 'TestMissProj'; const entityName: string = 'Customer'; const corpus: CdmCorpusDefinition = testHelper.getLocalCorpus(testsSubpath, testName); for (const resOpt of resOptsCombinations) { await projectionTestUtils.loadEntityForResolutionOptionAndSave(corpus, testName, testsSubpath, entityName, resOpt); } }); /** * Test a Combine Attributes operation with a different sequence of selection attributes */ it('TestSeqProj', async () => { const testName: string = 'TestSeqProj'; const entityName: string = 'Customer'; const corpus: CdmCorpusDefinition = testHelper.getLocalCorpus(testsSubpath, testName); for (const resOpt of resOptsCombinations) { await projectionTestUtils.loadEntityForResolutionOptionAndSave(corpus, testName, testsSubpath, entityName, resOpt); } }); /** * Test for object model */ it('TestEAProjOM', async () => { const className: string = 'TestProjectionCombine'; const testName: string = 'TestEAProjOM'; const entityName_Email: string = 'Email'; const attributeParams_Email: TypeAttributeParam[] = []; attributeParams_Email.push(new TypeAttributeParam(`EmailID`, `string`, `identifiedBy`)); attributeParams_Email.push(new TypeAttributeParam(`Address`, `string`, `hasA`)); attributeParams_Email.push(new TypeAttributeParam(`IsPrimary`, `boolean`, `hasA`)); const entityName_Phone: string = 'Phone'; const attributeParams_Phone: TypeAttributeParam[] = []; attributeParams_Phone.push(new TypeAttributeParam(`PhoneID`, `string`, `identifiedBy`)); attributeParams_Phone.push(new TypeAttributeParam(`Number`, `string`, `hasA`)); attributeParams_Phone.push(new TypeAttributeParam(`IsPrimary`, `boolean`, `hasA`)); const entityName_Social: string = 'Social'; const attributeParams_Social: TypeAttributeParam[] = []; attributeParams_Social.push(new TypeAttributeParam(`SocialID`, `string`, `identifiedBy`)); attributeParams_Social.push(new TypeAttributeParam(`Account`, `string`, `hasA`)); attributeParams_Social.push(new TypeAttributeParam(`IsPrimary`, `boolean`, `hasA`)); const entityName_Customer: string = 'Customer'; const attributeParams_Customer: TypeAttributeParam[] = []; attributeParams_Customer.push(new TypeAttributeParam(`CustomerName`, `string`, `hasA`)); const selectedAttributes: string[] = [`EmailID`, `PhoneID`, `SocialID`]; const util: ProjectionOMTestUtil = new ProjectionOMTestUtil(className, testName); const entity_Email: CdmEntityDefinition = util.CreateBasicEntity(entityName_Email, attributeParams_Email); util.validateBasicEntity(entity_Email, entityName_Email, attributeParams_Email); const entity_Phone: CdmEntityDefinition = util.CreateBasicEntity(entityName_Phone, attributeParams_Phone); util.validateBasicEntity(entity_Phone, entityName_Phone, attributeParams_Phone); const entity_Social: CdmEntityDefinition = util.CreateBasicEntity(entityName_Social, attributeParams_Social); util.validateBasicEntity(entity_Social, entityName_Social, attributeParams_Social); const entity_Customer: CdmEntityDefinition = util.CreateBasicEntity(entityName_Customer, attributeParams_Customer); util.validateBasicEntity(entity_Customer, entityName_Customer, attributeParams_Customer); const projection_Customer: CdmProjection = util.createProjection(entity_Customer.entityName); const typeAttribute_MergeInto: CdmTypeAttributeDefinition = util.createTypeAttribute(`MergeInto`, `string`, `hasA`); const operation_CombineAttributes: CdmOperationCombineAttributes = util.createOperationCombineAttributes(projection_Customer, selectedAttributes, typeAttribute_MergeInto); const projectionEntityRef_Customer: CdmEntityReference = util.createProjectionInlineEntityReference(projection_Customer); const entityAttribute_ContactAt: CdmEntityAttributeDefinition = util.createEntityAttribute(`ContactAt`, projectionEntityRef_Customer); entity_Customer.attributes.push(entityAttribute_ContactAt); for (const resOpts of resOptsCombinations) { await util.getAndValidateResolvedEntity(entity_Customer, resOpts); } await util.defaultManifest.saveAsAsync(util.manifestDocName, true); }); });
the_stack
const g = require('gulp') const webpack: typeof import('webpack') = require('webpack') const ForkTsCheckerWebpackPlugin = require('fork-ts-checker-webpack-plugin') const MonacoEditorWebpackPlugin = require('monaco-editor-webpack-plugin') const HtmlWebpackPlugin = require('html-webpack-plugin') const builder: typeof import('electron-builder') = require('electron-builder') const notifier = require('node-notifier') const download = require('download') const zipDir = require('zip-dir') const TsconfigPathsPlugin = require('tsconfig-paths-webpack-plugin') const glob: typeof import('fast-glob') = require('fast-glob') const os = require('os') const fs = require('fs-extra') const path = require('path') const { join, parse: pathParse } = require('path') const { spawn } = require('child_process') const NATIVE_MODULES = ['fontmanager-redux'] const paths = { src: { root: join(__dirname, './packages/'), plugins: join(__dirname, './packages/post-effect-plugins'), contribPEP: join(__dirname, './packages/contrib-posteffect'), frontend: join(__dirname, './packages/delir/'), core: join(__dirname, './packages/core/'), }, compiled: { root: join(__dirname, './prepublish/'), plugins: join(__dirname, './prepublish/plugins'), frontend: join(__dirname, './prepublish/delir/'), }, build: join(__dirname, './prepublish/'), release: join(__dirname, './release/'), } const isWindows = os.type() === 'Windows_NT' const isMacOS = os.type() === 'Darwin' const isLinux = os.type() === 'Linux' const __DEV__ = process.env.NODE_ENV === 'development' export function buildBrowserJs(done) { webpack( { mode: __DEV__ ? 'development' : 'production', target: 'electron-main', node: { __dirname: false, }, watch: __DEV__, context: paths.src.frontend, entry: { browser: ['./src/browser'], }, output: { filename: '[name].js', sourceMapFilename: 'map/[file].map', path: paths.compiled.frontend, }, devtool: __DEV__ ? '#source-map' : false, resolve: { extensions: ['.js', '.ts'], }, module: { rules: [ { test: /\.ts?$/, exclude: /node_modules/, enforce: 'pre', loader: 'tslint-loader', }, { test: /\.ts?$/, exclude: /node_modules\//, use: [ { loader: 'ts-loader', options: { transpileOnly: true, }, }, ], }, ], }, plugins: [ ...(__DEV__ ? [new (webpack as any).ExternalsPlugin('commonjs', ['devtron', 'electron-devtools-installer'])] : [new webpack.optimize.AggressiveMergingPlugin()]), ], }, function(err, stats) { err && console.error(err) stats.compilation.errors.length && stats.compilation.errors.forEach(e => { console.error(e.message) e.module && console.error(e.module.userRequest) }) notifier.notify({ title: 'Delir browser build', message: 'Browser compiled' }) done() }, ) } export async function buildPublishPackageJSON(done) { const string = await fs.readFile(join(paths.src.frontend, 'package.json'), { encoding: 'utf8' }) const json = JSON.parse(string) delete json.devDependencies json.dependencies = { // install only native modules 'fontmanager-redux': '0.4.0', } const newJson = JSON.stringify(json, null, ' ') try { await fs.mkdir(paths.compiled.root) } catch (e) {} try { await fs.writeFile(join(paths.compiled.root, 'package.json'), newJson, { encoding: 'utf8' }) } catch (e) {} done() } export async function symlinkNativeModules(done) { const prepublishNodeModules = join(paths.compiled.root, 'node_modules/') await fs.remove(prepublishNodeModules) await fs.mkdir(prepublishNodeModules) for (let dep of NATIVE_MODULES) { try { if (dep.includes('/')) { const ns = dep.slice(0, dep.indexOf('/')) if (!(await fs.exists(join(prepublishNodeModules, ns)))) { await fs.mkdir(join(prepublishNodeModules, ns)) } } await fs.symlink(join(__dirname, 'node_modules/', dep), join(prepublishNodeModules, dep), 'dir') } catch (e) { console.log(e) } } done() } export async function downloadAndDeployFFmpeg() { const ffmpegBinUrl = { mac: { archiveUrl: 'https://ffmpeg.zeranoe.com/builds/macos64/static/ffmpeg-4.0.2-macos64-static.zip', binFile: 'ffmpeg', binDist: join(paths.release, 'mac/Delir.app/Contents/Resources/ffmpeg'), licenseDist: join(paths.release, 'mac/Delir.app/Contents/Resources/FFMPEG_LICENSE.txt'), }, windows: { archiveUrl: 'https://ffmpeg.zeranoe.com/builds/win64/static/ffmpeg-4.0.2-win64-static.zip', binFile: 'ffmpeg.exe', binDist: join(paths.release, 'win-unpacked/ffmpeg.exe'), licenseDist: join(paths.release, 'win-unpacked/FFMPEG_LICENSE.txt'), }, } const downloadDir = join(__dirname, 'tmp/ffmpeg') await fs.remove(downloadDir) await fs.mkdirp(downloadDir) console.log('Downloading ffmpeg...') await Promise.all( Object.entries(ffmpegBinUrl).map(async ([platform, { archiveUrl, binFile, binDist, licenseDist }]) => { const dirname = path.parse(archiveUrl.slice(archiveUrl.lastIndexOf('/'))).name await download(archiveUrl, downloadDir, { extract: true }) await fs.copy(join(downloadDir, dirname, 'bin', binFile), binDist) await fs.copy(join(downloadDir, dirname, 'LICENSE.txt'), licenseDist) }), ) } export async function generateLicenses() { const destination = join(paths.src.frontend, '/src/modals/AboutModal/Licenses.ts') const jsons = [ JSON.parse(await fs.readFile(join(__dirname, 'package.json'), { encoding: 'UTF-8' })), JSON.parse(await fs.readFile(join(paths.src.frontend, 'package.json'), { encoding: 'UTF-8' })), JSON.parse(await fs.readFile(join(paths.src.core, 'package.json'), { encoding: 'UTF-8' })), ] const deps = jsons.reduce((deps, json) => ({ ...deps, ...json.dependencies, ...json.devDependencies }), {}) const sorted = Object.entries(deps).sort((a, b) => { return a[0] < b[0] ? -1 : a[0] > b[0] ? 1 : 0 }) const entries = sorted.map(([name]) => { const json = require(require.resolve(`${name}/package.json`, { paths: [__dirname, paths.src.frontend, paths.src.core], })) return { name, url: json.homepage || `https://www.npmjs.com/package/${name}` } }) const content = `// This is auto generated file\n// tslint:disable\n// prettier-ignore\nexport const dependencies = ${JSON.stringify( entries, null, 4, )}\n` await fs.writeFile(destination, content) } export function compileRendererJs(done) { webpack( { mode: __DEV__ ? 'development' : 'production', target: 'electron-renderer', watch: __DEV__, context: paths.src.frontend, entry: { main: ['./src/main'], }, optimization: { splitChunks: { name: 'vendor', chunks: 'initial', }, }, output: { filename: '[name].js', sourceMapFilename: 'map/[file].map', path: paths.compiled.frontend, }, devtool: false, resolve: { extensions: ['.js', '.jsx', '.ts', '.tsx'], modules: ['node_modules'], alias: { // Disable React development build for performance measurement react: 'react/cjs/react.production.min.js', 'react-dom': 'react-dom/cjs/react-dom.production.min.js', // Using fresh development packages always '@delirvfx/core': join(paths.src.core, 'src/index.ts'), }, plugins: [ new TsconfigPathsPlugin({ configFile: join(paths.src.frontend, 'tsconfig.json'), }), ], }, module: { rules: [ { test: /\.tsx?$/, exclude: /node_modules/, enforce: 'pre', loader: 'tslint-loader', }, { test: /\.tsx?$/, exclude: /node_modules\//, use: [ { loader: 'ts-loader', options: { transpileOnly: true, }, }, ], }, { test: /\.s(a|c)ss$/, use: [ { loader: 'style-loader', }, { loader: 'css-loader', options: { modules: { localIdentName: __DEV__ ? '[path][name]__[local]--[hash:base64:5]' : '[local]--[hash:base64:5]', }, }, }, { loader: 'sass-loader', options: { implementation: require('sass'), }, }, ], }, { test: /\.css$/, use: ['style-loader', 'css-loader'], }, { test: /\.(eot|svg|ttf|woff|woff2|gif)$/, loader: 'file-loader', options: { name: '[name][hash].[ext]', publicPath: '', }, }, ], }, plugins: [ new webpack.DefinePlugin({ __DEV__: JSON.stringify(__DEV__) }), // preserve require() for native modules new (webpack as any).ExternalsPlugin('commonjs', [...NATIVE_MODULES, 'aws-sdk']), new MonacoEditorWebpackPlugin(), new HtmlWebpackPlugin({ template: join(paths.src.frontend, 'src/index.html'), }), new ForkTsCheckerWebpackPlugin({ tsconfig: join(paths.src.frontend, 'tsconfig.json'), }), new webpack.IgnorePlugin({ resourceRegExp: /@microsoft\/typescript-etw/, contextRegExp: /typescript/ }), ...(__DEV__ ? [] : [new webpack.optimize.AggressiveMergingPlugin()]), ], }, function(err, stats) { err && console.error(err) stats.compilation.errors.length && stats.compilation.errors.forEach(e => { console.error(e.message) e.module && console.error(e.module.userRequest) }) notifier.notify({ title: 'Delir build', message: 'Renderer compiled', sound: true }) console.log('Compiled') done() }, ) } export async function compilePlugins(done) { const contribPEP = (await glob.sync('*/index.ts', { cwd: paths.src.contribPEP })).reduce((memo, entry) => { const { dir, name } = pathParse(entry) memo[`${dir}/${name}`] = join(paths.src.contribPEP, entry) return memo }, {}) webpack( { mode: __DEV__ ? 'development' : 'production', target: 'electron-renderer', watch: __DEV__, context: paths.src.plugins, entry: { 'the-world/index': './the-world/index', 'numeric-slider/index': './numeric-slider/index', 'color-slider/index': './color-slider/index', 'chromakey/index': './chromakey/index', 'webgl/index': './webgl/index', 'time-posterization/index': './time-posterization/index', 'repeat-tile/index': './repeat-tile/index', // 'color-collection/index': './color-collection/index', ...contribPEP, ...(__DEV__ ? { // 'gaussian-blur/index': '../experimental-plugins/gaussian-blur/index', // 'filler/index': '../experimental-plugins/filler/index', // 'mmd/index': '../experimental-plugins/mmd/index', // 'composition-layer/composition-layer': '../experimental-plugins/composition-layer/composition-layer', // 'plane/index': '../experimental-plugins/plane/index', // 'noise/index': '../experimental-plugins/noise/index', } : {}), }, output: { filename: '[name].js', path: paths.compiled.plugins, libraryTarget: 'commonjs-module' as any, }, devtool: __DEV__ ? '#source-map' : false, resolve: { extensions: ['.js', '.ts'], modules: ['node_modules'], }, module: { rules: [ { test: /\.tsx?$/, exclude: /node_modules\//, use: [ { loader: 'ts-loader', options: { transpileOnly: true, }, }, ], }, { test: /\.(frag|vert)$/, loader: 'raw-loader', }, ], }, plugins: [ new webpack.DefinePlugin({ __DEV__: JSON.stringify(__DEV__) }), new (webpack as any).ExternalsPlugin('commonjs', ['@delirvfx/core']), ...(__DEV__ ? [] : [new webpack.optimize.AggressiveMergingPlugin()]), ], }, function(err, stats) { err && console.error(err) stats.compilation.errors.length && stats.compilation.errors.forEach(e => { console.error('Plugin compilation: ', e.message) e.module && console.error(e.module.userRequest) }) notifier.notify({ title: 'Delir build', message: 'Plugin compiled', sound: true }) console.log('Plugin compiled') done() }, ) } export function copyPluginsPackageJson() { return g .src(join(paths.src.plugins, '*/package.json'), { base: join(paths.src.plugins) }) .pipe(g.dest(paths.compiled.plugins)) } export function copyContribPEPPackageJson() { return g .src(join(paths.src.contribPEP, '*/package.json'), { base: join(paths.src.contribPEP) }) .pipe(g.dest(paths.compiled.plugins)) } export function copyExperimentalPluginsPackageJson() { return __DEV__ ? g.src(join(paths.src.root, 'experimental-plugins/*/package.json')).pipe(g.dest(paths.compiled.plugins)) : Promise.resolve() } export function copyImage() { return g .src(join(paths.src.frontend, 'assets/images/**/*'), { since: g.lastRun('copyImage') }) .pipe(g.dest(join(paths.compiled.frontend, 'assets/images'))) } export function makeIcon() { return new Promise((resolve, reject) => { const binName = isWindows ? 'electron-icon-maker.cmd' : 'electron-icon-maker' const binPath = join(__dirname, 'node_modules/.bin/', binName) const source = join(__dirname, 'build-assets/icon.png') const iconMaker = spawn(binPath, [`--input=${source}`, `--output=./build-assets`]) iconMaker .on('error', err => reject(err)) .on('close', (code, signal) => (code === 0 ? resolve() : reject(new Error(signal)))) }) } export async function pack(done) { const yarnBin = isWindows ? 'yarn.cmd' : 'yarn' const electronVersion = require('./package.json').devDependencies.electron await fs.remove(join(paths.build, 'node_modules')) await new Promise((resolve, reject) => { spawn(yarnBin, ['install'], { cwd: paths.build, stdio: 'inherit' }) .on('error', err => reject(err)) .on('close', (code, signal) => (code === 0 ? resolve() : reject(new Error(code)))) }) const targets = [ ...(isMacOS ? [builder.Platform.MAC.createTarget()] : []), ...(isWindows ? [builder.Platform.WINDOWS.createTarget()] : []), ...(isLinux ? [builder.Platform.LINUX.createTarget()] : []), ] for (const target of targets) { await builder.build({ // targets: builder.Platform.MAC.createTarget(), targets: target, publish: 'never', config: { appId: 'studio.delir', copyright: '© 2017 Ragg', productName: 'Delir', electronVersion, asar: true, asarUnpack: ['node_modules/'], npmRebuild: true, // nodeGypRebuild: true, directories: { buildResources: join(__dirname, 'build-assets/build'), app: paths.build, output: paths.release, }, mac: { target: 'dir', type: 'distribution', category: 'AudioVideo', icon: join(__dirname, 'build-assets/icons/mac/icon.icns'), }, win: { target: 'dir', icon: join(__dirname, 'build-assets/icons/win/icon.ico'), }, linux: { target: [{ target: 'AppImage' }, { target: 'deb' }], category: 'Video', }, deb: { depends: ['gconf2', 'gconf-service', 'libnotify4', 'libappindicator1', 'libxtst6', 'libnss3', 'libdbus-1-3'], }, }, }) } } export async function zipPackage() { const version = require('./package.json').version await Promise.all([ new Promise((resolve, reject) => zipDir(join(paths.release, 'mac'), { saveTo: join(paths.release, `Delir-${version}-mac.zip`) }, err => { err ? reject(err) : resolve() }), ), new Promise((resolve, reject) => zipDir(join(paths.release, 'win-unpacked'), { saveTo: join(paths.release, `Delir-${version}-win.zip`) }, err => { err ? reject(err) : resolve() }), ), ]) } export async function clean(done) { await fs.remove(paths.release) await fs.remove(paths.compiled.root) if (fs.existsSync(join(paths.compiled.root, 'node_modules'))) { try { await fs.unlink(join(paths.compiled.root, 'node_modules')) } catch (e) {} } done() } export async function cleanRendererScripts(done) { await fs.remove(join(paths.compiled.frontend, 'scripts')) done() } export function run(done) { const electron = spawn(require('electron'), [join(paths.compiled.frontend, 'browser.js')], { stdio: 'inherit' }) electron.on('close', code => { code === 0 && run(() => {}) }) done() } export function watch() { g.watch(join(paths.src.frontend, '**/*'), buildRendererWithoutJs) g.watch( join(paths.src.root, '**/package.json'), g.parallel(copyPluginsPackageJson, copyContribPEPPackageJson, copyExperimentalPluginsPackageJson), ) g.watch(join(__dirname, 'node_modules'), symlinkNativeModules) } export function runStorybook(done) { const yarnBin = isWindows ? 'yarn.cmd' : 'yarn' spawn(yarnBin, ['storybook', '--ci', '--quiet'], { stdio: 'inherit', cwd: paths.src.frontend }) done() } const buildRendererWithoutJs = g.parallel(copyImage) const buildRenderer = g.parallel( g.series( generateLicenses, compileRendererJs, g.parallel(compilePlugins, copyPluginsPackageJson, copyContribPEPPackageJson, copyExperimentalPluginsPackageJson), ), copyImage, ) const buildBrowser = g.parallel(buildBrowserJs, g.series(buildPublishPackageJSON, symlinkNativeModules)) const build = g.parallel(buildRenderer, buildBrowser) const buildAndWatch = g.series(clean, g.parallel(runStorybook, build), run, watch) const publish = g.series(clean, generateLicenses, build, makeIcon, pack, downloadAndDeployFFmpeg, zipPackage) export { publish, build } export default buildAndWatch
the_stack
import * as d3 from "d3"; import * as d3Tip from "d3-tip"; import * as d3Shape from "d3-shape"; interface Measurement { js: number; wasm: number; emcc: number; } interface TestCase { name: string; results: { [browserId: string ]: Measurement }; visible?: boolean; } interface BarChartData { testCases: TestCase[]; browsers: { name: string, id: string, version: string, visible?: boolean }[]; } const TRANSITION_DURATION = 300; /** * Creates a new chart instance that renders into the given svg element * @param svgElementQuery string | HtmlElement the svg element into which the chart is to be rendered */ function createChart(svgElementQuery) { const target = d3.select(svgElementQuery); const margin = { top: 20, right: 20, bottom: 30, left: 40 }, width = +target.attr("width") - margin.left - margin.right, height = +target.attr("height") - margin.top - margin.bottom, innerHeight = height - 30; target.append("g").attr("transform", "translate(" + margin.left + "," + margin.top + ")"); /** * The overall x axis by test case name */ const x = d3.scaleBand() .rangeRound([0, width]) .paddingInner(0.1); /** * The sub x axis per group. The keys are the browser names */ const xPerCase = d3.scaleBand() .padding(0.05); const y = d3.scaleLinear() .rangeRound([innerHeight, 0]); const yAxis = d3.axisLeft(y) .ticks(10, "%"); const z = d3.scaleOrdinal(d3.schemeCategory10); const opsFormat = d3.format(".2f"); const tip = d3Tip() .attr('class', 'tooltip') .offset([-10, 0]) .html(function(d) { return "<strong>Ops/s:</strong> <span style='color:red'>" + opsFormat(d.ops) + "</span>"; }); target.call(tip); let staticRendered = false; function renderStatic() { const container = target.select("g"); function renderYAxis() { container.append("g") .attr("class", "axis y-axis") .append("text") .attr("y", 10) .attr("dy", "0.32em") .attr("fill", "#000") .attr("font-weight", "bold") .attr("text-anchor", "end") .attr("transform", "rotate(-90)") .text("Speedup"); } function renderLegendBox () { const legend = container.append("g") .attr("class", "legend-box") .attr("font-family", "sans-serif") .attr("font-size", 10) .attr("text-anchor", "end"); const jsLegend = legend.append("g") .attr("class", "legend-js"); jsLegend.append("line") .attr("x1", width) .attr("y1", 9.5) .attr("x2", width - 19) .attr("y2", 9.5) .attr("stroke", "black"); jsLegend.append("text") .attr("x", width - 24) .attr("y", 9.5) .attr("dy", "0.32em") .text("JS"); const emccLegend = legend .append("g") .attr("class", "legend-emcc") .attr("transform", "translate(0, 20)"); emccLegend .append("path") .attr("d", d3Shape.symbol().size(70).type(d3Shape.symbolCross)()) .attr("fill", "black") .attr("transform", "translate(" + (width - 19 / 2) + "," + 9.5 + ") rotate(45)"); emccLegend.append("text") .attr("x", width - 24) .attr("y", 9.5) .attr("dy", "0.32em") .text("Emscripten"); } function renderXAxis() { container.append("g") .attr("class", "axis x-axis") .attr("transform", "translate(0," + innerHeight + ")"); } container.append("g") .attr("class", "cases"); container.append("line") .attr("class", "hundred-percent") .attr("x1", x.range()[0]) .attr("x2", x.range()[1]) .attr("y1", innerHeight) .attr("y2", innerHeight) .attr("stroke-width", 1.5) .attr("stroke", "black"); renderXAxis(); renderYAxis(); renderLegendBox(); staticRendered = true; } function renderData(data: BarChartData) { const container = target.select("g"); const visibleBrowsers = data.browsers.filter(browser => browser.visible !== false); const visibleTestCases = data.testCases.filter(testCase => testCase.visible !== false); function updateLegend() { let legends = container .select("g.legend-box") .selectAll("g.legend") .data(visibleBrowsers); const legendsEnter = legends .enter() .append("g") .attr("class", "legend") .attr("transform", (browser, i) => "translate(" + width + "," + (i + 2) * 20 + ")"); // enter and update const legendsMerged = legends.merge(legendsEnter).transition().duration(TRANSITION_DURATION); legendsMerged.attr("transform", (browser, i) => "translate(0," + (i + 2) * 20 + ")"); legendsEnter.append("rect") .attr("x", width - 19) .attr("width", 19) .attr("height", 19); legendsMerged.select("rect").attr("fill", browser => z(browser.id)); legendsEnter.append("text") .attr("x", width - 24) .attr("y", 9.5) .attr("dy", "0.32em"); legendsMerged.select("text") .text(browser => browser.name + " " + browser.version); legends.exit().remove(); } function testCaseToResults(testCase: TestCase) { return visibleBrowsers.map(browser => { return { browserId: browser.id, percentage: testCase.results[browser.id].wasm / testCase.results[browser.id].js, emccPercentage: testCase.results[browser.id].emcc / testCase.results[browser.id].js, ops: testCase.results[browser.id].wasm }; }); } function updateAxises() { x.domain(visibleTestCases.map(testCase => testCase.name)); xPerCase.domain(visibleBrowsers.map(browser => browser.id)) .rangeRound([0, x.bandwidth()]); y.domain([0, d3.max(visibleTestCases, testCase => d3.max(visibleBrowsers, browser => testCase.results[browser.id].wasm / testCase.results[browser.id].js))]).nice(); // update the x-axis const xAxis = container.select("g.x-axis") .transition() .duration(TRANSITION_DURATION) .call(d3.axisBottom(x)); xAxis .selectAll("text") .attr("y", 10) .attr("x", 5) .attr("dy", ".35em") .attr("transform", "rotate(45)") .style("text-anchor", "start"); xAxis.select(".domain").remove(); container.select("g.y-axis") .transition() .duration(TRANSITION_DURATION) .call(d3.axisLeft(y) .ticks(10, "%")); } updateAxises(); let cases = container .select("g.cases") .selectAll("g.test-case") .data(visibleTestCases); cases.exit().remove(); const casesEnter = cases.enter() .append("g") .attr("class", "test-case"); cases = cases.merge(casesEnter) .attr("transform", testCase => { return "translate(" + x(testCase.name) + ",0)"; }); // render the bars const bars = cases .selectAll("g.bar") .data(testCaseToResults); bars.exit().remove(); const barsEnter = bars .enter() .append("g") .attr("class", "bar"); const barsMerged = bars.merge(barsEnter) .attr("transform", wasmResult => `translate(${xPerCase(wasmResult.browserId)}, 0)`); barsEnter .append("rect") .attr("class", "bar") .attr("y", innerHeight) .attr("height", 0); barsMerged.select("rect") .on("mouseover", tip.show) .on("mouseout", tip.hide) .transition() .duration(TRANSITION_DURATION) .attr("fill", wasmResult => z(wasmResult.browserId)) .attr("y", wasmResult => y(wasmResult.percentage)) .attr("width", xPerCase.bandwidth()) .attr("height", wasmResult => innerHeight - y(wasmResult.percentage)); const percentFormat = d3.format(".0%"); barsEnter .append("text") .attr("class", "bar-label") .attr("fill", "white") .attr("text-anchor", "middle") .attr("font-size", 9) .attr("transform", "rotate(-90)") .text(percentFormat(0)) .attr("x", wasmResult => -innerHeight + 15) .attr("y", wasmResult => xPerCase.bandwidth() / 2 + 2.5); barsMerged.select("text") .transition() .duration(TRANSITION_DURATION) .attr("y", wasmResult => xPerCase.bandwidth() / 2 + 2.5) .text(wasmResult => percentFormat(wasmResult.percentage)); const emcc = barsMerged.selectAll("path.emcc") .data(wasmResult => wasmResult.emccPercentage ? [wasmResult] : []); emcc.exit().remove(); const emccEnter = emcc.enter() .append("path") .attr("class", "emcc") .attr("d", d3Shape.symbol().size(38).type(d3Shape.symbolCross)()) .attr("fill", "black") .attr("transform", "translate(" + xPerCase.bandwidth() / 2 + "," + innerHeight + "), rotate(45)"); emcc.merge(emccEnter) .transition() .duration(TRANSITION_DURATION) .attr("transform", wasmResult => "translate(" + xPerCase.bandwidth() / 2 + "," + y(wasmResult.emccPercentage) + "), rotate(45)"); updateLegend(); container.select("line.hundred-percent") .transition() .duration(TRANSITION_DURATION) .attr("y1", y(1) + 0.75) .attr("y2", y(1) + 0.75); } /** * Initial rendering of the chart * @param data the results to render. */ function render(data: BarChartData) { if (!staticRendered) { renderStatic(); } update(data); } function update(data: BarChartData) { renderData(data); } return { render: render, update: update } } export = createChart;
the_stack
import { Property, ChildProperty, Event, BaseEventArgs, append, compile, createElement } from '@syncfusion/ej2-base'; import { Touch, Browser, Animation as tooltipAnimation, AnimationModel as tooltipAnimationModel } from '@syncfusion/ej2-base'; import { isNullOrUndefined, formatUnit } from '@syncfusion/ej2-base'; import { attributes, removeClass, addClass, remove, updateBlazorTemplate } from '@syncfusion/ej2-base'; import { OffsetPosition, calculatePosition } from './position'; import { isCollide, fit } from './collision'; import { Diagram } from '../diagram'; import { Position } from '@syncfusion/ej2-popups'; import { Effect } from '@syncfusion/ej2-base'; /** * Applicable tip positions attached to the Tooltip. * * @private */ export type TipPointerPosition = 'Auto' | 'Start' | 'Middle' | 'End'; /** * Animation options that are common for both open and close actions of the Tooltip * * @private */ export class BlazorAnimation extends ChildProperty<BlazorAnimation> { /** * Animation settings to be applied on the Tooltip, while it is being shown over the target. * * @ignoreapilink */ @Property<TooltipAnimationSettings>({ effect: 'FadeIn', duration: 150, delay: 0 }) public open: TooltipAnimationSettings; /** * Animation settings to be applied on the Tooltip, when it is closed. * * @ignoreapilink */ @Property<TooltipAnimationSettings>({ effect: 'FadeOut', duration: 150, delay: 0 }) public close: TooltipAnimationSettings; } /** * Describes the element positions. * * @private */ interface ElementPosition extends OffsetPosition { position: Position; horizontal: string; vertical: string; } /** * Interface for Tooltip event arguments. * * @private */ export interface TooltipEventArgs extends BaseEventArgs { /** * It is used to denote the type of the triggered event. */ type: String; /** * It illustrates whether the current action needs to be prevented or not. */ cancel: boolean; /** * It is used to specify the current event object. */ event: Event; /** * It is used to denote the current target element where the Tooltip is to be displayed. */ target: HTMLElement; /** * It is used to denote the Tooltip element */ element: HTMLElement; /** * It is used to denote the Collided Tooltip position * */ collidedPosition?: string; /** * If the event is triggered by interaction, it returns true. Otherwise, it returns false. * */ isInteracted?: boolean; } /** * Animation options that are common for both open and close actions of the Tooltip. * * @private */ export interface TooltipAnimationSettings { /** * It is used to apply the Animation effect on the Tooltip, during open and close actions. */ effect?: Effect; /** * It is used to denote the duration of the animation that is completed per animation cycle. */ duration?: number; /** * It is used to denote the delay value in milliseconds and indicating the waiting time before animation begins. */ delay?: number; } const SHOW_POINTER_TIP_GAP: number = 0; const HIDE_POINTER_TIP_GAP: number = 8; const POINTER_ADJUST: number = 2; const ROOT: string = 'e-tooltip'; const RTL: string = 'e-rtl'; const DEVICE: string = 'e-bigger'; const CLOSE: string = 'e-tooltip-close'; const TOOLTIP_WRAP: string = 'e-tooltip-wrap'; const CONTENT: string = 'e-tip-content'; const ARROW_TIP: string = 'e-arrow-tip'; const ARROW_TIP_OUTER: string = 'e-arrow-tip-outer'; const ARROW_TIP_INNER: string = 'e-arrow-tip-inner'; const TIP_BOTTOM: string = 'e-tip-bottom'; const TIP_TOP: string = 'e-tip-top'; const TIP_LEFT: string = 'e-tip-left'; const TIP_RIGHT: string = 'e-tip-right'; const POPUP_ROOT: string = 'e-popup'; const POPUP_OPEN: string = 'e-popup-open'; const POPUP_CLOSE: string = 'e-popup-close'; const POPUP_LIB: string = 'e-lib'; const HIDE_POPUP: string = 'e-hidden'; const CLASSNAMES: ClassList = { ROOT: 'e-popup', RTL: 'e-rtl', OPEN: 'e-popup-open', CLOSE: 'e-popup-close' }; /** * @private */ interface ClassList { ROOT: string; RTL: string; OPEN: string; CLOSE: string; } /** * @private */ export class BlazorTooltip { private tooltipEle: HTMLElement; private ctrlId: string; private tipClass: string; private tooltipPositionX: string; private tooltipPositionY: string; private tooltipEventArgs: TooltipEventArgs; private isHidden: boolean; private showTimer: number; private hideTimer: number; private tipWidth: number; private touchModule: Touch; private tipHeight: number; private isBlazorTemplate: boolean; private isBlazorTooltip: boolean = false; private contentEvent: Event = null; /** @private */ public width: string | number = 'auto'; /** @private */ public height: string | number = 'auto'; /** @private */ public content: string | HTMLElement = ''; /** @private */ public target: string = ''; /** @private */ public position: Position = 'TopCenter'; /** @private */ public offsetX: number = 0; /** @private */ public offsetY: number = 0; /** @private */ public tipPointerPosition: TipPointerPosition = 'Auto'; /** @private */ public openDelay: number = 0; /** @private */ public closeDelay: number = 0; /** @private */ public cssClass: string = ''; /** @private */ public element: Diagram; /** @private */ public animation: BlazorAnimation; /** @private */ public showTipPointer: boolean; constructor(diagram: Diagram) { this.element = diagram; this.tipClass = TIP_BOTTOM; this.tooltipPositionX = 'Center'; this.tooltipPositionY = 'Top'; this.isHidden = true; this.showTipPointer = true; } /** * @private */ public open(target: HTMLElement, showAnimation: TooltipAnimationSettings, e?: Event): void { if (isNullOrUndefined(this.animation.open)) { this.animation.open = this.element.tooltip && this.element.tooltip.animation && this.element.tooltip.animation.open as TooltipAnimationSettings; } this.showTooltip(target, showAnimation); } /** * @private */ public updateTooltip(target: HTMLElement): void { if (this.tooltipEle) { this.addDescribedBy(target, this.ctrlId + '_content'); this.renderContent(target); this.reposition(target); this.adjustArrow(target, this.position, this.tooltipPositionX, this.tooltipPositionY); } } private formatPosition(): void { if (this.position.indexOf('Top') === 0 || this.position.indexOf('Bottom') === 0) { [this.tooltipPositionY, this.tooltipPositionX] = this.position.split(/(?=[A-Z])/); } else { [this.tooltipPositionX, this.tooltipPositionY] = this.position.split(/(?=[A-Z])/); } } /** * @private */ public destroy(): void { //No code } /** * @private */ public close(): void { if (this.tooltipEle) { removeClass([this.tooltipEle], POPUP_CLOSE); addClass([this.tooltipEle], POPUP_OPEN); tooltipAnimation.stop(this.tooltipEle); let animationOptions: tooltipAnimationModel; // eslint-disable-next-line @typescript-eslint/no-this-alias const currentTooltip: BlazorTooltip = this; currentTooltip.isHidden = true; if (this.animation.close) { animationOptions = { name: this.animation.close.effect, duration: this.animation.close.duration || 0, delay: this.animation.close.delay || 0, timingFunction: 'easeOut' }; } if (!isNullOrUndefined(animationOptions)) { animationOptions.end = () => { if (currentTooltip.isHidden) { remove(currentTooltip.tooltipEle); currentTooltip.tooltipEle = null; } }; new tooltipAnimation(animationOptions).animate(this.tooltipEle); } else { removeClass([this.tooltipEle], CLASSNAMES.OPEN); addClass([this.tooltipEle], CLASSNAMES.CLOSE); remove(this.tooltipEle); this.tooltipEle = null; } } } /** * @private */ public showTooltip(target: HTMLElement, showAnimation: TooltipAnimationSettings, e?: Event): void { clearTimeout(this.showTimer); clearTimeout(this.hideTimer); this.tooltipEventArgs = { type: e ? e.type : null, cancel: false, target: target, event: e ? e : null, element: this.tooltipEle, isInteracted: !isNullOrUndefined(e) }; const observeCallback: Function = (beforeRenderArgs: TooltipEventArgs) => { this.beforeRenderCallback(beforeRenderArgs, target, e, showAnimation); }; this.element.trigger('beforeRender', this.tooltipEventArgs, observeCallback.bind(this)); } private beforeRenderCallback( beforeRenderArgs: TooltipEventArgs, target: HTMLElement, e: Event, showAnimation: TooltipAnimationSettings): void { this.formatPosition(); const isBlazorTooltipRendered: boolean = false; if (beforeRenderArgs.cancel) { this.isHidden = true; // this.clear(); } else { this.isHidden = false; if (isNullOrUndefined(this.tooltipEle)) { this.ctrlId = this.element.element.id; this.tooltipEle = createElement('div', { className: TOOLTIP_WRAP + ' ' + POPUP_ROOT + ' ' + POPUP_LIB, attrs: { role: 'tooltip', 'aria-hidden': 'false', 'id': this.ctrlId + '_content' }, styles: 'width:' + formatUnit(this.width) + ';height:' + formatUnit(this.height) + ';position:absolute; pointer-events:none;' }); this.beforeRenderBlazor(target, this); tooltipAnimation.stop(this.tooltipEle); this.afterRenderBlazor(target, e, showAnimation, this); } else { if (target) { this.addDescribedBy(target, this.ctrlId + '_content'); this.renderContent(target); tooltipAnimation.stop(this.tooltipEle); this.reposition(target); this.afterRenderBlazor(target, e, showAnimation, this); this.adjustArrow(target, this.position, this.tooltipPositionX, this.tooltipPositionY); } } } } private afterRenderBlazor(target: HTMLElement, e: Event, showAnimation: TooltipAnimationSettings, ctrlObj: BlazorTooltip): void { if (target) { removeClass([ctrlObj.tooltipEle], POPUP_OPEN); addClass([ctrlObj.tooltipEle], POPUP_CLOSE); ctrlObj.tooltipEventArgs = { type: e ? e.type : null, cancel: false, target: target, event: e ? e : null, element: ctrlObj.tooltipEle, isInteracted: !isNullOrUndefined(e) }; let animation: tooltipAnimationModel; if (this.animation.open) { animation = { name: this.animation.open.effect, duration: this.animation.open.duration || 0, delay: this.animation.open.delay || 0, timingFunction: 'easeIn' }; } if (!isNullOrUndefined(animation)) { animation.begin = () => { removeClass([ctrlObj.tooltipEle], CLASSNAMES.CLOSE); addClass([ctrlObj.tooltipEle], CLASSNAMES.OPEN); }; animation.end = () => { this.element.trigger('open'); }; new tooltipAnimation(animation).animate(this.tooltipEle); } else { removeClass([ctrlObj.tooltipEle], POPUP_CLOSE); addClass([ctrlObj.tooltipEle], POPUP_OPEN); } } } private setTipClass(position: Position): void { if (position.indexOf('Right') === 0) { this.tipClass = TIP_LEFT; } else if (position.indexOf('Bottom') === 0) { this.tipClass = TIP_TOP; } else if (position.indexOf('Left') === 0) { this.tipClass = TIP_RIGHT; } else { this.tipClass = TIP_BOTTOM; } } private renderArrow(): void { this.setTipClass(this.position); const tip: HTMLElement = createElement('div', { className: ARROW_TIP + ' ' + this.tipClass }); tip.appendChild(createElement('div', { className: ARROW_TIP_OUTER + ' ' + this.tipClass })); tip.appendChild(createElement('div', { className: ARROW_TIP_INNER + ' ' + this.tipClass })); this.tooltipEle.appendChild(tip); } private getTooltipPosition(target: HTMLElement): OffsetPosition { this.tooltipEle.style.display = 'block'; const pos: OffsetPosition = calculatePosition(target, this.tooltipPositionX, this.tooltipPositionY); const offsetPos: OffsetPosition = this.calculateTooltipOffset(this.position); const elePos: OffsetPosition = this.collisionFlipFit(target, pos.left + offsetPos.left, pos.top + offsetPos.top); this.tooltipEle.style.display = ''; return elePos; } private checkCollision(target: HTMLElement, x: number, y: number): ElementPosition { const elePos: ElementPosition = { left: x, top: y, position: this.position, horizontal: this.tooltipPositionX, vertical: this.tooltipPositionY }; const affectedPos: string[] = isCollide(this.tooltipEle, (this.target ? this.element.element : null) as HTMLElement, x, y); if (affectedPos.length > 0) { elePos.horizontal = affectedPos.indexOf('left') >= 0 ? 'Right' : affectedPos.indexOf('right') >= 0 ? 'Left' : this.tooltipPositionX; elePos.vertical = affectedPos.indexOf('top') >= 0 ? 'Bottom' : affectedPos.indexOf('bottom') >= 0 ? 'Top' : this.tooltipPositionY; } return elePos; } private collisionFlipFit(target: HTMLElement, x: number, y: number): OffsetPosition { const elePos: ElementPosition = this.checkCollision(target, x, y); let newpos: Position = elePos.position; if (this.tooltipPositionY !== elePos.vertical) { newpos = ((this.position.indexOf('Bottom') === 0 || this.position.indexOf('Top') === 0) ? elePos.vertical + this.tooltipPositionX : this.tooltipPositionX + elePos.vertical) as Position; } if (this.tooltipPositionX !== elePos.horizontal) { if (newpos.indexOf('Left') === 0) { elePos.vertical = (newpos === 'LeftTop' || newpos === 'LeftCenter') ? 'Top' : 'Bottom'; newpos = (elePos.vertical + 'Left') as Position; } if (newpos.indexOf('Right') === 0) { elePos.vertical = (newpos === 'RightTop' || newpos === 'RightCenter') ? 'Top' : 'Bottom'; newpos = (elePos.vertical + 'Right') as Position; } elePos.horizontal = this.tooltipPositionX; } this.tooltipEventArgs = { type: null, cancel: false, target: target, event: null, element: this.tooltipEle, collidedPosition: newpos }; this.element.trigger('beforeCollision', this.tooltipEventArgs); if (elePos.position !== newpos) { const pos: OffsetPosition = calculatePosition(target, elePos.horizontal, elePos.vertical); this.adjustArrow(target, newpos, elePos.horizontal, elePos.vertical); const offsetPos: OffsetPosition = this.calculateTooltipOffset(newpos); offsetPos.top -= (('TopBottom'.indexOf(this.position.split(/(?=[A-Z])/)[0]) !== -1) && ('TopBottom'.indexOf(newpos.split(/(?=[A-Z])/)[0]) !== -1)) ? (2 * this.offsetY) : 0; offsetPos.left -= (('RightLeft'.indexOf(this.position.split(/(?=[A-Z])/)[0]) !== -1) && ('RightLeft'.indexOf(newpos.split(/(?=[A-Z])/)[0]) !== -1)) ? (2 * this.offsetX) : 0; elePos.position = newpos; elePos.left = pos.left + offsetPos.left; elePos.top = pos.top + offsetPos.top; } else { this.adjustArrow(target, newpos, elePos.horizontal, elePos.vertical); } const eleOffset: OffsetPosition = { left: elePos.left, top: elePos.top }; const left: number = fit( this.tooltipEle, (this.target ? this.element.element : null) as HTMLElement, { X: true, Y: false }, eleOffset).left; this.tooltipEle.style.display = 'block'; if (this.showTipPointer && (newpos.indexOf('Bottom') === 0 || newpos.indexOf('Top') === 0)) { const arrowEle: HTMLElement = this.tooltipEle.querySelector('.' + ARROW_TIP) as HTMLElement; let arrowleft: number = parseInt(arrowEle.style.left, 10) - (left - elePos.left); if (arrowleft < 0) { arrowleft = 0; } else if ((arrowleft + arrowEle.offsetWidth) > this.tooltipEle.clientWidth) { arrowleft = this.tooltipEle.clientWidth - arrowEle.offsetWidth; } arrowEle.style.left = arrowleft.toString() + 'px'; } this.tooltipEle.style.display = ''; eleOffset.left = left; return eleOffset; } private calculateTooltipOffset(position: Position): OffsetPosition { const pos: OffsetPosition = { top: 0, left: 0 }; const tooltipEleWidth: number = this.tooltipEle.offsetWidth; const tooltipEleHeight: number = this.tooltipEle.offsetHeight; const arrowEle: HTMLElement = this.tooltipEle.querySelector('.' + ARROW_TIP) as HTMLElement; const tipWidth: number = arrowEle ? arrowEle.offsetWidth : 0; const tipHeight: number = arrowEle ? arrowEle.offsetHeight : 0; const tipAdjust: number = (this.showTipPointer ? SHOW_POINTER_TIP_GAP : HIDE_POINTER_TIP_GAP); const tipHeightAdjust: number = (tipHeight / 2) + POINTER_ADJUST + (this.tooltipEle.offsetHeight - this.tooltipEle.clientHeight); const tipWidthAdjust: number = (tipWidth / 2) + POINTER_ADJUST + (this.tooltipEle.offsetWidth - this.tooltipEle.clientWidth); switch (position) { case 'RightTop': pos.left += tipWidth + tipAdjust; pos.top -= tooltipEleHeight - tipHeightAdjust; break; case 'RightCenter': pos.left += tipWidth + tipAdjust; pos.top -= (tooltipEleHeight / 2); break; case 'RightBottom': pos.left += tipWidth + tipAdjust; pos.top -= (tipHeightAdjust); break; case 'BottomRight': pos.top += (tipHeight + tipAdjust); pos.left -= (tipWidthAdjust); break; case 'BottomCenter': pos.top += (tipHeight + tipAdjust); pos.left -= (tooltipEleWidth / 2); break; case 'BottomLeft': pos.top += (tipHeight + tipAdjust); pos.left -= (tooltipEleWidth - tipWidthAdjust); break; case 'LeftBottom': pos.left -= (tipWidth + tooltipEleWidth + tipAdjust); pos.top -= (tipHeightAdjust); break; case 'LeftCenter': pos.left -= (tipWidth + tooltipEleWidth + tipAdjust); pos.top -= (tooltipEleHeight / 2); break; case 'LeftTop': pos.left -= (tipWidth + tooltipEleWidth + tipAdjust); pos.top -= (tooltipEleHeight - tipHeightAdjust); break; case 'TopLeft': pos.top -= (tooltipEleHeight + tipHeight + tipAdjust); pos.left -= (tooltipEleWidth - tipWidthAdjust); break; case 'TopRight': pos.top -= (tooltipEleHeight + tipHeight + tipAdjust); pos.left -= (tipWidthAdjust); break; default: pos.top -= (tooltipEleHeight + tipHeight + tipAdjust); pos.left -= (tooltipEleWidth / 2); break; } pos.left += this.offsetX; pos.top += this.offsetY; return pos; } private reposition(target: HTMLElement): void { const elePos: OffsetPosition = this.getTooltipPosition(target); this.tooltipEle.style.left = elePos.left + 'px'; this.tooltipEle.style.top = elePos.top + 'px'; } private beforeRenderBlazor(target: HTMLElement, ctrlObj: BlazorTooltip): void { if (target) { if (Browser.isDevice) { addClass([ctrlObj.tooltipEle], DEVICE); } if (ctrlObj.width !== 'auto') { ctrlObj.tooltipEle.style.maxWidth = formatUnit(ctrlObj.width); } ctrlObj.tooltipEle.appendChild(createElement('div', { className: CONTENT + ' ' + 'e-diagramTooltip-content' })); document.body.appendChild(ctrlObj.tooltipEle); addClass([ctrlObj.tooltipEle], POPUP_OPEN); removeClass([ctrlObj.tooltipEle], HIDE_POPUP); ctrlObj.addDescribedBy(target, ctrlObj.ctrlId + '_content'); ctrlObj.renderContent(target); addClass([ctrlObj.tooltipEle], POPUP_OPEN); if (this.showTipPointer) { ctrlObj.renderArrow(); } const elePos: OffsetPosition = this.getTooltipPosition(target); this.tooltipEle.classList.remove(POPUP_LIB); this.tooltipEle.style.left = elePos.left + 'px'; this.tooltipEle.style.top = elePos.top + 'px'; ctrlObj.reposition(target); ctrlObj.adjustArrow(target, ctrlObj.position, ctrlObj.tooltipPositionX, ctrlObj.tooltipPositionY); } } private addDescribedBy(target: HTMLElement, id: string): void { const describedby: string[] = (target.getAttribute('aria-describedby') || '').split(/\s+/); if (describedby.indexOf(id) < 0) { describedby.push(id); } attributes(target, { 'aria-describedby': describedby.join(' ').trim(), 'data-tooltip-id': id }); } private renderContent(target?: HTMLElement): void { const tooltipContent: HTMLElement = this.tooltipEle.querySelector('.' + CONTENT) as HTMLElement; if (this.cssClass) { addClass([this.tooltipEle], this.cssClass.split(' ')); } if (target && !isNullOrUndefined(target.getAttribute('title'))) { target.setAttribute('data-content', target.getAttribute('title')); target.removeAttribute('title'); } if (!isNullOrUndefined(this.content)) { if (this.isBlazorTooltip || !(false)) { tooltipContent.innerHTML = ''; if (this.content instanceof HTMLElement) { tooltipContent.appendChild(this.content); } else if (typeof this.content === 'string' && this.content.indexOf('<div>Blazor') < 0) { tooltipContent.innerHTML = this.content; } else { const templateFunction: Function = compile(this.content); append(templateFunction({}, null, null, this.element.element.id + 'content'), tooltipContent); if (typeof this.content === 'string' && this.content.indexOf('<div>Blazor') >= 0) { this.isBlazorTemplate = true; updateBlazorTemplate(this.element.element.id + 'content', 'Content', this); } } } } else { if (target && !isNullOrUndefined(target.getAttribute('data-content'))) { tooltipContent.innerHTML = target.getAttribute('data-content'); } } } private updateTipPosition(position: Position): void { const selEle: NodeList = this.tooltipEle.querySelectorAll('.' + ARROW_TIP + ',.' + ARROW_TIP_OUTER + ',.' + ARROW_TIP_INNER); const removeList: string[] = [TIP_BOTTOM, TIP_TOP, TIP_LEFT, TIP_RIGHT]; removeClass(selEle, removeList); this.setTipClass(position); addClass(selEle, this.tipClass); } private adjustArrow(target: HTMLElement, position: Position, tooltipPositionX: string, tooltipPositionY: string): void { if (!this.showTipPointer) { return; } this.updateTipPosition(position); let leftValue: string; let topValue: string; this.tooltipEle.style.display = 'block'; const tooltipWidth: number = this.tooltipEle.clientWidth; const tooltipHeight: number = this.tooltipEle.clientHeight; const arrowEle: HTMLElement = this.tooltipEle.querySelector('.' + ARROW_TIP) as HTMLElement; const arrowInnerELe: HTMLElement = this.tooltipEle.querySelector('.' + ARROW_TIP_INNER) as HTMLElement; const tipWidth: number = arrowEle.offsetWidth; const tipHeight: number = arrowEle.offsetHeight; this.tooltipEle.style.display = ''; if (this.tipClass === TIP_BOTTOM || this.tipClass === TIP_TOP) { if (this.tipClass === TIP_BOTTOM) { topValue = '99.9%'; // Arrow icon aligned -2px height from ArrowOuterTip div arrowInnerELe.style.top = '-' + (tipHeight - 2) + 'px'; } else { topValue = -(tipHeight - 1) + 'px'; // Arrow icon aligned -6px height from ArrowOuterTip div arrowInnerELe.style.top = '-' + (tipHeight - 6) + 'px'; } if (target) { const tipPosExclude: boolean = tooltipPositionX !== 'Center' || (tooltipWidth > target.offsetWidth); if ((tipPosExclude && tooltipPositionX === 'Left') || (!tipPosExclude && this.tipPointerPosition === 'End')) { leftValue = (tooltipWidth - tipWidth - POINTER_ADJUST) + 'px'; } else if ((tipPosExclude && tooltipPositionX === 'Right') || (!tipPosExclude && this.tipPointerPosition === 'Start')) { leftValue = POINTER_ADJUST + 'px'; } else { leftValue = ((tooltipWidth / 2) - (tipWidth / 2)) + 'px'; } } } else { if (this.tipClass === TIP_RIGHT) { leftValue = '99.9%'; // Arrow icon aligned -2px left from ArrowOuterTip div arrowInnerELe.style.left = '-' + (tipWidth - 2) + 'px'; } else { leftValue = -(tipWidth - 1) + 'px'; // Arrow icon aligned -2px from ArrowOuterTip width arrowInnerELe.style.left = (-(tipWidth) + (tipWidth - 2)) + 'px'; } const tipPosExclude: boolean = tooltipPositionY !== 'Center' || (tooltipHeight > target.offsetHeight); if ((tipPosExclude && tooltipPositionY === 'Top') || (!tipPosExclude && this.tipPointerPosition === 'End')) { topValue = (tooltipHeight - tipHeight - POINTER_ADJUST) + 'px'; } else if ((tipPosExclude && tooltipPositionY === 'Bottom') || (!tipPosExclude && this.tipPointerPosition === 'Start')) { topValue = POINTER_ADJUST + 'px'; } else { topValue = ((tooltipHeight / 2) - (tipHeight / 2)) + 'px'; } } arrowEle.style.top = topValue; arrowEle.style.left = leftValue; } /** * Returns the module name of the blazor tooltip * * @returns {string} Returns the module name of the blazor tooltip */ public getModuleName(): string { return 'BlazorTooltip'; } }
the_stack
import * as pulumi from "@pulumi/pulumi"; import { input as inputs, output as outputs } from "../types"; import * as utilities from "../utilities"; /** * Represents a VPN gateway running in GCP. This virtual device is managed * by Google, but used only by you. This type of VPN Gateway allows for the creation * of VPN solutions with higher availability than classic Target VPN Gateways. * * To get more information about HaVpnGateway, see: * * * [API documentation](https://cloud.google.com/compute/docs/reference/rest/v1/vpnGateways) * * How-to Guides * * [Choosing a VPN](https://cloud.google.com/vpn/docs/how-to/choosing-a-vpn) * * [Cloud VPN Overview](https://cloud.google.com/vpn/docs/concepts/overview) * * ## Example Usage * ### Ha Vpn Gateway Basic * * ```typescript * import * as pulumi from "@pulumi/pulumi"; * import * as gcp from "@pulumi/gcp"; * * const network1 = new gcp.compute.Network("network1", {autoCreateSubnetworks: false}); * const haGateway1 = new gcp.compute.HaVpnGateway("haGateway1", { * region: "us-central1", * network: network1.id, * }); * ``` * ### Ha Vpn Gateway Gcp To Gcp * * ```typescript * import * as pulumi from "@pulumi/pulumi"; * import * as gcp from "@pulumi/gcp"; * * const network1 = new gcp.compute.Network("network1", { * routingMode: "GLOBAL", * autoCreateSubnetworks: false, * }); * const haGateway1 = new gcp.compute.HaVpnGateway("haGateway1", { * region: "us-central1", * network: network1.id, * }); * const network2 = new gcp.compute.Network("network2", { * routingMode: "GLOBAL", * autoCreateSubnetworks: false, * }); * const haGateway2 = new gcp.compute.HaVpnGateway("haGateway2", { * region: "us-central1", * network: network2.id, * }); * const network1Subnet1 = new gcp.compute.Subnetwork("network1Subnet1", { * ipCidrRange: "10.0.1.0/24", * region: "us-central1", * network: network1.id, * }); * const network1Subnet2 = new gcp.compute.Subnetwork("network1Subnet2", { * ipCidrRange: "10.0.2.0/24", * region: "us-west1", * network: network1.id, * }); * const network2Subnet1 = new gcp.compute.Subnetwork("network2Subnet1", { * ipCidrRange: "192.168.1.0/24", * region: "us-central1", * network: network2.id, * }); * const network2Subnet2 = new gcp.compute.Subnetwork("network2Subnet2", { * ipCidrRange: "192.168.2.0/24", * region: "us-east1", * network: network2.id, * }); * const router1 = new gcp.compute.Router("router1", { * network: network1.name, * bgp: { * asn: 64514, * }, * }); * const router2 = new gcp.compute.Router("router2", { * network: network2.name, * bgp: { * asn: 64515, * }, * }); * const tunnel1 = new gcp.compute.VPNTunnel("tunnel1", { * region: "us-central1", * vpnGateway: haGateway1.id, * peerGcpGateway: haGateway2.id, * sharedSecret: "a secret message", * router: router1.id, * vpnGatewayInterface: 0, * }); * const tunnel2 = new gcp.compute.VPNTunnel("tunnel2", { * region: "us-central1", * vpnGateway: haGateway1.id, * peerGcpGateway: haGateway2.id, * sharedSecret: "a secret message", * router: router1.id, * vpnGatewayInterface: 1, * }); * const tunnel3 = new gcp.compute.VPNTunnel("tunnel3", { * region: "us-central1", * vpnGateway: haGateway2.id, * peerGcpGateway: haGateway1.id, * sharedSecret: "a secret message", * router: router2.id, * vpnGatewayInterface: 0, * }); * const tunnel4 = new gcp.compute.VPNTunnel("tunnel4", { * region: "us-central1", * vpnGateway: haGateway2.id, * peerGcpGateway: haGateway1.id, * sharedSecret: "a secret message", * router: router2.id, * vpnGatewayInterface: 1, * }); * const router1Interface1 = new gcp.compute.RouterInterface("router1Interface1", { * router: router1.name, * region: "us-central1", * ipRange: "169.254.0.1/30", * vpnTunnel: tunnel1.name, * }); * const router1Peer1 = new gcp.compute.RouterPeer("router1Peer1", { * router: router1.name, * region: "us-central1", * peerIpAddress: "169.254.0.2", * peerAsn: 64515, * advertisedRoutePriority: 100, * "interface": router1Interface1.name, * }); * const router1Interface2 = new gcp.compute.RouterInterface("router1Interface2", { * router: router1.name, * region: "us-central1", * ipRange: "169.254.1.2/30", * vpnTunnel: tunnel2.name, * }); * const router1Peer2 = new gcp.compute.RouterPeer("router1Peer2", { * router: router1.name, * region: "us-central1", * peerIpAddress: "169.254.1.1", * peerAsn: 64515, * advertisedRoutePriority: 100, * "interface": router1Interface2.name, * }); * const router2Interface1 = new gcp.compute.RouterInterface("router2Interface1", { * router: router2.name, * region: "us-central1", * ipRange: "169.254.0.2/30", * vpnTunnel: tunnel3.name, * }); * const router2Peer1 = new gcp.compute.RouterPeer("router2Peer1", { * router: router2.name, * region: "us-central1", * peerIpAddress: "169.254.0.1", * peerAsn: 64514, * advertisedRoutePriority: 100, * "interface": router2Interface1.name, * }); * const router2Interface2 = new gcp.compute.RouterInterface("router2Interface2", { * router: router2.name, * region: "us-central1", * ipRange: "169.254.1.1/30", * vpnTunnel: tunnel4.name, * }); * const router2Peer2 = new gcp.compute.RouterPeer("router2Peer2", { * router: router2.name, * region: "us-central1", * peerIpAddress: "169.254.1.2", * peerAsn: 64514, * advertisedRoutePriority: 100, * "interface": router2Interface2.name, * }); * ``` * ### Compute Ha Vpn Gateway Encrypted Interconnect * * ```typescript * import * as pulumi from "@pulumi/pulumi"; * import * as gcp from "@pulumi/gcp"; * * const network = new gcp.compute.Network("network", {autoCreateSubnetworks: false}); * const address1 = new gcp.compute.Address("address1", { * addressType: "INTERNAL", * purpose: "IPSEC_INTERCONNECT", * address: "192.168.1.0", * prefixLength: 29, * network: network.selfLink, * }); * const router = new gcp.compute.Router("router", { * network: network.name, * encryptedInterconnectRouter: true, * bgp: { * asn: 16550, * }, * }); * const attachment1 = new gcp.compute.InterconnectAttachment("attachment1", { * edgeAvailabilityDomain: "AVAILABILITY_DOMAIN_1", * type: "PARTNER", * router: router.id, * encryption: "IPSEC", * ipsecInternalAddresses: [address1.selfLink], * }); * const address2 = new gcp.compute.Address("address2", { * addressType: "INTERNAL", * purpose: "IPSEC_INTERCONNECT", * address: "192.168.2.0", * prefixLength: 29, * network: network.selfLink, * }); * const attachment2 = new gcp.compute.InterconnectAttachment("attachment2", { * edgeAvailabilityDomain: "AVAILABILITY_DOMAIN_2", * type: "PARTNER", * router: router.id, * encryption: "IPSEC", * ipsecInternalAddresses: [address2.selfLink], * }); * const vpn_gateway = new gcp.compute.HaVpnGateway("vpn-gateway", { * network: network.id, * vpnInterfaces: [ * { * id: 0, * interconnectAttachment: attachment1.selfLink, * }, * { * id: 1, * interconnectAttachment: attachment2.selfLink, * }, * ], * }); * ``` * * ## Import * * HaVpnGateway can be imported using any of these accepted formats * * ```sh * $ pulumi import gcp:compute/haVpnGateway:HaVpnGateway default projects/{{project}}/regions/{{region}}/vpnGateways/{{name}} * ``` * * ```sh * $ pulumi import gcp:compute/haVpnGateway:HaVpnGateway default {{project}}/{{region}}/{{name}} * ``` * * ```sh * $ pulumi import gcp:compute/haVpnGateway:HaVpnGateway default {{region}}/{{name}} * ``` * * ```sh * $ pulumi import gcp:compute/haVpnGateway:HaVpnGateway default {{name}} * ``` */ export class HaVpnGateway extends pulumi.CustomResource { /** * Get an existing HaVpnGateway resource's state with the given name, ID, and optional extra * properties used to qualify the lookup. * * @param name The _unique_ name of the resulting resource. * @param id The _unique_ provider ID of the resource to lookup. * @param state Any extra arguments used during the lookup. * @param opts Optional settings to control the behavior of the CustomResource. */ public static get(name: string, id: pulumi.Input<pulumi.ID>, state?: HaVpnGatewayState, opts?: pulumi.CustomResourceOptions): HaVpnGateway { return new HaVpnGateway(name, <any>state, { ...opts, id: id }); } /** @internal */ public static readonly __pulumiType = 'gcp:compute/haVpnGateway:HaVpnGateway'; /** * Returns true if the given object is an instance of HaVpnGateway. This is designed to work even * when multiple copies of the Pulumi SDK have been loaded into the same process. */ public static isInstance(obj: any): obj is HaVpnGateway { if (obj === undefined || obj === null) { return false; } return obj['__pulumiType'] === HaVpnGateway.__pulumiType; } /** * An optional description of this resource. */ public readonly description!: pulumi.Output<string | undefined>; /** * Name of the resource. Provided by the client when the resource is * created. The name must be 1-63 characters long, and comply with * RFC1035. Specifically, the name must be 1-63 characters long and * match the regular expression `a-z?` which means * the first character must be a lowercase letter, and all following * characters must be a dash, lowercase letter, or digit, except the last * character, which cannot be a dash. */ public readonly name!: pulumi.Output<string>; /** * The network this VPN gateway is accepting traffic for. */ public readonly network!: pulumi.Output<string>; /** * The ID of the project in which the resource belongs. * If it is not provided, the provider project is used. */ public readonly project!: pulumi.Output<string>; /** * The region this gateway should sit in. */ public readonly region!: pulumi.Output<string>; /** * The URI of the created resource. */ public /*out*/ readonly selfLink!: pulumi.Output<string>; /** * A list of interfaces on this VPN gateway. * Structure is documented below. */ public readonly vpnInterfaces!: pulumi.Output<outputs.compute.HaVpnGatewayVpnInterface[]>; /** * Create a HaVpnGateway resource with the given unique name, arguments, and options. * * @param name The _unique_ name of the resource. * @param args The arguments to use to populate this resource's properties. * @param opts A bag of options that control this resource's behavior. */ constructor(name: string, args: HaVpnGatewayArgs, opts?: pulumi.CustomResourceOptions) constructor(name: string, argsOrState?: HaVpnGatewayArgs | HaVpnGatewayState, opts?: pulumi.CustomResourceOptions) { let inputs: pulumi.Inputs = {}; opts = opts || {}; if (opts.id) { const state = argsOrState as HaVpnGatewayState | undefined; inputs["description"] = state ? state.description : undefined; inputs["name"] = state ? state.name : undefined; inputs["network"] = state ? state.network : undefined; inputs["project"] = state ? state.project : undefined; inputs["region"] = state ? state.region : undefined; inputs["selfLink"] = state ? state.selfLink : undefined; inputs["vpnInterfaces"] = state ? state.vpnInterfaces : undefined; } else { const args = argsOrState as HaVpnGatewayArgs | undefined; if ((!args || args.network === undefined) && !opts.urn) { throw new Error("Missing required property 'network'"); } inputs["description"] = args ? args.description : undefined; inputs["name"] = args ? args.name : undefined; inputs["network"] = args ? args.network : undefined; inputs["project"] = args ? args.project : undefined; inputs["region"] = args ? args.region : undefined; inputs["vpnInterfaces"] = args ? args.vpnInterfaces : undefined; inputs["selfLink"] = undefined /*out*/; } if (!opts.version) { opts = pulumi.mergeOptions(opts, { version: utilities.getVersion()}); } super(HaVpnGateway.__pulumiType, name, inputs, opts); } } /** * Input properties used for looking up and filtering HaVpnGateway resources. */ export interface HaVpnGatewayState { /** * An optional description of this resource. */ description?: pulumi.Input<string>; /** * Name of the resource. Provided by the client when the resource is * created. The name must be 1-63 characters long, and comply with * RFC1035. Specifically, the name must be 1-63 characters long and * match the regular expression `a-z?` which means * the first character must be a lowercase letter, and all following * characters must be a dash, lowercase letter, or digit, except the last * character, which cannot be a dash. */ name?: pulumi.Input<string>; /** * The network this VPN gateway is accepting traffic for. */ network?: pulumi.Input<string>; /** * The ID of the project in which the resource belongs. * If it is not provided, the provider project is used. */ project?: pulumi.Input<string>; /** * The region this gateway should sit in. */ region?: pulumi.Input<string>; /** * The URI of the created resource. */ selfLink?: pulumi.Input<string>; /** * A list of interfaces on this VPN gateway. * Structure is documented below. */ vpnInterfaces?: pulumi.Input<pulumi.Input<inputs.compute.HaVpnGatewayVpnInterface>[]>; } /** * The set of arguments for constructing a HaVpnGateway resource. */ export interface HaVpnGatewayArgs { /** * An optional description of this resource. */ description?: pulumi.Input<string>; /** * Name of the resource. Provided by the client when the resource is * created. The name must be 1-63 characters long, and comply with * RFC1035. Specifically, the name must be 1-63 characters long and * match the regular expression `a-z?` which means * the first character must be a lowercase letter, and all following * characters must be a dash, lowercase letter, or digit, except the last * character, which cannot be a dash. */ name?: pulumi.Input<string>; /** * The network this VPN gateway is accepting traffic for. */ network: pulumi.Input<string>; /** * The ID of the project in which the resource belongs. * If it is not provided, the provider project is used. */ project?: pulumi.Input<string>; /** * The region this gateway should sit in. */ region?: pulumi.Input<string>; /** * A list of interfaces on this VPN gateway. * Structure is documented below. */ vpnInterfaces?: pulumi.Input<pulumi.Input<inputs.compute.HaVpnGatewayVpnInterface>[]>; }
the_stack
import { Temporal } from '@js-temporal/polyfill'; import * as ThingTalk from 'thingtalk'; import AsyncQueue from 'consumer-queue'; abstract class BaseTimer { private _stopped : boolean; private _queue : AsyncQueue<IteratorResult<{ __timestamp : number }, void>>; private _timeout : NodeJS.Timeout|null; constructor() { this._stopped = false; this._queue = new AsyncQueue(); this._timeout = null; } protected abstract _nextTimeout() : number; next() { return this._queue.pop(); } end() { if (this._stopped) return; this._stopped = true; this._queue.push({ done: true, value: undefined }); } stop() { this._stopped = true; clearTimeout(this._timeout!); this._timeout = null; } private _reschedule() { this._timeout = setTimeout(() => { if (this._stopped) return; this._queue.push({ done: false, value: { __timestamp: Date.now() } }); this._reschedule(); }, this._nextTimeout()); } start() { this._reschedule(); } } class Timer extends BaseTimer { private _base : number; private _interval : number; private _frequency : number; constructor(base : number, interval : number, frequency : number) { super(); if (Number.isNaN(base) || Number.isNaN(interval) || Number.isNaN(frequency)) throw new Error(`Invalid timer`); this._base = base; this._interval = interval; this._frequency = frequency; } toString() { return `[Timer ${this._base}, ${this._interval}, ${this._frequency}]`; } private _setTimems(date : number|Date, timeInms : number) { // Takes and returns ms representation // 0 sets time to 0:00:00 // 1000 sets time to 0:00:01 // 43200000 sets time to 12:00:00 const dateObj = new Date(date); return dateObj.setHours(0, 0, 0, timeInms); } private _getTimems(date : number) { // Takes and returns ms representation // SOME_DATE 0:00:00 returns 0 // SOME_DATE 0:00:01 returns 1000 // SOME_DATE 12:00:00 returns 43200000 const dateObj = new Date(date); const dateObj0 = new Date(date); return dateObj.getTime() - this._setTimems(dateObj0, 0); } private _setDay(date : number, day : number) { // Takes and returns ms representation const dateObj = new Date(date); const currentDay = dateObj.getDay(); return date + (day - currentDay) * 86400000; } private _splitDay(frequency : number) { // Takes frequency (per day) and returns reasonable timings const REASONABLE_START_TIME = 32400000; // 9AM const REASONABLE_INTERVAL = 43200000; // 12h const TIME_12PM = 43200000; const timings = []; if (frequency === null || frequency === 1) { // If it's just once a day, set timing as 12pm timings.push(TIME_12PM); } else { // For more than once a day, set interval as 9AM to 9PM // and divide equally starting from 9AM onwards // e.g. 3 times a day will be [9AM, 3PM, 9PM] // 4 times a day will be [9AM, 1PM, 5PM, 9PM] // Might want to set a limit on frequency? // Like if it is more than once per hour // then we just do simple divide const interval = REASONABLE_INTERVAL / (frequency - 1); for (let i = 0; i < frequency; i++) timings.push(Math.round(REASONABLE_START_TIME + i * interval)); } return timings; } private _splitWeek(frequency : number) { // Takes frequency (per week) and returns reasonable days // Days of week are 0-indexed, starting from Sunday const base_day = new Date(this._base).getDay(); switch (frequency) { case 2: return [base_day, (base_day + 4) % 7]; case 3: return [1, 3, 5]; case 4: return [1, 2, 4, 5]; case 5: return [1, 2, 3, 4, 5]; case 6: return [1, 2, 3, 4, 5, 6]; case 7: return [0, 1, 2, 3, 4, 5, 6]; default: throw new Error("Invalid frequency for _splitWeek"); } } private _getEarliest(base : number, timings : number[]) { // Returns earliest valid timing after base // e.g. if timings = [9am, 3pm, 9pm] and base = 1st Jan 1pm // then next timing should be 1st Jan 3pm // if base = 1st Jan 10pm, next timing should be 2nd Jan 9am let earliest = null; for (let n = 0; n < timings.length; n++) { earliest = this._setTimems(base, timings[n]); if (earliest >= base) return earliest; } // If base is already past latest timing, return next day's timings[0] return this._setTimems(base + 86400000, timings[0]); } protected _nextTimeout(_now : number|null = null) { // Should we check for cases where frequency > interval? let interval = this._interval; const base = this._base; const now = _now === null ? Date.now() : _now; // used for testing const frequency = this._frequency === null ? 1 : this._frequency; const DAY = 86400000; const WEEK = 7 * DAY; let nextTiming = 0; if (frequency === 0) { // End timer because it will never execute this.end(); return 0; } else if ((this._interval / frequency) < 2000) { throw new Error(`Timer with total interval ${this._interval} and frequency ${this._frequency} will have intervals of ${this._interval / this._frequency}. Minimum interval is 2 seconds.`); } else if (this._interval === DAY) { // Special case if interval is 1 day const timings = this._splitDay(frequency); nextTiming = this._getEarliest(Math.max(now, base), timings); } else if (this._interval === WEEK) { // Special case if interval is 1 week if (base > now) { nextTiming = base; } else if (frequency === 1) { nextTiming = now + WEEK - ((now - base) % WEEK); } else if (frequency < 8) { // Hardcoded cases const days = this._splitWeek(frequency); const baseTime = this._getTimems(base); for (let n = 0; n < days.length; n++) { nextTiming = this._setDay(now, days[n]); nextTiming = this._setTimems(nextTiming, baseTime); if (nextTiming >= now) break; } if (nextTiming < now) nextTiming = this._setDay(now + WEEK, days[0]); nextTiming = this._setTimems(nextTiming, baseTime); } else { // Simple divide interval /= frequency; nextTiming = Math.round(now + interval - ((now - base) % interval)); } } else if (this._interval > DAY) { // Otherwise, just try to call at consistent times if (base > now) { nextTiming = base; } else if (frequency <= (this._interval / DAY)) { // In this case, we are calling at most once a day // So just call at consistent time const baseTime = this._getTimems(base); interval /= frequency; nextTiming = Math.round(now + interval - ((now - base) % interval)); nextTiming = this._setTimems(nextTiming, baseTime); } else { // Calling more than once a day. // Just do a simple divide interval /= frequency; nextTiming = Math.round(now + interval - ((now - base) % interval)); } } else if (this._interval < DAY) { // Just do simple divide if interval is less than a day if (base > now) { nextTiming = base; } else { interval /= frequency; nextTiming = Math.round(now + interval - ((now - base) % interval)); } } return nextTiming - now; } } class AtTimer extends BaseTimer { private _times : ThingTalk.Builtin.Time[]; private _expiration_date : Date|null|undefined; private _timezone : string; constructor(times : ThingTalk.Builtin.Time[], expiration_date : Date|null|undefined, timezone : string) { super(); this._times = times; this._expiration_date = expiration_date; if (this._expiration_date && Number.isNaN(this._expiration_date.getTime())) throw new Error(`Invalid timer`); this._timezone = timezone; } toString() { return `[AtTimer [${this._times}], ${this._expiration_date}]`; } protected _nextTimeout() { const now = Temporal.Now.zonedDateTime('iso8601', this._timezone); if (this._expiration_date !== undefined && this._expiration_date !== null && this._expiration_date.getTime() < now.epochMilliseconds) { console.log('AtTimer to the times ' + this._times + ': has hit expiration date of ' + this._expiration_date); this.end(); return 86400000; } let interval = 86400000; // Tomorrow for (let i = 0; i < this._times.length; i++) { const target = now.withPlainTime(new Temporal.PlainTime(this._times[i].hour, this._times[i].minute, this._times[i].second, 0)); const newInterval = target.epochMilliseconds - now.epochMilliseconds; if (newInterval < interval && newInterval >= 0) interval = newInterval; } console.log('AtTimer to the times ' + this._times + ': polling again in ' + interval + ' ms'); return interval; } } class OnTimer extends BaseTimer { private _dates : Date[]; constructor(dates : Date[]) { super(); this._dates = dates; if (dates.some((d) => Number.isNaN(d.getTime()))) throw new Error(`Invalid timer`); } toString() { return `[OnTimer [${this._dates}]]`; } protected _nextTimeout(_now : number|null = null) { const now = _now === null ? new Date() : new Date(_now); // used for testing let target = new Date(this._dates[0]); for (let i = 1; i < this._dates.length; i++) { const temp = new Date(this._dates[i]); if (temp.getTime() > now.getTime() && (temp.getTime() < target.getTime() || now.getTime() > target.getTime())) target = temp; } const interval = target.getTime() - now.getTime(); // prevent overflow, ignore very large timers if (interval < 2**31-1 && interval > 0) return interval; this.end(); return 0; } } export { Timer, AtTimer, OnTimer };
the_stack
import { ComponentEvent, delegateEvents, logUnhandledException, managed, managedChild, ManagedEvent, observe, } from "../core"; import { err, ERROR } from "../errors"; import { UIComponent, UIRenderable, UIRenderableConstructor, UIRenderContext, UIRenderPlacement, UITheme, Stringable, } from "../ui"; import { AppActivity } from "./AppActivity"; import { Application } from "./Application"; /** * View activity base class. Represents an application activity with content that can be rendered when activated. * @note Nothing is rendered if the `placement` property is undefined (default). Make sure this property is set to a `UIRenderPlacement` value before rendering, or use a specific view activity class such as `PageViewActivity`. */ export class ViewActivity extends AppActivity implements UIRenderable { /** * Register this activity class with the application auto-update handler (for automatic reload/hot module update). When possible, updates to the module trigger updates to any existing activity instances, with new methods and a new view instance. * @param module * Reference to the module that should be watched for updates (build system-specific) */ static autoUpdate(module: any) { Application.registerAutoUpdate(module, this, "@reload"); } /** @internal Update prototype for given class with newer prototype */ static ["@reload"](Old: typeof ViewActivity, Updated: typeof ViewActivity) { if (Old.prototype._OrigClass) Old = Old.prototype._OrigClass; Updated.prototype._OrigClass = Old; let desc = (Object as any).getOwnPropertyDescriptors(Updated.prototype); for (let p in desc) Object.defineProperty(Old.prototype, p, desc[p]); let View = (Old.prototype._ViewClass = Updated.prototype._ViewClass); if (View && Old.prototype._PresetClass) { Old.prototype._PresetClass.presetBoundComponent("view", View, AppActivity); for (var id in Old.prototype._allActive) { var activity = Old.prototype._allActive[id]; if (activity.isActive()) activity.view = new View(); } } } static preset(presets: ViewActivity.Presets, View?: UIRenderableConstructor): Function { if (View) { this.presetBoundComponent("view", View, AppActivity); if (!this.prototype._allActive) this.prototype._allActive = Object.create(null); this.prototype._ViewClass = View; this.prototype._PresetClass = this; } return super.preset(presets); } /** The root component that makes up the content for this view, as a child component */ @delegateEvents @managedChild view?: UIRenderable; /** View placement mode, determines if and how view is rendered when activated */ placement = UIRenderPlacement.NONE; /** Modal shade backdrop opacity behind content (0-1), if supported by placement mode */ modalShadeOpacity?: number; /** * Render the view for this activity and display it, if it is not currently visible. * This method is called automatically after the root view component is created and/or when an application render context is made available or emits a change event, and should not be called directly. */ render(callback?: UIRenderContext.RenderCallback) { if (this._cbContext !== this.renderContext) { // remember this render context and invalidate // previous callback if context changed this._renderCallback = undefined; this._cbContext = this.renderContext; } if (callback && callback !== this._renderCallback) { if (this._renderCallback) this._renderCallback(undefined); this._renderCallback = callback; } if (!this._renderCallback) { if (!this.placement) return; if (!this.renderContext) { throw err(ERROR.ViewActivity_NoRenderContext); } let placement = this.placement; let rootCallback = this.renderContext.getRenderCallback(); let rootProxy: NonNullable<typeof callback> = (output, afterRender) => { if (output) { output.placement = placement; output.modalShadeOpacity = this.modalShadeOpacity; } rootCallback = rootCallback(output as any, afterRender) as NonNullable< typeof callback >; return rootProxy; }; this._renderCallback = rootProxy; } this._renderer.render(this.view, this._renderCallback); } /** * Remove the view output that was rendered by `ViewActivity.render`, if any. * This method is called automatically after the root view component or render context is removed, and should not be called directly. */ async removeViewAsync() { await this._renderer.removeAsync(); } /** Request input focus on the last (or first) focused UI component, if any */ restoreFocus(firstFocused?: boolean) { if (firstFocused) this.firstFocused && this.firstFocused.requestFocus(); else this.lastFocused && this.lastFocused.requestFocus(); } /** Handle FocusIn UI event, remember first/last focused component */ protected onFocusIn(e: ComponentEvent): boolean | void { if (e.source instanceof UIComponent) { if (!this.firstFocused) this.firstFocused = e.source; this.lastFocused = e.source; } } /** The UI component that was focused first, if any */ @managed firstFocused?: UIComponent; /** The UI component that was most recently focused, if any */ @managed lastFocused?: UIComponent; /** * Create an instance of given view component, wrapped in a singleton dialog view activity, and adds it to the application to be displayed immediately. Unless an event handler is specified explicitly, the activity responds to the CloseModal event by destroying the activity, which removes the view as well. * @param View * A view component constructor * @param eventHandler * A function that is invoked for all events that are emitted by the view * @returns A promise that resolves to the view _activity_ instance after it has been activated. * @note Use the `Application.showViewActivityAsync` method, or reference an activity using a managed child property to show a view that is already encapsulated in an activity. */ showDialogAsync( View: UIRenderableConstructor, eventHandler?: (this: DialogViewActivity, e: ManagedEvent) => void ) { let app = this.getApplication(); if (!app) throw err(ERROR.ViewActivity_NoApplication); // create a singleton activity constructor with event handler class SingletonActivity extends DialogViewActivity.with(View) {} if (eventHandler) { SingletonActivity.prototype.delegateEvent = eventHandler; } let activity: ViewActivity = new SingletonActivity(); return app.showViewActivityAsync(activity); } /** * Display a confirmation/alert dialog with given content. If the 'cancel' button label is not provided, the dialog will only contain a 'confirm' button. All strings are automatically translated to the current locale using the `strf` function. * @param message * The message to be displayed, or multiple message paragraphs (for arrays) * @param title * The dialog title, displayed at the top of the dialog (optional) * @param confirmButtonLabel * The label for the 'confirm' button * @param cancelButtonLabel * The label for the 'cancel' button, if any * @returns A promise that resolves to true if the OK button was clicked, false otherwise. */ showConfirmationDialogAsync( message: Stringable | Stringable[], title?: Stringable, confirmButtonLabel?: Stringable, cancelButtonLabel?: Stringable ) { let Builder = UITheme.current.ConfirmationDialogBuilder; if (!Builder) { throw err(ERROR.ViewActivity_NoDialogBuilder); } let builder = new Builder(); if (Array.isArray(message)) message.forEach(m => builder.addMessage(m)); else builder.addMessage(message); if (title) builder.setTitle(title); if (confirmButtonLabel) builder.setConfirmButtonLabel(confirmButtonLabel); if (cancelButtonLabel) builder.setCancelButtonLabel(cancelButtonLabel); let Dialog = builder.build(); return new Promise<boolean>(resolve => { this.showDialogAsync(Dialog, function (e) { if (e.name === "Confirm") { resolve(true); this.destroyAsync(); } if (e.name === "CloseModal" && cancelButtonLabel) { resolve(false); this.destroyAsync(); } }); }); } private _renderCallback?: UIRenderContext.RenderCallback; private _cbContext?: UIRenderContext; private _renderer = new UIComponent.DynamicRendererWrapper(); // these references are set on the prototype instead (by static `preset()`): private _allActive?: { [managedId: string]: ViewActivity }; private _ViewClass?: UIRenderableConstructor; private _PresetClass?: typeof ViewActivity; private _OrigClass?: typeof ViewActivity; /** @internal Observe view activities to create views and render when needed */ @observe protected static ViewActivityObserver = class { constructor(public activity: ViewActivity) {} onActive() { if (this.activity._allActive) { this.activity._allActive[this.activity.managedId] = this.activity; } if (this.activity._ViewClass) { this.activity.view = new this.activity._ViewClass(); } } onInactive() { if (this.activity._allActive) { delete this.activity._allActive[this.activity.managedId]; } this.activity.view = undefined; } async onRenderContextChange() { if (this.activity.isActive() && this.activity._ViewClass) { this.activity.view = undefined; if (this.activity.renderContext) { // introduce a delay artificially to clear the old view await Promise.resolve(); setTimeout(() => { if ( !this.activity.view && this.activity.renderContext && this.activity.isActive() && this.activity._ViewClass ) { this.activity.view = new this.activity._ViewClass(); } }, 1); } } } onViewChangeAsync() { this.checkAndRender(); } checkAndRender() { if (this.activity.renderContext && this.activity.view) this.activity.render(); else this.activity.removeViewAsync().catch(logUnhandledException); } }; } /** Represents an application activity with a view that is rendered as a full page (when active) */ export class PageViewActivity extends ViewActivity { placement = UIRenderPlacement.PAGE; } /** * Represents an application activity with a view that is rendered as a modal dialog (when active). The activity is destroyed automatically when a `CloseModal` event is emitted on the view instance. * @note Use `UIComponent.position` (`UIStyle.Position`, specifically the `gravity` property) to determine the position of the dialog UI. */ export class DialogViewActivity extends ViewActivity { /** Create a new activity that is rendered as a modal dialog */ constructor() { super(); this.placement = UIRenderPlacement.DIALOG; this.modalShadeOpacity = UITheme.current.modalDialogShadeOpacity; } /** Handle CloseModal event by destroying this activity; stops propagation of the event */ protected onCloseModal(): boolean | void { this.destroyAsync(); return true; } } export namespace ViewActivity { /** View activity presets type, for use with `Component.with` */ export interface Presets extends AppActivity.Presets { /** View placement mode */ placement?: UIRenderPlacement; /** Modal shade backdrop opacity behind content (0-1), if supported by placement mode */ modalShadeOpacity?: number; } }
the_stack
import ReportUtil from "../../reportUtil"; // import ReportSummaryUtil from '../../../util/reportSummaryUtil'; import ExcelJS from "exceljs" export default class MultiScanReport { public static async multiScanXlsxDownload(storedScans: any, scanType:string, storedScanCount: number, archives: []) { // create workbook var reportWorkbook = MultiScanReport.createReportWorkbook(storedScans, scanType, storedScanCount, archives); // create binary buffer const buffer = await reportWorkbook.xlsx.writeBuffer(); // create xlsx blob const fileType = 'application/vnd.openxmlformats-officedocument.spreadsheetml.sheet'; const blob = new Blob([buffer], {type: fileType}); // const fileName = ReportUtil.single_page_report_file_name(xlsx_props.tab_title); const fileName = ReportUtil.single_page_report_file_name(storedScans[storedScans.length - 1].pageTitle); // if scanStorage false clear/delete current scan? // download file ReportUtil.download_file(blob, fileName); } public static createReportWorkbook(storedScans: any, scanType: string, storedScanCount: number, archives: []) { // create workbook // @ts-ignore const workbook = new ExcelJS.Workbook({useStyles: true }); // create worksheets this.createOverviewSheet(storedScans, scanType, storedScanCount, archives, workbook); this.createScanSummarySheet(storedScans, scanType, workbook); this.createIssueSummarySheet(storedScans, scanType, workbook); this.createIssuesSheet(storedScans, scanType, workbook); this.createDefinitionsSheet(workbook); return workbook; } public static createOverviewSheet(storedScans: any, scanType: string, storedScanCount: number, archives: [], workbook: any) { let violations = 0; let needsReviews = 0; let recommendations = 0; let totalIssues = 0; // if scanType is "selected" need to recalculate storedScanCount let selectedStoredScanCount = 0; // BIG QUESTION: is report // 1. for current scan (from menu) // 2. all stored scans (from menu) // 3. selected stored scans (from scan manager) const theCurrentScan = storedScans[storedScans.length - 1]; if (scanType === "current") { violations = theCurrentScan.violations; needsReviews = theCurrentScan.needsReviews; recommendations = theCurrentScan.recommendations; totalIssues = theCurrentScan.violations+theCurrentScan.needsReviews+theCurrentScan.recommendations; } else if (scanType === "all") { for (let i=0; i < storedScans.length; i++) { violations += storedScans[i].violations; needsReviews += storedScans[i].needsReviews; recommendations += storedScans[i].recommendations; } totalIssues = violations+needsReviews+recommendations; } else if (scanType === "selected") { for (let i=0; i < storedScans.length; i++) { if (storedScans[i].isSelected === true) { selectedStoredScanCount++; violations += storedScans[i].violations; needsReviews += storedScans[i].needsReviews; recommendations += storedScans[i].recommendations; } } totalIssues = violations+needsReviews+recommendations; } const worksheet = workbook.addWorksheet("Overview"); // Report Title worksheet.mergeCells('A1', "D1"); const titleRow = worksheet.getRow(1); titleRow.height = "27"; const cellA1 = worksheet.getCell('A1'); cellA1.value = "Accessibility Scan Report"; cellA1.alignment = { vertical: "middle", horizontal: "left"}; cellA1.font = { name: "Calibri", color: { argb: "FFFFFFFF" }, size: "16" }; cellA1.fill = { type: 'pattern', pattern: 'solid', fgColor:{argb:'FF403151'} }; // what are column widths - can't get it till you set it const colWidthData = [ {col: 'A', width: '15.1'}, {col: 'B', width: '15.9'}, {col: 'C', width: '16.23'}, {col: 'D', width: '19.4'}, ] for (let i=0; i<4; i++) { worksheet.getColumn(colWidthData[i].col).width = colWidthData[i].width; } // set row height for rows 2-10 for (let i=2; i<11; i++) { if (i == 7) { worksheet.getRow(i).height = 36; } else { worksheet.getRow(i).height = 12; // results in a row height of 16 } } // note except for Report Date this is the same for all scans const rowData = [ {key1: 'Tool:', key2: 'IBM Equal Access Accessibility Checker'}, {key1: 'Version:', key2: chrome.runtime.getManifest().version}, //@ts-ignore {key1: 'Rule set:', key2: (theCurrentScan.ruleSet === "Latest Deployment") ? archives[1].name : theCurrentScan.ruleSet }, {key1: 'Guidelines:', key2: theCurrentScan.guidelines}, {key1: 'Report date:', key2: theCurrentScan.reportDate}, // do we need to get actual date? {key1: 'Platform:', key2: navigator.userAgent}, {key1: 'Scans:', key2: scanType === "current" ? 1 : scanType === "all" ? storedScanCount : selectedStoredScanCount}, // *** NEED TO FIX FOR selected {key1: 'Pages:', key2: ""} ]; worksheet.mergeCells('B2', "D2"); worksheet.mergeCells('B3', "D3"); worksheet.mergeCells('B4', "D4"); worksheet.mergeCells('B5', "D5"); worksheet.mergeCells('B6', "D6"); worksheet.mergeCells('B7', "D7"); worksheet.mergeCells('B8', "D8"); worksheet.mergeCells('B9', "D9"); worksheet.mergeCells('A10', "D10"); for (let i=2; i<10; i++) { worksheet.getRow(i).getCell(1).font = { name: "Calibri", color: { argb: "FF000000" }, size: "12" }; worksheet.getRow(i).getCell(2).font = { name: "Calibri", color: { argb: "FF000000" }, size: "12" }; worksheet.getRow(i).getCell(1).alignment = { horizontal: "left"}; worksheet.getRow(i).getCell(2).alignment = { horizontal: "left"}; if (i == 7) { worksheet.getRow(i).getCell(1).alignment = { vertical: "top"}; worksheet.getRow(i).getCell(2).alignment = { wrapText: true }; } } for (let i=2; i<10; i++) { worksheet.getRow(i).getCell(1).value = rowData[i-2].key1; worksheet.getRow(i).getCell(2).value = rowData[i-2].key2; } // Summary Title worksheet.mergeCells('A11', "D11"); const summaryRow = worksheet.getRow(11); summaryRow.height = "27"; const cellA11 = worksheet.getCell('A11'); cellA11.value = "Summary"; cellA11.alignment = { vertical: "middle", horizontal: "left"}; cellA11.font = { name: "Calibri", color: { argb: "FFFFFFFF" }, size: "16" }; cellA11.fill = { type: 'pattern', pattern: 'solid', fgColor:{argb:'FF403151'} }; // Scans info Headers worksheet.getRow(12).height = 16; // actual height is const cellA12 = worksheet.getCell('A12'); cellA12.value = "Total issues"; const cellB12 = worksheet.getCell('B12'); cellB12.value = "Violations"; const cellC12 = worksheet.getCell('C12'); cellC12.value = "Needs review"; const cellD12 = worksheet.getCell('D12'); cellD12.value = "Recommendations"; const cellObjects1 = [cellA12, cellB12, cellC12, cellD12]; for (let i=0; i<4; i++) { cellObjects1[i].alignment = { vertical: "middle", horizontal: "center"}; if (i == 1 || i == 2 || i == 3) { cellObjects1[i].font = { name: "Calibri", color: { argb: "FF000000" }, size: "12" }; } else { cellObjects1[i].font = { name: "Calibri", color: { argb: "FFFFFFFF" }, size: "12" }; } // cellObjects1[i].fill = { type: 'pattern', pattern: 'solid', fgColor:{argb:'FFC65911'} }; cellObjects1[i].border = { top: {style:'thin', color: {argb: 'FFA6A6A6'}}, left: {style:'thin', color: {argb: 'FFA6A6A6'}}, bottom: {style:'thin', color: {argb: 'FFA6A6A6'}}, right: {style:'thin', color: {argb: 'FFA6A6A6'}} } } cellA12.fill = { type: 'pattern', pattern: 'solid', fgColor:{argb:'FF000000'} }; cellB12.fill = { type: 'pattern', pattern: 'solid', fgColor:{argb:'FFE4AAAF'} }; cellC12.fill = { type: 'pattern', pattern: 'solid', fgColor:{argb:'FFF4E08A'} }; cellD12.fill = { type: 'pattern', pattern: 'solid', fgColor:{argb:'FF96A9D7'} }; // Scans info Values worksheet.getRow(13).height = 27; // actual height is const cellA13 = worksheet.getCell('A13'); cellA13.value = totalIssues; const cellB13 = worksheet.getCell('B13'); cellB13.value = violations; const cellC13 = worksheet.getCell('C13'); cellC13.value = needsReviews; const cellD13 = worksheet.getCell('D13'); cellD13.value = recommendations; const cellObjects2 = [cellA13, cellB13, cellC13, cellD13]; for (let i=0; i<4; i++) { cellObjects2[i].alignment = { vertical: "middle", horizontal: "center"}; cellObjects2[i].font = { name: "Calibri", color: { argb: "FF000000" }, size: "12" }; // cellObjects2[i].fill = { type: 'pattern', pattern: 'solid', fgColor:{argb:'FFf8cbad'} }; cellObjects2[i].border = { top: {style:'thin', color: {argb: 'FFA6A6A6'}}, left: {style:'thin', color: {argb: 'FFA6A6A6'}}, bottom: {style:'thin', color: {argb: 'FFA6A6A6'}}, right: {style:'thin', color: {argb: 'FFA6A6A6'}} } } } public static createScanSummarySheet(storedScans: any, scanType: string, workbook: any) { const worksheet = workbook.addWorksheet("Scan summary"); // Scans info Headers worksheet.getRow(1).height = 39; // actual height is 52 const colWidthData = [ {col: 'A', width: '27.0'}, {col: 'B', width: '46.0'}, {col: 'C', width: '20.17'}, {col: 'D', width: '18.5'}, {col: 'E', width: '17.17'}, {col: 'F', width: '17.17'}, {col: 'G', width: '17.17'}, {col: 'H', width: '17.17'}, {col: 'I', width: '17.17'}, ] for (let i=0; i<9; i++) { worksheet.getColumn(colWidthData[i].col).width = colWidthData[i].width; } const cellA1 = worksheet.getCell('A1'); cellA1.value = "Page title"; const cellB1 = worksheet.getCell('B1'); cellB1.value = "Page url"; const cellC1 = worksheet.getCell('C1'); cellC1.value = "Scan label"; const cellD1 = worksheet.getCell('D1'); cellD1.value = "Base scan"; const cellObjects1 = [cellA1, cellB1, cellC1, cellD1]; for (let i=0; i<4; i++) { cellObjects1[i].alignment = { vertical: "middle", horizontal: "left"}; cellObjects1[i].font = { name: "Calibri", color: { argb: "FFFFFFFF" }, size: "12" }; cellObjects1[i].fill = { type: 'pattern', pattern: 'solid', fgColor:{argb:'FF403151'} }; cellObjects1[i].border = { top: {style:'thin', color: {argb: 'FFA6A6A6'}}, left: {style:'thin', color: {argb: 'FFA6A6A6'}}, bottom: {style:'thin', color: {argb: 'FFA6A6A6'}}, right: {style:'thin', color: {argb: 'FFA6A6A6'}} } } const cellE1 = worksheet.getCell('E1'); cellE1.value = "Violations"; const cellF1 = worksheet.getCell('F1'); cellF1.value = "Needs review"; const cellG1 = worksheet.getCell('G1'); cellG1.value = "Recommendations"; const cellH1 = worksheet.getCell('H1'); cellH1.value = "% elements without violations"; const cellI1 = worksheet.getCell('I1'); cellI1.value = "% elements without violations or items to review"; const cellObjects2 = [cellE1, cellF1, cellG1, cellH1, cellI1]; for (let i=0; i<5; i++) { cellObjects2[i].alignment = { vertical: "middle", horizontal: "center", wrapText: true }; if (i == 0 || i ==1 || i == 2) { cellObjects2[i].font = { name: "Calibri", color: { argb: "FF000000" }, size: "12" }; } else { cellObjects2[i].font = { name: "Calibri", color: { argb: "FFFFFFFF" }, size: "12" }; } // cellObjects2[i].fill = { type: 'pattern', pattern: 'solid', fgColor:{argb:'FFC65911'} }; cellObjects2[i].border = { top: {style:'thin', color: {argb: 'FFA6A6A6'}}, left: {style:'thin', color: {argb: 'FFA6A6A6'}}, bottom: {style:'thin', color: {argb: 'FFA6A6A6'}}, right: {style:'thin', color: {argb: 'FFA6A6A6'}} } } cellE1.fill = { type: 'pattern', pattern: 'solid', fgColor:{argb:'FFE4AAAF'} }; cellF1.fill = { type: 'pattern', pattern: 'solid', fgColor:{argb:'FFF4E08A'} }; cellG1.fill = { type: 'pattern', pattern: 'solid', fgColor:{argb:'FF96A9D7'} }; cellH1.fill = { type: 'pattern', pattern: 'solid', fgColor:{argb:'FF000000'} }; cellI1.fill = { type: 'pattern', pattern: 'solid', fgColor:{argb:'FF000000'} }; // if current scan use last scan, if // if current scan use only the last scan otherwise loop through each scan an create row let j = scanType === "current" ? storedScans.length - 1 : 0; // NEED TO FIX for selected for (j; j < storedScans.length; j++) { // for each scan console.log("scanType = ", scanType, " storedScans[j].isSelected = ", storedScans[j].isSelected); if (scanType === "selected" && storedScans[j].isSelected === true) { let row = worksheet.addRow( [storedScans[j].pageTitle, storedScans[j].url, storedScans[j].userScanLabel, "none", storedScans[j].violations, storedScans[j].needsReviews, storedScans[j].recommendations, storedScans[j].elementsNoViolations, storedScans[j].elementsNoFailures ]); row.height = 37; // actual height is for (let i = 1; i < 5; i++) { row.getCell(i).alignment = { vertical: "middle", horizontal: "left", wrapText: true }; row.getCell(i).font = { name: "Calibri", color: { argb: "00000000" }, size: "12" }; } for (let i = 5; i < 10; i++) { row.getCell(i).alignment = { vertical: "middle", horizontal: "center", wrapText: true }; row.getCell(i).font = { name: "Calibri", color: { argb: "00000000" }, size: "12" }; // row.getCell(i).fill = { type: 'pattern', pattern: 'solid', fgColor:{argb:'FFf8cbad'} }; row.getCell(i).border = { top: {style:'thin', color: {argb: 'FFA6A6A6'}}, left: {style:'thin', color: {argb: 'FFA6A6A6'}}, bottom: {style:'thin', color: {argb: 'FFA6A6A6'}}, right: {style:'thin', color: {argb: 'FFA6A6A6'}} } } } else if (scanType === "all") { let row = worksheet.addRow( [storedScans[j].pageTitle, storedScans[j].url, storedScans[j].userScanLabel, "none", storedScans[j].violations, storedScans[j].needsReviews, storedScans[j].recommendations, storedScans[j].elementsNoViolations, storedScans[j].elementsNoFailures ]); row.height = 37; // actual height is for (let i = 1; i < 5; i++) { row.getCell(i).alignment = { vertical: "middle", horizontal: "left", wrapText: true }; row.getCell(i).font = { name: "Calibri", color: { argb: "00000000" }, size: "12" }; } for (let i = 5; i < 10; i++) { row.getCell(i).alignment = { vertical: "middle", horizontal: "center", wrapText: true }; row.getCell(i).font = { name: "Calibri", color: { argb: "00000000" }, size: "12" }; // row.getCell(i).fill = { type: 'pattern', pattern: 'solid', fgColor:{argb:'FFf8cbad'} }; row.getCell(i).border = { top: {style:'thin', color: {argb: 'FFA6A6A6'}}, left: {style:'thin', color: {argb: 'FFA6A6A6'}}, bottom: {style:'thin', color: {argb: 'FFA6A6A6'}}, right: {style:'thin', color: {argb: 'FFA6A6A6'}} } } } else if (scanType === "current") { let row = worksheet.addRow( [storedScans[j].pageTitle, storedScans[j].url, storedScans[j].userScanLabel, "none", storedScans[j].violations, storedScans[j].needsReviews, storedScans[j].recommendations, storedScans[j].elementsNoViolations, storedScans[j].elementsNoFailures ]); row.height = 37; // actual height is for (let i = 1; i < 5; i++) { row.getCell(i).alignment = { vertical: "middle", horizontal: "left", wrapText: true }; row.getCell(i).font = { name: "Calibri", color: { argb: "00000000" }, size: "12" }; } for (let i = 5; i < 10; i++) { row.getCell(i).alignment = { vertical: "middle", horizontal: "center", wrapText: true }; row.getCell(i).font = { name: "Calibri", color: { argb: "00000000" }, size: "12" }; // row.getCell(i).fill = { type: 'pattern', pattern: 'solid', fgColor:{argb:'FFf8cbad'} }; row.getCell(i).border = { top: {style:'thin', color: {argb: 'FFA6A6A6'}}, left: {style:'thin', color: {argb: 'FFA6A6A6'}}, bottom: {style:'thin', color: {argb: 'FFA6A6A6'}}, right: {style:'thin', color: {argb: 'FFA6A6A6'}} } } } } } public static createIssueSummarySheet(storedScans: any, scanType: string, workbook: any) { let violations = 0; let needsReviews = 0; let recommendations = 0; let totalIssues = 0; // question 1: is report for current scans or all available scans? const theCurrentScan = storedScans[storedScans.length - 1]; if (scanType === "current") { violations = theCurrentScan.violations; needsReviews = theCurrentScan.needsReviews; recommendations = theCurrentScan.recommendations; totalIssues = theCurrentScan.violations+theCurrentScan.needsReviews+theCurrentScan.recommendations; } else if (scanType === "all") { for (let i=0; i < storedScans.length; i++) { violations += storedScans[i].violations; needsReviews += storedScans[i].needsReviews; recommendations += storedScans[i].recommendations; } totalIssues = violations+needsReviews+recommendations; } else if (scanType === "selected") { for (let i=0; i < storedScans.length; i++) { if (storedScans[i].isSelected === true) { violations += storedScans[i].violations; needsReviews += storedScans[i].needsReviews; recommendations += storedScans[i].recommendations; } } totalIssues = violations+needsReviews+recommendations; } // counts let level1Counts = [0,0,0,0]; // level 1 total issues, violations, needs reviews, recommendations let level2Counts = [0,0,0,0]; let level3Counts = [0,0,0,0]; let level4Counts = [0,0,0,0]; let level1V = []; let level2V = []; let level3V = []; let level4V = []; let level1NR = []; let level2NR = []; let level3NR = []; let level4NR = []; let level1R = []; let level2R = []; let level3R = []; let level4R = []; let j = scanType === "current" ? storedScans.length - 1 : 0; // NEED TO FIX for selected for (j; j < storedScans.length; j++) { // for each scan const myStoredData = storedScans[j].storedScanData; if (scanType === "selected" && storedScans[j].isSelected === true) { for (let i=0; i<myStoredData.length;i++) { // for each issue row if (myStoredData[i][5] == 1) { // if level 1 level1Counts[0]++; if (myStoredData[i][4] === "Violation") { level1Counts[1]++; level1V.push(myStoredData[i][9]); } if (myStoredData[i][4] === "Needs review") { level1Counts[2]++; level1NR.push(myStoredData[i][9]); } if (myStoredData[i][4] === "Recommendation") { level1Counts[3]++; level1R.push(myStoredData[i][9]); } } if (myStoredData[i][5] == 2) { // if level 2 level2Counts[0]++; if (myStoredData[i][4] === "Violation") { level2Counts[1]++; level2V.push(myStoredData[i][9]); } if (myStoredData[i][4] === "Needs review") { level2Counts[2]++; level2NR.push(myStoredData[i][9]); } if (myStoredData[i][4] === "Recommendation") { level2Counts[3]++; level2R.push(myStoredData[i][9]); } } if (myStoredData[i][5] == 3) { // if level 3 level3Counts[0]++; if (myStoredData[i][4] === "Violation") { level3Counts[1]++; level3V.push(myStoredData[i][9]); } if (myStoredData[i][4] === "Needs review") { level3Counts[2]++; level3NR.push(myStoredData[i][9]); } if (myStoredData[i][4] === "Recommendation") { level3Counts[3]++; level3R.push(myStoredData[i][9]); } } if (myStoredData[i][5] == 4) { // if level 4 level4Counts[0]++; if (myStoredData[i][4] === "Violation") { level4Counts[1]++; level4V.push(myStoredData[i][9]); } if (myStoredData[i][4] === "Needs review") { level4Counts[2]++; level4NR.push(myStoredData[i][9]); } if (myStoredData[i][4] === "Recommendation") { level4Counts[3]++; level4R.push(myStoredData[i][9]); } } } } else if (scanType === "all") { for (let i=0; i<myStoredData.length;i++) { // for each issue row if (myStoredData[i][5] == 1) { // if level 1 level1Counts[0]++; if (myStoredData[i][4] === "Violation") { level1Counts[1]++; level1V.push(myStoredData[i][9]); } if (myStoredData[i][4] === "Needs review") { level1Counts[2]++; level1NR.push(myStoredData[i][9]); } if (myStoredData[i][4] === "Recommendation") { level1Counts[3]++; level1R.push(myStoredData[i][9]); } } if (myStoredData[i][5] == 2) { // if level 2 level2Counts[0]++; if (myStoredData[i][4] === "Violation") { level2Counts[1]++; level2V.push(myStoredData[i][9]); } if (myStoredData[i][4] === "Needs review") { level2Counts[2]++; level2NR.push(myStoredData[i][9]); } if (myStoredData[i][4] === "Recommendation") { level2Counts[3]++; level2R.push(myStoredData[i][9]); } } if (myStoredData[i][5] == 3) { // if level 3 level3Counts[0]++; if (myStoredData[i][4] === "Violation") { level3Counts[1]++; level3V.push(myStoredData[i][9]); } if (myStoredData[i][4] === "Needs review") { level3Counts[2]++; level3NR.push(myStoredData[i][9]); } if (myStoredData[i][4] === "Recommendation") { level3Counts[3]++; level3R.push(myStoredData[i][9]); } } if (myStoredData[i][5] == 4) { // if level 4 level4Counts[0]++; if (myStoredData[i][4] === "Violation") { level4Counts[1]++; level4V.push(myStoredData[i][9]); } if (myStoredData[i][4] === "Needs review") { level4Counts[2]++; level4NR.push(myStoredData[i][9]); } if (myStoredData[i][4] === "Recommendation") { level4Counts[3]++; level4R.push(myStoredData[i][9]); } } } } else if (scanType === "current") { for (let i=0; i<myStoredData.length;i++) { // for each issue row if (myStoredData[i][5] == 1) { // if level 1 level1Counts[0]++; if (myStoredData[i][4] === "Violation") { level1Counts[1]++; level1V.push(myStoredData[i][9]); } if (myStoredData[i][4] === "Needs review") { level1Counts[2]++; level1NR.push(myStoredData[i][9]); } if (myStoredData[i][4] === "Recommendation") { level1Counts[3]++; level1R.push(myStoredData[i][9]); } } if (myStoredData[i][5] == 2) { // if level 2 level2Counts[0]++; if (myStoredData[i][4] === "Violation") { level2Counts[1]++; level2V.push(myStoredData[i][9]); } if (myStoredData[i][4] === "Needs review") { level2Counts[2]++; level2NR.push(myStoredData[i][9]); } if (myStoredData[i][4] === "Recommendation") { level2Counts[3]++; level2R.push(myStoredData[i][9]); } } if (myStoredData[i][5] == 3) { // if level 3 level3Counts[0]++; if (myStoredData[i][4] === "Violation") { level3Counts[1]++; level3V.push(myStoredData[i][9]); } if (myStoredData[i][4] === "Needs review") { level3Counts[2]++; level3NR.push(myStoredData[i][9]); } if (myStoredData[i][4] === "Recommendation") { level3Counts[3]++; level3R.push(myStoredData[i][9]); } } if (myStoredData[i][5] == 4) { // if level 4 level4Counts[0]++; if (myStoredData[i][4] === "Violation") { level4Counts[1]++; level4V.push(myStoredData[i][9]); } if (myStoredData[i][4] === "Needs review") { level4Counts[2]++; level4NR.push(myStoredData[i][9]); } if (myStoredData[i][4] === "Recommendation") { level4Counts[3]++; level4R.push(myStoredData[i][9]); } } } } } // @ts-ignore let level1VrowValues: { [index: string]:any } = this.countDuplicatesInArray(level1V); // note this returns an object // @ts-ignore let level1NRrowValues: { [index: string]:any } = this.countDuplicatesInArray(level1NR); // @ts-ignore let level1RrowValues: { [index: string]:any } = this.countDuplicatesInArray(level1R); // @ts-ignore let level2VrowValues: { [index: string]:any } = this.countDuplicatesInArray(level2V); // note this returns an object // @ts-ignore let level2NRrowValues: { [index: string]:any } = this.countDuplicatesInArray(level2NR); // @ts-ignore let level2RrowValues: { [index: string]:any } = this.countDuplicatesInArray(level2R); // @ts-ignore let level3VrowValues: { [index: string]:any } = this.countDuplicatesInArray(level3V); // note this returns an object // @ts-ignore let level3NRrowValues: { [index: string]:any } = this.countDuplicatesInArray(level3NR); // @ts-ignore let level3RrowValues: { [index: string]:any } = this.countDuplicatesInArray(level3R); // @ts-ignore let level4VrowValues: { [index: string]:any } = this.countDuplicatesInArray(level4V); // note this returns an object // @ts-ignore let level4NRrowValues: { [index: string]:any } = this.countDuplicatesInArray(level4NR); // @ts-ignore let level4RrowValues: { [index: string]:any } = this.countDuplicatesInArray(level4R); const worksheet = workbook.addWorksheet("Issue summary"); // Approach: // 1. sort by levels // 2. for each level sort by V, NR and R // 3. for each V, NR, and R in a level get issue dup counts // 4. build the rows // build Issue summary title worksheet.mergeCells('A1', "B1"); const titleRow = worksheet.getRow(1); titleRow.height = "27"; // actual is 36 const cellA1 = worksheet.getCell('A1'); cellA1.value = "Issue summary"; cellA1.alignment = { vertical: "middle", horizontal: "left"}; cellA1.font = { name: "Calibri", color: { argb: "FFFFFFFF" }, size: "16" }; cellA1.fill = { type: 'pattern', pattern: 'solid', fgColor:{argb:'FF403151'} }; const colWidthData = [ {col: 'A', width: '155.51'}, // note .84 added to actual width {col: 'B', width: '21.16'}, ] for (let i=0; i<2; i++) { worksheet.getColumn(colWidthData[i].col).width = colWidthData[i].width; } // build Description title worksheet.mergeCells('A2', "B2"); const descriptionRow = worksheet.getRow(2); descriptionRow.height = "20.25"; // actual is 27 const cellA2 = worksheet.getCell("A2"); cellA2.value = " In the IBM Equal Access Toolkit, issues are divided into three levels (1-3). Tackle the levels in order to address some of the most impactful issues first."; cellA2.alignment = { vertical: "middle", horizontal: "left"}; cellA2.font = { name: "Calibri", color: { argb: "FF000000" }, size: "12" }; // cellA2.fill = { type: 'pattern', pattern: 'solid', fgColor:{argb:'FFCCC0DA'} }; // build Total issues found: title // worksheet.mergeCells('A3', "B3"); const totalIssuesRow = worksheet.getRow(3); totalIssuesRow.height = "27"; // actual is 36 const cellA3 = worksheet.getCell("A3"); cellA3.value = "Total issues found:"; cellA3.alignment = { vertical: "middle", horizontal: "left"}; cellA3.font = { name: "Calibri", color: { argb: "FFFFFFFF" }, size: "16" }; cellA3.fill = { type: 'pattern', pattern: 'solid', fgColor:{argb:'FF000000'} }; const cellB3 = worksheet.getCell("B3"); cellB3.value = totalIssues; cellB3.alignment = { vertical: "middle", horizontal: "right"}; cellB3.font = { name: "Calibri", color: { argb: "FFFFFFFF" }, size: "16" }; cellB3.fill = { type: 'pattern', pattern: 'solid', fgColor:{argb:'FF000000'} }; // build Number of issues title const numberOfIssuesRow = worksheet.getRow(4); numberOfIssuesRow.height = "20.25"; // actual is 27 const cellA4 = worksheet.getCell("A4"); // no value cellA4.alignment = { vertical: "middle", horizontal: "left"}; cellA4.border = { top: {style:'thin', color: {argb: 'FFA6A6A6'}}, left: {style:'thin', color: {argb: 'FFA6A6A6'}}, bottom: {style:'thin', color: {argb: 'FFA6A6A6'}}, right: {style:'thin', color: {argb: 'FFFFFFFF'}} }; const cellB4 = worksheet.getCell("B4"); cellB4.value = "Number of issues"; cellB4.alignment = { vertical: "middle", horizontal: "right"}; cellB4.font = { name: "Calibri", color: { argb: "FF000000" }, size: "12" }; cellB4.border = { top: {style:'thin', color: {argb: 'FFA6A6A6'}}, left: {style:'thin', color: {argb: 'FFFFFFFF'}}, bottom: {style:'thin', color: {argb: 'FFA6A6A6'}}, right: {style:'thin', color: {argb: 'FFA6A6A6'}} }; ///////////////////////////// // build Level 1 title ///////////////////////////// const level1Row = worksheet.getRow(5); level1Row.height = "27"; // actual is 36 const cellA5 = worksheet.getCell("A5"); cellA5.value = "Level 1 - the most essential issues to address"; cellA5.alignment = { vertical: "middle", horizontal: "left"}; cellA5.font = { name: "Calibri", color: { argb: "FFFFFFFF" }, size: "16" }; cellA5.fill = { type: 'pattern', pattern: 'solid', fgColor:{argb:'FF403151'} }; const cellB5 = worksheet.getCell("B5"); cellB5.value = level1Counts[0]; // total Level 1 issues cellB5.alignment = { vertical: "middle", horizontal: "right"}; cellB5.font = { name: "Calibri", color: { argb: "FFFFFFFF" }, size: "16" }; cellB5.fill = { type: 'pattern', pattern: 'solid', fgColor:{argb:'FF403151'} }; // Level 1 Violation title const level1ViolationRow = worksheet.getRow(6); level1ViolationRow.height = "18"; // target is 21 const cellA6 = worksheet.getCell("A6"); cellA6.value = " Violation"; cellA6.alignment = { vertical: "middle", horizontal: "left"}; cellA6.font = { name: "Calibri", color: { argb: "FF000000" }, size: "12" }; cellA6.fill = { type: 'pattern', pattern: 'solid', fgColor:{argb:'FFE4AAAF'} }; level1ViolationRow.getCell(1).border = { top: {style:'thin', color: {argb: 'FFA6A6A6'}}, left: {style:'thin', color: {argb: 'FFA6A6A6'}}, bottom: {style:'thin', color: {argb: 'FFA6A6A6'}}, // right: {style:'thin', color: {argb: 'FFA6A6A6'}} }; const cellB6 = worksheet.getCell("B6"); cellB6.value = level1Counts[1]; // total level 1 violations cellB6.alignment = { vertical: "middle", horizontal: "right"}; cellB6.font = { name: "Calibri", color: { argb: "FF000000" }, size: "12" }; cellB6.fill = { type: 'pattern', pattern: 'solid', fgColor:{argb:'FFE4AAAF'} }; level1ViolationRow.getCell(2).border = { top: {style:'thin', color: {argb: 'FFA6A6A6'}}, // left: {style:'thin', color: {argb: 'FFA6A6A6'}}, bottom: {style:'thin', color: {argb: 'FFA6A6A6'}}, right: {style:'thin', color: {argb: 'FFA6A6A6'}} }; // Level 1 Violation Rows // build rows let rowArray = []; for (const property in level1VrowValues) { let row = [" "+`${property}`, parseInt(`${level1VrowValues[property]}`) ]; rowArray.push(row); } // sort array according to count rowArray.sort((a,b) => (a[1] < b[1]) ? 1 : -1); // add array of rows let rows = worksheet.addRows(rowArray); rows.forEach((row:any) => { row.height = 14; row.getCell(1).alignment = { vertical: "middle", horizontal: "left"}; row.getCell(2).alignment = { vertical: "middle", horizontal: "right"}; row.font = { name: "Calibri", color: { argb: "FF000000" }, size: "12" }; // row.getCell(1).fill = { type: 'pattern', pattern: 'solid', fgColor:{argb:'FFf8cbad'} }; // row.getCell(2).fill = { type: 'pattern', pattern: 'solid', fgColor:{argb:'FFf8cbad'} }; row.getCell(1).border = { top: {style:'thin', color: {argb: 'FFA6A6A6'}}, left: {style:'thin', color: {argb: 'FFA6A6A6'}}, bottom: {style:'thin', color: {argb: 'FFA6A6A6'}}, // right: {style:'thin', color: {argb: 'FFA6A6A6'}} }; row.getCell(2).border = { top: {style:'thin', color: {argb: 'FFA6A6A6'}}, // left: {style:'thin', color: {argb: 'FFA6A6A6'}}, bottom: {style:'thin', color: {argb: 'FFA6A6A6'}}, right: {style:'thin', color: {argb: 'FFA6A6A6'}} }; }); // Level 1 Needs review title const level1NeedsReviewRow = worksheet.addRow(["", 0]); level1NeedsReviewRow.height = "18"; // target is 21 level1NeedsReviewRow.getCell(1).value = " Needs review"; level1NeedsReviewRow.getCell(1).alignment = { vertical: "middle", horizontal: "left"}; level1NeedsReviewRow.getCell(1).font = { name: "Calibri", color: { argb: "FF000000" }, size: "12" }; level1NeedsReviewRow.getCell(1).fill = { type: 'pattern', pattern: 'solid', fgColor:{argb:'FFF4E08A'} }; level1NeedsReviewRow.getCell(1).border = { top: {style:'thin', color: {argb: 'FFA6A6A6'}}, left: {style:'thin', color: {argb: 'FFA6A6A6'}}, bottom: {style:'thin', color: {argb: 'FFA6A6A6'}}, // right: {style:'thin', color: {argb: 'FFA6A6A6'}} }; level1NeedsReviewRow.getCell(2).value = level1Counts[2]; // total level 1 needs review level1NeedsReviewRow.getCell(2).alignment = { vertical: "middle", horizontal: "right"}; level1NeedsReviewRow.getCell(2).font = { name: "Calibri", color: { argb: "FF000000" }, size: "12" }; level1NeedsReviewRow.getCell(2).fill = { type: 'pattern', pattern: 'solid', fgColor:{argb:'FFF4E08A'} }; level1NeedsReviewRow.getCell(2).border = { top: {style:'thin', color: {argb: 'FFA6A6A6'}}, // left: {style:'thin', color: {argb: 'FFA6A6A6'}}, bottom: {style:'thin', color: {argb: 'FFA6A6A6'}}, right: {style:'thin', color: {argb: 'FFA6A6A6'}} }; // Level 1 Needs review Rows // build rows rowArray = []; for (const property in level1NRrowValues) { let row = [" "+`${property}`, parseInt(`${level1NRrowValues[property]}`) ]; rowArray.push(row); } // sort array according to count rowArray.sort((a,b) => (a[1] < b[1]) ? 1 : -1); // add array of rows rows = []; rows = worksheet.addRows(rowArray); rows.forEach((row:any) => { row.height = 14; row.getCell(1).alignment = { vertical: "middle", horizontal: "left"}; row.getCell(2).alignment = { vertical: "middle", horizontal: "right"}; row.font = { name: "Calibri", color: { argb: "FF000000" }, size: "12" }; //row.getCell(1).fill = { type: 'pattern', pattern: 'solid', fgColor:{argb:'FFf8cbad'} }; //row.getCell(2).fill = { type: 'pattern', pattern: 'solid', fgColor:{argb:'FFf8cbad'} }; row.getCell(1).border = { top: {style:'thin', color: {argb: 'FFA6A6A6'}}, left: {style:'thin', color: {argb: 'FFA6A6A6'}}, bottom: {style:'thin', color: {argb: 'FFA6A6A6'}}, // right: {style:'thin', color: {argb: 'FFA6A6A6'}} }; row.getCell(2).border = { top: {style:'thin', color: {argb: 'FFA6A6A6'}}, // left: {style:'thin', color: {argb: 'FFA6A6A6'}}, bottom: {style:'thin', color: {argb: 'FFA6A6A6'}}, right: {style:'thin', color: {argb: 'FFA6A6A6'}} }; }); // Level 1 Recommendation title const level1RecommendationRow = worksheet.addRow(["", 0]); level1RecommendationRow.height = "18"; // target is 21 level1RecommendationRow.getCell(1).value = " Recommendation"; level1RecommendationRow.getCell(1).alignment = { vertical: "middle", horizontal: "left"}; level1RecommendationRow.getCell(1).font = { name: "Calibri", color: { argb: "FF000000" }, size: "12" }; level1RecommendationRow.getCell(1).fill = { type: 'pattern', pattern: 'solid', fgColor:{argb:'FF96A9D7'} }; level1RecommendationRow.getCell(1).border = { top: {style:'thin', color: {argb: 'FFA6A6A6'}}, left: {style:'thin', color: {argb: 'FFA6A6A6'}}, bottom: {style:'thin', color: {argb: 'FFA6A6A6'}}, // right: {style:'thin', color: {argb: 'FFA6A6A6'}} }; level1RecommendationRow.getCell(2).value = level1Counts[3]; // total level 1 recommendations level1RecommendationRow.getCell(2).alignment = { vertical: "middle", horizontal: "right"}; level1RecommendationRow.getCell(2).font = { name: "Calibri", color: { argb: "FFFFFFFF" }, size: "12" }; level1RecommendationRow.getCell(2).fill = { type: 'pattern', pattern: 'solid', fgColor:{argb:'FF96A9D7'} }; level1RecommendationRow.getCell(2).border = { top: {style:'thin', color: {argb: 'FFA6A6A6'}}, // left: {style:'thin', color: {argb: 'FFA6A6A6'}}, bottom: {style:'thin', color: {argb: 'FFA6A6A6'}}, right: {style:'thin', color: {argb: 'FFA6A6A6'}} }; // Level 1 Recommendation Rows // build rows rowArray = []; for (const property in level1RrowValues) { let row = [" "+`${property}`, parseInt(`${level1RrowValues[property]}`) ]; rowArray.push(row); } // sort array according to count rowArray.sort((a,b) => (a[1] < b[1]) ? 1 : -1); // add array of rows rows = []; rows = worksheet.addRows(rowArray); rows.forEach((row:any) => { row.height = 14; row.getCell(1).alignment = { vertical: "middle", horizontal: "left"}; row.getCell(2).alignment = { vertical: "middle", horizontal: "right"}; row.font = { name: "Calibri", color: { argb: "FF000000" }, size: "12" }; //row.getCell(1).fill = { type: 'pattern', pattern: 'solid', fgColor:{argb:'FFf8cbad'} }; //row.getCell(2).fill = { type: 'pattern', pattern: 'solid', fgColor:{argb:'FFf8cbad'} }; row.getCell(1).border = { top: {style:'thin', color: {argb: 'FFA6A6A6'}}, left: {style:'thin', color: {argb: 'FFA6A6A6'}}, bottom: {style:'thin', color: {argb: 'FFA6A6A6'}}, // right: {style:'thin', color: {argb: 'FFA6A6A6'}} }; row.getCell(2).border = { top: {style:'thin', color: {argb: 'FFA6A6A6'}}, // left: {style:'thin', color: {argb: 'FFA6A6A6'}}, bottom: {style:'thin', color: {argb: 'FFA6A6A6'}}, right: {style:'thin', color: {argb: 'FFA6A6A6'}} }; }); ///////////////////////////// // build Level 2 title ///////////////////////////// const level2Row = worksheet.addRow(["",0]); level2Row.height = "27"; // actual is 36 level2Row.getCell(1).value = "Level 2 - the next most important issues"; level2Row.getCell(1).alignment = { vertical: "middle", horizontal: "left"}; level2Row.getCell(1).font = { name: "Calibri", color: { argb: "FFFFFFFF" }, size: "16" }; level2Row.getCell(1).fill = { type: 'pattern', pattern: 'solid', fgColor:{argb:'FF403151'} }; level2Row.getCell(2).value = level2Counts[0]; // total Level 2 issues level2Row.getCell(2).alignment = { vertical: "middle", horizontal: "right"}; level2Row.getCell(2).font = { name: "Calibri", color: { argb: "FFFFFFFF" }, size: "16" }; level2Row.getCell(2).fill = { type: 'pattern', pattern: 'solid', fgColor:{argb:'FF403151'} }; // Level 2 Violation title const level2ViolationRow = worksheet.addRow(["",0]); level2ViolationRow.height = "18"; // target is 21 level2ViolationRow.getCell(1).value = " Violation"; level2ViolationRow.getCell(1).alignment = { vertical: "middle", horizontal: "left"}; level2ViolationRow.getCell(1).font = { name: "Calibri", color: { argb: "FF000000" }, size: "12" }; level2ViolationRow.getCell(1).fill = { type: 'pattern', pattern: 'solid', fgColor:{argb:'FFE4AAAF'} }; level2ViolationRow.getCell(1).border = { top: {style:'thin', color: {argb: 'FFA6A6A6'}}, left: {style:'thin', color: {argb: 'FFA6A6A6'}}, bottom: {style:'thin', color: {argb: 'FFA6A6A6'}}, // right: {style:'thin', color: {argb: 'FFA6A6A6'}} }; level2ViolationRow.getCell(2).value = level2Counts[1]; // total level 2 violations level2ViolationRow.getCell(2).alignment = { vertical: "middle", horizontal: "right"}; level2ViolationRow.getCell(2).font = { name: "Calibri", color: { argb: "FF000000" }, size: "12" }; level2ViolationRow.getCell(2).fill = { type: 'pattern', pattern: 'solid', fgColor:{argb:'FFE4AAAF'} }; level2ViolationRow.getCell(2).border = { top: {style:'thin', color: {argb: 'FFA6A6A6'}}, // left: {style:'thin', color: {argb: 'FFA6A6A6'}}, bottom: {style:'thin', color: {argb: 'FFA6A6A6'}}, right: {style:'thin', color: {argb: 'FFA6A6A6'}} }; // Level 2 Violation Rows // build rows rowArray = []; for (const property in level2VrowValues) { let row = [" "+`${property}`, parseInt(`${level2VrowValues[property]}`) ]; rowArray.push(row); } // sort array according to count rowArray.sort((a,b) => (a[1] < b[1]) ? 1 : -1); // add array of rows rows = worksheet.addRows(rowArray); rows.forEach((row:any) => { row.height = 14; row.getCell(1).alignment = { vertical: "middle", horizontal: "left"}; row.getCell(2).alignment = { vertical: "middle", horizontal: "right"}; row.font = { name: "Calibri", color: { argb: "FF000000" }, size: "12" }; //row.getCell(1).fill = { type: 'pattern', pattern: 'solid', fgColor:{argb:'FFf8cbad'} }; //row.getCell(2).fill = { type: 'pattern', pattern: 'solid', fgColor:{argb:'FFf8cbad'} }; row.getCell(1).border = { top: {style:'thin', color: {argb: 'FFA6A6A6'}}, left: {style:'thin', color: {argb: 'FFA6A6A6'}}, bottom: {style:'thin', color: {argb: 'FFA6A6A6'}}, // right: {style:'thin', color: {argb: 'FFA6A6A6'}} }; row.getCell(2).border = { top: {style:'thin', color: {argb: 'FFA6A6A6'}}, // left: {style:'thin', color: {argb: 'FFA6A6A6'}}, bottom: {style:'thin', color: {argb: 'FFA6A6A6'}}, right: {style:'thin', color: {argb: 'FFA6A6A6'}} }; }); // Level 2 Needs review title const level2NeedsReviewRow = worksheet.addRow(["", 0]); level2NeedsReviewRow.height = "18"; // target is 21 level2NeedsReviewRow.getCell(1).value = " Needs review"; level2NeedsReviewRow.getCell(1).alignment = { vertical: "middle", horizontal: "left"}; level2NeedsReviewRow.getCell(1).font = { name: "Calibri", color: { argb: "FF000000" }, size: "12" }; level2NeedsReviewRow.getCell(1).fill = { type: 'pattern', pattern: 'solid', fgColor:{argb:'FFF4E08A'} }; level2NeedsReviewRow.getCell(1).border = { top: {style:'thin', color: {argb: 'FFA6A6A6'}}, left: {style:'thin', color: {argb: 'FFA6A6A6'}}, bottom: {style:'thin', color: {argb: 'FFA6A6A6'}}, // right: {style:'thin', color: {argb: 'FFA6A6A6'}} }; level2NeedsReviewRow.getCell(2).value = level2Counts[2]; // total level 2 needs review level2NeedsReviewRow.getCell(2).alignment = { vertical: "middle", horizontal: "right"}; level2NeedsReviewRow.getCell(2).font = { name: "Calibri", color: { argb: "FF000000" }, size: "12" }; level2NeedsReviewRow.getCell(2).fill = { type: 'pattern', pattern: 'solid', fgColor:{argb:'FFF4E08A'} }; level2NeedsReviewRow.getCell(2).border = { top: {style:'thin', color: {argb: 'FFA6A6A6'}}, // left: {style:'thin', color: {argb: 'FFA6A6A6'}}, bottom: {style:'thin', color: {argb: 'FFA6A6A6'}}, right: {style:'thin', color: {argb: 'FFA6A6A6'}} }; // Level 2 Needs review Rows // build rows rowArray = []; for (const property in level2NRrowValues) { let row = [" "+`${property}`, parseInt(`${level2NRrowValues[property]}`) ]; rowArray.push(row); } // sort array according to count rowArray.sort((a,b) => (a[1] < b[1]) ? 1 : -1); // add array of rows rows = []; rows = worksheet.addRows(rowArray); rows.forEach((row:any) => { row.height = 14; row.getCell(1).alignment = { vertical: "middle", horizontal: "left"}; row.getCell(2).alignment = { vertical: "middle", horizontal: "right"}; row.font = { name: "Calibri", color: { argb: "FF000000" }, size: "12" }; //row.getCell(1).fill = { type: 'pattern', pattern: 'solid', fgColor:{argb:'FFf8cbad'} }; //row.getCell(2).fill = { type: 'pattern', pattern: 'solid', fgColor:{argb:'FFf8cbad'} }; row.getCell(1).border = { top: {style:'thin', color: {argb: 'FFA6A6A6'}}, left: {style:'thin', color: {argb: 'FFA6A6A6'}}, bottom: {style:'thin', color: {argb: 'FFA6A6A6'}}, // right: {style:'thin', color: {argb: 'FFA6A6A6'}} }; row.getCell(2).border = { top: {style:'thin', color: {argb: 'FFA6A6A6'}}, // left: {style:'thin', color: {argb: 'FFA6A6A6'}}, bottom: {style:'thin', color: {argb: 'FFA6A6A6'}}, right: {style:'thin', color: {argb: 'FFA6A6A6'}} }; }); // Level 2 Recommendation title const level2RecommendationRow = worksheet.addRow(["", 0]); level2RecommendationRow.height = "18"; // target is 21 level2RecommendationRow.getCell(1).value = " Recommendation"; level2RecommendationRow.getCell(1).alignment = { vertical: "middle", horizontal: "left"}; level2RecommendationRow.getCell(1).font = { name: "Calibri", color: { argb: "FF000000" }, size: "12" }; level2RecommendationRow.getCell(1).fill = { type: 'pattern', pattern: 'solid', fgColor:{argb:'FF96A9D7'} }; level2RecommendationRow.getCell(1).border = { top: {style:'thin', color: {argb: 'FFA6A6A6'}}, left: {style:'thin', color: {argb: 'FFA6A6A6'}}, bottom: {style:'thin', color: {argb: 'FFA6A6A6'}}, // right: {style:'thin', color: {argb: 'FFA6A6A6'}} }; level2RecommendationRow.getCell(2).value = level2Counts[3]; // total level 2 recommendations level2RecommendationRow.getCell(2).alignment = { vertical: "middle", horizontal: "right"}; level2RecommendationRow.getCell(2).font = { name: "Calibri", color: { argb: "FFFFFFFF" }, size: "12" }; level2RecommendationRow.getCell(2).fill = { type: 'pattern', pattern: 'solid', fgColor:{argb:'FF96A9D7'} }; level2RecommendationRow.getCell(2).border = { top: {style:'thin', color: {argb: 'FFA6A6A6'}}, // left: {style:'thin', color: {argb: 'FFA6A6A6'}}, bottom: {style:'thin', color: {argb: 'FFA6A6A6'}}, right: {style:'thin', color: {argb: 'FFA6A6A6'}} }; // Level 2 Recommendation Rows // build rows rowArray = []; for (const property in level2RrowValues) { let row = [" "+`${property}`, parseInt(`${level2RrowValues[property]}`) ]; rowArray.push(row); } // sort array according to count rowArray.sort((a,b) => (a[1] < b[1]) ? 1 : -1); // add array of rows rows = []; rows = worksheet.addRows(rowArray); rows.forEach((row:any) => { row.height = 14; row.getCell(1).alignment = { vertical: "middle", horizontal: "left"}; row.getCell(2).alignment = { vertical: "middle", horizontal: "right"}; row.font = { name: "Calibri", color: { argb: "FF000000" }, size: "12" }; //row.getCell(1).fill = { type: 'pattern', pattern: 'solid', fgColor:{argb:'FFf8cbad'} }; //row.getCell(2).fill = { type: 'pattern', pattern: 'solid', fgColor:{argb:'FFf8cbad'} }; row.getCell(1).border = { top: {style:'thin', color: {argb: 'FFA6A6A6'}}, left: {style:'thin', color: {argb: 'FFA6A6A6'}}, bottom: {style:'thin', color: {argb: 'FFA6A6A6'}}, // right: {style:'thin', color: {argb: 'FFA6A6A6'}} }; row.getCell(2).border = { top: {style:'thin', color: {argb: 'FFA6A6A6'}}, // left: {style:'thin', color: {argb: 'FFA6A6A6'}}, bottom: {style:'thin', color: {argb: 'FFA6A6A6'}}, right: {style:'thin', color: {argb: 'FFA6A6A6'}} }; }); ///////////////////////////// // build Level 3 title ///////////////////////////// const level3Row = worksheet.addRow(["",0]); level3Row.height = "27"; // actual is 36 level3Row.getCell(1).value = "Level 3 - necessary to complete IBM requirements"; level3Row.getCell(1).alignment = { vertical: "middle", horizontal: "left"}; level3Row.getCell(1).font = { name: "Calibri", color: { argb: "FFFFFFFF" }, size: "16" }; level3Row.getCell(1).fill = { type: 'pattern', pattern: 'solid', fgColor:{argb:'FF403151'} }; level3Row.getCell(2).value = level3Counts[0]; // total Level 3 issues level3Row.getCell(2).alignment = { vertical: "middle", horizontal: "right"}; level3Row.getCell(2).font = { name: "Calibri", color: { argb: "FFFFFFFF" }, size: "16" }; level3Row.getCell(2).fill = { type: 'pattern', pattern: 'solid', fgColor:{argb:'FF403151'} }; // Level 3 Violation title const level3ViolationRow = worksheet.addRow(["",0]); level3ViolationRow.height = "18"; // target is 21 level3ViolationRow.getCell(1).value = " Violation"; level3ViolationRow.getCell(1).alignment = { vertical: "middle", horizontal: "left"}; level3ViolationRow.getCell(1).font = { name: "Calibri", color: { argb: "FF000000" }, size: "12" }; level3ViolationRow.getCell(1).fill = { type: 'pattern', pattern: 'solid', fgColor:{argb:'FFE4AAAF'} }; level3ViolationRow.getCell(1).border = { top: {style:'thin', color: {argb: 'FFA6A6A6'}}, left: {style:'thin', color: {argb: 'FFA6A6A6'}}, bottom: {style:'thin', color: {argb: 'FFA6A6A6'}}, // right: {style:'thin', color: {argb: 'FFA6A6A6'}} }; level3ViolationRow.getCell(2).value = level3Counts[1]; // total level 3 violations level3ViolationRow.getCell(2).alignment = { vertical: "middle", horizontal: "right"}; level3ViolationRow.getCell(2).font = { name: "Calibri", color: { argb: "FFFFFFFF" }, size: "12" }; level3ViolationRow.getCell(2).fill = { type: 'pattern', pattern: 'solid', fgColor:{argb:'FFE4AAAF'} }; level3ViolationRow.getCell(2).border = { top: {style:'thin', color: {argb: 'FFA6A6A6'}}, // left: {style:'thin', color: {argb: 'FFA6A6A6'}}, bottom: {style:'thin', color: {argb: 'FFA6A6A6'}}, right: {style:'thin', color: {argb: 'FFA6A6A6'}} }; // Level 3 Violation Rows // build rows rowArray = []; for (const property in level3VrowValues) { let row = [" "+`${property}`, parseInt(`${level3VrowValues[property]}`) ]; rowArray.push(row); } // sort array according to count rowArray.sort((a,b) => (a[1] < b[1]) ? 1 : -1); // add array of rows rows = worksheet.addRows(rowArray); rows.forEach((row:any) => { row.height = 14; row.getCell(1).alignment = { vertical: "middle", horizontal: "left"}; row.getCell(2).alignment = { vertical: "middle", horizontal: "right"}; row.font = { name: "Calibri", color: { argb: "FF000000" }, size: "12" }; //row.getCell(1).fill = { type: 'pattern', pattern: 'solid', fgColor:{argb:'FFf8cbad'} }; //row.getCell(2).fill = { type: 'pattern', pattern: 'solid', fgColor:{argb:'FFf8cbad'} }; row.getCell(1).border = { top: {style:'thin', color: {argb: 'FFA6A6A6'}}, left: {style:'thin', color: {argb: 'FFA6A6A6'}}, bottom: {style:'thin', color: {argb: 'FFA6A6A6'}}, // right: {style:'thin', color: {argb: 'FFA6A6A6'}} }; row.getCell(2).border = { top: {style:'thin', color: {argb: 'FFA6A6A6'}}, // left: {style:'thin', color: {argb: 'FFA6A6A6'}}, bottom: {style:'thin', color: {argb: 'FFA6A6A6'}}, right: {style:'thin', color: {argb: 'FFA6A6A6'}} }; }); // Level 3 Needs review title const level3NeedsReviewRow = worksheet.addRow(["", 0]); level3NeedsReviewRow.height = "18"; // target is 21 level3NeedsReviewRow.getCell(1).value = " Needs review"; level3NeedsReviewRow.getCell(1).alignment = { vertical: "middle", horizontal: "left"}; level3NeedsReviewRow.getCell(1).font = { name: "Calibri", color: { argb: "FF000000" }, size: "12" }; level3NeedsReviewRow.getCell(1).fill = { type: 'pattern', pattern: 'solid', fgColor:{argb:'FFF4E08A'} }; level3NeedsReviewRow.getCell(1).border = { top: {style:'thin', color: {argb: 'FFA6A6A6'}}, left: {style:'thin', color: {argb: 'FFA6A6A6'}}, bottom: {style:'thin', color: {argb: 'FFA6A6A6'}}, // right: {style:'thin', color: {argb: 'FFA6A6A6'}} }; level3NeedsReviewRow.getCell(2).value = level3Counts[2]; // total level 3 needs review level3NeedsReviewRow.getCell(2).alignment = { vertical: "middle", horizontal: "right"}; level3NeedsReviewRow.getCell(2).font = { name: "Calibri", color: { argb: "FF000000" }, size: "12" }; level3NeedsReviewRow.getCell(2).fill = { type: 'pattern', pattern: 'solid', fgColor:{argb:'FFF4E08A'} }; level3NeedsReviewRow.getCell(2).border = { top: {style:'thin', color: {argb: 'FFA6A6A6'}}, // left: {style:'thin', color: {argb: 'FFA6A6A6'}}, bottom: {style:'thin', color: {argb: 'FFA6A6A6'}}, right: {style:'thin', color: {argb: 'FFA6A6A6'}} }; // Level 3 Needs review Rows // build rows rowArray = []; for (const property in level3NRrowValues) { let row = [" "+`${property}`, parseInt(`${level3NRrowValues[property]}`) ]; rowArray.push(row); } // sort array according to count rowArray.sort((a,b) => (a[1] < b[1]) ? 1 : -1); // add array of rows rows = []; rows = worksheet.addRows(rowArray); rows.forEach((row:any) => { row.height = 14; row.getCell(1).alignment = { vertical: "middle", horizontal: "left"}; row.getCell(2).alignment = { vertical: "middle", horizontal: "right"}; row.font = { name: "Calibri", color: { argb: "FF000000" }, size: "12" }; //row.getCell(1).fill = { type: 'pattern', pattern: 'solid', fgColor:{argb:'FFf8cbad'} }; //row.getCell(2).fill = { type: 'pattern', pattern: 'solid', fgColor:{argb:'FFf8cbad'} }; row.getCell(1).border = { top: {style:'thin', color: {argb: 'FFA6A6A6'}}, left: {style:'thin', color: {argb: 'FFA6A6A6'}}, bottom: {style:'thin', color: {argb: 'FFA6A6A6'}}, // right: {style:'thin', color: {argb: 'FFA6A6A6'}} }; row.getCell(2).border = { top: {style:'thin', color: {argb: 'FFA6A6A6'}}, // left: {style:'thin', color: {argb: 'FFA6A6A6'}}, bottom: {style:'thin', color: {argb: 'FFA6A6A6'}}, right: {style:'thin', color: {argb: 'FFA6A6A6'}} }; }); // Level 3 Recommendation title const level3RecommendationRow = worksheet.addRow(["", 0]); level3RecommendationRow.height = "18"; // target is 21 level3RecommendationRow.getCell(1).value = " Recommendation"; level3RecommendationRow.getCell(1).alignment = { vertical: "middle", horizontal: "left"}; level3RecommendationRow.getCell(1).font = { name: "Calibri", color: { argb: "FF000000" }, size: "12" }; level3RecommendationRow.getCell(1).fill = { type: 'pattern', pattern: 'solid', fgColor:{argb:'FF96A9D7'} }; level3RecommendationRow.getCell(1).border = { top: {style:'thin', color: {argb: 'FFA6A6A6'}}, left: {style:'thin', color: {argb: 'FFA6A6A6'}}, bottom: {style:'thin', color: {argb: 'FFA6A6A6'}}, // right: {style:'thin', color: {argb: 'FFA6A6A6'}} }; level3RecommendationRow.getCell(2).value = level3Counts[3]; // total level 3 recommendations level3RecommendationRow.getCell(2).alignment = { vertical: "middle", horizontal: "right"}; level3RecommendationRow.getCell(2).font = { name: "Calibri", color: { argb: "FFFFFFFF" }, size: "12" }; level3RecommendationRow.getCell(2).fill = { type: 'pattern', pattern: 'solid', fgColor:{argb:'FF96A9D7'} }; level3RecommendationRow.getCell(2).border = { top: {style:'thin', color: {argb: 'FFA6A6A6'}}, // left: {style:'thin', color: {argb: 'FFA6A6A6'}}, bottom: {style:'thin', color: {argb: 'FFA6A6A6'}}, right: {style:'thin', color: {argb: 'FFA6A6A6'}} }; // Level 3 Recommendation Rows // build rows rowArray = []; for (const property in level3RrowValues) { let row = [" "+`${property}`, parseInt(`${level3RrowValues[property]}`) ]; rowArray.push(row); } // sort array according to count rowArray.sort((a,b) => (a[1] < b[1]) ? 1 : -1); // add array of rows rows = []; rows = worksheet.addRows(rowArray); rows.forEach((row:any) => { row.height = 14; row.getCell(1).alignment = { vertical: "middle", horizontal: "left"}; row.getCell(2).alignment = { vertical: "middle", horizontal: "right"}; row.font = { name: "Calibri", color: { argb: "FF000000" }, size: "12" }; //row.getCell(1).fill = { type: 'pattern', pattern: 'solid', fgColor:{argb:'FFf8cbad'} }; //row.getCell(2).fill = { type: 'pattern', pattern: 'solid', fgColor:{argb:'FFf8cbad'} }; row.getCell(1).border = { top: {style:'thin', color: {argb: 'FFA6A6A6'}}, left: {style:'thin', color: {argb: 'FFA6A6A6'}}, bottom: {style:'thin', color: {argb: 'FFA6A6A6'}}, // right: {style:'thin', color: {argb: 'FFA6A6A6'}} }; row.getCell(2).border = { top: {style:'thin', color: {argb: 'FFA6A6A6'}}, // left: {style:'thin', color: {argb: 'FFA6A6A6'}}, bottom: {style:'thin', color: {argb: 'FFA6A6A6'}}, right: {style:'thin', color: {argb: 'FFA6A6A6'}} }; }); ///////////////////////////// // build Level 4 title ///////////////////////////// const level4Row = worksheet.addRow(["",0]); level4Row.height = "27"; // actual is 36 level4Row.getCell(1).value = "Level 4 - further recommended improvements to accessibility"; level4Row.getCell(1).alignment = { vertical: "middle", horizontal: "left"}; level4Row.getCell(1).font = { name: "Calibri", color: { argb: "FFFFFFFF" }, size: "16" }; level4Row.getCell(1).fill = { type: 'pattern', pattern: 'solid', fgColor:{argb:'FF403151'} }; level4Row.getCell(2).value = level4Counts[0]; // total Level 4 issues level4Row.getCell(2).alignment = { vertical: "middle", horizontal: "right"}; level4Row.getCell(2).font = { name: "Calibri", color: { argb: "FFFFFFFF" }, size: "16" }; level4Row.getCell(2).fill = { type: 'pattern', pattern: 'solid', fgColor:{argb:'FF403151'} }; // Level 4 Violation title const level4ViolationRow = worksheet.addRow(["",0]); level4ViolationRow.height = "18"; // target is 21 level4ViolationRow.getCell(1).value = " Violation"; level4ViolationRow.getCell(1).alignment = { vertical: "middle", horizontal: "left"}; level4ViolationRow.getCell(1).font = { name: "Calibri", color: { argb: "FF000000" }, size: "12" }; level4ViolationRow.getCell(1).fill = { type: 'pattern', pattern: 'solid', fgColor:{argb:'FFE4AAAF'} }; level4ViolationRow.getCell(1).border = { top: {style:'thin', color: {argb: 'FFA6A6A6'}}, left: {style:'thin', color: {argb: 'FFA6A6A6'}}, bottom: {style:'thin', color: {argb: 'FFA6A6A6'}}, // right: {style:'thin', color: {argb: 'FFA6A6A6'}} }; level4ViolationRow.getCell(2).value = level4Counts[1]; // total level 4 violations level4ViolationRow.getCell(2).alignment = { vertical: "middle", horizontal: "right"}; level4ViolationRow.getCell(2).font = { name: "Calibri", color: { argb: "FF000000" }, size: "12" }; level4ViolationRow.getCell(2).fill = { type: 'pattern', pattern: 'solid', fgColor:{argb:'FFE4AAAF'} }; level4ViolationRow.getCell(2).border = { top: {style:'thin', color: {argb: 'FFA6A6A6'}}, // left: {style:'thin', color: {argb: 'FFA6A6A6'}}, bottom: {style:'thin', color: {argb: 'FFA6A6A6'}}, right: {style:'thin', color: {argb: 'FFA6A6A6'}} }; // Level 4 Violation Rows // build rows rowArray = []; for (const property in level4VrowValues) { let row = [" "+`${property}`, parseInt(`${level4VrowValues[property]}`) ]; rowArray.push(row); } // sort array according to count rowArray.sort((a,b) => (a[1] < b[1]) ? 1 : -1); // add array of rows rows = worksheet.addRows(rowArray); rows.forEach((row:any) => { row.height = 14; row.getCell(1).alignment = { vertical: "middle", horizontal: "left"}; row.getCell(2).alignment = { vertical: "middle", horizontal: "right"}; row.font = { name: "Calibri", color: { argb: "FF000000" }, size: "12" }; //row.getCell(1).fill = { type: 'pattern', pattern: 'solid', fgColor:{argb:'FFf8cbad'} }; //row.getCell(2).fill = { type: 'pattern', pattern: 'solid', fgColor:{argb:'FFf8cbad'} }; row.getCell(1).border = { top: {style:'thin', color: {argb: 'FFA6A6A6'}}, left: {style:'thin', color: {argb: 'FFA6A6A6'}}, bottom: {style:'thin', color: {argb: 'FFA6A6A6'}}, // right: {style:'thin', color: {argb: 'FFA6A6A6'}} }; row.getCell(2).border = { top: {style:'thin', color: {argb: 'FFA6A6A6'}}, // left: {style:'thin', color: {argb: 'FFA6A6A6'}}, bottom: {style:'thin', color: {argb: 'FFA6A6A6'}}, right: {style:'thin', color: {argb: 'FFA6A6A6'}} }; }); // Level 4 Needs review title const level4NeedsReviewRow = worksheet.addRow(["", 0]); level4NeedsReviewRow.height = "18"; // target is 21 level4NeedsReviewRow.getCell(1).value = " Needs review"; level4NeedsReviewRow.getCell(1).alignment = { vertical: "middle", horizontal: "left"}; level4NeedsReviewRow.getCell(1).font = { name: "Calibri", color: { argb: "FF000000" }, size: "12" }; level4NeedsReviewRow.getCell(1).fill = { type: 'pattern', pattern: 'solid', fgColor:{argb:'FFF4E08A'} }; level4NeedsReviewRow.getCell(1).border = { top: {style:'thin', color: {argb: 'FFA6A6A6'}}, left: {style:'thin', color: {argb: 'FFA6A6A6'}}, bottom: {style:'thin', color: {argb: 'FFA6A6A6'}}, // right: {style:'thin', color: {argb: 'FFA6A6A6'}} }; level4NeedsReviewRow.getCell(2).value = level4Counts[2]; // total level 4 needs review level4NeedsReviewRow.getCell(2).alignment = { vertical: "middle", horizontal: "right"}; level4NeedsReviewRow.getCell(2).font = { name: "Calibri", color: { argb: "FF000000" }, size: "12" }; level4NeedsReviewRow.getCell(2).fill = { type: 'pattern', pattern: 'solid', fgColor:{argb:'FFF4E08A'} }; level4NeedsReviewRow.getCell(2).border = { top: {style:'thin', color: {argb: 'FFA6A6A6'}}, // left: {style:'thin', color: {argb: 'FFA6A6A6'}}, bottom: {style:'thin', color: {argb: 'FFA6A6A6'}}, right: {style:'thin', color: {argb: 'FFA6A6A6'}} }; // Level 4 Needs review Rows // build rows rowArray = []; for (const property in level4NRrowValues) { let row = [" "+`${property}`, parseInt(`${level4NRrowValues[property]}`) ]; rowArray.push(row); } // sort array according to count rowArray.sort((a,b) => (a[1] < b[1]) ? 1 : -1); // add array of rows rows = []; rows = worksheet.addRows(rowArray); rows.forEach((row:any) => { row.height = 14; row.getCell(1).alignment = { vertical: "middle", horizontal: "left"}; row.getCell(2).alignment = { vertical: "middle", horizontal: "right"}; row.font = { name: "Calibri", color: { argb: "FF000000" }, size: "12" }; //row.getCell(1).fill = { type: 'pattern', pattern: 'solid', fgColor:{argb:'FFf8cbad'} }; //row.getCell(2).fill = { type: 'pattern', pattern: 'solid', fgColor:{argb:'FFf8cbad'} }; row.getCell(1).border = { top: {style:'thin', color: {argb: 'FFA6A6A6'}}, left: {style:'thin', color: {argb: 'FFA6A6A6'}}, bottom: {style:'thin', color: {argb: 'FFA6A6A6'}}, // right: {style:'thin', color: {argb: 'FFA6A6A6'}} }; row.getCell(2).border = { top: {style:'thin', color: {argb: 'FFA6A6A6'}}, // left: {style:'thin', color: {argb: 'FFA6A6A6'}}, bottom: {style:'thin', color: {argb: 'FFA6A6A6'}}, right: {style:'thin', color: {argb: 'FFA6A6A6'}} }; }); // Level 4 Recommendation title const level4RecommendationRow = worksheet.addRow(["", 0]); level4RecommendationRow.height = "18"; // target is 21 level4RecommendationRow.getCell(1).value = " Recommendation"; level4RecommendationRow.getCell(1).alignment = { vertical: "middle", horizontal: "left"}; level4RecommendationRow.getCell(1).font = { name: "Calibri", color: { argb: "FF000000" }, size: "12" }; level4RecommendationRow.getCell(1).fill = { type: 'pattern', pattern: 'solid', fgColor:{argb:'FF96A9D7'} }; level4RecommendationRow.getCell(1).border = { top: {style:'thin', color: {argb: 'FFA6A6A6'}}, left: {style:'thin', color: {argb: 'FFA6A6A6'}}, bottom: {style:'thin', color: {argb: 'FFA6A6A6'}}, // right: {style:'thin', color: {argb: 'FFA6A6A6'}} }; level4RecommendationRow.getCell(2).value = level4Counts[3]; // total level 4 recommendations level4RecommendationRow.getCell(2).alignment = { vertical: "middle", horizontal: "right"}; level4RecommendationRow.getCell(2).font = { name: "Calibri", color: { argb: "FFFFFFFF" }, size: "12" }; level4RecommendationRow.getCell(2).fill = { type: 'pattern', pattern: 'solid', fgColor:{argb:'FF96A9D7'} }; level4RecommendationRow.getCell(2).border = { top: {style:'thin', color: {argb: 'FFA6A6A6'}}, // left: {style:'thin', color: {argb: 'FFA6A6A6'}}, bottom: {style:'thin', color: {argb: 'FFA6A6A6'}}, right: {style:'thin', color: {argb: 'FFA6A6A6'}} }; // Level 4 Recommendation Rows // build rows rowArray = []; for (const property in level4RrowValues) { let row = [" "+`${property}`, parseInt(`${level4RrowValues[property]}`) ]; rowArray.push(row); } // sort array according to count rowArray.sort((a,b) => (a[1] < b[1]) ? 1 : -1); // add array of rows rows = []; rows = worksheet.addRows(rowArray); rows.forEach((row:any) => { row.height = 14; row.getCell(1).alignment = { vertical: "middle", horizontal: "left"}; row.getCell(2).alignment = { vertical: "middle", horizontal: "right"}; row.font = { name: "Calibri", color: { argb: "FF000000" }, size: "12" }; //row.getCell(1).fill = { type: 'pattern', pattern: 'solid', fgColor:{argb:'FFf8cbad'} }; //row.getCell(2).fill = { type: 'pattern', pattern: 'solid', fgColor:{argb:'FFf8cbad'} }; row.getCell(1).border = { top: {style:'thin', color: {argb: 'FFA6A6A6'}}, left: {style:'thin', color: {argb: 'FFA6A6A6'}}, bottom: {style:'thin', color: {argb: 'FFA6A6A6'}}, // right: {style:'thin', color: {argb: 'FFA6A6A6'}} }; row.getCell(2).border = { top: {style:'thin', color: {argb: 'FFA6A6A6'}}, // left: {style:'thin', color: {argb: 'FFA6A6A6'}}, bottom: {style:'thin', color: {argb: 'FFA6A6A6'}}, right: {style:'thin', color: {argb: 'FFA6A6A6'}} }; }); } public static createIssuesSheet(storedScans: any, scanType: string, workbook: any) { const worksheet = workbook.addWorksheet("Issues"); // build rows let rowArray = []; let j = scanType === "current" ? storedScans.length - 1 : 0; // NEED TO FIX for selected for (j; j < storedScans.length; j++) { const myStoredData = storedScans[j].storedScanData; if (scanType === "selected" && storedScans[j].isSelected === true) { for (let i=0; i<myStoredData.length;i++) { let row = [myStoredData[i][0], myStoredData[i][1], storedScans[j].userScanLabel, myStoredData[i][3], myStoredData[i][4], Number.isNaN(myStoredData[i][5]) ? "n/a" : myStoredData[i][5], myStoredData[i][6], Number.isNaN(myStoredData[i][5]) ? "n/a" : myStoredData[i][7], myStoredData[i][8], myStoredData[i][9], myStoredData[i][10], myStoredData[i][11], myStoredData[i][12], myStoredData[i][13] ]; rowArray.push(row); } } else if (scanType === "all") { for (let i=0; i<myStoredData.length;i++) { let row = [myStoredData[i][0], myStoredData[i][1], storedScans[j].userScanLabel, myStoredData[i][3], myStoredData[i][4], Number.isNaN(myStoredData[i][5]) ? "n/a" : myStoredData[i][5], myStoredData[i][6], Number.isNaN(myStoredData[i][5]) ? "n/a" : myStoredData[i][7], myStoredData[i][8], myStoredData[i][9], myStoredData[i][10], myStoredData[i][11], myStoredData[i][12], myStoredData[i][13] ]; rowArray.push(row); } } else if (scanType === "current") { for (let i=0; i<myStoredData.length;i++) { let row = [myStoredData[i][0], myStoredData[i][1], storedScans[j].userScanLabel, myStoredData[i][3], myStoredData[i][4], Number.isNaN(myStoredData[i][5]) ? "n/a" : myStoredData[i][5], myStoredData[i][6], Number.isNaN(myStoredData[i][5]) ? "n/a" : myStoredData[i][7], myStoredData[i][8], myStoredData[i][9], myStoredData[i][10], myStoredData[i][11], myStoredData[i][12], myStoredData[i][13] ]; rowArray.push(row); } } } // column widths const colWidthData = [ {col: 'A', width: '18.0', alignment: { vertical: "middle", horizontal: "left"}}, {col: 'B', width: '20.5', alignment: { vertical: "middle", horizontal: "left"}}, {col: 'C', width: '21.0', alignment: { vertical: "middle", horizontal: "center"}}, {col: 'D', width: '18.5', alignment: { vertical: "middle", horizontal: "left"}}, {col: 'E', width: '17.0', alignment: { vertical: "middle", horizontal: "center"}}, {col: 'F', width: '17.17', alignment: { vertical: "middle", horizontal: "center"}}, {col: 'G', width: '17.17', alignment: { vertical: "middle", horizontal: "left"}}, {col: 'H', width: '17.17', alignment: { vertical: "middle", horizontal: "center"}}, {col: 'I', width: '17.17', alignment: { vertical: "middle", horizontal: "left"}}, {col: 'J', width: '17.17', alignment: { vertical: "middle", horizontal: "left"}}, {col: 'K', width: '14.00', alignment: { vertical: "middle", horizontal: "center"}}, {col: 'L', width: '17.17', alignment: { vertical: "middle", horizontal: "left"}}, {col: 'M', width: '43.00', alignment: { vertical: "middle", horizontal: "left"}}, {col: 'N', width: '17.17', alignment: { vertical: "middle", horizontal: "fill"}}, ] for (let i=0; i<14; i++) { worksheet.getColumn(colWidthData[i].col).width = colWidthData[i].width; worksheet.getColumn(colWidthData[i].col).alignment = colWidthData[i].alignment; } // set font and alignment for the header cells for (let i=1; i<15; i++) { worksheet.getRow(1).getCell(i).alignment = { vertical: "middle", horizontal: "center", wrapText: true }; worksheet.getRow(1).getCell(i).font = { name: "Calibri", color: { argb: "FFFFFFFF" }, size: "12" }; worksheet.getRow(1).getCell(i).fill = { type: 'pattern', pattern: 'solid', fgColor:{argb:'FF403151'} }; worksheet.getRow(1).getCell(i).border = { top: {style:'thin', color: {argb: 'FFA6A6A6'}}, left: {style:'thin', color: {argb: 'FFA6A6A6'}}, bottom: {style:'thin', color: {argb: 'FFA6A6A6'}}, right: {style:'thin', color: {argb: 'FFA6A6A6'}} } } // height for header row worksheet.getRow(1).height = 24; // add table to a sheet worksheet.addTable({ name: 'MyTable', ref: 'A1', headerRow: true, // totalsRow: true, style: { theme: 'TableStyleMedium2', showRowStripes: true, }, columns: [ {name: 'Page title', filterButton: true}, {name: 'Page URL', filterButton: true}, {name: 'Scan label', filterButton: true}, {name: 'Issue ID', filterButton: true}, {name: 'Issue type', filterButton: true}, {name: 'Toolkit level', filterButton: true}, {name: 'Checkpoint', filterButton: true}, {name: 'WCAG level', filterButton: true}, {name: 'Rule', filterButton: true}, {name: 'Issue', filterButton: true}, {name: 'Element', filterButton: true}, {name: 'Code', filterButton: true}, {name: 'Xpath', filterButton: true}, {name: 'Help', filterButton: true}, ], rows: rowArray }); for (let i=2; i<=rowArray.length+1; i++) { worksheet.getRow(i).height = 14; for (let j=1; j<=14; j++) { worksheet.getRow(i).getCell(j).border = { top: {style:'thin', color: {argb: 'FFA6A6A6'}}, left: {style:'thin', color: {argb: 'FFA6A6A6'}}, bottom: {style:'thin', color: {argb: 'FFA6A6A6'}}, right: {style:'thin', color: {argb: 'FFA6A6A6'}} } } } } public static createDefinitionsSheet(workbook: any) { const worksheet = workbook.addWorksheet("Definition of fields"); // "Definition of fields" title worksheet.mergeCells('A1', "B1"); const titleRow = worksheet.getRow(1); titleRow.height = "36"; // actual is 48 titleRow.getCell(1).value = "Definition of fields"; titleRow.getCell(1).alignment = { vertical: "middle", horizontal: "left"}; titleRow.getCell(1).font = { name: "Calibri", color: { argb: "FFFFFFFF" }, size: "20" }; titleRow.getCell(1).fill = { type: 'pattern', pattern: 'solid', fgColor:{argb:'FF403151'} }; const colWidthData = [ {col: 'A', width: '41.51'}, // note .84 added to actual width {col: 'B', width: '119.51'}, ] for (let i=0; i<2; i++) { worksheet.getColumn(colWidthData[i].col).width = colWidthData[i].width; } // blank row worksheet.mergeCells('A2', "B2"); const blankRow = worksheet.getRow(2); blankRow.height = "12"; // actual is 16 // "Scan summary and Issue summary" title worksheet.mergeCells('A3', "B3"); const summaryRow = worksheet.getRow(3); summaryRow.height = "20"; // actual is 26.75 summaryRow.getCell(1).value = "Scan summary and Issue summary"; summaryRow.getCell(1).alignment = { vertical: "middle", horizontal: "left"}; summaryRow.getCell(1).font = { name: "Calibri", color: { argb: "FFFFFFFF" }, size: "16" }; summaryRow.getCell(1).fill = { type: 'pattern', pattern: 'solid', fgColor:{argb:'FF403151'} }; // row 4 Field / Definition const row4 = worksheet.getRow(4); row4.height = "16"; // actual is row4.getCell(1).value = "Field"; row4.getCell(2).value = "Definition"; row4.getCell(1).alignment = row4.getCell(2).alignment = { vertical: "middle", horizontal: "left"}; row4.getCell(1).font = row4.getCell(2).font = { name: "Calibri", color: { argb: "FF000000" }, size: "16" }; row4.getCell(1).fill = row4.getCell(2).fill = { type: 'pattern', pattern: 'solid', fgColor:{argb:'FFCCC0DA'} }; row4.getCell(1).border = row4.getCell(2).border = { top: {style:'thin', color: {argb: 'FFA6A6A6'}}, left: {style:'thin', color: {argb: 'FFA6A6A6'}}, bottom: {style:'thin', color: {argb: 'FFA6A6A6'}}, right: {style:'thin', color: {argb: 'FFA6A6A6'}} }; // rows 5-13 // set row height for rows 5-13 for (let i=5; i<14; i++) { worksheet.getRow(i).height = 12; // results in a row height of 16 } let rowData = [ {key1: 'Page', key2: 'Identifies the page or html file that was scanned.'}, {key1: 'Scan label', key2: 'Label for the scan. Default values can be edited in the Accessibility Checker before saving this report, or programmatically assigned in automated testing.'}, {key1: 'Base scan', key2: 'Scan label for a previous scan against which this scan was compared. Only new issues are reported when a base scan is used.'}, {key1: 'Violations', key2: 'Accessibility failures that need to be corrected.'}, {key1: 'Needs review', key2: 'Issues that may not be a violation. These need a manual review to identify whether there is an accessibility problem.'}, {key1: 'Recommendations', key2: 'Opportunities to apply best practices to further improve accessibility.'}, {key1: '% elements without violations', key2: 'Percentage of elements on the page that had no violations found.'}, {key1: '% elements without violations or items to review', key2: 'Percentage of elements on the page that had no violations found and no items to review.'}, {key1: 'Level 1,2,3', key2: 'Priority level defined by the IBM Equal Access Toolkit. See https://www.ibm.com/able/toolkit/plan#pace-of-completion for details.'} ]; for (let i=5; i<14; i++) { worksheet.getRow(i).getCell(1).font = worksheet.getRow(i).getCell(2).font = { name: "Calibri", color: { argb: "FF000000" }, size: "12" }; worksheet.getRow(i).getCell(1).alignment = worksheet.getRow(i).getCell(2).alignment = { horizontal: "left"}; } for (let i=5; i<14; i++) { worksheet.getRow(i).getCell(1).value = rowData[i-5].key1; worksheet.getRow(i).getCell(2).value = rowData[i-5].key2; } // "Scan summary and Issue summary" title worksheet.mergeCells('A14', "B14"); const issuesRow = worksheet.getRow(14); issuesRow.height = "20"; // actual is 26.75 issuesRow.getCell(1).value = "Issues"; issuesRow.getCell(1).alignment = { vertical: "middle", horizontal: "left"}; issuesRow.getCell(1).font = { name: "Calibri", color: { argb: "FFFFFFFF" }, size: "16" }; issuesRow.getCell(1).fill = { type: 'pattern', pattern: 'solid', fgColor:{argb:'FF403151'} }; // row 15 Field / Definition const row15 = worksheet.getRow(15); row15.height = "16"; // actual is row15.getCell(1).value = "Field"; row15.getCell(2).value = "Definition"; row15.getCell(1).alignment = row15.getCell(2).alignment = { vertical: "middle", horizontal: "left"}; row15.getCell(1).font = row15.getCell(2).font = { name: "Calibri", color: { argb: "FF000000" }, size: "16" }; row15.getCell(1).fill = row15.getCell(2).fill = { type: 'pattern', pattern: 'solid', fgColor:{argb:'FFCCC0DA'} }; row15.getCell(1).border = row15.getCell(2).border = { top: {style:'thin', color: {argb: 'FFA6A6A6'}}, left: {style:'thin', color: {argb: 'FFA6A6A6'}}, bottom: {style:'thin', color: {argb: 'FFA6A6A6'}}, right: {style:'thin', color: {argb: 'FFA6A6A6'}} }; // rows 16-28 // set row height for rows 16-28 for (let i=16; i<29; i++) { worksheet.getRow(i).height = 12; // results in a row height of 16 } rowData = []; rowData = [ {key1: 'Page', key2: 'Identifies the page or html file that was scanned.'}, {key1: 'Scan label', key2: 'Label for the scan. Default values can be edited in the Accessibility Checker before saving this report, or programmatically assigned in automated testing.'}, {key1: 'Issue ID', key2: 'Identifier for this issue within this page. Rescanning the same page will produce the same issue ID. '}, {key1: 'Issue type', key2: 'Violation, needs review, or recommendation'}, {key1: 'Toolkit level', key2: '1, 2 or 3. Priority level defined by the IBM Equal Access Toolkit. See https://www.ibm.com/able/toolkit/plan#pace-of-completion for details'}, {key1: 'Checkpoint', key2: 'Web Content Accessibility Guidelines (WCAG) checkpoints this issue falls into.'}, {key1: 'WCAG level', key2: 'A, AA or AAA. WCAG level for this issue.'}, {key1: 'Rule', key2: 'Name of the accessibility test rule that detected this issue.'}, {key1: 'Issue', key2: 'Message describing the issue.'}, {key1: 'Element', key2: 'Type of HTML element where the issue is found.'}, {key1: 'Code', key2: 'Actual HTML element where the issue is found.'}, {key1: 'Xpath', key2: 'Xpath of the HTML element where the issue is found.'}, {key1: 'Help', key2: 'Link to a more detailed description of the issue and suggested solutions.'}, ]; for (let i=16; i<29; i++) { worksheet.getRow(i).getCell(1).font = worksheet.getRow(i).getCell(2).font = { name: "Calibri", color: { argb: "FF000000" }, size: "12" }; worksheet.getRow(i).getCell(1).alignment = worksheet.getRow(i).getCell(2).alignment = { horizontal: "left"}; } for (let i=16; i<29; i++) { worksheet.getRow(i).getCell(1).value = rowData[i-16].key1; worksheet.getRow(i).getCell(2).value = rowData[i-16].key2; } } public static countDuplicatesInArray(array: []) { let count = {}; // let result = []; array.forEach(item => { if (count[item]) { //@ts-ignore count[item] +=1 return } //@ts-ignore count[item] = 1; }) return count; } }
the_stack
import React from 'react'; import { mountTheme } from '@helpers/enzyme-unit-test'; // Material UI import IconButton from '@mui/material/IconButton'; // Internal import RawFieldSet, { FieldSetContent, } from '../FieldSet'; import { RawFieldSetArray } from '../FieldSetArray'; import { RawFieldSetObject } from '../FieldSetObject'; import ReorderableFormField, { RawReorderableFormField } from '../ReorderableFormField'; import ReorderControls, { RawReorderControls } from '../ReorderControls'; import FormField from '../../FormField'; const { root, row } = { root: 'rootClassName', row: 'rowClassName', }; describe('FieldSet', () => { describe('FieldSet - control', () => { it('mounts (control)', () => { const schema = {}; const data = {}; // act const wrapper = mountTheme({ component: ( <RawFieldSet classes={{ root }} schema={schema} data={data} path={'path'} uiSchema={{}} xhrSchema={{}} onKeyDown={jest.fn} onChange={jest.fn} onXHRSchemaEvent={jest.fn} /> ) }); // check expect(wrapper).toHaveLength(1); const ffComp = wrapper.find(FieldSetContent); expect(ffComp).toHaveLength(1); expect(ffComp.prop('schema')).toBe(schema); const legendComp = wrapper.find('legend'); expect(legendComp).toHaveLength(0); }); }); describe('FieldSetObject', () => { it('mounts with single field (control)', () => { const schema = { type: 'object', properties: { name: { 'type': 'string', 'title': 'Name', }, }, }; const data = { name: 'Bob' }; // act const wrapper = mountTheme({ component: ( <RawFieldSetObject classes={{ row }} schema={schema} data={data} path={''} uiSchema={{}} xhrSchema={{}} onKeyDown={jest.fn} onChange={jest.fn} onXHRSchemaEvent={jest.fn} id={'1'} idxKey={'1'} validation={{}} isTabContent={false} tabKey={''} /> ) }); // check expect(wrapper).toHaveLength(1); // expect(wrapper.prop('className')).toMatch(/rowClassName/); const ffComp = wrapper.find(FormField); expect(ffComp).toHaveLength(1); expect(ffComp.prop('path')).toBe('name'); expect(ffComp.prop('data')).toBe(data.name); expect(ffComp.prop('objectData')).toStrictEqual(data); }); it('mounts with single field with additional properties (control)', () => { const schema = { type: 'object', additionalProperties: { name: { 'type': 'string', 'title': 'Name', }, }, }; const data = { name: 'Bob' }; // act const wrapper = mountTheme({ component: ( <RawFieldSetObject classes={{ row }} schema={schema} data={data} path={''} uiSchema={{}} xhrSchema={{}} onKeyDown={jest.fn} onChange={jest.fn} onXHRSchemaEvent={jest.fn} id={'1'} idxKey={'1'} validation={{}} isTabContent={false} tabKey={''} /> ) }); // check expect(wrapper).toHaveLength(1); // expect(wrapper.prop('className')).toMatch(/rowClassName/); const ffComp = wrapper.find(FormField); expect(ffComp).toHaveLength(2); expect(ffComp.at(1).prop('path')).toBe('name'); expect(ffComp.at(1).prop('data')).toBe(data.name); expect(ffComp.at(1).prop('objectData')).toStrictEqual(data); }); it('respects orientation hint', () => { const schema = { type: 'object', properties: { name: { 'type': 'string', 'title': 'Name', }, }, }; const uiSchema = { 'ui:orientation': 'row', }; const data = { name: 'Bob' }; // act const parent = mountTheme({ component: ( <RawFieldSetObject classes={{ row }} schema={schema} data={data} uiSchema={uiSchema} path={''} xhrSchema={{}} onKeyDown={jest.fn} onChange={jest.fn} onXHRSchemaEvent={jest.fn} id={'1'} idxKey={'1'} validation={{}} isTabContent={false} tabKey={''} /> ) }); const wrapper = parent.find('RawFieldSetObject'); // check expect(wrapper).toHaveLength(1); // expect(wrapper.prop('className')).toMatch(/rowClassName/); const ffComp = wrapper.find(FormField); expect(ffComp).toHaveLength(1); expect(ffComp.prop('path')).toBe('name'); expect(ffComp.prop('data')).toBe(data.name); }); }); describe('FieldSetArray', () => { it('handles simple, orderable list of strings', () => { const path = 'names'; const defaultValue = 'abc'; const startIdx = 2; const array = [0, 1]; const schema = { type: 'array', title: 'My list', items: { 'type': 'string', 'title': 'Name', 'default': defaultValue, }, }; const onMoveItemUp = jest.fn(); const onMoveItemDown = jest.fn(); const onDeleteItem = jest.fn(); onMoveItemUp.mockReturnValue(array.map((i) => (`moveUp${i}`))); onMoveItemDown.mockReturnValue(array.map((i) => (`moveDown${i}`))); onDeleteItem.mockReturnValue(array.map((i) => (`deleteItem${i}`))); const uiSchema = { items: { 'ui:widget': 'textarea', }, }; const data = ['Bob', 'Harry']; const onAddItem = jest.fn(); // act const parent = mountTheme({ component: ( <RawFieldSetArray startIdx={startIdx} onAddItem={onAddItem} onMoveItemUp={onMoveItemUp} onMoveItemDown={onMoveItemDown} onDeleteItem={onDeleteItem} uiSchema={uiSchema} path={path} classes={{ row }} schema={schema} data={data} onXHRSchemaEvent={jest.fn} /> ) }); const wrapper = parent.find('RawFieldSetArray'); // check expect(wrapper).toHaveLength(1); const ffComp = wrapper.find(ReorderableFormField); expect(ffComp).toHaveLength(2); array.forEach((i) => { expect(ffComp.at(i).prop('path')).toBe(`names[${i + startIdx}]`); expect(ffComp.at(i).prop('data')).toBe(data[i]); expect(ffComp.at(i).prop('schema')).toBe(schema.items); expect(ffComp.at(i).prop('uiSchema')).toBe(uiSchema.items); expect(ffComp.at(i).prop('onMoveItemUp')[i]).toBe(`moveUp${i}`); expect(ffComp.at(i).prop('onMoveItemDown')[i]).toBe(`moveDown${i}`); expect(ffComp.at(i).prop('onDeleteItem')[i]).toBe(`deleteItem${i}`); }); expect(ffComp.at(0).prop('first')).toBe(true); expect(ffComp.at(0).prop('last')).toBe(false); expect(ffComp.at(1).prop('first')).toBe(false); expect(ffComp.at(1).prop('last')).toBe(true); const addButton = wrapper.find(IconButton); expect(addButton).toHaveLength(3); expect(addButton.at(2).prop('onClick')).toBe(undefined); expect(onAddItem).toBeCalledWith(path, defaultValue); }); it('handles simple, fixed list of strings', () => { const path = 'names'; const array = [0, 1]; const schema = { type: 'array', title: 'My list', items: [{ 'type': 'string', 'title': 'Name', }, { 'type': 'boolean', 'title': 'Name', }], }; const uiSchema = { items: [{ 'ui:widget': 'textarea', }, { 'ui:widget': 'checkbox', }], }; const data = ['Bob', false]; // act const parent = mountTheme({ component: ( <RawFieldSetArray uiSchema={uiSchema} path={path} classes={{ row }} schema={schema} data={data} onXHRSchemaEvent={jest.fn} /> ) }); const wrapper = parent.find('RawFieldSetArray'); // check expect(wrapper).toHaveLength(1); const ffComp = wrapper.find(FormField); const rffComp = wrapper.find(ReorderableFormField); expect(ffComp).toHaveLength(2); expect(rffComp).toHaveLength(0); array.forEach((idx) => { expect(ffComp.at(idx).prop('path')).toBe(`names[${idx}]`); expect(ffComp.at(idx).prop('data')).toBe(data[idx]); expect(ffComp.at(idx).prop('schema')).toBe(schema.items[idx]); expect(ffComp.at(idx).prop('uiSchema')).toBe(uiSchema.items[idx]); }); }); it('handles simple, fixed list of strings with additional items', () => { const path = 'names'; const onMoveItemUp = jest.fn(() => 'onMoveItemUp'); const onMoveItemDown = jest.fn(() => 'onMoveItemDown'); const onDeleteItem = jest.fn(() => 'onDeleteItem'); const schema = { type: 'array', title: 'My list', items: [{ 'type': 'string', 'title': 'Name', }, { 'type': 'boolean', 'title': 'Name', }], additionalItems: { 'type': 'string', 'title': 'Name', }, }; const uiSchema = { items: [{ 'ui:widget': 'textarea', }, { 'ui:widget': 'checkbox', }], additionalItems: { 'ui:title': 'Children', }, }; const data = ['Bob', false, 'Harry', 'Susan']; // act const parent = mountTheme({ component: ( <RawFieldSetArray onMoveItemUp={onMoveItemUp} onMoveItemDown={onMoveItemDown} onDeleteItem={onDeleteItem} uiSchema={uiSchema} path={path} classes={{ row }} schema={schema} data={data} onXHRSchemaEvent={jest.fn} /> ) }); const wrapper = parent.find('RawFieldSetArray'); // check expect(wrapper).toHaveLength(2); const ffComp = wrapper.find(FormField); expect(ffComp).toHaveLength(4); [0, 1].forEach((i) => { expect(ffComp.at(i).prop('path')).toBe(`names[${i}]`); expect(ffComp.at(i).prop('data')).toBe(data[i]); expect(ffComp.at(i).prop('schema')).toBe(schema.items[i]); expect(ffComp.at(i).prop('uiSchema')).toBe(uiSchema.items[i]); /** Currently ordering is disable for additional props */ // expect(ffComp.at(i)).toHaveProperty('onMoveItemUp'); // expect(ffComp.at(i)).toHaveProperty('onMoveItemDown'); // expect(ffComp.at(i)).toHaveProperty('onDeleteItem'); }); const fsArrayComp = wrapper.find('RawFieldSetArray').at(1); expect(fsArrayComp).toHaveLength(1); expect(fsArrayComp.prop('path')).toBe(path); expect(fsArrayComp.prop('data')).toStrictEqual(['Harry', 'Susan']); expect(fsArrayComp.prop('schema')).toStrictEqual({ type: 'array', items: schema.additionalItems }); expect(fsArrayComp.prop('uiSchema')).toStrictEqual(uiSchema.additionalItems); expect(fsArrayComp.prop('startIdx')).toStrictEqual(schema.items.length); expect(fsArrayComp.prop('onMoveItemUp')).toStrictEqual(onMoveItemUp); expect(fsArrayComp.prop('onMoveItemDown')).toStrictEqual(onMoveItemDown); expect(fsArrayComp.prop('onDeleteItem')).toStrictEqual(onDeleteItem); }); }); describe('ReorderControls', () => { it('renders buttons with callbacks', () => { // prepare const onMoveItemUp = jest.fn(); const onMoveItemDown = jest.fn(); const onDeleteItem = jest.fn(); // act const parent = mountTheme({ component: ( <RawReorderControls onMoveItemDown={onMoveItemDown} onDeleteItem={onDeleteItem} onMoveItemUp={onMoveItemUp} classes={{ row }} first last={false} canReorder /> ) }); const wrapper = parent.find('RawReorderControls'); // check expect(wrapper).toHaveLength(1); const buttonList = wrapper.find(IconButton); expect(buttonList).toHaveLength(3); buttonList.at(0).prop('onClick')(); expect(onMoveItemUp).toHaveBeenCalled(); buttonList.at(1).prop('onClick')(); expect(onMoveItemDown).toHaveBeenCalled(); buttonList.at(2).prop('onClick')(); expect(onDeleteItem).toHaveBeenCalled(); }); it('ReorderControls - first', () => { // act const parent = mountTheme({ component: ( <RawReorderControls first last={false} classes={{ row }} canReorder /> ) }); const wrapper = parent.find('RawReorderControls'); // check expect(wrapper).toHaveLength(1); const buttonList = wrapper.find(IconButton); expect(buttonList).toHaveLength(3); expect(buttonList.at(0).prop('disabled')).toBe(true); expect(buttonList.at(1).prop('disabled')).toBe(false); expect(buttonList.at(2)).not.toHaveProperty('disabled'); }); it('ReorderControls - last', () => { // act const parent = mountTheme({ component: ( <RawReorderControls first={false} last classes={{ row }} canReorder /> ) }); const wrapper = parent.find('RawReorderControls'); // check expect(wrapper).toHaveLength(1); const buttonList = wrapper.find(IconButton); expect(buttonList).toHaveLength(3); expect(buttonList.at(0).prop('disabled')).toBe(false); expect(buttonList.at(1).prop('disabled')).toBe(true); expect(buttonList.at(2)).not.toHaveProperty('disabled'); }); }); describe('ReorderableFormField', () => { it('ReorderableFormField - control', () => { const path = 'path'; const first = true; const last = false; // act const parent = mountTheme({ component: ( <RawReorderableFormField path={path} first={first} last={last} schema={{ type: 'object' }} classes={{ row }} /> ) }); const wrapper = parent.find('RawReorderableFormField'); // check const ffComp = wrapper.find(FormField); expect(ffComp).toHaveLength(1); const controls = wrapper.find(ReorderControls); expect(controls).toHaveLength(1); expect(controls.prop('first')).toBe(first); expect(controls.prop('last')).toBe(last); }); }); });
the_stack
import { ContextLevel } from '@/core/constants'; import { Injectable } from '@angular/core'; import { CoreSiteWSPreSets, CoreSite } from '@classes/site'; import { CoreUser } from '@features/user/services/user'; import { CoreApp } from '@services/app'; import { CoreSites } from '@services/sites'; import { CoreUtils } from '@services/utils/utils'; import { CoreWSExternalWarning } from '@services/ws'; import { makeSingleton } from '@singletons'; import { CoreEvents } from '@singletons/events'; import { CoreRatingOffline } from './rating-offline'; const ROOT_CACHE_KEY = 'CoreRating:'; /** * Service to handle ratings. */ @Injectable( { providedIn: 'root' }) export class CoreRatingProvider { static readonly AGGREGATE_NONE = 0; // No ratings. static readonly AGGREGATE_AVERAGE = 1; static readonly AGGREGATE_COUNT = 2; static readonly AGGREGATE_MAXIMUM = 3; static readonly AGGREGATE_MINIMUM = 4; static readonly AGGREGATE_SUM = 5; static readonly UNSET_RATING = -999; static readonly AGGREGATE_CHANGED_EVENT = 'core_rating_aggregate_changed'; static readonly RATING_SAVED_EVENT = 'core_rating_rating_saved'; /** * Returns whether the web serivce to add ratings is available. * * @return If WS is available. * @deprecated since app 4.0 */ isAddRatingWSAvailable(): boolean { return true; } /** * Add a rating to an item. * * @param component Component. Example: "mod_forum". * @param ratingArea Rating area. Example: "post". * @param contextLevel Context level: course, module, user, etc. * @param instanceId Context instance id. * @param itemId Item id. Example: forum post id. * @param itemSetId Item set id. Example: forum discussion id. * @param courseId Course id. * @param scaleId Scale id. * @param rating Rating value. Use CoreRatingProvider.UNSET_RATING to delete rating. * @param ratedUserId Rated user id. * @param aggregateMethod Aggregate method. * @param siteId Site ID. If not defined, current site. * @return Promise resolved with the aggregated rating or void if stored offline. */ async addRating( component: string, ratingArea: string, contextLevel: ContextLevel, instanceId: number, itemId: number, itemSetId: number, courseId: number, scaleId: number, rating: number, ratedUserId: number, aggregateMethod: number, siteId?: string, ): Promise<CoreRatingAddRatingWSResponse | void> { siteId = siteId || CoreSites.getCurrentSiteId(); // Convenience function to store a rating to be synchronized later. const storeOffline = async (): Promise<void> => { await CoreRatingOffline.addRating( component, ratingArea, contextLevel, instanceId, itemId, itemSetId, courseId, scaleId, rating, ratedUserId, aggregateMethod, siteId, ); CoreEvents.trigger(CoreRatingProvider.RATING_SAVED_EVENT, { component, ratingArea, contextLevel, instanceId, itemSetId, itemId, }, siteId); }; if (!CoreApp.isOnline()) { // App is offline, store the action. return storeOffline(); } try { await CoreRatingOffline.deleteRating(component, ratingArea, contextLevel, instanceId, itemId, siteId); const response = await this.addRatingOnline( component, ratingArea, contextLevel, instanceId, itemId, scaleId, rating, ratedUserId, aggregateMethod, siteId, ); return response; } catch (error) { if (CoreUtils.isWebServiceError(error)) { // The WebService has thrown an error or offline not supported, reject. return Promise.reject(error); } // Couldn't connect to server, store offline. return storeOffline(); } } /** * Add a rating to an item. It will fail if offline or cannot connect. * * @param component Component. Example: "mod_forum". * @param ratingArea Rating area. Example: "post". * @param contextLevel Context level: course, module, user, etc. * @param instanceId Context instance id. * @param itemId Item id. Example: forum post id. * @param scaleId Scale id. * @param rating Rating value. Use CoreRatingProvider.UNSET_RATING to delete rating. * @param ratedUserId Rated user id. * @param aggregateMethod Aggregate method. * @param siteId Site ID. If not defined, current site. * @return Promise resolved with the aggregated rating. */ async addRatingOnline( component: string, ratingArea: string, contextLevel: ContextLevel, instanceId: number, itemId: number, scaleId: number, rating: number, ratedUserId: number, aggregateMethod: number, siteId?: string, ): Promise<CoreRatingAddRatingWSResponse> { const site = await CoreSites.getSite(siteId); const params: CoreRatingAddRatingWSParams = { contextlevel: contextLevel, instanceid: instanceId, component, ratingarea: ratingArea, itemid: itemId, scaleid: scaleId, rating, rateduserid: ratedUserId, aggregation: aggregateMethod, }; const response = await site.write<CoreRatingAddRatingWSResponse>('core_rating_add_rating', params); await this.invalidateRatingItems(contextLevel, instanceId, component, ratingArea, itemId, scaleId); CoreEvents.trigger(CoreRatingProvider.AGGREGATE_CHANGED_EVENT, { contextLevel, instanceId, component, ratingArea, itemId, aggregate: response.aggregate, count: response.count, }); return response; } /** * Get item ratings. * * @param contextLevel Context level: course, module, user, etc. * @param instanceId Context instance id. * @param component Component. Example: "mod_forum". * @param ratingArea Rating area. Example: "post". * @param itemId Item id. Example: forum post id. * @param scaleId Scale id. * @param sort Sort field. * @param courseId Course id. Used for fetching user profiles. * @param siteId Site ID. If not defined, current site. * @param ignoreCache True if it should ignore cached data (it will always fail in offline or server down). * @return Promise resolved with the list of ratings. */ async getItemRatings( contextLevel: ContextLevel, instanceId: number, component: string, ratingArea: string, itemId: number, scaleId: number, sort: string = 'timemodified', courseId?: number, siteId?: string, ignoreCache: boolean = false, ): Promise<CoreRatingItemRating[]> { const site = await CoreSites.getSite(siteId); const params: CoreRatingGetItemRatingsWSParams = { contextlevel: contextLevel, instanceid: instanceId, component, ratingarea: ratingArea, itemid: itemId, scaleid: scaleId, sort, }; const preSets: CoreSiteWSPreSets = { cacheKey: this.getItemRatingsCacheKey(contextLevel, instanceId, component, ratingArea, itemId, scaleId, sort), updateFrequency: CoreSite.FREQUENCY_RARELY, }; if (ignoreCache) { preSets.getFromCache = false; preSets.emergencyCache = false; } const response = await site.read<CoreRatingGetItemRatingsWSResponse>('core_rating_get_item_ratings', params, preSets); if (!site.isVersionGreaterEqualThan([' 3.6.5', '3.7.1', '3.8'])) { // MDL-65042 We need to fetch profiles because the returned profile pictures are incorrect. const promises = response.ratings.map((rating: CoreRatingItemRating) => CoreUser.getProfile(rating.userid, courseId, true, site.id).then((user) => { rating.userpictureurl = user.profileimageurl || ''; return; }).catch(() => { // Ignore error. rating.userpictureurl = ''; })); await Promise.all(promises); } return response.ratings; } /** * Invalidate item ratings. * * @param contextLevel Context level: course, module, user, etc. * @param instanceId Context instance id. * @param component Component. Example: "mod_forum". * @param ratingArea Rating area. Example: "post". * @param itemId Item id. Example: forum post id. * @param scaleId Scale id. * @param sort Sort field. * @param siteId Site ID. If not defined, current site. * @return Promise resolved when the data is invalidated. */ async invalidateRatingItems( contextLevel: ContextLevel, instanceId: number, component: string, ratingArea: string, itemId: number, scaleId: number, sort: string = 'timemodified', siteId?: string, ): Promise<void> { const site = await CoreSites.getSite(siteId); const key = this.getItemRatingsCacheKey(contextLevel, instanceId, component, ratingArea, itemId, scaleId, sort); await site.invalidateWsCacheForKey(key); } /** * Check if rating is disabled in a certain site. * * @param site Site. If not defined, use current site. * @return Whether it's disabled. */ isRatingDisabledInSite(site?: CoreSite): boolean { site = site || CoreSites.getCurrentSite(); return !!site?.isFeatureDisabled('NoDelegate_CoreRating'); } /** * Check if rating is disabled in a certain site. * * @param siteId Site Id. If not defined, use current site. * @return Promise resolved with true if disabled, rejected or resolved with false otherwise. */ async isRatingDisabled(siteId?: string): Promise<boolean> { const site = await CoreSites.getSite(siteId); return this.isRatingDisabledInSite(site); } /** * Convenience function to merge two or more rating infos of the same instance. * * @param ratingInfos Array of rating infos. * @return Merged rating info or undefined. */ mergeRatingInfos(ratingInfos: CoreRatingInfo[]): CoreRatingInfo | undefined { let result: CoreRatingInfo | undefined; const scales: Record<number, CoreRatingScale> = {}; const ratings: Record<number, CoreRatingInfoItem> = {}; ratingInfos.forEach((ratingInfo) => { if (!ratingInfo) { // Skip null rating infos. return; } if (!result) { result = Object.assign({}, ratingInfo); } (ratingInfo.scales || []).forEach((scale) => { scales[scale.id] = scale; }); (ratingInfo.ratings || []).forEach((rating) => { ratings[rating.itemid] = rating; }); }); if (result) { result.scales = CoreUtils.objectToArray(scales); result.ratings = CoreUtils.objectToArray(ratings); } return result; } /** * Prefetch individual ratings. * * This function should be called from the prefetch handler of activities with ratings. * * @param contextLevel Context level: course, module, user, etc. * @param instanceId Instance id. * @param siteId Site id. If not defined, current site. * @param courseId Course id. Used for prefetching user profiles. * @param ratingInfo Rating info returned by web services. * @return Promise resolved when done. */ async prefetchRatings( contextLevel: ContextLevel, instanceId: number, scaleId: number, courseId?: number, ratingInfo?: CoreRatingInfo, siteId?: string, ): Promise<void> { if (!ratingInfo || !ratingInfo.ratings) { return; } const site = await CoreSites.getSite(siteId); const promises = ratingInfo.ratings.map((item) => this.getItemRatings( contextLevel, instanceId, ratingInfo.component, ratingInfo.ratingarea, item.itemid, scaleId, undefined, courseId, site.id, true, )); if (!site.isVersionGreaterEqualThan([' 3.6.5', '3.7.1', '3.8'])) { promises.map((promise) => promise.then(async (ratings) => { const userIds = ratings.map((rating: CoreRatingItemRating) => rating.userid); await CoreUser.prefetchProfiles(userIds, courseId, site.id); return; })); } await Promise.all(promises); } /** * Get cache key for rating items WS calls. * * @param contextLevel Context level: course, module, user, etc. * @param component Component. Example: "mod_forum". * @param ratingArea Rating area. Example: "post". * @param itemId Item id. Example: forum post id. * @param scaleId Scale id. * @param sort Sort field. * @return Cache key. */ protected getItemRatingsCacheKey( contextLevel: ContextLevel, instanceId: number, component: string, ratingArea: string, itemId: number, scaleId: number, sort: string, ): string { return `${ROOT_CACHE_KEY}${contextLevel}:${instanceId}:${component}:${ratingArea}:${itemId}:${scaleId}:${sort}`; } } export const CoreRating = makeSingleton(CoreRatingProvider); declare module '@singletons/events' { /** * Augment CoreEventsData interface with events specific to this service. * * @see https://www.typescriptlang.org/docs/handbook/declaration-merging.html#module-augmentation */ export interface CoreEventsData { [CoreRatingProvider.AGGREGATE_CHANGED_EVENT]: CoreRatingAggregateChangedEventData; [CoreRatingProvider.RATING_SAVED_EVENT]: CoreRatingSavedEventData; } } /** * Structure of the rating info returned by web services. */ export type CoreRatingInfo = { contextid: number; // Context id. component: string; // Context name. ratingarea: string; // Rating area name. canviewall?: boolean; // Whether the user can view all the individual ratings. canviewany?: boolean; // Whether the user can view aggregate of ratings of others. scales?: CoreRatingScale[]; // Different scales used information. ratings?: CoreRatingInfoItem[]; // The ratings. }; /** * Structure of scales in the rating info. */ export type CoreRatingScale = { id: number; // Scale id. courseid?: number; // Course id. name?: string; // Scale name (when a real scale is used). max: number; // Max value for the scale. isnumeric: boolean; // Whether is a numeric scale. items?: { // Scale items. Only returned for not numerical scales. value: number; // Scale value/option id. name: string; // Scale name. }[]; }; /** * Structure of items in the rating info. */ export type CoreRatingInfoItem = { itemid: number; // Item id. scaleid?: number; // Scale id. scale?: CoreRatingScale; // Added for rendering purposes. userid?: number; // User who rated id. aggregate?: number; // Aggregated ratings grade. aggregatestr?: string; // Aggregated ratings as string. aggregatelabel?: string; // The aggregation label. count?: number; // Ratings count (used when aggregating). rating?: number; // The rating the user gave. canrate?: boolean; // Whether the user can rate the item. canviewaggregate?: boolean; // Whether the user can view the aggregated grade. }; /** * Structure of a rating returned by the item ratings web service. */ export type CoreRatingItemRating = { id: number; // Rating id. userid: number; // User id. userpictureurl: string; // URL user picture. userfullname: string; // User fullname. rating: string; // Rating on scale. timemodified: number; // Time modified (timestamp). }; /** * Params of core_rating_get_item_ratings WS. */ type CoreRatingGetItemRatingsWSParams = { contextlevel: ContextLevel; // Context level: course, module, user, etc... instanceid: number; // The instance id of item associated with the context level. component: string; // Component. ratingarea: string; // Rating area. itemid: number; // Associated id. scaleid: number; // Scale id. sort: string; // Sort order (firstname, rating or timemodified). }; /** * Data returned by core_rating_get_item_ratings WS. */ export type CoreRatingGetItemRatingsWSResponse = { ratings: CoreRatingItemRating[]; warnings?: CoreWSExternalWarning[]; }; /** * Params of core_rating_add_rating WS. */ type CoreRatingAddRatingWSParams = { contextlevel: ContextLevel; // Context level: course, module, user, etc... instanceid: number; // The instance id of item associated with the context level. component: string; // Component. ratingarea: string; // Rating area. itemid: number; // Associated id. scaleid: number; // Scale id. rating: number; // User rating. rateduserid: number; // Rated user id. aggregation?: number; // Agreggation method. }; /** * Data returned by core_rating_add_rating WS. */ export type CoreRatingAddRatingWSResponse = { success: boolean; // Whether the rate was successfully created. aggregate?: string; // New aggregate. count?: number; // Ratings count. itemid?: number; // Rating item id. warnings?: CoreWSExternalWarning[]; }; /** * Data sent by AGGREGATE_CHANGED_EVENT event. */ export type CoreRatingAggregateChangedEventData = { contextLevel: ContextLevel; instanceId: number; component: string; ratingArea: string; itemId: number; aggregate?: string; count?: number; }; /** * Data sent by RATING_SAVED_EVENT event. */ export type CoreRatingSavedEventData = { component: string; ratingArea: string; contextLevel: ContextLevel; instanceId: number; itemSetId: number; itemId: number; };
the_stack
import Webhooks = require('@octokit/webhooks') import { PrismaClient, Installation } from '@prisma/client' import bodyParser from 'body-parser' import cors from 'cors' import _ from 'lodash' import moment from 'moment' import ml from 'multilines' import os from 'os' import path from 'path' import { Application, Context } from 'probot' import Stripe from 'stripe' import { createLogger, Logger, transports, format } from 'winston' import { populateTemplate } from './bootstrap' import { getLSConfigRepoName, LSCConfiguration, LS_CONFIG_PATH, parseConfig, configRepos, isConfigRepo, LSCRepository, } from './configuration' import { addLabelsToIssue, bootstrapConfigRepository, checkInstallationAccess, createPRComment, getFile, getRepo, GHTree, GithubLabel, openIssue, removeLabelsFromRepository, } from './github' import { handleLabelSync } from './handlers/labels' import { generateHumanReadableCommitReport, generateHumanReadablePRReport, } from './language/labels' import { loadTreeFromPath, withDefault } from './utils' import { isNullOrUndefined } from 'util' import { create } from 'handlebars' /* Templates */ const TEMPLATES = { yaml: path.resolve(__dirname, '../../templates/yaml'), typescript: path.resolve(__dirname, '../../templates/typescript'), } /* Subscription Plans */ interface Plans { ANNUALLY: string MONTHLY: string } export type Period = keyof Plans const plans: Plans = process.env.NODE_ENV === 'test' ? { ANNUALLY: 'plan_HEG5LPquldqfJp', MONTHLY: 'plan_HEG5wHlZp4io5Q', } : { ANNUALLY: 'price_HKxac3217AdNnw', MONTHLY: 'price_HKxYK7gvZO3ieE', } // : { // ANNUALLY: 'plan_HCkpZId8BCi7cI', // MONTHLY: 'plan_HCkojOBbK8hFh6', // } const corsOrigins = process.env.NODE_ENV === 'test' ? ['http://localhost', 'http://127.0.0.1'] : [ 'https://label-sync.com', 'https://www.label-sync.com', 'https://webhook.label-sync.com', ] /* Application */ module.exports = ( app: Application, /* Stored here for testing */ prisma: PrismaClient = new PrismaClient(), winston: Logger = createLogger({ level: 'debug', exitOnError: false, format: format.json(), transports: [ new transports.Http({ host: 'http-intake.logs.datadoghq.com', path: `/v1/input/${process.env.DATADOG_APIKEY}?ddsource=nodejs&service=label-sync`, ssl: true, }), ], }), stripe: Stripe = new Stripe(process.env.STRIPE_API_KEY!, { apiVersion: '2020-08-27', }), ) => { /* Start the server */ app.log(`LabelSync manager up and running! 🚀`) /* */ /** * Runs the script once on the server. */ /* istanbul ignore next */ async function migrate() { winston.info('Migrating...') const gh = await app.auth() /* Github Installations */ const ghapp = await gh.apps.getAuthenticated().then((res) => res.data) /* Tracked installations */ const lsInstallations = await prisma.installation.count({ where: { activated: true }, }) winston.info(`Existing installations: ${ghapp.installations_count}`) /* Skip sync if all are already tracked. */ if (lsInstallations >= ghapp.installations_count) { winston.info(`All installations in sync.`) return } const installations = await gh.apps .listInstallations({ page: 0, per_page: 100, }) .then((res) => res.data) /* Process installations */ for (const installation of installations) { winston.info(`Syncing with database ${installation.account.login}`) const now = moment() const account = installation.account.login.toLowerCase() await prisma.installation.upsert({ where: { account }, create: { account, email: null, plan: 'FREE', periodEndsAt: now.clone().add(3, 'years').toDate(), activated: true, }, update: { activated: true, }, }) } } /* istanbul ignore next */ if (process.env.NODE_ENV === 'production') { console.log('MIGRATING') migrate() } /* API */ const api = app.route('/subscribe') api.use( cors({ origin: corsOrigins, preflightContinue: true, }), ) api.use(bodyParser.json()) /** * Handles request for subscription. */ api.post('/session', async (req, res) => { try { let { email, account, plan, agreed, period, coupon } = req.body as { [key: string]: string } /* istanbul ignore next */ if ([email, account].some((val) => val.trim() === '')) { return res.send({ status: 'err', message: 'Some fields are missing.', }) } /* istanbul ignore next */ if (!['PAID', 'FREE'].includes(plan)) { return res.send({ status: 'err', message: `Invalid plan ${plan}.`, }) } /* istanbul ignore next */ if (plan === 'PAID' && !['MONTHLY', 'ANNUALLY'].includes(period)) { return res.send({ status: 'err', message: `Invalid period for paid plan ${period}.`, }) } /* Terms of Service */ /* istanbul ignore next */ if (!agreed) { return res.send({ status: 'err', message: 'You must agree with Terms of Service and Privacy Policy.', }) } /* Valid coupon */ /* istanbul ignore next */ if ( coupon !== undefined && (typeof coupon !== 'string' || coupon.trim() === '') ) { return res.send({ status: 'err', message: 'Invalid coupon provided.', }) } /* Unify account casing */ account = account.toLowerCase() /** * People shouldn't be able to change purchase information afterwards. */ const now = moment() await prisma.installation.upsert({ where: { account }, create: { account, email, plan: 'FREE', periodEndsAt: now.clone().add(3, 'years').toDate(), activated: false, }, update: {}, }) switch (plan) { case 'FREE': { /* Return a successful request to redirect to installation. */ return res.send({ status: 'ok', plan: 'FREE' }) } case 'PAID': { /* Figure out the plan */ let plan: string switch (period) { case 'MONTHLY': case 'ANNUALLY': { plan = plans[period as Period] break } /* istanbul ignore next */ default: { throw new Error(`Unknown period ${period}.`) } } /* Create checkout session. */ const session = await stripe.checkout.sessions.create({ payment_method_types: ['card'], subscription_data: { items: [{ plan }], metadata: { period, account, }, coupon, }, customer_email: email, expand: ['subscription'], success_url: 'https://label-sync.com/success', cancel_url: 'https://label-sync.com', }) return res.send({ status: 'ok', plan: 'PAID', session: session.id }) } /* istanbul ignore next */ default: { throw new Error(`Unknown plan ${plan}.`) } } } catch (err) /* istanbul ignore next */ { winston.error(`Error in subscription flow: ${err.message}`) return res.send({ status: 'err', message: err.message }) } }) /* Stripe */ const router = app.route('/stripe') router.post( '/', bodyParser.raw({ type: 'application/json' }), async (req, res) => { /** * Stripe Webhook handler. */ let event try { event = stripe.webhooks.constructEvent( req.body, req.headers['stripe-signature'] as string, process.env.STRIPE_ENDPOINT_SECRET!, ) } catch (err) /* istanbul ingore next */ { winston.error(`Error in stripe webhook deconstruction.`, { meta: { error: err.message, }, }) return res.status(400).send(`Webhook Error: ${err.message}`) } /* Logger */ winston.info(`Stripe event ${event.type}`, { meta: { payload: JSON.stringify(event.data.object), }, }) /* Event handlers */ switch (event.type) { /* Customer successfully subscribed to LabelSync */ case 'checkout.session.completed': /* Customer paid an invoice */ case 'invoice.payment_succeeded': { const payload = event.data.object as { subscription: string } const sub = await stripe.subscriptions.retrieve(payload.subscription) /* Calculate expiration date. */ const now = moment() let expiresAt switch (sub.metadata.period) { case 'ANNUALLY': { expiresAt = now.clone().add(1, 'year').add(3, 'day') break } case 'MONTHLY': { expiresAt = now.clone().add(1, 'month').add(3, 'day') break } /* istanbul ingore next */ default: { throw new Error(`Unknown period ${sub.metadata.period}`) } } /* Update the installation in the database. */ const installation = await prisma.installation.update({ where: { account: sub.metadata.account }, data: { plan: 'PAID', periodEndsAt: expiresAt.toDate(), }, }) winston.info(`New subscriber ${installation.account}`, { meta: { plan: 'PAID', periodEndsAt: installation.periodEndsAt, }, }) return res.json({ received: true }) } /* istanbul ignore next */ default: { winston.warn(`unhandled stripe webhook event: ${event.type}`) return res.status(400).end() } } /* End of Stripe Webhook handler */ }, ) /* Github. */ /** * Marketplace purchase event * * Tasks: * - reference the purchase in the database. */ // app.on('marketplace_purchase.purchased', async (ctx) => { // // TODO: Github Marketplace. // const purchase = ctx.payload.marketplace_purchase // const owner = purchase.account // // TODO: Add tier appropreately. // const tier = ctx.payload.marketplace_purchase.plan.unit_name // const dbpurchase = await prisma.purchase.create({ // data: { // owner: owner.login.toLowerCase(), // email: owner.organization_billing_email, // plan: purchase.plan.name, // planId: purchase.plan.id, // tier: 'BASIC', // type: owner.type === 'User' ? 'USER' : 'ORGANIZATION', // }, // }) // ctx.logger.info( // `${owner.login.toLowerCase()}: ${owner.type} purchased LabelSync plan ${dbpurchase.planId}`, // ) // }) /** * Marketplace purchase event * * Tasks: * - reference the purchase in the database. */ // app.on('marketplace_purchase.cancelled', async (ctx) => { // // TODO: Github Marketplace. // const purchase = ctx.payload.marketplace_purchase // const owner = purchase.account // const dbpurchase = await prisma.purchase.delete({ // where: { // owner: owner.login.toLowerCase(), // }, // }) // ctx.logger.info( // { owner: owner.login.toLowerCase(), event: 'marketplace_purchase.cancelled' }, // `${owner.login.toLowerCase()} cancelled LabelSync plan ${dbpurchase.planId}`, // ) // }) /** * Installation event * * Performs an onboarding configuration to make it easier to get acquainted * with LabelSync. * * Tasks: * - check whether there exists a configuration repository, * - create a configuration repository from template. */ app.on( 'installation.created', withLogger(winston, async (ctx) => { const account = ctx.payload.installation.account const owner = account.login.toLowerCase() const configRepo = getLSConfigRepoName(owner) /* Find installation. */ const now = moment() const installation = await prisma.installation.upsert({ where: { account: owner }, create: { account: owner, plan: 'FREE', periodEndsAt: now.clone().add(3, 'y').toDate(), activated: true, }, update: { activated: true, }, }) ctx.logger.info(`Onboarding ${owner}.`, { meta: { plan: installation.plan, periodEndsAt: installation.periodEndsAt, }, }) /* See if config repository exists. */ const repo = await getRepo(ctx.github, owner, configRepo) switch (repo.status) { case 'Exists': { /* Perform sync. */ ctx.logger.info( `User has existing repository in ${configRepo}, performing sync.`, ) const ref = `refs/heads/${repo.repo.default_branch}` /* Load configuration */ const configRaw = await getFile( ctx.github, { owner, repo: configRepo, ref }, LS_CONFIG_PATH, ) /* No configuration, skip the evaluation. */ /* istanbul ignore next */ if (configRaw === null) { ctx.logger.info(`No configuration, skipping sync.`) return } const [error, config] = parseConfig(installation.plan, configRaw) /* Wrong configuration, open the issue. */ if (error !== null) { ctx.logger.info(`Error in config, skipping sync.`, { meta: { config: JSON.stringify(config), error: error, }, }) /* Open an issue about invalid configuration. */ const title = 'LabelSync - Onboarding configuration' const body = ml` | # Welcome to LabelSync! | | Hi there, | Thank you for using LabelSync. We hope you enjoyed the experience so far. | It seems like there are some problems with your configuration. | Our parser reported that: | | ${error} | | Let us know if we can help you with the configuration by sending us an email to support@label-sync.com. We'll try to get back to you as quickly as possible. | | Best, | LabelSync Team ` const issue = await openIssue( ctx.github, owner, configRepo, title, body, ) ctx.logger.info(`Opened issue ${issue.number}.`) return } /* Verify that we can access all configured files. */ const access = await checkInstallationAccess( ctx.github, configRepos(config!), ) switch (access.status) { case 'Sufficient': { ctx.logger.info(`Performing sync.`) /* Performs sync. */ for (const repo of configRepos(config!)) { await Promise.all([ handleLabelSync( ctx.github, owner, repo, config!.repos[repo], true, ), ]) } return } case 'Insufficient': { ctx.logger.info(`Insufficient permissions, skipping sync.`, { meta: { access: JSON.stringify(access) }, }) /* Opens up an issue about insufficient permissions. */ const title = 'LabelSync - Insufficient permissions' const body = ml` | # Insufficient permissions | | Hi there, | Thank you for installing LabelSync. We have noticed that your configuration stretches beyond repositories we can access. We assume that you forgot to allow access to certain repositories. | | Please update your installation. | | _Missing repositories:_ | ${access.missing.map((missing) => ` * ${missing}`).join(os.EOL)} | | Best, | LabelSync Team ` const issue = await openIssue( ctx.github, owner, configRepo, title, body, ) ctx.logger.info(`Opened issue ${issue.number}.`) return } } } case 'Unknown': { ctx.logger.info( `No existing repository for ${owner}, start onboarding.`, ) /** * Bootstrap the configuration depending on the * type of the installation account. */ const accountType = ctx.payload.installation.account.type switch (accountType) { /* istanbul ignore next */ case 'User': { // TODO: Update once Github changes the settings ctx.logger.info(`User account ${owner}, skip onboarding.`) return } case 'Organization': { /** * Tempalte using for onboarding new customers. */ ctx.logger.info(`Bootstraping config repo for ${owner}.`) const template: GHTree = loadTreeFromPath(TEMPLATES.yaml, [ 'dist', 'node_modules', '.DS_Store', /.*\.log.*/, /.*\.lock.*/, ]) /* Bootstrap a configuration repository in organisation. */ const personalisedTemplate = populateTemplate(template, { repository: configRepo, repositories: ctx.payload.repositories, }) await bootstrapConfigRepository( ctx.github, { owner, repo: configRepo }, personalisedTemplate, ) ctx.logger.info(`Onboarding complete for ${owner}.`) return } /* istanbul ignore next */ default: { ctx.logger.warn(`Unsupported account type: ${accountType}`) return } } } } }), ) /** * Push Event * * Listens for changes to the configuration file. * * Tasks: * - determine whether the configuration file is OK, * - sync labels across repositories (i.e. create new ones, remove old ones) * on master branch, * - perform check runs on non-master branch. */ app.on( 'push', withUserContextLogger( winston, withInstallation( prisma, withSubscription(async (ctx) => { const owner = ctx.payload.repository.owner.login.toLowerCase() const repo = ctx.payload.repository.name const ref = ctx.payload.ref const defaultRef = `refs/heads/${ctx.payload.repository.default_branch}` const commit_sha: string = ctx.payload.after const configRepo = getLSConfigRepoName(owner) /* Skip non default branch and other repos pushes. */ /* istanbul ignore if */ if (defaultRef !== ref || !isConfigRepo(owner, repo)) { ctx.logger.info(`Not config repo or ref. Skipping sync.`, { meta: { ref, repo, defaultRef, configRepo, }, }) return } /* Load configuration */ const configRaw = await getFile( ctx.github, { owner, repo, ref }, LS_CONFIG_PATH, ) /* Skip altogether if there's no configuration. */ /* istanbul ignore next */ if (configRaw === null) { ctx.logger.info(`No configuration, skipping sync.`) return } const [error, config] = parseConfig(ctx.installation.plan, configRaw) /* Open an issue about invalid configuration. */ if (error !== null) { ctx.logger.info(`Error in config ${error}`, { meta: { config: JSON.stringify(config), error: error, }, }) const report = ml` | It seems like your configuration uses a format unknown to me. | That might be a consequence of invalid yaml cofiguration file. | | Here's what I am having problems with: | | ${error} ` await ctx.github.repos.createCommitComment({ owner, repo, commit_sha, body: report, }) ctx.logger.info(`Commented on commit ${commit_sha}.`) return } ctx.logger.info(`Configuration loaded.`, { meta: { config: JSON.stringify(config), }, }) /* Verify that we can access all configured files. */ const access = await checkInstallationAccess( ctx.github, configRepos(config!), ) /* Skip configurations that we can't access. */ switch (access.status) { case 'Sufficient': { ctx.logger.info(`Performing label sync on ${owner}.`) /* Performs sync. */ const reports = await Promise.all( configRepos(config!).map((repo) => handleLabelSync( ctx.github, owner, repo, config!.repos[repo], true, ), ), ) ctx.logger.info(`Sync completed.`, { meta: { config: JSON.stringify(config), reports: JSON.stringify(reports), }, }) /* Comment on commit */ const report = generateHumanReadableCommitReport(reports) const commit_sha: string = ctx.payload.after await ctx.github.repos.createCommitComment({ owner, repo, commit_sha, body: report, }) return } case 'Insufficient': { ctx.logger.info( `Insufficient permissions: ${access.missing.join(', ')}`, { meta: { config: JSON.stringify(config), access: JSON.stringify(access), }, }, ) const commit_sha: string = ctx.payload.after const report = ml` | Your configuration stretches beyond repositories I can access. | Please update it so I may sync your labels. | | _Missing repositories:_ | ${access.missing.map((missing) => ` * ${missing}`).join(os.EOL)} ` await ctx.github.repos.createCommitComment({ owner, repo, commit_sha, body: report, }) ctx.logger.info(`Commented on commit ${commit_sha}.`) return } } }), ), ), ) /** * Pull Request event * * Tasks: * - review changes introduced, * - open issues, * - review changes. */ app.on( 'pull_request', withUserContextLogger( winston, withInstallation( prisma, withSubscription(async (ctx) => { const owner = ctx.payload.repository.owner.login.toLowerCase() const repo = ctx.payload.repository.name const ref = ctx.payload.pull_request.head.ref const number = ctx.payload.pull_request.number const configRepo = getLSConfigRepoName(owner) ctx.logger.info(`PullRequest action: ${ctx.payload.action}`) /* istanbul ignore if */ if (!isConfigRepo(owner, repo)) { ctx.logger.info( `Not configuration repository, skipping pull request overview.`, { meta: { configurationRepo: configRepo, currentRepo: repo } }, ) return } /* Check changed files */ const compare = await ctx.github.repos.compareCommits({ owner: owner, repo: repo, base: ctx.payload.pull_request.base.ref, head: ctx.payload.pull_request.head.ref, }) /* istanbul ignore next */ if ( compare.data.files.every((file) => file.filename !== LS_CONFIG_PATH) ) { ctx.logger.info(`Configuration didn't change, skipping comment.`, { meta: { files: compare.data.files .map((file) => file.filename) .join(', '), }, }) return } /* Start the process of PR review. */ /* Tackle PR Action */ switch (ctx.payload.action) { case 'opened': case 'reopened': case 'ready_for_review': case 'review_requested': case 'synchronize': case 'edited': { /* Review pull request. */ const startedAt = new Date() /* Start a Github check. */ const check = await ctx.github.checks .create({ name: 'label-sync/dryrun', owner: owner, repo: repo, head_sha: ctx.payload.pull_request.head.sha, started_at: startedAt.toISOString(), status: 'in_progress', }) .then((res) => res.data) /* Load configuration */ const configRaw = await getFile( ctx.github, { owner, repo, ref }, LS_CONFIG_PATH, ) /* Skip the pull request if there's no configuraiton. */ /* istanbul ignore next */ if (configRaw === null) { ctx.logger.info(`No configuration, skipping comment.`) return } const [error, config] = parseConfig( ctx.installation.plan, configRaw, ) /* Skips invalid configuration. */ /* istanbul ignore if */ if (error !== null) { ctx.logger.info(`Invalid configuration on ${ref}`, { meta: { config: JSON.stringify(config), error: error, }, }) const report = ml` | Your configuration seems a bit strange. Here's what I am having problems with: | | ${error} ` const completedAt = new Date() /* Complete a Github check. */ const completedCheck = await ctx.github.checks .update({ check_run_id: check.id, owner: owner, repo: repo, status: 'completed', completed_at: completedAt.toISOString(), conclusion: 'failure', output: { title: 'Invalid configuration', summary: report, }, }) .then((res) => res.data) ctx.logger.info( `Submited a check failure (${completedCheck.id})`, ) return } ctx.logger.info(`Configration loaded configuration on ${ref}`, { meta: { config: JSON.stringify(config), }, }) /* Verify that we can access all configured files. */ const access = await checkInstallationAccess( ctx.github, configRepos(config!), ) /* Skip configurations that we can't access. */ switch (access.status) { case 'Sufficient': { ctx.logger.info(`Simulating sync.`) /* Fetch changes to repositories. */ const reports = await Promise.all( configRepos(config!).map((repo) => handleLabelSync( ctx.github, owner, repo, config!.repos[repo], false, ), ), ) /* Comment on pull request. */ const report = generateHumanReadablePRReport(reports) const successful = reports.every( (report) => report.status === 'Success', ) /* Comment on a PR in a human friendly way. */ const comment = await createPRComment( ctx.github, owner, configRepo, number, report, ) ctx.logger.info(`Commented on PullRequest (${comment.id})`) const completedAt = new Date() /* Complete a Github check. */ const completedCheck = await ctx.github.checks .update({ check_run_id: check.id, owner: owner, repo: repo, status: 'completed', completed_at: completedAt.toISOString(), conclusion: successful ? 'success' : 'failure', }) .then((res) => res.data) ctx.logger.info( `Check updated (${completedCheck.id}) (#${number}) ${completedCheck.status}`, ) return } case 'Insufficient': { ctx.logger.info(`Insufficient permissions`) /* Opens up an issue about insufficient permissions. */ const body = ml` | It seems like this configuration stretches beyond repositories we can access. Please update it so we can help you as best as we can. | | _Missing repositories:_ | ${access.missing .map((missing) => ` * ${missing}`) .join(os.EOL)} ` /* Complete a check run */ const completedAt = new Date() const completedCheck = await ctx.github.checks .update({ check_run_id: check.id, owner: owner, repo: repo, status: 'completed', completed_at: completedAt.toISOString(), conclusion: 'failure', output: { title: 'Missing repository access.', summary: body, }, }) .then((res) => res.data) ctx.logger.info(`Completed check ${completedCheck.id}`) return } } } /* istanbul ignore next */ case 'assigned': /* istanbul ignore next */ case 'closed': /* istanbul ignore next */ case 'labeled': /* istanbul ignore next */ case 'locked': /* istanbul ignore next */ case 'review_request_removed': /* istanbul ignore next */ case 'unassigned': /* istanbul ignore next */ case 'unlabeled': /* istanbul ignore next */ case 'unlocked': { /* Ignore other events. */ ctx.logger.info(`Ignoring event ${ctx.payload.action}.`) return } /* istanbul ignore next */ default: { /* Log unsupported pull_request action. */ /* prettier-ignore */ ctx.logger.warn(`Unhandled PullRequest action: ${ctx.payload.action}`) return } } }), ), ), ) /** * Label Created * * Tasks: * - figure out whether repository is strict * - prune unsupported labels. */ app.on( 'label.created', withUserContextLogger( winston, withInstallation( prisma, withSubscription( withSources(async (ctx) => { const owner = ctx.payload.repository.owner.login.toLowerCase() const repo = ctx.payload.repository.name.toLowerCase() const config = ctx.sources.config.repos[repo] || ctx.sources.config.repos['*'] const label = ctx.payload.label as GithubLabel ctx.logger.info(`New label create in ${repo}: "${label.name}".`) /* Ignore no configuration. */ /* istanbul ignore if */ if (!config) { ctx.logger.info(`No configuration, skipping`) return } /* Ignore complying changes. */ /* istanbul ignore if */ if (config.labels.hasOwnProperty(label.name)) { ctx.logger.info(`Label is configured, skipping removal.`) return } /* Config */ const removeUnconfiguredLabels = withDefault( false, config.config?.removeUnconfiguredLabels, ) if (removeUnconfiguredLabels) { ctx.logger.info(`Removing "${label.name}" from ${repo}.`) /* Prune unsupported labels in strict repositories. */ await removeLabelsFromRepository( ctx.github, { repo, owner }, [label], removeUnconfiguredLabels, ) ctx.logger.info(`Removed label "${label.name}" from ${repo}.`) } }), ), ), ), ) /** * Label assigned to issue * * Tasks: * - check if there are any siblings that we should add * - add siblings */ app.on( 'issues.labeled', withUserContextLogger( winston, withInstallation( prisma, withSubscription( withSources(async (ctx) => { const owner = ctx.payload.repository.owner.login.toLowerCase() const repo = ctx.payload.repository.name.toLowerCase() const config: LSCRepository | undefined = ctx.sources.config.repos[repo] const label = ((ctx.payload as any) as { label: GithubLabel }).label const issue = ctx.payload.issue ctx.logger.debug('IssueLabeled payload and config', { payload: ctx.payload, sources: ctx.sources.config, }) ctx.logger.info( `Issue (${issue.number}) labeled with "${label.name}".`, ) /* Ignore changes in non-strict config */ /* istanbul ignore if */ if (!config) { ctx.logger.info(`No configuration found, skipping.`) return } /* istanbul ignore if */ if (!config.labels.hasOwnProperty(label.name)) { ctx.logger.info(`Unconfigured label "${label.name}", skipping.`) return } /* Find siblings. */ const siblings = _.get( config, ['labels', label.name, 'siblings'], [] as string[], ) const ghSiblings = siblings.map((sibling) => ({ name: sibling })) /* istanbul ignore if */ if (ghSiblings.length === 0) { ctx.logger.info( `No siblings to add to "${label.name}", skipping.`, ) return } await addLabelsToIssue( ctx.github, { repo, owner, issue: issue.number }, ghSiblings, true, ) /* prettier-ignore */ ctx.logger.info(`Added siblings of ${label.name} to issue ${issue.number}: ${siblings.join(', ')}`) }), ), ), ), ) /** * Label assigned to pull_request * * Tasks: * - check if there are any siblings that we should add * - add siblings */ app.on( 'pull_request.labeled', withUserContextLogger( winston, withInstallation( prisma, withSubscription( withSources(async (ctx) => { const owner = ctx.payload.repository.owner.login.toLowerCase() const repo = ctx.payload.repository.name.toLowerCase() const config: LSCRepository | undefined = ctx.sources.config.repos[repo] const label = ((ctx.payload as any) as { label: GithubLabel }).label const issue = ctx.payload.pull_request ctx.logger.debug('PullRequestLabeled payload and config', { payload: ctx.payload, sources: ctx.sources.config, }) ctx.logger.info( `PullRequest (${issue.number}) labeled with "${label.name}".`, ) /* Ignore changes in non-strict config */ /* istanbul ignore if */ if (!config) { ctx.logger.info(`No configuration found, skipping.`) return } /* istanbul ignore if */ if (!config.labels.hasOwnProperty(label.name)) { ctx.logger.info(`Unconfigured label "${label.name}", skipping.`) return } /* Find siblings. */ const siblings = _.get( config, ['labels', label.name, 'siblings'], [] as string[], ) const ghSiblings = siblings.map((sibling) => ({ name: sibling })) /* istanbul ignore if */ if (ghSiblings.length === 0) { ctx.logger.info( `No siblings to add to "${label.name}", skipping.`, ) return } await addLabelsToIssue( ctx.github, { repo, owner, issue: issue.number }, ghSiblings, true, ) /* prettier-ignore */ ctx.logger.info(`Added siblings of ${label.name} to pr ${issue.number}: ${siblings.join(', ')}`) }), ), ), ), ) /** * New repository created * * Tasks: * - check if there's a wildcard configuration * - sync labels on that repository */ app.on( 'repository.created', withUserContextLogger<Webhooks.WebhookPayloadRepository, any>( winston, withInstallation( prisma, withSubscription( withSources(async (ctx) => { const owner = ctx.payload.repository.owner.login.toLowerCase() const repo = ctx.payload.repository.name.toLowerCase() const config = ctx.sources.config.repos[repo] || ctx.sources.config.repos['*'] ctx.logger.info(`New repository ${repo} in ${owner}.`) /* Ignore no configuration. */ /* istanbul ignore if */ if (!config) { ctx.logger.info(`No configuration, skipping sync.`) return } ctx.logger.info(`Performing sync on ${repo}.`) await handleLabelSync(ctx.github, owner, repo, config, true) ctx.logger.info(`Repository synced ${repo}.`) }), ), ), ), ) } // MARK: - Utilities interface Sources { config: LSCConfiguration } /** * Wraps a function inside a sources loader. */ function withSources< /* Context */ C extends | Webhooks.WebhookPayloadCheckRun | Webhooks.WebhookPayloadIssues | Webhooks.WebhookPayloadLabel | Webhooks.WebhookPayloadPullRequest | Webhooks.WebhookPayloadRepository, /* Additional context fields */ W extends { installation: Installation; logger: Logger }, /* Return type */ T >( fn: (ctx: Context<C> & W & { sources: Sources }) => Promise<T>, ): (ctx: Context<C> & W) => Promise<T | undefined> { return async (ctx) => { const owner = ctx.payload.repository.owner.login.toLowerCase() const repo = getLSConfigRepoName(owner) const ref = `refs/heads/${ctx.payload.repository.default_branch}` /* Load configuration */ const configRaw = await getFile( ctx.github, { owner, repo, ref }, LS_CONFIG_PATH, ) /* Skip if there's no configuration. */ /* istanbul ignore next */ if (configRaw === null) { ctx.logger.debug(`No configuration found while loading sources.`) return } const [error, config] = parseConfig(ctx.installation.plan, configRaw) /* Skips invlaid config. */ /* istanbul ignore if */ if (error !== null) { ctx.logger.debug(`Error while loading sources: ${error}`) return } ;(ctx as Context<C> & W & { sources: Sources }).sources = { config: config!, } return fn(ctx as Context<C> & W & { sources: Sources }) } } /** * Wraps a function inside a subscriptions check. */ function withSubscription< /* Context */ C extends | Webhooks.WebhookPayloadCheckRun | Webhooks.WebhookPayloadCheckSuite | Webhooks.WebhookPayloadCommitComment | Webhooks.WebhookPayloadLabel | Webhooks.WebhookPayloadRepository, /* Additional context fields */ W extends { installation: Installation; logger: Logger }, /* Return type */ T >( fn: (ctx: Context<C> & W) => Promise<T>, ): (ctx: Context<C> & W) => Promise<T | undefined> { return async (ctx) => { const now = moment() /* istanbul ignore if */ if (moment(ctx.installation.periodEndsAt).isBefore(now)) { ctx.logger.warn(`Expired subscription ${ctx.installation.account}`) return } return fn(ctx as Context<C> & W) } } /** * Wraps a function inside a sources loader. */ function withInstallation< /* Context */ C extends | Webhooks.WebhookPayloadCheckRun | Webhooks.WebhookPayloadCheckSuite | Webhooks.WebhookPayloadCommitComment | Webhooks.WebhookPayloadLabel | Webhooks.WebhookPayloadIssues | Webhooks.WebhookPayloadIssueComment | Webhooks.WebhookPayloadPullRequest | Webhooks.WebhookPayloadPullRequestReview | Webhooks.WebhookPayloadPullRequestReviewComment | Webhooks.WebhookPayloadPush | Webhooks.WebhookPayloadRepository, /* Additional context fields */ W, /* Return type */ T >( prisma: PrismaClient, fn: (ctx: Context<C> & W & { installation: Installation }) => Promise<T>, ): (ctx: Context<C> & W) => Promise<T | undefined> { return async (ctx) => { const owner = ctx.payload.repository.owner.login.toLowerCase() /* Try to find the purchase in the database. */ let installation = await prisma.installation.findUnique({ where: { account: owner }, }) /* istanbul ignore if */ if (isNullOrUndefined(installation)) { throw new Error(`Couldn't find installation for ${owner}.`) } /* Handle expired purchases */ ;(ctx as Context<C> & W & { installation: Installation }).installation = installation return fn(ctx as Context<C> & W & { installation: Installation }) } } /** * Wraps event handler in logger and creates a context. */ function withUserContextLogger< /* Context */ C extends | Webhooks.WebhookPayloadCheckRun | Webhooks.WebhookPayloadCheckSuite | Webhooks.WebhookPayloadCommitComment | Webhooks.WebhookPayloadLabel | Webhooks.WebhookPayloadIssues | Webhooks.WebhookPayloadIssueComment | Webhooks.WebhookPayloadPullRequest | Webhooks.WebhookPayloadPullRequestReview | Webhooks.WebhookPayloadPullRequestReviewComment | Webhooks.WebhookPayloadPush | Webhooks.WebhookPayloadRepository, /* Return type */ T >( logger: Logger, fn: (ctx: Context<C> & { logger: Logger }) => Promise<T>, ): (ctx: Context<C>) => Promise<T | undefined> { return async (ctx) => { const owner = ctx.payload.repository.owner const repo = ctx.payload.repository const action = (ctx.payload as | Webhooks.WebhookPayloadCheckRun | Webhooks.WebhookPayloadCheckSuite | Webhooks.WebhookPayloadCommitComment | Webhooks.WebhookPayloadLabel | Webhooks.WebhookPayloadIssues | Webhooks.WebhookPayloadIssueComment | Webhooks.WebhookPayloadPullRequest | Webhooks.WebhookPayloadPullRequestReview | Webhooks.WebhookPayloadPullRequestReviewComment | Webhooks.WebhookPayloadRepository).action || 'push' const eventLogger = logger.child({ event: { name: ctx.event, action: action, repo: { name: repo.name, }, user: { id: owner.id, owner: owner.login, type: owner.type, }, context: { user_id: owner.id, }, }, }) /** * Attach the current user context. * Run the event handler. * Remove the middleware. */ try { ;(ctx as Context<C> & { logger: Logger }).logger = eventLogger return await fn(ctx as Context<C> & { logger: Logger }) } catch (err) /* istanbul ignore next */ { /* Report the error and skip evaluation. */ eventLogger.error(`Event resulted in error.`, { meta: { error: err.message }, }) if (process.env.NODE_ENV !== 'production') console.error(err) } /* istanbul ignore next */ return undefined } } /** * Wraps event handler in logger and creates a context. */ function withLogger< /* Context */ C extends | Webhooks.WebhookPayloadMarketplacePurchase | Webhooks.WebhookPayloadInstallation | Webhooks.WebhookPayloadCheckRun | Webhooks.WebhookPayloadCheckSuite | Webhooks.WebhookPayloadCommitComment | Webhooks.WebhookPayloadLabel | Webhooks.WebhookPayloadIssues | Webhooks.WebhookPayloadIssueComment | Webhooks.WebhookPayloadPullRequest | Webhooks.WebhookPayloadPullRequestReview | Webhooks.WebhookPayloadPullRequestReviewComment | Webhooks.WebhookPayloadPush | Webhooks.WebhookPayloadRepository, /* Return type */ T >( logger: Logger, fn: (ctx: Context<C> & { logger: Logger }) => Promise<T>, ): (ctx: Context<C>) => Promise<T | undefined> { return async (ctx) => { const eventLogger = logger.child({ event: { name: ctx.event, }, }) /** * Run the event handler. */ try { ;(ctx as Context<C> & { logger: Logger }).logger = eventLogger return await fn(ctx as Context<C> & { logger: Logger }) } catch (err) /* istanbul ignore next */ { /* Report the error and skip evaluation. */ eventLogger.error(`Event resulted in error.`, { meta: { error: err.message }, }) if (process.env.NODE_ENV !== 'production') console.error(err) } /* istanbul ignore next */ return undefined } }
the_stack
import { Component, HostListener, Input, Renderer2, ContentChild, ElementRef, AfterViewInit, ViewChild, } from '@angular/core'; import { Router, Event, NavigationEnd } from '@angular/router'; import * as _ from 'lodash'; import { SprkMastheadNavCollapsibleDirective } from './directives/sprk-masthead-nav-collapsible/sprk-masthead-nav-collapsible.directive'; import { SprkMastheadBrandingDirective } from './directives/sprk-masthead-branding/sprk-masthead-branding.directive'; import { isElementVisible } from '../../utilities/isElementVisible/isElementVisible'; @Component({ selector: 'sprk-masthead', template: ` <header [ngClass]="getClasses()" role="banner" [attr.data-id]="idString"> <sprk-stack splitAt="extraTiny" isStackItem="true" additionalClasses="sprk-c-Masthead__content" *ngIf="branding" > <div sprkStackItem *ngIf="collapsibleNavDirective" #mastheadMenuContainer class="sprk-c-Masthead__menu sprk-o-Stack__item--center-column@xxs" > <sprk-masthead-nav-collapsible-button [collapsibleNavId]="collapsibleNavDirective.id" [isOpen]="isCollapsibleNavOpen" [screenReaderText]="collapsibleNavButtonScreenReaderText" (collapsibleNavButtonEvent)="toggleCollapsibleNav($event)" ></sprk-masthead-nav-collapsible-button> </div> <ng-content select="[sprkMastheadBranding]"></ng-content> <ng-content select="[sprkMastheadNavItem]"></ng-content> <ng-content select="[sprkMastheadNavItems]"></ng-content> </sprk-stack> <ng-content></ng-content> </header> `, }) export class SprkMastheadComponent implements AfterViewInit { /** * @ignore */ constructor(private renderer: Renderer2, router: Router) { router.events.subscribe((event: Event) => { /** * If page is changed by the router * and they have a collapsibleNav * we want to make sure it is closed * when the new page loads if it is open. */ if (!this.collapsibleNavDirective) { return; } if ( event instanceof NavigationEnd && !this.collapsibleNavDirective.isCollapsed ) { this.closeCollapsibleNav(); } }); } /** * Expects a space separated string * of classes to be added to the * component. */ @Input() additionalClasses: string; /** * The value supplied will be used * as the screen reader text for the * collapsible nav button. If none is * supplied then a default of * \"Toggle Navigation\" is set. */ @Input() collapsibleNavButtonScreenReaderText = 'Toggle Navigation'; /** * The value supplied will be assigned * to the `data-id` attribute on the * component. This is intended to be * used as a selector for automated * tools. This value should be unique * per page. */ @Input() idString: string; @ContentChild(SprkMastheadNavCollapsibleDirective, { static: false, }) collapsibleNavDirective: SprkMastheadNavCollapsibleDirective; @ViewChild('mastheadMenuContainer', { static: false }) mastheadMenuContainer: ElementRef; @ContentChild(SprkMastheadBrandingDirective, { static: false, read: ElementRef, }) branding: ElementRef; /** * Keeps state of if the page has been scrolled. */ isPageScrolled = false; /** * Keeps state of if the Masthead is on a narrow viewport. */ isNarrowViewport = false; /** * Keeps state of the scroll direction in order to apply * CSS classes or not. */ currentScrollDirection = 'up'; /** * Keeps state of if the Masthead is hidden in order to apply * CSS classes or not. */ isMastheadHidden = false; /** * Keeps state of the viewport on resize. */ isNarrowViewportOnResize = false; /** * Keeps state of the scroll position in * order to apply CSS classes or not. */ currentScrollPosition = 0; /** * Represents the initial state of the * collapsible nav of the Masthead component. */ isCollapsibleNavOpen = false; /** * Throttles the updateScrollDirection function to prevent * it from impacting performance. */ throttledUpdateScrollDirection = _.throttle(this.updateScrollDirection, 500); /** * Throttles the updateLayoutState function to prevent * it from impacting performance. */ throttledUpdateLayoutState = _.throttle(this.updateLayoutState, 500); /** * Updates the scroll direction when the page is scrolled. */ @HostListener('window:scroll', ['$event']) onScroll(event): void { window.scrollY >= 10 ? (this.isPageScrolled = true) : (this.isPageScrolled = false); this.throttledUpdateScrollDirection(); } /** * Closes the collapsible navigation menu * if it is left open when * the viewport orientation changes. */ @HostListener('window:orientationchange') handleResizeEvent() { if (this.collapsibleNavDirective) { this.closeCollapsibleNav(); } } /** * When page is resized * we want to update the internal state to close * the collapsible nav if needed. */ @HostListener('window:resize', ['$event']) onResize(event): void { if (!this.collapsibleNavDirective) { return; } // Update internal layout state this.isNarrowViewportOnResize = isElementVisible( this.mastheadMenuContainer, ); this.throttledUpdateLayoutState(); } /** * If the viewport size has changed then update * the isNarrowViewport state with true if * it is now a narrow viewport or false is it is * now a large viewport. If it is now a large viewport, * we want to make sure the Masthead is not hidden * and that we close the collapsible nav if it was open. */ updateLayoutState() { // If the viewport didn't change then do not do anything if (this.isNarrowViewport === this.isNarrowViewportOnResize) { return; } // Update internal state to new viewport state on resize this.isNarrowViewport = this.isNarrowViewportOnResize; this.isMastheadHidden = false; this.closeCollapsibleNav(); } /** * When the view initializes we set internal state * for if the viewport is narrow or not. */ ngAfterViewInit() { // We say that it is a narrow viewport if // the collapisble nav button style is not set to display: none this.isNarrowViewport = isElementVisible(this.mastheadMenuContainer); if (this.collapsibleNavDirective) { this.collapsibleNavDirective.isCollapsed ? (this.isCollapsibleNavOpen = false) : (this.isCollapsibleNavOpen = true); } } /** * @returns 'up' || 'down' * This returns whether or not * there was an up or down scrolling * action. */ getVerticalScrollDirection(): string { if (typeof window === 'undefined') { return; } const newScrollPos = window.scrollY; if (newScrollPos < 0) { return; } const diff = newScrollPos - this.currentScrollPosition; const direction = diff > 0 ? 'down' : 'up'; this.currentScrollPosition = newScrollPos; return direction; } /** * This gets the direction of the scroll that occurred last * and updates the `isMastheadHidden` tracker value. If the user * scrolled down, we update `isMastheadHidden` to `true` (hide the Masthead). * If the scroll direction is up, we update `isMastheadHidden` to `false` (show the Masthead). */ updateScrollDirection(): void { const newlyScrolledDirection = this.getVerticalScrollDirection(); if (this.currentScrollDirection !== newlyScrolledDirection) { this.currentScrollDirection = newlyScrolledDirection; this.currentScrollDirection === 'down' ? (this.isMastheadHidden = true) : (this.isMastheadHidden = false); } } /** * Gets any additional classes for the main Masthead element * and sets the default classes. */ getClasses(): string { const classArray: string[] = ['sprk-c-Masthead', 'sprk-o-Stack']; if (this.additionalClasses) { this.additionalClasses.split(' ').forEach((className) => { classArray.push(className); }); } if ( this.collapsibleNavDirective && !this.collapsibleNavDirective.isCollapsed && this.isNarrowViewport ) { classArray.push('sprk-c-Masthead--is-open'); } if (this.isPageScrolled) { classArray.push('sprk-c-Masthead--is-scrolled'); } if (this.isMastheadHidden && this.isNarrowViewport) { classArray.push('sprk-c-Masthead--is-hidden'); } return classArray.join(' '); } /** * When the button for the collapsible nav * is clicked this will check if the collapsible * nav is open. If it is open, then it will close it. If it * is closed then it will open it. We run this method * whenever the collapsible nav emits the `isButtonOpen` event. */ toggleCollapsibleNav(isButtonOpen: boolean): void { if (!this.collapsibleNavDirective.isCollapsed) { this.closeCollapsibleNav(); } else { // The button is now open and we want to open the nav too this.openCollapsibleNav(); } } /** * Adds the correct styles to the body and HTML elements * in order for the collapsible nav to be open. * Sets the `isCollapsed` input on the collapsible nav * to be false so that the directive adds the CSS styles * to show the nav. */ openCollapsibleNav(): void { this.renderer.addClass(document.body, 'sprk-u-Overflow--hidden'); this.renderer.addClass( document.body.parentElement, 'sprk-u-Overflow--hidden', ); this.renderer.addClass(document.body, 'sprk-u-Height--100'); this.renderer.addClass(document.body.parentElement, 'sprk-u-Height--100'); // Set the `isCollapsed` property on the collapsible nav to false to open it this.collapsibleNavDirective.isCollapsed = false; // Ensure the button styles are set to open this.isCollapsibleNavOpen = true; } /** * Removes the styles that were added to * the body and HTML elements when the nav was open. * Sets the `isCollapsed` input on the collapsible nav to be true * so that the directive adds the collapsed CSS class. */ closeCollapsibleNav(): void { this.renderer.removeClass(document.body, 'sprk-u-Overflow--hidden'); this.renderer.removeClass( document.body.parentElement, 'sprk-u-Overflow--hidden', ); this.renderer.removeClass(document.body, 'sprk-u-Height--100'); this.renderer.removeClass( document.body.parentElement, 'sprk-u-Height--100', ); // Set the `isCollapsed` property on the collapsible nav to `true` to close it this.collapsibleNavDirective.isCollapsed = true; // Ensure the button styles are set to closed this.isCollapsibleNavOpen = false; } }
the_stack
import {Response} from 'express'; import { Body, Delete, Post, JsonController, Req, HttpError, UseBefore, BodyParam, ForbiddenError, InternalServerError, BadRequestError, OnUndefined, Res } from 'routing-controllers'; import {json as bodyParserJson} from 'body-parser'; import passportLoginMiddleware from '../security/passportLoginMiddleware'; import emailService from '../services/EmailService'; import {IUser} from '../../../shared/models/IUser'; import {IUserModel, User} from '../models/User'; import {JwtUtils} from '../security/JwtUtils'; import * as errorCodes from '../config/errorCodes'; import {Course} from '../models/Course'; import config from '../config/main'; @JsonController('/auth') export class AuthController { /** * @api {post} /api/auth/login Login user by responding with a httpOnly JWT cookie and the user's IUserModel data. * @apiName PostAuthLogin * @apiGroup Auth * * @apiParam {Request} request Login request (with email and password). * * @apiSuccess {IUserModel} user Authenticated user. * * @apiSuccessExample {json} Success-Response: * { * "user": { * "_id": "5a037e6a60f72236d8e7c813", * "updatedAt": "2018-01-08T19:24:26.522Z", * "createdAt": "2017-11-08T22:00:10.897Z", * "email": "admin@test.local", * "__v": 0, * "isActive": true, * "lastVisitedCourses": [], * "role": "admin", * "profile": { * "firstName": "Dago", * "lastName": "Adminman", * "picture": {} * }, * "id": "5a037e6a60f72236d8e7c813" * } * } */ @Post('/login') @UseBefore(bodyParserJson(), passportLoginMiddleware) // We need body-parser for passport to find the credentials postLogin(@Req() request: any, @Res() response: Response) { const user: IUserModel = request.user; response.cookie('token', JwtUtils.generateToken(user), { httpOnly: true, sameSite: true, // secure: true, // TODO Maybe make this configurable? }); response.json({ user: user.toObject() }); return response; } /** * @api {delete} /api/auth/logout Logout user by clearing the httpOnly token cookie. * @apiName AuthLogout * @apiGroup Auth * * @apiSuccessExample {json} Success-Response: * {} */ @Delete('/logout') logout(@Res() response: Response) { response.clearCookie('token'); response.json({}); return response; } /** * @api {post} /api/auth/register Register user * @apiName PostAuthRegister * @apiGroup Auth * * @apiParam {IUser} user New user to be registered. * * @apiError BadRequestError That matriculation number is already in use * @apiError BadRequestError That email address is already in use * @apiError BadRequestError You can only sign up as student or teacher * @apiError BadRequestError You are not allowed to register as teacher * @apiError InternalServerError Could not send E-Mail */ @Post('/register') @OnUndefined(204) async postRegister(@Body() user: IUser) { const existingUser = await User.findOne({$or: [{email: user.email}, {uid: user.uid}]}); // If user is not unique, return error if (existingUser) { if (user.role === 'student' && existingUser.uid === user.uid) { throw new BadRequestError(errorCodes.errorCodes.duplicateUid.code); } if (existingUser.email === user.email) { throw new BadRequestError(errorCodes.errorCodes.mail.duplicate.code); } } if (user.role !== 'teacher' && user.role !== 'student') { throw new BadRequestError('You can only sign up as student or teacher'); } if (user.role === 'teacher' && (typeof user.email !== 'string' || !user.email.match(config.teacherMailRegex))) { throw new BadRequestError(errorCodes.errorCodes.mail.noTeacher.code); } const newUser = new User(user); const savedUser = await newUser.save(); // User can now match a whitelist. await this.addWhitelistedUserToCourses(savedUser); try { emailService.sendActivation(savedUser); } catch (err) { throw new InternalServerError(errorCodes.errorCodes.mail.notSend.code); } } /** * @api {post} /api/auth/activate Activate user * @apiName PostAuthActivate * @apiGroup Auth * * @apiParam {string} authenticationToken Authentication token. * * @apiSuccess {Boolean} success Confirmation of activation. * * @apiSuccessExample {json} Success-Response: * { * "success": true * } * * @apiError HttpError 422 - could not activate user */ // TODO If activate user and is in playlist add to course. @Post('/activate') postActivation(@BodyParam('authenticationToken') authenticationToken: string) { return User.findOne({authenticationToken: authenticationToken}) .then((existingUser) => { if (!existingUser) { throw new HttpError(422, 'could not activate user'); } existingUser.authenticationToken = undefined; existingUser.isActive = true; return existingUser.save(); }) .then((user) => { return {success: true}; }); } /** * @api {post} /api/auth/activationresend Resend Activation * @apiName ActivationResend * @apiGroup Auth * * @apiParam {string} lastname lastname of user which activation should be resend. * @apiParam {string} uid matriculation number of user which activation should be resend. * @apiParam {string} email email the new activation should be sent to. * * @apiError (BadRequestError) 400 User was not found. * @apiError (BadRequestError) 400 That email address is already in use * @apiError (BadRequestError) 400 User is already activated. * @apiError (HttpError) 503 You can only resend the activation every X minutes. Your next chance is in * time left till next try in 'try-after' header in seconds * @apiError (InternalServerError) Could not send E-Mail */ @Post('/activationresend') @OnUndefined(204) async activationResend (@BodyParam('lastname') lastname: string, @BodyParam('uid') uid: string, @BodyParam('email') email: string, @Res() response: Response) { const user = await User.findOne({'profile.lastName': lastname, uid: uid, role: 'student'}); if (!user) { throw new BadRequestError(errorCodes.errorCodes.user.userNotFound.code); } if (user.isActive) { throw new BadRequestError(errorCodes.errorCodes.user.userAlreadyActive.code); } const timeSinceUpdate: number = (Date.now() - user.updatedAt.getTime() ) / 60000; if (timeSinceUpdate < Number(config.timeTilNextActivationResendMin)) { const retryAfter: number = (Number(config.timeTilNextActivationResendMin) - timeSinceUpdate) * 60; response.set('retry-after', retryAfter.toString()); throw new HttpError(503, errorCodes.errorCodes.user.retryAfter.code); } const existingUser = await User.findOne({email: email}); if (existingUser && existingUser.uid !== uid) { throw new BadRequestError(errorCodes.errorCodes.mail.duplicate.code); } user.authenticationToken = undefined; user.email = email; const savedUser = await user.save(); try { await emailService.resendActivation(savedUser); } catch (err) { throw new InternalServerError(err.toString()); } } /** * @api {post} /api/auth/reset Reset password * @apiName PostAuthReset * @apiGroup Auth * * @apiParam {string} resetPasswordToken Authentication token. * @apiParam {string} newPassword New password. * * @apiSuccess {Boolean} success Confirmation of reset. * * @apiSuccessExample {json} Success-Response: * { * "success": true * } * * @apiError HttpError 422 - could not reset users password * @apiError ForbiddenError your reset password token is expired */ @Post('/reset') postPasswordReset(@BodyParam('resetPasswordToken') resetPasswordToken: string, @BodyParam('newPassword') newPassword: string) { return User.findOne({resetPasswordToken: resetPasswordToken}) .then((existingUser) => { if (!existingUser) { throw new HttpError(422, 'could not reset users password'); } if (existingUser.resetPasswordExpires < new Date()) { throw new ForbiddenError('your reset password token is expired'); } existingUser.password = newPassword; existingUser.resetPasswordToken = undefined; existingUser.resetPasswordExpires = undefined; existingUser.markModified('password'); return existingUser.save(); }) .then((savedUser) => { return {success: true}; }); } /** * @api {post} /api/auth/requestreset Request password reset * @apiName PostAuthRequestReset * @apiGroup Auth * * @apiParam {string} email Email to notify. * * @apiSuccess {Boolean} success Confirmation of email transmission. * * @apiSuccessExample {json} Success-Response: * { * "success": true * } * * @apiError HttpError 422 - could not reset users password * @apiError InternalServerError Could not send E-Mail */ @Post('/requestreset') postRequestPasswordReset(@BodyParam('email') email: string) { return User.findOne({email: email}) .then((existingUser) => { if (!existingUser) { throw new HttpError(422, 'could not reset users password'); } const expires = new Date(); expires.setTime((new Date()).getTime() // Add 24h + (24 * 60 * 60 * 1000)); existingUser.resetPasswordExpires = expires; return existingUser.save(); }) .then((user) => { return emailService.sendPasswordReset(user); }) .then(() => { return {success: true}; }) .catch((err) => { throw new InternalServerError('Could not send E-Mail'); }); } /** * Add new user to all whitelisted courses in example after registration. * @param {IUser} user * @returns {Promise<void>} */ private async addWhitelistedUserToCourses(user: IUser) { const courses = await Course.find( {enrollType: 'whitelist'}).populate('whitelist'); await Promise.all(courses.map(async (course) => { const userUidIsRegisteredInWhitelist = course.whitelist.findIndex(w => w.uid === user.uid) >= 0; const userIsntAlreadyStudentOfCourse = course.students.findIndex(u => u._id === user._id) < 0; if (userUidIsRegisteredInWhitelist && userIsntAlreadyStudentOfCourse) { course.students.push(user); await course.save(); } })); } }
the_stack
import * as d3 from 'd3'; import { PolygonShapes, PolystatDiameters } from './types'; /** * LayoutManager creates layouts for supported polygon shapes */ export class LayoutManager { width: number; height: number; numColumns: number; numRows: number; radius: number; autoSize: boolean; maxRowsUsed: number; maxColumnsUsed: number; displayLimit: number; shape: PolygonShapes; readonly SQRT3 = 1.7320508075688772; constructor( width: number, height: number, numColumns: number, numRows: number, displayLimit: number, autoSize: boolean, shape: PolygonShapes ) { this.width = width; this.height = height; this.numColumns = numColumns; this.numRows = numRows; this.maxColumnsUsed = 0; this.maxRowsUsed = 0; this.displayLimit = displayLimit; this.shape = shape; this.radius = 0; this.autoSize = autoSize; } /** * Sets the radius to be used in all layout calculations * * @param radius user defined value */ setRadius(radius: number) { this.radius = radius; } setHeight(height: number) { this.height = height; } setWidth(width: number) { this.width = width; } /** * returns a layout for hexagons with pointed tops */ generateHexagonPointedTopLayout(): any { const layout = {}; this.radius = this.getHexFlatTopRadius(); return layout; } /** * returns a layout for square-shapes */ generateUniformLayout(): any { const layout = {}; this.radius = this.getUniformRadius(); return layout; } /** * The maximum radius the hexagons can have to still fit the screen * With (long) radius being R: * - Total width (rows > 1) = 1 small radius (sqrt(3) * R / 2) + columns * small diameter (sqrt(3) * R) * - Total height = 1 pointy top (1/2 * R) + rows * size of the rest (3/2 * R) */ getHexFlatTopRadius(): number { const polygonBorderSize = 0; // TODO: borderRadius should be configurable and part of the config let hexRadius = d3.min([ this.width / ((this.numColumns + 0.5) * this.SQRT3), this.height / ((this.numRows + 1 / 3) * 1.5), ]); hexRadius = hexRadius - polygonBorderSize; return this.truncateFloat(hexRadius); } /** * Helper method to return rendered width and height of hexagon shape */ getHexFlatTopDiameters(): PolystatDiameters { const hexRadius = this.getHexFlatTopRadius(); const diameterX = this.truncateFloat(hexRadius * this.SQRT3); const diameterY = this.truncateFloat(hexRadius * 2); return { diameterX, diameterY }; } /** * Helper method to return rendered width and height of a circle/square shapes */ getUniformDiameters(): PolystatDiameters { const radius = this.getUniformRadius(); const diameterX = radius * 2; const diameterY = radius * 2; return { diameterX, diameterY }; } /** * Given the number of columns and rows, calculate the maximum size of a uniform shaped polygon that can be used * uniformed shapes are: square/circle * width divided by the number of columns determines the max horizontal of the square * height divided by the number of rows determines the max vertical size ofthe square * the smaller of the two is used since that is the "best fit" for a square */ getUniformRadius(): number { const polygonBorderSize = 0; // TODO: borderRadius should be configurable and part of the config // width divided by the number of columns determines the max horizontal of the square // height divided by the number of rows determines the max vertical size ofthe square // the smaller of the two is used since that is the "best fit" const horizontalMax = (this.width / this.maxColumnsUsed) * 0.5; const verticalMax = (this.height / this.maxRowsUsed) * 0.5; let uniformRadius = horizontalMax; if (uniformRadius > verticalMax) { // vertically limited uniformRadius = verticalMax; } // internal border uniformRadius = uniformRadius - polygonBorderSize; return this.truncateFloat(uniformRadius); } generatePossibleColumnAndRowsSizes(columnAutoSize: boolean, rowAutoSize: boolean, dataSize: number) { if (rowAutoSize && columnAutoSize) { // sqrt of # data items const squared = Math.sqrt(dataSize); // favor columns when width is greater than height // favor rows when width is less than height if (this.width > this.height) { this.numColumns = Math.ceil((this.width / this.height) * squared * 0.75); // always at least 1 column and max. data.length columns if (this.numColumns < 1) { this.numColumns = 1; } else if (this.numColumns > dataSize) { this.numColumns = dataSize; } // Align rows count to computed columns count this.numRows = Math.ceil(dataSize / this.numColumns); // always at least 1 row if (this.numRows < 1) { this.numRows = 1; } } else { this.numRows = Math.ceil((this.height / this.width) * squared * 0.75); // always at least 1 row and max. data.length rows if (this.numRows < 1) { this.numRows = 1; } else if (this.numRows > dataSize) { this.numRows = dataSize; } // Align colunns count to computed rows count this.numColumns = Math.ceil(dataSize / this.numRows); // always at least 1 column if (this.numColumns < 1) { this.numColumns = 1; } } } else if (rowAutoSize) { // Align rows count to fixed columns count this.numRows = Math.ceil(dataSize / this.numColumns); // always at least 1 row if (this.numRows < 1) { this.numRows = 1; } } else if (columnAutoSize) { // Align colunns count to fixed rows count this.numColumns = Math.ceil(dataSize / this.numRows); // always at least 1 column if (this.numColumns < 1) { this.numColumns = 1; } } } /** * This determines how many rows and columns are going to be rendered, which can then * be used to calculate the radius size (which is needed before generating points) * @param data metrics * @param displayLimit max number of polygons to show */ generateActualColumnAndRowUsage(data: any, displayLimit: number) { let polygonsUsed = 0; let maxRowsUsed = 0; let columnsUsed = 0; let maxColumnsUsed = 0; for (let i = 0; i < this.numRows; i++) { if ((!displayLimit || polygonsUsed < displayLimit) && polygonsUsed < data.length) { maxRowsUsed += 1; columnsUsed = 0; for (let j = 0; j < this.numColumns; j++) { if ((!displayLimit || polygonsUsed < displayLimit) && polygonsUsed < data.length) { columnsUsed += 1; // track the most number of columns if (columnsUsed > maxColumnsUsed) { maxColumnsUsed = columnsUsed; } polygonsUsed++; } } } } this.maxRowsUsed = maxRowsUsed; this.maxColumnsUsed = maxColumnsUsed; } shapeToCoordinates(shape: PolygonShapes, radius: number, column: number, row: number) { switch (shape) { case PolygonShapes.HEXAGON_POINTED_TOP: let x = radius * column * this.SQRT3; //Offset each uneven row by half of a "hex-width" to the right if (row % 2 === 1) { x += (radius * this.SQRT3) / 2; } const y = radius * row * 1.5; return [x, y]; break; case PolygonShapes.CIRCLE: return [radius * column * 2, radius * row * 2]; break; case PolygonShapes.SQUARE: return [radius * column * 2, radius * row * 2]; break; default: return [radius * column * 1.75, radius * row * 1.5]; break; } } // Builds the placeholder polygons needed to represent each metric generatePoints(data: any, displayLimit: number, shape: PolygonShapes): any { const points = []; if (typeof data === 'undefined') { return points; } let maxRowsUsed = 0; let columnsUsed = 0; let maxColumnsUsed = 0; // when duplicating panels, this gets odd if (this.numRows === Infinity) { return points; } if (isNaN(this.numColumns)) { return points; } for (let i = 0; i < this.numRows; i++) { if ((!displayLimit || points.length < displayLimit) && points.length < data.length) { maxRowsUsed += 1; columnsUsed = 0; for (let j = 0; j < this.numColumns; j++) { if ((!displayLimit || points.length < displayLimit) && points.length < data.length) { columnsUsed += 1; // track the most number of columns if (columnsUsed > maxColumnsUsed) { maxColumnsUsed = columnsUsed; } points.push(this.shapeToCoordinates(shape, this.radius, j, i)); } } } } this.maxRowsUsed = maxRowsUsed; this.maxColumnsUsed = maxColumnsUsed; return points; } generateUniformPoints(data: any, displayLimit: number): any { const points = []; if (typeof data === 'undefined') { return points; } let maxRowsUsed = 0; let columnsUsed = 0; let maxColumnsUsed = 0; let xpos = 1; let ypos = 1; // when duplicating panels, this gets odd if (this.numRows === Infinity) { return points; } if (isNaN(this.numColumns)) { return points; } for (let i = 0; i < this.numRows; i++) { if ((!displayLimit || points.length < displayLimit) && points.length < data.length) { maxRowsUsed += 1; columnsUsed = 0; for (let j = 0; j < this.numColumns; j++) { if ((!displayLimit || points.length < displayLimit) && points.length < data.length) { columnsUsed += 1; // track the most number of columns if (columnsUsed > maxColumnsUsed) { maxColumnsUsed = columnsUsed; } points.push({ x: xpos, y: ypos, width: this.radius * 2, height: this.radius * 2, }); xpos += this.radius * 2; } } xpos = 1; ypos += this.radius * 2; } } this.maxRowsUsed = maxRowsUsed; this.maxColumnsUsed = maxColumnsUsed; return points; } getRadius(): number { return this.radius; } generateRadius(shape: PolygonShapes): number { if (!this.autoSize) { return this.radius; } let radius = 0; switch (shape) { case PolygonShapes.HEXAGON_POINTED_TOP: radius = this.getHexFlatTopRadius(); break; case PolygonShapes.CIRCLE: radius = this.getUniformRadius(); break; case PolygonShapes.SQUARE: radius = this.getUniformRadius(); break; default: radius = this.getHexFlatTopRadius(); break; } this.radius = radius; return radius; } truncateFloat(value: number): number { if (value === Infinity || isNaN(value)) { return 0; } const with2Decimals = value.toString().match(/^-?\d+(?:\.\d{0,2})?/)[0]; return Number(with2Decimals); } getOffsets(shape: PolygonShapes, dataSize: number): any { switch (shape) { case PolygonShapes.HEXAGON_POINTED_TOP: return this.getOffsetsHexagonPointedTop(dataSize); case PolygonShapes.SQUARE: return this.getOffsetsSquare(dataSize); case PolygonShapes.CIRCLE: return this.getOffsetsUniform(dataSize); default: return this.getOffsetsUniform(dataSize); } } getOffsetsHexagonPointedTop(dataSize: number): any { let hexRadius = d3.min([ this.width / ((this.numColumns + 0.5) * this.SQRT3), this.height / ((this.numRows + 1 / 3) * 1.5), ]); hexRadius = this.truncateFloat(hexRadius); const shapeWidth = this.truncateFloat(hexRadius * this.SQRT3); const shapeHeight = this.truncateFloat(hexRadius * 2); const offsetToViewY = shapeHeight * 0.5; // even rows are half-sized const { oddCount, evenCount } = this.getOddEvenCountForRange(1, this.maxRowsUsed); // odd-numbered hexagons are full height, evens are half height const actualHeightUsed = oddCount * shapeHeight + evenCount * shapeHeight * 0.5; let yoffset = (this.height - actualHeightUsed) / 2; yoffset = -(yoffset + offsetToViewY); const offsetToViewX = shapeWidth * 0.5; // columns have a half-width offset if there are more than 1 rows let widthOffset = 0; if (this.numRows > 1) { // if the datasize is equal to or larger than the 2*Columns, there is an additional offset needed if (dataSize >= this.maxColumnsUsed * 2) { widthOffset = 0.5; } } const actualWidthUsed = (this.numColumns + widthOffset) * shapeWidth; let xoffset = (this.width - actualWidthUsed) / 2; xoffset = -(xoffset + offsetToViewX); return { xoffset, yoffset }; } getOffsetsUniform(dataSize: number): any { const { diameterX, diameterY } = this.getDiameters(); const shapeWidth = this.truncateFloat(diameterX); const shapeHeight = this.truncateFloat(diameterY); const offsetToViewY = shapeHeight * 0.5; const actualHeightUsed = this.maxRowsUsed * shapeHeight; let yoffset = (this.height - actualHeightUsed) / 2; yoffset = -(yoffset + offsetToViewY); const offsetToViewX = shapeWidth * 0.5; const actualWidthUsed = this.numColumns * shapeWidth; let xoffset = (this.width - actualWidthUsed) / 2; xoffset = -(xoffset + offsetToViewX); return { xoffset, yoffset }; } getOffsetsSquare(dataSize: number): any { const { diameterX, diameterY } = this.getDiameters(); const shapeWidth = this.truncateFloat(diameterX); const shapeHeight = this.truncateFloat(diameterY); const offsetToViewY = 0; // shapeHeight * 0.5; const actualHeightUsed = this.maxRowsUsed * shapeHeight; let yoffset = (this.height - actualHeightUsed) / 2; yoffset = -(yoffset + offsetToViewY); const offsetToViewX = 0; //shapeWidth * 0.5; const actualWidthUsed = this.numColumns * shapeWidth; let xoffset = (this.width - actualWidthUsed) / 2; xoffset = -(xoffset + offsetToViewX); return { xoffset, yoffset }; } getOddEvenCountForRange(L: number, R: number): any { let oddCount = (R - L) / 2; // if either R or L is odd if (R % 2 !== 0 || L % 2 !== 0) { oddCount++; } const evenCount = R - L + 1 - oddCount; return { oddCount, evenCount }; } /** * Returns diameterX and diameterY for given shape */ getDiameters(): PolystatDiameters { switch (this.shape) { case PolygonShapes.HEXAGON_POINTED_TOP: return this.getHexFlatTopDiameters(); case PolygonShapes.SQUARE: return this.getUniformDiameters(); case PolygonShapes.CIRCLE: return this.getUniformDiameters(); default: return this.getUniformDiameters(); } } }
the_stack
import { injectable } from "../Utils/DI"; import { ColorEntry, ColorReason, ColorInheritance } from "./ColorEntry"; import { BaseColorProcessor } from "./BaseColorProcessor"; import { IApplicationSettings } from "../Settings/IApplicationSettings"; import { IBaseSettingsManager } from "../Settings/BaseSettingsManager"; import { HslaColor } from "./HslaColor"; import { ColorShift } from "./ColorShift"; import { RgbaColor } from "./RgbaColor"; import { Component } from "./ComponentShift"; import { IDynamicSettingsManager } from "../Settings/DynamicSettingsManager"; import { USP } from "../ContentScript/CssStyle"; export abstract class ITextColorProcessor { abstract calculateDefaultColor(doc: Document, defaultColor?: string): string; abstract getDefaultColor(doc: Document): string | undefined; abstract changeColor(rgbaString: string | null, backgroundLightness: number, tag: any, ignoreBlueFilter?: boolean): ColorEntry; } export abstract class ILinkColorProcessor extends ITextColorProcessor { } export abstract class IVisitedLinkColorProcessor extends ILinkColorProcessor { } export abstract class IHoverVisitedLinkColorProcessor extends IVisitedLinkColorProcessor { } export abstract class IActiveVisitedLinkColorProcessor extends IVisitedLinkColorProcessor { } export abstract class IHoverLinkColorProcessor extends ILinkColorProcessor { } export abstract class IActiveLinkColorProcessor extends ILinkColorProcessor { } export abstract class IHighlightedTextColorProcessor extends ITextColorProcessor { } export abstract class ITextShadowColorProcessor { abstract changeColor(rgbaString: string | null, backgroundLightness: number, tag: any): ColorEntry; } export abstract class IBorderColorProcessor { abstract changeColor(rgbaString: string | null, backgroundLightness: number, tag: any, ignoreBlueFilter?: boolean): ColorEntry; } export abstract class IButtonBorderColorProcessor extends IBorderColorProcessor { } export abstract class IButtonBackgroundColorProcessor { abstract changeColor(rgbaString: string | null, backgroundLightness: number, tag: any, ignoreBlueFilter?: boolean): ColorEntry; } export abstract class IHighlightedBackgroundColorProcessor { abstract changeColor(rgbaString: string | null, backgroundLightness: number, tag: any): ColorEntry; } export abstract class IScrollbarHoverColorProcessor { abstract changeColor(rgbaString: string | null, backgroundLightness: number, tag?: any, ignoreBlueFilter?: boolean): ColorEntry; } export abstract class IScrollbarNormalColorProcessor { abstract changeColor(rgbaString: string | null, backgroundLightness: number, tag?: any, ignoreBlueFilter?: boolean): ColorEntry; } export abstract class IScrollbarActiveColorProcessor { abstract changeColor(rgbaString: string | null, backgroundLightness: number, tag?: any, ignoreBlueFilter?: boolean): ColorEntry; } export abstract class IDynamicTextColorProcessor extends ITextColorProcessor { } export abstract class IDynamicLinkColorProcessor extends ILinkColorProcessor { } export abstract class IDynamicVisitedLinkColorProcessor extends IVisitedLinkColorProcessor { } export abstract class IDynamicBorderColorProcessor extends IBorderColorProcessor { } export abstract class IDynamicButtonBackgroundColorProcessor extends IButtonBackgroundColorProcessor { } abstract class ForegroundColorProcessor extends BaseColorProcessor { constructor( app: IApplicationSettings, settingsManager: IBaseSettingsManager) { super(app, settingsManager); } protected getInheritedColor(tag: Element, rgbStr: string): ColorEntry | null | undefined { return null; } protected changeHslaColor(hsla: HslaColor, backgroundLightness: number, isGray: boolean, grayShift: ColorShift) { let shift = this._colorShift; if (isGray) { shift = grayShift; hsla.hue = shift.grayHue; hsla.saturation = shift.graySaturation; } else { if (shift.hueGravity) { hsla.hue = this.shiftHue(hsla.hue, shift.grayHue, shift.hueGravity); } hsla.saturation = this.scaleValue(hsla.saturation, shift.saturationLimit); } hsla.lightness = this.scaleValue(hsla.lightness, shift.lightnessLimit); const shiftContrast = shift.contrast / hsla.alpha; const currentContrast = Number((hsla.lightness - backgroundLightness).toFixed(2)), down = Number(Math.max(backgroundLightness - Math.min(Math.max(backgroundLightness - shiftContrast, 0), shift.lightnessLimit), 0).toFixed(2)), up = Number(Math.max(Math.min(backgroundLightness + shiftContrast, shift.lightnessLimit) - backgroundLightness, 0).toFixed(2)); if (currentContrast < 0) // background is lighter than foreground { if (down >= up) // make foreground even darker { hsla.lightness = Math.max(backgroundLightness + Math.min(currentContrast, -shiftContrast), 0); } else // invert and make foreground lighter than background { hsla.lightness = Math.min(backgroundLightness + shiftContrast, shift.lightnessLimit); } } else // background is darker than foreground { if (up >= down) // make foreground even more lighter { hsla.lightness = Math.min(backgroundLightness + Math.max(currentContrast, shiftContrast), shift.lightnessLimit); } else // invert and make foreground darker than background { hsla.lightness = Math.max(backgroundLightness - shiftContrast, 0); } } } public changeColor(rgbaString: string | null, backgroundLightness: number, tag: any, ignoreBlueFilter?: boolean): ColorEntry { rgbaString = rgbaString || RgbaColor.Black; rgbaString = rgbaString === "none" ? RgbaColor.Transparent : rgbaString; const inheritedColor = this.getInheritedColor(tag, rgbaString); let inheritedColorValue: string | undefined = undefined; if (inheritedColor) { if (//inheritedColor.inheritance === ColorInheritance.Original && inheritedColor.backgroundLight === backgroundLightness && inheritedColor.role === this._component) { inheritedColor.owner = this._app.isDebug ? tag : null; return inheritedColor; } else { inheritedColorValue = rgbaString; rgbaString = inheritedColor.originalColor; } } let rgba = RgbaColor.parse(rgbaString!), result: ColorEntry; if (rgba.alpha === 0) { result = this.processTransparentColor(rgbaString, backgroundLightness, inheritedColorValue, tag); return result; } else { const hsla = RgbaColor.toHslaColor(rgba); const originalLight = hsla.lightness, isGray = this.isGray(tag, rgbaString, hsla); this.changeHslaColor(hsla, backgroundLightness, isGray, isGray ? this.getGrayShift(tag, rgbaString, hsla) : this._colorShift); let newRgbColor = ignoreBlueFilter ? HslaColor.toRgbaColor(hsla) : this.applyBlueFilter(HslaColor.toRgbaColor(hsla)); result = { role: this._component, color: newRgbColor.toString(), light: hsla.lightness, backgroundLight: backgroundLightness, originalLight: originalLight, originalColor: rgbaString, inheritedColor: inheritedColorValue, alpha: rgba.alpha, isUpToDate: true, reason: ColorReason.Ok, owner: this._app.isDebug ? tag : null, }; return result; } } protected processTransparentColor(rgbaString: string, backgroundLightness: number, inheritedColorValue: string | undefined, tag: any) { return { role: this._component, color: null, light: 0, backgroundLight: backgroundLightness, originalLight: 0, originalColor: rgbaString, inheritedColor: inheritedColorValue, alpha: 0, isUpToDate: true, reason: ColorReason.Transparent, owner: this._app.isDebug ? tag : null, } as ColorEntry; } protected isGray(tag: Element, rgbaString: string, hsla: HslaColor): boolean { return this._colorShift.replaceAllHues || hsla.saturation < 0.1 && this._colorShift.graySaturation !== 0; } protected getGrayShift(tag: Element, rgbaString: string, hsla: HslaColor): ColorShift { return this._colorShift; } } @injectable(ITextShadowColorProcessor) class TextShadowColorProcessor extends ForegroundColorProcessor implements ITextShadowColorProcessor { protected getInheritedColor(tag: HTMLElement, rgbStr: string): ColorEntry | null { if (tag.parentElement && tag.parentElement instanceof HTMLElement === tag instanceof HTMLElement) { if (tag.parentElement.mlTextShadow) { let inheritedColor: ColorEntry | undefined if (tag.parentElement.mlTextShadow.color === rgbStr) { inheritedColor = Object.assign({}, tag.parentElement!.mlTextShadow!); inheritedColor!.inheritance = ColorInheritance.Afterwards; } else if (tag.parentElement.mlTextShadow.originalColor === rgbStr || tag.parentElement.mlTextShadow.inheritedColor === rgbStr) { if (!tag.style.textShadow && tag.tagName !== "CODE") { inheritedColor = Object.assign({}, tag.parentElement!.mlTextShadow!); inheritedColor!.inheritance = ColorInheritance.Original; } } if (inheritedColor) { inheritedColor.color = null; inheritedColor.reason = ColorReason.Inherited; inheritedColor.base = this._app.isDebug ? tag.parentElement!.mlTextShadow : null return inheritedColor; } } else { return this.getInheritedColor(tag.parentElement, rgbStr) } } return null; } constructor( app: IApplicationSettings, settingsManager: IBaseSettingsManager) { super(app, settingsManager); this._component = Component.TextShadow; } } @injectable(ITextColorProcessor) class TextColorProcessor extends ForegroundColorProcessor implements ITextColorProcessor { protected readonly _tagName: "p" | "a" = "p"; protected readonly _defaultColors = new WeakMap<Document, string>(); protected isGray(tag: Element, rgbaString: string, hsla: HslaColor): boolean { return this._colorShift.replaceAllHues || (hsla.saturation < 0.1 || rgbaString === this.getDefaultColor(tag.ownerDocument!)) && this._colorShift.graySaturation !== 0; } public getDefaultColor(doc: Document): string | undefined { return this._defaultColors.get(doc); } public calculateDefaultColor(doc: Document, defaultColor?: string) { let elementColor = defaultColor || ""; if (!elementColor) { const element = doc.createElement(this._tagName); element.mlIgnore = true; (element as any).href = "#"; element.style.display = "none"; doc.body.appendChild(element); const style = doc.defaultView!.getComputedStyle(element, ""); if (style) { elementColor = style.color!; } else { elementColor = RgbaColor.Black; } element.remove(); } this._defaultColors.set(doc, elementColor); return elementColor; } protected getInheritedColor(tag: HTMLElement, rgbStr: string): ColorEntry | null { if (tag.parentElement && (tag.isPseudo || tag.parentElement instanceof HTMLElement === tag instanceof HTMLElement) && !(tag instanceof HTMLTableElement || tag instanceof HTMLTableCellElement || tag instanceof HTMLTableRowElement || tag instanceof HTMLTableSectionElement)) { if (tag.parentElement!.mlColor) { let inheritedColor: ColorEntry | undefined if (tag.parentElement!.mlColor!.color === rgbStr) { inheritedColor = Object.assign({}, tag.parentElement!.mlColor!); inheritedColor!.inheritance = ColorInheritance.Afterwards; } else if (tag.parentElement!.mlColor!.originalColor === rgbStr || tag.parentElement!.mlColor!.inheritedColor === rgbStr || tag.parentElement!.mlColor!.intendedColor === rgbStr) { const ns = tag instanceof SVGElement ? USP.svg : USP.htm; if (!tag.style.getPropertyValue(ns.css.fntColor)) { inheritedColor = Object.assign({}, tag.parentElement!.mlColor!); inheritedColor!.inheritance = ColorInheritance.Original; } } if (inheritedColor) { inheritedColor.intendedColor = inheritedColor.intendedColor || inheritedColor.color; inheritedColor.color = null; inheritedColor.reason = ColorReason.Inherited; inheritedColor.base = this._app.isDebug ? tag.parentElement!.mlColor! : null return inheritedColor; } } else { return this.getInheritedColor(tag.parentElement!, rgbStr) } } return null; } constructor( app: IApplicationSettings, settingsManager: IBaseSettingsManager) { super(app, settingsManager); this._component = Component.Text; } } @injectable(IHighlightedTextColorProcessor) class HighlightedTextColorProcessor extends TextColorProcessor implements IHighlightedTextColorProcessor { constructor( app: IApplicationSettings, settingsManager: IBaseSettingsManager) { super(app, settingsManager); this._component = Component.HighlightedText; } } @injectable(ILinkColorProcessor) class LinkColorProcessor extends TextColorProcessor implements ILinkColorProcessor { protected readonly _tagName = "a"; protected getInheritedColor(tag: HTMLElement, rgbStr: string): ColorEntry | null { if (!(tag instanceof HTMLAnchorElement)) { return super.getInheritedColor(tag, rgbStr); } return null; } protected isGray(tag: Element, rgbaString: string, hsla: HslaColor): boolean { // если практически серый // или равен нормальному цвету текста // или близок к дефолтному оттенку текста (значит унаследован) то считать текстом return this._colorShift.replaceAllHues || (Math.abs(hsla.hue - this._settingsManager.shift.Text.grayHue) < 2) || (hsla.saturation < 0.1 || rgbaString === this.getDefaultColor(tag.ownerDocument!)) && this._colorShift.graySaturation !== 0 || (hsla.saturation < 0.1 || rgbaString === this._textColorProcessor.getDefaultColor(tag.ownerDocument!)) && this._settingsManager.shift.Text.graySaturation !== 0; } protected getGrayShift(tag: Element, rgbaString: string, hsla: HslaColor): ColorShift { if ((hsla.saturation < 0.1 || Math.abs(hsla.hue - this._settingsManager.shift.Text.grayHue) < 2 || rgbaString === this._textColorProcessor.getDefaultColor(tag.ownerDocument!))) { return this._settingsManager.shift.Text; } else { return this._colorShift; } } constructor( app: IApplicationSettings, settingsManager: IBaseSettingsManager, protected readonly _textColorProcessor: ITextColorProcessor) { super(app, settingsManager); this._component = Component.Link; } } @injectable(IVisitedLinkColorProcessor) class VisitedLinkColorProcessor extends LinkColorProcessor implements IVisitedLinkColorProcessor { protected readonly _tagName = "a"; constructor( app: IApplicationSettings, settingsManager: IBaseSettingsManager, textColorProcessor: ITextColorProcessor) { super(app, settingsManager, textColorProcessor); this._component = Component.VisitedLink; } } @injectable(IActiveLinkColorProcessor) class ActiveLinkColorProcessor extends LinkColorProcessor implements IActiveLinkColorProcessor { protected readonly _tagName = "a"; constructor( app: IApplicationSettings, settingsManager: IBaseSettingsManager, textColorProcessor: ITextColorProcessor) { super(app, settingsManager, textColorProcessor); this._component = Component.Link$Active; } } @injectable(IHoverLinkColorProcessor) class HoverLinkColorProcessor extends LinkColorProcessor implements IHoverLinkColorProcessor { protected readonly _tagName = "a"; constructor( app: IApplicationSettings, settingsManager: IBaseSettingsManager, textColorProcessor: ITextColorProcessor) { super(app, settingsManager, textColorProcessor); this._component = Component.Link$Hover; } } @injectable(IActiveVisitedLinkColorProcessor) class ActiveVisitedLinkColorProcessor extends LinkColorProcessor implements IActiveVisitedLinkColorProcessor { protected readonly _tagName = "a"; constructor( app: IApplicationSettings, settingsManager: IBaseSettingsManager, textColorProcessor: ITextColorProcessor) { super(app, settingsManager, textColorProcessor); this._component = Component.VisitedLink$Active; } } @injectable(IHoverVisitedLinkColorProcessor) class HoverVisitedLinkColorProcessor extends LinkColorProcessor implements IHoverVisitedLinkColorProcessor { protected readonly _tagName = "a"; constructor( app: IApplicationSettings, settingsManager: IBaseSettingsManager, textColorProcessor: ITextColorProcessor) { super(app, settingsManager, textColorProcessor); this._component = Component.VisitedLink$Hover; } } @injectable(IBorderColorProcessor) class BorderColorProcessor extends ForegroundColorProcessor implements IBorderColorProcessor { constructor( app: IApplicationSettings, settingsManager: IBaseSettingsManager) { super(app, settingsManager); this._component = Component.Border; } } @injectable(IButtonBackgroundColorProcessor) class ButtonBackgroundColorProcessor extends ForegroundColorProcessor implements IButtonBackgroundColorProcessor { constructor( app: IApplicationSettings, settingsManager: IBaseSettingsManager) { super(app, settingsManager); this._component = Component.ButtonBackground; } protected processTransparentColor(rgbaString: string, backgroundLightness: number, inheritedColorValue: string | undefined, tag: any) { return { role: this._component, color: null, reason: ColorReason.Parent, originalColor: rgbaString, owner: this._app.isDebug ? tag : null, light: backgroundLightness, backgroundLight: backgroundLightness, originalLight: 1, // since i don't know the real value inheritedColor: inheritedColorValue, alpha: 1, // since i don't know the real value isUpToDate: true } as ColorEntry; } } @injectable(IHighlightedBackgroundColorProcessor) class HighlightedBackgroundColorProcessor extends ForegroundColorProcessor implements IHighlightedBackgroundColorProcessor { constructor( app: IApplicationSettings, settingsManager: IBaseSettingsManager) { super(app, settingsManager); this._component = Component.HighlightedBackground; } protected processTransparentColor(rgbaString: string, backgroundLightness: number, inheritedColorValue: string | undefined, tag: any) { return { role: this._component, color: null, reason: ColorReason.Parent, originalColor: rgbaString, owner: this._app.isDebug ? tag : null, light: backgroundLightness, backgroundLight: backgroundLightness, originalLight: 1, // since i don't know the real value inheritedColor: inheritedColorValue, alpha: 1, // since i don't know the real value isUpToDate: true } as ColorEntry; } } @injectable(IButtonBorderColorProcessor) class ButtonBorderColorProcessor extends ForegroundColorProcessor implements IButtonBorderColorProcessor { constructor( app: IApplicationSettings, settingsManager: IBaseSettingsManager) { super(app, settingsManager); this._component = Component.ButtonBorder; } } @injectable(IScrollbarHoverColorProcessor) class ScrollbarHoverColorProcessor extends ForegroundColorProcessor implements IScrollbarHoverColorProcessor { constructor( app: IApplicationSettings, settingsManager: IBaseSettingsManager) { super(app, settingsManager); this._component = Component.Scrollbar$Hover; } } @injectable(IScrollbarNormalColorProcessor) class ScrollbarNormalColorProcessor extends ForegroundColorProcessor implements IScrollbarNormalColorProcessor { constructor( app: IApplicationSettings, settingsManager: IBaseSettingsManager) { super(app, settingsManager); this._component = Component.Scrollbar$Normal; } } @injectable(IScrollbarActiveColorProcessor) class ScrollbarActiveColorProcessor extends ForegroundColorProcessor implements IScrollbarActiveColorProcessor { constructor( app: IApplicationSettings, settingsManager: IBaseSettingsManager) { super(app, settingsManager); this._component = Component.Scrollbar$Active; } } @injectable(IDynamicTextColorProcessor) class DynamicTextColorProcessor extends TextColorProcessor implements IDynamicTextColorProcessor { constructor( app: IApplicationSettings, settingsManager: IDynamicSettingsManager) { super(app, settingsManager); this._component = Component.Text; } } @injectable(IDynamicLinkColorProcessor) class DynamicLinkColorProcessor extends LinkColorProcessor implements IDynamicLinkColorProcessor { constructor( app: IApplicationSettings, settingsManager: IDynamicSettingsManager) { super(app, settingsManager, null as any); this._component = Component.Link; } protected isGray(tag: Element, rgbaString: string, hsla: HslaColor): boolean { return true; } protected getGrayShift(tag: Element, rgbaString: string, hsla: HslaColor): ColorShift { return this._colorShift; } } @injectable(IDynamicVisitedLinkColorProcessor) class DynamicVisitedLinkColorProcessor extends VisitedLinkColorProcessor implements IDynamicVisitedLinkColorProcessor { constructor( app: IApplicationSettings, settingsManager: IDynamicSettingsManager) { super(app, settingsManager, null as any); this._component = Component.VisitedLink; } protected isGray(tag: Element, rgbaString: string, hsla: HslaColor): boolean { return true; } protected getGrayShift(tag: Element, rgbaString: string, hsla: HslaColor): ColorShift { return this._colorShift; } } @injectable(IDynamicBorderColorProcessor) class DynamicBorderColorProcessor extends BorderColorProcessor implements IDynamicBorderColorProcessor { constructor( app: IApplicationSettings, settingsManager: IDynamicSettingsManager) { super(app, settingsManager); this._component = Component.Border; } } @injectable(IDynamicButtonBackgroundColorProcessor) class DynamicButtonBackgroundColorProcessor extends ButtonBackgroundColorProcessor implements IDynamicButtonBackgroundColorProcessor { constructor( app: IApplicationSettings, settingsManager: IDynamicSettingsManager) { super(app, settingsManager); this._component = Component.ButtonBackground; } }
the_stack
import { routingPathConfig } from '@config/routing-path.config'; import { NotaddNavigationItem } from '@notadd/types'; export const navigation: Array<NotaddNavigationItem> = [ { id: 'general', title: '常规', i18n: 'Navigation.General', type: 'group', children: [ { id: 'dashboard', title: '仪表盘', i18n: 'Navigation.Dashboard', type: 'collapse', icon: 'dashboard', children: [ { id: 'analytics', title: '分析页', i18n: 'Navigation.Analytics', type: 'item', url: [ routingPathConfig.app.general, routingPathConfig.general.dashboards, routingPathConfig.dashboards.analytics ], badge: { title: '25', bg: '#1189fb', fg: '#FFFFFF' } }, { id: 'workspace', title: '工作台', i18n: 'Navigation.Workspace', type: 'item', url: [ routingPathConfig.app.general, routingPathConfig.general.dashboards, routingPathConfig.dashboards.workspace ] } ] }, { id: 'pages', title: '页面', i18n: 'Navigation.Pages', type: 'collapse', icon: 'pages', children: [ { id: 'profile', title: '个人主页', i18n: 'Navigation.Profile', type: 'item', url: [ routingPathConfig.app.general, routingPathConfig.general.pages, routingPathConfig.pages.profile ] }, { id: 'errors', title: '错误页', i18n: 'Navigation.Errors', type: 'collapse', children: [ { id: 'errors_400', title: '400', i18n: 'Navigation.Errors_400', type: 'item', url: [ routingPathConfig.app.error, ], urlParam: { code: 400 } }, { id: 'errors_403', title: '403', i18n: 'Navigation.Errors_403', type: 'item', url: [ routingPathConfig.app.error, ], urlParam: { code: 403 } }, { id: 'errors_404', title: '404', i18n: 'Navigation.Errors_404', type: 'item', url: [ routingPathConfig.app.error, ], urlParam: { code: 404 } }, { id: 'errors_500', title: '500', i18n: 'Navigation.Errors_500', type: 'item', url: [ routingPathConfig.app.error, ], urlParam: { code: 500 } }, { id: 'errors_503', title: '503', i18n: 'Navigation.Errors_503', type: 'item', url: [ routingPathConfig.app.error ], urlParam: { code: 503 } } ] }, { id: 'login', title: '登录', i18n: 'Navigation.Login', type: 'item', url: [ routingPathConfig.app.general, routingPathConfig.general.pages, routingPathConfig.pages.login ] }, { id: 'register', title: '注册', i18n: 'Navigation.Register', type: 'item', url: [ routingPathConfig.app.general, routingPathConfig.general.pages, routingPathConfig.pages.register ] }, { id: 'login-v2', title: '登录 V2', i18n: 'Navigation.Login_v2', type: 'item', url: [ routingPathConfig.app.general, routingPathConfig.general.pages, routingPathConfig.pages.loginV2 ] }, { id: 'register-v2', title: '注册 V2', i18n: 'Navigation.Register_v2', type: 'item', url: [ routingPathConfig.app.general, routingPathConfig.general.pages, routingPathConfig.pages.registerV2 ] }, { id: 'forgot-password', title: '忘记密码', i18n: 'Navigation.ForgotPassword', type: 'item', url: [ routingPathConfig.app.general, routingPathConfig.general.pages, routingPathConfig.pages.forgotPassword ] }, { id: 'lockscreen', title: '锁定屏幕', i18n: 'Navigation.Lockscreen', type: 'item', url: [ routingPathConfig.app.general, routingPathConfig.general.pages, routingPathConfig.pages.lockscreen ] } ] } ] }, { id: 'elements', title: 'UI 元素', i18n: 'Navigation.Element', type: 'group', children: [ { id: 'basic-ui', title: '基础 UI', i18n: 'Navigation.BasicUi', type: 'collapse', icon: 'palette', children: [ { id: 'buttons', title: '按钮', i18n: 'Navigation.Button', type: 'item', url: [ routingPathConfig.app.elements, routingPathConfig.elements.basicUi, routingPathConfig.basicUi.buttons ] }, { id: 'cards', title: '卡片', i18n: 'Navigation.Card', type: 'item', url: [ routingPathConfig.app.elements, routingPathConfig.elements.basicUi, routingPathConfig.basicUi.cards ] }, { id: 'icons', title: '图标', i18n: 'Navigation.Icon', type: 'item', url: [ routingPathConfig.app.elements, routingPathConfig.elements.basicUi, routingPathConfig.basicUi.icons ] }, { id: 'list', title: '列表', i18n: 'Navigation.List', type: 'item', url: [ routingPathConfig.app.elements, routingPathConfig.elements.basicUi, routingPathConfig.basicUi.list ] }, { id: 'badges', title: '徽章', i18n: 'Navigation.Badge', type: 'item', url: [ routingPathConfig.app.elements, routingPathConfig.elements.basicUi, routingPathConfig.basicUi.badges ] }, { id: 'progress-bar', title: '进度条', i18n: 'Navigation.ProgressBar', type: 'item', url: [ routingPathConfig.app.elements, routingPathConfig.elements.basicUi, routingPathConfig.basicUi.progressBar ] }, { id: 'button-toggle', title: '开关按钮', i18n: 'Navigation.ButtonToggle', type: 'item', url: [ routingPathConfig.app.elements, routingPathConfig.elements.basicUi, routingPathConfig.basicUi.buttonToggle ] }, { id: 'chips', title: '标签', i18n: 'Navigation.Chip', type: 'item', url: [ routingPathConfig.app.elements, routingPathConfig.elements.basicUi, routingPathConfig.basicUi.chips ] }, { id: 'expansion-panel', title: '可展开面板', i18n: 'Navigation.ExpansionPanel', type: 'item', url: [ routingPathConfig.app.elements, routingPathConfig.elements.basicUi, routingPathConfig.basicUi.expansionPanel ] }, { id: 'tabs', title: '选项卡', i18n: 'Navigation.Tab', type: 'item', url: [ routingPathConfig.app.elements, routingPathConfig.elements.basicUi, routingPathConfig.basicUi.tabs ] }, { id: 'stepper', title: '步进器', i18n: 'Navigation.Stepper', type: 'item', url: [ routingPathConfig.app.elements, routingPathConfig.elements.basicUi, routingPathConfig.basicUi.stepper ] }, { id: 'grid-list', title: '网格列表', i18n: 'Navigation.GridList', type: 'item', url: [ routingPathConfig.app.elements, routingPathConfig.elements.basicUi, routingPathConfig.basicUi.gridList ] } ] }, { id: 'ng-material', title: '拓展组件', i18n: 'Navigation.NgMaterial2', type: 'collapse', icon: 'extension', children: [ { id: 'alert', title: '提示框', i18n: 'Navigation.Alert', type: 'item', url: [ routingPathConfig.app.elements, routingPathConfig.elements.ngMaterial2, routingPathConfig.ngMaterial2.alert ] }, { id: 'carousel', title: '轮播图', i18n: 'Navigation.Carousel', type: 'item', url: [ routingPathConfig.app.elements, routingPathConfig.elements.ngMaterial2, routingPathConfig.ngMaterial2.carousel ] }, { id: 'cascade-dropdownlist', title: '多级联动', i18n: 'Navigation.CascadeDropdownlist', type: 'item', url: [ routingPathConfig.app.elements, routingPathConfig.elements.ngMaterial2, routingPathConfig.ngMaterial2.cascadeDropdownlist ] } ] }, { id: 'angular-cdk', title: 'Angular CDK', i18n: 'Navigation.AngularCdk', type: 'collapse', icon: 'font_download', children: [ { id: 'virtual-list', title: '虚拟列表', i18n: 'Navigation.VirtualList', type: 'item', url: [ routingPathConfig.app.elements, routingPathConfig.elements.angularCdk, routingPathConfig.angularCdk.virtualList ] } ] }, { id: 'data-table', title: '数据表', i18n: 'Navigation.DataTable', type: 'item', icon: 'grid_on', url: [ routingPathConfig.app.elements, routingPathConfig.elements.dataTable ] }, { id: 'advanced-ui', title: '高级组件', i18n: 'Navigation.AdvancedUi', type: 'collapse', icon: 'tune', children: [ { id: 'file-upload', title: '文件上传', i18n: 'Navigation.FileUpload', type: 'item', url: [ routingPathConfig.app.elements, routingPathConfig.elements.advancedUi, routingPathConfig.advancedUi.fileUpload ] }, { id: 'json-schema-form', title: 'json schema form', i18n: 'Navigation.JsonSchemaForm', type: 'item', url: [ routingPathConfig.app.elements, routingPathConfig.elements.advancedUi, routingPathConfig.advancedUi.jsonSchemaForm ] } ] } ] }/*, { id: 'applications', title: '应用', i18n: 'Navigation.Applications', type: 'group', children: [ { id: 'roles-permissions', title: '角色 & 权限', i18n: 'Navigation.RolesPermissions', type: 'collapse', icon: 'lock', children: [ { id: 'roles', title: '角色', i18n: 'Navigation.Role', type: 'item', url: [ routingPathConfig.app.applications, routingPathConfig.applications.rolesPermissions, routingPathConfig.rolesPermissions.roles ] }, { id: 'permission', title: '权限', i18n: 'Navigation.Permission', type: 'item', url: [ routingPathConfig.app.applications, routingPathConfig.applications.rolesPermissions, routingPathConfig.rolesPermissions.permission ] } ] }, { id: 'users', title: '用户', i18n: 'Navigation.Users', type: 'collapse', icon: 'people', children: [ { id: 'user-group', title: '用户组', i18n: 'Navigation.UserGroup', type: 'item', url: [ routingPathConfig.app.applications, routingPathConfig.applications.users, routingPathConfig.users.userGroup ] }, { id: 'user', title: '用户', i18n: 'Navigation.User', type: 'item', url: [ routingPathConfig.app.applications, routingPathConfig.applications.users, routingPathConfig.users.user ] } ] } ] }*/, { id: 'services', title: 'SERVICES', i18n: 'Navigation.Services', type: 'group', children: [ { id: 'excel-export', title: 'Excel 导出', i18n: 'Navigation.ExcelExport', type: 'item', icon: 'unarchive', url: [ routingPathConfig.app.services, routingPathConfig.services.excelExport ] }, { id: 'screenshot', title: '屏幕截图', i18n: 'Navigation.Screenshot', type: 'item', icon: 'wallpaper', url: [ routingPathConfig.app.services, routingPathConfig.services.screenshot ] } ] } ];
the_stack
module TDev.Browser { export var TheHub: Hub; export interface HubSection { title: string; // localized } var editorModes: StringMap<Cloud.EditorMode>; var themes: StringMap<Cloud.ClientTheme>; function initThemes() { if (editorModes && themes) return; editorModes = { 'block': { id: 'block', name: lf("beginner"), descr: lf("Drag and drop blocks, simplified interface, great for beginners!"), astMode: 1, artId: 'brfljsds', widgets: { // edit addNewButton: true, undoButton: true, changeSkillLevel: true, // refactoring promoteRefactoring: true, fixItButton: true, splitScreen: false, splitScreenOnLoad: true, searchArtRefactoring: true, calcSearchArt: true, scriptPropertiesIcons: true, // statements stringConcatProperty: true, show: true, "return": true, // sections dataSection: true, artSection: true, librariesSection: true, // ui wallScreenshot: true, wallHeart: true, startTutorialButton: true, nextTutorialsList: true, // hub hubTutorials: true, hubLearn: true, hubShowcase: true, publicationComments: true, translateComments: true, whileConditionDefault: "true", forConditionDefault: "5", ifConditionDefault: "true", scriptSocialLinks: true, scriptEmail: true, scriptAddToChannel: true, } }, 'classic': { id: 'classic', name: lf("coder"), descr: lf("Edit code as text, more options, for aspiring app writers!"), artId: 'ehymsljr', astMode: 2, widgets: { // edit addNewButton: true, undoButton: true, // refactoring promoteRefactoring: true, fixItButton: true, splitScreen: true, searchArtRefactoring: true, calcSearchArt: true, tokenRefactoring: true, // misc changeSkillLevel: true, // edit copyPaste: true, selectStatements: true, selectExpressions: true, // features actionSettings: true, publishAsHidden: true, // refactoring simplify: true, // ui splitButton: true, uploadArtInSearchButton: true, calcApiHelp: true, sideRunButton: true, tutorialGoToPreviousStep: true, helpLinks: true, wallScreenshot: true, wallHeart: true, wallStop: true, nextTutorialsList: true, codeSearch: true, // section dataSection: true, eventsSection: true, pagesSection: true, artSection: true, librariesSection: true, scriptProperties: true, objectsSection: true, decoratorsSection: true, scriptPropertiesIcons: true, scriptPropertiesSettings: true, scriptPropertiesPropertyAtomic: true, scriptPropertiesManagement: true, databaseSection: true, persistanceRadio: true, // statements comment: true, foreach: true, boxed: true, stringConcatProperty: true, show: true, "return": true, "break": true, "continue": true, // hub hubTutorials: true, hubLearn: true, hubShowcase: true, hubTopAndNew: true, hubScriptUpdates: true, hubUsers: true, hubChannels: true, notifyAppReloaded: true, startTutorialButton: true, publicationComments: true, translateComments: true, outAssign: true, scriptSocialLinks: true, scriptPrintScript: true, scriptPrintTopic: true, scriptEmail: true, scriptAddToChannel: true, } }, 'pro': { id: 'pro', name: lf("expert"), artId: 'indivfwz', descr: lf("'Javascripty' curly braces, all the tools, for experienced devs!"), astMode: 3, widgets: { // edit addNewButton: true, undoButton: true, // refactoring promoteRefactoring: true, fixItButton: true, splitScreen: true, searchArtRefactoring: true, calcSearchArt: true, makeAsyncRefactoring: true, tokenRefactoring: true, // misc changeSkillLevel: true, // edit copyPaste: true, selectStatements: true, selectExpressions: true, // features actionSettings: true, publishAsHidden: true, // refactoring simplify: true, // ui splitButton: true, uploadArtInSearchButton: true, calcApiHelp: true, sideRunButton: true, tutorialGoToPreviousStep: true, helpLinks: true, wallScreenshot: true, wallHeart: true, wallStop: true, // section dataSection: true, eventsSection: true, artSection: true, librariesSection: true, scriptProperties: true, scriptPropertiesSettings: true, scriptPropertiesPropertyAtomic: true, scriptPropertiesUseCppCompiler: true, databaseSection: true, // statements comment: true, foreach: true, boxed: true, show: true, "return": true, "break": true, "continue": true, stringConcatProperty: true, //navigation codeSearch: true, findReferences: true, gotoNavigation: true, // refactorings stripBlock: true, // debugging toggleBreakpoint: true, debugButton: true, // ui publishDescription: true, sendPullRequest: true, scriptStats: true, userSocialTab: true, scriptConvertToDocs: true, scriptConvertToTutorial: true, nextTutorialsList: true, // sections testsSection: true, actionTypesSection: true, pagesSection: true, objectsSection: true, decoratorsSection: true, // script lifecycle updateButton: true, editLibraryButton: true, errorsButton: true, logsButton: true, deployButton: true, // ui pluginsButton: true, runTestsButton: true, scriptPropertiesManagement: true, scriptPropertiesIcons: true, scriptPropertiesExport: true, scriptPropertiesPlatform: true, scriptPropertiesInstrumentation: true, scriptPropertiesData: true, wallLogsButton: true, scriptPropertiesPropertyCloud: true, stringEditFullScreen: true, persistanceRadio: true, awaitClock: true, // language async: true, testAction: true, lambda: true, // hub commentHistory: true, scriptPullChanges: true, scriptDiffToBase: true, scriptHistoryTab: true, scriptInsightsTab: true, notifyAppReloaded: true, showTemporaryNotice: true, githubLinks: true, hubLearn: true, hubShowcase: true, hubTopAndNew: true, hubScriptUpdates: true, hubUsers: true, hubMyArt: true, hubChannels: true, publicationComments: true, translateComments: true, outAssign: true, scriptSocialLinks: true, scriptPrintScript: true, scriptPrintTopic: true, scriptEmail: true, scriptAddToChannel: true, } } } themes = { 'expert': { name: lf("Expert"), description: lf("All options turned on"), editorMode: editorModes['pro'] }, 'minecraft': { name: "Minecraft", description: lf("Learn to code with Minecraft"), logoArtId: 'eopyzwpm', tutorialsTopic: 'minecrafttutorials', scriptSearch: '#minecraft', scriptTemplates: ['blankminecraft', 'blankcreeper'], noAnimations: true, editorMode: { id: 'minecraft', name: lf("minecraft"), descr: lf("Drag and drop blocks, simplified interface, great for beginners!"), astMode: 2, artId: 'brfljsds', widgets: { // edit addNewButton: true, undoButton: true, changeSkillLevel: true, async: true, // refactoring updateButton: true, promoteRefactoring: true, fixItButton: true, splitScreen: false, splitScreenOnLoad: true, // searchArtRefactoring: true, // calcSearchArt: true, scriptProperties: true, scriptPropertiesIcons: true, // statements copyPaste: true, selectStatements: true, stringConcatProperty: true, show: true, "return": true, gotoNavigation: true, // sections dataSection: true, // artSection: true, librariesSection: true, // ui wallScreenshot: true, wallHeart: true, startTutorialButton: true, nextTutorialsList: true, // hub hubTutorials: true, // hubShowcase : true, publicationComments: true, translateComments: true, whileConditionDefault: "true", whileBodyDefault: "skip; minecraft->pause(20);", forConditionDefault: "5", ifConditionDefault: "true", scriptSocialLinks: true, scriptAddToChannel: true, } } }, 'rpi': { name: "Raspberry Pi", description: lf("Learn to code with Raspberry Pi"), logoArtId: 'eopyzwpm', tutorialsTopic: 'minecraftpitutorials', scriptTemplates: ['blankminecraftpi'], noAnimations: true, lowMemory: true, editorMode: editorModes['block'], }, 'arduino': { name: "Arduino", description: lf("Program Arduino boards"), logoArtId: 'kzajxznr', wallpaperArtId: 'kzajxznr', tutorialsTopic: 'arduinotutorials', scriptSearch: '#arduino', scriptTemplates: ['blankarduino', 'blankesplore'], intelliProfileId: 'kbmkc', editorMode: editorModes['classic'], }, 'engduino': { name: "Engduino", description: lf("Programming the Engduino"), logoArtId: 'qmjzqlkc', wallpaperArtId: 'qmjzqlkc', scriptSearch: '#engduino', scriptTemplates: ['blankengduino'], intelliProfileId: 'kbmkc', editorMode: editorModes['classic'], }, 'microbit': { name: 'BBC micro:bit', description: ' ', scriptSearch: '#microbit', scriptTemplates: ['blankmicrobit'], intelliProfileId: 'upfje', editorMode: { id: 'microbit', name: 'Micro Bit', descr: lf("Micro Bit mode!"), astMode: 2, widgets: { hubTutorials: true, addNewButton: true, undoButton: true, promoteRefactoring: true, copyPaste: true, comment: true, dataSection: true, gotoNavigation: true, splitScreenOnLoad: true, updateButton: true, forceMainAsAction: true, singleReturnValue: true, integerNumbers: true, codeSearch: true, librariesSection: true, scriptPropertiesSettings: true, editorRunOnLoad: true, whileConditionDefault: "true", whileBodyDefault: "skip; basic->pause(20);", forConditionDefault: "5", "return": true, "break": true, scriptPrintScript: true, scriptPrintTopic: true, tutorialGoToPreviousStep: true, } }, }, 'restricted': { name: "Restricted", description: lf("Opinionated restricted mode"), scriptTemplates: ['blank'], intelliProfileId: 'lyusma', editorMode: { id: 'restricted', name: lf("restricted"), descr: lf("Restricted mode!"), astMode: 2, widgets: { addNewButton: true, undoButton: true, promoteRefactoring: true, fixItButton: true, copyPaste: true, comment: true, dataSection: true, objectsSection: true, gotoNavigation: true, splitScreenOnLoad: true, updateButton: true, forceMainAsAction: true, singleReturnValue: true, integerNumbers: true, codeSearch: true, librariesSection: true, scriptPropertiesSettings: true, editorRunOnLoad: true, calcApiHelp: true, scriptPropertiesUseCppCompiler: true, whileConditionDefault: "true", whileBodyDefault: "skip; basic->pause(20);", forConditionDefault: "5", "return": true, "break": true, awaitClock: true, tutorialGoToPreviousStep: true, scriptPrintScript: true, scriptPrintTopic: true, } }, }, 'restrictedteacher': { name: "Restricted Teacher", description: lf("Opinionated restricted mode"), scriptTemplates: ['blank', 'blankdocs'], intelliProfileId: 'lyusma', editorMode: { id: 'restrictedteacher', name: lf("teacher"), descr: lf("Restricted teacher mode!"), astMode: 2, widgets: { addNewButton: true, undoButton: true, promoteRefactoring: true, copyPaste: true, comment: true, dataSection: true, objectsSection: true, gotoNavigation: true, splitScreenOnLoad: true, updateButton: true, forceMainAsAction: true, singleReturnValue: true, integerNumbers: true, codeSearch: true, librariesSection: true, scriptProperties: true, scriptPropertiesSettings: true, scriptPropertiesUseCppCompiler: true, editorRunOnLoad: true, calcApiHelp: true, whileConditionDefault: "true", whileBodyDefault: "skip; basic->pause(20);", forConditionDefault: "5", "return": true, "break": true, scriptHistoryTab: true, tutorialGoToPreviousStep: true, awaitClock: true, scriptPrintScript: true, scriptPrintTopic: true, // for docs artSection: true, selectStatements: true, // teacher specific scriptDiffToBase: true, scriptConvertToTutorial:true, socialNetworks: true, socialNetworkvideoptr: true, socialNetworkart: true, socialNetworkbbc: true, publishAsHidden: true, computingAtSchool: true, splitScreen: true, splitButton: true, actionSettings: true, calcSearchArt: true, searchArtRefactoring: true, editLibraryButton: true, scriptEmail: true, publicationComments: true, } }, }, 'restrictededitor': { name: "Restricted Editor", description: lf("Opinionated restricted mode"), scriptTemplates: ['blank', 'blankdocs'], editorMode: { id: 'restricteditor', name: lf("editor"), descr: lf("Restricted editor mode!"), astMode: 2, widgets: { addNewButton: true, undoButton: true, promoteRefactoring: true, copyPaste: true, comment: true, dataSection: true, gotoNavigation: true, updateButton: true, forceMainAsAction: true, singleReturnValue: true, integerNumbers: true, codeSearch: true, librariesSection: true, scriptProperties: true, scriptPropertiesSettings: true, scriptPropertiesUseCppCompiler: true, scriptPropertiesPropertyAtomic: true, editorRunOnLoad: true, calcApiHelp: true, whileConditionDefault: "true", whileBodyDefault: "skip; basic->pause(20);", forConditionDefault: "5", artSection: true, "return": true, "break": true, splitScreenOnLoad: false, findReferences: true, selectStatements: true, stringEditFullScreen: true, objectsSection: true, decoratorsSection: true, persistanceRadio: true, databaseSection: true, scriptPropertiesManagement: true, hideMyScriptHeader: true, scriptHistoryTab: true, tutorialGoToPreviousStep: true, awaitClock: true, //MORE // teacher specific scriptDiffToBase: true, scriptConvertToTutorial:true, socialNetworks: true, socialNetworkvideoptr: true, socialNetworkart: true, socialNetworkbbc: true, publishAsHidden: true, computingAtSchool: true, splitScreen: true, splitButton: true, actionSettings: true, calcSearchArt: true, searchArtRefactoring: true, editLibraryButton: true, scriptPrintScript: true, scriptPrintTopic: true, scriptEmail: true, publicationComments: true, // editor specific publishDescription: true, scriptPullChanges: true, testAction: true, testsSection: true, tokenRefactoring: true, selectExpressions: true, scriptConvertToDocs: true, } } } } } export module EditorSettings { export var AST_BLOCK = 1; export var AST_LEGACY = 2; export var AST_PRO = 3; export function showFeedbackBox() { var link = (text: string, lnk: string) => HTML.mkButton(text, () => { window.location.href = lnk }); if (ModalDialog.current && !ModalDialog.current.canDismiss) { window.open(Cloud.getServiceUrl()); return; } var relId = "(local)"; var mtch = /-(\d+)\//.exec(Ticker.mainJsName) if (mtch) relId = mtch[1]; var m = new ModalDialog(); m.fullWhite(); m.add(div("wall-dialog-header", Runtime.appName)); if (Cloud.config.tdVersion) m.add(div("wall-dialog-body", lf("Web app version {0}.", Cloud.config.tdVersion))); else m.add(div("wall-dialog-body", lf("Running against cloud services v{0}.", relId))); var legalButtons = Cloud.config.legalButtons.map(b => link(lf_static(b.name, true), b.url)); var btns: HTMLElement; m.add(btns = div("wall-dialog-buttons", Cloud.getUserId() ? HTML.mkButton(lf("Sign out"), () => TheEditor.logoutDialog()) : undefined, legalButtons )); if (EditorSettings.widgets().githubLinks) { btns.appendChild(HTML.mkButton(lf("changes"),() => { HTML.showProgressNotification(lf("downloading change log...")) Util.httpGetJsonAsync((<any>window).mainJsName.replace(/main.js$/, "buildinfo.json")) .then(t => RT.Web.browseAsync("http://github.com/Microsoft/TouchDevelop/commits/" + t.commit)) .done(); })); btns.appendChild( link(lf("GitHub"), "https://github.com/Microsoft/TouchDevelop") ); } if (Cloud.lite && ["upload", "admin", "view-bug", "root-ptr", "gen-code", "internal", "global-list"].some(perm => Cloud.hasPermission(perm))) { m.add(div("wall-dialog-header", lf("internal"))); var versionInfo = HTML.mkTextArea() versionInfo.rows = 4; versionInfo.style.fontSize = "0.8em"; versionInfo.style.width = "100%"; versionInfo.value = lf("Loading version info...") Cloud.getPrivateApiAsync("stats/dmeta") .done(resp => { var tm = (n: number) => Util.isoTime(n) + " (" + Util.timeSince(n) + ")" versionInfo.value = lf("Web App version: {0} {1} /{2}", Cloud.config.releaseLabel, Cloud.config.tdVersion, Cloud.config.relid) + "\n" + lf("Service deployment: {0}", tm(resp.deploytime)) + "\n" + lf("Service activation: {0}", tm(resp.activationtime)); }) m.add(div("wall-dialog-body", versionInfo)) m.add(div("wall-dialog-body", [ (Cloud.hasPermission("internal") ? HTML.mkButton(lf("my scripts"), () => { Util.setHash("#list:installed-scripts") }) : null), (Cloud.hasPermission("internal") ? HTML.mkButton(lf("create script"), () => { TemplateManager.createScript() }) : null), // (Cloud.hasPermission("user-mgmt") ? HTML.mkButton(lf("abuse reports"), () => { Util.setHash("#list:installed-scripts:abusereports") }) : null), (Cloud.hasPermission("user-mgmt") ? HTML.mkButton(lf("abuse review"), () => { AbuseReview.show() }) : null), (Cloud.hasPermission("admin") ? HTML.mkButton(lf("API config"), () => { editApiConfig() }) : null), (Cloud.hasPermission("admin") ? HTML.mkButton(lf("permission review"), () => { permissionReview() }) : null), (Cloud.hasPermission("stats") ? HTML.mkButton(lf("stats"), () => { stats() }) : null), (Cloud.hasPermission("admin") ? HTML.mkButton(lf("mbedint"), () => { mbedintUpdate() }) : null), (Cloud.hasPermission("global-list") ? HTML.mkButton(lf("pointer review"), () => { pointerReview() }) : null), (Cloud.hasPermission("root") ? HTML.mkAsyncButton(lf("clear videos"), () => clearVideosAsync("")) : null), (Cloud.hasPermission("gen-code") ? HTML.mkButton(lf("generate codes"), () => { var m = new ModalDialog() var perm = HTML.mkTextInput("text", "") var count = HTML.mkTextInput("text", "") var credit = HTML.mkTextInput("text", "") var desc = HTML.mkTextInput("text", "") var numuses = HTML.mkTextInput("text", "") perm.value = "preview" count.value = "1" credit.value = "1" numuses.value = "1" m.add(div("wall-dialog-body", lf("Permissions (preview, educator, moderator, staff): "), perm, lf("Number of codes: "), count, lf("Credit for each code: "), credit, lf("Number of uses for each code: "), numuses, lf("Code description (purpose): "), desc, HTML.mkAsyncButton(lf("generate"), () => { var data = { count: parseInt(count.value), credit: parseInt(credit.value) * parseInt(numuses.value), singlecredit: parseInt(credit.value), permissions: perm.value.replace(/[,\s]+/g, ","), description: desc.value, } var items = [] var getsome = count => { if (count == 0) { ModalDialog.showText(items.join("\n"), lf("your codes")) return } data.count = Math.min(count, 100) count -= data.count TDev.Cloud.postPrivateApiAsync("generatecodes", data) .then(r => { HTML.showProgressNotification(lf("generating, {0} to go", count)) items.pushRange(r.items) getsome(count) }, e => Cloud.handlePostingError(e, lf("generate codes"))) } if (!data.count) HTML.wrong(count) else if (!data.singlecredit) HTML.wrong(credit) else if (!data.credit) HTML.wrong(numuses) else if (!data.permissions) HTML.wrong(perm) else if (!data.description) HTML.wrong(desc) else ModalDialog.ask( lf("Creating this code will let up to {0} users into the system.", data.count * data.credit), lf("create codes"), () => getsome(data.count)) return Promise.as() }))) m.show() }) : null) ])) if (Cloud.hasPermission("global-list")) { m.add(div("wall-dialog-header", lf("global lists"))); m.add(div("wall-dialog-body", [ HTML.mkButton(lf("users"), () => { Util.setHash("#list:users") }), HTML.mkButton(lf("scripts"), () => { Util.setHash("#list:new-scripts") }), HTML.mkButton(lf("art"), () => { Util.setHash("#list:art") }), HTML.mkButton(lf("pointers"), () => { Util.setHash("#list:pointers")}), HTML.mkButton(lf("page map"), () => { Browser.TheHub.showPointers() }), HTML.mkButton(lf("releases"), () => { Util.setHash("#list:releases" + (Cloud.config.relid ? ":release:" + Cloud.config.relid : "")) }), HTML.mkButton(lf("art review"), () => { Browser.ArtInfo.artReview() }), ])) } if (Cloud.hasPermission("script-promo")) { m.add(div("wall-dialog-header", lf("manage promos"))); var promoDiv = div("wall-dialog-body", HTML.mkButton(lf("NEW"), () => { ModalDialog.info(lf("creating..."), "") var app = new AST.App(null) app.setName("promo holder " + (Random.uint32() % 10000)) app.comment = "#promoholder" Cloud.postPrivateApiAsync("scripts", { text: app.serialize(), name: app.getName(), description: app.comment }) .then(resp => { TheApiCacheMgr.store(resp.id, resp) TheHost.getScriptInfoById(resp.id).editPromo() }) .done() })) m.add(promoDiv) Cloud.getPrivateApiAsync("config/promo") .then(resp => { var tags = (resp.autotags || []).concat((resp.tags || [])) var addtags = []; (resp.addlangs || []).forEach(l => { tags.forEach(t => { if (resp.addlangs.indexOf(t) < 0) addtags.push(t + "@" + l) }) }) tags.concat(addtags).forEach(t => { promoDiv.appendChild( HTML.mkButton(t, () => { Util.setHash("#list:promo-scripts/" + t) })) }) }) .done() } m.setScroll(); } var users = Object.keys(Cloud.litePermissions).filter(k => /^signin-/.test(k)).map(k => k.replace(/signin-/, "")) if (users.length > 0) { m.add(div("wall-dialog-header", lf("sign in as:"))); var usersDiv = div("wall-dialog-body") m.add(usersDiv) users.map(u => TheApiCacheMgr.getAsync(u, true).done(r => { if (r) { usersDiv.appendChild(HTML.mkButton(r.name, () => Editor.loginAs(r.id))) } })) } m.show(); } function clearVideosAsync(cont: string) : Promise { return Cloud.getPrivateApiAsync("videos" + (cont ? "?continuation=" + cont : "")) .then((videos: JsonList) => Promise.join( videos.items.map(video => Cloud.deletePrivateApiAsync(video.id).then(() => { }, () => { Util.log('failed to delete video ' + video.id) })) .concat(videos.continuation ? clearVideosAsync(videos.continuation) : Promise.as()))); } export function editApiConfig() { ModalDialog.editText(lf("API name"), "config/settings", name => { var r = Cloud.getPrivateApiAsync(name) r.then(resp => EditorHost.editFullScreenAsync("resp.json", JSON.stringify(resp, null, 2))) .then(val => { var r = RT.JsonObject.mk(val, (err) => { ModalDialog.info(lf("parse error"), err) }) if (r && r.value()) { var str = JSON.stringify(r.value(), null, 1) if (str.length > 300) str = str.slice(0, 300) + "..."; ModalDialog.ask(str, "update", () => { Cloud.postPrivateApiAsync(name, r.value()).done() }) } }) .done() return r }) } function csv(l:string[]) { return l.map(s => "\"" + (s||"").replace(/[\\"]/g, " ") + "\"").join(",") + "\n" } function pointerReview() { ModalDialog.editText(lf("Ignored paths"), "usercontent/,td/,functions/,device/,signin/,templates/", perms => { var okpaths = perms.split(/\s*,\s*/).filter(p => !!p) var pointers = [] var loop = (cont) => Browser.TheApiCacheMgr.getAsync("pointers?count=1000" + cont) .then(resp => { pointers.pushRange(resp.items) if (resp.continuation) loop("&continuation=" + resp.continuation) else fin() }) .done() var pointerList = "" var fin = () => { pointerList += csv(["Path", "User Name", "Description", "Script"]) pointers.forEach(p => { if (okpaths.some(pp => p.path.slice(0, pp.length) == pp)) return pointerList += csv([p.path, p.username, p.description, p.redirect || p.scriptid]) }) ModalDialog.showText(pointerList) } loop("") return new PromiseInv() }) } function mbedintUpdate() { ModalDialog.editText(lf("Target:tag"), "gcc:v2", perms => { var args = perms.split(/:/) return Cloud.postPrivateApiAsync("admin/mbedint/" + args[0], { op: "update", args: ["git checkout " + args[1] + ";"] }) .then(r => { var full = r.output.replace(/\x1b\[[0-9;]*m/g, "") var m = ModalDialog.showText("...[snip]...\n" + full.slice(-3000), null, <any>div(null, HTML.mkButton(lf("full"), () => { ModalDialog.showText(full) }), HTML.mkAsyncButton("save tag " + args[1], () => { var opts = {} opts[args[0] + "-" + args[1]] = r.imageid opts[args[1]] = r.imageid return Cloud.postPrivateApiAsync("config/compiletag", opts) .then(r => r, e => Cloud.handlePostingError(e, "")) }), HTML.mkButton(lf("cancel"), () => { m.dismiss() }))) }, e => Cloud.handlePostingError(e, "")) }) } function stats() { var fields = { "Scripts": "New_script,New_script_hidden", "Scripts (public)": "New_script", "Scripts (hidden)": "New_script_hidden", "#docs": "PubScript_fresh_docs,PubScript_update_docs,PubScript_fork_docs", "HTML": "PubScript_fresh_html,PubScript_update_html,PubScript_fork_html", "Blocks": "PubScript_fresh_blockly,PubScript_update_blockly,PubScript_fork_blockly", "Blocks (fork)": "PubScript_fork_blockly", "Blocks (new)": "PubScript_fresh_blockly", "TD": "PubScript_fresh_touchdevelop,PubScript_update_touchdevelop,PubScript_fork_touchdevelop", "TD (fork)": "PubScript_fork_touchdevelop", "TD (new)": "PubScript_fresh_touchdevelop", "CK": "PubScript_fresh_codekingdoms,PubScript_update_codekingdoms,PubScript_fork_codekingdoms", "CK (fork)": "PubScript_fork_codekingdoms", "CK (new)": "PubScript_fresh_codekingdoms", "Python": "PubScript_fresh_python,PubScript_update_python,PubScript_fork_python", "Python (fork)": "PubScript_fork_python", "Python (new)": "PubScript_fresh_python", "Resources": "New_art", "URLs": "New_pointer", "Accounts": "PubUser@federated", "Abuse reports": "New_abusereport", "Ignored reports": "AbuseSet@ignored", "Pub with report deleted": "AbuseSet@deleted", "Unignored reports": "AbuseSet@active", "Logins": "Login@federated", "Hearts": "New_review", "/app/ served": "ServeApp@index.html", "Homepage served": "ServePtr@home,ServePtrFirst@home", "Other page served": "ServePtr@other,ServePtrFirst@other", "Usage: TD": "app_editor_touchdevelop", "Usage: Blocks": "app_editor_blockly", "Usage: CK": "app_editor_codekingdoms", "Usage: Python": "app_editor_python", "Usage: My Scripts": "app_editor_shell", "Mobile: TD": "app_editor_touchdevelop_mobile", "Mobile: Blocks": "app_editor_blockly_mobile", "Mobile: CK": "app_editor_codekingdoms_mobile", "Mobile: Python": "app_editor_python_mobile", "Mobile: My Scripts": "app_editor_shell_mobile", "New script TD": "app_NewScript_touchdevelop", "New script Blocks": "app_NewScript_blockly", "New script CK": "app_NewScript_codekingdoms", "New script Python": "app_NewScript_python", "Simulator Runs": "app_coreRun,app_externalRun", "Compiles": "app_coreNativeCompile", "WebApp Start": "app_mainInit", "Edit Script": "app_browseEdit", "Install Script": "app_browseEditInstall", "Uninstall Script": "app_browseUninstall", "File Save": "app_browseSave", "TD Tutorial Start": "Tutorial_step0", } ModalDialog.editText(lf("How many days back?"), "180", days => { var flds = {} Object.keys(fields).forEach(k => { fields[k].split(/,\s*/).forEach(f => { flds[f] = 1 }) }) return Cloud.postPrivateApiAsync("dailystats", { start: Date.now()/1000-parseInt(days,10)*24*3600, length: 365, fields: Object.keys(flds) }) .then(resp => { if (resp.length < 1) { ModalDialog.info(lf("sorry"), lf("no data returned")) return; } var res = csv(["Date"].concat(Object.keys(fields))) var addValues = (hd:string, i:number) => { var line = [hd] Object.keys(fields).forEach(k => { var n = 0 fields[k].split(/,\s*/).forEach(f => { n += (resp.values[f][i] || 0) }) line.push(n.toString()) }) res += csv(line) } Object.keys(flds).forEach(f => { var sum = 0 for (var i = 0; i < resp.length; ++i) { sum += resp.values[f][i] } if (/^app_editor_/.test(f)) // convert to minutes sum = Math.round(sum / 6) resp.values[f][resp.length + 1] = sum resp.values[f][resp.length + 2] = Math.round(sum / resp.length * 100) / 100 }) for (var i = 0; i < resp.length; ++i) { var tm = new Date((resp.start + i * 24 * 3600) * 1000) var hd = tm.getUTCFullYear() + "-" + (tm.getUTCMonth()+1) + "-" + tm.getUTCDate() addValues(hd, i) } addValues("Total", resp.length + 1) addValues("Avarage", resp.length + 2) addValues("Lifetime total", resp.length) var dataurl = "data:text/csv;base64," + Util.base64Encode(res) HTML.browserDownloadText(res, "stats.csv", "text/csv") }, e => Cloud.handlePostingError(e, "")) }) } function permissionReview() { ModalDialog.info(lf("analyzing..."), lf("please wait")) var users = [] var loop = (cont) => Cloud.getPrivateApiAsync("users/admin?count=1000" + cont) .then(resp => { users.pushRange(resp.items) HTML.showProgressNotification(lf("got {0} users", users.length)) if (resp.continuation) loop("&continuation=" + resp.continuation) else fin() }) .done() var userList = "" var fin = () => { userList += csv(["User ID", "Nickname", "Permission"]) users.forEach(u => { var per = u.permissions.split(/,/).filter(p => !!p) per.sort() userList += csv([u.id, u.name, per.join(", ")]) }) ModalDialog.showText(userList) } loop("") } export function mkCopyrightNote(): HTMLElement { var beta = divLike("footer", "beta-note"); beta.setAttribute("role", "contentinfo"); var versionId = (<any>window).betaFriendlyId || Cloud.config.tdVersion; var versionNote = versionId ? ("<b>" + versionId + "</b> ") : ""; var copy = lf("© Copyright {0} {1}", new Date().getFullYear(), Runtime.companyCopyright) var copyrights = "<div class='beta-legal'>" + Cloud.config.legalButtons.map(b => Util.fmt("<span class='beta-underline'>{0:q}</span>", lf_static(b.name, true))).join("&nbsp;|&nbsp;") + "&nbsp;&nbsp;" + versionNote + "<span class='beta-black'>" + copy + "</span>&nbsp;&nbsp;" + "</div>"; Browser.setInnerHTML(beta, copyrights); beta.withClick(EditorSettings.showFeedbackBox); return beta; } export function setThemeFromSettings() { initThemes(); var m = /(\?|&)theme=([a-z]+)(#|&|$)/.exec(window.location.href); if (m) EditorSettings.setTheme(themes[m[2]]); else if (Cloud.isRestricted()) { var theme = Cloud.hasPermission('full-editor') ? 'restrictededitor' : Cloud.hasPermission('teacher-editor') ? 'restrictedteacher' : 'restricted'; EditorSettings.setTheme(themes[theme]); } else if (Browser.isRaspberryPiDebian) EditorSettings.setTheme(themes['rpi']); else EditorSettings.setTheme(undefined); } export function init() { if (window && window.location) { Cloud.setPermissions(); setThemeFromSettings(); } } export function initEditorModeAsync() : Promise { if (!!editorMode()) return Promise.as(); var theme = Browser.EditorSettings.currentTheme; if (theme && theme.editorMode) { Browser.EditorSettings.setEditorMode(theme.editorMode, false); return Promise.as(); } return Browser.EditorSettings.showChooseEditorModeAsync(); } export function wallpaper(): string { return localStorage.getItem("editorWallpaper") || ""; } export function setWallpaper(id: string, upload: boolean) { var previous = EditorSettings.wallpaper(); if (previous != id) { if (!id) localStorage.removeItem("editorWallpaper") else localStorage.setItem("editorWallpaper", id); if (upload) uploadWallpaper(); updateWallpaper(); } } function updateWallpaper() { var id = wallpaper(); if (!id) { var theme = EditorSettings.currentTheme if (theme) id = theme.wallpaperArtId; } [elt("hubRoot"), elt("slRoot")].filter(e => !!e).forEach(e => { if (id) { e.style.backgroundImage = Cloud.artCssImg(id); e.style.backgroundRepeat = 'repeat' } else e.style.backgroundImage = ""; }); } function uploadWallpaper() { var m = wallpaper(); if (Cloud.getUserId() && Cloud.isOnline()) { Util.log('updating wallpaper to ' + m); Cloud.postUserSettingsAsync({ wallpaper: m }) .done(() => { HTML.showProgressNotification(lf("wallpaper saved"), true); },(e) => { }); } } export function loadEditorMode(id: string) { initThemes(); if (id === "coder") id = 'classic'; // legacy var mode = editorModes[id] || editorModes['block']; if (mode) Browser.EditorSettings.setEditorMode(mode, false); } export function setEditorMode(mode: Cloud.EditorMode, upload: boolean) { if (Cloud.isRestricted()) return; var previous = localStorage.getItem("editorMode"); if (previous != mode) { localStorage.setItem("editorMode", mode.id); currentEditorMode = mode; if (upload) uploadEditorMode(); TheEditor.refreshMode(); } } var currentEditorMode: Cloud.EditorMode; export function editorMode(): Cloud.EditorMode { initThemes(); if (!currentEditorMode) { currentEditorMode = currentTheme && currentTheme.editorMode ? currentTheme.editorMode : editorModes[localStorage.getItem("editorMode") || ""] || editorModes['block'] TheEditor.refreshMode(); } return currentEditorMode; } export function widgets(): Cloud.EditorWidgets { return editorMode().widgets; } function uploadEditorMode() { var m = localStorage.getItem("editorMode"); if (Cloud.getUserId() && Cloud.isOnline() && m) { Util.log('updating skill level to ' + m); Cloud.postUserSettingsAsync({ editorMode:m }) .done(() => { HTML.showProgressNotification(lf("skill level saved"), true); },(e) => { }); } } export function changeSkillLevelDiv(editor: Editor, tk: Ticks, cls = ""): HTMLElement { if (!widgets().changeSkillLevel) return undefined; return div(cls, HTML.mkLinkButton(lf("Change skill level!"),() => { tick(tk); EditorSettings.showChooseEditorModeAsync().done(() => { editor.refreshMode(); }); })); } export function createChooseSkillLevelElements(click?: () => void): HTMLElement[] { initThemes(); return Util.values(editorModes).map((mode, index) => { var pic = div('pic'); pic.style.background = Cloud.artCssImg(mode.artId, true); pic.style.backgroundSize = "cover"; return div('editor-mode', pic, HTML.mkButton(mode.name,() => { Ticker.rawTick('editorMode' + mode.id); EditorSettings.setEditorMode(mode, true); if (click) click(); }, 'title'), div('descr', mode.descr)); }); } export function showChooseEditorModeAsync(preferredMode : string = undefined): Promise { TipManager.setTip(null) return new Promise((onSuccess, onError, onProgress) => { var m = new ModalDialog(); m.onDismiss = () => onSuccess(undefined); m.add(div('wall-dialog-header', lf("choose your coding skill level"))); m.add(div('wall-dialog-body', lf("We will adapt the editor to your coding skill level. You can change your skill level later in the hub."))); m.add(div('wall-dialog-body center', EditorSettings.createChooseSkillLevelElements(() => m.dismiss()))); m.fullWhite(); m.show(); }); } export var currentTheme: Cloud.ClientTheme; // call themeIntelliProfileAsync() to populate export var currentThemeIntelliProfile: AST.IntelliProfile; export function setTheme(theme: Cloud.ClientTheme) { Util.log('theme: ' + theme); currentTheme = theme; currentThemeIntelliProfile = undefined; currentEditorMode = undefined; updateThemeSettings(); updateWallpaper(); } export function loadThemeIntelliProfileAsync(): Promise { // of IntelliProfile // cache hit if (currentThemeIntelliProfile) return Promise.as(currentThemeIntelliProfile); // should we load anything? if (!currentTheme || !currentTheme.intelliProfileId) return Promise.as(undefined); // try loading profile data var update = ScriptCache.forcedUpdate(currentTheme.intelliProfileId); var p = update ? Promise.as(update.text) : ScriptCache.getScriptAsync(currentTheme.intelliProfileId); return p.then((text: string) => { if (!text) { Util.log('failed to load intelliprofile script'); return undefined; } Util.log('loading intelliprofile for theme'); var app = AST.Parser.parseScript(text); AST.TypeChecker.tcApp(app); currentThemeIntelliProfile = new AST.IntelliProfile(); currentThemeIntelliProfile.allowAllLibraries = true; currentThemeIntelliProfile.loadFrom(app, false); return currentThemeIntelliProfile; }, e => { return Promise.as(undefined) }) } function updateThemeSettings() { var theme = EditorSettings.currentTheme; if (theme) { Browser.noAnimations = !!theme.noAnimations; Browser.lowMemory = !!theme.lowMemory; } else { Browser.noAnimations = false; Browser.lowMemory = false; } } } export interface ScriptTemplate { title: string; id: string; scriptid:string; //tick: Ticks; automatically generated icon: string; description: string; name: string; source: string; section: string; editorMode: number; caps?: string; baseId?: string; baseUserId?: string; requiresLogin?: boolean; editor?: string; updateLibraries?: boolean; } interface ITutorial { title: string; // Represents the progress of the script corresponding to that tutorial header?: Cloud.Header; // The tutorial per se (the terminology in the source code refers to // "topic") topic: HelpTopic; // The app that contains the tutorial app?: AST.App; } export module EditorSoundManager { var sounds : any = {}; export var keyboardSounds = /sounds/.test(window.location.href); export function intellibuttonClick() { if (keyboardSounds) playSound('aonptkth'); } export function tutorialStepNew() { playSound('ncoqavnw', 1); } export function tutorialStepFinished() { playSound('sjmgbwrv', 1); } export function tutorialStart() { playSound('sjmgbwrv', 1); } export function startTutorial() { tutorialStart(); } function playSound(id : string, volume : number = 0.2) { if (Browser.lowMemory) return; var snd = <TDev.RT.Sound>sounds[id]; if(snd) snd.playAsync().done(); else { TDev.RT.Sound.fromArtId(id).done(s => { sounds[id] = s; if (s) { s.set_volume(volume); s.playAsync().done(); } }, e => {}); } } } export module TemplateManager { export var createEditor : ExternalEditor = { company: "", name: lf("Create Code"), description: lf("Create a new script"), origin: "", path: "", id: "create", order: 5, logoUrl: "", }; export var importEditor : ExternalEditor = { company: "", name: lf("Import Code"), description: lf("Import a script from a file"), origin: "", path: "", id: "import", order: 6, logoUrl: "", }; export function chooseEditorAsync() : Promise { // of ScriptTemplate return new Promise((onSuccess, onError, onProgress) => { var m = new ModalDialog(); m.onDismiss = () => onSuccess(undefined); var editors = [{ company: "Microsoft", name: "Touch Develop", description: lf("A beginner friendly editor"), id: "touchdevelop", origin: "", path: "", order: 2, }].concat(getExternalEditors()); editors.sort((a, b) => a.order - b.order); // add import editor editors.push(importEditor) var elts = []; editors.forEach((k : ExternalEditor) => { var res = mkEditorBox(k); res.withClick(() => { m.onDismiss = undefined; m.dismiss(); onSuccess(k.id); }); elts.push(res) }) m.choose(elts, { header: lf("create code with...") }); }); } export function mkEditorBox(k: ExternalEditor): HTMLElement { var icon = div("sdIcon"); var ic = ScriptInfo.editorIcons[k.id]; icon.style.backgroundColor = ic.background; icon.setChildren([HTML.mkImg("svg:" + ic.icon + "," + (ic.color ? ic.color : "white"), '', k.name)]); var nameBlock = div("sdName", k.name); var hd = div("sdNameBlock", nameBlock); var author = div("sdAuthorInner", k.company); var addInfo = div("sdAddInfoInner", k.description); var res = div("sdHeaderOuter", div("sdHeader", icon, div("sdHeaderInner", hd, div("sdAuthor", author), div("sdAddInfoOuter", addInfo)))); res.setAttribute("aria-label", k.name); return res; } export function createScript() { var gotoTemplate = () => { chooseScriptFromTemplateAsync() .done(template => { if (template) { var stub: World.ScriptStub = { editorName: "touchdevelop", scriptName: template.name, scriptText: template.source }; TheHost.openNewScriptAsync(stub).done(); } }); }; if (Cloud.isRestricted()) chooseEditorAsync().done((editor) => { if (!editor) return; if (editor == "import") { ArtUtil.importFileDialog(); return; } var p = Promise.as(""); if (editor == "touchdevelop") p = Promise.as(ScriptCache.forcedUpdate('nmhibf').text); p.then(src => { var stub: World.ScriptStub = { editorName: editor, scriptName: lf("{0} script", TopicInfo.getAwesomeAdj()), scriptText: src, }; return TheHost.openNewScriptAsync(stub); }); p.done(); }) else gotoTemplate(); } export function chooseScriptFromTemplateAsync() : Promise { // of ScriptTemplate TipManager.setTip(null) return new Promise((onSuccess, onError, onProgress) => { var m = new ModalDialog(); var templates = getAvailableTemplates(); var sections = Util.unique(templates, t => t.section).map(t => t.section); var bySection = Util.groupBy(templates, t => t.section); m.onDismiss = () => onSuccess(undefined); var elts = [] sections.forEach(k => { if (k != "templates") elts.push(div("modalSearchHeader section", lf_static(k, true))) bySection[k].forEach((template: ScriptTemplate) => { var icon = div("sdIcon"); icon.style.backgroundColor = ScriptIcons.stableColorFromName(template.title); // missing icons // icon.setChildren([HTML.mkImg("svg:" + template.icon + ",white")]); var nameBlock = div("sdName", lf_static(template.title, true)); var hd = div("sdNameBlock", nameBlock); var addInfo = div("sdAddInfoInner", lf_static(template.description, true)); var res = div("sdHeaderOuter", div("sdHeader", icon, div("sdHeaderInner", hd, div("sdAddInfoOuter", addInfo)))); res.withClick(() => { m.onDismiss = undefined; m.dismiss(); renameScriptFromTemplateAsync(template, false) .done((temp : ScriptTemplate) => onSuccess(temp), e => onSuccess(undefined)); }); elts.push(res) }) }) m.choose(elts, { searchHint: lf("search templates"), header: lf("pick a script template...") }); }); } export function createScriptFromTemplate(template: ScriptTemplate) { renameScriptFromTemplateAsync(template, true) .then((temp : ScriptTemplate) => { if (temp) return TheHost.openNewScriptAsync(<World.ScriptStub>{ editorName: temp.editor || "touchdevelop", scriptText: temp.source, scriptName: temp.name }, temp); else return Promise.as(); }) .done(); } export function expandTemplateName(name: string): string { if (name) name = name.replace(/ADJ/g, () => TopicInfo.getAwesomeAdj()); return name; } function renameScriptFromTemplateAsync(template:ScriptTemplate, headless : boolean) : Promise // of ScriptTemplate { if (!Cloud.getUserId() && template.requiresLogin) { Hub.loginToCreate(template.title, "create:" + template.id) return Promise.as(undefined); } Ticker.rawTick('scriptTemplate_' + template.id); template = JSON.parse(JSON.stringify(template)); // clone template template.name = expandTemplateName(template.name); return TheHost.updateInstalledHeaderCacheAsync() .then(() => new Promise((onSuccess, onError, onProgress) => { template.name = TheHost.newScriptName(template.name); if (headless) { onSuccess(template); return; } var nameBox = HTML.mkTextInput("text", lf("Enter a script name...")); nameBox.value = TheHost.newScriptName(template.name) var m = new ModalDialog(); m.onDismiss = () => onSuccess(undefined); var create = () => { m.onDismiss = undefined; m.dismiss(); template.name = nameBox.value; TheHost.clearAsync(false) .done(() => onSuccess(template), e => onSuccess(undefined)) } // no cancel when using #derive:... route if (template.id == "derive") m.onDismiss = create; m.add([ div("wall-dialog-header", lf_static(template.title, true)), div("wall-dialog-body", lf_static(template.description, true)), div("wall-dialog-line-textbox", nameBox), //div("wall-dialog-body", lf("Tip: pick a good name for your script.")), div("wall-dialog-buttons", HTML.mkButton(lf("create"), create)) ]); m.show(); })); } var _templates: ScriptTemplate[]; function getAvailableTemplates():ScriptTemplate[] { if (!_templates) { _templates = (<any>TDev).scriptTemplates.filter(t => isBeta || !t.betaOnly); _templates.forEach(t => t.source = ScriptCache.forcedUpdate(t.scriptid).text); } // filter by editor mode var currentCap = PlatformCapabilityManager.current(); var theme = EditorSettings.currentTheme; return _templates .filter(template => { if (theme && theme.scriptTemplates && theme.scriptTemplates.indexOf(template.id) < 0) return false; if (!template.caps) return true; else { var plat = AST.App.fromCapabilityList(template.caps.split(/,/)) return (plat & currentCap) == plat; } }) } } export class Hub extends Screen { constructor() { super() this.topContainer = div(null, this.logo, this.meBox, this.notificationBox); this.topBox = div(null, this.topContainer); this.eol = document.createElement("a"); this.eol.className = "eol"; this.eol.innerText = "Touch Develop retirement postponed until June 22, 2019. Sign-in and access to cloud assets to be removed on May 23, 2018. Learn more."; this.eol.href = "https://makecode.com/touchdevelop"; this.theRoot = div("hubRoot", this.bglogo, this.mainContent, this.topBox); } private mainContent = div("hubContent"); private logo = div("hubLogo", SVG.getTopLogo()); private bglogo = div("hubBgLogo", HTML.mkImg("svg:touchDevelop,currentColor", '', '', true)); private meBox = div("hubMe"); private eol: HTMLAnchorElement; private notificationBox = div("notificationBox"); private topBox: HTMLElement; private topContainer: HTMLElement; private theRoot: HTMLElement; private visible = false; private historyMode = false; public vertical = true; private afterSections: () => void = null; public screenId() { return "hub"; } public init() { this.theRoot.style.display = "none"; this.theRoot.id = "hubRoot"; elt("root").appendChild(this.eol); elt("root") .appendChild(this.theRoot); this.logo.withClick(() => { tick(Ticks.hubAbout); Hub.showAbout(); }); if (!Browser.mobileWebkit) this.mainContent.addEventListener("scroll",() => this.paralax()) ArtUtil.setupDragAndDrop(document.body); } public keyDown(e: KeyboardEvent) { var s = Util.keyEventString(e); if (s && !e.ctrlKey && !e.metaKey) { this.hide(); this.browser().initialSearch = s; this.browser().showList("search"); return true; } return false; } private paralax() { if (Browser.noAnimations) return; if (this.vertical) { var dx = -this.mainContent.scrollTop / 10; Util.setTransform(this.bglogo, "translate(0px," + dx + "px)") } else { var dx = -this.mainContent.scrollLeft / 10; Util.setTransform(this.bglogo, "translate(" + dx + "px, 0px)") } } private show() { if (!this.visible && !Cloud.isRestricted()) { this.theRoot.style.display = "block"; this.visible = true; currentScreen = this; setGlobalScript(null); TheEditor.historyMgr.setHash("hub", ""); Host.tryUpdate(); } } public hide() { if (this.visible) { TipManager.setTip(null); this.theRoot.style.display = "none"; this.visible = false; } World.cancelContinuouslySync(); } public applySizes() { this.updateSections(); } public syncDone() { this.updateSections(); World.continuouslySyncAsync(false, () => this.showSectionsCoreAsync(true)).done(); } private browser(): Host { return TheHost; } static legacyTemplateIds: StringMap<string> = { turtle: "firststepswithturtle", bouncingmonster: "monsterslicertutorial", soundboard: "soundboardtutorial", lovemenot: "lovemenottutorial", fallingrocks: "fallingrockstutorial", popper: "bubblepoppertutorial", bubbles: "bouncingbubbleswalkthrough", shaker: "songshakertutorial", tapmania: "tapmaniatutorial", cutestvotingapp: "cutestvotingapptutorial", mapofthings: "mapofthingstutorial", acceleroturtle: "acceleroturtle", turtlestrianglespiral: "turtletrianglespiraltutorial", turtlefractals: "turtlefractalstutorial", turtletree: "turtletreetutorial", drawing: "firststepswithdrawing", pixels: "pixelstutorial", scratchdancingcat: "scratchcattutorial", scratchhideandseek: "hideandseekscratchtutorial", scratchpong: "scratchpongtutorial", quadraticequationsolver: "quadraticequationsolver", turtlesphero: "funwithspheroturtle", makeybeatbox: "makeymakeybeatboxtutorial", esploralevel: "esploraleveltutorial", small: "insanelyshorttutorial", } private followOrContinueTutorial(top: HelpTopic, tutorialMode?: string) { this.tutorialsByUpdateIdAsync() .done(tutorials => { var h: AST.HeaderWithState = tutorials[top.updateKey()] if (!h || h.status == "deleted") { Util.log('follow, not previous script found, starting new'); TopicInfo.followTopic(top, tutorialMode) } else { var st = h.editorState; this.browser().createInstalled(h).edit() } }) } public loadHash(h: string[]) { TipManager.update(); if (h[1] == "logout") { // we may be hosed enough that ModalDialog.ask doesn't work anymore if (window.confirm(lf("Do you really want to sign out?\nAll your script data and any unsynchronized script changes will be lost.")) == true) { TheEditor.logoutAsync(false).done(); return; } } if (h[1] == "signout") { TheEditor.logoutDialog() return } if (h[1] == "migrate") { Login.show("hub", "&u=" + encodeURIComponent(h[2])) return } if (h[1] == "signin") { Login.show(h[2] || (Cloud.isRestricted() ? "list:installed-scripts" : "hub")) return } if (h[1] == 'new') { var id = h[2]; if (Hub.legacyTemplateIds.hasOwnProperty(id)) id = Hub.legacyTemplateIds[id] Util.setHash("follow:" + id, true) return } if (h[1] == 'account-settings') { this.afterSections = () => Hub.accountSettings(); } if (h[1] == 'settings') { this.afterSections = () => TheEditor.popupMenu(); } if (h[1] == "install-run" && /^\w+$/.test(h[2])) { this.browser().clearAsync(true).done(() => { var details = this.browser().getScriptInfoById(h[2]) details.run(); }) return } if ((h[1] == "follow" || h[1] == "follow-tile") && /^\w+$/.test(h[2])) { // temporary fix if (h[2] == 'jumpingbird') h[2] = 'jumpingbirdtutorial'; Util.log('follow: {0}', h[2]); // if specified, force the current editor mode EditorSettings.loadEditorMode(h[3]); this.browser().clearAsync(true) .done(() => { // try finding built-in topic first var bt = HelpTopic.findById(h[2]); if (bt) { Util.log('found built-in topic ' + bt.id); this.followOrContinueTutorial(bt); } else { ProgressOverlay.show(lf("loading tutorial"),() => { TheApiCacheMgr.getAsync(h[2], true) .then((res: JsonIdObject) => { if (res && res.kind == "script" && res.id != (<JsonScript>res).updateid) { Util.log('follow topic updated to ' + (<JsonScript>res).updateid); return TheApiCacheMgr.getAsync((<JsonScript>res).updateid, true); } else return Promise.as(res); }) .done(j => { ProgressOverlay.hide(); if (j && j.kind == "script") { Util.log('following ' + j.id); this.followOrContinueTutorial(HelpTopic.fromJsonScript(j)); } else { Util.log('followed script not found'); Util.setHash(TDev.hubHash); } }, e => { ProgressOverlay.hide(); Util.log('follow route error: {0}, {1}' + h[2], e.message); Util.setHash(TDev.hubHash); }); }); } }); return; } this.showSections(); switch (h[1]) { case "pub": // redirect to list Util.setHash("#list:installed-scripts:pub:" + h[2], true); return; case "create": case "derive": Util.setHash("#list:installed-scripts:create:" + h[2], true); return; default: if (TDev.noHub) Util.setHash("#" + TDev.hubHash, true); break; } } private tileClick(t: HTMLElement, f: () => void) { t.withClick(() => { var p = Util.offsetIn(t, this.theRoot); t.style.left = p.x + "px"; t.style.top = p.y + "px"; t.removeSelf(); this.theRoot.appendChild(t); Util.coreAnim("fadeSlide", 200, this.mainContent,() => { t.removeSelf(); f(); }) }); } private layoutTiles(c: HTMLElement, elements: HTMLElement[], noFnBreak = false) { var margin = 0.3; var maxHeight = 20; var rowWidth = 0; var maxY = 0; var x = 0; var y = 0; c.setChildren(elements); var beforeFirstFnBtn = elements.filter((e) => !(<any>e).fnBtn).peek(); if (elements.some((e) => (<any>e).tutorialBtn)) beforeFirstFnBtn = elements.filter((e) => !(<any>e).tutorialBtn).peek(); if (noFnBreak) beforeFirstFnBtn = null; var heightUnit = (7 + margin) / 2; elements.forEach((t: HTMLElement, i) => { t.style.left = x + "em"; t.style.top = y + "em"; var w = 7; var h = 2; if (/hubTileSize0/.test(t.className)) h = 1; if (/hubTileSize[23]/.test(t.className)) w = 11; if (/hubTileSize3/.test(t.className)) h = 4; h *= heightUnit; rowWidth = Math.max(rowWidth, w); y += h; maxY = Math.max(y, maxY); if (t == beforeFirstFnBtn || y > maxHeight || (elements[i + 1] && (<any>elements[i + 1]).breakBefore)) { y = 0; x += rowWidth + margin; rowWidth = 0; } }); c.style.height = maxY + 0.2 + "em"; } private mkFnBtn(lbl: string, f: () => void, t = Ticks.noEvent, modal = false, size = 1, ovrLbl = null) { var wordLength = Util.wordLength(lbl); var words = lbl.split(/\s+/).length; var elt = div("hubTile hubTileBtn hubTileSize" + size, dirAuto(div("hubTileBtnLabel " + ( size <= 1 && wordLength > 18 ? " hubTileBtnLabelTiny" : size <= 1 && (wordLength > 10) ? " hubTileBtnLabelSmall" : wordLength >= 7 || (words >=3 && wordLength > 4) || (size < 3 && lbl.length > 20) || Util.hasCJKChars(lbl) ? " hubTileBtnLabelMedium" : ""), ovrLbl, lbl))); (<any>elt).fnBtn = 1; var f0 = () => { tick(t); f() }; if (t) elt.id = "btn-" + Ticker.tickName(t) if (modal) elt.withClick(f0); else this.tileClick(elt, f0); return elt; } static loginToCreate(name:string, hash:string) { var m = new ModalDialog(); m.addHTML( Util.fmt(lf("<h3>{0:q} requires sign&nbsp;in</h3>"), name) + "<p class='agree'>" + lf("This tutorial uses cloud data which is shared with other users.") + "</p>" ) m.fullWhite(); m.add(div("wall-dialog-buttons", HTML.mkButton(lf("sign in"), () => { Login.show(hash); }))); m.show(); } public tutorialsByUpdateIdAsync(): Promise // StringMap<AST.HeaderWithState> { return this.browser().getTutorialsStateAsync().then((headers:AST.HeaderWithState[]) => { var res = {} headers.forEach(h => { var id = h.editorState.tutorialUpdateKey if (res.hasOwnProperty(id) && res[id].recentUse > h.recentUse) return; res[id] = h }) return res }) } private headerByTutorialId:Promise; private headerByTutorialIdUpdated:number; public topicTile(templateId:string, topDesc:string):HTMLElement { var tileOuter = div("tutTileOuter tutTileLink") var top = HelpTopic.findById("t:" + templateId) var tile = div("tutTile") tileOuter.setChildren([tile]) tile.appendChildren([ div("tutTileLinkLabel", div("tutTileLinkMore", topDesc), div("tutTileLinkTitle", top ? top.json.name : "[missing] " + templateId)) ]) tile.withClick(() => { Util.setHash("#topic:" + templateId) }) return tileOuter } // From what I understand, finding a tutorial is all but an easy task. // There's a variety of steps involved which I tried to isolate in this // function... // - [headerByTutorialId] is a promise of a map from tutorial id (e.g. // "t:codingjetpackjumper" to the corresponding [Cloud.Header]) // - the result of this promise is considered good for three seconds // only, and is renewed after that by re-assigning a fresh promise // into the variable // - the result of a call to [HelpTopic.findById]... may return a // null-ish value in case the tutorial is not in the cache; if this is // the case, we fetch the corresponding tutorial using [TheApiCacheMgr] // and follow the succession of updates to the tutorial. // - once this is done, we call [finish] // - because we may have found the tutorial we wanted in the process, we // return a new value for [top] private findTutorial(templateId: string, finish: (res: { app: AST.App; headers: StringMap<AST.HeaderWithState> }, top: HelpTopic) => void) { var top = HelpTopic.findById("t:" + templateId) if (!this.headerByTutorialId || Date.now() - this.headerByTutorialIdUpdated > 3000) { this.headerByTutorialId = this.tutorialsByUpdateIdAsync(); this.headerByTutorialIdUpdated = Date.now() } if (top) { Promise.join([Promise.as(null), this.headerByTutorialId]).done(res => finish({ app: res[0], headers: res[1] }, top)); } else { var fetchingId = null var fetchId = id => { // Is the pointer structure of [updateid]'s expected to // loop? I assume that we abort in this case? if (fetchingId == id) return; fetchingId = id; TheApiCacheMgr.getAnd(id, (j:JsonScript) => { if (j.updateid && j.id !== j.updateid && j.updatetime > j.time) fetchId(j.updateid); else { top = HelpTopic.fromJsonScript(j); Promise.join([top.initAsync(), this.headerByTutorialId]).done(res => finish({ app: res[0], headers: res[1] }, top)); } }) } fetchId(templateId); } } // Start a tutorial, with an (optional) header that represents progress, // along with an optional function. private startTutorial(top: HelpTopic, header: Cloud.Header = null) { if (header) { this.browser().createInstalled(header).edit(); } else { TopicInfo.followTopic(top); } } private findImgForTutorial(app: AST.App) { // XXX it seems that this function is actually unused as [app] is // always null?!! if (!app) return null; var findImg = t => app.resources().filter(r => r.getKind() == api.core.Picture && t.test(r.getName()) && Cloud.isArtUrl(r.url))[0]; var img = findImg(/screenshot/) || findImg(/background/); return img; } public tutorialTile(templateId:string, f:(startFrom:Cloud.Header)=>void):HTMLElement { var tileOuter = div("tutTileOuter") var startTutorial = (top : HelpTopic, header: Cloud.Header) => { Util.log("tutorialTile.start: " + templateId) if (f) f(header); this.startTutorial(top, header); }; var finish = (res: { app: AST.App; headers: StringMap<AST.HeaderWithState> }, top: HelpTopic) => { var isHelpTopic = !!top; var tile = div("tutTile") tileOuter.setChildren([tile]) var app:AST.App = res.app var progs = res.headers var titleText = top.json.name.replace(/ (tutorial|walkthrough)$/i, ""); var descText = top.json.description.replace(/ #(docs|tutorials|stepbystep)\b/ig, " ") descText = descText.replace(/\s+\.$/, "") var author = top.fromJson && top.fromJson.userid != "jeiv" ? top.fromJson.username : "Touch Develop"; var titleDiv; tileOuter.appendChildren([ div("tutDesc", titleDiv = div("tutDescFirst", div("tutDescTitle", titleText), div(null, descText)), div("tutAuthor", "by " + author).withClick(() => { if (isHelpTopic) Util.setHash("topic:" + templateId); else Util.setHash("script:" + top.json.id); }) ) ]) var cap = AST.App.fromCapabilityList(top.json.platforms || []) if (cap & ~api.core.currentPlatform) { tileOuter.appendChildren([ div("tutWarning", HTML.mkImg("svg:Warning,currentColor")) ]) } var img = this.findImgForTutorial(app); var imgUrl = img ? img.url : top.json.screenshot; if (imgUrl && !Browser.lowMemory) { var picDiv = tile picDiv.style.backgroundColor = '#eee'; picDiv.style.backgroundImage = HTML.cssImage(imgUrl); picDiv.style.backgroundRepeat = 'no-repeat'; picDiv.style.backgroundPosition = 'center'; picDiv.style.backgroundSize = 'cover'; } else { tile.style.backgroundColor = top.json.iconbackground; var icon = div("tutIcon"); icon.setChildren([HTML.mkImg("svg:" + top.json.icon + ",white")]); tile.appendChildren([icon]) } var continueHeader:Cloud.Header = null var id = top.updateKey() if (progs.hasOwnProperty(id)) { var h:AST.HeaderWithState = progs[id] continueHeader = h var prog = h.editorState var starSpan = span("bold", ((prog.tutorialStep || 0) + 1) + "★"); var ofSteps = prog.tutorialNumSteps ? " of " + (prog.tutorialNumSteps + 1) : "" tile.appendChild(div("tutProgress", ((prog.tutorialStep && (prog.tutorialStep == prog.tutorialNumSteps)) ? div("steps", lf("done!"), div("label", starSpan)) : div("steps", starSpan, ofSteps, div("label", lf("tutorial progress")))), div("restart", HTML.mkButton(lf("start over"), () => startTutorial(top, null))))) } titleDiv.withClick(() => startTutorial(top, continueHeader)) tile.withClick(() => startTutorial(top, continueHeader)) }; this.findTutorial(templateId, finish); return tileOuter } private startTutorialButton(t: Ticks) { var elt = this.mkFnBtn(lf("Tutorials"),() => { this.browser().showList(Cloud.config.tutorialsid + "/scripts", { header: lf("tutorials") }); }, t, true, 3, dirAuto(div("hubTileOver", lf("Create your own apps")))); if (!Browser.lowMemory) { elt.style.backgroundSize = 'contain'; elt.style.backgroundImage = Cloud.artCssImg('zxddkvgm'); elt.style.backgroundRepeat = 'no-repeat'; } elt.className += " tutorialBtn"; return elt } private showTutorialTip() { if (!this.visible) return; if (ModalDialog.currentIsVisible()) { Util.setTimeout(1000, () => this.showTutorialTip()) return; } TipManager.setTip(null) TipManager.setTip({ tick: Ticks.hubFirstTutorial, title: lf("tap there"), description: lf("we'll guide you step by step"), //forceTop: true, }) } private addPageTiles(s: string, c: HTMLElement, items: BrowserPage[]) { var elements: HTMLElement[] = []; if (s == "top" || s == "showcase" || s == "new") { items = items.filter((s) => !(s instanceof ScriptInfo) || (<ScriptInfo>s).willWork()) } var tutorialOffset = 0 function tileSize(k) { k += tutorialOffset var sz = 1; if (k == 0) sz = 3; else if (k == 1) sz = 2; return sz; } var scriptSlots = 0 if (s == "recent" && items.length < 5) { scriptSlots = 5 - items.length if (EditorSettings.widgets().startTutorialButton) { tutorialOffset++; elements.push(this.startTutorialButton(Ticks.hubFirstTutorial)) scriptSlots--; } } items.slice(0, 5).forEach((item, i) => { var sz = tileSize(i); var t = items[i].mkTile(sz); this.tileClick(t, () => { this.hide(); if (s == "recent") this.browser().showList("installed-scripts", { item: item }); else if (s == "myart") this.browser().showList(Cloud.getUserId() ? "myart" : "art", { item: item }); else if (s == "art") this.browser().showList("art", { item: item }); else if (s == "users") this.browser().showList("users", { item: item }); else if (s == "channels") this.browser().showList("channels", { item: item }); else if (s == "showcase") this.browser().showList(Cloud.config.showcaseid + "/scripts", { item: item, header: lf("showcase") }); else if (s == "tutorials") this.browser().showList(Cloud.config.tutorialsid + "/scripts", { item: item, header: lf("tutorials") }); else this.browser().showList(s + "-scripts", { item: item }); }); elements.push(t); }); if (scriptSlots && items.length == 0 && EditorSettings.widgets().startTutorialButton) { Util.setTimeout(1000, () => this.showTutorialTip()) } while (scriptSlots-- > 0) { var oneSlot = this.mkFnBtn(lf("Your script will appear here"),() => { this.showTutorialTip() }, Ticks.hubFirstTutorial, true, tileSize(elements.length - tutorialOffset)); oneSlot.className += " scriptSlot"; elements.push(oneSlot) } var beforeFirstFnBtn = null; var noFnBreak = false; var addFnBtn = (lbl: string, t, f: () =>void , modal = false, size = 1) => { elements.push(this.mkFnBtn(lbl, f, t, modal, size)); } if (s == "recent") { noFnBreak = true; addFnBtn(lf("All my scripts"), Ticks.hubSeeMoreMyScripts, () => { this.hide(); this.browser().showList("installed-scripts") }); elements.peek().appendChild(div("hubTileSearch", HTML.mkImg("svg:search,white"))); addFnBtn(lf("Create Script"), Ticks.hubCreateScript, () => { TemplateManager.createScript(); }, true); if (EditorSettings.widgets().hubScriptUpdates) { var upd = this.browser().headersWithUpdates(); if (upd.length > 0) { var updBtn = this.mkFnBtn(lf("Script Updates"),() => { this.updateScripts() }, Ticks.hubUpdates, true); updBtn.appendChild(div('hubTileCounter', upd.length.toString())); elements.push(updBtn) } } } else if (s == "art" || s == "myart") { noFnBreak = true; while(elements.length < 5) { var oneSlot = this.mkFnBtn(lf("Your art will appear here"), () => { }, Ticks.hubFirstTutorial, true, tileSize(elements.length)); oneSlot.className += " scriptSlot"; elements.push(oneSlot) } addFnBtn(lf("See More"), Ticks.hubSeeMoreArt, () => { this.hide(); this.browser().showList("myart") }); elements.peek().appendChild(div("hubTileSearch", HTML.mkImg("svg:search,white"))); addFnBtn(lf("Upload Picture"), Ticks.hubUploadPicture, () => { ArtUtil.uploadPictureDialogAsync({ finalDialog: true }).done() }, true); addFnBtn(lf("Upload Sound"), Ticks.hubUploadSound, () => { ArtUtil.uploadSoundDialogAsync().done() }, true); } else if (s == "channels") { noFnBreak = true; while (elements.length < 5) { var oneSlot = this.mkFnBtn(lf("Your channel will appear here"),() => { }, Ticks.hubFirstTutorial, true, tileSize(elements.length)); oneSlot.className += " scriptSlot"; elements.push(oneSlot) } addFnBtn(lf("See More"), Ticks.hubSeeMoreLists, () => { this.hide(); this.browser().showList("channels") }); elements.peek().appendChild(div("hubTileSearch", HTML.mkImg("svg:search,white"))); addFnBtn(lf("Create channel"), Ticks.hubCreateList, () => { this.browser().createChannel(); }); elements.peek().appendChild(div("hubTileSearch", HTML.mkImg("svg:list,white"))); } else if (s == "showcase") { addFnBtn(lf("See More"), Ticks.hubSeeMoreShowcase, () => { this.hide(); this.browser().showList(Cloud.config.showcaseid + "/scripts", { header : lf("showcase")}) }); elements.peek().appendChild(div("hubTileSearch", HTML.mkImg("svg:search,white"))); } else if (s == "tutorials") { addFnBtn(lf("See More"), Ticks.hubSeeMoreTutorials, () => { this.hide(); this.browser().showList(Cloud.config.tutorialsid + "/scripts", { header : lf("tutorials")}) }); elements.peek().appendChild(div("hubTileSearch", HTML.mkImg("svg:search,white"))); } else { //if (items.length > 5) // there is almost always more; the list will filter by capabilities, so it may seem short addFnBtn(lf("See More"), s == "new" ? Ticks.hubSeeMoreNewScripts : s == "top" ? Ticks.hubSeeMoreTopScripts : Ticks.hubSeeMoreCloudOther, () => { this.hide(); this.browser().showList(s + "-scripts") }); elements.peek().appendChild(div("hubTileSearch", HTML.mkImg("svg:search,white"))); if (s == "top") { addFnBtn(lf("New Scripts"), Ticks.hubSeeMoreNewScripts, () => { this.hide(); this.browser().showList("new-scripts") }); elements.peek().appendChild(div("hubTileSearch", HTML.mkImg("svg:star,white"))); } } this.layoutTiles(c, elements, noFnBreak); } private updateScripts() { var boxes = this.browser().headersWithUpdates().map((h) => { var c = HTML.mkCheckBox(h.name); (<any>c).scriptGuid = h.guid; HTML.setCheckboxValue(c, true); return c; }) var update = () => { tick(Ticks.hubDoUpdates); var byGuid = {} var forUpdate:Cloud.Header[] = [] this.browser().headersWithUpdates().forEach((h) => { byGuid[h.guid] = h }) boxes.forEach((b) => { if (HTML.getCheckboxValue(b)) { var h = byGuid[(<any>b).scriptGuid]; if (h) { forUpdate.push(h); } } }) ProgressOverlay.lockAndShow(lf("updating your scripts"), () => { var idx = 0; var promises = [] forUpdate.forEach((h) => { promises.push(World.updateAsync(h.guid) .then(() => { ProgressOverlay.setProgress(lf("{0} of {1} done", ++idx, forUpdate.length)) })) }) Promise.join(promises).done(() => { ProgressOverlay.hide(); this.showSections(); }) }) } var m = new ModalDialog(); m.add(div("wall-dialog-header", lf("{0} script{0:s} to update", boxes.length))) if (dbg) m.add(div("wall-dialog-buttons", HTML.mkButton(lf("select all"), () => { boxes.forEach((b) => HTML.setCheckboxValue(b, true) ) }), HTML.mkButton(lf("unselect all"), () => { boxes.forEach((b) => HTML.setCheckboxValue(b, false) ) }))) m.add(HTML.mkModalList(boxes)); m.add(div("wall-dialog-buttons", HTML.mkButton(lf("cancel"), () => m.dismiss()), HTML.mkButton(lf("update them!"), () => { m.dismiss(); update(); }))) m.show(); } private showSectionsCoreAsync(skipSync = false) { return this.browser().clearAsync(skipSync).then(() => { this.updateSections(); if (this.afterSections) { var f = this.afterSections; this.afterSections = null; f(); } }); } private temporaryRequestedSignin = false; private showingTemporarySignin = false; private showTemporaryNotice() { if ((!Storage.temporary || this.showingTemporarySignin) || !EditorSettings.widgets().showTemporaryNotice || ModalDialog.currentIsVisible()) return; // if only and not signed in, request to sign in if (!this.temporaryRequestedSignin && Cloud.isOnline() && Cloud.isAccessTokenExpired()) { this.temporaryRequestedSignin = true; this.showingTemporarySignin = true; var d = new ModalDialog(); d.add(div('wall-dialog-header', lf("Sign in to avoid losing your scripts!"))); d.add(div('wall-dialog-body', lf("Your browser does not allow Touch Develop to store web site data. This usually happens if run in Private Mode (Safari), in InPrivate mode (Internet Explorer) or your security settings prevent data storage."))); d.add(div('wall-dialog-body', lf("When you sign in, Touch Develop will save your scripts in the cloud."))); d.add(div("wall-dialog-buttons", HTML.mkButton(lf("skip this"), () => { this.showingTemporarySignin = false; d.canDismiss = true; d.dismiss(); }), HTML.mkButton(lf("sign in"), () => { this.showingTemporarySignin = false; if (Login.show()) { d.canDismiss = true; d.dismiss(); } }) )); d.fullWhite() d.canDismiss = false; d.show(); } else { if (EditorSettings.widgets().showTemporaryNotice) Storage.showTemporaryWarning(); } } static userPictureChooser(fbButton:boolean, onUpd:()=>void) { var preview = <HTMLImageElement> document.createElement("img"); var placeholder = "https://az31353.vo.msecnd.net/c04/nbpp.png" preview.onerror = () => { if (preview.src != placeholder && Cloud.isOnline()) preview.src = placeholder; }; var error = div("formError"); var msg = div("formHint"); var updatePreview = () => { preview.src = Cloud.getPrivateApiUrl("me/picture?nocache=" + Util.guidGen()) } updatePreview(); var chooser = HTML.mkImageChooser((uri) => { var img = <HTMLImageElement>HTML.mkImg(uri) function onLoad() { var w = img.width; var h = img.height; if (w < 150 || h < 150) { error.setChildren(lf("image too small (we need 150x150px or more)")) return; } // 500px max var f = 500 / Math.max(w, h); if (f > 1) f = 1; var canvas = <HTMLCanvasElement>document.createElement("canvas"); canvas.width = Math.floor(w * f); canvas.height = Math.floor(h * f); var ctx = canvas.getContext("2d"); ctx.drawImage(img, 0, 0, canvas.width, canvas.height); uri = canvas.toDataURL('image/jpeg', 0.85); preview.src = uri; msg.setChildren([]) error.setChildren([]) Cloud.postPrivateApiAsync("me/picture", { content: uri.replace(/^[^,]*,/, ""), contentType: "image/jpeg" }).done(resp => { msg.setChildren(lf("picture changed; it may take a few minutes and a page reload for the changes to show up")); onUpd(); updatePreview(); }, err => { error.setChildren(lf("failed to upload image")); updatePreview(); }) } img.onload = onLoad; }) var widget = div("form-section", div("float-right", preview), div(null, lf("picture")), div(null, chooser), error, msg, HTML.mkButton(lf("remove picture"), () => { Util.httpDeleteAsync(Cloud.getPrivateApiUrl("me/picture")).done(() => { msg.setChildren(lf("picture removed")); updatePreview(); }) }), !fbButton ? null : HTML.mkButton(lf("get from facebook"), () => { Util.httpPostJsonAsync(Cloud.getPrivateApiUrl("me/settings"), { picturelinkedtofacebook: true }).done(() => { msg.setChildren(lf("picture linked to your facebook profile")); updatePreview(); }) }), div("clear")) return widget; } static askToEnableNotifications(finish: () => void = undefined) { if (finish) finish(); } static accountSettings(notificationsOnly: boolean = false, finish: () => void = undefined) { if (Cloud.anonMode(lf("editing user settings"), null, true)) return; var d = new ModalDialog(); var updated = false; if (finish === undefined && !notificationsOnly) finish = () => { if (updated && !Storage.showTemporaryWarning()) Util.setTimeout(500, () => window.location.reload()); }; var dialogBody = div(null) Browser.setInnerHTML(dialogBody, lf("<h3>loading current settings...</h3>")); d.add(dialogBody) var err = div("formError"); var lastDiv; var textEntry = (lbl: any, inp: HTMLElement, ...rest: any[]) => { dialogBody.appendChild(lastDiv = div("form-section", HTML.label("", HTML.span("input-label", lbl), inp, div("formHint", rest)))) return inp; } Util.httpGetJsonAsync(Cloud.getPrivateApiUrl("me/settings")).done((settings) => { Browser.setInnerHTML(dialogBody, "") var nickname, website, twitterhandle, githubuser, minecraftuser, location, area, aboutme, realname, gender, yearofbirth, howfound, programmingknowledge, occupation, email, emailnewsletter, emailfrequency, pushNotifications, school; if (!notificationsOnly) { dialogBody.appendChild(div("formHint", lf("Don't forget to scroll down and tap 'save' when you are done editing!"))); dialogBody.appendChild(div("form-title", lf("public profile"))); nickname = <HTMLInputElement>textEntry(<any[]>[lf("nickname"), HTML.span("errorSq", "*")], HTML.mkTextInput("text", lf("nickname")), lf("A unique display name for your public profile (at least 8 characters)")); website = <HTMLInputElement>textEntry(lf("website"), HTML.mkTextInput("url", lf("website url")), lf("Enter the URL to your personal website (Example: http://www.northwindtraders.com)")) twitterhandle = <HTMLInputElement>textEntry(lf("twitter handle"), HTML.mkTextInput("text", lf("twitter handle")), lf("Your twitter handle, like @touchdevelop.")); githubuser = <HTMLInputElement>textEntry(lf("github user"), HTML.mkTextInput("text", lf("github user")), lf("Your GitHub user.")); minecraftuser = <HTMLInputElement>textEntry(lf("Minecraft user"), HTML.mkTextInput("text", lf("minecraft user")), lf("Your Minecraft user.")); location = <HTMLInputElement>textEntry(lf("location"), HTML.mkTextInput("text", lf("location")), lf("Where in the world are you?")) area = HTML.mkAutoExpandingTextArea() aboutme = textEntry(lf("about you"), area.div, lf("Enter some information about yourself")) dialogBody.appendChild(Hub.userPictureChooser(settings.picturelinkedtofacebook === false, () => { updated = true })) dialogBody.appendChild(div("form-title", lf("private profile"))); realname = <HTMLInputElement>textEntry(lf("real name"), HTML.mkTextInput("text", lf("real name")), lf("Your full name")); gender = <HTMLSelectElement>textEntry(lf("gender"), HTML.mkComboBox([HTML.mkOption("", "")].concat(settings.genderoptions.map(s => HTML.mkOption(s, s, settings.gender == s))))); yearofbirth = <HTMLSelectElement>textEntry(lf("year of birth"), HTML.mkComboBox([HTML.mkOption("0", "")].concat(settings.yearofbirthoptions.map(year => HTML.mkOption(year + "", year + "", settings.yearofbirth == year))))); howfound = <HTMLSelectElement>textEntry(lf("how found"), HTML.mkComboBox([HTML.mkOption("", "")].concat(settings.howfoundoptions.map(s => HTML.mkOption(s, s, settings.howfound == s)))), lf("How did you discover Touch Develop?")); programmingknowledge = <HTMLSelectElement>textEntry(lf("programming knowledge"), HTML.mkComboBox([HTML.mkOption("", "")].concat(settings.programmingknowledgeoptions.map(s => HTML.mkOption(s, s, settings.programmingknowledge == s)))), lf("What is your level of programming knowledge?")); occupation = <HTMLSelectElement>textEntry(lf("occupation"), HTML.mkComboBox([HTML.mkOption("", "")].concat(settings.occupationoptions.map(s => HTML.mkOption(s, s, settings.occupation == s)))), lf("What is your occupation?")); school = <HTMLInputElement>textEntry(lf("school"), HTML.mkTextInput("text", lf("school")), lf("Enter your school affiliation, if any.")); } dialogBody.appendChild(div("form-title", lf("email and push notifications"))); if (!notificationsOnly || World._askEmail || World._askToEnableEmailNewsletter || World._askToEnableEmailNotifications) { email = <HTMLSelectElement>textEntry(lf("email"), HTML.mkTextInput("text", "you@example.com")); if (settings.email && !settings.emailverified) { var emailError = div("formError2"); emailError.setChildren(lf("Your email address has not yet been verified. Please check your inbox.")) dialogBody.appendChild(emailError); } } var emailnewsletterDiv, emailfrequencyDiv, pushNotificationsDiv; var t = settings.emailnewsletter2; if (notificationsOnly && !t) t = "yes"; emailnewsletter = <HTMLSelectElement>textEntry(lf("receive email newsletters"), HTML.mkComboBox([HTML.mkOption("", "")].concat(settings.emailnewsletter2options.map(s => HTML.mkOption(s, s, t == s)))), lf("Do you want to receive informational Touch Develop-related newsletters, e.g. about new features and upcoming events?")); emailnewsletterDiv = lastDiv; var u = settings.emailfrequency; if (notificationsOnly && !u) u = "weekly"; emailfrequency = <HTMLSelectElement>textEntry(lf("receive email notifications"), HTML.mkComboBox([HTML.mkOption("", "")].concat(settings.emailfrequencyoptions.map(s => HTML.mkOption(s, s, u == s)))), lf("Receive email notifications when other people review/take a screenshot of/comment on your scripts, or reply to one of your comments, or when events related to your subscriptions occur.")); emailfrequencyDiv = lastDiv; var v = settings.notifications2; if (Runtime.offerNotifications() && !v) v = "yes"; if (Runtime.offerNotifications() || v) { pushNotifications = <HTMLSelectElement>textEntry(lf("receive push notifications"), HTML.mkComboBox([HTML.mkOption("", "")].concat(settings.notifications2options.map(s => HTML.mkOption(s, s, v == s)))), lf("Receive notifications to your mobile device when other people review / take a screenshot of/comment on your scripts, or reply to one of your comments, or when events related to your subscriptions occur.")); pushNotificationsDiv = lastDiv; } if (notificationsOnly) { emailnewsletterDiv.style.display = "none"; emailfrequencyDiv.style.display = "none"; if (pushNotificationsDiv) pushNotificationsDiv.style.display = "none"; var summary = div("formHint", t == "yes" ? lf("You will get Touch Develop newsletters.") : lf("You will not get Touch Develop newsletters."), "You will get a ", span("emph", u), " email notification digest ", pushNotifications ? <any[]>["and ", span("emph", v == "yes" ? "mobile" : "no"), " push notifications"] : [], " when users engage with your publications or posts. ", span("emph", lf("Change settings..."))); summary.onclick = () => { emailnewsletterDiv.style.display = "block"; emailfrequencyDiv.style.display = "block"; if (pushNotificationsDiv) pushNotificationsDiv.style.display = "block"; summary.style.display = "none"; }; dialogBody.appendChild(summary); } dialogBody.appendChild(div("form-section", "")); // spacing if (!notificationsOnly) { dialogBody.appendChild(div("formHint", lf("Items marked with * are required."), Editor.mkHelpLink("account settings"))); } dialogBody.appendChild(div("formHint", HTML.mkA(null, Cloud.getServiceUrl() + "/privacy", "_blank", lf("Please review our Privacy Statement.")))); var saveBtn: HTMLElement; dialogBody.appendChild(err) var progressBar = HTML.mkProgressBar(); dialogBody.appendChild(div("formRelative", progressBar)); dialogBody.appendChild( div("wall-dialog-buttons", HTML.mkButton(notificationsOnly ? lf("maybe later") : lf("cancel"), () => { d.dismiss() }), saveBtn = HTML.mkButton(lf("save"), () => { var emailnewsletter2Value = emailnewsletter === undefined ? undefined : emailnewsletter.options[emailnewsletter.selectedIndex].value; var emailfrequencyValue = emailfrequency === undefined ? undefined : emailfrequency.options[emailfrequency.selectedIndex].value; if (isBeta && (emailnewsletter2Value == "yes" || emailfrequencyValue && emailfrequencyValue != "never") && email && !email.value) { if (notificationsOnly) { err.className = "formError2"; err.setChildren(lf("Tap 'maybe later' if you don't want to enter an email address now.")); } else { err.setChildren(lf("You need to enter a valid email address if you want to get emails.")); } return; } progressBar.start(); saveBtn.setChildren(lf("saving...")); err.setChildren([]) Cloud.postUserSettingsAsync({ nickname: nickname === undefined ? undefined : nickname.value, website: website === undefined ? undefined : website.value, aboutme: aboutme === undefined ? undefined : area.textarea.value, notifications2: pushNotifications === undefined ? undefined : pushNotifications.options[pushNotifications.selectedIndex].value, realname: realname === undefined ? undefined : realname.value, gender: gender === undefined ? undefined : gender.options[gender.selectedIndex].value, howfound: howfound === undefined ? undefined : howfound.options[howfound.selectedIndex].value, yearofbirth: yearofbirth === undefined ? undefined : parseInt(yearofbirth.options[yearofbirth.selectedIndex].value), programmingknowledge: programmingknowledge === undefined ? undefined : programmingknowledge.options[programmingknowledge.selectedIndex].value, occupation: occupation === undefined ? undefined : occupation.options[occupation.selectedIndex].value, emailnewsletter2: emailnewsletter2Value, emailfrequency: emailfrequencyValue, email: email === undefined ? undefined : email.value, location: location === undefined ? undefined : location.value, twitterhandle: twitterhandle === undefined ? undefined : twitterhandle.value, githubuser: githubuser === undefined ? undefined : githubuser.value, minecraftuser: minecraftuser === undefined ? undefined : minecraftuser.value, school: school ? school.value : undefined, }).done(resp => { progressBar.stop(); saveBtn.setChildren("save"); if (resp.message) err.setChildren(resp.message); else { if (resp.emailverificationsent) d.onDismiss = undefined; updated = true; d.dismiss(); if (resp.emailverificationsent) { var m = new ModalDialog(); m.add([ div("wall-dialog-header", lf("email verification")), div("wall-dialog-body", lf("We sent you a verification email. Please check your inbox."))]) m.addOk(lf("ok")) m.onDismiss = finish; m.show(); } } }, error => { progressBar.stop(); d.onDismiss = undefined; d.dismiss(); ModalDialog.info("error", lf("A network error occurred. Your account settings could not be saved. Are you offline?")).onDismiss = finish; }) }))) if (nickname) nickname.value = settings.nickname || ""; if (website) website.value = settings.website || ""; if (location) location.value = settings.location || ""; if (area) { area.textarea.value = settings.aboutme || ""; area.update() } if (realname) realname.value = settings.realname || ""; if (twitterhandle) twitterhandle.value = settings.twitterhandle || ""; if (githubuser) githubuser.value = settings.githubuser || ""; if (minecraftuser) minecraftuser.value = settings.minecraftuser || ""; if (email) email.value = settings.email || ""; if (school) school.value = settings.school || ""; World._askEmail = World._askToEnableNotifications = World._askToEnableEmailNewsletter = World._askToEnableEmailNotifications = false; }); d.onDismiss = finish; d.fullWhite(); d.addClass("accountSettings"); d.setScroll(); d.show(); } static chooseWallpaper() { if (Cloud.anonMode(lf("choosing wallpaper"), null, true)) return; tick(Ticks.hubChooseWallpaper); var buttons : StringMap<() => void> = {}; buttons[lf("clear")] = () => EditorSettings.setWallpaper("", true); Meta.chooseArtPictureAsync({ title: lf("choose a wallpaper"), initialQuery: "background", buttons: buttons }) .done((a: JsonArt) => { if (a) EditorSettings.setWallpaper(a.id, true); }); } public showSections(skipSync = false) { this.show(); this.showTemporaryNotice(); this.showSectionsCoreAsync(skipSync).done(); } private exportBtn(lbl:string, f:()=>void, t : Ticks):HTMLElement { var elt = div("hubTile hubTileBtn hubTileSize1 hubTileWithLogo tutorialBtn", dirAuto(div("hubTileBtnLabel hubTileBtnLabelSmall", lbl)) /* ,div("hubTileSearch hubTileSearchSmall", HTML.mkImg("svg:shoppingcartalt,white")) FIXME: need icons */ ); elt.withClick(() => { tick(t); f(); }); (<any>elt).tutorialBtn = 1; return elt; } private smallBtn(lbl:string, f:()=>void, t : Ticks, tutorial : boolean = false):HTMLElement { var lbls = lbl.split(/: /) if (lbls[1]) lbl = lbls[1] var elt = div("hubTile hubTileBtn hubTileSize0", dirAuto(div("hubTileBtnLabel " + ( lbl.length > 30 ? " hubTileBtnLabelTiny" : " hubTileBtnLabelSmall"), lbl))); if (lbls[1]) elt.appendChild(div("hubTileCorner", lbls[0])) elt.withClick(() => { tick(t); f(); }); if (tutorial) { (<any>elt).tutorialBtn = 1; elt.className += " tutorialBtn"; } return elt; } static showForum() { Util.setHash("#forum") } static showAbout() { Util.navigateInWindow(Cloud.config.rootUrl); } private createSkillButton(): HTMLElement { var skillTitle = lf("Skill level: {0} ", EditorSettings.editorMode().name); var skill = this.mkFnBtn(skillTitle,() => { EditorSettings.showChooseEditorModeAsync().done(() => this.updateSections(), e => this.updateSections()); }, Ticks.hubChooseSkill, true); skill.className += " exportBtn"; return skill; } private showLearn(container:HTMLElement) { function toTutBtn(btn: HTMLElement) { btn.className += " tutorialBtn"; return btn; } var docsEl: HTMLElement; var ccgaEl: HTMLElement; var whatsNew: HTMLElement; var begginersEl : HTMLElement; //var advancedEl:HTMLElement; var rate, settings: HTMLElement; var searchEl: HTMLElement; var elements = [ this.startTutorialButton(Ticks.hubDocsTutorial), docsEl = toTutBtn(this.mkFnBtn(lf("Docs"), () => { Util.navigateNewWindow(Cloud.config.helpPath); }, Ticks.hubDocs, true, 2)), whatsNew = toTutBtn(this.mkFnBtn(lf("What's new"), () => { Util.navigateNewWindow(Cloud.config.topicPath + "whatsnew"); }, Ticks.hubDocsWhatsNew, true)), begginersEl = toTutBtn(this.mkFnBtn(lf("Getting started"), () => { Util.navigateNewWindow(Cloud.config.topicPath + "gettingstarted"); }, Ticks.hubBeginnersGettingStarted, true)), ccgaEl = toTutBtn(this.mkFnBtn(lf("Teach Creative Coding!"), () => { Util.navigateNewWindow("/ccga"); }, Ticks.hubCCGA, true)), // this button says "Search", which means "search" not "search docs" - "Help" is for that searchEl = this.mkFnBtn(lf("Search everything"), () => { this.hide(); this.browser().showList("search"); }, Ticks.hubChatSearch, false), this.createSkillButton(), settings = this.smallBtn(lf("Settings"), () => { TheEditor.popupMenu() }, Ticks.hubSettings) ]; elements = elements.filter((e) => e != null); searchEl.appendChild(div("hubTileSearch", HTML.mkImg("svg:search,white"))); (<any>searchEl).breakBefore = 1; docsEl.appendChild(div("hubTileSearch", HTML.mkImg("svg:search,white"))); whatsNew.appendChild(div("hubTileSearch hubTileSearchSmall", HTML.mkImg("svg:star,white"))); settings.appendChild(div("hubTileSearch hubTileSearchSmall", HTML.mkImg("svg:settings,white"))); if (rate) rate.className += " exportBtn"; this.layoutTiles(container, elements); } private updateSections() { var widgets = EditorSettings.widgets(); var sects : StringMap<HubSection> = { "recent": { title: lf("my scripts") }, }; if (widgets.hubTutorials) sects["tutorials"] = { title: lf("tutorials") }; if (widgets.hubLearn) sects["learn"] = { title: lf("learn") }; if (widgets.hubChannels) sects["channels"] = { title: lf("channels") }; if (widgets.hubShowcase) sects["showcase"] = { title: lf("showcase") }; if (widgets.hubTopAndNew) sects["top"] = { title: lf("top & new") }; if (widgets.hubMyArt) sects["myart"] = { title: lf("my art") }; if (SizeMgr.portraitMode) { this.vertical = true; } else { // IE has mouse-wheel translation feature that makes horizontal scrolling easier // it also makes sense for tablets in landscape mode if (Browser.isTrident || (Browser.isTouchDevice && !Browser.isDesktop)) this.vertical = false; else // everyone else gets vertical this.vertical = true; } if (/vertical/.test(document.URL)) this.vertical = true; if (/horizontal/.test(document.URL)) this.vertical = false; Util.resetDragToScroll(this.mainContent); if (this.vertical) Util.setupDragToScroll(this.mainContent); else Util.setupHDragToScroll(this.mainContent); var tileWidth = 7.3; var bigTileWidth = 11.3; var sectWidths = { tags: 5*tileWidth, libraries:2*tileWidth, games: 3*tileWidth, misc: 2*tileWidth, 'default': bigTileWidth + 2*tileWidth } var sectWidth = (name:string):number => sectWidths['default'] this.logo.style.display = ""; this.meBox.style.display = ""; // h=26em var topMargin = 5; var sectionHeight = 26; var winHeight = SizeMgr.windowHeight / SizeMgr.topFontSize; var spaceRemaining = winHeight - topMargin; var fontScale = 1.0; var requiredWidth = sectWidth('recent') + (this.vertical ? 2 : 8); var posLeft = SizeMgr.portraitMode ? 1 : 4; var posTop = (spaceRemaining - fontScale*sectionHeight) / 2; this.theRoot.setFlag("vertical", this.vertical); if (this.vertical) { requiredWidth = sectWidth('recent'); requiredWidth = SizeMgr.phoneMode ? requiredWidth + 2 : SizeMgr.portraitMode ? requiredWidth + 2 : requiredWidth * 2 + 4 + 6; fontScale = 1.5; posLeft = SizeMgr.portraitMode ? 1 : 3; posTop = 5; } var posLeft0 = posLeft; var minScale = SizeMgr.windowWidth / (SizeMgr.topFontSize * requiredWidth); if (minScale < fontScale) fontScale = minScale; var divs = [] this.topContainer.removeSelf(); if (this.vertical) { var needHeight = sectionHeight + 3.5; if (spaceRemaining < needHeight*fontScale) fontScale = spaceRemaining/needHeight; divs.push(this.topContainer); } else { if (posTop < 0) { fontScale = spaceRemaining / sectionHeight; posTop = (topMargin - 1) / fontScale; posLeft /= fontScale; } else { posTop += topMargin - 1; } this.topBox.setChildren([this.topContainer]); } this.mainContent.style.fontSize = fontScale + "em"; SizeMgr.hubFontSize = fontScale * SizeMgr.topFontSize; this.mainContent.style.height = SizeMgr.windowHeight + "px"; var lastHeight = 0; Object.keys(sects).forEach((s : string) => { var c = div("hubSectionBody"); var hd : HubSection = sects[s]; var sd = div("hubSection hubSection-" + s, div("hubSectionHeader", spanDirAuto(hd.title)), c); divs.push(sd) this.mainContent.appendChild(sd); sd.style.top = posTop + "em"; sd.style.left = posLeft + "em"; sd.style.width = sectWidth(s) + "em"; lastHeight = posTop; if (this.vertical) { if (!SizeMgr.portraitMode && posLeft == posLeft0) posLeft += sectWidth(s) + 4; else { posTop += sectionHeight + 2; posLeft = posLeft0; } } else posLeft += sectWidth(s) + 4; if (s == "tutorials") this.browser().getLocationList(Cloud.config.tutorialsid + "/scripts/?count=6",(items, cont) => this.addPageTiles(s, c, items)); else if (s == "learn") this.showLearn(c); else if (s == "myart") { if (Cloud.getUserId()) this.browser().getLocationList(Cloud.getUserId() + "/art?count=6", (items, cont) => this.addPageTiles(s, c, items)); else { this.addPageTiles(s, c, []); } } else if (s == "channels") { if (Cloud.getUserId()) this.browser().getLocationList(Cloud.getUserId() + "/channels?count=6",(items, cont) => this.addPageTiles(s, c, items)); else this.addPageTiles(s, c, []); } else if (s == "showcase") { this.browser().getLocationList(Cloud.config.showcaseid + "/scripts/?count=6",(items, cont) => this.addPageTiles(s, c, items)); } else this.browser().getLocationList(s + "-scripts", (items, cont) => this.addPageTiles(s, c, items)); }); if (this.vertical) { var spc = div("hubSectionSpacer"); spc.style.top = (lastHeight + sectionHeight) + "em"; divs.push(spc); } this.mainContent.setChildren(divs); if (Cloud.getUserId()) { var uid = this.browser().getUserInfoById("me", "me"); this.meBox.setChildren([uid.mkSmallBox()]); this.browser().addNotificationCounter(this.notificationBox); } else { var loginBtn = HTML.mkButtonElt("wall-button login-button", SVG.getLoginButton()) this.meBox.setChildren(loginBtn.withClick(() => { Login.show(); })) this.notificationBox.setChildren([]); } } private docTopics:any[]; public importDocs() { var md = new ModalDialog(); var getTopicsAsync = () => Promise.as(TDev.HelpTopic.getAll().map(t => t.json)) var btns = div("wall-dialog-buttons", HTML.mkButton(lf("import"), () => { var m = /^http.*\/docs\/([a-zA-Z0-9]+)$/.exec(inp.value) if (!m) HTML.wrong(inp) else { var tt = HelpTopic.findById(m[1]) if (!tt) { HTML.wrong(inp) } else { md.dismiss() return Util.httpGetTextAsync(Cloud.getPrivateApiUrl("tdtext/" + tt.json.id)) .then(text => { text = text.replace(/{parenttopic:([^{}]+)}/i, (r, pt) => "{parentTopic:td/" + pt + "} {topic:td/" + m[1] + "}") var stub: World.ScriptStub = { editorName: "touchdevelop", scriptName: tt.json.name, scriptText: text, }; return this.browser().openNewScriptAsync(stub) }) .done() } } }), HTML.mkButton(lf("cancel"), () => md.dismiss())) var inp = HTML.mkTextInput("text", "") inp.placeholder = "https://www.touchdevelop.com/docs/..." md.add(div("wall-dialog-header", lf("import docs"))) md.add(div(null, inp)) md.add(btns) md.show() } public showPointers() { var allPointers:JsonPointer[] = [] var fetchAsync = (cont:string) => Cloud.getPrivateApiAsync("pointers?count=50" + cont) .then(res => { allPointers.pushRange(res.items) if (res.continuation) return fetchAsync("&continuation=" + res.continuation) }) var m = ModalDialog.info(lf("page map"), lf("loading..."), "") m.fullWhite() m.setScroll() fetchAsync("") .then(() => { allPointers = allPointers.filter(p => !/^ptr-usercontent-/.test(p.id)) allPointers.sort((a, b) => Util.stringCompare(a.id, b.id)) var html = "" allPointers.forEach(p => { html += Util.fmt("<a href='{0:q}' target='_blank'>{0:q}</a> {1:q} {2:q}<br/>\n", "/" + p.path, p.redirect ? "-> " + p.redirect : "", p.description) }) m.empty() m.addHTML(html).style.fontSize = "0.8em" m.addOk() }) .done() } } }
the_stack
module Kiwi.Renderers { /** * The Blend Mode object for recording and applying GL blend functions on a renderer. * @class GLBlendMode * @constructor * @namespace Kiwi.Renderers * @param gl {WebGLRenderingContext} * @param params {Object} * @return {Kiwi.Renderers.GLBlendMode} * @ since 1.1.0 */ export class GLBlendMode { constructor(gl: WebGLRenderingContext, params: any) { this.gl = gl; this.dirty = true; // Set default parameters this._srcRGB = gl.SRC_ALPHA; this._dstRGB = gl.ONE_MINUS_SRC_ALPHA; this._srcAlpha = gl.ONE; this._dstAlpha = gl.ONE; this._modeRGB = gl.FUNC_ADD; this._modeAlpha = gl.FUNC_ADD; // Process params if(typeof params === "undefined") { params = null; } if(params) this.readConfig(params); } /** * Target WebGL rendering context. * @property gl * @type WebGLRenderingContext * @public */ public gl: WebGLRenderingContext; /** * Dirty flag indicates whether this object has been altered and needs to be processed. * @property dirty * @type boolean * @public */ public dirty: boolean; /** * Source RGB factor used in WebGL blendfunc. * @property _srcRGB * @type number * @private */ private _srcRGB: number; /** * Destination RGB factor used in WebGL blendfunc. * @property _dstRGB * @type number * @private */ private _dstRGB: number; /** * Source alpha factor used in WebGL blendfunc. * @property _srcAlpha * @type number * @private */ private _srcAlpha: number; /** * Destination alpha factor used in WebGL blendfunc. * @property _dstAlpha * @type number * @private */ private _dstAlpha: number; /** * RGB mode used in WebGL blendfunc. * @property _modeRGB * @type number * @private */ private _modeRGB: number; /** * Alpha mode used in WebGL blendfunc. * @property _modeAlpha * @type number * @private */ private _modeAlpha: number; /** * Set a blend mode from a param object. * * This is the main method for configuring blend modes on a renderer. It resolves to a pair of calls to blendEquationSeparate and blendFuncSeparate. The params object should specify compatible terms, namely { srcRGB: a, dstRGB: b, srcAlpha: c, dstAlpha: d, modeRGB: e, modeAlpha: f }. You should set abcdef using either direct calls to a gl context (ie. gl.SRC_ALPHA) or by using predefined strings. * * The predefined string parameters for blendEquationSeparate are: * * FUNC_ADD, FUNC_SUBTRACT, and FUNC_REVERSE_SUBTRACT. * * The predefined string parameters for blendFuncSeparate are: * * ZERO, ONE, SRC_COLOR, ONE_MINUS_SRC_COLOR, DST_COLOR, ONE_MINUS_DST_COLOR, SRC_ALPHA, ONE_MINUS_SRC_ALPHA, DST_ALPHA, ONE_MINUS_DST_ALPHA, SRC_ALPHA_SATURATE, CONSTANT_COLOR, ONE_MINUS_CONSTANT_COLOR, CONSTANT_ALPHA, and ONE_MINUS_CONSTANT_ALPHA. * * @method readConfig * @param params {Object} * @public */ public readConfig(params: any) { if(params.mode !== undefined) this.setMode(params.mode); else { // Expecting a series of constants in "number" type from a GL object, or valid string names corresponding to same. // Sanitise input - do not change unspecified values params.srcRGB = this.makeConstant(params.srcRGB); if(typeof params.srcRGB !== "undefined") this._srcRGB = params.srcRGB; params.dstRGB = this.makeConstant(params.dstRGB); if(typeof params.dstRGB !== "undefined") this._dstRGB = params.dstRGB; params.srcAlpha = this.makeConstant(params.srcAlpha); if(typeof params.srcAlpha !== "undefined") this._srcAlpha = params.srcAlpha; params.dstAlpha = this.makeConstant(params.dstAlpha); if(typeof params.dstAlpha !== "undefined") this._dstAlpha = params.dstAlpha; params.modeRGB = this.makeConstant(params.modeRGB); if(typeof params.modeRGB !== "undefined") this._modeRGB = params.modeRGB; params.modeAlpha = this.makeConstant(params.modeAlpha); if(typeof params.modeAlpha !== "undefined") this._modeAlpha = params.modeAlpha; } this.dirty = true; } /** * Formats a parameter into a GL context-compatible number. This recognises valid constant names, such as "SRC_ALPHA" or "REVERSE_AND_SUBTRACT", with some tolerance for case. It does not check for valid numeric codes. * @method makeConstant * @param code {String} * @return {number} * @private */ private makeConstant(code: any) { // Numbers are assumed to be correct. if(typeof code == "number") return( code ); if(typeof code == "string") code = code.toUpperCase(); switch( code ) { case "ZERO": code = this.gl.ZERO; break; case "ONE": code = this.gl.ONE; break; case "SRC_COLOR": case "SRC_COLOUR": code = this.gl.SRC_COLOR; break; case "ONE_MINUS_SRC_COLOR": case "ONE_MINUS_SRC_COLOUR": code = this.gl.ONE_MINUS_SRC_COLOR; break; case "DST_COLOR": case "DST_COLOUR": code = this.gl.DST_COLOR; break; case "ONE_MINUS_DST_COLOR": case "ONE_MINUS_DST_COLOUR": code = this.gl.ONE_MINUS_DST_COLOR; break; case "SRC_ALPHA": code = this.gl.SRC_ALPHA; break; case "ONE_MINUS_SRC_ALPHA": code = this.gl.ONE_MINUS_SRC_ALPHA; break; case "DST_ALPHA": code = this.gl.DST_ALPHA; break; case "ONE_MINUS_DST_ALPHA": code = this.gl.ONE_MINUS_DST_ALPHA; break; case "SRC_ALPHA_SATURATE": code = this.gl.SRC_ALPHA_SATURATE; break; case "CONSTANT_COLOR": case "CONSTANT_COLOUR": code = this.gl.CONSTANT_COLOR; break; case "ONE_MINUS_CONSTANT_COLOR": case "ONE_MINUS_CONSTANT_COLOUR": code = this.gl.ONE_MINUS_CONSTANT_COLOR; break; case "CONSTANT_ALPHA": code = this.gl.CONSTANT_ALPHA; break; case "ONE_MINUS_CONSTANT_ALPHA": code = this.gl.ONE_MINUS_CONSTANT_ALPHA; break; case "FUNC_ADD": code = this.gl.FUNC_ADD; break; case "FUNC_SUBTRACT": code = this.gl.FUNC_SUBTRACT; break; case "FUNC_REVERSE_SUBTRACT": code = this.gl.FUNC_REVERSE_SUBTRACT; break; default: code = undefined; break; } return( code ); } /** * Sets a blend mode by name. Name is case-tolerant. * * These are shortcuts to setting the blend function parameters manually. A listing of valid modes follows. Each is listed with the parameters modeRGB, modeAlpha, srcRGB, dstRGB, srcAlpha, and dstAlpha, constants used in the gl calls "blendEquationSeparate(modeRGB, modeAlpha)" and "blendFuncSeparate(srcRGB, dstRGB, srcAlpha, dstAlpha". This is very technical, and will probably only be useful if you are developing your own shaders for Kiwi.js. * * "NORMAL" or any non-recognised string will draw as normal, blending colour via alpha. FUNC_ADD, FUNC_ADD, SRC_ALPHA, ONE_MINUS_SRC_ALPHA, ONE, ONE. * * "ADD" or "ADDITIVE" will add pixels to the background, creating a lightening effect. FUNC_ADD, FUNC_ADD, SRC_ALPHA, ONE, ONE, ONE. * * "SUBTRACT" or "SUBTRACTIVE" will subtract pixels from the background, creating an eerie dark effect. FUNC_REVERSE_SUBTRACT, FUNC_ADD, SRC_ALPHA, ONE, ONE, ONE. * * "ERASE" or "ERASER" will erase the game canvas itself, allowing the page background to show through. You can later draw over this erased region. FUNC_REVERSE_SUBTRACT, FUNC_REVERSE_SUBTRACT, SRC_ALPHA, ONE_MINUS_SRC_ALPHA, ONE, ONE. * * "BLACK" or "BLACKEN" will turn all colour black, but preserve alpha. FUNC_ADD, FUNC_ADD, ZERO, ONE_MINUS_SRC_ALPHA, ONE, ONE. * * Blend modes as seen in Adobe Photoshop are not reliably available via WebGL blend modes. Such blend modes require shaders to create. * @method setMode * @param mode {String} * @public */ public setMode(mode: string) { mode = mode.toUpperCase(); switch( mode ) { case "ADDITIVE": case "ADD": this._srcRGB = this.gl.SRC_ALPHA; this._dstRGB = this.gl.ONE; this._srcAlpha = this.gl.ONE; this._dstAlpha = this.gl.ONE; this._modeRGB = this.gl.FUNC_ADD; this._modeAlpha = this.gl.FUNC_ADD; break; case "SUBTRACT": case "SUBTRACTIVE": this._srcRGB = this.gl.SRC_ALPHA; this._dstRGB = this.gl.ONE; this._srcAlpha = this.gl.ONE; this._dstAlpha = this.gl.ONE; this._modeRGB = this.gl.FUNC_REVERSE_SUBTRACT; this._modeAlpha = this.gl.FUNC_ADD; break; case "ERASE": case "ERASER": this._srcRGB = this.gl.SRC_ALPHA; this._dstRGB = this.gl.ONE_MINUS_SRC_ALPHA; this._srcAlpha = this.gl.ONE; this._dstAlpha = this.gl.ONE; this._modeRGB = this.gl.FUNC_REVERSE_SUBTRACT; this._modeAlpha = this.gl.FUNC_REVERSE_SUBTRACT; break; case "BLACK": case "BLACKEN": this._srcRGB = this.gl.ZERO; this._dstRGB = this.gl.ONE_MINUS_SRC_ALPHA; this._srcAlpha = this.gl.ONE; this._dstAlpha = this.gl.ONE; this._modeRGB = this.gl.FUNC_ADD; this._modeAlpha = this.gl.FUNC_ADD; break; case "NORMAL": default: this._srcRGB = this.gl.SRC_ALPHA; this._dstRGB = this.gl.ONE_MINUS_SRC_ALPHA; this._srcAlpha = this.gl.ONE; this._dstAlpha = this.gl.ONE; this._modeRGB = this.gl.FUNC_ADD; this._modeAlpha = this.gl.FUNC_ADD; break; } this.dirty = true; } /** * Compares against another GLBlendMode * @method isIdentical * @return {Boolean} Is this GLBlendMode identical to the passed GLBlendMode? * @param blendMode {Kiwi.Renderers.GLBlendMode} * @public */ public isIdentical(blendMode: GLBlendMode) { if(this == blendMode) return( true ); if( this._srcRGB == blendMode._srcRGB && this._dstRGB == blendMode._dstRGB && this._srcAlpha == blendMode._srcAlpha && this._dstAlpha == blendMode._dstAlpha && this._modeRGB == blendMode._modeRGB && this._modeAlpha == blendMode._modeAlpha) return( true ); return( false ); } /** * Sets the blend mode on the video card * @method apply * @param gl {WebGLRenderingContext} * @public */ public apply(gl: WebGLRenderingContext) { gl.blendEquationSeparate(this._modeRGB, this._modeAlpha); gl.blendFuncSeparate(this._srcRGB, this._dstRGB, this._srcAlpha, this._dstAlpha); // Remove dirty flag this.dirty = false; } } }
the_stack
import { combineReducers } from 'redux' import { AsyncStorage } from 'react-native' import { createMigrate, PersistConfig, MigrationManifest, persistReducer } from 'redux-persist' import { accountReducer } from '../features/account' import { reducer as authReducer } from './AuthRedux' import { contactsReducer } from '../features/contacts' import { updatesReducer } from '../features/updates' import { reducer as groupsReducer } from './GroupsRedux' import { reducer as preferencesReducer } from './PreferencesRedux' import { reducer as photoViewingReducer } from './PhotoViewingRedux' import { reducer as threadsReducer } from './ThreadsRedux' import { reducer as uiReducer } from './UIRedux' import { reducer as startupReducer } from './StartupRedux' import { reducer as deviceLogsReducer } from './DeviceLogsRedux' import { reducer as textileEventsReducer } from './TextileEventsRedux' import { groupReducer } from '../features/group' import { cafesReducer } from '../features/cafes' import { initializationReducer } from '../features/initialization' const migrations: MigrationManifest = { 0: persistedState => { const state = persistedState as any // Migration to add user preferences with option for verboseUi return { ...state, textile: { ...state.textile, preferences: { verboseUi: false }, camera: {} } } }, 1: persistedState => { const state = persistedState as any // Migration to add remaining retry attempts to any persisted image data const updatedItems = state.textile.images.items.map((item: any) => { return { ...item, remainingUploadAttempts: 3 } }) return { ...state, textile: { ...state.textile, images: { ...state.textile.images, items: updatedItems } } } }, 2: persistedState => { const state = persistedState as any const uris = state.textile.camera && state.textile.camera.processed ? state.textile.camera.processed : [] const processed: { [key: string]: 'complete' } = {} for (const uri of uris) { processed[uri] = 'complete' } return { ...state, textile: { ...state.textile, camera: { processed } } } }, 3: persistedState => { const state = persistedState as any return { ...state, textile: { ...state.textile, onboarded: false } } }, 4: persistedState => { const state = persistedState as any // Not migrating devices because we didn't previously have meaningful device data return { ...state, preferences: { onboarded: state.textile.onboarded, verboseUi: state.textile.preferences.verboseUi } } }, 5: persistedState => { const state = persistedState as any return { ...state, cameraRoll: { ...state.cameraRoll, pendingShares: {} } } }, 6: persistedState => { const state = persistedState as any return { ...state, preferences: { ...state.preferences, tourScreens: { wallet: true } } } }, 7: persistedState => { const state = persistedState as any return { ...state, preferences: { ...state.preferences, tourScreens: { ...state.preferences.tourScreens, threads: true } } } }, 8: persistedState => { const state = persistedState as any return { ...state, preferences: { ...state.preferences, tourScreens: { ...state.preferences.tourScreens, feed: true, notifications: true, threads: true }, services: { notifications: { status: false }, photoAddedNotification: { status: true }, receivedInviteNotification: { status: true }, deviceAddedNotification: { status: false }, commentAddedNotification: { status: false }, likeAddedNotification: { status: false }, peerJoinedNotification: { status: false }, peerLeftNotification: { status: false }, backgroundLocation: { status: false } } } } }, 9: persistedState => { const state = persistedState as any return { ...state, preferences: { ...state.preferences, storage: { autoPinPhotos: { status: false }, storeHighRes: { status: false }, deleteDeviceCopy: { status: false }, enablePhotoBackup: { status: false }, enableWalletBackup: { status: false } } } } }, 10: persistedState => { const state = persistedState as any return { ...state, preferences: { ...state.preferences, tourScreens: { ...state.preferences.tourScreens, threadView: true } } } }, 11: persistedState => { const state = persistedState as any return { ...state, preferences: { ...state.preferences, tourScreens: { ...state.preferences.tourScreens, location: true } } } }, 12: persistedState => { const state = persistedState as any return { ...state, preferences: { ...state.preferences, tourScreens: { ...state.preferences.tourScreens, threadsManager: true } } } }, 13: persistedState => { const state = persistedState as any return { ...state, preferences: { ...state.preferences, viewSettings: { selectedWalletTab: 'Photos' } } } }, 14: persistedState => { const state = persistedState as any return { ...state, preferences: { ...state.preferences, onboarded: false } } }, 15: persistedState => { const state = persistedState as any return { ...state, preferences: { ...state.preferences, services: { notifications: { status: state.preferences.services.notifications }, backgroundLocation: { status: state.preferences.services.backgroundLocation }, INVITE_RECEIVED: { status: true }, ACCOUNT_PEER_JOINED: { status: true }, PEER_JOINED: { status: true }, PEER_LEFT: { status: true }, FILES_ADDED: { status: true }, COMMENT_ADDED: { status: true }, LIKE_ADDED: { status: true } } } } }, 16: persistedState => { const state = persistedState as any return { ...state, preferences: { ...state.preferences, viewSettings: { selectedWalletTab: 'Groups' } } } }, 17: persistedState => { const state = persistedState as any return { ...state, account: { ...state.account, initialized: state.preferences.onboarded } } }, 18: persistedState => { const state = persistedState as any return { ...state, group: { ...state.group, addPhoto: state.processingImages.images } } }, 19: persistedState => { // Remove migration key from persisted state const state = persistedState as any const { migration, ...rest } = state return rest }, 20: persistedState => { const state = persistedState as any return { ...state, preferences: { ...state.preferences, verboseUiOptions: { nodeStateOverlay: true, nodeStateNotifications: true, nodeErrorNotifications: true } } } }, 21: persistedState => { const state = persistedState as any const { cameraRoll, group, uploadingImages, photos, ...rest } = state return rest }, 22: persistedState => { // remove cafeSessions persisted data from account key const state = persistedState as any const { cafeSessions, ...rest } = state.account return { ...state, account: rest } }, 23: persistedState => { const state = persistedState as any const { fileSync, ...rest } = state return rest }, 24: persistedState => { const state = persistedState as any const { onboarded, ...restPreferences } = state.preferences const { initialized, ...restAccount } = state.account return { ...state, account: restAccount, preferences: restPreferences, initialization: { onboarding: { completed: onboarded }, instance: { state: 'initialized' } } } } } const persistConfig: PersistConfig = { key: 'primary', storage: AsyncStorage, version: 24, whitelist: [ 'account', 'preferences', 'deviceLogs', 'initialization', 'groups' ], migrate: createMigrate(migrations, { debug: false }), debug: false } const rootReducer = combineReducers({ auth: authReducer, contacts: contactsReducer, updates: updatesReducer, groups: groupsReducer, preferences: preferencesReducer, photoViewing: photoViewingReducer, threads: threadsReducer, ui: uiReducer, startup: startupReducer, deviceLogs: deviceLogsReducer, account: accountReducer, textile: textileEventsReducer, group: groupReducer, cafes: cafesReducer, initialization: initializationReducer }) export default persistReducer(persistConfig, rootReducer)
the_stack
import { ModuleData } from "./moduleTypes"; import { BackgroundpageWindow, ContextMenuCreateProperties, ContextMenuUpdateProperties, ContextMenuOverrides } from './sharedTypes'; declare const browserAPI: browserAPI; declare const BrowserAPI: BrowserAPI; declare const window: BackgroundpageWindow; export namespace Util { export let modules: ModuleData; export function initModule(_modules: ModuleData) { modules = _modules; } /** * JSONfn - javascript (both node.js and browser) plugin to stringify, * parse and clone objects with Functions, Regexp and Date. * * Version - 0.60.00 * Copyright (c) 2012 - 2014 Vadim Kiryukhin * vkiryukhin @ gmail.com * http://www.eslinstructor.net/jsonfn/ * * Licensed under the MIT license ( http://www.opensource.org/licenses/mit-license.php ) */ export const jsonFn = { stringify: (obj: any): string => { return JSON.stringify(obj, (_: string, value: any) => { if (value instanceof Function || typeof value === 'function') { return value.toString(); } if (value instanceof RegExp) { return '_PxEgEr_' + value; } return value; }); }, parse: (str: string, date2Obj?: boolean): any => { const iso8061 = !date2Obj ? false : /^(\d{4})-(\d{2})-(\d{2})T(\d{2}):(\d{2}):(\d{2}(?:\.\d*)?)Z$/; return JSON.parse(str, (_key: string, value: any) => { if (typeof value !== 'string') { return value; } if (value.length < 8) { return value; } const prefix = value.substring(0, 8); if (iso8061 && value.match(iso8061 as RegExp)) { return new Date(value); } if (prefix === 'function') { return new Function(value); } if (prefix === '_PxEgEr_') { return new RegExp(value.slice(8)); } return value; }); } }; function compareObj(firstObj: { [key: string]: any; [key: number]: any; }, secondObj: { [key: string]: any; [key: number]: any; }): boolean { for (let key in firstObj) { if (firstObj.hasOwnProperty(key) && firstObj[key] !== undefined) { if (typeof firstObj[key] === 'object') { if (typeof secondObj[key] !== 'object') { return false; } if (Array.isArray(firstObj[key])) { if (!Array.isArray(secondObj[key])) { return false; } if (!compareArray(firstObj[key], secondObj[key])) { return false; } } else if (!compareObj(firstObj[key], secondObj[key])) { return false; } } else if (firstObj[key] !== secondObj[key]) { return false; } } } return true; } export function compareArray(firstArray: any[], secondArray: any[]): boolean { if (!firstArray && !secondArray) { return false; } else if (!firstArray || !secondArray) { return true; } const firstLength = firstArray.length; if (firstLength !== secondArray.length) { return false; } for (let i = 0; i < firstLength; i++) { if (typeof firstArray[i] === 'object') { if (typeof secondArray[i] !== 'object') { return false; } if (Array.isArray(firstArray[i])) { if (!Array.isArray(secondArray[i])) { return false; } if (!compareArray(firstArray[i], secondArray[i])) { return false; } } else if (!compareObj(firstArray[i], secondArray[i])) { return false; } } else if (firstArray[i] !== secondArray[i]) { return false; } } return true; } export function safe(node: CRM.MenuNode): CRM.SafeMenuNode; export function safe(node: CRM.LinkNode): CRM.SafeLinkNode; export function safe(node: CRM.ScriptNode): CRM.SafeScriptNode; export function safe(node: CRM.DividerNode): CRM.SafeDividerNode; export function safe(node: CRM.StylesheetNode): CRM.SafeStylesheetNode; export function safe(node: CRM.Node): CRM.SafeNode; export function safe(node: CRM.Node): CRM.SafeNode { return modules.crm.crmByIdSafe.get(node.id as CRM.NodeId<CRM.SafeNode>); } const keys: { [secretKey: string]: boolean; } = {}; export function createSecretKey(): number[] { const key: number[] = []; for (let i = 0; i < 25; i++) { key[i] = Math.round(Math.random() * 100); } if (!keys[key.join(',')]) { keys[key.join(',')] = true; return key; } else { return createSecretKey(); } } let _lastNumber: number = Math.round(Math.random() * 100); export function createUniqueNumber(): number { //Make it somewhat unpredictable const addition = Math.round(Math.random() * 100); _lastNumber += addition; return _lastNumber; } export async function generateItemId(): Promise<CRM.GenericNodeId> { modules.globalObject.globals.latestId = modules.globalObject.globals.latestId || 0; modules.globalObject.globals.latestId++; if (modules.storages.settingsStorage) { await modules.Storages.applyChanges({ type: 'optionsPage', settingsChanges: [{ key: 'latestId', oldValue: modules.globalObject.globals.latestId - 1, newValue: modules.globalObject.globals.latestId }] }); } return modules.globalObject.globals.latestId as CRM.GenericNodeId; } export async function getMultipleItemIds(amount: number): Promise<CRM.GenericNodeId[]> { modules.globalObject.globals.latestId = modules.globalObject.globals.latestId || 0; const ids: CRM.GenericNodeId[] = []; for (let i = 0; i < amount; i++) { modules.globalObject.globals.latestId++; ids.push(modules.globalObject.globals.latestId as CRM.GenericNodeId); } if (modules.storages.settingsStorage) { await modules.Storages.applyChanges({ type: 'optionsPage', settingsChanges: [{ key: 'latestId', oldValue: modules.globalObject.globals.latestId - amount, newValue: modules.globalObject.globals.latestId }] }); } return ids; } export function convertFileToDataURI(url: string, callback: (dataURI: string, dataString: string) => void, onError?: () => void) { const xhr: XMLHttpRequest = new window.XMLHttpRequest(); xhr.responseType = 'blob'; xhr.onload = () => { const readerResults: [string, string] = [null, null]; const blobReader = new FileReader(); blobReader.onloadend = () => { readerResults[0] = blobReader.result as string; if (readerResults[1]) { callback(readerResults[0], readerResults[1]); } }; blobReader.readAsDataURL(xhr.response); const textReader = new FileReader(); textReader.onloadend = () => { readerResults[1] = textReader.result as string; if (readerResults[0]) { callback(readerResults[0], readerResults[1]); } }; textReader.readAsText(xhr.response); }; if (onError) { xhr.onerror = onError; } xhr.open('GET', url); xhr.send(); } export function isNewer(newVersion: string, oldVersion: string): boolean { const newSplit = newVersion.split('.'); const oldSplit = oldVersion.split('.'); const longest = Math.max(newSplit.length, oldSplit.length); for (let i = 0; i < longest; i++) { const newNum = ~~newSplit[i]; const oldNum = ~~oldSplit[i]; if (newNum > oldNum) { return true; } else if (newNum < oldNum) { return false; } } return false; } export function pushIntoArray<T, U>(toPush: T, position: number, target: (T|U)[]): (T|U)[] { if (position === target.length) { target[position] = toPush; } else { const length = target.length + 1; let temp1: T | U = target[position]; let temp2: T | U = toPush; for (let i = position; i < length; i++) { target[i] = temp2; temp2 = temp1; temp1 = target[i + 1]; } } return target; } export function flattenCrm(searchScope: CRM.Node[], obj: CRM.Node): void; export function flattenCrm(searchScope: CRM.SafeNode[], obj: CRM.SafeNode): void; export function flattenCrm(searchScope: (CRM.Node[])|(CRM.SafeNode[]), obj: CRM.Node|CRM.SafeNode) { (searchScope as any).push(obj as any); if (obj.type === 'menu' && obj.children) { for (const child of obj.children) { flattenCrm(searchScope, child); } } } export function iterateMap<K, V>(map: Map<K, V>, handler: (key: K, val: V) => void|true) { let breakLoop: boolean = false; map.forEach((value, key) => { if (breakLoop) { return; } if (handler(key, value)) { breakLoop = true; } }); } export function mapToArr<K, V>(map: Map<K, V>): [K, V][] { const pairs: [K,V][] = []; map.forEach((value, key) => { pairs.push([key, value]); }); return pairs; } export async function asyncIterateMap<K, V>(map: Map<K, V>, handler: (key: K, val: V) => Promise<void|true>) { for (const [ key, value ] of mapToArr(map)) { if (await handler(key, value)) { return; } } } export function setMapDefault<K, V>(map: Map<K, V>, key: K, defaultValue: V): boolean { if (!map.has(key)) { map.set(key, defaultValue); return true; } return false; } export function accessPath<B, K1 extends keyof B, K2 extends keyof B[K1], K3 extends keyof B[K1][K2], K4 extends keyof B[K1][K2][K3], K5 extends keyof B[K1][K2][K3][K4]>(base: B, key1: K1): B[K1] | void; export function accessPath<B, K1 extends keyof B, K2 extends keyof B[K1], K3 extends keyof B[K1][K2], K4 extends keyof B[K1][K2][K3], K5 extends keyof B[K1][K2][K3][K4]>(base: B, key1: K1, key2: K2): B[K1][K2] | void; export function accessPath<B, K1 extends keyof B, K2 extends keyof B[K1], K3 extends keyof B[K1][K2], K4 extends keyof B[K1][K2][K3], K5 extends keyof B[K1][K2][K3][K4]>(base: B, key1: K1, key2: K2, key3: K3): B[K1][K2][K3] | void; export function accessPath<B, K1 extends keyof B, K2 extends keyof B[K1], K3 extends keyof B[K1][K2], K4 extends keyof B[K1][K2][K3], K5 extends keyof B[K1][K2][K3][K4]>(base: B, key1: K1, key2: K2, key3: K3, key4: K4): B[K1][K2][K3][K4] | void; export function accessPath<B, K1 extends keyof B, K2 extends keyof B[K1], K3 extends keyof B[K1][K2], K4 extends keyof B[K1][K2][K3], K5 extends keyof B[K1][K2][K3][K4]>(base: B, key1: K1, key2: K2, key3: K3, key4: K4, key5: K5): B[K1][K2][K3][K4][K5] | void; export function accessPath<B, K1 extends keyof B, K2 extends keyof B[K1], K3 extends keyof B[K1][K2], K4 extends keyof B[K1][K2][K3], K5 extends keyof B[K1][K2][K3][K4]>(base: B, key1: K1, key2?: K2, key3?: K3, key4?: K4, key5?: K5): B[K1][K2][K3][K4][K5]| B[K1][K2][K3][K4]|B[K1][K2][K3]|B[K1][K2]|B[K1]|void { const v1 = base[key1]; if (!v1) { return undefined; } if (!key2) { return v1; } const v2 = v1[key2]; if (!v2) { return undefined; } if (!key3) { return v2; } const v3 = v2[key3]; if (!v3) { return undefined; } if (!key4) { return v3; } const v4 = v3[key4]; if (!v4) { return undefined; } if (!key5) { return v4; } const v5 = v4[key5]; if (!v5) { return undefined; } return v5; } export function toMap<V, K extends string|number, O extends CRM.ObjectifiedMap<K, V>>(obj: O): Map<K, V> { return new window.Map<K, V>(Object.getOwnPropertyNames(obj).map((key: any) => { return [key, obj[key as Extract<keyof CRM.ObjectifiedMap<K, V>, string>]]; })); } export function fromMap<K, V>(map: Map<K, V>): CRM.ObjectifiedMap<K, V> { const obj: CRM.ObjectifiedMap<K, V> = {} as any; map.forEach((val, key) => { (obj as any)[key] = val; }); return obj; } export function toArray<T, O extends { [key: string]: T; } = {}>(obj: O): [string, T][] { return Object.getOwnPropertyNames(obj).map((key) => { return [key, obj[key]] as [string, T]; }); } export function removeTab(tabId: TabId) { const nodeStatusses = modules.crmValues.nodeTabStatuses; iterateMap(nodeStatusses, (_, { tabs }) => { if (tabs.has(tabId)) { tabs.delete(tabId); } }); modules.crmValues.tabData.delete(tabId); } export function leftPad(char: string, amount: number): string { let res = ''; for (let i = 0; i < amount; i++) { res += char; } return res; } export function getLastItem<T>(arr: T[]): T { return arr[arr.length - 1]; } export function endsWith(haystack: string, needle: string): boolean { return haystack.split('').reverse().join('') .indexOf(needle.split('').reverse().join('')) === 0; } const _requiredFiles: string[] = []; export async function execFile(path: string, global?: keyof BackgroundpageWindow): Promise<void> { if (_requiredFiles.indexOf(path) > -1) { return; } const el = document.createElement('script'); el.src = browserAPI.runtime.getURL(path); document.body.appendChild(el); _requiredFiles.push(path); if (global) { await window.onExists(global, window); } } export function getScriptNodeJS(script: CRM.ScriptNode|CRM.SafeScriptNode, type: 'background'|'script' = 'script'): string { return type === 'background' ? script.value.backgroundScript : script.value.script; } export async function getScriptNodeScript(script: CRM.ScriptNode|CRM.SafeScriptNode, type: 'background'|'script' = 'script'): Promise<string> { if (script.value.ts && script.value.ts.enabled) { await modules.CRMNodes.TS.compileNode(script); return type === 'background' ? script.value.ts.backgroundScript.compiled : script.value.ts.script.compiled; } return getScriptNodeJS(script, type); } export async function getLibraryCode(library: CRM.InstalledLibrary) { if (library.ts && library.ts.enabled) { if (library.ts.code) { return library.ts.code.compiled; } const { ts } = await (await modules.CRMNodes.TS.compileLibrary(library)); return ts.code.compiled; } return library.code; } const HOUR = 1000 * 60 * 60; let lastFsAccessCheck: number; let fsAccessAllowed: boolean; export function canRunOnUrl(url: string): boolean { if (!url || modules.CRMNodes.Running.urlIsGlobalExcluded(url) || url.indexOf('chrome://') !== -1 || url.indexOf('chrome-extension://') !== -1 || url.indexOf('about://') !== -1 || url.indexOf('chrome-devtools://') !== -1 || url.indexOf('view-source:') !== -1 || (url.indexOf('://chrome.google') > -1 && url.indexOf('/webstore') > -1)) { return false; } if (Date.now() - lastFsAccessCheck > HOUR) { (async () => { fsAccessAllowed = await browserAPI.extension.isAllowedFileSchemeAccess(); lastFsAccessCheck = Date.now(); }); } if (fsAccessAllowed) { return true; } return url.indexOf('file://') === -1; } export async function xhr(url: string, msg: any[] = []): Promise<string> { return new Promise<string>((resolve, reject) => { const xhr: XMLHttpRequest = new window.XMLHttpRequest(); xhr.open('GET', url); xhr.onreadystatechange = () => { if (xhr.readyState === window.XMLHttpRequest.LOADING) { //Close to being done, send message msg.length > 0 && window.infoAsync.apply(console, msg); } if (xhr.readyState === window.XMLHttpRequest.DONE) { if (xhr.status >= 200 && xhr.status < 300) { resolve(xhr.responseText); } else { reject(new Error('Failed XHR')); } } } xhr.send(); }); } export function wait(duration: number): Promise<void> { return new Promise<void>((resolve) => { window.setTimeout(() => { resolve(null); }, duration); }); } //Immediately-invoked promise expresion export function iipe<T>(fn: () => Promise<T>): Promise<T> { return fn(); } export function createArray(length: number): void[] { const arr = []; for (let i = 0; i < length; i++) { arr[i] = undefined; } return arr; } export function promiseChain<T>(initializers: (() => Promise<any>)[]) { return new Promise<T>((resolve) => { if (!initializers[0]) { return resolve(null); } initializers[0]().then(async (result) => { if (initializers[1]) { result = await promiseChain<T>(initializers.slice(1)); } resolve(result); }); }); } export function postMessage(port: { postMessage(message: any): void; }, message: any) { port.postMessage(message); } export function climbTree<T extends { children: T[]; }>(tree: T[], shouldContinue: (item: T) => boolean) { for (const item of tree) { if (shouldContinue(item)) { climbTree(item.children, shouldContinue); } } } export function isThennable(value: any): value is Promise<any> { return value && typeof value === "object" && typeof value.then === "function"; } export async function filter<T>(tree: T[], fn: (item: T) => boolean|Promise<boolean>) { for (let i = 0; i < tree.length; i++) { let res = fn(tree[i]); if (isThennable(res)) { res = await res; } if (!res) { //Remove tree.splice(i, 1); } } } export function crmForEach(crm: CRM.Tree, fn: (node: CRM.Node) => void) { for (const node of crm) { fn(node); if (node.type === 'menu' && node.children) { crmForEach(node.children, fn); } } } export async function crmForEachAsync(crm: CRM.Tree, fn: (node: CRM.Node) => Promise<void>) { for (const node of crm) { await fn(node); if (node.type === 'menu' && node.children) { await crmForEach(node.children, fn); } } } export function getChromeVersion() { if (BrowserAPI.getBrowser() === 'chrome') { return parseInt(navigator.userAgent.match(/Chrom(e|ium)\/([0-9]+)\./)[2], 10); } return 1000; } export function applyContextmenuOverride<T extends ContextMenuCreateProperties|ContextMenuUpdateProperties, U extends ContextMenuOverrides>(base: T, override: U): T { override = override || {} as U; base = base || {} as T; const { type, checked, contentTypes, isVisible, isDisabled, name } = override; if (type) { base.type = type; } if (typeof checked === 'boolean') { base.checked = checked; } if (contentTypes) { base.contexts = contentTypes; } if (typeof isVisible === 'boolean' && BrowserAPI.getBrowser() === 'chrome' && getChromeVersion() >= 62) { (base as any).visible = isVisible; } if (typeof isDisabled === 'boolean') { base.enabled = !isDisabled; } if (name) { base.title = name; } return base; } const locks: Map<LOCK, Promise<void>> = new window.Map(); export const enum LOCK { ROOT_CONTEXTMENU_NODE } export function lock(lockName: LOCK): Promise<() => void> { setMapDefault(locks, lockName, Promise.resolve(null)); const currentLock = locks.get(lockName); let _resolve: () => void; const returnPromise = new Promise<void>((resolve) => { _resolve = () => { resolve(null); } }); const prom = new Promise<void>((resolve) => { returnPromise.then(() => { resolve(null); }); }); locks.set(lockName, prom); return new Promise((resolve) => { currentLock.then(() => { resolve(_resolve); }); }); } }
the_stack
import * as assert from "assert"; import { asyncTest } from "./util"; import * as pulumi from ".."; import * as internals from "../provider/internals"; const gstruct = require("google-protobuf/google/protobuf/struct_pb.js"); class TestResource extends pulumi.CustomResource { constructor(name: string, opts?: pulumi.CustomResourceOptions) { super("test:index:TestResource", name, {}, opts); } } class TestModule implements pulumi.runtime.ResourceModule { construct(name: string, type: string, urn: string): pulumi.Resource { switch (type) { case "test:index:TestResource": return new TestResource(name, { urn }); default: throw new Error(`unknown resource type ${type}`); } } } class TestMocks implements pulumi.runtime.Mocks { call(args: pulumi.runtime.MockCallArgs): Record<string, any> { throw new Error(`unknown function ${args.token}`); } newResource(args: pulumi.runtime.MockResourceArgs): { id: string | undefined; state: Record<string, any> } { return { id: args.name + "_id", state: args.inputs, }; } } describe("provider", () => { it("parses arguments generated by --logflow", asyncTest(async () => { const parsedArgs = internals.parseArgs(["--logtostderr", "-v=9", "--tracing", "127.0.0.1:6007", "127.0.0.1:12345"]); if (parsedArgs !== undefined) { assert.strictEqual("127.0.0.1:12345", parsedArgs.engineAddress); } else { assert.fail("failed to parse"); } })); describe("deserializeInputs", () => { beforeEach(() => { pulumi.runtime._reset(); pulumi.runtime._resetResourcePackages(); pulumi.runtime._resetResourceModules(); }); async function assertOutputEqual( actual: any, value: ((v: any) => Promise<void>) | any, known: boolean, secret: boolean, deps?: pulumi.URN[]) { assert.ok(pulumi.Output.isInstance(actual)); if (typeof value === "function") { await value(await actual.promise()); } else { assert.deepStrictEqual(await actual.promise(), value); } assert.deepStrictEqual(await actual.isKnown, known); assert.deepStrictEqual(await actual.isSecret, secret); const actualDeps = new Set<pulumi.URN>(); const resources = await actual.allResources!(); for (const r of resources) { const urn = await r.urn.promise(); actualDeps.add(urn); } assert.deepStrictEqual(actualDeps, new Set<pulumi.URN>(deps ?? [])); } function createSecret(value: any) { return { [pulumi.runtime.specialSigKey]: pulumi.runtime.specialSecretSig, value, }; } function createResourceRef(urn: pulumi.URN, id?: pulumi.ID) { return { [pulumi.runtime.specialSigKey]: pulumi.runtime.specialResourceSig, urn, ...(id && { id }), }; } function createOutputValue(value?: any, secret?: boolean, dependencies?: pulumi.URN[]) { return { [pulumi.runtime.specialSigKey]: pulumi.runtime.specialOutputValueSig, ...(value !== undefined && { value }), ...(secret && { secret }), ...(dependencies && { dependencies }), }; } const testURN = "urn:pulumi:stack::project::test:index:TestResource::name"; const testID = "name_id"; const tests: { name: string; input: any; deps?: string[]; expected?: any; assert?: (actual: any) => Promise<void>; }[] = [ { name: "unknown", input: pulumi.runtime.unknownValue, deps: ["fakeURN"], assert: async(actual) => { await assertOutputEqual(actual, undefined, false, false, ["fakeURN"]); }, }, { name: "array nested unknown", input: [pulumi.runtime.unknownValue], deps: ["fakeURN"], assert: async(actual) => { await assertOutputEqual(actual, undefined, false, false, ["fakeURN"]); }, }, { name: "object nested unknown", input: { foo: pulumi.runtime.unknownValue }, deps: ["fakeURN"], assert: async(actual) => { await assertOutputEqual(actual, undefined, false, false, ["fakeURN"]); }, }, { name: "unknown output value", input: createOutputValue(undefined, false, ["fakeURN"]), deps: ["fakeURN"], assert: async(actual) => { await assertOutputEqual(actual, undefined, false, false, ["fakeURN"]); }, }, { name: "unknown output value (no deps)", input: createOutputValue(), assert: async(actual) => { await assertOutputEqual(actual, undefined, false, false); }, }, { name: "array nested unknown output value", input: [createOutputValue(undefined, false, ["fakeURN"])], deps: ["fakeURN"], assert: async(actual) => { assert.ok(Array.isArray(actual)); await assertOutputEqual(actual[0], undefined, false, false, ["fakeURN"]); }, }, { name: "array nested unknown output value (no deps)", input: [createOutputValue(undefined, false, ["fakeURN"])], assert: async(actual) => { assert.ok(Array.isArray(actual)); await assertOutputEqual(actual[0], undefined, false, false, ["fakeURN"]); }, }, { name: "object nested unknown output value", input: { foo: createOutputValue(undefined, false, ["fakeURN"]) }, deps: ["fakeURN"], assert: async(actual) => { assert.ok(!pulumi.Output.isInstance(actual)); await assertOutputEqual(actual.foo, undefined, false, false, ["fakeURN"]); }, }, { name: "object nested unknown output value (no deps)", input: { foo: createOutputValue(undefined, false, ["fakeURN"]) }, assert: async(actual) => { assert.ok(!pulumi.Output.isInstance(actual)); await assertOutputEqual(actual.foo, undefined, false, false, ["fakeURN"]); }, }, { name: "string value (no deps)", input: "hi", expected: "hi", }, { name: "array nested string value (no deps)", input: ["hi"], expected: ["hi"], }, { name: "object nested string value (no deps)", input: { foo: "hi" }, expected: { foo: "hi" }, }, { name: "string output value", input: createOutputValue("hi", false, ["fakeURN"]), deps: ["fakeURN"], assert: async (actual) => { await assertOutputEqual(actual, "hi", true, false, ["fakeURN"]); }, }, { name: "string output value (no deps)", input: createOutputValue("hi"), assert: async (actual) => { await assertOutputEqual(actual, "hi", true, false); }, }, { name: "array nested string output value", input: [createOutputValue("hi", false, ["fakeURN"])], deps: ["fakeURN"], assert: async (actual) => { assert.ok(Array.isArray(actual)); await assertOutputEqual(actual[0], "hi", true, false, ["fakeURN"]); }, }, { name: "array nested string output value (no deps)", input: [createOutputValue("hi", false, ["fakeURN"])], assert: async (actual) => { assert.ok(Array.isArray(actual)); await assertOutputEqual(actual[0], "hi", true, false, ["fakeURN"]); }, }, { name: "object nested string output value", input: { foo: createOutputValue("hi", false, ["fakeURN"]) }, deps: ["fakeURN"], assert: async (actual) => { assert.ok(!pulumi.Output.isInstance(actual)); await assertOutputEqual(actual.foo, "hi", true, false, ["fakeURN"]); }, }, { name: "object nested string output value (no deps)", input: { foo: createOutputValue("hi", false, ["fakeURN"]) }, assert: async (actual) => { assert.ok(!pulumi.Output.isInstance(actual)); await assertOutputEqual(actual.foo, "hi", true, false, ["fakeURN"]); }, }, { name: "string secret (no deps)", input: createSecret("shh"), assert: async (actual) => { await assertOutputEqual(actual, "shh", true, true); }, }, { name: "array nested string secret (no deps)", input: [createSecret("shh")], assert: async (actual) => { await assertOutputEqual(actual, ["shh"], true, true); }, }, { name: "object nested string secret (no deps)", input: { foo: createSecret("shh") }, assert: async (actual) => { await assertOutputEqual(actual, { foo: "shh" }, true, true); }, }, { name: "string secret output value (no deps)", input: createOutputValue("shh", true), assert: async (actual) => { await assertOutputEqual(actual, "shh", true, true); }, }, { name: "array nested string secret output value (no deps)", input: [createOutputValue("shh", true)], assert: async (actual) => { assert.ok(Array.isArray(actual)); await assertOutputEqual(actual[0], "shh", true, true); }, }, { name: "object nested string secret output value (no deps)", input: { foo: createOutputValue("shh", true) }, assert: async (actual) => { assert.ok(!pulumi.Output.isInstance(actual)); await assertOutputEqual(actual.foo, "shh", true, true); }, }, { name: "string secret output value", input: createOutputValue("shh", true, ["fakeURN1", "fakeURN2"]), deps: ["fakeURN1", "fakeURN2"], assert: async (actual) => { await assertOutputEqual(actual, "shh", true, true, ["fakeURN1", "fakeURN2"]); }, }, { name: "string secret output value (no deps)", input: createOutputValue("shh", true, ["fakeURN1", "fakeURN2"]), assert: async (actual) => { await assertOutputEqual(actual, "shh", true, true, ["fakeURN1", "fakeURN2"]); }, }, { name: "array nested string secret output value", input: [createOutputValue("shh", true, ["fakeURN1", "fakeURN2"])], deps: ["fakeURN1", "fakeURN2"], assert: async (actual) => { assert.ok(Array.isArray(actual)); await assertOutputEqual(actual[0], "shh", true, true, ["fakeURN1", "fakeURN2"]); }, }, { name: "array nested string secret output value (no deps)", input: [createOutputValue("shh", true, ["fakeURN1", "fakeURN2"])], assert: async (actual) => { assert.ok(Array.isArray(actual)); await assertOutputEqual(actual[0], "shh", true, true, ["fakeURN1", "fakeURN2"]); }, }, { name: "object nested string secret output value", input: { foo: createOutputValue("shh", true, ["fakeURN1", "fakeURN2"]) }, deps: ["fakeURN1", "fakeURN2"], assert: async (actual) => { assert.ok(!pulumi.Output.isInstance(actual)); await assertOutputEqual(actual.foo, "shh", true, true, ["fakeURN1", "fakeURN2"]); }, }, { name: "object nested string secret output value (no deps)", input: { foo: createOutputValue("shh", true, ["fakeURN1", "fakeURN2"]) }, assert: async (actual) => { assert.ok(!pulumi.Output.isInstance(actual)); await assertOutputEqual(actual.foo, "shh", true, true, ["fakeURN1", "fakeURN2"]); }, }, { name: "resource ref", input: createResourceRef(testURN, testID), deps: [testURN], assert: async (actual) => { assert.ok(actual instanceof TestResource); assert.deepStrictEqual(await actual.urn.promise(), testURN); assert.deepStrictEqual(await actual.id.promise(), testID); }, }, { name: "resource ref (no deps)", input: createResourceRef(testURN, testID), assert: async (actual) => { assert.ok(actual instanceof TestResource); assert.deepStrictEqual(await actual.urn.promise(), testURN); assert.deepStrictEqual(await actual.id.promise(), testID); }, }, { name: "array nested resource ref", input: [createResourceRef(testURN, testID)], deps: [testURN], assert: async (actual) => { await assertOutputEqual(actual, async (v: any) => { assert.ok(Array.isArray(v)); assert.ok(v[0] instanceof TestResource); assert.deepStrictEqual(await v[0].urn.promise(), testURN); assert.deepStrictEqual(await v[0].id.promise(), testID); }, true, false, [testURN]); }, }, { name: "array nested resource ref (no deps)", input: [createResourceRef(testURN, testID)], assert: async (actual) => { assert.ok(Array.isArray(actual)); assert.ok(actual[0] instanceof TestResource); assert.deepStrictEqual(await actual[0].urn.promise(), testURN); assert.deepStrictEqual(await actual[0].id.promise(), testID); }, }, { name: "object nested resource ref", input: { foo: createResourceRef(testURN, testID) }, deps: [testURN], assert: async (actual) => { await assertOutputEqual(actual, async (v: any) => { assert.ok(v.foo instanceof TestResource); assert.deepStrictEqual(await v.foo.urn.promise(), testURN); assert.deepStrictEqual(await v.foo.id.promise(), testID); }, true, false, [testURN]); }, }, { name: "object nested resource ref (no deps)", input: { foo: createResourceRef(testURN, testID) }, assert: async (actual) => { assert.ok(actual.foo instanceof TestResource); assert.deepStrictEqual(await actual.foo.urn.promise(), testURN); assert.deepStrictEqual(await actual.foo.id.promise(), testID); }, }, { name: "object nested resource ref and secret", input: { foo: createResourceRef(testURN, testID), bar: createSecret("shh"), }, deps: [testURN], assert: async (actual) => { // Because there's a nested secret, the top-level property is an output. await assertOutputEqual(actual, async (v: any) => { assert.ok(v.foo instanceof TestResource); assert.deepStrictEqual(await v.foo.urn.promise(), testURN); assert.deepStrictEqual(await v.foo.id.promise(), testID); assert.deepStrictEqual(v.bar, "shh"); }, true, true, [testURN]); }, }, { name: "object nested resource ref and secret output value", input: { foo: createResourceRef(testURN, testID), bar: createOutputValue("shh", true), }, deps: [testURN], assert: async (actual) => { assert.ok(!pulumi.Output.isInstance(actual)); assert.ok(actual.foo instanceof TestResource); assert.deepStrictEqual(await actual.foo.urn.promise(), testURN); assert.deepStrictEqual(await actual.foo.id.promise(), testID); await assertOutputEqual(actual.bar, "shh", true, true); }, }, { name: "object nested resource ref and secret output value (no deps)", input: { foo: createResourceRef(testURN, testID), bar: createOutputValue("shh", true), }, assert: async (actual) => { assert.ok(!pulumi.Output.isInstance(actual)); assert.ok(actual.foo instanceof TestResource); assert.deepStrictEqual(await actual.foo.urn.promise(), testURN); assert.deepStrictEqual(await actual.foo.id.promise(), testID); await assertOutputEqual(actual.bar, "shh", true, true); }, }, ]; for (const test of tests) { it(`deserializes '${test.name}' correctly`, asyncTest(async () => { pulumi.runtime.setMocks(new TestMocks(), "project", "stack", true); pulumi.runtime.registerResourceModule("test", "index", new TestModule()); new TestResource("name"); // Create an instance so it can be deserialized. const inputs = { value: test.input }; const inputsStruct = gstruct.Struct.fromJavaScript(inputs); const inputDependencies = { get: () => ({ getUrnsList: () => test.deps, }), }; const result = await pulumi.provider.deserializeInputs(inputsStruct, inputDependencies); const actual = result["value"]; if (test.assert) { await test.assert(actual); } else { assert.deepStrictEqual(actual, test.expected); } })); } }); describe("containsOutputs", () => { const tests: { name: string; input: any; expected: boolean; }[] = [ { name: "Output", input: pulumi.Output.create("hi"), expected: true, }, { name: "[Output]", input: [pulumi.Output.create("hi")], expected: true, }, { name: "{ foo: Output }", input: { foo: pulumi.Output.create("hi") }, expected: true, }, { name: "Resource", input: new pulumi.DependencyResource("fakeURN"), expected: false, }, { name: "[Resource]", input: [new pulumi.DependencyResource("fakeURN")], expected: false, }, { name: "{ foo: Resource }", input: { foo: new pulumi.DependencyResource("fakeURN") }, expected: false, }, ]; for (const test of tests) { it(`${test.name} should return ${test.expected}`, () => { const actual = pulumi.provider.containsOutputs(test.input); assert.strictEqual(actual, test.expected); }); } }); });
the_stack
import { call, delay, CallEffect } from "redux-saga/effects"; import { google, sql_v1beta4 } from "googleapis"; import { log, SECOND, sleep } from "@opstrace/utils"; import { ensureSQLInstanceDoesNotExist, ensureSQLInstanceExists } from "./cloudSQLInstance"; import { ensureSQLDatabaseDoesNotExist, ensureSQLDatabaseExists } from "./cloudSQLDatabase"; import { ensureAddressDoesNotExist, ensureAddressExists } from "./globalAddress"; const snclient = google.servicenetworking("v1"); async function listServiceConnections(network: string): Promise<void> { let result: any; try { result = await snclient.services.connections.list({ parent: "services/servicenetworking.googleapis.com", network: network }); } catch (err: any) { log.warning(`error during services.connections.list: ${err} -- ignore`); return; } const pfx = `services.connections.list for services/servicenetworking.googleapis.com ` + `and network ${network}:`; if (result.data !== undefined) { log.info(`${pfx}\nt${JSON.stringify(result.data, null, 2)}`); return; } log.warning( `${pfx}: unexpected result obj: ${JSON.stringify(result, null, 2)}` ); } /** * Set up VPC Network Peering connection between a service producer's VPC * network and a service consumer's VPC network. * * The VPC peering creation is a long-running operation that is followed with * individual API calls until it either has succeeded or failed. VPC peering * creation is retried upon failure. * * The parameters are explained here: * https://cloud.google.com/service-infrastructure/docs/service-networking/reference/rest/v1/services.connections#Connection * * `network`: The name of service consumer's VPC network that's connected with * service producer network, in the following format: * projects/{project}/global/networks/{network} * * `addressName`: "The name of one IP address range for the service producer", * "of type PEERING." */ async function createServiceConnection({ addressName, network }: { addressName: string; network: string; }) { const logpfx = "set up peering between CloudSQL VPC and Opstrace instance VPC"; let operationName: string; let attempt = 0; const requestparams = { parent: "services/servicenetworking.googleapis.com", requestBody: { network, reservedPeeringRanges: [addressName], service: "servicenetworking.googleapis.com" } }; while (true) { attempt += 1; // log currently known service connections await listServiceConnections(network); // Trigger CREATE log.info(`${logpfx}: create with params: ${requestparams}`); let result: any; try { result = await snclient.services.connections.create(requestparams); } catch (err: any) { log.error(`${logpfx}: error during services.connections.create: ${err}`); } log.debug( `${logpfx}: services.connections.create result: ${JSON.stringify( result, null, 2 )}` ); // filter for success, exit loop in that case if (result !== undefined && result.data !== undefined) { const response = result.data; if (response.name !== undefined) { log.info(`${logpfx}: started log-running operation: ${response.name}`); // This is something like "operations/pssn.p24-948748128269-bfaca658-11c7-4a9c-821b-b1dafc37231f" operationName = response.name; // Enter loop for following operation progress (as of the time of // writing this is not timeout-controlled, and waits forever until // operation either fails permanently or succeeds) if ( await waitForLongrunningOperationToSucceed( snclient, operationName, logpfx ) ) { log.info(`${logpfx}: operation completed, leave peerVpcs()`); return; } else { log.info( `${logpfx}: operation resulted in permanent error, retry creation from scratch` ); } } } // Do not retry too quickly, otherwise we can expect a largish fraction of // requests to be responded to with `Quota exceeded for quota metric // 'Mutate requests'` https://github.com/opstrace/opstrace/issues/1213 const delaySeconds = 45; log.info( `${logpfx}: connections.create(): attempt ${attempt} failed, retry in ${delaySeconds} s` ); await sleep(delaySeconds); } } /** * Follow operation progress. Wait forever until operation either fails * permanently or succeeds. * * https://cloud.google.com/resource-manager/reference/rest/v1/operations/get * https://cloud.google.com/build/docs/api/reference/rest/v1/operations * * @param operationName: a string of the shape * operations/pssn.p24-948748128269-bfaca658-11c7-4a9c-821b-b1dafc37231f * @param logpfx: a log message prefix added to all log messages, for retaining * context * @returns `true` upon success or `false` upon (permanent) failure. */ async function waitForLongrunningOperationToSucceed( apiclient: any, operationName: string, logpfx: string ): Promise<boolean> { log.info(`${logpfx}: follow long-running operation ${operationName}`); let attempt = 0; while (true) { attempt += 1; // Get current operation status let result: any; try { result = await apiclient.operations.get({ name: operationName }); } catch (err: any) { log.error(`${logpfx}: error during operations.get: ${err}`); } log.debug(`${logpfx}: operations.get result: ${result}`); // Filter for success, exit loop in that case. if (result !== undefined && result.data !== undefined) { // Anatomy of an Operations object: // https://cloud.google.com/resource-manager/reference/rest/Shared.Types/Operation // https://cloud.google.com/resource-manager/reference/rest/Shared.Types/Operation#Status const operation = result.data; // Docs about `operation.metadata`: "Service-specific metadata associated // with the operation. It typically contains progress information and // common metadata such as create time" log.info( `${logpfx}: current operation status: ${JSON.stringify( operation, null, 2 )}` ); if (operation.error !== undefined) { // Note(JP): As of docs this means that the error is permanent, i.e. // there is no point in waiting for this operation to succeed anymore. // Instead, we should retry creating that operation -- indicate that by // returning `false`. log.info( `${logpfx}: operation failed: ${JSON.stringify( operation.error, null, 2 )}` ); // Be sure to also log all error detail, documented with "A list of // messages that carry the error details." log.debug( `${logpfx}: operation failed, err.details: ${JSON.stringify( operation.error.details, null, 2 )}` ); return false; } if (operation.response !== undefined) { // "The normal response of the operation in case of success" log.info( `${logpfx}: operation seems to have successfully completed. ` + `Response: ${JSON.stringify(operation.response, null, 2)}` ); if (!operation.done) { // Docs says "if true, the operation is completed, and either error // or response is available.". If that is not true then emit warning, // but don't consider this failed. log.warning( `${logpfx}: operation has response, but 'done' is not true yet` ); } // Indicate operation success to caller. return true; } } const delaySeconds = 10; log.info( `${logpfx}: follow operation ${operationName}: attempt ${attempt} done, retry in ${delaySeconds} s` ); await sleep(delaySeconds); } } export function* ensureCloudSQLExists({ instance, addressName, network, region, ipCidrRange, opstraceClusterName }: { addressName: string; network: string; region: string; ipCidrRange: string; opstraceClusterName: string; instance: sql_v1beta4.Schema$DatabaseInstance; // eslint-disable-next-line @typescript-eslint/no-explicit-any }): Generator<CallEffect, sql_v1beta4.Schema$DatabaseInstance, any> { log.info(`Ensuring CloudSQL exists`); const auth = new google.auth.GoogleAuth({ scopes: [ "https://www.googleapis.com/auth/cloud-platform", "https://www.googleapis.com/auth/sqlservice.admin", "https://www.googleapis.com/auth/compute", "https://www.googleapis.com/auth/compute.readonly", "https://www.googleapis.com/auth/service.management" ] }); google.options({ auth }); log.info(`Ensure Address exists`); yield call(ensureAddressExists, { region, addressName, network, ipCidrRange }); log.info( `Peering cluster VPC with CloudSQL services VPC: ${JSON.stringify( { network, addressName }, null, 2 )}` ); yield call(createServiceConnection, { network, addressName }); // for better insight and debugging, on the hunt for dangling resources. yield call(listServiceConnections, network); let attemptNumber = 0; const sqlInstanceCreationDeadline = Date.now() + 15 * 60 * SECOND; log.info(`Ensure SQLInstance exists`); while (sqlInstanceCreationDeadline > Date.now()) { log.info(`Attempt ${attemptNumber++} to create SQLInstance`); yield delay(15 * SECOND); try { const existingInstance: sql_v1beta4.Schema$DatabaseInstance = yield call( ensureSQLInstanceExists, { instance, opstraceClusterName } ); if (!existingInstance.name) { throw Error("SQLInstance did not return a name"); } log.info(`Ensure SQLDatabase exists`); yield call(ensureSQLDatabaseExists, { opstraceClusterName }); return existingInstance; } catch (err: any) { log.debug("Creating SQLInstance failed, retrying: %s", err); } } throw Error( `SQLInstance creation deadline hit after ${attemptNumber} attempts` ); } export function* ensureCloudSQLDoesNotExist({ opstraceClusterName, addressName }: { opstraceClusterName: string; addressName: string; }): Generator<CallEffect, void, unknown> { const auth = new google.auth.GoogleAuth({ scopes: [ "https://www.googleapis.com/auth/cloud-platform", "https://www.googleapis.com/auth/sqlservice.admin", "https://www.googleapis.com/auth/compute", "https://www.googleapis.com/auth/compute.readonly", "https://www.googleapis.com/auth/service.management" ] }); google.options({ auth }); log.info(`Ensure SQLDatabase deletion`); yield call(ensureSQLDatabaseDoesNotExist, opstraceClusterName); log.info(`Ensure SQLInstance deletion`); yield call(ensureSQLInstanceDoesNotExist, opstraceClusterName); log.info(`Ensure Address deletion`); yield call(ensureAddressDoesNotExist, { addressName }); }
the_stack
import { TimelineSelectionMode, TimelineKeyframe, TimelineRow, TimelineModel, Timeline, TimelineElementType, TimelineElement, TimelineOptions, TimelineRowStyle, TimelineElementDragState, TimelineKeyframeStyle, } from './../lib/animation-timeline'; describe('Timeline', function () { describe('_findDraggable', function () { it('Keyframe should be selected', function () { const timeline = new Timeline(); const elements = [ { type: TimelineElementType.Group, val: 5, } as TimelineElement, { type: TimelineElementType.Keyframe, val: 5, } as TimelineElement, ]; const element = timeline._findDraggable(elements, 5); if (!element) { throw new Error('element cannot be empty'); } chai.expect(element.type).equal(TimelineElementType.Keyframe, TimelineElementType.Keyframe + ' should be selected'); }); it('Timeline should be selected', function () { const timeline = new Timeline(); const elements = [ { type: TimelineElementType.Timeline, val: 5, } as TimelineElement, { type: TimelineElementType.Group, val: 5, } as TimelineElement, ]; const element = timeline._findDraggable(elements, 5); if (!element) { throw new Error('element cannot be empty'); } chai.expect(element.type).equal(TimelineElementType.Timeline, TimelineElementType.Timeline + ' should be selected'); }); it('Timeline should taken first', function () { const timeline = new Timeline(); const elements = [ { type: TimelineElementType.Timeline, val: 5, } as TimelineElement, { type: TimelineElementType.Keyframe, val: 4, }, { type: TimelineElementType.Keyframe, val: 5, } as TimelineElement, { type: TimelineElementType.Group, val: 5, } as TimelineElement, ]; const element = timeline._findDraggable(elements, 5); if (!element) { throw new Error('element cannot be empty'); } chai.expect(element.type).equal(TimelineElementType.Timeline, TimelineElementType.Timeline + ' should be selected'); // Keyframe with value 5 should be selected chai.expect(element.val).equal(5); }); it('Group should be selected', function () { const timeline = new Timeline(); const elements: Array<TimelineElement> = [ { type: TimelineElementType.Group, val: 5, } as TimelineElement, ]; const element = timeline._findDraggable(elements, 5); if (!element) { throw new Error('element cannot be empty'); } chai.expect(element.type).equal(TimelineElementType.Group, TimelineElementType.Group + ' should be selected'); }); it('closest keyframe should be returned', function () { const timeline = new Timeline(); const elements = [ { type: TimelineElementType.Keyframe, val: 0, } as TimelineElement, { type: TimelineElementType.Keyframe, val: 4, } as TimelineElement, { type: TimelineElementType.Keyframe, val: 9, } as TimelineElement, ]; const element = timeline._findDraggable(elements, 5); chai.expect(element.val).equal(elements[1].val); }); it('Keyframes are not draggable by global settings', function () { const timeline = new Timeline(); const elements: Array<TimelineElement> = [ { type: TimelineElementType.Keyframe, val: 4, }, { type: TimelineElementType.Keyframe, val: 5, } as TimelineElement, { type: TimelineElementType.Group, val: 5, } as TimelineElement, ]; // Apply global options:: timeline._options = { rowsStyle: { keyframesStyle: { draggable: false, } as TimelineKeyframeStyle, } as TimelineRowStyle, } as TimelineOptions; const element = timeline._findDraggable(elements, 5); chai.expect(element.type).equal(TimelineElementType.Group, 'Group should be selected'); }); it('Keyframes are not draggable by row settings', function () { const timeline = new Timeline(); const elements: Array<TimelineElement> = [ { type: TimelineElementType.Keyframe, val: 4, row: { keyframesStyle: { draggable: false, } as TimelineRowStyle, } as TimelineRow, }, { type: TimelineElementType.Keyframe, val: 5, row: { keyframesStyle: { draggable: true, } as TimelineRowStyle, } as TimelineRow, } as TimelineElement, ]; // Apply global options:: const element = timeline._findDraggable(elements, 4); // Keyframe with value 5 should be selected as draggable chai.expect(element.val).equal(5); }); it('Keyframes are draggable', function () { const timeline = new Timeline(); const elements: Array<TimelineElement> = [ { type: TimelineElementType.Keyframe, val: 4, keyframe: { val: 0, } as TimelineKeyframe, row: { keyframesStyle: { draggable: false, } as TimelineRowStyle, } as TimelineRow, } as TimelineElement, { type: TimelineElementType.Keyframe, val: 5, keyframe: { draggable: true, } as TimelineKeyframe, row: { keyframesStyle: { keyframesStyle: {} as TimelineKeyframeStyle, } as TimelineRowStyle, } as TimelineRow, } as TimelineElement, ]; // Apply global options:: const element = timeline._findDraggable(elements, 4); // Keyframe with value 5 should be selected as draggable chai.expect(element.val).equal(5); }); }); describe('select', function () { const model: TimelineModel = { rows: [ { val: 0, keyframes: [{ val: 0 }, { val: 0 }] } as TimelineRow, { val: 0, keyframes: [{ val: 0 }, { val: 0 }, { val: 0 }] } as TimelineRow, { val: 0, keyframes: [{ val: 0 }, { val: 0 }] } as TimelineRow, { val: 0, keyframes: [{ val: 0 }] } as TimelineRow, ] as Array<TimelineRow>, } as TimelineModel; it('Select all', function () { const timeline = new Timeline(); timeline._model = model; const element = timeline.selectAllKeyframes(); chai.expect(element.selectionChanged).equal(true); let changed = 0; model.rows.forEach((row: TimelineRow) => { row.keyframes.forEach((keyframe: TimelineKeyframe) => { chai.expect(keyframe.selected).equal(true); changed++; }); }); chai.expect(element.selected.length).equal(changed); }); it('Select all selectable', function () { const timeline = new Timeline(); timeline._model = model; const element = timeline.getAllKeyframes(); let changed = 0; let selectable = 0; model.rows.forEach((row: TimelineRow) => { row.keyframes.forEach((keyframe: TimelineKeyframe) => { keyframe.selected = false; keyframe.selectable = changed % 2 === 0; if (keyframe.selectable) { selectable++; } changed++; }); }); const selectionResults = timeline.select(element); chai.expect(selectionResults.changed.length).equal(selectable); chai.expect(selectionResults.selected.length).equal(selectable); }); it('Deselect all', function () { const timeline = new Timeline(); timeline._model = model; model.rows.forEach((row: TimelineRow) => { row.keyframes.forEach((keyframe: TimelineKeyframe) => { keyframe.selectable = true; keyframe.selected = true; }); }); // deselect all const element = timeline.deselectAll(); chai.expect(element.selectionChanged).equal(true); chai.expect(element.selected.length).equal(0); model.rows.forEach((row: TimelineRow) => { row.keyframes.forEach((keyframe: TimelineKeyframe) => { chai.expect(keyframe.selected).equal(false); }); }); }); it('Select one and deselect other all', function () { const timeline = new Timeline(); timeline._model = model; let expectedChanged = 0; // Select all model.rows.forEach((row: TimelineRow) => { row.keyframes.forEach((keyframe: TimelineKeyframe) => { keyframe.selectable = true; keyframe.selected = true; expectedChanged++; }); }); // select one will deselect other const toSelect = model.rows[1].keyframes[0]; const element = timeline.select(toSelect); chai.expect(element.selectionChanged).equal(true); chai.expect(element.selected.length).equal(1); chai.expect(element.changed.length).equal(expectedChanged - 1); model.rows.forEach((row: TimelineRow) => { row.keyframes.forEach((keyframe: TimelineKeyframe) => { if (toSelect == keyframe) { chai.expect(keyframe.selected).equal(true); } else { chai.expect(keyframe.selected).equal(false); } }); }); }); it('Revert selection (Toggle)', function () { const timeline = new Timeline(); timeline._model = model; let totalKeyframes = 0; // Select all model.rows.forEach((row: TimelineRow) => { row.keyframes.forEach((keyframe: TimelineKeyframe) => { keyframe.selectable = true; keyframe.selected = true; totalKeyframes++; }); }); // toggle selection const toSelect = model.rows[1].keyframes[0]; // item is selected, should be reverted const element = timeline.select(toSelect, TimelineSelectionMode.Revert); chai.expect(element.selectionChanged).equal(true); chai.expect(element.selected.length).equal(totalKeyframes - 1); chai.expect(element.changed.length).equal(1); model.rows.forEach((row: TimelineRow) => { row.keyframes.forEach((keyframe: TimelineKeyframe) => { if (toSelect == keyframe) { chai.expect(keyframe.selected).equal(false); } else { chai.expect(keyframe.selected).equal(true); } }); }); }); it('Select full row', function () { const timeline = new Timeline(); timeline._model = model; // Deselect all model.rows.forEach((row: TimelineRow) => { row.keyframes.forEach((keyframe: TimelineKeyframe) => { keyframe.selectable = true; keyframe.selected = false; }); }); // select one will deselect other const rowToSelect = model.rows[1]; const element = timeline.select(rowToSelect.keyframes); chai.expect(element.selectionChanged).equal(true); chai.expect(element.selected.length).equal(rowToSelect.keyframes.length); chai.expect(element.changed.length).equal(3); model.rows.forEach((row: TimelineRow) => { if (rowToSelect === row) { rowToSelect.keyframes.forEach((keyframe: TimelineKeyframe) => { chai.expect(keyframe.selected).equal(true); }); } else { row.keyframes.forEach((keyframe: TimelineKeyframe) => { chai.expect(keyframe.selected).equal(false); }); } }); }); it('Append select', function () { const timeline = new Timeline(); timeline._model = model; // Deselect all model.rows.forEach((row: TimelineRow) => { row.keyframes.forEach((keyframe: TimelineKeyframe) => { keyframe.selected = false; }); }); // select one row (array of the keyframes) const rowToSelect = model.rows[1]; let results = timeline.select(rowToSelect.keyframes); chai.expect(results.selectionChanged).equal(true); chai.expect(results.selected.length).equal(rowToSelect.keyframes.length); chai.expect(results.changed.length).equal(rowToSelect.keyframes.length); // (array of the keyframes) const rowToSelect2 = model.rows[2]; results = timeline.select(rowToSelect2.keyframes, TimelineSelectionMode.Append); chai.expect(results.selectionChanged).equal(true); chai.expect(results.selected.length).equal(rowToSelect.keyframes.length + rowToSelect2.keyframes.length); chai.expect(results.changed.length).equal(rowToSelect2.keyframes.length); model.rows.forEach((row: TimelineRow) => { if (rowToSelect === row || rowToSelect2 === row) { rowToSelect.keyframes.forEach((keyframe: TimelineKeyframe) => { chai.expect(keyframe.selected).equal(true); }); } else { row.keyframes.forEach((keyframe: TimelineKeyframe) => { chai.expect(keyframe.selected).equal(false); }); } }); }); }); describe('Coordinates', function () { it('Coordinates', function () { const timeline = new Timeline(); timeline._setOptions({ stepVal: 100, stepPx: 50, zoom: 1, } as TimelineOptions); chai.expect(timeline.valToPx(0)).equal(0); chai.expect(timeline.valToPx(100)).equal(50); chai.expect(timeline.valToPx(200)).equal(100); chai.expect(timeline.pxToVal(0)).equal(0); chai.expect(timeline.pxToVal(50)).equal(100); chai.expect(timeline.pxToVal(100)).equal(200); }); it('Coordinates. min is negative', function () { const timeline = new Timeline(); timeline._setOptions({ stepVal: 100, stepPx: 50, min: -100, zoom: 1, } as TimelineOptions); chai.expect(timeline.valToPx(-100)).equal(0); chai.expect(timeline.valToPx(-50)).equal(25); chai.expect(timeline.valToPx(0)).equal(50); chai.expect(timeline.valToPx(50)).equal(75); chai.expect(timeline.valToPx(100)).equal(100); chai.expect(timeline.pxToVal(0)).equal(-100); chai.expect(timeline.pxToVal(25)).equal(-50); chai.expect(timeline.pxToVal(50)).equal(0); chai.expect(timeline.pxToVal(75)).equal(50); chai.expect(timeline.pxToVal(100)).equal(100); }); it('Coordinates. min is positive', function () { const timeline = new Timeline(); timeline._setOptions({ stepVal: 100, stepPx: 50, min: 100, zoom: 1, } as TimelineOptions); chai.expect(timeline.valToPx(100)).equal(0); chai.expect(timeline.valToPx(150)).equal(25); chai.expect(timeline.pxToVal(0)).equal(100); chai.expect(timeline.pxToVal(25)).equal(150); }); it('Zoom is respected', function () { const timeline = new Timeline(); timeline._setOptions({ stepVal: 100, stepPx: 50, zoom: 1, } as TimelineOptions); chai.expect(timeline.valToPx(0)).equal(0); chai.expect(timeline.valToPx(100)).equal(50); chai.expect(timeline.valToPx(200)).equal(100); timeline._setZoom(2); chai.expect(timeline.valToPx(0)).equal(0); chai.expect(timeline.valToPx(100)).equal(25); chai.expect(timeline.valToPx(200)).equal(50); chai.expect(timeline.pxToVal(0)).equal(0); chai.expect(timeline.pxToVal(25)).equal(100); chai.expect(timeline.pxToVal(50)).equal(200); }); }); describe('Snapping', function () { it('Snapping', function () { const timeline = new Timeline(); timeline._setOptions({ stepVal: 100, stepPx: 50, snapStep: 25, zoom: 1, } as TimelineOptions); chai.expect(timeline.snapVal(0)).equal(0); chai.expect(timeline.snapVal(10)).equal(0); chai.expect(timeline.snapVal(26)).equal(25); chai.expect(timeline.snapVal(48)).equal(50); chai.expect(timeline.snapVal(58)).equal(50); }); it('Snapping. min is defined', function () { const timeline = new Timeline(); timeline._setOptions({ stepVal: 100, stepPx: 50, snapStep: 25, min: 5, zoom: 1, } as TimelineOptions); chai.expect(timeline.snapVal(0)).equal(5); chai.expect(timeline.snapVal(10)).equal(5); chai.expect(timeline.snapVal(26)).equal(30); chai.expect(timeline.snapVal(48)).equal(55); chai.expect(timeline.snapVal(58)).equal(55); // Don't overlap the limit. chai.expect(timeline.snapVal(-100)).equal(5); }); it('Snapping. negative min is defined', function () { const timeline = new Timeline(); timeline._setOptions({ stepVal: 100, stepPx: 50, snapStep: 25, min: -55, zoom: 1, } as TimelineOptions); chai.expect(timeline.snapVal(0)).equal(-5); chai.expect(timeline.snapVal(10)).equal(-5); chai.expect(timeline.snapVal(26)).equal(20); chai.expect(timeline.snapVal(48)).equal(45); chai.expect(timeline.snapVal(58)).equal(45); chai.expect(timeline.snapVal(-1)).equal(-5); chai.expect(timeline.snapVal(-10)).equal(-5); chai.expect(timeline.snapVal(-26)).equal(-30); chai.expect(timeline.snapVal(-48)).equal(-55); chai.expect(timeline.snapVal(-58)).equal(-55); // Don't overlap the limit. chai.expect(timeline.snapVal(-100)).equal(-55); }); it('Snapping. negative min (-25) is defined', function () { const timeline = new Timeline(); timeline._setOptions({ stepVal: 100, stepPx: 50, snapStep: 25, min: -25, zoom: 1, } as TimelineOptions); chai.expect(timeline.snapVal(-1)).equal(0); chai.expect(timeline.snapVal(-10)).equal(0); chai.expect(timeline.snapVal(10)).equal(0); chai.expect(timeline.snapVal(26)).equal(25); chai.expect(timeline.snapVal(50)).equal(50); chai.expect(timeline.snapVal(-58)).equal(-25); }); }); describe('Move Keyframes', function () { it('move left', function () { const timeline = new Timeline(); timeline._options = null; const item1 = 25; const item2 = 50; const model = { rows: [{ val: 0, keyframes: [{ val: item1 }, { val: item2 }] } as TimelineRow] as Array<TimelineRow>, } as TimelineModel; timeline._model = model; const move = -50; const movedOffset = timeline._moveElements(move, [ { keyframe: model.rows[0].keyframes[1], row: model.rows[0], } as TimelineElementDragState, { keyframe: model.rows[0].keyframes[0], row: model.rows[0], } as TimelineElementDragState, ]); chai.expect(movedOffset).equal(move); chai.expect(model.rows[0].keyframes[0].val).equal(item1 + move); chai.expect(model.rows[0].keyframes[1].val).equal(item2 + move); }); it('move right', function () { const timeline = new Timeline(); const item1 = 25; const item2 = 50; const model = { rows: [{ val: 0, keyframes: [{ val: item1 }, { val: item2 }] } as TimelineRow] as Array<TimelineRow>, } as TimelineModel; timeline._model = model; const move = 100; const movedOffset = timeline._moveElements(move, [ { keyframe: model.rows[0].keyframes[1], row: model.rows[0], } as TimelineElementDragState, { keyframe: model.rows[0].keyframes[0], row: model.rows[0], } as TimelineElementDragState, ]); chai.expect(movedOffset).equal(move); chai.expect(model.rows[0].keyframes[0].val).equal(item1 + move); chai.expect(model.rows[0].keyframes[1].val).equal(item2 + move); }); it('move left limited by min', function () { const timeline = new Timeline(); const item1 = 25; const item2 = 50; timeline._options = { min: 0, max: 75 } as TimelineOptions; const move = -50; const elementsToMove = [ { keyframe: { val: item1 }, } as TimelineElementDragState, { keyframe: { val: item2 }, } as TimelineElementDragState, ]; const movedOffset = timeline._moveElements(move, elementsToMove); chai.expect(movedOffset).equal(move / 2); chai.expect(elementsToMove[0].keyframe.val).equal(0); chai.expect(elementsToMove[1].keyframe.val).equal(25); }); it('move right limited by max', function () { const timeline = new Timeline(); const item1 = 25; const item2 = 50; timeline._options = { min: 0, max: 100 } as TimelineOptions; const move = 100; const elementsToMove = [ { keyframe: { val: item1 }, } as TimelineElementDragState, { keyframe: { val: item2 }, } as TimelineElementDragState, ]; const movedOffset = timeline._moveElements(move, elementsToMove); chai.expect(movedOffset).equal(move / 2); chai.expect(elementsToMove[0].keyframe.val).equal(item1 + 50); chai.expect(elementsToMove[1].keyframe.val).equal(item2 + 50); }); it('move right limited by max negative', function () { const timeline = new Timeline(); const item1 = -125; const item2 = -150; timeline._options = { min: -200, max: -100 } as TimelineOptions; const move = 100; const elementsToMove = [ { keyframe: { val: item1 }, } as TimelineElementDragState, { keyframe: { val: item2 }, } as TimelineElementDragState, ]; const movedOffset = timeline._moveElements(move, elementsToMove); chai.expect(movedOffset).equal(25); chai.expect(elementsToMove[0].keyframe.val).equal(item1 + 25); chai.expect(elementsToMove[1].keyframe.val).equal(item2 + 25); }); it('move right limited by max negative when other row out of the bounds', function () { const timeline = new Timeline(); timeline._options = { min: 0, max: 600 } as TimelineOptions; const move = 200; const row = { max: 500 } as TimelineRow; const row2 = {} as TimelineRow; const elementsToMove = [ { keyframe: { val: 100 }, row: row, } as TimelineElementDragState, { keyframe: { val: 400 }, row: row, } as TimelineElementDragState, { keyframe: { val: 200 }, row: row2, } as TimelineElementDragState, { keyframe: { val: 300 }, row: row2, } as TimelineElementDragState, ]; const movedOffset = timeline._moveElements(move, elementsToMove); const moved = move / 2; chai.expect(movedOffset).equal(moved); chai.expect(elementsToMove[0].keyframe.val).equal(100 + moved); chai.expect(elementsToMove[1].keyframe.val).equal(400 + moved); chai.expect(elementsToMove[2].keyframe.val).equal(200 + moved); chai.expect(elementsToMove[3].keyframe.val).equal(300 + moved); }); it('move left limited by min negative', function () { const timeline = new Timeline(); const item1 = -125; const item2 = -150; timeline._options = { min: -200, max: -100 } as TimelineOptions; const move = -100; const elementsToMove = [ { keyframe: { val: item1 }, } as TimelineElementDragState, { keyframe: { val: item2 }, } as TimelineElementDragState, ]; const movedOffset = timeline._moveElements(move, elementsToMove); chai.expect(movedOffset).equal(move / 2); chai.expect(elementsToMove[0].keyframe.val).equal(item1 - 50); chai.expect(elementsToMove[1].keyframe.val).equal(item2 - 50); }); it('move left only one keyframe is limited', function () { const timeline = new Timeline(); const move = 100; const row = { min: 0, max: 100 } as TimelineRow; const elementsToMove = [ { keyframe: { val: 25 }, row: row, } as TimelineElementDragState, { keyframe: { val: 50 }, row: row, } as TimelineElementDragState, ]; const movedOffset = timeline._moveElements(move, elementsToMove); chai.expect(movedOffset).equal(move / 2); chai.expect(elementsToMove[0].keyframe.val).equal(25 + 50); chai.expect(elementsToMove[1].keyframe.val).equal(50 + 50); }); }); });
the_stack
import { gql, useQuery } from '@apollo/client'; import Card from '@material-ui/core/Card'; import SupervisorAccountIcon from '@material-ui/icons/SupervisorAccount'; import React from 'react'; import { useSingle } from '../../lib/crud/withSingle'; import { Link } from '../../lib/reactRouterWrapper'; import { looksLikeDbIdString } from '../../lib/routeUtil'; import { Components, registerComponent } from '../../lib/vulcan-lib'; import { useCommentByLegacyId } from '../comments/useComment'; import { useHover } from '../common/withHover'; import { usePostByLegacyId, usePostBySlug } from '../posts/usePost'; const PostLinkPreview = ({href, targetLocation, innerHTML, id}: { href: string, targetLocation: any, innerHTML: string, id: string, }) => { const postID = targetLocation.params._id; const { document: post, error } = useSingle({ collectionName: "Posts", fragmentName: 'PostsList', fetchPolicy: 'cache-then-network' as any, //TODO documentId: postID, }); return <Components.PostLinkPreviewVariantCheck post={post||null} targetLocation={targetLocation} error={error} href={href} innerHTML={innerHTML} id={id} /> } const PostLinkPreviewComponent = registerComponent('PostLinkPreview', PostLinkPreview); const PostLinkPreviewSequencePost = ({href, targetLocation, innerHTML, id}: { href: string, targetLocation: any, innerHTML: string, id: string, }) => { const postID = targetLocation.params.postId; const { document: post, error } = useSingle({ collectionName: "Posts", fragmentName: 'PostsList', fetchPolicy: 'cache-then-network' as any, //TODO documentId: postID, }); return <Components.PostLinkPreviewVariantCheck post={post||null} targetLocation={targetLocation} error={error} href={href} innerHTML={innerHTML} id={id} /> } const PostLinkPreviewSequencePostComponent = registerComponent('PostLinkPreviewSequencePost', PostLinkPreviewSequencePost); const PostLinkPreviewSlug = ({href, targetLocation, innerHTML, id}: { href: string, targetLocation: any, innerHTML: string, id: string, }) => { const slug = targetLocation.params.slug; const { post, error } = usePostBySlug({ slug }); return <Components.PostLinkPreviewVariantCheck href={href} innerHTML={innerHTML} post={post} targetLocation={targetLocation} error={error} id={id} /> } const PostLinkPreviewSlugComponent = registerComponent('PostLinkPreviewSlug', PostLinkPreviewSlug); const PostLinkPreviewLegacy = ({href, targetLocation, innerHTML, id}: { href: string, targetLocation: any, innerHTML: string, id: string, }) => { const legacyId = targetLocation.params.id; const { post, error } = usePostByLegacyId({ legacyId }); return <Components.PostLinkPreviewVariantCheck href={href} innerHTML={innerHTML} post={post} targetLocation={targetLocation} error={error} id={id} /> } const PostLinkPreviewLegacyComponent = registerComponent('PostLinkPreviewLegacy', PostLinkPreviewLegacy); const CommentLinkPreviewLegacy = ({href, targetLocation, innerHTML, id}: { href: string, targetLocation: any, innerHTML: string, id: string, }) => { const legacyPostId = targetLocation.params.id; const legacyCommentId = targetLocation.params.commentId; const { post, error: postError } = usePostByLegacyId({ legacyId: legacyPostId }); const { comment, error: commentError } = useCommentByLegacyId({ legacyId: legacyCommentId }); const error = postError || commentError; if (comment) { return <Components.CommentLinkPreviewWithComment comment={comment} post={post} error={error} href={href} innerHTML={innerHTML} id={id} /> } return <Components.PostLinkPreviewWithPost href={href} innerHTML={innerHTML} post={post} error={error} id={id} /> } const CommentLinkPreviewLegacyComponent = registerComponent('CommentLinkPreviewLegacy', CommentLinkPreviewLegacy); const PostCommentLinkPreviewGreaterWrong = ({href, targetLocation, innerHTML, id}: { href: string, targetLocation: any, innerHTML: string, id: string, }) => { const postId = targetLocation.params._id; const commentId = targetLocation.params.commentId; const { document: post } = useSingle({ collectionName: "Posts", fragmentName: 'PostsList', fetchPolicy: 'cache-then-network' as any, //TODO documentId: postId, }); return <Components.PostLinkCommentPreview href={href} innerHTML={innerHTML} commentId={commentId} post={post||null} id={id}/> } const PostCommentLinkPreviewGreaterWrongComponent = registerComponent('PostCommentLinkPreviewGreaterWrong', PostCommentLinkPreviewGreaterWrong); const PostLinkPreviewVariantCheck = ({ href, innerHTML, post, targetLocation, comment, commentId, error, id}: { href: string, innerHTML: string, post: PostsList|null, targetLocation: any, comment?: any, commentId?: string, error: any, id: string, }) => { if (targetLocation.query.commentId) { return <PostLinkCommentPreview commentId={targetLocation.query.commentId} href={href} innerHTML={innerHTML} post={post} id={id}/> } if (targetLocation.hash) { const commentId = targetLocation.hash.split("#")[1] if (looksLikeDbIdString(commentId)) { return <PostLinkCommentPreview commentId={commentId} href={href} innerHTML={innerHTML} post={post} id={id} /> } } if (commentId) { return <Components.PostLinkCommentPreview commentId={commentId} post={post} href={href} innerHTML={innerHTML} id={id}/> } return <Components.PostLinkPreviewWithPost href={href} innerHTML={innerHTML} post={post} error={error} id={id} /> } const PostLinkPreviewVariantCheckComponent = registerComponent('PostLinkPreviewVariantCheck', PostLinkPreviewVariantCheck); export const linkStyle = (theme: ThemeType) => ({ '&:after': { content: '"°"', marginLeft: 1, color: theme.palette.primary.main, } }) const styles = (theme: ThemeType): JssStyles => ({ link: { ...linkStyle(theme) } }) const PostLinkCommentPreview = ({href, commentId, post, innerHTML, id}: { href: string, commentId: string, post: PostsList|null, innerHTML: string, id: string, }) => { const { document: comment, error } = useSingle({ collectionName: "Comments", fragmentName: 'CommentsList', fetchPolicy: 'cache-then-network' as any, //TODO documentId: commentId, }); if (comment) { return <Components.CommentLinkPreviewWithComment comment={comment} post={post} error={error} href={href} innerHTML={innerHTML} id={id}/> } return <Components.PostLinkPreviewWithPost href={href} innerHTML={innerHTML} post={post} error={error} id={id} /> } const PostLinkCommentPreviewComponent = registerComponent('PostLinkCommentPreview', PostLinkCommentPreview); const PostLinkPreviewWithPost = ({classes, href, innerHTML, post, id, error}: { classes: ClassesType, href: string, innerHTML: string, post: PostsList|null, id: string, error: any, }) => { const { PostsPreviewTooltip, LWPopper } = Components const { anchorEl, hover, eventHandlers } = useHover(); const hash = (href.indexOf("#")>=0) ? (href.split("#")[1]) : null; if (!post) { return <span {...eventHandlers}> <Link to={href} dangerouslySetInnerHTML={{__html: innerHTML}}/> </span> } return ( <span {...eventHandlers}> <LWPopper open={hover} anchorEl={anchorEl} placement="bottom-start" allowOverflow > <PostsPreviewTooltip post={post} hash={hash} /> </LWPopper> <Link className={classes.link} to={href} dangerouslySetInnerHTML={{__html: innerHTML}} id={id} smooth/> </span> ); } const PostLinkPreviewWithPostComponent = registerComponent('PostLinkPreviewWithPost', PostLinkPreviewWithPost, { styles }); const CommentLinkPreviewWithComment = ({classes, href, innerHTML, comment, post, id, error}: { classes: ClassesType, href: string, innerHTML: string, comment: any, post: PostsList|null, id: string, error: any, }) => { const { PostsPreviewTooltip, LWPopper } = Components const { eventHandlers, anchorEl, hover } = useHover(); if (!comment) { return <span {...eventHandlers}> <Link to={href} dangerouslySetInnerHTML={{__html: innerHTML}}/> </span> } return ( <span {...eventHandlers}> <LWPopper open={hover} anchorEl={anchorEl} placement="bottom-start" allowOverflow > <PostsPreviewTooltip post={post} comment={comment} /> </LWPopper> <Link className={classes.link} to={href} dangerouslySetInnerHTML={{__html: innerHTML}} id={id}/> </span> ) } const CommentLinkPreviewWithCommentComponent = registerComponent('CommentLinkPreviewWithComment', CommentLinkPreviewWithComment, { styles, }); const footnotePreviewStyles = (theme: ThemeType): JssStyles => ({ hovercard: { padding: `${theme.spacing.unit*3}px ${theme.spacing.unit*2}px ${theme.spacing.unit*2}px`, ...theme.typography.body2, fontSize: "1.1rem", ...theme.typography.commentStyle, color: theme.palette.grey[800], maxWidth: 500, '& a': { color: theme.palette.primary.main, }, }, }) const FootnotePreview = ({classes, href, innerHTML, onsite=false, id, rel}: { classes: ClassesType, href: string, innerHTML: string, onsite?: boolean, id?: string, rel?: string }) => { const { LWPopper } = Components const { eventHandlers, hover, anchorEl } = useHover({ pageElementContext: "linkPreview", hoverPreviewType: "DefaultPreview", href, onsite }); let footnoteContentsNonempty = false; let footnoteMinusBacklink = ""; // Get the contents of the linked footnote. // This has a try-catch-ignore around it because the link doesn't necessarily // make a valid CSS selector; eg there are some posts in the DB with internal // links to anchors like "#fn:1" which will crash this because it has a ':' in // it. try { // Grab contents of linked footnote if it exists const footnoteHTML = document.querySelector(href)?.innerHTML; // Remove the backlink anchor tag. Note that this regex is deliberately very narrow; // a more permissive regex would introduce risk of XSS, since we're not re-validating // after this transform. footnoteMinusBacklink = footnoteHTML?.replace(/<a href="#fnref[a-zA-Z0-9]*">^<\/a>/g, '') || ""; // Check whether the footnotehas nonempty contents footnoteContentsNonempty = !!Array.from(document.querySelectorAll(`${href} p`)).reduce((acc, p) => acc + p.textContent, "").trim(); // eslint-disable-next-line no-empty } catch(e) { } return ( <span {...eventHandlers}> {footnoteContentsNonempty && <LWPopper open={hover} anchorEl={anchorEl} placement="bottom-start" allowOverflow > <Card> <div className={classes.hovercard}> <div dangerouslySetInnerHTML={{__html: footnoteMinusBacklink || ""}} /> </div> </Card> </LWPopper>} <a href={href} dangerouslySetInnerHTML={{__html: innerHTML}} id={id} rel={rel}/> </span> ); } const FootnotePreviewComponent = registerComponent('FootnotePreview', FootnotePreview, { styles: footnotePreviewStyles, }); const defaultPreviewStyles = (theme: ThemeType): JssStyles => ({ hovercard: { padding: theme.spacing.unit, paddingLeft: theme.spacing.unit*1.5, paddingRight: theme.spacing.unit*1.5, ...theme.typography.body2, fontSize: "1.1rem", ...theme.typography.commentStyle, color: theme.palette.grey[600], maxWidth: 500, overflow: 'hidden', textOverflow: 'ellipsis', whiteSpace: 'nowrap' }, }) const DefaultPreview = ({classes, href, innerHTML, onsite=false, id, rel}: { classes: ClassesType, href: string, innerHTML: string, onsite?: boolean, id?: string, rel?: string }) => { const { LWPopper } = Components const { eventHandlers, hover, anchorEl } = useHover({ pageElementContext: "linkPreview", hoverPreviewType: "DefaultPreview", href, onsite }); return ( <span {...eventHandlers}> <LWPopper open={hover} anchorEl={anchorEl} placement="bottom-start" clickable={false}> <Card> <div className={classes.hovercard}> {href} </div> </Card> </LWPopper> {onsite ? <Link to={href} dangerouslySetInnerHTML={{__html: innerHTML}} id={id} rel={rel}/> : <Components.AnalyticsTracker eventType="link" eventProps={{to: href}}> <a href={href} dangerouslySetInnerHTML={{__html: innerHTML}} id={id} rel={rel}/> </Components.AnalyticsTracker>} </span> ); } const DefaultPreviewComponent = registerComponent('DefaultPreview', DefaultPreview, { styles: defaultPreviewStyles, }); const mozillaHubStyles = (theme: ThemeType): JssStyles => ({ users: { marginLeft: 3, fontSize: "1.2rem", fontWeight: 600 }, usersPreview: { fontSize: "1.1rem" }, icon: { height: 18, position: "relative", top: 3 }, image: { width: 350, height: 200 }, roomInfo: { padding: 16 }, roomHover: { position: "relative", }, roomTitle: { fontWeight: 600, fontSize: "1.3rem" }, card: { boxShadow: theme.palette.boxShadow.mozillaHubPreview, width: 350, backgroundColor: theme.palette.panelBackground.default, }, description: { marginTop: 8, fontSize: "1.1rem" } }) const MozillaHubPreview = ({classes, href, innerHTML, id}: { classes: ClassesType, href: string, innerHTML: string, id?: string, }) => { const roomId = href.split("/")[3] const { data: rawData, loading } = useQuery(gql` query MozillaHubsRoomData { MozillaHubsRoomData(roomId: "${roomId || 'asdasd'}") { id previewImage lobbyCount memberCount roomSize description url name } } `, { ssr: true }); const data = rawData?.MozillaHubsRoomData const { AnalyticsTracker, LWPopper, ContentStyles } = Components const { anchorEl, hover, eventHandlers } = useHover(); if (loading || !data) return <a href={href}> <span dangerouslySetInnerHTML={{__html: innerHTML}}/> </a> return <AnalyticsTracker eventType="link" eventProps={{to: href}}> <span {...eventHandlers}> <a href={data.url} id={id}> <span dangerouslySetInnerHTML={{__html: innerHTML}}/> <span className={classes.users}> (<SupervisorAccountIcon className={classes.icon}/> {data.memberCount}/{data.roomSize}) </span> </a> <LWPopper open={hover} anchorEl={anchorEl} placement="bottom-start"> <div className={classes.card}> <img className={classes.image} src={data.previewImage}/> <ContentStyles contentType="postHighlight" className={classes.roomInfo}> <div className={classes.roomTitle}>{data.name}</div> <div className={classes.usersPreview}> <SupervisorAccountIcon className={classes.icon}/> {data.memberCount}/{data.roomSize} users online ({data.lobbyCount} in lobby) </div> {data.description && <div className={classes.description}> {data.description} </div>} </ContentStyles> </div> </LWPopper> </span> </AnalyticsTracker> } const MozillaHubPreviewComponent = registerComponent('MozillaHubPreview', MozillaHubPreview, { styles: mozillaHubStyles }) const owidStyles = (theme: ThemeType): JssStyles => ({ iframeStyling: { width: 600, height: 375, border: "none", maxWidth: "100vw", }, link: { ...linkStyle(theme) } }) const OWIDPreview = ({classes, href, innerHTML, id}: { classes: ClassesType, href: string, innerHTML: string, id?: string, }) => { const { AnalyticsTracker, LWPopper } = Components const { anchorEl, hover, eventHandlers } = useHover(); const [match] = href.match(/^http(?:s?):\/\/ourworldindata\.org\/grapher\/.*/) || [] if (!match) { return <a href={href}> <span dangerouslySetInnerHTML={{__html: innerHTML}}/> </a> } return <AnalyticsTracker eventType="link" eventProps={{to: href}}> <span {...eventHandlers}> <a className={classes.link} href={href} id={id} dangerouslySetInnerHTML={{__html: innerHTML}} /> <LWPopper open={hover} anchorEl={anchorEl} placement="bottom-start"> <div className={classes.background}> <iframe className={classes.iframeStyling} src={match} /> </div> </LWPopper> </span> </AnalyticsTracker> } const OWIDPreviewComponent = registerComponent('OWIDPreview', OWIDPreview, { styles: owidStyles }) const metaculusStyles = (theme: ThemeType): JssStyles => ({ background: { backgroundColor: theme.palette.panelBackground.metaculusBackground, }, iframeStyling: { width: 400, height: 250, border: "none", maxWidth: "100vw" }, link: { ...linkStyle(theme) } }) const MetaculusPreview = ({classes, href, innerHTML, id}: { classes: ClassesType, href: string, innerHTML: string, id?: string, }) => { const { AnalyticsTracker, LWPopper } = Components const { anchorEl, hover, eventHandlers } = useHover(); const [match, www, questionNumber] = href.match(/^http(?:s?):\/\/(www\.)?metaculus\.com\/questions\/([a-zA-Z0-9]{1,6})?/) || [] if (!questionNumber) { return <a href={href}> <span dangerouslySetInnerHTML={{__html: innerHTML}}/> </a> } return <AnalyticsTracker eventType="link" eventProps={{to: href}}> <span {...eventHandlers}> <a className={classes.link} href={href} id={id} dangerouslySetInnerHTML={{__html: innerHTML}} /> <LWPopper open={hover} anchorEl={anchorEl} placement="bottom-start"> <div className={classes.background}> <iframe className={classes.iframeStyling} src={`https://d3s0w6fek99l5b.cloudfront.net/s/1/questions/embed/${questionNumber}/?plot=pdf`} /> </div> </LWPopper> </span> </AnalyticsTracker> } const MetaculusPreviewComponent = registerComponent('MetaculusPreview', MetaculusPreview, { styles: metaculusStyles }) const manifoldStyles = (theme: ThemeType): JssStyles => ({ iframeStyling: { width: 560, height: 405, border: "none", maxWidth: "100vw", }, link: linkStyle(theme), }); const ManifoldPreview = ({classes, href, innerHTML, id}: { classes: ClassesType; href: string; innerHTML: string; id?: string; }) => { const { AnalyticsTracker, LWPopper } = Components; const { anchorEl, hover, eventHandlers } = useHover(); // test if fits https://manifold.markets/embed/[...] const isEmbed = /^https?:\/\/manifold\.markets\/embed\/.+$/.test(href); // if it fits https://manifold.markets/[username]/[market-slug] instead, get the (username and market slug) const [, userAndSlug] = href.match(/^https?:\/\/manifold\.markets\/(\w+\/[\w-]+)/) || []; if (!isEmbed && !userAndSlug) { return ( <a href={href}> <span dangerouslySetInnerHTML={{ __html: innerHTML }} /> </a> ); } const url = isEmbed ? href : `https://manifold.markets/embed/${userAndSlug}`; return ( <AnalyticsTracker eventType="link" eventProps={{ to: href }}> <span {...eventHandlers}> <a className={classes.link} href={href} id={id} dangerouslySetInnerHTML={{ __html: innerHTML }} /> <LWPopper open={hover} anchorEl={anchorEl} placement="bottom-start"> <iframe className={classes.iframeStyling} src={url} /> </LWPopper> </span> </AnalyticsTracker> ); }; const ManifoldPreviewComponent = registerComponent('ManifoldPreview', ManifoldPreview, { styles: manifoldStyles }) const ArbitalLogo = () => <svg x="0px" y="0px" height="100%" viewBox="0 0 27.5 23.333"> <g> <path d="M19.166,20.979v-0.772c-1.035,0.404-2.159,0.626-3.334,0.626c-0.789,0-1.559-0.1-2.291-0.288 c-0.813-0.21-1.584-0.529-2.292-0.94c-0.032-0.019-0.06-0.042-0.091-0.061c-2.686-1.596-4.49-4.525-4.492-7.877 c0.001-3.027,1.471-5.713,3.733-7.381c-0.229,0.04-0.458,0.079-0.679,0.139C9.68,4.435,9.643,4.449,9.604,4.461 C9.359,4.53,9.123,4.613,8.891,4.706c-0.07,0.028-0.14,0.057-0.209,0.086C8.42,4.906,8.164,5.029,7.918,5.172 c-2.243,1.299-3.752,3.717-3.752,6.494c0,2.99,1.123,5.711,2.973,7.777c0.285,0.319,0.594,0.625,0.918,0.915 c1.123,1.005,2.44,1.797,3.888,2.309c0.626,0.223,1.272,0.39,1.944,0.503c0.632,0.105,1.281,0.162,1.943,0.162 c1.159,0,2.277-0.17,3.334-0.484V20.979z"></path> <path d="M19.443,2.975c-1.123-1.007-2.441-1.799-3.889-2.311c-0.623-0.221-1.273-0.391-1.943-0.502 C12.979,0.056,12.33,0,11.666,0c-1.365,0-2.671,0.233-3.889,0.664C6.33,1.176,5.012,1.966,3.889,2.971 C1.5,5.11,0.001,8.208,0,11.666c0.001,3.457,1.5,6.557,3.889,8.695c1.123,1.004,2.441,1.794,3.889,2.306 c0.32,0.113,0.646,0.213,0.979,0.298c-0.186-0.116-0.361-0.248-0.541-0.373c-0.108-0.075-0.219-0.146-0.324-0.224 c-0.327-0.243-0.645-0.498-0.947-0.77c-0.363-0.327-0.715-0.674-1.047-1.044C3.785,18.198,2.5,15.078,2.5,11.666 c0-3.393,1.846-6.355,4.582-7.937c1.35-0.78,2.916-1.231,4.584-1.231c0.789,0,1.559,0.102,2.292,0.291 c0.813,0.209,1.584,0.529,2.292,0.938c2.738,1.583,4.582,4.546,4.584,7.938c-0.002,3.027-1.473,5.713-3.736,7.381 c-0.007,0.005-0.013,0.011-0.02,0.016c0.237-0.039,0.471-0.092,0.699-0.154c0.042-0.011,0.082-0.026,0.124-0.038 c0.24-0.069,0.475-0.151,0.704-0.242c0.072-0.029,0.144-0.058,0.215-0.089c0.261-0.113,0.517-0.236,0.761-0.378l1.251-0.725v2.562 v0.98v2.354h2.5v-2.351v-0.984v-8.332c0-2.992-1.123-5.712-2.971-7.777C20.074,3.568,19.767,3.265,19.443,2.975z"></path> <path d="M23.609,2.971c-1.123-1.005-2.44-1.795-3.888-2.307C19.4,0.551,19.073,0.451,18.74,0.365 c0.186,0.116,0.36,0.246,0.539,0.371c0.109,0.076,0.223,0.148,0.33,0.228c0.326,0.243,0.643,0.497,0.945,0.769 c0.365,0.327,0.716,0.674,1.049,1.043c2.109,2.357,3.396,5.479,3.396,8.891v8.332v0.984v2.35H27.5V11.666 C27.498,8.208,25.999,5.11,23.609,2.971z"></path> </g> </svg> const arbitalStyles = (theme: ThemeType): JssStyles => ({ hovercard: { padding: theme.spacing.unit, paddingLeft: theme.spacing.unit*1.5, paddingRight: theme.spacing.unit*1.5, maxWidth: 500, overflow: 'hidden', textOverflow: 'ellipsis', '& h2': { marginTop: 4 }, "& a[href='https://arbital.com/edit/']": { color: theme.palette.error.main } }, headerRow: { display: 'flex', justifyContent: 'space-between' }, logo: { height: 24, fill: theme.palette.icon.dim2, marginTop: -5 }, link: { ...linkStyle(theme) } }) const ArbitalPreview = ({classes, href, innerHTML, id}: { classes: ClassesType, href: string, innerHTML: string, id?: string, }) => { const { AnalyticsTracker, LWPopper, ContentStyles } = Components const { anchorEl, hover, eventHandlers } = useHover(); const [match, www, arbitalSlug] = href.match(/^http(?:s?):\/\/(www\.)?arbital\.com\/p\/([a-zA-Z0-9_]+)+/) || [] const { data: rawData, loading } = useQuery(gql` query ArbitalPageRequest { ArbitalPageData(pageAlias: "${arbitalSlug}") { title html } } `, { ssr: true, skip: !arbitalSlug, }); if (!arbitalSlug || loading) { return <Components.DefaultPreview href={href} innerHTML={innerHTML} id={id} /> } return <AnalyticsTracker eventType="link" eventProps={{to: href}}> <span {...eventHandlers}> <a className={classes.link} href={href} id={id} dangerouslySetInnerHTML={{__html: innerHTML}} /> <LWPopper open={hover} anchorEl={anchorEl} placement="bottom-start"> <Card> <ContentStyles contentType="comment" className={classes.hovercard}> <div className={classes.headerRow}> <a href={href}><h2>{rawData?.ArbitalPageData?.title}</h2></a> <a href="https://arbital.com" title="This article is hosted on Arbital.com"><div className={classes.logo}><ArbitalLogo/></div></a> </div> <div dangerouslySetInnerHTML={{__html: rawData?.ArbitalPageData?.html}} id={id} /> </ContentStyles> </Card> </LWPopper> </span> </AnalyticsTracker> } const ArbitalPreviewComponent = registerComponent('ArbitalPreview', ArbitalPreview, { styles: arbitalStyles }) declare global { interface ComponentTypes { PostLinkPreview: typeof PostLinkPreviewComponent, PostLinkPreviewSequencePost: typeof PostLinkPreviewSequencePostComponent, PostLinkPreviewSlug: typeof PostLinkPreviewSlugComponent, PostLinkPreviewLegacy: typeof PostLinkPreviewLegacyComponent, CommentLinkPreviewLegacy: typeof CommentLinkPreviewLegacyComponent, PostCommentLinkPreviewGreaterWrong: typeof PostCommentLinkPreviewGreaterWrongComponent, PostLinkPreviewVariantCheck: typeof PostLinkPreviewVariantCheckComponent, PostLinkCommentPreview: typeof PostLinkCommentPreviewComponent, PostLinkPreviewWithPost: typeof PostLinkPreviewWithPostComponent, CommentLinkPreviewWithComment: typeof CommentLinkPreviewWithCommentComponent, MozillaHubPreview: typeof MozillaHubPreviewComponent, MetaculusPreview: typeof MetaculusPreviewComponent, ManifoldPreview: typeof ManifoldPreviewComponent, OWIDPreview: typeof OWIDPreviewComponent, ArbitalPreview: typeof ArbitalPreviewComponent, FootnotePreview: typeof FootnotePreviewComponent, DefaultPreview: typeof DefaultPreviewComponent, } }
the_stack
import { Link, PageProps } from 'gatsby' import * as React from 'react' import { ContentSection } from '../components/content/ContentSection' import Layout from '../components/Layout' import Tab from 'react-bootstrap/Tab' import Tabs from 'react-bootstrap/Tabs' export const CommunityPage: React.FunctionComponent<PageProps> = props => ( <Layout location={props.location} meta={{ title: 'Welcome to the Sourcegraph Community', description: "Sourcegraph is so much more than a universal code search engine. It's the story of new gen-developers who renaissance-d the way we work, live, and collaborate. It's our unparalleled thinking that creates endless possibilities, to rebuild, to disrupt and to innovate relentlessly despite all the complexities of the big code. But we're just getting started. Imagine the road ahead if we take this journey together.", image: 'https://about.sourcegraph.com/sourcegraph-og.png', }} heroAndHeaderClassName="community-page__hero-and-header" hero={ <div className="container pb-4"> <div className="row p-5"> <div className="col-lg-6"> <div className="text-uppercase">Join us</div> <h1 className="display-2 font-weight-bold mb-0">Welcome to the Sourcegraph Community</h1> <p className="home__semiwide-paragraph my-5 display-5"> Seek guidance. Share best practices. Ask questions. The Sourcegraph Community is your new platform to connect with one of the world's most talented developer communities. Here, we encourage everyone to learn from each other and share everything they know. Because when we collaborate, we grow faster, better, and stronger. </p> <a className="btn btn-primary" href={ 'https://join.slack.com/t/sourcegraph-community/shared_invite/zt-w11gottx-c0PYTK69YVW_06tpJZ0bOQ' } title="Join our Slack" > Join our Slack </a> </div> <div className="col-lg-6"> <figure> <img className="hero_img" src="/community/hero_illustration.svg" alt="Sourcegraph Hero Image" /> </figure> </div> </div> </div> } > <ContentSection className="py-5 text-center"> <h2 className="display-3 font-weight-bold mt-5 mb-3">Get up to speed</h2> <div className="row justify-content-center"> <p className="col-md-8"> We can’t give you a 25-hour day, but here is a <a href="http://srcgr.ph/cheatsheet">speed sheet</a>{' '} with the most useful Sourcegraph shortcuts. Need even more speed? Fasten your seat belt and dive into our curated <a href="https://learn.sourcegraph.com/tags/sourcegraph"> tutorials</a> &#38; other{' '} <a href="https://docs.sourcegraph.com/">tip documents</a>. </p> </div> <div className="row"> <div className="col-12 mt-4"> <a href="http://srcgr.ph/cheatsheet"> <figure> <img className="cheatsheet_img" src="/community/cheatsheet_top.png" alt="Sourcegraph cheatsheet" /> </figure> </a> </div> </div> </ContentSection> <div className="bg-gradient-green-blue py-5"> <ContentSection className="py-5"> <div className="row"> <div className="col-lg-6"> <h2 className="display-3 font-weight-bold mb-3">Sourcegraph Champions Program</h2> <p> In the spirit of collaboration, we created the Sourcegraph Champions Program to serve the developer community, create a friendly networking space and share knowledge among each other. </p> <p> We believe that if we create the right environment and provide equal resources for all, everyone can learn how to code. This is our mission. And if you share the same idea you are a "champion" in our eyes. </p> <p> We can't wait to meet you! And send you really cool custom swag ;) <br /> <a className="btn btn-primary mt-3" href="https://handbook.sourcegraph.com/marketing/becoming_a_sourcegraph_champion" > Become a Sourcegraph Champion </a> </p> <p> Or if you know someone that should be a Sourcegraph Champion, please{' '} <a href="https://forms.gle/QP6BBCpN1TwQfHzo6">nominate them</a>. </p> </div> <div className="col-lg-6"> <img className="sg_champion_img mt-6" src="/community/SG_Robots_Trophy.png" alt="Become a Sourcegraph Champion!" /> </div> </div> </ContentSection> </div> <ContentSection className="py-6"> <div className="row"> <div className="col-lg-6"> <h2 className="display-3 font-weight-bold mt-5 mb-3">DM us on Slack. We're here.</h2> What you seek is seeking you — come, chat and collaborate with inspiring engineers like you. <ul className="list-spaced"> <li>Ask questions - any questions: what is the best sit-stand desk?</li> <li>Reach out to the community, discover new ideas &#38; seek or give mentorship</li> <li>Share the road less traveled so that everyone can learn</li> </ul> <a className="btn btn-primary" href={ 'https://join.slack.com/t/sourcegraph-community/shared_invite/zt-w11gottx-c0PYTK69YVW_06tpJZ0bOQ' } title="Join us on Slack" > Join us on Slack </a> </div> <div className="col-lg-5"> <img className="sg_champion_img mt-6" src="/community/SG_DM_us_on_slack.png" alt="DM us on Slack!" /> </div> </div> </ContentSection> <ContentSection className="py-4"> <h2 className="display-3 font-weight-bold mb-5 text-center">What's next?</h2> <Tabs defaultActiveKey="configuration" id="use-cases" className="justify-content-center"> <Tab eventKey="configuration" title="Events"> <div className="row mt-5 justify-content-center"> <div className="col-lg-8"> <p> Keynote speakers. Job opportunities and partnerships. You can find us in every major industry event. Give us an air-hug if you see us. </p> <ul> <li> <a href="https://events.linuxfoundation.org/open-source-summit-north-america/register/"> Open Source Summit </a>{' '} - 9/27 - 9/30 </li> <li> <a href="https://reactadvanced.com/">React Advanced London</a> - 10/22 </li> <li> <a href="https://africa.jsworldconference.com/">JSWorld Africa</a> - 10/30 </li> <li> <a href="https://festival.oscafrica.org/">Open Source Festival</a> - 11/11 - 11/13 </li> <li> <a href="https://www.gophercon.com/">GopherCon</a> - 12/5 - 12/8 </li> </ul> </div> </div> </Tab> <Tab eventKey="refactoring" title="Dev Tool Time"> <div className="row mt-5 justify-content-center"> <div className="col-lg-8"> <p> Cool hardware. Most-wanted guests. And hot topics. Check our{' '} <a href="https://srcgr.ph/dev-tool-time-playlist">YouTube channel</a> and subscribe to keep up with new episodes. </p> <a href="https://srcgr.ph/dev-tool-time-playlist"> <img className="w-100 h-auto mt-4" width="850" height="380" src="/community/DTT_module.jpg" alt="Dev Tool Time" /> </a> </div> </div> </Tab> <Tab eventKey="security" title="Podcast"> <div className="row mt-5 justify-content-center"> <div className="col-lg-8"> <p> Tune into our developer convos wherever you listen to your favorite podcasts. Every episode is an inspiration. </p> <a href="https://about.sourcegraph.com/podcast"> <img className="w-100 h-auto mt-4" width="750" height="472" src="/community/Podcast_module.png" alt="Podcasts" /> </a> </div> </div> </Tab> </Tabs> </ContentSection> <ContentSection className="py-5"> <div className="row"> <div className="col-lg-7"> <h2 className="display-3 font-weight-bold mb-3">We’d love to hear from you!</h2> <br /> Connect with us on the Sourcegraph Community Slack group, direct message us on Twitter, LinkedIn, or email us at <a href="mailto:community@sourcegraph.com">community@sourcegraph.com</a>. </div> <div className="col-lg-5 mt-3"> <a className="btn btn-secondary" href={ 'https://join.slack.com/t/sourcegraph-community/shared_invite/zt-w11gottx-c0PYTK69YVW_06tpJZ0bOQ' } title="Join us on Slack" > Join us on Slack </a> <br /> <a className="btn btn-primary mt-3" href={'mailto:community@sourcegraph.com'} title="Send us an email" > Send us an email </a> </div> </div> </ContentSection> </Layout> ) export default CommunityPage
the_stack
import { Injectable } from '@angular/core'; import moment, { LongDateFormatKey } from 'moment'; import { makeSingleton, Translate } from '@singletons'; import { CoreTime } from '@singletons/time'; /* * "Utils" service with helper functions for date and time. */ @Injectable({ providedIn: 'root' }) export class CoreTimeUtilsProvider { protected static readonly FORMAT_REPLACEMENTS = { // To convert PHP strf format to Moment format. '%a': 'ddd', '%A': 'dddd', '%d': 'DD', '%e': 'D', // Not exactly the same. PHP adds a space instead of leading zero, Moment doesn't. '%j': 'DDDD', '%u': 'E', '%w': 'e', // It might not behave exactly like PHP, the first day could be calculated differently. '%U': 'ww', // It might not behave exactly like PHP, the first week could be calculated differently. '%V': 'WW', '%W': 'ww', // It might not behave exactly like PHP, the first week could be calculated differently. '%b': 'MMM', '%B': 'MMMM', '%h': 'MMM', '%m': 'MM', '%C' : '', // Not supported by Moment. '%g': 'GG', '%G': 'GGGG', '%y': 'YY', '%Y': 'YYYY', '%H': 'HH', '%k': 'H', // Not exactly the same. PHP adds a space instead of leading zero, Moment doesn't. '%I': 'hh', '%l': 'h', // Not exactly the same. PHP adds a space instead of leading zero, Moment doesn't. '%M': 'mm', '%p': 'A', '%P': 'a', '%r': 'hh:mm:ss A', '%R': 'HH:mm', '%S': 'ss', '%T': 'HH:mm:ss', '%X': 'LTS', '%z': 'ZZ', '%Z': 'ZZ', // Not supported by Moment, it was deprecated. Use the same as %z. '%c': 'LLLL', '%D': 'MM/DD/YY', '%F': 'YYYY-MM-DD', '%s': 'X', '%x': 'L', '%n': '\n', '%t': '\t', '%%': '%', }; /** * Initialize. */ initialize(): void { // Set relative time thresholds for humanize(), otherwise for example 47 minutes were converted to 'an hour'. moment.relativeTimeThreshold('s', 60); moment.relativeTimeThreshold('m', 60); moment.relativeTimeThreshold('h', 24); moment.relativeTimeThreshold('d', 30); moment.relativeTimeThreshold('M', 12); moment.relativeTimeThreshold('y', 365); moment.relativeTimeThreshold('ss', 0); // To display exact number of seconds instead of just "a few seconds". } /** * Convert a PHP format to a Moment format. * * @param format PHP format. * @return Converted format. */ convertPHPToMoment(format: string): string { if (typeof format != 'string') { // Not valid. return ''; } let converted = ''; let escaping = false; for (let i = 0; i < format.length; i++) { let char = format[i]; if (char == '%') { // It's a PHP format, try to convert it. i++; char += format[i] || ''; if (escaping) { // We were escaping some characters, stop doing it now. escaping = false; converted += ']'; } converted += CoreTimeUtilsProvider.FORMAT_REPLACEMENTS[char] !== undefined ? CoreTimeUtilsProvider.FORMAT_REPLACEMENTS[char] : char; } else { // Not a PHP format. We need to escape them, otherwise the letters could be confused with Moment formats. if (!escaping) { escaping = true; converted += '['; } converted += char; } } if (escaping) { // Finish escaping. converted += ']'; } return converted; } /** * Fix format to use in an ion-datetime. * * @param format Format to use. * @return Fixed format. */ fixFormatForDatetime(format: string): string { if (!format) { return ''; } // The component ion-datetime doesn't support escaping characters ([]), so we remove them. let fixed = format.replace(/[[\]]/g, ''); if (fixed.indexOf('A') != -1) { // Do not use am/pm format because there is a bug in ion-datetime. fixed = fixed.replace(/ ?A/g, ''); fixed = fixed.replace(/h/g, 'H'); } return fixed; } /** * Returns years, months, days, hours, minutes and seconds in a human readable format. * * @param seconds A number of seconds * @param precision Number of elements to have in precision. * @return Seconds in a human readable format. * @deprecated since app 4.0. Use CoreTime.formatTime instead. */ formatTime(seconds: number, precision = 2): string { return CoreTime.formatTime(seconds, precision); } /** * Converts a number of seconds into a short human readable format: minutes and seconds, in fromat: 3' 27''. * * @param seconds Seconds * @return Short human readable text. * @deprecated since app 4.0. Use CoreTime.formatTimeShort instead. */ formatTimeShort(duration: number): string { return CoreTime.formatTimeShort(duration); } /** * Returns hours, minutes and seconds in a human readable format. * * @param duration Duration in seconds * @param precision Number of elements to have in precision. 0 or undefined to full precission. * @return Duration in a human readable format. * @deprecated since app 4.0. Use CoreTime.formatTime instead. */ formatDuration(duration: number, precision?: number): string { return CoreTime.formatTime(duration, precision); } /** * Returns duration in a short human readable format: minutes and seconds, in fromat: 3' 27''. * * @param duration Duration in seconds * @return Duration in a short human readable format. * @deprecated since app 4.0. Use CoreTime.formatTimeShort instead. */ formatDurationShort(duration: number): string { return CoreTime.formatTimeShort(duration); } /** * Return the current timestamp in a "readable" format: YYYYMMDDHHmmSS. * * @return The readable timestamp. */ readableTimestamp(): string { return moment(Date.now()).format('YYYYMMDDHHmmSS'); } /** * Return the current timestamp (UNIX format, seconds). * * @return The current timestamp in seconds. */ timestamp(): number { return Math.round(Date.now() / 1000); } /** * Convert a timestamp into a readable date. * * @param timestamp Timestamp in milliseconds. * @param format The format to use (lang key). Defaults to core.strftimedaydatetime. * @param convert If true (default), convert the format from PHP to Moment. Set it to false for Moment formats. * @param fixDay If true (default) then the leading zero from %d is removed. * @param fixHour If true (default) then the leading zero from %I is removed. * @return Readable date. */ userDate(timestamp: number, format?: string, convert: boolean = true, fixDay: boolean = true, fixHour: boolean = true): string { format = Translate.instant(format ? format : 'core.strftimedaydatetime') as string; if (fixDay) { format = format.replace(/%d/g, '%e'); } if (fixHour) { format = format.replace('%I', '%l'); } // Format could be in PHP format, convert it to moment. if (convert) { format = this.convertPHPToMoment(format); } return moment(timestamp).format(format); } /** * Convert a timestamp to the format to set to a datetime input. * * @param timestamp Timestamp to convert (in ms). If not provided, current time. * @return Formatted time. */ toDatetimeFormat(timestamp?: number): string { timestamp = timestamp || Date.now(); return this.userDate(timestamp, 'YYYY-MM-DDTHH:mm:ss.SSS', false) + 'Z'; } /** * Convert a text into user timezone timestamp. * * @todo The `applyOffset` argument is only used as a workaround, it should be removed once * MOBILE-3784 is resolved. * * @param date To convert to timestamp. * @param applyOffset Whether to apply offset to date or not. * @return Converted timestamp. */ convertToTimestamp(date: string, applyOffset?: boolean): number { const timestamp = moment(date).unix(); if (applyOffset !== undefined) { return applyOffset ? timestamp - moment().utcOffset() * 60 : timestamp; } return typeof date == 'string' && date.slice(-1) == 'Z' ? timestamp - moment().utcOffset() * 60 : timestamp; } /** * Return the localized ISO format (i.e DDMMYY) from the localized moment format. Useful for translations. * DO NOT USE this function for ion-datetime format. Moment escapes characters with [], but ion-datetime doesn't support it. * * @param localizedFormat Format to use. * @return Localized ISO format */ getLocalizedDateFormat(localizedFormat: LongDateFormatKey): string { return moment.localeData().longDateFormat(localizedFormat); } /** * For a given timestamp get the midnight value in the user's timezone. * * The calculation is performed relative to the user's midnight timestamp * for today to ensure that timezones are preserved. * * @param timestamp The timestamp to calculate from. If not defined, return today's midnight. * @return The midnight value of the user's timestamp. */ getMidnightForTimestamp(timestamp?: number): number { if (timestamp) { return moment(timestamp * 1000).startOf('day').unix(); } else { return moment().startOf('day').unix(); } } /** * Get the default max year for datetime inputs. */ getDatetimeDefaultMax(): string { return String(moment().year() + 20); } /** * Get the default min year for datetime inputs. */ getDatetimeDefaultMin(): string { return String(moment().year() - 20); } } export const CoreTimeUtils = makeSingleton(CoreTimeUtilsProvider);
the_stack
import {ICourse} from '../../../shared/models/ICourse'; import {ICourseDashboard} from '../../../shared/models/ICourseDashboard'; import {ICourseView} from '../../../shared/models/ICourseView'; import * as mongoose from 'mongoose'; import {User, IUserModel, IUserPrivileges} from './User'; import {ILectureModel, Lecture} from './Lecture'; import {ILecture} from '../../../shared/models/ILecture'; import {InternalServerError} from 'routing-controllers'; import {IUser} from '../../../shared/models/IUser'; import {Directory} from './mediaManager/Directory'; import {extractSingleMongoId} from '../utilities/ExtractMongoId'; import {ChatRoom, IChatRoomModel} from './ChatRoom'; import {Picture} from './mediaManager/File'; export interface ICourseUserPrivileges extends IUserPrivileges { courseAdminId: string; userIsCourseAdmin: boolean; userIsCourseTeacher: boolean; userIsCourseStudent: boolean; userIsCourseMember: boolean; userCanEditCourse: boolean; userCanViewCourse: boolean; } interface ICourseModel extends ICourse, mongoose.Document { exportJSON: (sanitize?: boolean, onlyBasicData?: boolean) => Promise<ICourse>; checkPrivileges: (user: IUser) => ICourseUserPrivileges; forDashboard: (user: IUser) => ICourseDashboard; forView: (user: IUser) => ICourseView; populateLecturesFor: (user: IUser) => this; processLecturesFor: (user: IUser) => Promise<this>; } interface ICourseMongoose extends mongoose.Model<ICourseModel> { exportPersonalData: (user: IUser) => Promise<ICourse>; changeCourseAdminFromUser: (userFrom: IUser, userTo: IUser) => Promise<ICourseMongoose>; } let Course: ICourseMongoose; const courseSchema = new mongoose.Schema({ name: { type: String, unique: true, required: true }, active: { type: Boolean }, description: { type: String }, courseAdmin: { type: mongoose.Schema.Types.ObjectId, ref: 'User' }, media: { type: mongoose.Schema.Types.ObjectId, ref: 'Directory' }, teachers: [ { type: mongoose.Schema.Types.ObjectId, ref: 'User' } ], students: [ { type: mongoose.Schema.Types.ObjectId, ref: 'User' } ], lectures: [ { type: mongoose.Schema.Types.ObjectId, ref: 'Lecture' } ], accessKey: { type: String }, enrollType: { type: String, enum: ['free', 'whitelist', 'accesskey'], default: 'free' }, whitelist: [ { type: mongoose.Schema.Types.ObjectId, ref: 'WhitelistUser' } ], image: { type: mongoose.Schema.Types.ObjectId, ref: 'Picture' }, chatRooms: [ { type: mongoose.Schema.Types.ObjectId, ref: 'ChatRoom' } ], freeTextStyle: { type: String, enum: ['', 'theme1', 'theme2', 'theme3', 'theme4'], default: '' }, }, { timestamps: true, toObject: { transform: function (doc: ICourseModel, ret: any, {currentUser}: { currentUser?: IUser }) { if (ret.hasOwnProperty('_id') && ret._id !== null) { ret._id = ret._id.toString(); } ret.courseAdmin = extractSingleMongoId(ret.courseAdmin); ret.hasAccessKey = false; if (ret.accessKey) { ret.hasAccessKey = true; } if (currentUser !== undefined) { if (doc.populated('teachers') !== undefined) { ret.teachers = doc.teachers.map((user: IUserModel) => user.forUser(currentUser)); } if (doc.populated('students') !== undefined) { ret.students = doc.students.map((user: IUserModel) => user.forUser(currentUser)); } } if (ret.chatRooms) { ret.chatRooms = ret.chatRooms.map(extractSingleMongoId); } } } } ); courseSchema.pre('save', async function () { const course = <ICourseModel>this; if (this.isNew) { const chatRoom: IChatRoomModel = await ChatRoom.create({ name: 'General', description: 'This is a general chat for the course ' + course.name, room: { roomType: 'Course', roomFor: course } }); course.chatRooms.push(chatRoom._id); Object.assign(this, course); } }); // Cascade delete courseSchema.pre('remove', async function () { const localCourse = <ICourseModel><any>this; try { const dic = await Directory.findById(localCourse.media); if (dic) { await dic.remove(); } for (const lec of localCourse.lectures) { const lecDoc = await Lecture.findById(lec); await lecDoc.remove(); } if (localCourse.image) { const picture: any = await Picture.findById(localCourse.image); await picture.remove(); } } catch (error) { throw new Error('Delete Error: ' + error.toString()); } }); courseSchema.methods.exportJSON = async function (sanitize: boolean = true, onlyBasicData: boolean = false) { const obj = this.toObject(); // remove unwanted informations // mongo properties delete obj._id; delete obj.createdAt; delete obj.__v; delete obj.updatedAt; // custom properties if (sanitize) { delete obj.accessKey; delete obj.active; delete obj.whitelist; delete obj.students; delete obj.courseAdmin; delete obj.teachers; delete obj.media; delete obj.chatRooms; delete obj.freeTextStyle; } if (onlyBasicData) { delete obj.id; delete obj.hasAccessKey; return obj; } // "populate" lectures const lectures: Array<mongoose.Types.ObjectId> = obj.lectures; obj.lectures = []; for (const lectureId of lectures) { const lecture: ILectureModel = await Lecture.findById(lectureId); if (lecture) { const lectureExport = await lecture.exportJSON(); obj.lectures.push(lectureExport); } } if (obj.image) { const imageId: mongoose.Types.ObjectId = obj.image; obj.image = await Picture.findById(imageId); } return obj; }; courseSchema.statics.importJSON = async function (course: ICourse, admin: IUser, active: boolean) { // set Admin course.courseAdmin = admin; // course shouldn't be visible for students after import // until active flag is explicitly set (e.g. fixtures) course.active = (active === true); // importTest lectures const lectures: Array<ILecture> = course.lectures; course.lectures = []; try { // Need to disabled this rule because we can't export 'Course' BEFORE this function-declaration // tslint:disable:no-use-before-declare const origName = course.name; let isCourseDuplicated = false; let i = 0; do { // 1. Duplicate -> 'name (copy)', 2. Duplicate -> 'name (copy 2)', 3. Duplicate -> 'name (copy 3)', ... course.name = origName + ((i > 0) ? ' (copy' + ((i > 1) ? ' ' + i : '') + ')' : ''); isCourseDuplicated = (await Course.findOne({name: course.name})) !== null; i++; } while (isCourseDuplicated); const savedCourse = await new Course(course).save(); for (const lecture of lectures) { await Lecture.schema.statics.importJSON(lecture, savedCourse._id); } const newCourse: ICourseModel = await Course.findById(savedCourse._id); return newCourse.toObject(); // tslint:enable:no-use-before-declare } catch (err) { const newError = new InternalServerError('Failed to import course'); newError.stack += '\nCaused by: ' + err.message + '\n' + err.stack; throw newError; } }; courseSchema.statics.exportPersonalData = async function (user: IUser) { const conditions: any = {}; conditions.$or = []; conditions.$or.push({students: user._id}); conditions.$or.push({teachers: user._id}); conditions.$or.push({courseAdmin: user._id}); const courses = await Course.find(conditions, 'name description -_id'); return Promise.all(courses.map(async (course: ICourseModel) => { return await course.exportJSON(true, true); })); }; courseSchema.statics.changeCourseAdminFromUser = async function (userFrom: IUser, userTo: IUser) { return Course.updateMany({courseAdmin: userFrom._id}, {courseAdmin: userTo._id}); }; courseSchema.methods.checkPrivileges = function (user: IUser): ICourseUserPrivileges { const {userIsAdmin, ...userIs} = User.checkPrivileges(user); const userId = extractSingleMongoId(user); const courseAdminId = extractSingleMongoId(this.courseAdmin); const userIsCourseAdmin: boolean = userId === courseAdminId; const userIsCourseTeacher: boolean = this.teachers.some((teacher: IUserModel) => userId === extractSingleMongoId(teacher)); const userIsCourseStudent: boolean = this.students.some((student: IUserModel) => userId === extractSingleMongoId(student)); const userIsCourseMember: boolean = userIsCourseAdmin || userIsCourseTeacher || userIsCourseStudent; const userCanEditCourse: boolean = userIsAdmin || userIsCourseAdmin || userIsCourseTeacher; const userCanViewCourse: boolean = (this.active && userIsCourseStudent) || userCanEditCourse; return { userIsAdmin, ...userIs, courseAdminId, userIsCourseAdmin, userIsCourseTeacher, userIsCourseStudent, userIsCourseMember, userCanEditCourse, userCanViewCourse }; }; /** * Modifies the Course data to be used by the courses dashboard. * * @param {IUser} user * @returns {Promise<ICourseDashboard>} */ courseSchema.methods.forDashboard = async function (user: IUser): Promise<ICourseDashboard> { const { name, active, description, enrollType } = this; const picture = await Picture.findById(this.image); const image = picture && picture.toObject(); const { userCanEditCourse, userCanViewCourse, userIsCourseAdmin, userIsCourseTeacher, userIsCourseMember } = this.checkPrivileges(user); return { // As in ICourse: _id: extractSingleMongoId(this), name, active, description, enrollType, image, // Special properties for the dashboard: userCanEditCourse, userCanViewCourse, userIsCourseAdmin, userIsCourseTeacher, userIsCourseMember }; }; courseSchema.methods.forView = function (user: IUser): ICourseView { const { name, description, courseAdmin, teachers, lectures, chatRooms, freeTextStyle, active } = this; const userCanEditCourse = this.checkPrivileges(user).userCanEditCourse; return { _id: extractSingleMongoId(this), name, description, active, courseAdmin: User.forCourseView(courseAdmin), teachers: teachers.map((teacher: IUser) => User.forCourseView(teacher)), lectures: lectures.map((lecture: any) => lecture.toObject()), chatRooms: chatRooms.map(extractSingleMongoId), freeTextStyle, userCanEditCourse }; }; courseSchema.methods.populateLecturesFor = function (user: IUser) { const isTeacherOrAdmin = (user.role === 'teacher' || user.role === 'admin'); return this.populate({ path: 'lectures', populate: { path: 'units', virtuals: true, match: {$or: [{visible: undefined}, {visible: true}, {visible: !isTeacherOrAdmin}]}, populate: { path: 'progressData', match: {user: {$eq: user._id}} } } }); }; courseSchema.methods.processLecturesFor = async function (user: IUser) { this.lectures = await Promise.all(this.lectures.map(async (lecture: ILectureModel) => { return await lecture.processUnitsFor(user); })); return this; }; Course = mongoose.model<ICourseModel, ICourseMongoose>('Course', courseSchema); export {Course, ICourseModel};
the_stack
import '../test/common-test-setup-karma'; import { descendedFromClass, eventMatchesShortcut, getComputedStyleValue, getEventPath, Modifier, querySelectorAll, shouldSuppress, strToClassName, } from './dom-util'; import {PolymerElement} from '@polymer/polymer/polymer-element'; import {html} from '@polymer/polymer/lib/utils/html-tag'; import * as MockInteractions from '@polymer/iron-test-helpers/mock-interactions'; import {mockPromise, queryAndAssert} from '../test/test-utils'; /** * You might think that instead of passing in the callback with assertions as a * parameter that you could as well just `await keyEventOn()` and *then* run * your assertions. But at that point the event is not "hot" anymore, so most * likely you want to assert stuff about the event within the callback * parameter. */ function keyEventOn( el: HTMLElement, callback: (e: KeyboardEvent) => void, keyCode = 75, key = 'k' ): Promise<KeyboardEvent> { const promise = mockPromise<KeyboardEvent>(); el.addEventListener('keydown', (e: KeyboardEvent) => { callback(e); promise.resolve(e); }); MockInteractions.keyDownOn(el, keyCode, null, key); return promise; } class TestEle extends PolymerElement { static get is() { return 'dom-util-test-element'; } static get template() { return html` <div> <div class="a"> <div class="b"> <div class="c"></div> </div> <span class="ss"></span> </div> <span class="ss"></span> </div> `; } } customElements.define(TestEle.is, TestEle); const basicFixture = fixtureFromTemplate(html` <div id="test" class="a b c"> <a class="testBtn" style="color:red;"></a> <dom-util-test-element></dom-util-test-element> <span class="ss"></span> </div> `); suite('dom-util tests', () => { suite('getEventPath', () => { test('empty event', () => { assert.equal(getEventPath(), ''); assert.equal(getEventPath(undefined), ''); assert.equal(getEventPath(new MouseEvent('click')), ''); }); test('event with fake path', () => { assert.equal(getEventPath(new MouseEvent('click')), ''); const dd = document.createElement('dd'); assert.equal( getEventPath({...new MouseEvent('click'), composedPath: () => [dd]}), 'dd' ); }); test('event with fake complicated path', () => { const dd = document.createElement('dd'); dd.setAttribute('id', 'test'); dd.className = 'a b'; const divNode = document.createElement('DIV'); divNode.id = 'test2'; divNode.className = 'a b c'; assert.equal( getEventPath({ ...new MouseEvent('click'), composedPath: () => [dd, divNode], }), 'div#test2.a.b.c>dd#test.a.b' ); }); test('event with fake target', () => { const fakeTargetParent1 = document.createElement('dd'); fakeTargetParent1.setAttribute('id', 'test'); fakeTargetParent1.className = 'a b'; const fakeTargetParent2 = document.createElement('DIV'); fakeTargetParent2.id = 'test2'; fakeTargetParent2.className = 'a b c'; fakeTargetParent2.appendChild(fakeTargetParent1); const fakeTarget = document.createElement('SPAN'); fakeTargetParent1.appendChild(fakeTarget); assert.equal( getEventPath({ ...new MouseEvent('click'), composedPath: () => [], target: fakeTarget, }), 'div#test2.a.b.c>dd#test.a.b>span' ); }); test('event with real click', () => { const element = basicFixture.instantiate() as HTMLElement; const aLink = queryAndAssert(element, 'a'); let path; aLink.addEventListener('click', (e: Event) => { path = getEventPath(e as MouseEvent); }); MockInteractions.click(aLink); assert.equal( path, `html>body>test-fixture#${basicFixture.fixtureId}>` + 'div#test.a.b.c>a.testBtn' ); }); }); suite('querySelector and querySelectorAll', () => { test('query cross shadow dom', () => { const element = basicFixture.instantiate() as HTMLElement; const theFirstEl = queryAndAssert(element, '.ss'); const allEls = querySelectorAll(element, '.ss'); assert.equal(allEls.length, 3); assert.equal(theFirstEl, allEls[0]); }); }); suite('getComputedStyleValue', () => { test('color style', () => { const element = basicFixture.instantiate() as HTMLElement; const testBtn = queryAndAssert(element, '.testBtn'); assert.equal(getComputedStyleValue('color', testBtn), 'rgb(255, 0, 0)'); }); }); suite('descendedFromClass', () => { test('basic tests', () => { const element = basicFixture.instantiate() as HTMLElement; const testEl = queryAndAssert(element, 'dom-util-test-element'); // .c is a child of .a and not vice versa. assert.isTrue(descendedFromClass(queryAndAssert(testEl, '.c'), 'a')); assert.isFalse(descendedFromClass(queryAndAssert(testEl, '.a'), 'c')); // Stops at stop element. assert.isFalse( descendedFromClass( queryAndAssert(testEl, '.c'), 'a', queryAndAssert(testEl, '.b') ) ); }); }); suite('strToClassName', () => { test('basic tests', () => { assert.equal(strToClassName(''), 'generated_'); assert.equal(strToClassName('11'), 'generated_11'); assert.equal(strToClassName('0.123'), 'generated_0_123'); assert.equal(strToClassName('0.123', 'prefix_'), 'prefix_0_123'); assert.equal(strToClassName('0>123', 'prefix_'), 'prefix_0_123'); assert.equal(strToClassName('0<123', 'prefix_'), 'prefix_0_123'); assert.equal(strToClassName('0+1+23', 'prefix_'), 'prefix_0_1_23'); }); }); suite('eventMatchesShortcut', () => { test('basic tests', () => { const a = new KeyboardEvent('keydown', {key: 'a'}); const b = new KeyboardEvent('keydown', {key: 'B'}); assert.isTrue(eventMatchesShortcut(a, {key: 'a'})); assert.isFalse(eventMatchesShortcut(a, {key: 'B'})); assert.isFalse(eventMatchesShortcut(b, {key: 'a'})); assert.isTrue(eventMatchesShortcut(b, {key: 'B'})); }); test('check modifiers for a', () => { const e = new KeyboardEvent('keydown', {key: 'a'}); const s = {key: 'a'}; assert.isTrue(eventMatchesShortcut(e, s)); const eAlt = new KeyboardEvent('keydown', {key: 'a', altKey: true}); const sAlt = {key: 'a', modifiers: [Modifier.ALT_KEY]}; assert.isFalse(eventMatchesShortcut(eAlt, s)); assert.isFalse(eventMatchesShortcut(e, sAlt)); const eCtrl = new KeyboardEvent('keydown', {key: 'a', ctrlKey: true}); const sCtrl = {key: 'a', modifiers: [Modifier.CTRL_KEY]}; assert.isFalse(eventMatchesShortcut(eCtrl, s)); assert.isFalse(eventMatchesShortcut(e, sCtrl)); const eMeta = new KeyboardEvent('keydown', {key: 'a', metaKey: true}); const sMeta = {key: 'a', modifiers: [Modifier.META_KEY]}; assert.isFalse(eventMatchesShortcut(eMeta, s)); assert.isFalse(eventMatchesShortcut(e, sMeta)); // Do NOT check SHIFT for alphanum keys. const eShift = new KeyboardEvent('keydown', {key: 'a', shiftKey: true}); const sShift = {key: 'a', modifiers: [Modifier.SHIFT_KEY]}; assert.isTrue(eventMatchesShortcut(eShift, s)); assert.isTrue(eventMatchesShortcut(e, sShift)); }); test('check modifiers for Enter', () => { const e = new KeyboardEvent('keydown', {key: 'Enter'}); const s = {key: 'Enter'}; assert.isTrue(eventMatchesShortcut(e, s)); const eAlt = new KeyboardEvent('keydown', {key: 'Enter', altKey: true}); const sAlt = {key: 'Enter', modifiers: [Modifier.ALT_KEY]}; assert.isFalse(eventMatchesShortcut(eAlt, s)); assert.isFalse(eventMatchesShortcut(e, sAlt)); const eCtrl = new KeyboardEvent('keydown', {key: 'Enter', ctrlKey: true}); const sCtrl = {key: 'Enter', modifiers: [Modifier.CTRL_KEY]}; assert.isFalse(eventMatchesShortcut(eCtrl, s)); assert.isFalse(eventMatchesShortcut(e, sCtrl)); const eMeta = new KeyboardEvent('keydown', {key: 'Enter', metaKey: true}); const sMeta = {key: 'Enter', modifiers: [Modifier.META_KEY]}; assert.isFalse(eventMatchesShortcut(eMeta, s)); assert.isFalse(eventMatchesShortcut(e, sMeta)); const eShift = new KeyboardEvent('keydown', { key: 'Enter', shiftKey: true, }); const sShift = {key: 'Enter', modifiers: [Modifier.SHIFT_KEY]}; assert.isFalse(eventMatchesShortcut(eShift, s)); assert.isFalse(eventMatchesShortcut(e, sShift)); }); test('check modifiers for [', () => { const e = new KeyboardEvent('keydown', {key: '['}); const s = {key: '['}; assert.isTrue(eventMatchesShortcut(e, s)); const eCtrl = new KeyboardEvent('keydown', {key: '[', ctrlKey: true}); const sCtrl = {key: '[', modifiers: [Modifier.CTRL_KEY]}; assert.isFalse(eventMatchesShortcut(eCtrl, s)); assert.isFalse(eventMatchesShortcut(e, sCtrl)); const eMeta = new KeyboardEvent('keydown', {key: '[', metaKey: true}); const sMeta = {key: '[', modifiers: [Modifier.META_KEY]}; assert.isFalse(eventMatchesShortcut(eMeta, s)); assert.isFalse(eventMatchesShortcut(e, sMeta)); // Do NOT check SHIFT and ALT for special chars like [. const eAlt = new KeyboardEvent('keydown', {key: '[', altKey: true}); const sAlt = {key: '[', modifiers: [Modifier.ALT_KEY]}; assert.isTrue(eventMatchesShortcut(eAlt, s)); assert.isTrue(eventMatchesShortcut(e, sAlt)); const eShift = new KeyboardEvent('keydown', { key: '[', shiftKey: true, }); const sShift = {key: '[', modifiers: [Modifier.SHIFT_KEY]}; assert.isTrue(eventMatchesShortcut(eShift, s)); assert.isTrue(eventMatchesShortcut(e, sShift)); }); }); suite('shouldSuppress', () => { test('do not suppress shortcut event from <div>', async () => { await keyEventOn(document.createElement('div'), e => { assert.isFalse(shouldSuppress(e)); }); }); test('suppress shortcut event from <input>', async () => { await keyEventOn(document.createElement('input'), e => { assert.isTrue(shouldSuppress(e)); }); }); test('suppress shortcut event from <textarea>', async () => { await keyEventOn(document.createElement('textarea'), e => { assert.isTrue(shouldSuppress(e)); }); }); test('do not suppress shortcut event from checkbox <input>', async () => { const inputEl = document.createElement('input'); inputEl.setAttribute('type', 'checkbox'); await keyEventOn(inputEl, e => { assert.isFalse(shouldSuppress(e)); }); }); test('suppress shortcut event from children of <gr-overlay>', async () => { const overlay = document.createElement('gr-overlay'); const div = document.createElement('div'); overlay.appendChild(div); await keyEventOn(div, e => { assert.isTrue(shouldSuppress(e)); }); }); test('suppress "enter" shortcut event from <gr-button>', async () => { await keyEventOn( document.createElement('gr-button'), e => assert.isTrue(shouldSuppress(e)), 13, 'enter' ); }); test('suppress "enter" shortcut event from <a>', async () => { await keyEventOn(document.createElement('a'), e => { assert.isFalse(shouldSuppress(e)); }); await keyEventOn( document.createElement('a'), e => assert.isTrue(shouldSuppress(e)), 13, 'enter' ); }); }); });
the_stack
module RW.TextureEditor { export interface MaterialScope extends ng.IScope { //material: BABYLON.StandardMaterial; materialDefinition: MaterialDefinition; //sectionNames: string[]; //materialSections: { [section: string]: MaterialDefinitionSection }; updateTexture(type): void; mirrorEnabled: boolean; } /* TODO * Fix the alpha problem * Multi Material Javascript export. */ export class MaterialController { public static $inject = [ '$scope', '$modal', '$http', '$timeout', 'canvasService', 'materialService' ]; public multiMaterialPosition: number; public numberOfMaterials: number; public isMultiMaterial: boolean; public materialId: string; public alerts = []; public progress; private _object: BABYLON.AbstractMesh; public static ServerUrl: string = ""; constructor( private $scope: MaterialScope, private $modal: any /* modal from angular bootstrap ui */, private $http: ng.IHttpService, private $timeout: ng.ITimeoutService, private canvasService: CanvasService, private materialService:MaterialService ) { this.isMultiMaterial = false; this.multiMaterialPosition = 0; this.numberOfMaterials = 0; this.progress = { enabled: false, value: 0, text:"" } $scope.updateTexture = (type) => { $scope.$apply(() => { $scope.materialDefinition.materialSections[type].texture.canvasUpdated(); }); } $scope.$on("objectChanged", this.afterObjectChanged); } public afterObjectChanged = (event: ng.IAngularEvent, object: BABYLON.AbstractMesh) => { //if object has no submeshes, do nothing. It is a null parent object. Who needs it?... if (object.subMeshes == null) return; //If an object has more than one subMesh, it means I have already created a multi material object for it. this._object = object; this.isMultiMaterial = object.subMeshes.length > 1; var force = false; if (this.isMultiMaterial) { this.numberOfMaterials = (<BABYLON.MultiMaterial> object.material).subMaterials.length; this.multiMaterialPosition = 0; force = true; } else { this.numberOfMaterials = 0; this.multiMaterialPosition = -1; } //force should be false, it is however true while a multi-material object needs to be always initialized. this.initMaterial(force, () => { this.$timeout(() => { this.$scope.$apply(); }) }, this.multiMaterialPosition); } public initMaterial(forceNew: boolean, onSuccess: () => void, position?:number) { //making sure it is undefined if it is not multi material. if (this.isMultiMaterial) { this.$scope.materialDefinition = this.materialService.initMaterialSections(this._object, forceNew, onSuccess, position); } else { this.$scope.materialDefinition = this.materialService.initMaterialSections(this._object, forceNew, onSuccess); } } public setPlaneForMirror() { console.log("setPlane"); var pointsArray: Array<BABYLON.Vector3> = []; //TODO maybe find a different way of computing the plane? trying to avoid getting the object in the constructor. var meshWorldMatrix = this._object.computeWorldMatrix(); var verticesPosition = this._object.getVerticesData(BABYLON.VertexBuffer.PositionKind); //handle submeshes var offset = 0; if (this.isMultiMaterial) { offset = this._object.subMeshes[this.multiMaterialPosition].indexStart } for (var i = 0; i < 3; i++) { var v = this._object.getIndices()[offset + i]; pointsArray.push(BABYLON.Vector3.TransformCoordinates(BABYLON.Vector3.FromArray(verticesPosition, v*3), meshWorldMatrix)); } var plane = BABYLON.Plane.FromPoints(pointsArray[0], pointsArray[1], pointsArray[2]); this.$scope.materialDefinition.materialSections["reflection"].texture.setMirrorPlane(plane); } public exportMaterial() { var modalInstance = this.$modal.open({ templateUrl: 'materialExport.html', controller: 'MaterialExportModalController', size: "lg", resolve: { materialDefinitions: () => { return this.materialService.getMaterialDefinisionsArray(this._object.id); } } }); } public updateProgress(enabled: boolean, text?: string, value?: number) { this.progress.enabled = enabled; this.progress.text = text; this.progress.value = value; } public saveMaterial() { //todo get ID from server this.updateProgress(true, "Saving...", 20); this.$http.get(MaterialController.ServerUrl + "/getNextId").success((idObject) => { var id = idObject['id']; var material = this.materialService.exportAsBabylonScene(id, this.$scope.materialDefinition); //upload material object this.updateProgress(true, "Received ID...", 40); this.$http.post(MaterialController.ServerUrl + "/materials", material).success((worked) => { if (!worked['success']) { this.alerts.push({ type: 'danger', msg: 'Error uploading to server.' }); this.updateProgress(false); return; } //how many textures should be uploaded? var textureSections = []; this.$scope.materialDefinition.sectionNames.forEach((sectionName) => { if (this.$scope.materialDefinition.materialSections[sectionName].hasTexture && this.$scope.materialDefinition.materialSections[sectionName].texture.enabled()) { var textureDefinition = this.$scope.materialDefinition.materialSections[sectionName].texture; if (textureDefinition.babylonTextureType == BabylonTextureType.NORMAL) { textureSections.push(sectionName); } } }); if (textureSections.length == 0) { this.updateProgress(false); this.alerts.push({ type: 'success', msg: "Material stored. " }); this.$timeout(() => { this.alerts.pop(); }, 5000); //update the UI this.materialId = id; } else { var texturesUploaded = 0; this.updateProgress(true, "Uploading textures...", 50); textureSections.forEach((sectionName) => { if (this.$scope.materialDefinition.materialSections[sectionName].hasTexture && this.$scope.materialDefinition.materialSections[sectionName].texture.enabled()) { var textureDefinition = this.$scope.materialDefinition.materialSections[sectionName].texture; if (textureDefinition.babylonTextureType == BabylonTextureType.NORMAL) { textureDefinition.getCanvasImageUrls((urls) => { //if (urls.length == 1) { //textures will be uploaded async. The user should be notified about it! var obj = {}; obj[id + '_' + textureDefinition.name + textureDefinition.getExtension()] = urls[0]; this.$http.post(MaterialController.ServerUrl + "/textures", obj).success((worked) => { if (!worked['success']) { this.alerts.push({ type: 'danger', msg: "error uploading the texture " + textureDefinition.name }); this.updateProgress(false); } texturesUploaded++; this.updateProgress(true, "Uploading textures...", 50 + (texturesUploaded * 10)); if (texturesUploaded == textureSections.length) { this.updateProgress(false); this.alerts.push({ type: 'success', msg: "Material stored." }); this.$timeout(() => { this.alerts.pop(); }, 5000); this.materialId = id; } }); //} }); } } }); } }); }); } public loadMaterial() { if (!this.materialId) { this.alerts.push({ type: 'warning', msg: "Please enter an ID" }); return; } this.updateProgress(true, "Loading material...", 30); //babylon doesn't check for 404 for some reason, doing it on my own. File will be loaded twice! TODO fix it in BABYLON! this.$http.get(MaterialController.ServerUrl + "/materials/" + this.materialId + ".babylon").error(() => { this.alerts.push({ type: 'danger', msg: "Material could not be loaded. Check the ID." }); this.updateProgress(false); }).success(() => { this.canvasService.appendMaterial(this.materialId, () => { var material: BABYLON.Material = this.canvasService.getMaterial(this.materialId); var success = () => { if (this.alerts.length < 1) this.alerts.push({ type: 'success', msg: "Material loaded." }); this.$timeout(() => { this.alerts.pop(); }, 5000); this.updateProgress(false); this.$scope.$apply(); } this.$timeout(() => { if (this.isMultiMaterial) { (<BABYLON.MultiMaterial> this._object.material).subMaterials[this.multiMaterialPosition] = material; this.initMaterial(true, success, this.multiMaterialPosition); } else { this._object.material = material; this.initMaterial(true, success); } }); }, (progress) => { this.updateProgress(true, "Loading material...", 60); }, (error) => { console.log(error); this.alerts.push({ type: 'danger', msg: "Material could not be loaded. Check the ID." }); this.updateProgress(false); }); }); } public closeAlert(index) { this.alerts.splice(index, 1); } //for ng-repeat public getMaterialIndices = () => { return new Array(this.numberOfMaterials); } } }
the_stack
import assert from 'assert'; import config from './config'; import * as schemaObjects from '../helper/schema-objects'; import { addRxPlugin, randomCouchString, getPseudoSchemaForVersion, getFromMapOrThrow, getNewestSequence, lastOfArray, writeSingle, blobBufferUtil, flatClone, MangoQuery, PouchDBInstance } from '../../plugins/core'; import { getRxStoragePouch, addCustomEventsPluginToPouch, getCustomEventEmitterByPouch, PouchDB } from '../../plugins/pouchdb'; import { RxDBKeyCompressionPlugin } from '../../plugins/key-compression'; addRxPlugin(RxDBKeyCompressionPlugin); import { RxDBValidatePlugin } from '../../plugins/validate'; addRxPlugin(RxDBValidatePlugin); import { RxDBQueryBuilderPlugin } from '../../plugins/query-builder'; import { randomString, wait, waitUntil } from 'async-test-util'; import { RxDocumentData, RxDocumentWriteData, RxLocalDocumentData, RxStorageChangeEvent } from '../../src/types'; addRxPlugin(RxDBQueryBuilderPlugin); declare type TestDocType = { key: string; value: string; }; config.parallel('rx-storage-pouchdb.test.js', () => { describe('custom events plugin', () => { it('should not throw when added to pouch', () => { addCustomEventsPluginToPouch(); }); it('should emit data on bulkDocs', async () => { const pouch: PouchDBInstance = new PouchDB( randomCouchString(12), { adapter: 'memory' } ) as any; const emitted: any[] = []; const sub = getCustomEventEmitterByPouch(pouch).subject.subscribe(ev => { emitted.push(ev); }); await pouch.bulkDocs([{ _id: 'foo', val: 'bar' }], { // add custom data to the options which should be passed through custom: { foo: 'bar' } } as any); await waitUntil(() => emitted.length === 1); const first = emitted[0]; assert.deepStrictEqual( first.writeOptions.custom, { foo: 'bar' } ); sub.unsubscribe(); }); }); describe('RxStorageInstance', () => { describe('.bulkWrite()', () => { it('should write the document', async () => { const storageInstance = await getRxStoragePouch('memory').createStorageInstance<TestDocType>({ databaseName: randomCouchString(12), collectionName: randomCouchString(12), schema: getPseudoSchemaForVersion(0, 'key'), options: {} }); const writeResponse = await storageInstance.bulkWrite( [{ document: { key: 'foobar', value: 'barfoo1', _attachments: {} } }] ); assert.strictEqual(writeResponse.error.size, 0); const first = getFromMapOrThrow(writeResponse.success, 'foobar'); assert.strictEqual(first.key, 'foobar'); assert.strictEqual(first.value, 'barfoo1'); assert.ok(first._rev); storageInstance.close(); }); it('should error on conflict', async () => { const storageInstance = await getRxStoragePouch('memory').createStorageInstance<TestDocType>({ databaseName: randomCouchString(12), collectionName: randomCouchString(12), schema: getPseudoSchemaForVersion(0, 'key'), options: {} }); const writeData: RxDocumentWriteData<TestDocType> = { key: 'foobar', value: 'barfoo', _attachments: {} }; await storageInstance.bulkWrite( [{ document: writeData }] ); const writeResponse = await storageInstance.bulkWrite( [{ document: writeData }] ); assert.strictEqual(writeResponse.success.size, 0); const first = getFromMapOrThrow(writeResponse.error, 'foobar'); assert.strictEqual(first.status, 409); assert.strictEqual(first.documentId, 'foobar'); assert.ok(first.writeRow); storageInstance.close(); }); }); describe('.bulkAddRevisions()', () => { it('should add the revisions for new documents', async () => { const storageInstance = await getRxStoragePouch('memory').createStorageInstance<TestDocType>({ databaseName: randomCouchString(12), collectionName: randomCouchString(12), schema: getPseudoSchemaForVersion(0, 'key'), options: {} }); const writeData: RxDocumentData<TestDocType> = { key: 'foobar', value: 'barfoo', _attachments: {}, _rev: '1-a723631364fbfa906c5ffa8203ac9725' }; await storageInstance.bulkAddRevisions( [ writeData ] ); const found = await storageInstance.findDocumentsById([writeData.key], false); const doc = getFromMapOrThrow(found, writeData.key); assert.ok(doc); assert.strictEqual(doc.value, writeData.value); // because overwrite=true, the _rev from the input data must be used. assert.strictEqual(doc._rev, writeData._rev); storageInstance.close(); }); }); describe('.getSortComparator()', () => { it('should sort in the correct order', async () => { const storageInstance = await getRxStoragePouch('memory').createStorageInstance<TestDocType>({ databaseName: randomCouchString(12), collectionName: randomCouchString(12), schema: getPseudoSchemaForVersion(0, '_id' as any), options: {} }); const query: MangoQuery = { selector: {}, limit: 1000, sort: [ { age: 'asc' } ] }; const comparator = storageInstance.getSortComparator( query ); const doc1: any = schemaObjects.human(); doc1._id = 'aa'; doc1.age = 1; const doc2: any = schemaObjects.human(); doc2._id = 'bb'; doc2.age = 100; // should sort in the correct order assert.deepStrictEqual( [doc1, doc2], [doc1, doc2].sort(comparator) ); storageInstance.close(); }); }); describe('.getQueryMatcher()', () => { it('should match the right docs', async () => { const storageInstance = await getRxStoragePouch('memory').createStorageInstance<TestDocType>({ databaseName: randomCouchString(12), collectionName: randomCouchString(12), schema: getPseudoSchemaForVersion(0, '_id' as any), options: {} }); const query: MangoQuery = { selector: { age: { $gt: 10, $ne: 50 } } }; const queryMatcher = storageInstance.getQueryMatcher( query ); const doc1: any = schemaObjects.human(); doc1._id = 'aa'; doc1.age = 1; const doc2: any = schemaObjects.human(); doc2._id = 'bb'; doc2.age = 100; assert.strictEqual(queryMatcher(doc1), false); assert.strictEqual(queryMatcher(doc2), true); storageInstance.close(); }); }); describe('.query()', () => { it('should find all documents', async () => { const storageInstance = await getRxStoragePouch('memory').createStorageInstance<{ key: string; value: string; }>({ databaseName: randomCouchString(12), collectionName: randomCouchString(12), schema: getPseudoSchemaForVersion(0, 'key'), options: {} }); const writeData = { key: 'foobar', value: 'barfoo', _attachments: {} }; await storageInstance.bulkWrite( [{ document: writeData }] ); const preparedQuery = storageInstance.prepareQuery({ selector: {} }); const allDocs = await storageInstance.query(preparedQuery); const first = allDocs.documents[0]; assert.ok(first); assert.strictEqual(first.value, 'barfoo'); storageInstance.close(); }); }); describe('.findDocumentsById()', () => { it('should find the documents', async () => { const storageInstance = await getRxStoragePouch('memory').createStorageInstance<TestDocType>({ databaseName: randomCouchString(12), collectionName: randomCouchString(12), schema: getPseudoSchemaForVersion(0, 'key'), options: {} }); await storageInstance.bulkWrite( [{ document: { key: 'foobar', value: 'barfoo', _attachments: {} } }] ); const found = await storageInstance.findDocumentsById(['foobar'], false); assert.ok(found.get('foobar')); storageInstance.close(); }); it('should find deleted documents', async () => { const storageInstance = await getRxStoragePouch('memory').createStorageInstance<TestDocType>({ databaseName: randomCouchString(12), collectionName: randomCouchString(12), schema: getPseudoSchemaForVersion(0, 'key'), options: {} }); const insertResult = await storageInstance.bulkWrite( [{ document: { key: 'foobar', value: 'barfoo', _attachments: {} } }] ); const previous = getFromMapOrThrow(insertResult.success, 'foobar'); await storageInstance.bulkWrite( [{ previous, document: { key: 'foobar', value: 'barfoo2', _deleted: true, _attachments: {} } }] ); const found = await storageInstance.findDocumentsById(['foobar'], true); const foundDeleted = getFromMapOrThrow(found, 'foobar'); // even on deleted documents, we must get the other properties. assert.strictEqual(foundDeleted.value, 'barfoo2'); assert.strictEqual(foundDeleted._deleted, true); storageInstance.close(); }); }); describe('.getChangedDocuments()', () => { it('should get the correct changes', async () => { const storageInstance = await getRxStoragePouch('memory').createStorageInstance<TestDocType>({ databaseName: randomCouchString(12), collectionName: randomCouchString(12), schema: getPseudoSchemaForVersion(0, 'key'), options: { auto_compaction: false } }); let previous: RxDocumentData<TestDocType> | undefined; const writeData = { key: 'foobar', value: 'one', _attachments: {}, _rev: undefined as any, _deleted: false }; // insert const firstWriteResult = await storageInstance.bulkWrite([{ previous, document: writeData }]); previous = getFromMapOrThrow(firstWriteResult.success, writeData.key); const changesAfterWrite = await storageInstance.getChangedDocuments({ order: 'asc', startSequence: 0 }); const firstChangeAfterWrite = changesAfterWrite.changedDocuments[0]; if (!firstChangeAfterWrite) { throw new Error('missing change'); } assert.ok(firstChangeAfterWrite.id === 'foobar'); assert.strictEqual(firstChangeAfterWrite.sequence, 1); // update writeData.value = 'two'; const updateResult = await storageInstance.bulkWrite([{ previous, document: writeData }]); previous = getFromMapOrThrow(updateResult.success, writeData.key); const changesAfterUpdate = await storageInstance.getChangedDocuments({ order: 'asc', startSequence: 0 }); const firstChangeAfterUpdate = changesAfterUpdate.changedDocuments[0]; if (!firstChangeAfterUpdate) { throw new Error('missing change'); } assert.ok(firstChangeAfterUpdate.id === 'foobar'); assert.strictEqual(firstChangeAfterUpdate.sequence, 2); // delete writeData._deleted = true; await storageInstance.bulkWrite([{ previous, document: writeData }]); const changesAfterDelete = await storageInstance.getChangedDocuments({ order: 'asc', startSequence: 0 }); const firstChangeAfterDelete = changesAfterDelete.changedDocuments[0]; if (!firstChangeAfterDelete) { throw new Error('missing change'); } assert.ok(firstChangeAfterDelete.id === 'foobar'); assert.strictEqual(firstChangeAfterDelete.sequence, 3); assert.strictEqual(changesAfterDelete.lastSequence, 3); storageInstance.close(); }); it('should emit the correct change when bulkAddRevisions is used and then deleted', async () => { const storageInstance = await getRxStoragePouch('memory').createStorageInstance<TestDocType>({ databaseName: randomCouchString(12), collectionName: randomCouchString(12), schema: getPseudoSchemaForVersion(0, 'key'), options: {} }); const key = 'foobar'; const insertResult = await storageInstance.bulkWrite([{ document: { key, _attachments: {}, value: 'myValue' } }]); const previous = getFromMapOrThrow(insertResult.success, key); // overwrite via set revisision const customRev = '2-5373c7dc85e8705456beaf68ae041110'; await storageInstance.bulkAddRevisions([ { key, _attachments: {}, value: 'myValueRev', _rev: customRev } ]); previous._rev = customRev; await storageInstance.bulkWrite([{ previous, document: { key, _attachments: {}, value: 'myValue', _deleted: true } }]); await storageInstance.internals.pouch.changes({ live: false, limit: 10, include_docs: true, since: 2 }); const changesAfterDelete = await storageInstance.getChangedDocuments({ order: 'asc', startSequence: 1 }); const firstChangeAfterDelete = changesAfterDelete.changedDocuments[0]; if (!firstChangeAfterDelete) { throw new Error('missing change'); } assert.strictEqual(firstChangeAfterDelete.id, key); storageInstance.close(); }); }); describe('.changeStream()', () => { it('should emit exactly one event on write', async () => { const storageInstance = await getRxStoragePouch('memory').createStorageInstance<TestDocType>({ databaseName: randomCouchString(12), collectionName: randomCouchString(12), schema: getPseudoSchemaForVersion(0, 'key'), options: { auto_compaction: false } }); const emitted: RxStorageChangeEvent<TestDocType>[] = []; const sub = storageInstance.changeStream().subscribe(x => { emitted.push(x); }); const writeData = { key: 'foobar', value: 'one', _rev: undefined as any, _deleted: false, _attachments: {} }; // insert await storageInstance.bulkWrite([{ document: writeData }]); await wait(100); assert.strictEqual(emitted.length, 1); sub.unsubscribe(); storageInstance.close(); }); it('should emit all events', async () => { const storageInstance = await getRxStoragePouch('memory').createStorageInstance<TestDocType>({ databaseName: randomCouchString(12), collectionName: randomCouchString(12), schema: getPseudoSchemaForVersion(0, 'key'), options: { auto_compaction: false } }); const emitted: RxStorageChangeEvent<TestDocType>[] = []; const sub = storageInstance.changeStream().subscribe(x => { emitted.push(x); }); let previous: RxDocumentData<TestDocType> | undefined; const writeData = { key: 'foobar', value: 'one', _rev: undefined as any, _deleted: false, _attachments: {} }; // insert const firstWriteResult = await storageInstance.bulkWrite([{ previous, document: writeData }]); previous = getFromMapOrThrow(firstWriteResult.success, writeData.key); // update const updateResult = await storageInstance.bulkWrite([{ previous, document: writeData }]); previous = getFromMapOrThrow(updateResult.success, writeData.key); // delete writeData._deleted = true; await storageInstance.bulkWrite([{ previous, document: writeData }]); await waitUntil(() => emitted.length === 3); const last = lastOfArray(emitted); if (!last) { throw new Error('missing last event'); } assert.strictEqual(last.change.operation, 'DELETE'); assert.ok(last.change.previous); sub.unsubscribe(); storageInstance.close(); }); it('should emit changes when bulkAddRevisions() is used to set the newest revision', async () => { const storageInstance = await getRxStoragePouch('memory').createStorageInstance<TestDocType>({ databaseName: randomCouchString(12), collectionName: randomCouchString(12), schema: getPseudoSchemaForVersion(0, 'key'), options: { auto_compaction: false } }); const emitted: RxStorageChangeEvent<TestDocType>[] = []; const sub = storageInstance.changeStream().subscribe(x => emitted.push(x)); const writeData: RxDocumentWriteData<TestDocType> = { key: 'foobar', value: 'one', _deleted: false, _attachments: {} }; // make normal insert await writeSingle( storageInstance, { document: writeData } ); // insert via addRevision await storageInstance.bulkAddRevisions( [{ key: 'foobar', value: 'two', /** * TODO when _deleted:false, * pouchdb will emit an event directly from the changes stream, * but when deleted: true, it does not and we must emit and event by our own. * This must be reported to the pouchdb repo. */ _deleted: true, _rev: '2-a723631364fbfa906c5ffa8203ac9725', _attachments: {} }] ); await waitUntil(() => emitted.length === 2); const lastEvent = emitted.pop(); if (!lastEvent) { throw new Error('last event missing'); } assert.strictEqual( lastEvent.change.operation, 'DELETE' ); sub.unsubscribe(); storageInstance.close(); }); it('should emit the correct events when a deleted document is overwritten with another deleted via bulkAddRevisions()', async () => { const storageInstance = await getRxStoragePouch('memory').createStorageInstance<TestDocType>({ databaseName: randomCouchString(12), collectionName: randomCouchString(12), schema: getPseudoSchemaForVersion(0, 'key'), options: {} }); const id = 'foobar'; const emitted: RxStorageChangeEvent<RxDocumentData<TestDocType>>[] = []; const sub = storageInstance.changeStream().subscribe(cE => emitted.push(cE)); const preparedQuery = storageInstance.prepareQuery({ selector: {} }); // insert await storageInstance.bulkWrite([{ document: { key: id, value: 'one', _attachments: {} } }]); // insert again via bulkAddRevisions() const bulkInsertAgain = { key: id, value: 'one', _deleted: false, _attachments: {}, _rev: '2-a6e639f1073f75farxdbreplicationgraphql' }; await storageInstance.bulkAddRevisions([bulkInsertAgain]); // delete via bulkWrite() await storageInstance.bulkWrite([{ previous: bulkInsertAgain, document: { key: id, value: 'one', _attachments: {}, _deleted: true } }]); const resultAfterBulkWriteDelete = await storageInstance.query(preparedQuery); assert.strictEqual(resultAfterBulkWriteDelete.documents.length, 0); // delete again via bulkAddRevisions() await storageInstance.bulkAddRevisions([{ key: id, value: 'one', _deleted: true, _attachments: {}, _rev: '4-c4195e76073f75farxdbreplicationgraphql' }]); await wait(1000); assert.strictEqual(emitted.length, 3); assert.ok(emitted[0].change.operation === 'INSERT'); assert.ok(emitted[1].change.operation === 'UPDATE'); assert.ok(emitted[2].change.operation === 'DELETE'); sub.unsubscribe(); storageInstance.close(); }); }); describe('attachments', () => { it('should return the correct attachment object on all document fetch methods', async () => { const storageInstance = await getRxStoragePouch('memory').createStorageInstance<TestDocType>({ databaseName: randomCouchString(12), collectionName: randomCouchString(12), schema: getPseudoSchemaForVersion(0, 'key'), options: { auto_compaction: false } }); const emitted: RxStorageChangeEvent<any>[] = []; const sub = storageInstance.changeStream().subscribe(x => { emitted.push(x); }); const attachmentData = randomString(20); const dataBlobBuffer = blobBufferUtil.createBlobBuffer( attachmentData, 'text/plain' ); const attachmentHash = await getRxStoragePouch('memory').hash(dataBlobBuffer); const writeData: RxDocumentWriteData<TestDocType> = { key: 'foobar', value: 'one', _rev: undefined as any, _deleted: false, _attachments: { foo: { data: dataBlobBuffer, type: 'text/plain' } } }; const writeResult = await writeSingle( storageInstance, { document: writeData } ); await waitUntil(() => emitted.length === 1); assert.strictEqual(writeResult._attachments.foo.type, 'text/plain'); assert.strictEqual(writeResult._attachments.foo.digest, attachmentHash); const queryResult = await storageInstance.query( storageInstance.prepareQuery({ selector: {} }) ); assert.strictEqual(queryResult.documents[0]._attachments.foo.type, 'text/plain'); assert.strictEqual(queryResult.documents[0]._attachments.foo.length, attachmentData.length); const byId = await storageInstance.findDocumentsById([writeData.key], false); const byIdDoc = getFromMapOrThrow(byId, writeData.key); assert.strictEqual(byIdDoc._attachments.foo.type, 'text/plain'); assert.strictEqual(byIdDoc._attachments.foo.length, attachmentData.length); // test emitted assert.strictEqual(emitted[0].change.doc._attachments.foo.type, 'text/plain'); assert.strictEqual(emitted[0].change.doc._attachments.foo.length, attachmentData.length); const changesResult = await storageInstance.getChangedDocuments({ startSequence: 0, order: 'asc' }); const firstChange = changesResult.changedDocuments[0]; if (!firstChange) { throw new Error('first change missing'); } assert.strictEqual(firstChange.id, 'foobar'); sub.unsubscribe(); storageInstance.close(); }); it('should be able to add multiple attachments, one each write', async () => { const storageInstance = await getRxStoragePouch('memory').createStorageInstance<TestDocType>({ databaseName: randomCouchString(12), collectionName: randomCouchString(12), schema: getPseudoSchemaForVersion(0, 'key'), options: { auto_compaction: false } }); let previous: RxDocumentData<TestDocType> | undefined; const writeData: RxDocumentWriteData<TestDocType> = { key: 'foobar', value: 'one', _rev: undefined as any, _deleted: false, _attachments: { foo: { data: blobBufferUtil.createBlobBuffer(randomString(20), 'text/plain'), type: 'text/plain' } } }; previous = await writeSingle( storageInstance, { previous, document: writeData } ); writeData._attachments = flatClone(previous._attachments) as any; writeData._attachments.bar = { data: blobBufferUtil.createBlobBuffer(randomString(20), 'text/plain'), type: 'text/plain' }; previous = await writeSingle( storageInstance, { previous, document: writeData } ); assert.strictEqual(Object.keys(previous._attachments).length, 2); storageInstance.close(); }); }); }); describe('RxStorageKeyObjectInstance', () => { describe('RxStorageKeyObjectInstance.bulkWrite()', () => { it('should write the documents', async () => { const storageInstance = await getRxStoragePouch('memory').createKeyObjectStorageInstance( randomCouchString(12), randomCouchString(12), {} ); const writeResponse = await storageInstance.bulkWrite( [{ document: { _id: 'foobar', value: 'barfoo', _attachments: {} } }] ); assert.strictEqual(writeResponse.error.size, 0); const first = getFromMapOrThrow(writeResponse.success, 'foobar'); assert.strictEqual(first._id, 'foobar'); assert.strictEqual(first.value, 'barfoo'); storageInstance.close(); }); it('should error on conflict', async () => { const storageInstance = await getRxStoragePouch('memory').createKeyObjectStorageInstance( randomCouchString(12), randomCouchString(12), {} ); const writeData = [{ document: { _id: 'foobar', value: 'barfoo', _attachments: {} } }]; await storageInstance.bulkWrite( writeData ); const writeResponse = await storageInstance.bulkWrite( writeData ); assert.strictEqual(writeResponse.success.size, 0); const first = getFromMapOrThrow(writeResponse.error, 'foobar'); assert.strictEqual(first.status, 409); assert.strictEqual(first.documentId, 'foobar'); assert.ok(first.writeRow.document); storageInstance.close(); }); it('should be able to delete', async () => { const storageInstance = await getRxStoragePouch('memory').createKeyObjectStorageInstance( randomCouchString(12), randomCouchString(12), {} ); const writeDoc = { _id: 'foobar', value: 'barfoo', _deleted: false, _rev: undefined as any, _attachments: {} }; const firstWriteResult = await storageInstance.bulkWrite( [{ document: writeDoc }] ); const writeDocResult = getFromMapOrThrow(firstWriteResult.success, writeDoc._id); writeDoc._rev = writeDocResult._rev; writeDoc._deleted = true; await storageInstance.bulkWrite( [{ document: writeDoc }] ); // should not find the document const res = await storageInstance.findLocalDocumentsById([writeDoc._id]); assert.strictEqual(res.has(writeDoc._id), false); storageInstance.close(); }); }); describe('.findLocalDocumentsById()', () => { it('should find the documents', async () => { const storageInstance = await getRxStoragePouch('memory').createKeyObjectStorageInstance( randomCouchString(12), randomCouchString(12), {} ); const writeData = { _id: 'foobar', value: 'barfoo', _attachments: {} }; await storageInstance.bulkWrite( [{ document: writeData }] ); const found = await storageInstance.findLocalDocumentsById([writeData._id]); const doc = getFromMapOrThrow(found, writeData._id); assert.strictEqual( doc.value, writeData.value ); storageInstance.close(); }); }); describe('.changeStream()', () => { it('should emit exactly one event on write', async () => { const storageInstance = await getRxStoragePouch('memory').createKeyObjectStorageInstance( randomCouchString(12), randomCouchString(12), {} ); const emitted: RxStorageChangeEvent<RxLocalDocumentData>[] = []; const sub = storageInstance.changeStream().subscribe(x => { emitted.push(x); }); const writeData = { _id: 'foobar', value: 'one', _rev: undefined as any, _deleted: false, _attachments: {} }; // insert await storageInstance.bulkWrite([{ document: writeData }]); await wait(100); assert.strictEqual(emitted.length, 1); sub.unsubscribe(); storageInstance.close(); }); it('should emit all events', async () => { const storageInstance = await getRxStoragePouch('memory').createKeyObjectStorageInstance( randomCouchString(12), randomCouchString(12), {} ); const emitted: RxStorageChangeEvent<RxLocalDocumentData>[] = []; const sub = storageInstance.changeStream().subscribe(x => { emitted.push(x); }); let previous: RxLocalDocumentData | undefined; const writeData = { _id: 'foobar', value: 'one', _rev: undefined as any, _deleted: false, _attachments: {} }; // insert const firstWriteResult = await storageInstance.bulkWrite([{ previous, document: writeData }]); previous = getFromMapOrThrow(firstWriteResult.success, writeData._id); // update const updateResult = await storageInstance.bulkWrite([{ previous, document: writeData }]); previous = getFromMapOrThrow(updateResult.success, writeData._id); // delete writeData._deleted = true; await storageInstance.bulkWrite([{ previous, document: writeData }]); await waitUntil(() => emitted.length === 3); const last = lastOfArray(emitted); if (!last) { throw new Error('missing last event'); } assert.strictEqual(last.change.operation, 'DELETE'); assert.ok(last.change.previous); sub.unsubscribe(); storageInstance.close(); }); }); }); describe('helper', () => { describe('.getNewestSequence()', () => { it('should get the latest sequence', async () => { const storageInstance = await getRxStoragePouch('memory').createStorageInstance<{ key: string }>({ databaseName: randomCouchString(12), collectionName: randomCouchString(12), schema: getPseudoSchemaForVersion(0, 'key'), options: { auto_compaction: false } }); const latestBefore = await getNewestSequence(storageInstance); await storageInstance.bulkWrite([ { document: { key: 'foobar', _attachments: {} } }, { document: { key: 'foobar2', _attachments: {} } } ]); const latestAfter = await getNewestSequence(storageInstance); assert.ok(latestAfter > latestBefore); storageInstance.close(); }); }); }); });
the_stack
//@ts-check ///<reference path="devkit.d.ts" /> declare namespace DevKit { namespace FormBookable_Resource_Mobile { interface tab_fstab_field_service_Sections { fstab_field_service_section_4: DevKit.Controls.Section; fstab_field_service_section_5: DevKit.Controls.Section; fstab_field_service_section_field_service: DevKit.Controls.Section; fstab_field_service_section_misc: DevKit.Controls.Section; fstab_field_service_section_scheduling: DevKit.Controls.Section; } interface tab_fstab_general_Sections { } interface tab_fstab_sub_grids_Sections { fstab_sub_grids_section: DevKit.Controls.Section; tab_3_section_2: DevKit.Controls.Section; tab_3_section_3: DevKit.Controls.Section; } interface tab_fstab_field_service extends DevKit.Controls.ITab { Section: tab_fstab_field_service_Sections; } interface tab_fstab_general extends DevKit.Controls.ITab { Section: tab_fstab_general_Sections; } interface tab_fstab_sub_grids extends DevKit.Controls.ITab { Section: tab_fstab_sub_grids_Sections; } interface Tabs { fstab_field_service: tab_fstab_field_service; fstab_general: tab_fstab_general; fstab_sub_grids: tab_fstab_sub_grids; } interface Body { Tab: Tabs; /** Select the account that represents this resource. */ AccountId: DevKit.Controls.Lookup; /** Select the contact that represents this resource. */ ContactId: DevKit.Controls.Lookup; /** The number of bookings to drip on the Mobile . This field is disabled/enabled based on Enable Drip Scheduling field */ msdyn_BookingsToDrip: DevKit.Controls.Integer; /** Specify if this resource should be enabled for availablity search. */ msdyn_DisplayOnScheduleAssistant: DevKit.Controls.Boolean; /** Specify if this resource should be displayed on the schedule board. */ msdyn_DisplayOnScheduleBoard: DevKit.Controls.Boolean; /** Enables drip scheduling on the mobile app. */ msdyn_EnableDripScheduling: DevKit.Controls.Boolean; /** Shows the default ending location type when booking daily schedules for this resource. */ msdyn_EndLocation: DevKit.Controls.OptionSet; msdyn_GenericType: DevKit.Controls.OptionSet; msdyn_HourlyRate: DevKit.Controls.Money; /** Shows the default starting location type when booking daily schedules for this resource. */ msdyn_StartLocation: DevKit.Controls.OptionSet; /** Specifies if approval required for Time Off Requests. */ msdyn_TimeOffApprovalRequired: DevKit.Controls.Boolean; /** Default Warehouse for this resource. */ msdyn_Warehouse: DevKit.Controls.Lookup; /** Type the name of the resource. */ Name: DevKit.Controls.String; notescontrol: DevKit.Controls.Note; /** Select whether the resource is a user, equipment, contact, account, generic resource or a group of resources. */ ResourceType: DevKit.Controls.OptionSet; /** Specifies the timezone for the resource's working hours. */ TimeZone: DevKit.Controls.Integer; /** Select the user who represents this resource. */ UserId: DevKit.Controls.Lookup; } interface Navigation { nav_msdyn_bookableresource_account_PreferredResource: DevKit.Controls.NavigationItem, nav_msdyn_bookableresource_bookableresourcebooking_ResourceGroup: DevKit.Controls.NavigationItem, nav_msdyn_bookableresource_msdyn_agreementbookingdate_Resource: DevKit.Controls.NavigationItem, nav_msdyn_bookableresource_msdyn_agreementbookingsetup_PreferredResource: DevKit.Controls.NavigationItem, nav_msdyn_bookableresource_msdyn_inventoryadjustment_AdjustedByResource: DevKit.Controls.NavigationItem, nav_msdyn_bookableresource_msdyn_inventoryadjustment_RequestedByResource: DevKit.Controls.NavigationItem, nav_msdyn_bookableresource_msdyn_inventorytransfer_TransferredByResource: DevKit.Controls.NavigationItem, nav_msdyn_bookableresource_msdyn_purchaseorder_RequestedByResource: DevKit.Controls.NavigationItem, nav_msdyn_bookableresource_msdyn_resourceterritory_Resource: DevKit.Controls.NavigationItem, nav_msdyn_bookableresource_msdyn_timeoffrequest_Resource: DevKit.Controls.NavigationItem, nav_msdyn_bookableresource_msdyn_workorder_PreferredResource: DevKit.Controls.NavigationItem, nav_msdyn_bookableresource_msdyn_workorderresourcerestriction_Resource: DevKit.Controls.NavigationItem, navAudit: DevKit.Controls.NavigationItem, navBookings: DevKit.Controls.NavigationItem, navCharacteristics: DevKit.Controls.NavigationItem, navChildGroups: DevKit.Controls.NavigationItem, navParentGroups: DevKit.Controls.NavigationItem, navResourceCategories: DevKit.Controls.NavigationItem } interface Grid { ResourceCategory: DevKit.Controls.Grid; ResourceCharacteristics: DevKit.Controls.Grid; BookableResourceCharacteristics: DevKit.Controls.Grid; CATEGORYASSOCIATIONS: DevKit.Controls.Grid; } } class FormBookable_Resource_Mobile extends DevKit.IForm { /** * DynamicsCrm.DevKit form Bookable_Resource_Mobile * @param executionContext the execution context * @param defaultWebResourceName default resource name. E.g.: "devkit_/resources/Resource" */ constructor(executionContext: any, defaultWebResourceName?: string); /** Utility functions/methods/objects for Dynamics 365 form */ Utility: DevKit.Utility; /** The Body section of form Bookable_Resource_Mobile */ Body: DevKit.FormBookable_Resource_Mobile.Body; /** The Navigation of form Bookable_Resource_Mobile */ Navigation: DevKit.FormBookable_Resource_Mobile.Navigation; /** The Grid of form Bookable_Resource_Mobile */ Grid: DevKit.FormBookable_Resource_Mobile.Grid; } namespace FormBookableResource_Information { interface tab__E37F4524_4A66_42DC_974C_078756AEF3FB_Sections { _6BFE3886_A003_47B5_A2C2_7E54AD6213A9: DevKit.Controls.Section; _9E7DEC57_2C62_4D5D_8B21_75D076C5D1A1: DevKit.Controls.Section; _E37F4524_4A66_42DC_974C_078756AEF3FB_SECTION_6: DevKit.Controls.Section; msdyn_userinformation: DevKit.Controls.Section; tab_4_section_1: DevKit.Controls.Section; } interface tab_FieldService_Sections { FieldService_section_4: DevKit.Controls.Section; FieldService_section_5: DevKit.Controls.Section; fstab_service_settings_section_5: DevKit.Controls.Section; fstab_service_settings_section_7: DevKit.Controls.Section; } interface tab_Omnichannel_Sections { tab_2_section_1: DevKit.Controls.Section; } interface tab_tab_2_Sections { tab_2_section_1: DevKit.Controls.Section; tab_2_section_2: DevKit.Controls.Section; } interface tab_tab_projectservice_Sections { tab_2_section_1: DevKit.Controls.Section; tab_2_section_2: DevKit.Controls.Section; } interface tab_workhours_Sections { tab_3_section_1: DevKit.Controls.Section; } interface tab__E37F4524_4A66_42DC_974C_078756AEF3FB extends DevKit.Controls.ITab { Section: tab__E37F4524_4A66_42DC_974C_078756AEF3FB_Sections; } interface tab_FieldService extends DevKit.Controls.ITab { Section: tab_FieldService_Sections; } interface tab_Omnichannel extends DevKit.Controls.ITab { Section: tab_Omnichannel_Sections; } interface tab_tab_2 extends DevKit.Controls.ITab { Section: tab_tab_2_Sections; } interface tab_tab_projectservice extends DevKit.Controls.ITab { Section: tab_tab_projectservice_Sections; } interface tab_workhours extends DevKit.Controls.ITab { Section: tab_workhours_Sections; } interface Tabs { _E37F4524_4A66_42DC_974C_078756AEF3FB: tab__E37F4524_4A66_42DC_974C_078756AEF3FB; FieldService: tab_FieldService; Omnichannel: tab_Omnichannel; tab_2: tab_tab_2; tab_projectservice: tab_tab_projectservice; workhours: tab_workhours; } interface Body { Tab: Tabs; /** Select the account that represents this resource. */ AccountId: DevKit.Controls.Lookup; /** Specifies the working days and hours of the resource. */ CalendarId: DevKit.Controls.Lookup; /** Select the contact that represents this resource. */ ContactId: DevKit.Controls.Lookup; /** The number of bookings to drip on the Mobile . This field is disabled/enabled based on Enable Drip Scheduling field */ msdyn_BookingsToDrip: DevKit.Controls.Integer; /** Crew Strategy */ msdyn_CrewStrategy: DevKit.Controls.OptionSet; msdyn_DeriveCapacity: DevKit.Controls.Boolean; /** Specify if this resource should be enabled for availablity search. */ msdyn_DisplayOnScheduleAssistant: DevKit.Controls.Boolean; /** Specify if this resource should be displayed on the schedule board. */ msdyn_DisplayOnScheduleBoard: DevKit.Controls.Boolean; /** Enable appointments to display on the new schedule board and be considered in availability search for resources. */ msdyn_EnableAppointments: DevKit.Controls.OptionSet; /** Set this field to Yes if this resource requires access to the legacy Field Service Mobile application. */ msdyn_EnabledForFieldServiceMobile: DevKit.Controls.Boolean; /** Enables drip scheduling on the mobile app. */ msdyn_EnableDripScheduling: DevKit.Controls.Boolean; /** Shows the default ending location type when booking daily schedules for this resource. */ msdyn_EndLocation: DevKit.Controls.OptionSet; /** Unique identifier for Facility Equipment */ msdyn_facilityequipmentid: DevKit.Controls.Lookup; msdyn_GenericType: DevKit.Controls.OptionSet; msdyn_HourlyRate: DevKit.Controls.Money; /** Organizational Unit that resource belong to */ msdyn_organizationalunit: DevKit.Controls.Lookup; /** Select whether the pool is an account, contact, user, equipment or a facility of resources. */ msdyn_PoolType: DevKit.Controls.MultiOptionSet; /** Shows the default starting location type when booking daily schedules for this resource. */ msdyn_StartLocation: DevKit.Controls.OptionSet; /** Shows the target utilization for the resource. */ msdyn_targetutilization: DevKit.Controls.Integer; /** Specifies if approval required for Time Off Requests. */ msdyn_TimeOffApprovalRequired: DevKit.Controls.Boolean; /** Default Warehouse for this resource. */ msdyn_Warehouse: DevKit.Controls.Lookup; /** Type the name of the resource. */ Name: DevKit.Controls.String; notescontrol: DevKit.Controls.Note; /** Select whether the resource is a user, equipment, contact, account, generic resource or a group of resources. */ ResourceType: DevKit.Controls.OptionSet; /** Specifies the timezone for the resource's working hours. */ TimeZone: DevKit.Controls.Integer; /** Select the user who represents this resource. */ UserId: DevKit.Controls.Lookup; /** Select the user who represents this resource. */ UserId_1: DevKit.Controls.Lookup; } interface Navigation { nav_msdyn_bookableresource_account_PreferredResource: DevKit.Controls.NavigationItem, nav_msdyn_bookableresource_bookableresourcebooking_ResourceGroup: DevKit.Controls.NavigationItem, nav_msdyn_bookableresource_msdyn_agreementbookingdate_Resource: DevKit.Controls.NavigationItem, nav_msdyn_bookableresource_msdyn_agreementbookingsetup_PreferredResource: DevKit.Controls.NavigationItem, nav_msdyn_bookableresource_msdyn_delegation_delegationfrom: DevKit.Controls.NavigationItem, nav_msdyn_bookableresource_msdyn_delegation_delegationto: DevKit.Controls.NavigationItem, nav_msdyn_bookableresource_msdyn_estimateline_bookableresource: DevKit.Controls.NavigationItem, nav_msdyn_bookableresource_msdyn_fact_bookableresource: DevKit.Controls.NavigationItem, nav_msdyn_bookableresource_msdyn_findworkevent_BookableResource: DevKit.Controls.NavigationItem, nav_msdyn_bookableresource_msdyn_inventoryadjustment_AdjustedByResource: DevKit.Controls.NavigationItem, nav_msdyn_bookableresource_msdyn_inventoryadjustment_RequestedByResource: DevKit.Controls.NavigationItem, nav_msdyn_bookableresource_msdyn_inventorytransfer_TransferredByResource: DevKit.Controls.NavigationItem, nav_msdyn_bookableresource_msdyn_invoicelinetransaction_bookableresource: DevKit.Controls.NavigationItem, nav_msdyn_bookableresource_msdyn_journalline_bookableresource: DevKit.Controls.NavigationItem, nav_msdyn_bookableresource_msdyn_opportunitylinetransaction_bookableresource: DevKit.Controls.NavigationItem, nav_msdyn_bookableresource_msdyn_orderlinetransaction_bookableresource: DevKit.Controls.NavigationItem, nav_msdyn_bookableresource_msdyn_projectapproval_bookableresource: DevKit.Controls.NavigationItem, nav_msdyn_bookableresource_msdyn_projecttaskstatususer_BookableResource: DevKit.Controls.NavigationItem, nav_msdyn_bookableresource_msdyn_projectteam_bookableresourceid: DevKit.Controls.NavigationItem, nav_msdyn_bookableresource_msdyn_projectteammembersignup_BookableResource: DevKit.Controls.NavigationItem, nav_msdyn_bookableresource_msdyn_purchaseorder_RequestedByResource: DevKit.Controls.NavigationItem, nav_msdyn_bookableresource_msdyn_quotebookingsetup_PreferredResource: DevKit.Controls.NavigationItem, nav_msdyn_bookableresource_msdyn_quotelinetransaction_bookableresource: DevKit.Controls.NavigationItem, nav_msdyn_bookableresource_msdyn_resourceassignment_bookableresourceid: DevKit.Controls.NavigationItem, nav_msdyn_bookableresource_msdyn_resourceterritory_Resource: DevKit.Controls.NavigationItem, nav_msdyn_bookableresource_msdyn_timeentry_bookableresource: DevKit.Controls.NavigationItem, nav_msdyn_bookableresource_msdyn_timeoffrequest_Resource: DevKit.Controls.NavigationItem, nav_msdyn_bookableresource_msdyn_userworkhistory_Bookableresource: DevKit.Controls.NavigationItem, nav_msdyn_bookableresource_msdyn_workorder_PreferredResource: DevKit.Controls.NavigationItem, nav_msdyn_bookableresource_msdyn_workorderresourcerestriction_Resource: DevKit.Controls.NavigationItem, navAsyncOperations: DevKit.Controls.NavigationItem, navAudit: DevKit.Controls.NavigationItem, navBookings: DevKit.Controls.NavigationItem, navCharacteristics: DevKit.Controls.NavigationItem, navChildGroups: DevKit.Controls.NavigationItem, navParentGroups: DevKit.Controls.NavigationItem, navProcessSessions: DevKit.Controls.NavigationItem, navResourceCategories: DevKit.Controls.NavigationItem, navResourceOneAssociation: DevKit.Controls.NavigationItem, navResourceTwoAssociation: DevKit.Controls.NavigationItem } interface Grid { ResourceCharacteristics: DevKit.Controls.Grid; ResourceCategory: DevKit.Controls.Grid; Resourceskills: DevKit.Controls.Grid; ResourceRole: DevKit.Controls.Grid; BookableResourceCharacteristics: DevKit.Controls.Grid; CATEGORYASSOCIATIONS: DevKit.Controls.Grid; } } class FormBookableResource_Information extends DevKit.IForm { /** * DynamicsCrm.DevKit form BookableResource_Information * @param executionContext the execution context * @param defaultWebResourceName default resource name. E.g.: "devkit_/resources/Resource" */ constructor(executionContext: any, defaultWebResourceName?: string); /** Utility functions/methods/objects for Dynamics 365 form */ Utility: DevKit.Utility; /** The Body section of form BookableResource_Information */ Body: DevKit.FormBookableResource_Information.Body; /** The Navigation of form BookableResource_Information */ Navigation: DevKit.FormBookableResource_Information.Navigation; /** The Grid of form BookableResource_Information */ Grid: DevKit.FormBookableResource_Information.Grid; } class BookableResourceApi { /** * DynamicsCrm.DevKit BookableResourceApi * @param entity The entity object */ constructor(entity?: any); /** * Get the value of alias * @param alias the alias value * @param isMultiOptionSet true if the alias is multi OptionSet */ getAliasedValue(alias: string, isMultiOptionSet?: boolean): any; /** * Get the formatted value of alias * @param alias the alias value * @param isMultiOptionSet true if the alias is multi OptionSet */ getAliasedFormattedValue(alias: string, isMultiOptionSet?: boolean): string; /** The entity object */ Entity: any; /** The entity name */ EntityName: string; /** The entity collection name */ EntityCollectionName: string; /** The @odata.etag is then used to build a cache of the response that is dependant on the fields that are retrieved */ "@odata.etag": string; /** Select the account that represents this resource. */ AccountId: DevKit.WebApi.LookupValue; /** Unique identifier of the resource. */ BookableResourceId: DevKit.WebApi.GuidValue; /** Specifies the working days and hours of the resource. */ CalendarId: DevKit.WebApi.LookupValue; /** Select the contact that represents this resource. */ ContactId: DevKit.WebApi.LookupValue; /** Unique identifier of the user who created the record. */ CreatedBy: DevKit.WebApi.LookupValueReadonly; /** Date and time when the record was created. */ CreatedOn_UtcDateAndTime: DevKit.WebApi.UtcDateAndTimeValueReadonly; /** Unique identifier of the delegate user who created the record. */ CreatedOnBehalfBy: DevKit.WebApi.LookupValueReadonly; /** Exchange rate for the currency associated with the bookableresource with respect to the base currency. */ ExchangeRate: DevKit.WebApi.DecimalValueReadonly; /** Sequence number of the import that created this record. */ ImportSequenceNumber: DevKit.WebApi.IntegerValue; /** Unique identifier of the user who modified the record. */ ModifiedBy: DevKit.WebApi.LookupValueReadonly; /** Date and time when the record was modified. */ ModifiedOn_UtcDateAndTime: DevKit.WebApi.UtcDateAndTimeValueReadonly; /** Unique identifier of the delegate user who modified the record. */ ModifiedOnBehalfBy: DevKit.WebApi.LookupValueReadonly; /** The number of bookings to drip on the Mobile . This field is disabled/enabled based on Enable Drip Scheduling field */ msdyn_BookingsToDrip: DevKit.WebApi.IntegerValue; /** Crew Strategy */ msdyn_CrewStrategy: DevKit.WebApi.OptionSetValue; msdyn_DeriveCapacity: DevKit.WebApi.BooleanValue; /** Specify if this resource should be enabled for availablity search. */ msdyn_DisplayOnScheduleAssistant: DevKit.WebApi.BooleanValue; /** Specify if this resource should be displayed on the schedule board. */ msdyn_DisplayOnScheduleBoard: DevKit.WebApi.BooleanValue; /** Enable appointments to display on the new schedule board and be considered in availability search for resources. */ msdyn_EnableAppointments: DevKit.WebApi.OptionSetValue; /** Set this field to Yes if this resource requires access to the legacy Field Service Mobile application. */ msdyn_EnabledForFieldServiceMobile: DevKit.WebApi.BooleanValue; /** Enables drip scheduling on the mobile app. */ msdyn_EnableDripScheduling: DevKit.WebApi.BooleanValue; /** Shows the default ending location type when booking daily schedules for this resource. */ msdyn_EndLocation: DevKit.WebApi.OptionSetValue; /** Unique identifier for Facility Equipment */ msdyn_facilityequipmentid: DevKit.WebApi.LookupValue; msdyn_GenericType: DevKit.WebApi.OptionSetValue; msdyn_HourlyRate: DevKit.WebApi.MoneyValue; /** Value of the Hourly Rate in base currency. */ msdyn_hourlyrate_Base: DevKit.WebApi.MoneyValueReadonly; /** For internal use only. */ msdyn_InternalFlags: DevKit.WebApi.StringValue; /** Is Default */ msdyn_isgenericresourceprojectscoped: DevKit.WebApi.BooleanValue; msdyn_Latitude: DevKit.WebApi.DoubleValue; /** The location timestamp. */ msdyn_locationtimestamp_UtcDateAndTime: DevKit.WebApi.UtcDateAndTimeValue; msdyn_Longitude: DevKit.WebApi.DoubleValue; /** Organizational Unit that resource belong to */ msdyn_organizationalunit: DevKit.WebApi.LookupValue; /** Select whether the pool is an account, contact, user, equipment or a facility of resources. */ msdyn_PoolType: DevKit.WebApi.MultiOptionSetValue; msdyn_PrimaryEMail: DevKit.WebApi.StringValue; /** Shows the default starting location type when booking daily schedules for this resource. */ msdyn_StartLocation: DevKit.WebApi.OptionSetValue; /** Shows the target utilization for the resource. */ msdyn_targetutilization: DevKit.WebApi.IntegerValue; /** Specifies if approval required for Time Off Requests. */ msdyn_TimeOffApprovalRequired: DevKit.WebApi.BooleanValue; /** Default Warehouse for this resource. */ msdyn_Warehouse: DevKit.WebApi.LookupValue; /** Type the name of the resource. */ Name: DevKit.WebApi.StringValue; /** Date and time that the record was migrated. */ OverriddenCreatedOn_UtcDateOnly: DevKit.WebApi.UtcDateOnlyValue; /** Enter the user who is assigned to manage the record. This field is updated every time the record is assigned to a different user */ OwnerId_systemuser: DevKit.WebApi.LookupValue; /** Enter the team who is assigned to manage the record. This field is updated every time the record is assigned to a different team */ OwnerId_team: DevKit.WebApi.LookupValue; /** Unique identifier for the business unit that owns the record */ OwningBusinessUnit: DevKit.WebApi.LookupValueReadonly; /** Unique identifier for the team that owns the record. */ OwningTeam: DevKit.WebApi.LookupValueReadonly; /** Unique identifier for the user that owns the record. */ OwningUser: DevKit.WebApi.LookupValueReadonly; /** Contains the id of the process associated with the entity. */ ProcessId: DevKit.WebApi.GuidValue; /** Select whether the resource is a user, equipment, contact, account, generic resource or a group of resources. */ ResourceType: DevKit.WebApi.OptionSetValue; /** Contains the id of the stage where the entity is located. */ StageId: DevKit.WebApi.GuidValue; /** Status of the Bookable Resource */ StateCode: DevKit.WebApi.OptionSetValue; /** Reason for the status of the Bookable Resource */ StatusCode: DevKit.WebApi.OptionSetValue; /** Specifies the timezone for the resource's working hours. */ TimeZone: DevKit.WebApi.IntegerValue; /** For internal use only. */ TimeZoneRuleVersionNumber: DevKit.WebApi.IntegerValue; /** Exchange rate for the currency associated with the BookableResource with respect to the base currency. */ TransactionCurrencyId: DevKit.WebApi.LookupValue; /** A comma separated list of string values representing the unique identifiers of stages in a Business Process Flow Instance in the order that they occur. */ TraversedPath: DevKit.WebApi.StringValue; /** Select the user who represents this resource. */ UserId: DevKit.WebApi.LookupValue; /** Time zone code that was in use when the record was created. */ UTCConversionTimeZoneCode: DevKit.WebApi.IntegerValue; /** Version Number */ VersionNumber: DevKit.WebApi.BigIntValueReadonly; } } declare namespace OptionSet { namespace BookableResource { enum msdyn_CrewStrategy { /** 192350000 */ Cascade_and_Accept_Cascade_Completely, /** 192350001 */ Crew_Leader_Management, /** 192350002 */ Crew_Member_Self_Management } enum msdyn_EnableAppointments { /** 192350000 */ No, /** 192350001 */ Yes } enum msdyn_EndLocation { /** 690970002 */ Location_Agnostic, /** 690970001 */ Organizational_Unit_Address, /** 690970000 */ Resource_Address } enum msdyn_GenericType { /** 690970000 */ Service_Center } enum msdyn_PoolType { /** 192350000 */ Account, /** 192350001 */ Contact, /** 192350003 */ Equipment, /** 192350004 */ Facility, /** 192350002 */ User } enum msdyn_StartLocation { /** 690970002 */ Location_Agnostic, /** 690970001 */ Organizational_Unit_Address, /** 690970000 */ Resource_Address } enum ResourceType { /** 5 */ Account, /** 2 */ Contact, /** 6 */ Crew, /** 4 */ Equipment, /** 7 */ Facility, /** 1 */ Generic, /** 8 */ Pool, /** 3 */ User } enum StateCode { /** 0 */ Active, /** 1 */ Inactive } enum StatusCode { /** 1 */ Active, /** 2 */ Inactive } enum RollupState { /** 0 - Attribute value is yet to be calculated */ NotCalculated, /** 1 - Attribute value has been calculated per the last update time in <AttributeSchemaName>_Date attribute */ Calculated, /** 2 - Attribute value calculation lead to overflow error */ OverflowError, /** 3 - Attribute value calculation failed due to an internal error, next run of calculation job will likely fix it */ OtherError, /** 4 - Attribute value calculation failed because the maximum number of retry attempts to calculate the value were exceeded likely due to high number of concurrency and locking conflicts */ RetryLimitExceeded, /** 5 - Attribute value calculation failed because maximum hierarchy depth limit for calculation was reached */ HierarchicalRecursionLimitReached, /** 6 - Attribute value calculation failed because a recursive loop was detected in the hierarchy of the record */ LoopDetected } } } //{'JsForm':['Bookable Resource - Mobile','Information'],'JsWebApi':true,'IsDebugForm':true,'IsDebugWebApi':true,'Version':'2.12.31','JsFormVersion':'v2'}
the_stack
import assert from 'assert'; import { ImportType } from '../analyzer/importResult'; import { getRelativeModuleName, getTextEditsForAutoImportInsertions, getTextEditsForAutoImportSymbolAddition, getTopLevelImports, ImportNameInfo, ImportNameWithModuleInfo, } from '../analyzer/importStatementUtils'; import { isArray } from '../common/core'; import { TextEditAction } from '../common/editAction'; import { combinePaths, getDirectoryPath } from '../common/pathUtils'; import { convertOffsetToPosition } from '../common/positionUtils'; import { rangesAreEqual } from '../common/textRange'; import { Range } from './harness/fourslash/fourSlashTypes'; import { parseAndGetTestState, TestState } from './harness/fourslash/testState'; test('getTextEditsForAutoImportInsertion - import empty', () => { const code = ` //// import os[|/*marker1*/{|"r":"!n!import sys"|}|] `; testInsertion(code, 'marker1', [], 'sys', ImportType.BuiltIn); }); test('getTextEditsForAutoImportInsertion - import', () => { const code = ` //// import os[|/*marker1*/{|"r":"!n!import sys"|}|] `; testInsertion(code, 'marker1', {}, 'sys', ImportType.BuiltIn); }); test('getTextEditsForAutoImportInsertion - import alias', () => { const code = ` //// import os[|/*marker1*/{|"r":"!n!import sys as s"|}|] `; testInsertion(code, 'marker1', { alias: 's' }, 'sys', ImportType.BuiltIn); }); test('getTextEditsForAutoImportInsertion - multiple imports', () => { const code = ` //// import os[|/*marker1*/{|"r":"!n!import sys"|}|] `; testInsertion(code, 'marker1', [{}, {}], 'sys', ImportType.BuiltIn); }); test('getTextEditsForAutoImportInsertion - multiple imports alias', () => { const code = ` //// import os[|/*marker1*/{|"r":"!n!import sys as s, sys as y"|}|] `; testInsertion(code, 'marker1', [{ alias: 's' }, { alias: 'y' }], 'sys', ImportType.BuiltIn); }); test('getTextEditsForAutoImportInsertion - multiple imports alias duplicated', () => { const code = ` //// import os[|/*marker1*/{|"r":"!n!import sys as s"|}|] `; testInsertion(code, 'marker1', [{ alias: 's' }, { alias: 's' }], 'sys', ImportType.BuiltIn); }); test('getTextEditsForAutoImportInsertion - from import', () => { const code = ` //// import os[|/*marker1*/{|"r":"!n!from sys import path"|}|] `; testInsertion(code, 'marker1', { name: 'path' }, 'sys', ImportType.BuiltIn); }); test('getTextEditsForAutoImportInsertion - from import alias', () => { const code = ` //// import os[|/*marker1*/{|"r":"!n!from sys import path as p"|}|] `; testInsertion(code, 'marker1', { name: 'path', alias: 'p' }, 'sys', ImportType.BuiltIn); }); test('getTextEditsForAutoImportInsertion - multiple from imports', () => { const code = ` //// import os[|/*marker1*/{|"r":"!n!from sys import meta_path, path"|}|] `; testInsertion(code, 'marker1', [{ name: 'path' }, { name: 'meta_path' }], 'sys', ImportType.BuiltIn); }); test('getTextEditsForAutoImportInsertion - multiple from imports with alias', () => { const code = ` //// import os[|/*marker1*/{|"r":"!n!from sys import meta_path as m, path as p"|}|] `; testInsertion( code, 'marker1', [ { name: 'path', alias: 'p' }, { name: 'meta_path', alias: 'm' }, ], 'sys', ImportType.BuiltIn ); }); test('getTextEditsForAutoImportInsertion - multiple from imports with alias duplicated', () => { const code = ` //// import os[|/*marker1*/{|"r":"!n!from sys import meta_path as m, path as p"|}|] `; testInsertion( code, 'marker1', [ { name: 'path', alias: 'p' }, { name: 'meta_path', alias: 'm' }, { name: 'path', alias: 'p' }, ], 'sys', ImportType.BuiltIn ); }); test('getTextEditsForAutoImportInsertion - multiple import statements', () => { const code = ` //// import os[|/*marker1*/{|"r":"!n!import sys as s!n!from sys import path as p"|}|] `; testInsertion(code, 'marker1', [{ alias: 's' }, { name: 'path', alias: 'p' }], 'sys', ImportType.BuiltIn); }); test('getTextEditsForAutoImportInsertion - different group', () => { const code = ` //// import os[|/*marker1*/{|"r":"!n!!n!import sys as s!n!from sys import path as p"|}|] `; testInsertion(code, 'marker1', [{ alias: 's' }, { name: 'path', alias: 'p' }], 'sys', ImportType.Local); }); test('getTextEditsForAutoImportInsertion - at the top', () => { const code = ` //// [|/*marker1*/{|"r":"import sys as s!n!from sys import path as p!n!!n!!n!"|}|]import os `; testInsertion(code, 'marker1', [{ alias: 's' }, { name: 'path', alias: 'p' }], 'sys', ImportType.BuiltIn); }); test('getTextEditsForAutoImportInsertion - at the top after module doc string', () => { const code = ` //// ''' module doc string ''' //// __author__ = "Software Authors Name" //// __copyright__ = "Copyright (C) 2004 Author Name" //// __license__ = "Public Domain" //// __version__ = "1.0" //// [|/*marker1*/{|"r":"import sys as s!n!from sys import path as p!n!!n!!n!"|}|]import os `; testInsertion(code, 'marker1', [{ alias: 's' }, { name: 'path', alias: 'p' }], 'sys', ImportType.BuiltIn); }); test('getTextEditsForAutoImportInsertions - mix of import and from import statements', () => { const code = ` //// [|/*marker1*/{|"r":"import sys as s!n!from sys import path as p!n!!n!!n!"|}|]import os `; const module = { moduleName: 'sys', importType: ImportType.BuiltIn, isLocalTypingsFile: false }; testInsertions(code, 'marker1', [ { module, alias: 's' }, { module, name: 'path', alias: 'p' }, ]); }); test('getTextEditsForAutoImportInsertions - multiple modules with different group', () => { const code = ` //// [|/*marker1*/|][|{|"r":"from sys import path as p!n!!n!!n!"|}|][|{|"r":"import numpy!n!!n!!n!"|}|][|{|"r":"from test import join!n!!n!!n!"|}|]import os `; const module1 = { moduleName: 'sys', importType: ImportType.BuiltIn, isLocalTypingsFile: false }; const module2 = { moduleName: 'numpy', importType: ImportType.ThirdParty, isLocalTypingsFile: false }; const module3 = { moduleName: 'test', importType: ImportType.Local, isLocalTypingsFile: false }; testInsertions(code, 'marker1', [ { module: module1, name: 'path', alias: 'p' }, { module: module2 }, { module: module3, name: 'join' }, ]); }); test('getTextEditsForAutoImportInsertions - multiple modules with existing imports', () => { const code = ` //// import os[|/*marker1*/|][|{|"r":"!n!from sys import path as p"|}|][|{|"r":"!n!!n!import numpy"|}|][|{|"r":"!n!!n!from test import join"|}|] `; const module1 = { moduleName: 'sys', importType: ImportType.BuiltIn, isLocalTypingsFile: false }; const module2 = { moduleName: 'numpy', importType: ImportType.ThirdParty, isLocalTypingsFile: false }; const module3 = { moduleName: 'test', importType: ImportType.Local, isLocalTypingsFile: false }; testInsertions(code, 'marker1', [ { module: module1, name: 'path', alias: 'p' }, { module: module2 }, { module: module3, name: 'join' }, ]); }); test('getTextEditsForAutoImportInsertions - multiple modules with same group', () => { const code = ` //// import os[|/*marker1*/|][|{|"r":"!n!!n!import module2!n!from module1 import path as p!n!from module3 import join"|}|] `; const module1 = { moduleName: 'module1', importType: ImportType.Local, isLocalTypingsFile: false }; const module2 = { moduleName: 'module2', importType: ImportType.Local, isLocalTypingsFile: false }; const module3 = { moduleName: 'module3', importType: ImportType.Local, isLocalTypingsFile: false }; testInsertions(code, 'marker1', [ { module: module1, name: 'path', alias: 'p' }, { module: module2 }, { module: module3, name: 'join' }, ]); }); test('getTextEditsForAutoImportSymbolAddition', () => { const code = ` //// from sys import [|/*marker1*/{|"r":"meta_path, "|}|]path `; testAddition(code, 'marker1', { name: 'meta_path' }, 'sys'); }); test('getTextEditsForAutoImportSymbolAddition - already exist', () => { const code = ` //// from sys import path[|/*marker1*/|] `; testAddition(code, 'marker1', { name: 'path' }, 'sys'); }); test('getTextEditsForAutoImportSymbolAddition - with alias', () => { const code = ` //// from sys import path[|/*marker1*/{|"r":", path as p"|}|] `; testAddition(code, 'marker1', { name: 'path', alias: 'p' }, 'sys'); }); test('getTextEditsForAutoImportSymbolAddition - multiple names', () => { const code = ` //// from sys import [|/*marker1*/{|"r":"meta_path as m, "|}|]path[|{|"r":", zoom as z"|}|] `; testAddition( code, 'marker1', [ { name: 'meta_path', alias: 'm' }, { name: 'zoom', alias: 'z' }, ], 'sys' ); }); test('getTextEditsForAutoImportSymbolAddition - multiple names at some spot', () => { const code = ` //// from sys import [|/*marker1*/{|"r":"meta_path as m, noon as n, "|}|]path `; testAddition( code, 'marker1', [ { name: 'meta_path', alias: 'm' }, { name: 'noon', alias: 'n' }, ], 'sys' ); }); test('getTextEditsForAutoImportSymbolAddition - wildcard', () => { const code = ` //// from sys import *[|/*marker1*/|] `; testAddition(code, 'marker1', [{ name: 'path' }], 'sys'); }); test('getRelativeModuleName - same file', () => { const code = ` // @filename: source.py //// [|/*src*/|] [|/*dest*/|] `; testRelativeModuleName(code, '.source'); }); test('getRelativeModuleName - same file __init__', () => { const code = ` // @filename: common/__init__.py //// [|/*src*/|] [|/*dest*/|] `; testRelativeModuleName(code, '.'); }); test('getRelativeModuleName - same folder', () => { const code = ` // @filename: source.py //// [|/*src*/|] // @filename: dest.py //// [|/*dest*/|] `; testRelativeModuleName(code, '.dest'); }); test('getRelativeModuleName - different folder move down', () => { const code = ` // @filename: common/source.py //// [|/*src*/|] // @filename: dest.py //// [|/*dest*/|] `; testRelativeModuleName(code, '..dest'); }); test('getRelativeModuleName - different folder move up', () => { const code = ` // @filename: source.py //// [|/*src*/|] // @filename: common/dest.py //// [|/*dest*/|] `; testRelativeModuleName(code, '.common.dest'); }); test('getRelativeModuleName - folder move down __init__ parent folder', () => { const code = ` // @filename: nest1/nest2/source.py //// [|/*src*/|] // @filename: nest1/__init__.py //// [|/*dest*/|] `; testRelativeModuleName(code, '..'); }); test('getRelativeModuleName - folder move down __init__ parent folder ignore folder structure', () => { const code = ` // @filename: nest1/nest2/source.py //// [|/*src*/|] // @filename: nest1/__init__.py //// [|/*dest*/|] `; testRelativeModuleName(code, '...nest1', /*ignoreFolderStructure*/ true); }); test('getRelativeModuleName - different folder move down __init__ sibling folder', () => { const code = ` // @filename: nest1/nest2/source.py //// [|/*src*/|] // @filename: different/__init__.py //// [|/*dest*/|] `; testRelativeModuleName(code, '...different'); }); test('getRelativeModuleName - different folder move up __init__', () => { const code = ` // @filename: source.py //// [|/*src*/|] // @filename: common/__init__.py //// [|/*dest*/|] `; testRelativeModuleName(code, '.common'); }); test('getRelativeModuleName - root __init__', () => { const code = ` // @filename: source.py //// [|/*src*/|] // @filename: __init__.py //// [|/*dest*/|] `; testRelativeModuleName(code, '.'); }); test('getRelativeModuleName over fake file', () => { const code = ` // @filename: target.py //// [|/*dest*/|] `; const state = parseAndGetTestState(code).state; const dest = state.getMarkerByName('dest')!.fileName; assert.strictEqual( getRelativeModuleName( state.fs, combinePaths(getDirectoryPath(dest), 'source.py'), dest, /*ignoreFolderStructure*/ false, /*sourceIsFile*/ true ), '.target' ); }); function testRelativeModuleName(code: string, expected: string, ignoreFolderStructure = false) { const state = parseAndGetTestState(code).state; const src = state.getMarkerByName('src')!.fileName; const dest = state.getMarkerByName('dest')!.fileName; assert.strictEqual(getRelativeModuleName(state.fs, src, dest, ignoreFolderStructure), expected); } function testAddition( code: string, markerName: string, importNameInfo: ImportNameInfo | ImportNameInfo[], moduleName: string ) { const state = parseAndGetTestState(code).state; const marker = state.getMarkerByName(markerName)!; const parseResults = state.program.getBoundSourceFile(marker!.fileName)!.getParseResults()!; const importStatement = getTopLevelImports(parseResults.parseTree).orderedImports.find( (i) => i.moduleName === moduleName )!; const edits = getTextEditsForAutoImportSymbolAddition(importNameInfo, importStatement, parseResults); const ranges = [...state.getRanges().filter((r) => !!r.marker?.data)]; assert.strictEqual(edits.length, ranges.length, `${markerName} expects ${ranges.length} but got ${edits.length}`); testTextEdits(state, edits, ranges); } function testInsertions( code: string, markerName: string, importNameInfo: ImportNameWithModuleInfo | ImportNameWithModuleInfo[] ) { const state = parseAndGetTestState(code).state; const marker = state.getMarkerByName(markerName)!; const parseResults = state.program.getBoundSourceFile(marker!.fileName)!.getParseResults()!; const importStatements = getTopLevelImports(parseResults.parseTree); const edits = getTextEditsForAutoImportInsertions( importNameInfo, importStatements, parseResults, convertOffsetToPosition(marker.position, parseResults.tokenizerOutput.lines) ); const ranges = [...state.getRanges().filter((r) => !!r.marker?.data)]; assert.strictEqual(edits.length, ranges.length, `${markerName} expects ${ranges.length} but got ${edits.length}`); testTextEdits(state, edits, ranges); } function testInsertion( code: string, markerName: string, importNameInfo: ImportNameInfo | ImportNameInfo[], moduleName: string, importType: ImportType ) { importNameInfo = isArray(importNameInfo) ? importNameInfo : [importNameInfo]; if (importNameInfo.length === 0) { importNameInfo.push({}); } testInsertions( code, markerName, importNameInfo.map((i) => { return { module: { moduleName, importType, isLocalTypingsFile: false, }, name: i.name, alias: i.alias, }; }) ); } function testTextEdits(state: TestState, edits: TextEditAction[], ranges: Range[]) { for (const edit of edits) { assert( ranges.some((r) => { const data = r.marker!.data as { r: string }; const expectedText = data.r; return ( rangesAreEqual(state.convertPositionRange(r), edit.range) && expectedText.replace(/!n!/g, '\n') === edit.replacementText ); }), `can't find '${edit.replacementText}'@'${edit.range.start.line},${edit.range.start.character}'` ); } }
the_stack
import React, { SyntheticEvent, useEffect, useRef } from 'react'; import { useEffectOnce, useSettings } from 'hooks'; import styled from 'styled-components'; import { DeviceThemeName, getTheme } from '../../utils/themes'; import FastForwardIcon from './icons/FastForwardIcon'; import MenuIcon from './icons/MenuIcon'; import PlayPauseIcon from './icons/PlayPauseIcon'; import RewindIcon from './icons/RewindIcon'; const Container = styled.div` user-select: none; position: relative; display: flex; justify-content: center; margin: auto 0; touch-action: none; transform: translate3d(0, 0, 0); `; const CanvasContainer = styled.div<{ width: number; height: number }>` position: relative; display: flex; justify-content: center; align-items: center; width: ${(props) => props.width}px; height: ${(props) => props.height}px; `; const Canvas = styled.canvas<{ deviceTheme: DeviceThemeName }>` border-radius: 50%; border: 1px solid ${({ deviceTheme }) => getTheme(deviceTheme).knob.outline}; background: ${({ deviceTheme }) => getTheme(deviceTheme).knob.background}; `; const CenterButton = styled.div<{ size: number; deviceTheme: DeviceThemeName }>` position: absolute; top: 0; bottom: 0; left: 0; right: 0; margin: auto; width: ${(props) => props.size / 2.5}px; height: ${(props) => props.size / 2.5}px; border-radius: 50%; box-shadow: ${({ deviceTheme }) => getTheme(deviceTheme).knob.centerButton.boxShadow} 0px 1em 3em inset; background: ${({ deviceTheme }) => getTheme(deviceTheme).knob.centerButton.background}; border: 1px solid ${({ deviceTheme }) => getTheme(deviceTheme).knob.centerButton.outline}}; :active { filter: brightness(0.9); } `; /** Custom Event from https://github.com/john-doherty/long-press-event */ interface LongPressEvent extends SyntheticEvent { detail: { clientX: number; clientY: number; }; } const ANGLE_ARC = (360 * Math.PI) / 180; const ANGLE_OFFSET = (0 * Math.PI) / 180; const START_ANGLE = 1.5 * Math.PI + ANGLE_OFFSET; const END_ANGLE = 1.5 * Math.PI + ANGLE_OFFSET + ANGLE_ARC; type Props = { value: number; onChange: (value: number) => void; onClick?: (e: React.MouseEvent) => void; onLongPress?: (e: Event) => void; onMenuLongPress?: (e: Event) => void; onWheelClick?: (value: number) => void; onChangeEnd?: (value: number) => void; min?: number; max?: number; step?: number; width?: number; height?: number; thickness?: number; bgColor?: string; fgColor?: string; className?: string; canvasClassName?: string; }; const Knob = ({ value, onChange, onChangeEnd = () => {}, onWheelClick = () => {}, onClick = () => {}, onLongPress = () => {}, onMenuLongPress = () => {}, min = 0, max = 100, step = 1, width = 200, height = 200, thickness = 0.35, bgColor = '#EEE', fgColor = '#EA2', className, canvasClassName, }: Props) => { const { deviceTheme } = useSettings(); const canvasRef = useRef<HTMLCanvasElement | undefined>(); const centerButtonRef = useRef<HTMLDivElement | undefined>(); const handleLongPress = (event: Event) => { event.preventDefault(); (event.target as any).setAttribute('longpress', new Date().getTime()); onLongPress(event); return false; }; const handleMenuLongPress = (event: Event) => { onMenuLongPress(event); }; const handleWheelLongPress = (event: LongPressEvent) => { event.preventDefault(); (event.target as any).setAttribute('longpress', new Date().getTime()); const rect = (event.target as Element).getBoundingClientRect(); const x = event.detail.clientX - rect.left; const y = event.detail.clientY - rect.top; console.log({ x, y }); const rectWidth = rect.width; const quadrant = findClickQuadrant(rectWidth, x, y); if (quadrant === 1) { handleMenuLongPress(event as any); } }; const getArcToValue = (v: number) => { const angle = ((v - min) * ANGLE_ARC) / (max - min); const startAngle = START_ANGLE - 0.00001; const endAngle = startAngle + angle + 0.00001; return { startAngle, endAngle, acw: false, }; }; const getCanvasScale = (ctx: CanvasRenderingContext2D) => { const devicePixelRatio = window.devicePixelRatio || (window.screen as any).deviceXDPI / (window.screen as any).logicalXDPI || // IE 11 1; const backingStoreRatio = (ctx as any).webkitBackingStorePixelRatio || 1; return devicePixelRatio / backingStoreRatio; }; const coerceToStep = (v: number) => { let val = ~~((v < 0 ? -0.5 : 0.5) + v / step) * step; val = Math.max(Math.min(val, max), min); if (isNaN(val)) { val = 0; } return Math.round(val * 1000) / 1000; }; const eventToValue = (e: any) => { const bounds = canvasRef.current?.getBoundingClientRect(); if (!bounds) { return 0; } const x = e.clientX - bounds.left; const y = e.clientY - bounds.top; let a = Math.atan2(x - width / 2, width / 2 - y) - ANGLE_OFFSET; if (ANGLE_ARC !== Math.PI * 2 && a < 0 && a > -0.5) { a = 0; } else if (a < 0) { a += Math.PI * 2; } const val = (a * (max - min)) / ANGLE_ARC + min; return coerceToStep(val); }; const handleMouseDown = (e: Event) => { onChange(eventToValue(e)); document.addEventListener('mousemove', handleMouseMove); document.addEventListener('mouseup', handleMouseUpNoMove); }; const handleTouchStart = (e: Event) => { onChange(eventToValue(e)); document.addEventListener('touchmove', handleTouchMove); document.addEventListener('touchend', handleTouchEndNoMove); document.removeEventListener('mousedown', handleMouseDown); }; const handleMouseMove = (e: Event) => { e.preventDefault(); const val = eventToValue(e); if (val !== value) { onChange(eventToValue(e)); } document.removeEventListener('mouseup', handleMouseUpNoMove); document.addEventListener('mouseup', handleMouseUp); }; const handleTouchMove = (e: Event) => { e.preventDefault(); const touchEvent = e as TouchEvent; const touchIndex = touchEvent.targetTouches.length - 1; const val = eventToValue(touchEvent.targetTouches[touchIndex]); if (val !== value) { onChange(val); } if (!canvasRef.current) { return; } canvasRef.current.removeEventListener( 'long-press', handleWheelLongPress as any ); document.removeEventListener('touchend', handleTouchEndNoMove); document.addEventListener('touchend', handleTouchEnd); }; const handleMouseUp = (e: Event) => { onChangeEnd(eventToValue(e)); document.removeEventListener('mousemove', handleMouseMove); document.removeEventListener('mouseup', handleMouseUp); }; const handleTouchEnd = (e: Event) => { const touchEvent = e as TouchEvent; const touchIndex = touchEvent.targetTouches.length - 1; onChangeEnd(touchEvent.targetTouches[touchIndex] as any); document.removeEventListener('touchmove', handleTouchMove); document.removeEventListener('touchend', handleTouchEnd); if (!canvasRef.current) { return; } canvasRef.current.addEventListener( 'long-press', handleWheelLongPress as any ); }; const findClickQuadrant = (rectSize: number, x: number, y: number) => { if (y < rectSize / 4) { return 1; } else if (y > rectSize * 0.75) { return 2; } else if (x < rectSize / 4) { return 3; } else if (x > rectSize * 0.75) { return 4; } return -1; }; const handleMouseUpNoMove = (e: Event) => { const mouseEvent = e as MouseEvent; const rect = (mouseEvent.target as Element).getBoundingClientRect(); const x = mouseEvent.clientX - rect.left; const y = mouseEvent.clientY - rect.top; const rectWidth = rect.width; const quadrant = findClickQuadrant(rectWidth, x, y); if (quadrant > 0 && quadrant <= 4) { onWheelClick(quadrant); } document.removeEventListener('mousemove', handleMouseMove); document.removeEventListener('mouseup', handleMouseUp); document.removeEventListener('mouseup', handleMouseUpNoMove); }; const handleTouchEndNoMove = (e: Event) => { const touchEvent = e as TouchEvent; const rect = (touchEvent.target as Element).getBoundingClientRect(); const touch = touchEvent.changedTouches[touchEvent.changedTouches.length - 1]; const x = touch.pageX - rect.left; const y = touch.pageY - rect.top; const rectWidth = rect.width; const quadrant = findClickQuadrant(rectWidth, x, y); if (quadrant > 0 && quadrant <= 4) { onWheelClick(quadrant); } document.removeEventListener('touchmove', handleTouchMove); document.removeEventListener('touchend', handleTouchEnd); document.removeEventListener('touchend', handleTouchEndNoMove); }; const drawCanvas = () => { if (!canvasRef.current) { return; } const ctx = canvasRef.current.getContext('2d')!; const scale = getCanvasScale(ctx); canvasRef.current.width = width * scale; // clears the canvas canvasRef.current.height = height * scale; ctx.scale(scale, scale); const xy = width / 2; // coordinates of canvas center const lineWidth = xy * thickness; const radius = xy - lineWidth / 2; ctx.lineWidth = lineWidth; ctx.lineCap = 'butt'; // background arc ctx.beginPath(); ctx.strokeStyle = bgColor; ctx.arc(xy, xy, radius, END_ANGLE - 0.00001, START_ANGLE + 0.00001, true); ctx.stroke(); // foreground arc const a = getArcToValue(value); ctx.beginPath(); ctx.strokeStyle = fgColor; ctx.arc(xy, xy, radius, a.startAngle, a.endAngle, a.acw); ctx.stroke(); }; // Component Did Mount useEffectOnce(() => { if (!canvasRef.current || !centerButtonRef.current) { console.error("Things didn't mount properly!"); return; } const isTouchEnabled = 'ontouchstart' in window || navigator.maxTouchPoints > 0 || navigator.msMaxTouchPoints > 0; drawCanvas(); if (isTouchEnabled) { canvasRef.current.addEventListener('touchstart', handleTouchStart); } else { canvasRef.current.addEventListener('mousedown', handleMouseDown); } centerButtonRef.current.addEventListener('long-press', handleLongPress); canvasRef.current.addEventListener( 'long-press', handleWheelLongPress as any ); // Component Will Unmount return () => { if (!canvasRef.current || !centerButtonRef.current) { console.error("Things didn't mount properly!"); return; } if (isTouchEnabled) { canvasRef.current.removeEventListener('touchstart', handleTouchStart); } else { canvasRef.current.removeEventListener('mousedown', handleMouseDown); } centerButtonRef.current.removeEventListener( 'long-press', handleLongPress ); canvasRef.current.removeEventListener( 'long-press', handleWheelLongPress as any ); }; }); // Component Did Update useEffect(() => { drawCanvas(); }); const buttonColor = getTheme(deviceTheme).knob.button; return ( <Container className={className}> <CanvasContainer width={width} height={height}> <Canvas ref={(ref) => { canvasRef.current = ref ?? undefined; }} className={canvasClassName} style={{ width: '100%', height: '100%' }} deviceTheme={deviceTheme} /> <CenterButton ref={(ref) => { centerButtonRef.current = ref ?? undefined; }} onClick={onClick} size={width} deviceTheme={deviceTheme} /> <MenuIcon top={'8%'} margin={'0 auto'} color={buttonColor} /> <PlayPauseIcon bottom={'8%'} margin={'0 auto'} color={buttonColor} /> <RewindIcon left={'8%'} margin={'auto 0'} color={buttonColor} /> <FastForwardIcon right={'8%'} margin={'auto 0'} color={buttonColor} /> </CanvasContainer> </Container> ); }; export default Knob;
the_stack
module Fayde.Localization { export class NumberFormatInfo { CurrencyDecimalDigits: number = 2; CurrencyDecimalSeparator: string = "."; CurrencyGroupSeparator: string = ","; CurrencyGroupSizes: number[] = [3]; CurrencyNegativePattern: number = 0; CurrencyPositivePattern: number = 0; CurrencySymbol: string = "$"; NaNSymbol: string = "NaN"; NegativeInfinitySymbol: string = "-Infinity"; PositiveInfinitySymbol: string = "Infinity"; NegativeSign: string = "-"; PositiveSign: string = "+"; NumberDecimalDigits: number = 2; NumberDecimalSeparator: string = "."; NumberGroupSeparator: string = ","; NumberGroupSizes: number[] = [3]; NumberNegativePattern: number = 1; PercentDecimalDigits: number = 2; PercentDecimalSeparator: string = "."; PercentGroupSeparator: string = ","; PercentGroupSizes: number[] = [3]; PercentNegativePattern: number = 0; PercentPositivePattern: number = 0; PercentSymbol: string = "%"; PerMilleSymbol: string = "‰"; static Instance = new NumberFormatInfo(); FormatCurrency(num: number, precision: number): string { if (precision == null) precision = this.CurrencyDecimalDigits; var rawnum = this.FormatRawNumber(Math.abs(num), precision, this.CurrencyDecimalSeparator, this.CurrencyGroupSeparator, this.CurrencyGroupSizes); if (num < 0) { switch (this.CurrencyNegativePattern) { case 0: default: return "(" + this.CurrencySymbol + rawnum + ")"; case 1: return [this.NegativeSign, this.CurrencySymbol, rawnum].join(""); case 2: return [this.CurrencySymbol, this.NegativeSign, rawnum].join(""); case 3: return [this.CurrencySymbol, rawnum, this.NegativeSign].join(""); case 4: return "(" + rawnum + this.CurrencySymbol + ")"; case 5: return [this.NegativeSign, rawnum, this.CurrencySymbol].join(""); case 6: return [rawnum, this.NegativeSign, this.CurrencySymbol].join(""); case 7: return [rawnum, this.CurrencySymbol, this.NegativeSign].join(""); case 8: return [this.NegativeSign, rawnum, " ", this.CurrencySymbol].join(""); case 9: return [this.NegativeSign, this.CurrencySymbol, " ", rawnum].join(""); case 10: return [rawnum, " ", this.CurrencySymbol, this.NegativeSign].join(""); case 11: return [this.CurrencySymbol, " ", rawnum, this.NegativeSign].join(""); case 12: return [this.CurrencySymbol, " ", this.NegativeSign, rawnum].join(""); case 13: return [rawnum, this.NegativeSign, " ", this.CurrencySymbol].join(""); case 14: return "(" + this.CurrencySymbol + " " + rawnum + ")"; case 15: return "(" + rawnum + " " + this.CurrencySymbol + ")"; } } else { switch (this.CurrencyPositivePattern) { case 0: default: return [this.CurrencySymbol, rawnum].join(""); case 1: return [rawnum, this.CurrencySymbol].join(""); case 2: return [this.CurrencySymbol, rawnum].join(" "); case 3: return [rawnum, this.CurrencySymbol].join(" "); } } } FormatNumber(num: number, precision: number, ignoreGroupSep?: boolean): string { if (precision == null) precision = this.NumberDecimalDigits; var rawnum = this.FormatRawNumber(Math.abs(num), precision, this.NumberDecimalSeparator, ignoreGroupSep ? "" : this.NumberGroupSeparator, this.NumberGroupSizes); if (num >= 0) return rawnum; switch (this.NumberNegativePattern) { case 0: return "(" + rawnum + ")"; case 1: default: return [this.NegativeSign, rawnum].join(""); case 2: return [this.NegativeSign, rawnum].join(" "); case 3: return [rawnum, this.NegativeSign].join(""); case 4: return [rawnum, this.NegativeSign].join(" "); } } FormatPercent(num: number, precision: number): string { if (precision == null) precision = this.PercentDecimalDigits; var rawnum = this.FormatRawNumber(Math.abs(num * 100), precision, this.PercentDecimalSeparator, this.PercentGroupSeparator, this.PercentGroupSizes); var sym = this.PercentSymbol; if (num < 0) { var sign = this.NegativeSign; switch (this.PercentNegativePattern) { case 0: default: return [sign, rawnum, " ", sym].join(""); case 1: return [sign, rawnum, sym].join(""); case 2: return [sign, sym, rawnum].join(""); case 3: return [sym, sign, rawnum].join(""); case 4: return [sym, rawnum, sign].join(""); case 5: return [rawnum, sign, sym].join(""); case 6: return [rawnum, sym, sign].join(""); case 7: return [sign, sym, " ", rawnum].join(""); case 8: return [sign, sym, " ", rawnum].join(""); case 9: return [sym, " ", rawnum, sign].join(""); case 10: return [sym, " ", sign, rawnum].join(""); case 11: return [rawnum, sign, " ", sym].join(""); } } else { switch (this.PercentPositivePattern) { case 0: default: return [rawnum, this.PercentSymbol].join(" "); case 1: return [rawnum, this.PercentSymbol].join(""); case 2: return [this.PercentSymbol, rawnum].join(""); case 3: return [this.PercentSymbol, rawnum].join(" "); } } } FormatGeneral(num: number, precision: number): string { if (precision == null) precision = 6; var sig = sigDigits(Math.abs(num), precision); var rawnum = sig.toString(); if (num >= 0) return rawnum; return this.NegativeSign + rawnum; } FormatDecimal(num: number, precision: number): string { var rawnum = this.FormatRawNumber(Math.abs(num), 0, "", "", null); var d = padded(rawnum, precision || 0, true); if (num < 0) d = this.NegativeSign + d; return d; } FormatExponential(num: number, precision: number): string { if (precision == null) precision = 6; var e = num.toExponential(precision); var tokens = e.split("e+"); return tokens[0] + "e" + this.PositiveSign + padded(tokens[1], 3, true); } FormatHexadecimal(num: number, precision: number): string { if (precision == null) precision = 2; num = parseInt(<any>num); if (num >= 0) return padded(num.toString(16), precision, true); var us = (Math.pow(2, 32) + num).toString(16); if (precision >= us.length) return padded(us, precision, true); var start = 0; while (us.length - start > precision && us[start] === "f") { start++; } return us.substr(start); } FormatRawNumber(num: number, precision: number, decSep: string, groupSep: string, groupSizes: number[]): string { //Ignoring group sizes for now: using [3] var rounded = round(num, precision); var ip = Math.floor(rounded).toString(); var fp = rounded.toString().split('.')[1]; var pfp = padded(fp, precision); if (!pfp) return grouped(ip, groupSep); return [ grouped(ip, groupSep), pfp ].join(decSep); } } function grouped(s: string, sep: string): string { if (s.length < 4) return s; var offset = s.length % 3; if (offset !== 0) { offset = 3 - offset; s = new Array(offset + 1).join("0") + s; } return s.match(/\d\d\d/g).join(sep).substr(offset); } function padded(s: string, precision: number, front?: boolean): string { if (!s) return new Array(precision + 1).join("0"); if (s.length > precision) return front ? s : s.substr(0, precision); if (front) return new Array(precision - s.length + 1).join("0") + s; return s + new Array(precision - s.length + 1).join("0"); } function round(num: number, places: number): number { var factor = Math.pow(10, places); return Math.round(num * factor) / factor; } function sigDigits(num: number, digits: number): number { var n = num.toString(); var index = n.indexOf("."); if (index > -1) return round(num, digits - index); return round(num, digits - n.length); } // Currency Negative Patterns // 0 ($n) // 1 -$n // 2 $-n // 3 $n- // 4 (n$) // 5 -n$ // 6 n-$ // 7 n$- // 8 -n $ // 9 -$ n // 10 n $- // 11 $ n- // 12 $ -n // 13 n- $ // 14 ($ n) // 15 (n $) // Currency Positive Patterns // 0 $n // 1 n$ // 2 $ n // 3 n $ // Number Negative Patterns // 0 (n) // 1 -n // 2 - n // 3 n- // 4 n - // Percent Negative Patterns // 0 -n % // 1 -n% // 2 -%n // 3 %-n // 4 %n- // 5 n-% // 6 n%- // 7 -% n // 8 n %- // 9 % n- // 10 % -n // 11 n- % // Percent Positive Patterns // 0 n % // 1 n% // 2 %n // 3 % n }
the_stack
import { IHeader, HeaderType, HeaderResizeBehavior, HeaderFilter, HeaderClampFunction } from './types'; import { IHeaderRepositoryCache } from './header-repository-cache'; export interface IHeaderRepositoryProps { cache?: IHeaderRepositoryCache; rows: IHeader[]; columns: IHeader[]; columnWidth: number; rowHeight: number; headersHeight: number; headersWidth: number; filter?: HeaderFilter; } export interface IHeaderRepositoryState extends IHeaderRepositoryProps { viewColumns: IHeader[]; viewRows: IHeader[]; offsetWidth: number; offsetHeight: number; /** header's type */ types: { [headerId: string]: HeaderType }; /** header's parent */ parents: { [headerId: string]: IHeader }; /** header's position */ positions: { [headerId: string]: number }; /** header's index */ indices: { [headerId: string]: number }; /** header's level */ levels: { [headerId: string]: number }; // CACHED: /** maximum levels */ viewLeftLevels: number; viewTopLevels: number; /** level sizes */ leftLevels: { [level: number]: number }; topLevels: { [level: number]: number }; /** header manual resized flag */ headerManualResized: Set<string | number>; /** level manual resized flag */ levelManualResized: Set<string | number>; } export class HeaderRepository { private _idCounter = 0; private _state: IHeaderRepositoryState; private _idMap: { [id: string]: IHeader; } = {}; constructor(props: IHeaderRepositoryProps) { if (!props) { return; } this._state = { ...props, offsetWidth: 0, offsetHeight: 0, viewColumns: null, viewRows: null, viewLeftLevels: 0, viewTopLevels: 0, leftLevels: {}, topLevels: {}, types: {}, indices: {}, positions: {}, levels: {}, parents: {}, headerManualResized: new Set<string>(), levelManualResized: new Set<string>() }; this._state.viewColumns = this._create(props.columns, [], HeaderType.Column, props.filter); this._state.viewRows = this._create(props.rows, [], HeaderType.Row, props.filter); this._calcPosition(); this._calcLevels(); } get columnWidth() { return this._state.columnWidth; } get rowHeight() { return this._state.rowHeight; } get headersHeight() { return this._state.headersHeight; } get headersWidth() { return this._state.headersWidth; } /** Total width of row headers. */ get offsetWidth() { return ( this._state.cache ? this._state.cache.getOffset('left') : this._state.offsetWidth ); } /** Total height of column headers. */ get offsetHeight() { return ( this._state.cache ? this._state.cache.getOffset('top') : this._state.offsetHeight ); } get topLevels() { return ( this._state.cache ? this._state.cache.getLevels('top') : this._state.viewTopLevels ); } get leftLevels() { return ( this._state.cache ? this._state.cache.getLevels('left') : this._state.viewLeftLevels ); } get columns() { return this._state.viewColumns; } get rows() { return this._state.viewRows; } toJSON() { return { source: { rows: this._state.rows, columns: this._state.columns, }, view: { rows: this.rows, columns: this.columns, }, settings: { columnWidth: this.columnWidth, rowHeight: this.rowHeight, headersHeight: this.headersHeight, headersWidth: this.headersWidth, canvasHeight: this.offsetHeight, canvasWidth: this.offsetWidth, topLevels: this.topLevels, leftLevels: this.leftLevels, filter: !!this._state.filter } }; } private _create( list: IHeader[], out: IHeader[], type: HeaderType, filter?: HeaderFilter, assignParent?: IHeader ) { list.forEach((h) => { h.$id = h.$id || ++this._idCounter; this._state.positions[h.$id] = 0; if (assignParent) { this._state.parents[h.$id] = assignParent; } if (filter && !filter({ header: h, type })) { return; } if (!h.$collapsed && h.$children && h.$children.length) { this._create(h.$children, out, type, filter, h); return; } out.push(h); }); return out; } private _createClone() { let c = new HeaderRepository(null); c._state = { ...this._state, leftLevels: { ...this._state.leftLevels }, topLevels: { ...this._state.topLevels }, types: { ...this._state.types }, indices: { ...this._state.indices }, positions: { ...this._state.positions }, levels: { ...this._state.levels }, parents: { ...this._state.parents }, headerManualResized: new Set(this._state.headerManualResized), levelManualResized: new Set(this._state.levelManualResized) }; return c; } private _applyHeaderLevel(h: IHeader) { let level = 0; let seek = h; while (this._state.parents[seek.$id]) { level++; seek = this._state.parents[seek.$id]; } this._state.levels[h.$id] = level; if (this._state.parents[h.$id]) { this._applyHeaderLevel(this._state.parents[h.$id]); } return level; } private _applyParentPosition(list: IHeader[], type: HeaderType) { let lock = new Set<string | number>(); let parents: IHeader[] = []; list.forEach((h) => { this._idMap[h.$id] = h; this._state.types[h.$id] = type; let first = h.$children[0]; let last = h.$children[h.$children.length - 1]; this._state.positions[h.$id] = this._state.positions[first.$id]; h.$size = this._state.positions[last.$id] + this.getSize(last) - this._state.positions[first.$id]; if (this._state.cache) { this._state.cache.setHeaderSize(h.$size, h, type); } let parent = this._state.parents[h.$id]; if (parent && !lock.has(parent.$id)) { lock.add(parent.$id); parents.push(parent); } }); if (parents.length) { this._applyParentPosition(parents, type); } } private _proceedHeaders(list: IHeader[], from: number, size: number, type: HeaderType) { let len = list.length; if (!len) { return 0; } let cursor = this._state.positions[list[from].$id]; let levels = 0; let lock = new Set<string | number>(); let parents: IHeader[] = []; for (let i = from; i < len; i++) { let h = list[i]; this._state.indices[h.$id] = (!h.$collapsed && h.$children && h.$children[0]) ? -1 : i; this._state.positions[h.$id] = cursor; this._state.types[h.$id] = type; this._idMap[h.$id] = h; for (let p of ['$size', '$sizeCollapsed']) { if (!h[p]) { if (this._state.cache) { let _h = { ...h, $collapsed: p === '$sizeCollapsed' }; let cachedSize = this._state.cache.getHeaderSize(_h, type); h[p] = cachedSize || size; if (!cachedSize) { this._state.cache.setHeaderSize(h[p], _h, type); } } else { h[p] = size; } } } cursor += this.getSize(h); let l = this._applyHeaderLevel(h); if (l > levels) { levels = l; } let parent = this._state.parents[h.$id]; if (parent && !lock.has(parent.$id)) { lock.add(parent.$id); parents.push(parent); } } if (parents.length) { this._applyParentPosition(parents, type); } return levels + 1; } private _calcLevels() { let w = 0, h = 0; for (let i = 0; i < this.leftLevels; i++) { w += this.getLeftLevelWidth(i); } for (let i = 0; i < this.topLevels; i++) { h += this.getTopLevelHeight(i); } this._state.offsetWidth = w || this._state.headersWidth; this._state.offsetHeight = h || this._state.headersHeight; if (this._state.cache) { this._state.cache.setOffset(this._state.offsetWidth, 'left'); this._state.cache.setOffset(this._state.offsetHeight, 'top'); } } private _calcPosition(from = 0) { this._state.viewTopLevels = this._proceedHeaders(this._state.viewColumns, from, this._state.columnWidth, HeaderType.Column); this._state.viewLeftLevels = this._proceedHeaders(this._state.viewRows, from, this._state.rowHeight, HeaderType.Row); if (this._state.cache) { this._state.cache.setLevels(this._state.viewLeftLevels, 'left'); this._state.cache.setLevels(this._state.viewTopLevels, 'top'); } } private _getLevelPosition(type: 'left' | 'top', level: number) { if (level >= (type === 'left' ? this.leftLevels : this.topLevels)) { return 0; } let p = 0; for (let i = 0; i < level; i++) { p += (type === 'left' ? this.getLeftLevelWidth(i) : this.getTopLevelHeight(i)); } return p; } private _getLeaves(h: IHeader, out: IHeader[] = []) { if (h.$collapsed || !h.$children || !h.$children.length) { out.push(h); return out; } h.$children.forEach(c => this._getLeaves(c, out)); return out; } private _getAllNodesByChildren(headers: IHeader[], lock = new Set<string | number>(), out: IHeader[] = []) { headers.forEach((h) => { if (!h) { return; } if (!lock.has(h.$id)) { out.push(h); lock.add(h.$id); } if (h.$children && h.$children.length) { this._getAllNodesByChildren(h.$children, lock, out); } }); return out; } private _getAllNodesByParents(headers: IHeader[], lock = new Set<string | number>(), out: IHeader[] = []) { const seek = (h: IHeader) => { if (!h) { return; } if (!lock.has(h.$id)) { out.push(h); lock.add(h.$id); } seek(this.getParent(h)); }; headers.forEach((h) => { seek(h); }); return out; } private _getResizeList(h: IHeader, size: number, clamp: HeaderClampFunction) { if (h.$collapsed || !h.$children || !h.$children.length) { size = clamp({ header: h, type: this._state.types[h.$id], size }); } let prevSize = this.getSize(h); if (h.$collapsed || !h.$children || !h.$children.length) { return [{ header: h, size }]; } let leaves = this.getHeaderLeaves(h); let d = 0; if (clamp) { leaves.forEach((c) => { let n = Math.floor(this.getSize(c) * size / prevSize); let m = clamp({ header: h, type: this._state.types[h.$id], size: n - d }); if (n < m) { d += m - n; } }); } return leaves.map((c) => { return { header: c, size: clamp({ header: c, type: this._state.types[c.id], size: Math.floor(this.getSize(c) * size / prevSize) - d }) }; }); } private _getHeaderAddress(h: IHeader, root: IHeader[]) { let ix: number[] = []; let seek = h; while (seek) { let p = this.getParent(seek); let list = p ? p.$children : root; let index = list.findIndex(c => c.$id === seek.$id); ix.push(index); seek = p; } ix.push(-1); // -1 means root return ix.reverse(); } private _mapBranch(address: number[], list: IHeader[], map: (h: IHeader) => IHeader): IHeader[] { if (!list) { return list; } let len = address.length; let output = list.map((h) => { if (!len) { return map(h); } return { ...h, $children: this._mapBranch(address.slice(1), h.$children, map) }; }); return output; } private _recalcHeaders() { this._state.viewColumns = null; this._state.viewRows = null; this._state.types = {}; this._state.indices = {}; this._state.positions = {}; this._state.levels = {}; this._state.parents = {}; this._state.viewColumns = this._create(this._state.columns, [], HeaderType.Column, this._state.filter); this._state.viewRows = this._create(this._state.rows, [], HeaderType.Row, this._state.filter); this._calcPosition(); this._calcLevels(); return this; } private _updateHeaders( branchMap: { [branchName: string]: { [$id: string]: IHeader; }; }, sourceList: IHeader[] ) { let branchList = Object.keys(branchMap); if (!branchList.length) { return sourceList; } branchList.forEach((branch) => { let address = branch.split('/').filter(v => !!v).map(Number); let updateMap = branchMap[branch]; // removing first -1 element, that represents root address.shift(); sourceList = this._mapBranch(address, sourceList, (h) => { let update = updateMap[h.$id]; if (!update) { return h; } let next = { ...h }; Object.keys(update).forEach((key) => { if (key === '$id') { return; } next[key] = update[key]; }); return next; }); }); return sourceList; } public getHeader(id: number | string) { return this._idMap[id]; } public getHeaderType(h: IHeader) { return this._state.types[h.$id]; } public getViewIndex(h: IHeader) { return this._state.indices[h.$id]; } public getPosition(h: IHeader) { return this._state.positions[h.$id]; } public getManualResized(h: IHeader) { return ( this._state.cache ? this._state.cache.getHeaderLock(h, this._state.types[h.$id]) : this._state.headerManualResized.has(h.$id) ); } public getManualResizedLevel(type: HeaderType, level: number) { return ( this._state.cache ? this._state.cache.getLevelLock(level, type) : this._state.levelManualResized.has(`${type}:${level}`) ); } /** Header level in logic tree. Used for positioning. */ public getLevel(h: IHeader) { return this._state.levels[h.$id]; } /** Header level in canvas. Used for measuring. */ public getPositionLevel(h: IHeader) { const level = this.getLevel(h); const maxLevel = (this._state.types[h.$id] === HeaderType.Column ? this.topLevels : this.leftLevels) - 1; const hasChildren = h.$children && h.$children.length; return level < maxLevel && (h.$collapsed || !hasChildren) ? maxLevel : level; } public getParent(h: IHeader) { return this._state.parents[h.$id]; } public getTopLevelPosition(level: number) { return this._getLevelPosition('top', level); } public getLeftLevelPosition(level: number) { return this._getLevelPosition('left', level); } public getSize(h: IHeader) { if (!h) { return 0; } if (this._state.cache) { return this._state.cache.getHeaderSize(h, this._state.types[h.$id]); } return h.$collapsed ? h.$sizeCollapsed : h.$size; } public getLeftLevelWidth(level: number, isCollapsed?: boolean) { if (isCollapsed) { return this.offsetWidth - this.getLeftLevelPosition(level); } let v = ( this._state.cache ? this._state.cache.getLevelSize(level, 'left') : this._state.leftLevels[level] ); return v || this._state.headersWidth; } public getTopLevelHeight(level: number, isCollapsed?: boolean) { if (isCollapsed) { return this.offsetHeight - this.getTopLevelPosition(level); } let v = ( this._state.cache ? this._state.cache.getLevelSize(level, 'top') : this._state.topLevels[level] ); return v || this._state.headersHeight; } public getHeaderLeaves(h: IHeader) { return this._getLeaves(h); } /** top-down search */ public getNodesTopDown(h: IHeader[]) { return this._getAllNodesByChildren(h); } /** bottom-up search */ public getNodesBottomUp(h: IHeader[]) { return this._getAllNodesByParents(h); } public getSource() { return { cache: this._state.cache, columns: this._state.columns, rows: this._state.rows, columnWidth: this._state.columnWidth, rowHeight: this._state.rowHeight, headersHeight: this._state.headersHeight, headersWidth: this._state.headersWidth, filter: this._state.filter } as IHeaderRepositoryProps; } /** Create clone of repository with new applied filter. */ public updateFilter(filter: HeaderFilter) { if (this._state.filter === filter) { return this; } let next = this._createClone(); next._state.filter = filter; return next._recalcHeaders(); } /** Update provided headers. Returns new perository. */ public updateHeaders(updates: { header: IHeader, update: IHeader }[]) { let mapColumns: { [branchName: string]: { [$id: string]: IHeader; }; } = {}; let mapRows: typeof mapColumns = {}; updates.forEach(({ header, update }) => { let headerType = this._state.types[header.$id]; let address = this._getHeaderAddress(header, headerType === HeaderType.Row ? this._state.rows : this._state.columns); let map = headerType === HeaderType.Column ? mapColumns : mapRows; let branchName = address.slice(0, address.length - 1).join('/'); if (!map[branchName]) { map[branchName] = {}; } map[branchName][header.$id] = update; }); let next = this._createClone(); next._state.columns = this._updateHeaders(mapColumns, next._state.columns); next._state.rows = this._updateHeaders(mapRows, next._state.rows); next = next._recalcHeaders(); return next; } /** * Resize all headers. * @param list Array of headers. * @param clamp Size clamp function. * @param behavior Defines flag when header was resized by autosize or manually. * Header will not be autosized when it was manually resized. Default `"manual"`. */ public resizeHeaders({ headers, clamp, behavior }: { headers: { header: IHeader, size: number }[]; clamp?: HeaderClampFunction; behavior?: HeaderResizeBehavior; }) { if (!headers || !headers.length) { return this; } clamp = clamp || (({ size }) => size); behavior = behavior || 'manual'; let updates: { header: IHeader, update: IHeader }[] = []; let leaves: IHeader[] = []; headers.forEach((u) => { let resizeList = this._getResizeList(u.header, u.size, clamp); resizeList.forEach(({ header, size }) => { leaves.push(header); updates.push({ header, update: ( header.$collapsed ? { $sizeCollapsed: size } : { $size: size } ) }); if (this._state.cache) { this._state.cache.setHeaderSize(size, header, this._state.types[header.$id]); } }); }); let c = this.updateHeaders(updates); switch (behavior) { case 'manual': case 'reset': let isManual = behavior === 'manual'; leaves.forEach((header) => { if (isManual) { c._state.headerManualResized.add(header.$id); if (c._state.cache) { c._state.cache.setHeaderLock(true, header, this._state.types[header.$id]); } } else { c._state.headerManualResized.delete(header.$id); if (c._state.cache) { c._state.cache.setHeaderLock(false, header, this._state.types[header.$id]); } } }); } return c; } /** Resize header levels, returns new repository. */ public resizeLevels({ levels, behavior }: { levels: { type: HeaderType; level: number; size: number; min?: number; max?: number; }[], behavior?: HeaderResizeBehavior }) { behavior = behavior || 'manual'; let next = this._createClone(); for (let { level, type, size, max, min } of levels) { min = min == null ? 5 : min; max = max == null ? Infinity : max; let levelSize = Math.min(Math.max(min, size), max); if (type === HeaderType.Column) { if (next._state.cache) { next._state.cache.setLevelSize(levelSize, level, 'top'); } next._state.topLevels[level] = levelSize; } else { if (next._state.cache) { next._state.cache.setLevelSize(levelSize, level, 'left'); } next._state.leftLevels[level] = levelSize; } switch (behavior) { case 'manual': case 'reset': let isManual = behavior === 'manual'; let key = `${type}:${level}`; if (isManual) { next._state.levelManualResized.add(key); if (next._state.cache) { next._state.cache.setLevelLock(true, level, type); } } else { next._state.levelManualResized.delete(key); if (next._state.cache) { next._state.cache.setLevelLock(false, level, type); } } } } return next._recalcHeaders(); } /** Update repository with new state properties. Returns new repository. */ public update(props: IHeaderRepositoryProps) { let next = this._createClone(); next._state = { ...next._state, ...props }; return next._recalcHeaders(); } } export default HeaderRepository;
the_stack
import React, { useState, useMemo, useEffect } from "react"; import { Link } from "react-router-dom"; import { OrgComponent } from "@ui_types"; import { Rbac, Model, Client, Auth, Api } from "@core/types"; import * as g from "@core/lib/graph"; import * as R from "ramda"; import { inviteRoute } from "./helpers"; import * as styles from "@styles"; import { style } from "typestyle"; import * as z from "zod"; import { SvgImage, SmallLoader } from "@images"; import * as ui from "@ui"; import { graphTypes } from "@core/lib/graph"; import { AddInviteAppForm } from "./add_invite_app_form"; import { AddInviteTeams } from "./add_invite_teams"; import { logAndAlertError } from "@ui_lib/errors"; const emailValidator = z.string().email(); export const InviteForm: OrgComponent<{ editIndex?: string; appId?: string; }> = (props) => { const { graph, graphUpdatedAt, pendingInvites } = props.core; const currentUserId = props.ui.loadedAccountId!; const appId = props.routeParams.appId; const samlProviders = graphTypes(graph).externalAuthProviders.filter( (p) => p.provider === "saml" ); const scimProviders = graphTypes(graph).scimProvisioningProviders; const editIndex = props.routeParams.editIndex ? parseInt(props.routeParams.editIndex) : undefined; const editingPendingInvite = typeof editIndex == "number" ? pendingInvites[editIndex] : undefined; // Default to SAML const [provider, setProvider] = useState<Auth.AuthProviderType>( editingPendingInvite?.user.provider ?? (samlProviders.length > 0 ? "saml" : "email") ); const [externalAuthProviderId, setExternalAuthProviderId] = useState< string | undefined >( editingPendingInvite?.user.externalAuthProviderId ?? (samlProviders.length > 0 ? samlProviders[0].id : undefined) ); const [scimProviderId, setScimProviderId] = useState<string | undefined>( editingPendingInvite?.scim?.providerId ?? scimProviders?.[0]?.id ); const [loadingScimCandidates, setLoadingScimCandidates] = useState(false); const [scimCandidates, setScimCandidates] = useState< Model.ScimUserCandidate[] >([]); const [selectedScimCandidateIds, setSelectedScimCandidateIds] = useState< string[] >([]); const [firstName, setFirstName] = useState( editingPendingInvite?.user.firstName ?? "" ); const [lastName, setLastName] = useState( editingPendingInvite?.user.lastName ?? "" ); const [email, setEmail] = useState(editingPendingInvite?.user.email ?? ""); const [submittedEmails, setSubmittedEmails] = useState<string[]>([]); const [showAddTeams, setShowAddTeams] = useState(false); const [showAddApps, setShowAddApps] = useState(false); const [invitableOrgRoleIds, grantableAppIds, grantableUserGroupIds] = useMemo(() => { let grantableAppIds = g.authz .getAccessGrantableApps(graph, currentUserId) .map(R.prop("id")); if (appId) { grantableAppIds = [appId, ...R.without([appId], grantableAppIds)]; } const grantableUserGroupIds = g.authz.hasOrgPermission( graph, currentUserId, "org_manage_teams" ) ? (g.getGroupsByObjectType(graph)["orgUser"] ?? []).map(R.prop("id")) : []; return [ g.authz.getInvitableOrgRoles(graph, currentUserId).map(R.prop("id")), grantableAppIds, grantableUserGroupIds, ]; }, [graphUpdatedAt, currentUserId]); const [ license, org, numActiveDevicesOrPendingInvites, numActiveUsersOrPendingInvites, ] = useMemo(() => { const { license, org } = g.graphTypes(graph); const numActiveDevices = org.deviceLikeCount; const numActiveUsers = org.activeUserOrInviteCount; const numPendingInvites = props.core.pendingInvites.length; const numActiveDevicesOrPendingInvites = numActiveDevices + numPendingInvites; const numActiveUsersOrPendingInvites = numActiveUsers ? numActiveUsers + numPendingInvites : undefined; return [ license, org, numActiveDevicesOrPendingInvites, numActiveUsersOrPendingInvites, ]; }, [ graphUpdatedAt, props.core.pendingInvites.length, currentUserId, props.ui.now, ]); const [orgRoleId, setOrgRoleId] = useState( editingPendingInvite?.user.orgRoleId ?? invitableOrgRoleIds[invitableOrgRoleIds.length - 1] ); const [initialPending, setInitialPending] = useState<Client.PendingInvite>(); const grantableAppRoleIdsByAppId = useMemo( () => R.mergeAll( grantableAppIds.map((id) => ({ [id]: g.authz .getAccessGrantableAppRolesForOrgRole( graph, currentUserId, id, orgRoleId ) .map(R.prop("id")), })) ), [graphUpdatedAt, currentUserId, grantableAppIds, orgRoleId] ); const pendingEmails = useMemo( () => new Set( R.without([editingPendingInvite], props.core.pendingInvites).map( (pending) => pending!.user.email ) ), [props.core.pendingInvites.length] ); const initialPendingEmails = useMemo(() => pendingEmails, []); const activeEmails = useMemo( () => new Set(g.getActiveOrgUsers(graph).map(R.prop("email"))), [graphUpdatedAt] ); const emailValid = useMemo( () => !email || emailValidator.safeParse(email).success, [email] ); const defaultAppUserGrants: Required<Client.PendingInvite["appUserGrants"]> = appId ? [ { appId, appRoleId: R.last(grantableAppRoleIdsByAppId[appId])!, }, ] : []; const [appUserGrantsByAppId, setAppUserGrantsByAppId] = useState< Record<string, Required<Client.PendingInvite>["appUserGrants"][0]> >( R.indexBy( R.prop("appId"), editingPendingInvite?.appUserGrants ?? defaultAppUserGrants ) ); const [userGroupIds, setUserGroupIds] = useState<string[]>( editingPendingInvite?.userGroupIds ?? [] ); const scimCandidatesById = useMemo( () => R.indexBy(R.prop("id"), scimCandidates), [scimCandidates] ); useEffect(() => { if (editingPendingInvite) { setInitialPending(getPending()); } }, []); useEffect(() => { setSelectedScimCandidateIds([]); setScimCandidates([]); if (!scimProviderId || editingPendingInvite) { return; } setLoadingScimCandidates(true); props .dispatch({ type: Api.ActionType.LIST_INVITABLE_SCIM_USERS, payload: { id: scimProviderId, all: true }, }) .then((res) => { if (res.success) { const fetchedCandidates = ( (res.resultAction as any) .payload as Api.Net.ApiResultTypes["ListInvitableScimUsers"] ).scimUserCandidates; if (fetchedCandidates.length > 0) { setScimCandidates(fetchedCandidates); } // else { // test data // setScimCandidates( // R.times<Model.ScimUserCandidate>( // (i) => ({ // type: "scimUserCandidate", // id: i.toString(), // orgId: "orgId", // providerId: scimProviderId, // firstName: "User", // lastName: i.toString(), // email: `test${i}@test.com`, // scimUserName: `test${i}@test.com`, // scimDisplayName: `test${i}@test.com`, // scimExternalId: i.toString(), // active: true, // orgUserId: "orgUserId", // createdAt: 0, // updatedAt: 0, // }), // 20 // ) // ); // } } }) .catch((err) => { logAndAlertError(`There was a problem listing SCIM users.`, err); }) .finally(() => setLoadingScimCandidates(false)); }, [scimProviderId]); useEffect(() => { if ( submittedEmails.length > 0 && submittedEmails.every((submittedEmail) => pendingEmails.has(submittedEmail) ) ) { props.history.push(inviteRoute(props, "/invite-users")); } }, [pendingEmails]); useEffect(() => { if (provider === "email") { setExternalAuthProviderId(undefined); } else if (!externalAuthProviderId) { setExternalAuthProviderId(samlProviders[0]?.id); } }, [provider]); const getPending = (scimCandidateId?: string): Client.PendingInvite => { const appUserGrants = Object.values(appUserGrantsByAppId); const scimCandidate = scimCandidateId ? scimCandidatesById[scimCandidateId] : undefined; const orgRole = graph[orgRoleId] as Rbac.OrgRole; return { user: { provider: provider as "saml" | "email", externalAuthProviderId: provider === "saml" ? externalAuthProviderId : undefined, uid: scimCandidate?.email ?? email, email: scimCandidate?.email ?? email, firstName: scimCandidate?.firstName ?? firstName, lastName: scimCandidate?.lastName ?? lastName, orgRoleId, }, appUserGrants: !orgRole.autoAppRoleId && appUserGrants.length > 0 ? appUserGrants : undefined, userGroupIds: !orgRole.autoAppRoleId && userGroupIds.length > 0 ? userGroupIds : undefined, scim: scimProviderId && scimCandidateId ? { candidateId: scimCandidateId, providerId: scimProviderId, } : undefined, }; }; const canSubmit = orgRoleId && ((!editingPendingInvite && scimProviderId && selectedScimCandidateIds.length > 0) || (email && firstName && lastName && emailValid && !initialPendingEmails.has(email) && !activeEmails.has(email))); const singleUserPending = editingPendingInvite || !scimProviderId ? getPending() : undefined; const hasChange = !editingPendingInvite || !singleUserPending || !R.equals(initialPending, singleUserPending); const onSubmit = async () => { if (!canSubmit) { return; } if (typeof editIndex == "number" && singleUserPending) { const res = await props.dispatch({ type: Client.ActionType.UPDATE_PENDING_INVITE, payload: { index: editIndex, pending: singleUserPending }, }); if (res.success) { props.history.push(inviteRoute(props, "/invite-users")); } else { logAndAlertError( "There was a problem updating the pending invite.", (res.resultAction as any)?.payload ); } } else if (scimProviderId) { setSubmittedEmails( selectedScimCandidateIds.map((id) => scimCandidatesById[id].email) ); let failed = false; for (let id of selectedScimCandidateIds) { const res = await props.dispatch({ type: Client.ActionType.ADD_PENDING_INVITE, payload: getPending(id), }); if (!res.success) { console.error( "There was a problem adding the pending invite.", (res.resultAction as any)?.payload ); } } if (failed) { logAndAlertError("There was a problem adding the pending invite."); } } else if (singleUserPending) { setSubmittedEmails([email]); props .dispatch({ type: Client.ActionType.ADD_PENDING_INVITE, payload: singleUserPending, }) .then((res) => { if (!res.success) { logAndAlertError( `There was a problem adding the pending invite.`, (res.resultAction as any)?.payload ); } }); } }; let cancelBtn: React.ReactNode; if (pendingInvites.length > 0) { cancelBtn = ( <button className="secondary" onClick={() => { props.history.push(inviteRoute(props, "/invite-users")); }} > ← Back </button> ); } const licenseExpired = license.expiresAt != -1 && props.ui.now > license.expiresAt; const userLimitExceeded = license.maxUsers && numActiveUsersOrPendingInvites && license.maxUsers != -1 && numActiveUsersOrPendingInvites >= license.maxUsers; const deviceLimitExceeded = license.maxDevices != -1 && numActiveDevicesOrPendingInvites >= license.maxDevices; if (deviceLimitExceeded || userLimitExceeded || licenseExpired) { let blockStatement: React.ReactNode; if (licenseExpired) { blockStatement = [ `Your organization's ${ license.provisional ? "provisional " : "" }license has `, <strong>expired.</strong>, ]; } else if (deviceLimitExceeded) { blockStatement = [ "Your organization has reached its limit of ", <strong> {license.maxDevices} active or pending device {license.maxDevices == 1 ? "" : "s"}. </strong>, ]; } else { blockStatement = [ "Your organization has reached its limit of ", <strong> {license.maxUsers!} active or pending users {license.maxUsers! == 1 ? "" : "s"}. </strong>, ]; } const canManageBilling = g.authz.hasOrgPermission( graph, currentUserId, "org_manage_billing" ); return ( <div className={styles.OrgContainer}> <h3> {licenseExpired ? "Renew" : "Upgrade"} <strong>License</strong> </h3> <p>{blockStatement}</p> {canManageBilling ? ( <p> To invite someone else, {licenseExpired ? "renew" : "upgrade"} your org's license. </p> ) : ( <p> To invite someone else, ask an admin to{" "} {licenseExpired ? "renew" : "upgrade"} your org's license. </p> )} {cancelBtn || canManageBilling ? ( <div className="buttons"> {cancelBtn} {canManageBilling ? ( <Link className="primary" to={props.orgRoute("/my-org/billing")}> Go To Billing → </Link> ) : ( "" )} </div> ) : ( "" )} </div> ); } const selectedOrgRole = orgRoleId ? (graph[orgRoleId] as Rbac.OrgRole) : undefined; const orgRoleOptions = invitableOrgRoleIds.map((id) => ( <option value={id} label={(graph[id] as Rbac.OrgRole).name} /> )); const authMethodField = org.ssoEnabled && (samlProviders.length > 0 || g.authz.hasOrgPermission( graph, currentUserId, "org_manage_auth_settings" )) ? ( <div className="field"> <label>Authentication Method</label> <div className="select"> <select value={externalAuthProviderId ?? email} onChange={(e) => { if (e.target.value === "email") { setProvider("email"); } else if (e.target.value == "connect-sso") { props.history.push( props.orgRoute( "/my-org/sso?inviteBackPath=" + encodeURIComponent(props.location.pathname) ) ); } else { setExternalAuthProviderId(e.target.value); setProvider("saml"); } }} > <option value="email">Email</option> {samlProviders.length == 0 && g.authz.hasOrgPermission( graph, currentUserId, "org_manage_auth_settings" ) ? ( <option value="connect-sso">SSO</option> ) : ( "" )} {samlProviders.map((sp) => ( <option key={sp.id} value={sp.id}> {`SSO → ${sp.nickname}`} </option> ))} </select> <SvgImage type="down-caret" /> </div> </div> ) : ( "" ); const userDirectoryField = scimProviders.length > 0 ? ( <div className="field"> <label>User Directory</label> <div className={ "select" + (Boolean(editingPendingInvite) ? " disabled" : "") } > <select value={scimProviderId ?? ""} disabled={Boolean(editingPendingInvite)} onChange={(e) => { setScimProviderId(e.target.value || undefined); }} > <option value="">None</option> {scimProviders.map((sc) => ( <option key={sc.id} value={sc.id}> SCIM → {sc.nickname} </option> ))} </select> <SvgImage type="down-caret" /> </div> </div> ) : null; let scimUserFields: React.ReactNode; if (scimProviderId) { if (editingPendingInvite) { scimUserFields = [ <div className="field"> <label>Name</label> <input type="text" disabled={true} value={firstName} /> <input type="text" disabled={true} value={lastName} /> </div>, <div className="field"> <label>Email</label> <input disabled={true} type="email" value={email} /> </div>, ]; } else if (loadingScimCandidates) { scimUserFields = ( <div className="field"> <label>People To Invite</label> <SmallLoader /> </div> ); } else { scimUserFields = ( <div className="field"> <label>People To Invite</label> <ui.CheckboxMultiSelect noSubmitButton={true} emptyText={ <p className="error"> This user directory doesn't have anyone available to invite. </p> } winHeight={props.winHeight} onChange={(ids) => setSelectedScimCandidateIds(ids)} items={scimCandidates .filter( (candidate) => !activeEmails.has(candidate.email) && !pendingEmails.has(candidate.email) ) .map((candidate) => { const name = `${candidate.firstName ?? ""} ${ candidate.lastName ?? "" }`.trim() || candidate.scimDisplayName || candidate.scimUserName; return { id: candidate.id, searchText: name, label: ( <label> {name} <span className="small">{candidate.email}</span> </label> ), }; })} /> </div> ); } } const form = ( <form> {authMethodField} {userDirectoryField} {g.authz.hasOrgPermission( graph, currentUserId, "org_manage_auth_settings" ) && samlProviders.length + scimProviders.length > 0 ? ( <div className={"buttons " + style({ marginBottom: 20 })}> <button className="tertiary" onClick={() => { props.history.push( props.orgRoute( "/my-org/sso?inviteBackPath=" + encodeURIComponent(props.location.pathname) ) ); }} > SSO Settings </button> </div> ) : ( "" )} {scimUserFields ?? ( <div> <div className="field"> <label>Name</label> <input type="text" placeholder="Enter the person's first name..." autoFocus={true} value={firstName} onChange={(e) => setFirstName(e.target.value)} /> <input type="text" placeholder="Enter the person's last name..." value={lastName} onChange={(e) => setLastName(e.target.value)} /> </div> <div className="field"> <label>Email</label> <input type="email" placeholder="Enter a valid email address..." value={email} onChange={(e) => setEmail(e.target.value)} /> </div> </div> )} {emailValid || email.length < 5 ? ( "" ) : ( <p className="error">Not a valid email.</p> )} {initialPendingEmails.has(email) ? ( <p className="error"> An invitation for someone with this email is already pending. </p> ) : ( "" )} {activeEmails.has(email) ? ( <p className="error"> Someone with this email is already an active member of the organization. </p> ) : ( "" )} <div className="field"> <label> Org Role <ui.RoleInfoLink {...props} /> </label> <div className="select"> <select value={orgRoleId} onChange={(e) => setOrgRoleId(e.target.value)} > {orgRoleOptions} </select> <SvgImage type="down-caret" /> </div> </div> </form> ); let teams: React.ReactNode; if ( selectedOrgRole && !selectedOrgRole.autoAppRoleId && grantableUserGroupIds.length > 0 ) { const pendingTeams = userGroupIds.length > 0 ? ( <div className={styles.AssocManager + " " + style({ width: "100%" })}> <div className="assoc-list"> {userGroupIds.map((id) => { const team = graph[id] as Model.Group; return ( <div key={id}> <div> <span className="title">{team.name}</span> <div className="actions"> <span className="delete" onClick={() => setUserGroupIds(R.without([id], userGroupIds)) } > <SvgImage type="x" /> <span>Remove</span> </span> </div> </div> </div> ); })} </div> </div> ) : ( <div className="field no-margin"> <p> <strong>This person doesn't yet belong to any teams.</strong> <br /> Note: it's perfectly fine to invite them now and add them to teams later. In fact, it may be quicker to do this if you're inviting multiple users, since you can add many people to a team at the same time once they've all been invited. <br /> You can also grant this person access to individual apps instead, or add them teams <strong>and</strong> override their access level to specific apps. </p> </div> ); teams = [ <h4>Teams</h4>, pendingTeams, grantableUserGroupIds.length > userGroupIds.length ? ( <div className="field buttons"> <button className="tertiary" onClick={() => setShowAddTeams(true)}> Add To {userGroupIds.length > 0 ? "More Teams" : "Teams"} </button> </div> ) : ( "" ), ]; } let appRoles: React.ReactNode; if ( selectedOrgRole && !selectedOrgRole.autoAppRoleId && grantableAppIds.length > 0 ) { const sortedApps = R.sortWith( [ R.ascend(({ appRoleId }) => { const appRole = graph[appRoleId] as Rbac.AppRole; return appRole.orderIndex; }), R.ascend(({ appId }) => { const app = graph[appId] as Model.App; return app.name; }), ], Object.values(appUserGrantsByAppId) ); const pendingApps = sortedApps.length > 0 ? ( <div className={styles.AssocManager + " " + style({ width: "100%" })}> <div className="assoc-list"> {sortedApps.map(({ appId, appRoleId }) => { const app = graph[appId] as Model.App; const appRole = graph[appRoleId] as Rbac.AppRole; return ( <div key={appId}> <div> <span className="title">{app.name}</span> </div> <div> <span className="role">{appRole.name} Access</span> <div className="actions"> <span className="delete" onClick={() => setAppUserGrantsByAppId( R.omit([appId], appUserGrantsByAppId) ) } > <SvgImage type="x" /> <span>Remove</span> </span> </div> </div> </div> ); })} </div> </div> ) : ( <div className="field no-margin"> {userGroupIds.length > 0 ? ( <p> <strong>No access granted yet to specific apps.</strong> <br /> Note: if a user already had access to an app through a team they belong to, setting access for a specific app will override the access level granted to them from the team. </p> ) : ( <p> <strong>This person doesn't yet have access to any apps.</strong> <br /> Note: it's perfectly fine to invite them now and grant access to apps later. In fact, it may be quicker to do this if you're inviting multiple users, since you can grant many people access to an app at the same time once they've all been invited. </p> )} </div> ); appRoles = [ <h4>App Access</h4>, pendingApps, grantableAppIds.length > sortedApps.length ? ( <div className="field buttons"> <button className="tertiary" onClick={() => setShowAddApps(true)}> Add To {sortedApps.length > 0 ? "More Apps" : "Apps"} </button> </div> ) : ( "" ), ]; } return ( <div className={styles.OrgContainer}> <h3> Send An <strong>Invitation</strong> </h3> {form} {teams} {appRoles} <div className="buttons"> {cancelBtn} <button className="primary" onClick={onSubmit} disabled={!canSubmit || !hasChange} > {typeof editIndex == "number" ? "Update" : "Next"} </button> </div> {showAddApps ? ( <AddInviteAppForm {...props} grantableAppIds={grantableAppIds} grantableAppRoleIdsByAppId={grantableAppRoleIdsByAppId} appUserGrantsByAppId={appUserGrantsByAppId} onClose={() => setShowAddApps(false)} onSubmit={(appRoleId, appIds) => { setAppUserGrantsByAppId( appIds.reduce( (agg, appId) => ({ ...agg, [appId]: { appId, appRoleId }, }), appUserGrantsByAppId ) ); setShowAddApps(false); }} /> ) : ( "" )} {showAddTeams ? ( <AddInviteTeams {...props} grantableUserGroupIds={grantableUserGroupIds} userGroupIds={userGroupIds} onClose={() => setShowAddTeams(false)} onSubmit={(ids) => { setUserGroupIds([...userGroupIds, ...ids]); setShowAddTeams(false); }} /> ) : ( "" )} </div> ); };
the_stack
import React, { useLayoutEffect, useRef, useState } from 'react'; import { anchorCustomPositionType, anchorType, labelsType, pathType, svgCustomEdgeType, svgEdgeShapeType, svgElemType, xarrowPropsType, } from '../types'; import { getElementByPropGiven, getElemPos, xStr2absRelative } from './utils'; import _ from 'lodash'; import { arrowShapes, cAnchorEdge, cArrowShapes } from '../constants'; import { anchorEdgeType, dimensionType } from '../privateTypes'; const parseLabels = (label: xarrowPropsType['labels']): labelsType => { let parsedLabel = { start: null, middle: null, end: null }; if (label) { if (typeof label === 'string' || React.isValidElement(label)) parsedLabel.middle = label; else { for (let key in label) { parsedLabel[key] = label[key]; } } } return parsedLabel; }; // remove 'auto' as possible anchor from anchorCustomPositionType.position interface anchorCustomPositionType2 extends Omit<Required<anchorCustomPositionType>, 'position'> { position: Exclude<typeof cAnchorEdge[number], 'auto'>; } const parseAnchor = (anchor: anchorType) => { // convert to array let anchorChoice = Array.isArray(anchor) ? anchor : [anchor]; //convert to array of objects let anchorChoice2 = anchorChoice.map((anchorChoice) => { if (typeof anchorChoice === 'string') { return { position: anchorChoice }; } else return anchorChoice; }); //remove any invalid anchor names anchorChoice2 = anchorChoice2.filter((an) => cAnchorEdge.includes(an.position)); if (anchorChoice2.length == 0) anchorChoice2 = [{ position: 'auto' }]; //replace any 'auto' with ['left','right','bottom','top'] let autosAncs = anchorChoice2.filter((an) => an.position === 'auto'); if (autosAncs.length > 0) { anchorChoice2 = anchorChoice2.filter((an) => an.position !== 'auto'); anchorChoice2.push( ...autosAncs.flatMap((anchorObj) => { return (['left', 'right', 'top', 'bottom'] as anchorEdgeType[]).map((anchorName) => { return { ...anchorObj, position: anchorName }; }); }) ); } // default values let anchorChoice3 = anchorChoice2.map((anchorChoice) => { if (typeof anchorChoice === 'object') { let anchorChoiceCustom = anchorChoice as anchorCustomPositionType; if (!anchorChoiceCustom.position) anchorChoiceCustom.position = 'auto'; if (!anchorChoiceCustom.offset) anchorChoiceCustom.offset = { x: 0, y: 0 }; if (!anchorChoiceCustom.offset.y) anchorChoiceCustom.offset.y = 0; if (!anchorChoiceCustom.offset.x) anchorChoiceCustom.offset.x = 0; anchorChoiceCustom = anchorChoiceCustom as Required<anchorCustomPositionType>; return anchorChoiceCustom; } else return anchorChoice; }) as Required<anchorCustomPositionType>[]; return anchorChoice3 as anchorCustomPositionType2[]; }; const parseDashness = (dashness, props) => { let dashStroke = 0, dashNone = 0, animDashSpeed, animDirection = 1; if (typeof dashness === 'object') { dashStroke = dashness.strokeLen || props.strokeWidth * 2; dashNone = dashness.strokeLen ? dashness.nonStrokeLen : props.strokeWidth; animDashSpeed = dashness.animation ? dashness.animation : null; } else if (typeof dashness === 'boolean' && dashness) { dashStroke = props.strokeWidth * 2; dashNone = props.strokeWidth; animDashSpeed = null; } return { strokeLen: dashStroke, nonStrokeLen: dashNone, animation: animDashSpeed, animDirection } as { strokeLen: number; nonStrokeLen: number; animation: number; }; }; const parseEdgeShape = (svgEdge): svgCustomEdgeType => { if (typeof svgEdge == 'string') { if (svgEdge in arrowShapes) svgEdge = arrowShapes[svgEdge as svgEdgeShapeType]; else { console.warn( `'${svgEdge}' is not supported arrow shape. the supported arrow shapes is one of ${cArrowShapes}. reverting to default shape.` ); svgEdge = arrowShapes['arrow1']; } } svgEdge = svgEdge as svgCustomEdgeType; if (svgEdge?.offsetForward === undefined) svgEdge.offsetForward = 0.25; if (svgEdge?.svgElem === undefined) svgEdge.svgElem = 'path'; // if (svgEdge?.svgProps === undefined) svgEdge.svgProps = arrowShapes.arrow1.svgProps; return svgEdge; }; const parseGridBreak = (gridBreak: string): { relative: number; abs: number } => { let resGridBreak = xStr2absRelative(gridBreak); if (!resGridBreak) resGridBreak = { relative: 0.5, abs: 0 }; return resGridBreak; }; /** * should be wrapped with any changed prop that is affecting the points path positioning * @param propVal * @param updateRef */ const withUpdate = (propVal, updateRef) => { if (updateRef) updateRef.current = true; return propVal; }; const noParse = (userProp) => userProp; const noParseWithUpdatePos = (userProp, _, updatePos) => withUpdate(userProp, updatePos); const parseNumWithUpdatePos = (userProp, _, updatePos) => withUpdate(Number(userProp), updatePos); const parseNum = (userProp) => Number(userProp); const parsePropsFuncs: Required<{ [key in keyof xarrowPropsType]: Function }> = { start: (userProp) => getElementByPropGiven(userProp), end: (userProp) => getElementByPropGiven(userProp), startAnchor: (userProp, _, updatePos) => withUpdate(parseAnchor(userProp), updatePos), endAnchor: (userProp, _, updatePos) => withUpdate(parseAnchor(userProp), updatePos), labels: (userProp) => parseLabels(userProp), color: noParse, lineColor: (userProp, propsRefs) => userProp || propsRefs.color, headColor: (userProp, propsRefs) => userProp || propsRefs.color, tailColor: (userProp, propsRefs) => userProp || propsRefs.color, strokeWidth: parseNumWithUpdatePos, showHead: noParseWithUpdatePos, headSize: parseNumWithUpdatePos, showTail: noParseWithUpdatePos, tailSize: parseNumWithUpdatePos, path: noParseWithUpdatePos, curveness: parseNumWithUpdatePos, gridBreak: (userProp, _, updatePos) => withUpdate(parseGridBreak(userProp), updatePos), // // gridRadius = strokeWidth * 2, //todo dashness: (userProp, propsRefs) => parseDashness(userProp, propsRefs), headShape: (userProp) => parseEdgeShape(userProp), tailShape: (userProp) => parseEdgeShape(userProp), showXarrow: noParse, animateDrawing: noParse, zIndex: parseNum, passProps: noParse, arrowBodyProps: noParseWithUpdatePos, arrowHeadProps: noParseWithUpdatePos, arrowTailProps: noParseWithUpdatePos, SVGcanvasProps: noParseWithUpdatePos, divContainerProps: noParseWithUpdatePos, divContainerStyle: noParseWithUpdatePos, SVGcanvasStyle: noParseWithUpdatePos, _extendSVGcanvas: noParseWithUpdatePos, _debug: noParseWithUpdatePos, _cpx1Offset: noParseWithUpdatePos, _cpy1Offset: noParseWithUpdatePos, _cpx2Offset: noParseWithUpdatePos, _cpy2Offset: noParseWithUpdatePos, }; //build dependencies const propsDeps = {}; //each prop depends on himself for (let propName in parsePropsFuncs) { propsDeps[propName] = [propName]; } // 'lineColor', 'headColor', 'tailColor' props also depends on 'color' prop for (let propName of ['lineColor', 'headColor', 'tailColor']) { propsDeps[propName].push('color'); } const parseGivenProps = (props: xarrowPropsType, propsRef) => { for (let [name, val] of Object.entries(props)) { propsRef[name] = parsePropsFuncs?.[name]?.(val, propsRef); } return propsRef; }; const defaultProps: Required<xarrowPropsType> = { start: null, end: null, startAnchor: 'auto', endAnchor: 'auto', labels: null, color: 'CornflowerBlue', lineColor: null, headColor: null, tailColor: null, strokeWidth: 4, showHead: true, headSize: 6, showTail: false, tailSize: 6, path: 'smooth', curveness: 0.8, gridBreak: '50%', // gridRadius : strokeWidth * 2, //todo dashness: false, headShape: 'arrow1', tailShape: 'arrow1', showXarrow: true, animateDrawing: false, zIndex: 0, passProps: {}, arrowBodyProps: {}, arrowHeadProps: {}, arrowTailProps: {}, SVGcanvasProps: {}, divContainerProps: {}, divContainerStyle: {}, SVGcanvasStyle: {}, _extendSVGcanvas: 0, _debug: false, _cpx1Offset: 0, _cpy1Offset: 0, _cpx2Offset: 0, _cpy2Offset: 0, } as const; type parsedXarrowProps = { shouldUpdatePosition: React.MutableRefObject<boolean>; start: HTMLElement; end: HTMLElement; startAnchor: anchorCustomPositionType[]; endAnchor: anchorCustomPositionType[]; labels: Required<labelsType>; color: string; lineColor: string; headColor: string; tailColor: string; strokeWidth: number; showHead: boolean; headSize: number; showTail: boolean; tailSize: number; path: pathType; showXarrow: boolean; curveness: number; gridBreak: { relative: number; abs: number }; // gridRadius: number; dashness: { strokeLen: number; nonStrokeLen: number; animation: number; }; headShape: svgCustomEdgeType; tailShape: svgCustomEdgeType; animateDrawing: number; zIndex: number; passProps: JSX.IntrinsicElements[svgElemType]; SVGcanvasProps: React.SVGAttributes<SVGSVGElement>; arrowBodyProps: React.SVGProps<SVGPathElement>; arrowHeadProps: JSX.IntrinsicElements[svgElemType]; arrowTailProps: JSX.IntrinsicElements[svgElemType]; divContainerProps: React.HTMLProps<HTMLDivElement>; SVGcanvasStyle: React.CSSProperties; divContainerStyle: React.CSSProperties; _extendSVGcanvas: number; _debug: boolean; _cpx1Offset: number; _cpy1Offset: number; _cpx2Offset: number; _cpy2Offset: number; }; let initialParsedProps = {} as parsedXarrowProps; initialParsedProps = parseGivenProps(defaultProps, initialParsedProps); const initialValVars = { startPos: { x: 0, y: 0, right: 0, bottom: 0 } as dimensionType, endPos: { x: 0, y: 0, right: 0, bottom: 0 } as dimensionType, }; // const parseAllProps = () => parseGivenProps(defaultProps, initialParsedProps); function deepCompareEquals(a, b) { return _.isEqual(a, b); } function useDeepCompareMemoize(value) { const ref = useRef(); // it can be done by using useMemo as well // but useRef is rather cleaner and easier if (!deepCompareEquals(value, ref.current)) { ref.current = value; } return ref.current; } function useDeepCompareEffect(callback, dependencies) { useLayoutEffect(callback, dependencies.map(useDeepCompareMemoize)); } /** * smart hook that provides parsed props to Xarrow and will trigger rerender whenever given prop is changed. */ const useXarrowProps = ( userProps: xarrowPropsType, refs: { headRef: React.MutableRefObject<any>; tailRef: React.MutableRefObject<any> } ) => { const [propsRefs, setPropsRefs] = useState(initialParsedProps); const shouldUpdatePosition = useRef(false); // const _propsRefs = useRef(initialParsedProps); // const propsRefs = _propsRefs.current; propsRefs['shouldUpdatePosition'] = shouldUpdatePosition; const curProps = { ...defaultProps, ...userProps }; // react states the number of hooks per render must stay constant, // this is ok we are using these hooks in a loop, because the number of props in defaultProps is constant, // so the number of hook we will fire each render will always be the same. // update the value of the ref that represents the corresponding prop // for example: if given 'start' prop would change call getElementByPropGiven(props.start) and save value into propsRefs.start.current // why to save refs to props parsed values? some of the props require relatively expensive computations(like 'start' and 'startAnchor'). // this will always run in the same order and THAT'S WAY ITS LEGAL for (let propName in defaultProps) { useLayoutEffect( () => { propsRefs[propName] = parsePropsFuncs?.[propName]?.(curProps[propName], propsRefs, shouldUpdatePosition); // console.log('prop update:', propName, 'with value', propsRefs[propName]); setPropsRefs({ ...propsRefs }); }, propsDeps[propName].map((name) => userProps[name]) ); } // rerender whenever position of start element or end element changes const [valVars, setValVars] = useState(initialValVars); const startPos = getElemPos(propsRefs.start); useDeepCompareEffect(() => { valVars.startPos = startPos; shouldUpdatePosition.current = true; setValVars({ ...valVars }); // console.log('start update pos', startPos); }, [startPos]); const endPos = getElemPos(propsRefs.end); useDeepCompareEffect(() => { valVars.endPos = endPos; shouldUpdatePosition.current = true; setValVars({ ...valVars }); // console.log('end update pos', endPos); }, [endPos]); useLayoutEffect(() => { // console.log('svg shape changed!'); shouldUpdatePosition.current = true; setValVars({ ...valVars }); }, [propsRefs.headShape.svgElem, propsRefs.tailShape.svgElem]); return [propsRefs, valVars] as const; }; export type useXarrowPropsResType = ReturnType<typeof useXarrowProps>; export default useXarrowProps;
the_stack
import getEnv from "./getEnv"; import Eris, { GuildTextableChannel, Message } from "eris"; import GuildService from "../services/GuildService"; import { loadLanguagePack } from "./languagePack"; import memberHasAdminPermission from "./memberHasAdminPermission"; import commandErrorHandler from "./commandErrorHandler"; import commands from "../commands/all"; import Bot from "../bot"; import LanguagePack from "../typings/LanguagePack"; import { GuildChannelCommand, AnyChannelCommand } from "../typings/Command"; import UserService from "../services/UserService"; import escapeRegex from "./escapeRegex"; import ClientStatsService from "../services/ClientStatsService"; import daysInCurrentMonth from "../utils/daysInCurrentMonth"; const { PREMIUM_BOT, DISCORD_PREFIX, DISCORD_PREFIX_MENTION_DISABLE, DISCORD_DEFAULT_LANG, DISCORD_OFFICIAL_SERVER_ID, GHOST_MODE, BOT_OWNERS } = getEnv(); export default async (message: Eris.Message) => { if (GHOST_MODE && !BOT_OWNERS.includes(message.author?.id)) return; const { author, content } = message; let { channel } = message; const { client } = Bot; // Ignore requested commands in the official server since this server already has the premium bot if ( channel instanceof Eris.GuildChannel && !PREMIUM_BOT && channel.guild.id === DISCORD_OFFICIAL_SERVER_ID ) { return; } // Avoid responding to other bots if (author && !author.bot) { // fetch dm channel if (!message.guildID) { message.channel = await message.author.getDMChannel(); ({ channel } = message); } let prefixToCheck: string; let languagePack: LanguagePack; let clientIntegrationRoleId: string; let guildService: GuildService; // upsert the message author in the db await UserService.init(author.id); if (channel instanceof Eris.GuildChannel) { const { guild } = channel; guildService = await GuildService.init(guild.id); languagePack = loadLanguagePack(guildService.language); prefixToCheck = guildService.prefix; clientIntegrationRoleId = guild.members .get(client.user.id) ?.roles.filter((roleID) => guild.roles.get(roleID)?.managed ? roleID : null )[0]; } else { languagePack = loadLanguagePack(DISCORD_DEFAULT_LANG); prefixToCheck = DISCORD_PREFIX; } prefixToCheck = prefixToCheck.toLowerCase(); let prefixRegexStr = "^("; if (!DISCORD_PREFIX_MENTION_DISABLE) { // mention of integration role as prefix if (clientIntegrationRoleId) { prefixRegexStr += `<@&${clientIntegrationRoleId}>|`; } // mention as prefix prefixRegexStr += `<@!?${client.user.id}>|`; } // normal prefix prefixRegexStr += escapeRegex(prefixToCheck); prefixRegexStr += `)\\s*`; const prefixRegex = new RegExp(prefixRegexStr, "i"); const commandRequested = content.toLowerCase(); // Case insensitive match const matchedPrefix = commandRequested.match(prefixRegex)?.[0]; if (matchedPrefix == null) return; if (commandRequested.startsWith(matchedPrefix)) { commandsLoop: for (const command of commands) { for (const alias of command.aliases) { let commandAliasToCheck = matchedPrefix + alias.toLowerCase(); if (commandRequested.startsWith(commandAliasToCheck)) { const ClientStats = await ClientStatsService.init(client.user.id); let commandStats = ClientStats.commandUsageStats.get( JSON.stringify(command.aliases) ); const date = new Date().toLocaleString("en-US", { month: "numeric", day: "numeric", year: "numeric" }); const time = new Date().toLocaleTimeString("en-US", { hour: "2-digit", minute: "2-digit" }); let stats = commandStats.stats; let hourlyUsage = commandStats.hourlyUsage; let hourlyUsageIncrement = hourlyUsage + 1; let hourlyUsageDate = commandStats.hourlyUsageDate; let dailyUsage = commandStats.dailyUsage; let dailyUsageIncrement = dailyUsage + 1; let dailyUsageDate = commandStats.dailyUsageDate; let weeklyUsage = commandStats.weeklyUsage; let weeklyUsageIncrement = weeklyUsage + 1; let weeklyUsageDate = commandStats.weeklyUsageDate; let monthlyUsage = commandStats.monthlyUsage; let monthlyUsageIncrement = monthlyUsage + 1; let monthlyUsageDate = commandStats.monthlyUsageDate; let totalUsage = commandStats.totalUsage; let totalUsageIncrement = totalUsage + 1; let engagedUsers = Object.fromEntries(stats?.entries() ?? new Map())[date] ?.engagedUsers ?? []; let statEntries = Object.entries( Object.fromEntries(stats?.entries() ?? new Map()) ); let useEntries = Object.entries( Object.fromEntries( Object.fromEntries(stats?.entries() ?? new Map())[ date ]?.uses?.entries() ?? new Map() ) ?? new Map() ); let uses = Object.fromEntries( Object.fromEntries(stats?.entries() ?? new Map())[ date ]?.uses?.entries() ?? new Map() )[time] === undefined ? 0 : Object.fromEntries( Object.fromEntries(stats?.entries() ?? new Map())[date] ?.uses )[time]; let usageStatsForDate = Object.fromEntries( ClientStats.commandUsageStatsByDate.entries() )[date] ?? { engagedUsers: [], uses: 0 }; let engagedUsersForDate = usageStatsForDate?.engagedUsers; let usesForDate = usageStatsForDate?.uses; engagedUsersForDate = [...engagedUsersForDate, "userid"]; usesForDate = usesForDate + 1; let hourlyUsageDifference = new Date().getTime() - hourlyUsageDate.getTime(); let dailyUsageDifference = new Date().getTime() - dailyUsageDate.getTime(); let weeklyUsageDifference = new Date().getTime() - weeklyUsageDate.getTime(); let monthlyUsageDifference = new Date().getTime() - monthlyUsageDate.getTime(); if (hourlyUsageDifference >= 3600000) { commandStats = Object.assign(commandStats, { hourlyUsage: 0, hourlyUsageDate: new Date() }); } else { commandStats = Object.assign(commandStats, { hourlyUsage: hourlyUsageIncrement }); } if (dailyUsageDifference >= 86400000) { commandStats = Object.assign(commandStats, { dailyUsage: 0, dailyUsageDate: new Date() }); } else { commandStats = Object.assign(commandStats, { dailyUsage: dailyUsageIncrement }); } if (weeklyUsageDifference >= 604800000) { commandStats = Object.assign(commandStats, { weeklyUsage: 0, weeklyUsageDate: new Date() }); } else { commandStats = Object.assign(commandStats, { weeklyUsage: weeklyUsageIncrement }); } if (daysInCurrentMonth === 30) { if (monthlyUsageDifference >= 2592000000) { commandStats = Object.assign(commandStats, { monthlyUsage: 0, monthlyUsageDate: new Date() }); } else { commandStats = Object.assign(commandStats, { monthlyUsage: monthlyUsageIncrement }); } } else { if (monthlyUsageDifference >= 2678400000) { commandStats = Object.assign(commandStats, { monthlyUsage: 0, monthlyUsageDate: new Date() }); } else { commandStats = Object.assign(commandStats, { monthlyUsage: monthlyUsageIncrement }); } } commandStats = Object.assign(commandStats, { totalUsage: totalUsageIncrement, stats: Object.fromEntries( new Map([ ...statEntries, [ date, { engagedUsers: [...engagedUsers, "userid"].filter( (v: string, i: number, a: Array<string>) => a.findIndex((t) => t === v) === i ), uses: Object.fromEntries( new Map([...useEntries, [time, uses + 1]]) ) } ] ]) ) }); setTimeout(async () => { await ClientStats.setCommandStats( JSON.stringify(command.aliases), commandStats ); await ClientStats.incrementCommandsRun(); usageStatsForDate = Object.assign(usageStatsForDate, { uses: usesForDate, engagedUsers: engagedUsersForDate.filter( (v: string, i: number, a: Array<string>) => a.findIndex((t) => t === v) === i ) }); await ClientStats.setCommandUsageByDate(date, usageStatsForDate); }, 100); if (channel instanceof Eris.PrivateChannel && command.denyDm) { channel .createMessage(languagePack.functions.commandHandler.noDm) .catch(console.error); break commandsLoop; } if ( channel instanceof Eris.GuildChannel && (command as GuildChannelCommand).onlyAdmin && !(await memberHasAdminPermission(message.member)) ) { channel .createMessage(languagePack.common.errorNoAdmin) .catch(console.error); break commandsLoop; } try { const guild = channel instanceof Eris.GuildChannel ? channel.guild : false; console.log( `${author.username}#${author.discriminator} (${author.id}) [${ guild ? `Server: ${guild.name} (${guild.id}), ` : `` }Channel: ${channel.id}]: ${content}` ); message.content = message.content.replace(prefixRegex, ""); if (matchedPrefix.startsWith("<@&")) { message.roleMentions.shift(); } else if (matchedPrefix.startsWith("<@")) { message.mentions.shift(); } if (channel instanceof Eris.GuildChannel) { await (command as GuildChannelCommand).run({ client, message: message as Message<GuildTextableChannel>, languagePack, guildService }); } else { await (command as AnyChannelCommand).run({ client, message, languagePack }); } } catch (error) { commandErrorHandler(channel, languagePack, prefixToCheck, error); } break commandsLoop; } } } } } };
the_stack
import Editor = require('../editor/index'); import events = require('events'); import classes = require('component-classes'); import query = require('component-query'); import domify = require('domify'); import dataset = require('dataset'); import DEBUG = require('debug'); import domSerializeInterfaces = require('dom-serialize/interfaces'); import SerializeEvent = domSerializeInterfaces.SerializeEvent; import corejs = require('babel-runtime/core-js'); import currentSelection = require('current-selection'); import collapse = require('collapse'); import is = require('../is/index'); var debug = DEBUG('editor:editor-block'); class Block extends events.EventEmitter { /** * Private Fields */ private _editor: Editor; private _overlay: HTMLElement; private _el: HTMLElement; private _id: string; private _hold: boolean = false; private _holdX: number = 0; private _holdY: number = 0; private static _boundEditors: WeakSet<Editor> = new corejs.default.WeakSet(); public constructor(overlay: HTMLElement) { super(); this._overlay = overlay; // store a reference to the block in the overlay DOM node this._overlay['block'] = this; } /** * Returns the current overlay reference for the block, searching * through the DOM of the editor to do so. */ public get el(): HTMLElement { var qry = '.overlay-reference[data-id=\'' + this._id + '\']'; try { var els: Array<HTMLElement> = query.all(qry, this._editor.el); } catch (e) { if (!this._editor) { throw new Error('Block not bound to an editor instance. You must call .bind() before accessing the \'el\' property.'); } throw e; } if (els.length > 0) { if (els.length > 1) { debug('duplicate elements for block with id ' + this._id); } if (this._el != els[0]) { debug('updating element reference for block with id ' + this._id); this._el = els[0]; } } return this._el; } /** * Returns the current overlay for the block */ public get overlay(): HTMLElement { return this._overlay; } /** * Returns the bound editor for the block */ public get editor(): Editor { return this._editor; } /** * Binds the block to the editor instance */ public bind(editor: Editor) { if (this._editor) { if (this._editor == editor) return; // noop throw new Error('Already bound to another editor instance'); } // also bind the Block class to the editor Block._bind(editor); this._editor = editor; this._el = editor.overlay.reference(this._overlay); this._id = dataset(this._el, 'id'); this._overlay.addEventListener('dragenter', this.onDragEnter.bind(this), false); this._overlay.addEventListener('dragover', this.onDragOver.bind(this), false); this._overlay.addEventListener('dragleave', this.onDragLeave.bind(this), false); this._overlay.addEventListener('drop', this.onDrop.bind(this), false); this._overlay.addEventListener('mousedown', (e) => this.onmousedown(e), false); window.addEventListener('mousemove', (e) => this.onmousemove(e), false); window.addEventListener('mouseup', (e) => this.onmouseup(e), false); var deleteElement: HTMLElement = query('.delete-button', this._overlay); if (deleteElement) { deleteElement.addEventListener('click', (e) => this.onremove(e), false); } var afterElement: HTMLElement = query('.caret-after-button', this._overlay); if (afterElement) { afterElement.addEventListener('mousedown', (e) => this.onmovecaret(e), false); } var beforeElement: HTMLElement = query('.caret-before-button', this._overlay); if (beforeElement) { beforeElement.addEventListener('mousedown', (e) => this.onmovecaret(e), false); } } private static _bind(editor: Editor) { if (Block._boundEditors.has(editor)) { // editor is already bound to the Block class, make this a noop return; } Block._boundEditors.add(editor); editor.el.addEventListener('serialize', (e: SerializeEvent) => { if (is.overlayReference(e.serializeTarget)) { var overlay = editor.overlay.for(<HTMLElement>e.serializeTarget); if (overlay && overlay['block']) { var block: Block = <Block>(overlay['block']); e.detail.serialize = block.serialize(e.detail.context); e.preventDefault(); } } }); } /** * Fired when the mouse button is pressed on the block */ private onmousedown(e: MouseEvent) { if (e.button != 0) return; var c = classes(<HTMLElement>e.target); if (e.target == this.overlay || c.has('body') || c.has('grabber')) { this._editor.focus(); this._hold = true; this._holdX = e.clientX; this._holdY = e.clientY; var range = document.createRange(); range.setStart(this.el, 0); range.setEnd(this.el, 0); var sel = window.getSelection(); sel.removeAllRanges(); sel.addRange(range); e.preventDefault(); return this; } } /** * Fired when the mouse moves */ private onmousemove(e: MouseEvent){ if (this._hold && (Math.abs(this._holdX - e.clientX) > 5 || Math.abs(this._holdY - e.clientY) > 5)) { this._editor.drag.start(this.el); this._hold = false; } else { var bounding = this.el.getBoundingClientRect(); if (e.clientX >= bounding.left && e.clientX < bounding.right && e.clientY >= bounding.top && e.clientY < bounding.bottom) { this._editor.drag.update(this.el, e.clientX, e.clientY); this._editor.autoscroll.target(e.clientX, e.clientY); } } } /** * Fired when the mouse button is lifted */ private onmouseup(e: MouseEvent): void{ if (e.button != 0) return; this._hold = false; } /** * Delete block through of `delete` button */ private onremove(e: MouseEvent){ this.el.parentNode.removeChild(this.el); this.emit('remove'); } /** * Move cursor either before or after the block */ private onmovecaret(e: MouseEvent){ // Figure out direction of motion var direction; if ((<HTMLElement>e.target).className == 'caret-before-button') { direction = -1; } else { direction = 1; } // Figure out whether we should create a new paragraph or move to an existing one var shouldCreate = false; if (direction == -1) { if (!this.el.previousSibling || is.overlayReference(this.el.previousSibling)) { shouldCreate = true; } } else { if (!this.el.nextSibling || is.overlayReference(this.el.nextSibling)) { shouldCreate = true; } } // To better match native behavior, we must change the selection asynchronously. // // If we change it synchronously inside the mousedown handler, and don't call // `e.preventDefault()` it will be overwritten by the default browser selection // behavior. // // If we do call `e.preventDefault()`, the default browser selection // behavior is also suppressed, so the user is not able to start a selection by // draggin before/after a block. // // Since there's no way to suppress just part of the default behavior (setting // caret position, but not starting a selection), what we do is that we set the // caret position asynchronously, so it overwrites the caret set by the default // browser behavior. This is not really pretty, but does the trick. // // Another way of dealing with this would be to manually implement selection // behavior. However that would be really complex and error prone, so this // approach is cleaner overall. // // TODO: figure out a way of getting the selection portion to work on Firefox // TODO: figure out why selection behavior gets a bit weird on Safari setTimeout(() => { var s = currentSelection(document); var r = document.createRange(); if (shouldCreate) { var p = document.createElement('p'); var n = document.createElement('br'); p.appendChild(n); if (direction == -1) { this.el.parentNode.insertBefore(p, this.el); } else { this.el.parentNode.insertBefore(p, this.el.nextSibling); } r.selectNode(n); collapse.toStart(r); } else { if (direction == -1) { if (is.emptyParagraph(this.el.previousSibling)) { // Make sure cursor is before `<br>` tag. r.selectNode(this.el.previousSibling.firstChild); collapse.toStart(r); } else { r.selectNodeContents(this.el.previousSibling); collapse.toEnd(r); } } else { r.selectNodeContents(this.el.nextSibling); collapse.toStart(r); } } this._editor.el.focus(); s.removeAllRanges(); s.addRange(r); }, 0); } /** * Destroy the block */ public destroy(): void { debug('destroying `%s` ...', this._id); this.emit('destroy'); } /** * Sets the float direction of the block * @param {String} dir * @api public */ public float(dir: string): void { var elClasses = classes(this.el); elClasses.remove('left'); elClasses.remove('right'); if (dir == 'left') { elClasses.add('left'); } else if (dir == 'right') { elClasses.add('right'); } this._editor.overlay.update(); } /** * Serializes the block */ protected serialize(context: String): Node | String { return document.createDocumentFragment(); } protected onDragEnter(e: DragEvent) { this.editor.media.onDragEnter(e); } protected onDragOver(e: DragEvent) { this.editor.media.onDragOver(e); } protected onDragLeave(e: DragEvent) { this.editor.media.onDragLeave(e); } protected onDrop(e: DragEvent) { // There's no need to call onDrop here, because it's // caught on a higher level on the DOM hierarchy by // the media controller. // If you do call it here you get a double drop. // this.editor.media.onDrop(e); } } export = Block;
the_stack
module TDev { export module Embedded { import J = AST.Json import H = Helpers function assert(x: boolean) { if (!x) throw new Error("Assert failure"); } // --- The code emitter. export class Emitter extends JsonAstVisitor<H.Env, string> { // Output "parameters", written to at the end. public prototypes = ""; public code = ""; public prelude = ""; // Type stubs. Then, type definitions. To allow for any kind of insane // type-level recursion. public tPrototypes = ""; public tCode = ""; private libraryMap: H.LibMap = {}; private imageLiterals = []; // All the libraries needed to compile this [JApp]. constructor( private libRef: J.JCall, private libs: J.JApp[], private resolveMap: { [index:string]: string } ) { super(); } public visitMany(e: H.Env, ss: J.JNode[]) { var code = []; ss.forEach((s: J.JNode) => { code.push(this.visit(e, s)) }); return code.join("\n"); } public visitComment(env: H.Env, c: string) { return env.indent+"// "+c.replace("\n", "\n"+env.indent+"// "); } public visitBreak(env: H.Env) { return env.indent + "break;"; } public visitContinue(env: H.Env) { return env.indent + "continue;"; } public visitShow(env: H.Env, expr: J.JExpr) { // TODO hook this up to "post to wall" handling if any return env.indent + "serial.print(" + this.visit(env, expr) + ");"; } public visitReturn(env: H.Env, expr: J.JExpr) { return env.indent + H.mkReturn(this.visit(env, expr)); } public visitExprStmt(env: H.Env, expr: J.JExpr) { return env.indent + this.visit(env, expr)+";"; } public visitInlineActions(env: H.Env, expr: J.JExprHolder, actions: J.JInlineAction[]) { var map = {}; expr.locals.forEach((l: J.JLocalDef) => { map[l.id] = l.name }); var lambdas = actions.map((a: J.JInlineAction) => { var n = H.resolveLocal(env, map[a.reference.id], a.reference.id); return ( env.indent + H.findTypeDef(env, this.libraryMap, a.inParameters, a.outParameters)+ " "+n+" = "+ this.visitAction(env, "", n, a.inParameters, a.outParameters, a.body, false, true)+";\n" ); }); return (lambdas.join("\n")+"\n"+ env.indent + this.visit(env, expr.tree) + ";"); } public visitExprHolder(env: H.Env, locals: J.JLocalDef[], expr: J.JExpr) { if (H.isInitialRecordAssignment(locals, expr)) return this.visit(env, locals[0])+"(new "+H.mkType(env, this.libraryMap, locals[0].type)+"_)"; var decls = locals.map(d => { // Side-effect: marks [d] as promoted, if needed. var decl = this.visit(env, d); var defaultValue = H.defaultValueForType(this.libraryMap, d.type); var initialValue = !H.isPromoted(env, d.id) && defaultValue ? " = " + defaultValue : ""; return decl + initialValue + ";"; }); return decls.join("\n"+env.indent) + (decls.length ? "\n" + env.indent : "") + this.visit(env, expr); } public visitLocalRef(env: H.Env, name: string, id: string) { // In our translation, referring to a TouchDevelop identifier never // requires adding a reference operator (&). Things passed by reference // are either: // - function pointers (a.k.a. "handlers" in TouchDevelop lingo), for // which C and C++ accept both "f" and "&f" (we hence use the former) // - arrays, strings, user-defined objects, which are in fact of type // "ManagedType<T>", no "&" operator here. // However, we now support capture-by-reference. This means that the // data is ref-counted (so as to be shared), but assignment and // reference operate on the ref-counted data (not on the pointer), so we // must add a dereference there. var prefix = H.isPromoted(env, id) ? "*" : ""; return prefix+H.resolveLocal(env, name, id); } public visitLocalDef(env: H.Env, name: string, id: string, type: J.JTypeRef, isByRef: boolean) { var t = H.mkType(env, this.libraryMap, type); var l = H.resolveLocal(env, name, id); if (H.shouldPromoteToRef(env, type, isByRef)) { H.markPromoted(env, id); return "Ref<"+ t + "> " + l; } else { return t + " " + l; } } // Allows the target to redefine their own string type. public visitStringLiteral(env: H.Env, s: string) { return 'touch_develop::mk_string("'+s.replace(/["\\\n\r]/g, c => { if (c == '"') return '\\"'; if (c == '\\') return '\\\\'; if (c == "\n") return '\\n'; if (c == "\r") return '\\r'; }) + '")'; } public visitNumberLiteral(env: H.Env, n: number) { return n+""; } public visitBooleanLiteral(env: H.Env, b: boolean) { return b+""; } public visitWhile(env: H.Env, cond: J.JExprHolder, body: J.JStmt[]) { var condCode = this.visit(env, cond); var bodyCode = this.visitMany(H.indent(env), body); return env.indent + "while ("+condCode+") {\n" + bodyCode + "\n" + env.indent + "}"; } public visitFor(env: H.Env, index: J.JLocalDef, bound: J.JExprHolder, body: J.JStmt[]) { var indexCode = this.visit(env, index) + " = 0"; var testCode = H.resolveLocalDef(env, index) + " < " + this.visit(env, bound); var incrCode = "++"+H.resolveLocalDef(env, index); var bodyCode = this.visitMany(H.indent(env), body); return ( env.indent + "for ("+indexCode+"; "+testCode+"; "+incrCode+") {\n" + bodyCode + "\n" + env.indent + "}" ); } public visitIf( env: H.Env, cond: J.JExprHolder, thenBranch: J.JStmt[], elseBranch: J.JStmt[], isElseIf: boolean) { var isIfFalse = cond.tree.nodeType == "booleanLiteral" && (<J.JBooleanLiteral> cond.tree).value === false; // TouchDevelop abuses "if false" to comment out code. Commented out // code is not type-checked, so don't try to compile it. However, an // "if false" followed by an "else" is *not* understood to be a comment. return [ env.indent, isElseIf ? "else " : "", "if (" + this.visit(env, cond) + "){\n", isIfFalse ? "" : this.visitMany(H.indent(env), thenBranch) + "\n", env.indent, "}", elseBranch ? " else {\n" : "", elseBranch ? this.visitMany(H.indent(env), elseBranch) + "\n" : "", elseBranch ? env.indent + "}" : "" ].join(""); } private resolveCall(env: H.Env, receiver: J.JExpr, name: string) { if (!receiver) return null; // Is this a call in the current scope? var scoped = H.isScopedCall(receiver); if (scoped) // If compiling a library, no scope actually means the library's // scope. This step is required to possibly find a shim. This means // that we may generate "lib::f()" where we could've just written // "f()", but since the prototypes have been written out already, // that's fine. return this.resolveCall(env, this.libRef, name); // Is this a call to a library? var n = H.isLibrary(receiver); if (n) { // I expect all libraries and all library calls to be properly resolved. var key = this.resolveMap[n] || n; var lib = this.libs.filter(l => l.name == key)[0]; var action = lib.decls.filter((d: J.JDecl) => d.name == name)[0]; var s = H.isShimBody((<J.JAction> action).body); if (s != null) { // Call to a built-in C++ function if (!s.length) throw new Error("Library author: some (compiled) function is trying to call "+name+" "+ "which is marked as {shim:}, i.e. for simulator purposes only.\n\n"+ "Hint: break on exceptions in the debugger and walk up the call stack to "+ "figure out which action it is."); return s; } else if (n in this.resolveMap) { // Actual call to a library function return H.resolveGlobalL(env, this.resolveMap[n], name); } else { // Call to a function from the current script. return H.resolveGlobal(env, name); } } return null; } // Some conversions cannot be expressed using the simple "enums" feature // (which maps a string literal to a constant). This function transforms // the arguments for some known specific C++ functions. private specialTreatment(e: H.Env, f: string, actualArgs: J.JExpr[]) { if (f == "micro_bit::createImage" || f == "micro_bit::showAnimation" || f == "micro_bit::showLeds" || f == "micro_bit::plotLeds") { var x = H.isStringLiteral(actualArgs[0]); if (x === "") x = "0 0 0 0 0\n0 0 0 0 0\n0 0 0 0 0\n0 0 0 0 0\n0 0 0 0 0\n"; if (!x) throw new Error("create image / show animation / plot image takes a string literal only"); var r = "literals::bitmap"+this.imageLiterals.length; var otherArgs = actualArgs.splice(1).map((x: J.JExpr) => this.visit(e, x)); var code = f+"("+r+"_w, "+r+"_h, "+r+ (otherArgs.length ? ", "+otherArgs : "")+ ")"; this.imageLiterals.push(x); return code; } else { return null; } } private safeGet(x: string, f: string): string { // The overload of [->] in [ManagedType] takes care of checking that the // underlying object is properly initialized. return x+"->"+f; } public visitCall(env: H.Env, name: string, args: J.JExpr[], typeArgs: J.JTypeRef[], parent: J.JTypeRef, callType: string, typeArgument: string = null) { var mkCall = (f: string, skipReceiver: boolean) => { var actualArgs = skipReceiver ? args.slice(1) : args; var s = this.specialTreatment(env, f, actualArgs); if (s) return s; else { var argsCode = actualArgs.map(a => { var k = H.isEnumLiteral(a); if (k) return k+""; else return this.visit(H.resetPriority(env), a) }); var t = typeArgument ? "<" + typeArgument + ">" : ""; return f + t + "(" + argsCode.join(", ") + ")"; } }; var mkWrap = (prio: number) => { var needsParentheses = prio > H.priority(env); var wrap = needsParentheses ? x => "(" + x + ")" : x => x; return wrap; }; // The [JCall] node has several, different, often unrelated purposes. // This function identifies (tentatively) the different cases and // compiles each one of them into something that makes sense. // 0a) Some methods take a type-level argument at the end, e.g. // "create -> collection of -> number". TouchDevelop represents this as // calling the method "Number" on "create -> collection of". C++ wants // the type argument to be passed as a template parameter to "collection of" // so we pop the type arguments off and call ourselves recursively with // the extra type argument. // Extra bonus subtlety: we are able to get the "complete" type argument // at the root of the call sequence, but we need skip "intermediate" // nodes (that have types such as Collection<T> in there) until we hit // the actual code arguments. if (<any> parent == "Unfinished Type") { var newTypeArg = typeArgument || H.mkType(env, this.libraryMap, typeArgs[0]); assert(args.length && args[0].nodeType == "call"); var call = <J.JCall> args[0]; return this.visitCall(H.resetPriority(env), call.name, call.args, call.typeArgs, call.parent, call.callType, newTypeArg); } // 0b) Ha ha! But actually, guess what? For records, it's the opposite, // and TouchDevelop writes "÷point -> create". if (H.isRecordConstructor(name, args)) { // Note: we cannot call new on type definitions from other libraries. // So the type we're looking for is always in the current scope's // "user_types" namespace. var struct_name = "user_types::"+H.resolveGlobal(env, <any> parent)+"_"; return "ManagedType<"+struct_name+">(new "+struct_name+"())"; } // 0c) Special-casing for [Thing -> invalid] (an invalid record). if (H.isInvalidRecord(name, args)) // See remark above. return "ManagedType<user_types::"+H.resolveGlobal(env, (<J.JCall> args[0]).name)+"_>()"; // 0d) Special casing for [thing -> is invalid] (test if null). if (name == "is invalid" && H.resolveTypeRef(this.libraryMap, parent).user) { // 9 is the precedence of == return mkWrap(9)(this.visit(H.setPriority(env, 9), args[0]) + ".get() == NULL"); } // 0e) Special casing for [thing -> equals] (address comparison) if (name == "equals" && H.resolveTypeRef(this.libraryMap, parent).user) return mkWrap(9)( this.visit( H.setPriority(env, 9), args[0]) + "==" + this.visit(H.setPriority(env, 9), args[1])); // 1) A call to a function, either in the current scope, or belonging to // a TouchDevelop library. Resolves to a C++ function call. var resolvedName = this.resolveCall(H.resetPriority(env), args[0], name); if (resolvedName) return mkCall(resolvedName, true); // 2) A call to the assignment operator on the receiver. C++ assignment. else if (name == ":=") return this.visit(H.resetPriority(env), args[0]) + " = " + this.visit(H.resetPriority(env), args[1]); // 3) Reference to a variable in the global scope. else if (args.length && H.isSingletonRef(args[0]) == "data") return "globals::"+H.resolveGlobal(env, name); // 4) Extension method, where p(x) is represented as x→ p. In case we're // actually referencing a function from a library, go through // [resolveCall] again, so that we find the shim if any. else if (callType == "extension") { var t = H.resolveTypeRef(this.libraryMap, parent); var prefixedName = t.lib ? this.resolveCall(H.resetPriority(env), H.mkLibraryRef(t.lib), name) : this.resolveCall(H.resetPriority(env), H.mkCodeRef(), name); return mkCall(prefixedName, false); } // 5) Field access for an object. else if (callType == "field") // TODO handle collisions at the record-field level. return this.safeGet(this.visit(H.resetPriority(env), args[0]), H.mangle(name)); // 6a) Lone reference to a library (e.g. ♻ micro:bit just by itself). else if (args.length && H.isSingletonRef(args[0]) == "♻") return ""; // 6b) Reference to a built-in library method, e.g. Math→ max. The // first call to lowercase avoids a conflict between Number (the type) // and number (the namespace). The second call to lowercase avoids a // conflict between Collection_of (the type) and collection_of (the // function). else if (args.length && H.isSingletonRef(args[0])) // Assuming no collisions in built-in library methods. return H.isSingletonRef(args[0]).toLowerCase() + "::" + mkCall(H.mangle(name).toLowerCase(), true); // 7) Instance method (e.g. Number's > operator, for which the receiver // is the number itself). Lowercase so that "number" is the namespace // that contains the functions that operate on typedef'd "Number". else { var t = H.resolveTypeRef(this.libraryMap, parent); var op = H.lookupOperator(t.type.toLowerCase()+"::"+name); if (op) { var wrap = mkWrap(op.prio); var rightPriority = op.right ? op.prio - 1 : op.prio; var leftPriority = op.prio; if (args.length == 2) return wrap( this.visit(H.setPriority(env, leftPriority), args[0]) + " " + op.op + " " + this.visit(H.setPriority(env, rightPriority), args[1])); else { assert(args.length == 1); return wrap(op.op + this.visit(H.setPriority(env, leftPriority), args[0])); } } else { // We assume no collisions for built-in operators. return mkCall(t.type.toLowerCase()+"::"+H.mangle(name), false); } } } public visitSingletonRef(e, n: string) { if (n == "$skip") return ""; else // Reference to "data", "Math" (or other namespaces), that makes no // sense. TouchDevelop allows these. return ""; } public visitGlobalDef(e: H.Env, name: string, t: J.JTypeRef, comment: string) { // TODO: we skip definitions marked as shims, but we do not do anything // meaningful when we *refer* to them. var s = H.isShim(comment); if (s !== null) return null; var def = comment.match(/{default:([^}]+)}/); var x = def ? def[1] : H.defaultValueForType(this.libraryMap, t); return e.indent + H.mkType(e, this.libraryMap, t) + " " + H.resolveGlobal(e, name) + (x ? " = " + x : "") + ";" } public visitAction( env: H.Env, name: string, id: string, inParams: J.JLocalDef[], outParams: J.JLocalDef[], body: J.JStmt[], isPrivate, isLambda=false) { // This function is always called with H.willCompile == true, meaning // it's not a shim. if (outParams.length > 1) throw new Error("Not supported (multiple return parameters)"); var env2 = H.indent(env); // Properly initializing the outparam with a default value is important, // because it guarantees that the function always ends with a proper // return statement of an initialized value. (Never returning is NOT an // error in TouchDevelop). var outParamInitialization = ""; if (outParams.length > 0) { var defaultValue = H.defaultValueForType(this.libraryMap, outParams[0].type); var initialValue = defaultValue ? " = " + defaultValue : ""; outParamInitialization = env2.indent + this.visit(env2, outParams[0]) + initialValue + ";"; } var bodyText = [ outParamInitialization, this.visitMany(env2, body), outParams.length ? env2.indent + H.mkReturn(H.resolveLocalDef(env, outParams[0])) : "", ].filter(x => x != "").join("\n"); var head = H.mkSignature(env, this.libraryMap, H.resolveGlobal(env, name), inParams, outParams, isLambda); return (isLambda ? "" : env.indent) + head + " {\n" + bodyText + "\n"+env.indent+"}"; } private compileImageLiterals(e: H.Env) { if (!this.imageLiterals.length) return ""; return e.indent + "namespace literals {\n" + this.imageLiterals.map((s: string, n: number) => { var x = 0; var w = 0; var h = 0; var lit = "{ "; for (var i = 0; i < s.length; ++i) { switch (s[i]) { case "0": case "1": lit += s[i]+", "; x++; break; case " ": break; case "\n": if (w == 0) w = x; else if (x != w) // Sanity check throw new Error("Malformed string literal"); x = 0; h++; break; default: throw new Error("Malformed string literal"); } } h++; lit += "}"; var r = "bitmap"+n; return e.indent + " const int "+r+"_w = "+w+";\n" + e.indent + " const int "+r+"_h = "+h+";\n"+ e.indent + " const uint8_t "+r+"[] = "+lit+";\n"; }).join("\n") + e.indent + "}\n\n"; } private typeDecl(e: H.Env, r: J.JRecord) { var s = H.isShim(r.comment); if (s !== null) return null; var n = H.resolveGlobal(e, r.name); var fields = r.fields.map((f: J.JRecordField) => { var t = H.mkType(e, this.libraryMap, f.type); return e.indent + " " + t + " " + H.mangle(f.name) + ";"; }).join("\n"); return [ e.indent + "struct " + n + "_ {", fields, e.indent + "};", ].join("\n"); } private typeStub(e: H.Env, r: J.JRecord) { var n = H.resolveGlobal(e, r.name); var s = H.isShim(r.comment); if (s === "") return null; else if (s !== null) return e.indent + "typedef "+s+" "+n+";"; else return [ e.indent + "struct " + n + "_;", e.indent + "typedef ManagedType<" + n + "_> " + n + ";", ].join("\n"); } private wrapNamespaceIf(e: H.Env, s: string) { if (e.libName != null) return (s.length ? " namespace "+H.mangle(e.libName)+" {\n"+ s + "\n }" : ""); else return s; } private wrapNamespaceDecls(e: H.Env, n: string, s: string[]) { return (s.length ? e.indent + "namespace "+n+" {\n"+ s.join("\n") + "\n" + e.indent + "}" : ""); } // This function runs over all declarations. After execution, the three // member fields [prelude], [prototypes] and [code] are filled accordingly. public visitApp(e: H.Env, decls: J.JDecl[]) { e = H.indent(e); if (e.libName) e = H.indent(e); // Some parts of the emitter need to lookup library names by their id decls.forEach((x: J.JDecl) => { if (x.nodeType == "library") { var l: J.JLibrary = <J.JLibrary> x; this.libraryMap[l.id] = l.name; } }); // Compile type "stubs". Because there may be any kind of recursion // between types, we first declare the structs, then the resulting // ref-counted type (which the TouchDevelop type maps onto): // struct Thing_; // typedef ManagedType<Thing_> Thing; var typeStubs = decls.map((f: J.JDecl) => { var e1 = H.indent(e) if (f.nodeType == "record") return this.typeStub(e1, <J.JRecord> f); else return null; }).filter(x => x != null); var typeStubsCode = this.wrapNamespaceDecls(e, "user_types", typeStubs); // Then, we can emit the definition of the structs (Thing_) because they // refer to TouchDevelop types (Thing). var typeDefs = decls.map((f: J.JDecl) => { var e1 = H.indent(e) if (f.nodeType == "record") return this.typeDecl(e1, <J.JRecord> f); else return null; }).filter(x => x != null); var typeDefsCode = this.wrapNamespaceDecls(e, "user_types", typeDefs); // Globals are in their own namespace (otherwise they would collide with // "math", "number", etc.). var globals = decls.map((f: J.JDecl) => { var e1 = H.indent(e) if (f.nodeType == "data") return this.visit(e1, f); else return null; }).filter(x => x != null); var globalsCode = this.wrapNamespaceDecls(e, "globals", globals); // We need forward declarations for all functions (they're, // by default, mutually recursive in TouchDevelop). var forwardDeclarations = decls.map((f: J.JDecl) => { if (f.nodeType == "action" && H.willCompile(<J.JAction> f)) { return e.indent + H.mkSignature(e, this.libraryMap, H.resolveGlobal(e, f.name), (<J.JAction> f).inParameters, (<J.JAction> f).outParameters)+";"; } else { return null; } }).filter(x => x != null); // Compile all the top-level functions. var userFunctions = decls.map((d: J.JDecl) => { if (d.nodeType == "action" && H.willCompile(<J.JAction> d)) { return this.visit(e, d); } else if (d.nodeType == "art" && d.name == "prelude.cpp") { this.prelude += (<J.JArt> d).value; } else { // The typical library has other stuff mixed in (pictures, other // resources) that are used, say, when running the simulator. Just // silently ignore these. return null; } return null; }).filter(x => x != null); // By convention, because we're forced to return a string, write the // output parameters in the member variables. Image literals are scoped // within our namespace. this.prototypes = this.wrapNamespaceIf(e, globalsCode + "\n" + forwardDeclarations.join("\n")); this.code = this.wrapNamespaceIf(e, this.compileImageLiterals(e) + userFunctions.join("\n")); this.tPrototypes = this.wrapNamespaceIf(e, typeStubsCode); this.tCode = this.wrapNamespaceIf(e, typeDefsCode); // [embedded.ts] now reads the three member fields separately and // ignores this return value. return null; } } } } // vim: set ts=2 sw=2 sts=2:
the_stack
import React, { Component } from 'react'; import PropTypes from 'prop-types'; import TextField from 'material-ui/TextField'; import { Form } from 'formsy-react'; import getMuiTheme from 'material-ui/styles/getMuiTheme'; import { mount } from 'enzyme'; import FormsyText from '../src/FormsyText'; // @ts-ignore import { mountTestForm } from './support'; function makeChildrenFn(props) { const fn = () => ( <FormsyText ref="text" name="text" validations="maxLength:10" validationErrors={{ maxLength: 'Text is too long' }} {...props} /> ); fn.DisplayName = 'FormsyText'; return fn; } const setup = (props = {}) => { const childrenFn = makeChildrenFn(props); const formWrapper = mountTestForm(childrenFn); const formsyTextWrapper = formWrapper.find(FormsyText); return { formWrapper, formsyTextWrapper, }; }; interface ITestFormProps { defaultValue?: string; value?: string; children?: React.ReactNode; disabled?: boolean; } class TestForm extends Component<ITestFormProps> { static childContextTypes = { muiTheme: PropTypes.object.isRequired, }; static propTypes = { children: PropTypes.node, defaultValue: PropTypes.string, value: PropTypes.string, }; getChildContext() { return { muiTheme: getMuiTheme() }; } componentWillMount() { const { value, defaultValue } = this.props; this.state = { value, defaultValue }; } render() { const { value, defaultValue, children, ...extraProps } = { ...this.props, ...this.state, }; return ( <Form {...extraProps}> {children ? children : <FormsyText ref="text" name="text" value={value} defaultValue={defaultValue} />} </Form> ); } } function makeTestParent(props) { const parent = mount(<TestForm {...props} />); const formWrapper = parent.find(Form); const formsyTextWrapper = parent.find(FormsyText); return { parent, formWrapper, formsyTextWrapper }; } const getFormInstance = (wrapper): any => { return wrapper.find(Form).instance(); }; const getInputInstance = (wrapper): any => { return wrapper.find('input').instance(); }; const fillInText = (wrapper, value) => { const input = wrapper.find('input').first(); input.simulate('focus'); input.instance().value = value; input.simulate('blur'); }; describe('FormsyText', () => { it('renders a material-ui TextField', () => { const { formsyTextWrapper } = setup(); expect(formsyTextWrapper.exists(TextField)).toEqual(true); }); it('sends input to the form', () => { const { formsyTextWrapper, formWrapper } = setup(); fillInText(formsyTextWrapper, 'some text'); const formsyForm = getFormInstance(formWrapper); const formValues = formsyForm.getCurrentValues(); expect(formValues.text).toEqual('some text'); }); it('renders validation information', () => { const { formsyTextWrapper, formWrapper } = setup(); expect(formsyTextWrapper.text()).not.toContain('Text is too long'); const formsyForm = getFormInstance(formWrapper); fillInText(formsyTextWrapper, 'toooooooo loooooong'); formsyForm.validateForm(); expect(formsyTextWrapper.text()).toContain('Text is too long'); fillInText(formsyTextWrapper, 'just fine'); formsyForm.validateForm(); expect(formsyTextWrapper.text()).not.toContain('Text is too long'); }); describe('value properties handle', () => { describe('initial', () => { it('value', () => { const { formsyTextWrapper, formWrapper } = setup({ value: 'VALUE', }); const formsyForm = getFormInstance(formWrapper); let formValues = formsyForm.getCurrentValues(); expect(formValues.text).toEqual('VALUE'); fillInText(formsyTextWrapper, 'some text'); formValues = formsyForm.getCurrentValues(); expect(formValues.text).toEqual('some text'); }); it('defaultValue', () => { const { formsyTextWrapper, formWrapper } = setup({ defaultValue: 'DEFAULT-VALUE', }); const formsyForm = getFormInstance(formWrapper); let formValues = formsyForm.getCurrentValues(); expect(formValues.text).toEqual('DEFAULT-VALUE'); fillInText(formsyTextWrapper, 'some text'); formValues = formsyForm.getCurrentValues(); expect(formValues.text).toEqual('some text'); }); it('value + defaultValue', () => { const { formsyTextWrapper, formWrapper } = setup({ value: 'VALUE', defaultValue: 'DEFAULT-VALUE', }); const formsyForm = getFormInstance(formWrapper); let formValues = formsyForm.getCurrentValues(); expect(formValues.text).toEqual('VALUE'); fillInText(formsyTextWrapper, 'some text'); formValues = formsyForm.getCurrentValues(); expect(formValues.text).toEqual('some text'); }); it('propagates disabled status', () => { const wrapper = mount( <TestForm disabled={true}> <FormsyText name="text" /> </TestForm>, ); const inputDOM = getInputInstance(wrapper); expect(inputDOM.disabled).toEqual(true); // Next, we set `disabled` to false and check the DOM node updates accordingly wrapper.setProps({ disabled: false, }); expect(inputDOM.disabled).toEqual(false); }); it('allows overriding disabled status locally', () => { let wrapper = mount( <TestForm disabled={true}> <FormsyText name="text" disabled={false} /> </TestForm>, ); // Here we check we can disable a single input in a globally enabled form let inputDOM = getInputInstance(wrapper); expect(inputDOM.disabled).toEqual(false); wrapper = mount( <TestForm disabled={false}> <FormsyText name="text" disabled={true} /> </TestForm>, ); // Likewise, we are able to keep a specific input enabled even if the form is marked as disabled inputDOM = getInputInstance(wrapper); expect(inputDOM.disabled).toEqual(true); }); }); describe('updating', () => { it('value', () => { const props = { value: 'VALUE', }; const { parent, formWrapper, formsyTextWrapper } = makeTestParent(props); const formsyForm = getFormInstance(formWrapper); parent.setState({ value: 'NEW VALUE' }); let formValues = formsyForm.getCurrentValues(); expect(formValues.text).toEqual('NEW VALUE'); fillInText(formsyTextWrapper, 'some text'); formValues = formsyForm.getCurrentValues(); expect(formValues.text).toEqual('some text'); parent.setState({ value: 'NEWER VALUE' }); formValues = formsyForm.getCurrentValues(); expect(formValues.text).toEqual('NEWER VALUE'); }); it('defaultValue', () => { const props = { defaultValue: 'VALUE', }; const { parent, formWrapper, formsyTextWrapper } = makeTestParent(props); const formsyForm = getFormInstance(formWrapper); parent.setState({ defaultValue: 'NEW VALUE' }); let formValues = formsyForm.getCurrentValues(); expect(formValues.text).toEqual('NEW VALUE'); fillInText(formsyTextWrapper, 'some text'); formValues = formsyForm.getCurrentValues(); expect(formValues.text).toEqual('some text'); parent.setState({ defaultValue: 'NEWER VALUE' }); // defaultValues does not override the typed in value. formValues = formsyForm.getCurrentValues(); expect(formValues.text).toEqual('some text'); }); it('calls onChange once per text update', () => { const calls = []; const { parent, formsyTextWrapper } = makeTestParent({ onChange: (...args) => calls.push(args), value: 'initial', }); const inputDOM = getInputInstance(formsyTextWrapper); inputDOM.value = 'updated'; parent.setState({ value: 'updated' }); expect(calls.length < 3).toEqual(true); }); }); describe('resetting to', () => { it('value', () => { const { formsyTextWrapper, formWrapper } = setup({ value: 'VALUE', }); const formsyForm = getFormInstance(formWrapper); fillInText(formsyTextWrapper, 'some text'); formsyForm.reset(); const formValues = formsyForm.getCurrentValues(); expect(formValues.text).toEqual('VALUE'); }); it('defaultValue', () => { const { formsyTextWrapper, formWrapper } = setup({ defaultValue: 'VALUE', }); const formsyForm = getFormInstance(formWrapper); fillInText(formsyTextWrapper, 'some text'); formsyForm.reset(); const formValues = formsyForm.getCurrentValues(); expect(formValues.text).toEqual('VALUE'); }); it('value + defaultValue', () => { const { formsyTextWrapper, formWrapper } = setup({ value: 'VALUE', defaultValue: 'DEFAULT-VALUE', }); const formsyForm = getFormInstance(formWrapper); fillInText(formsyTextWrapper, 'some text'); formsyForm.reset(); const formValues = formsyForm.getCurrentValues(); expect(formValues.text).toEqual('VALUE'); }); it('updated value', () => { const props = { value: 'VALUE', }; const { parent, formWrapper, formsyTextWrapper } = makeTestParent(props); const formsyForm = getFormInstance(formWrapper); parent.setState({ value: 'NEW VALUE' }); fillInText(formsyTextWrapper, 'some text'); formsyForm.reset(); // Reset reverts to the last value that has been set. const formValues = formsyForm.getCurrentValues(); expect(formValues.text).toEqual('NEW VALUE'); }); }); describe('with convertValue', () => { it('converts to number', () => { const { formsyTextWrapper, formWrapper } = setup({ value: 1, type: 'number', convertValue: v => Number(v), }); const formsyForm = getFormInstance(formWrapper); let formValues = formsyForm.getCurrentValues(); expect(formValues.text).toEqual(1); fillInText(formsyTextWrapper, '2'); formValues = formsyForm.getCurrentValues(); expect(formValues.text).toEqual(2); }); it('and defaultValue', () => { const { formWrapper } = setup({ defaultValue: 1, type: 'number', convertValue: v => Number(v), }); const formsyForm = getFormInstance(formWrapper); const formValues = formsyForm.getCurrentValues(); expect(formValues.text).toEqual(1); }); it('and no value', () => { const { formWrapper } = setup({ type: 'number', convertValue: v => Number(v), }); const formsyForm = getFormInstance(formWrapper); const formValues = formsyForm.getCurrentValues(); expect(formValues.text).toEqual(0); }); }); }); });
the_stack
import * as assert from 'assert'; import { merge } from 'vs/platform/userDataSync/common/snippetsMerge'; const tsSnippet1 = `{ // Place your snippets for TypeScript here. Each snippet is defined under a snippet name and has a prefix, body and // description. The prefix is what is used to trigger the snippet and the body will be expanded and inserted. Possible variables are: // $1, $2 for tab stops, $0 for the final cursor position, Placeholders with the // same ids are connected. "Print to console": { // Example: "prefix": "log", "body": [ "console.log('$1');", "$2" ], "description": "Log output to console", } }`; const tsSnippet2 = `{ // Place your snippets for TypeScript here. Each snippet is defined under a snippet name and has a prefix, body and // description. The prefix is what is used to trigger the snippet and the body will be expanded and inserted. Possible variables are: // $1, $2 for tab stops, $0 for the final cursor position, Placeholders with the // same ids are connected. "Print to console": { // Example: "prefix": "log", "body": [ "console.log('$1');", "$2" ], "description": "Log output to console always", } }`; const htmlSnippet1 = `{ /* // Place your snippets for HTML here. Each snippet is defined under a snippet name and has a prefix, body and // description. The prefix is what is used to trigger the snippet and the body will be expanded and inserted. // Example: "Print to console": { "prefix": "log", "body": [ "console.log('$1');", "$2" ], "description": "Log output to console" } */ "Div": { "prefix": "div", "body": [ "<div>", "", "</div>" ], "description": "New div" } }`; const htmlSnippet2 = `{ /* // Place your snippets for HTML here. Each snippet is defined under a snippet name and has a prefix, body and // description. The prefix is what is used to trigger the snippet and the body will be expanded and inserted. // Example: "Print to console": { "prefix": "log", "body": [ "console.log('$1');", "$2" ], "description": "Log output to console" } */ "Div": { "prefix": "div", "body": [ "<div>", "", "</div>" ], "description": "New div changed" } }`; const cSnippet = `{ // Place your snippets for c here. Each snippet is defined under a snippet name and has a prefix, body and // description. The prefix is what is used to trigger the snippet and the body will be expanded and inserted. Possible variables are: // $1, $2 for tab stops, $0 for the final cursor position.Placeholders with the // same ids are connected. // Example: "Print to console": { "prefix": "log", "body": [ "console.log('$1');", "$2" ], "description": "Log output to console" } }`; suite('SnippetsMerge', () => { test('merge when local and remote are same with one snippet', async () => { const local = { 'html.json': htmlSnippet1 }; const remote = { 'html.json': htmlSnippet1 }; const actual = merge(local, remote, null); assert.deepStrictEqual(actual.local.added, {}); assert.deepStrictEqual(actual.local.updated, {}); assert.deepStrictEqual(actual.local.removed, []); assert.deepStrictEqual(actual.conflicts, []); assert.deepStrictEqual(actual.remote.added, {}); assert.deepStrictEqual(actual.remote.updated, {}); assert.deepStrictEqual(actual.remote.removed, []); }); test('merge when local and remote are same with multiple entries', async () => { const local = { 'html.json': htmlSnippet1, 'typescript.json': tsSnippet1 }; const remote = { 'html.json': htmlSnippet1, 'typescript.json': tsSnippet1 }; const actual = merge(local, remote, null); assert.deepStrictEqual(actual.local.added, {}); assert.deepStrictEqual(actual.local.updated, {}); assert.deepStrictEqual(actual.local.removed, []); assert.deepStrictEqual(actual.conflicts, []); assert.deepStrictEqual(actual.remote.added, {}); assert.deepStrictEqual(actual.remote.updated, {}); assert.deepStrictEqual(actual.remote.removed, []); }); test('merge when local and remote are same with multiple entries in different order', async () => { const local = { 'typescript.json': tsSnippet1, 'html.json': htmlSnippet1 }; const remote = { 'html.json': htmlSnippet1, 'typescript.json': tsSnippet1 }; const actual = merge(local, remote, null); assert.deepStrictEqual(actual.local.added, {}); assert.deepStrictEqual(actual.local.updated, {}); assert.deepStrictEqual(actual.local.removed, []); assert.deepStrictEqual(actual.conflicts, []); assert.deepStrictEqual(actual.remote.added, {}); assert.deepStrictEqual(actual.remote.updated, {}); assert.deepStrictEqual(actual.remote.removed, []); }); test('merge when local and remote are same with different base content', async () => { const local = { 'html.json': htmlSnippet1, 'typescript.json': tsSnippet1 }; const remote = { 'html.json': htmlSnippet1, 'typescript.json': tsSnippet1 }; const base = { 'html.json': htmlSnippet2, 'typescript.json': tsSnippet2 }; const actual = merge(local, remote, base); assert.deepStrictEqual(actual.local.added, {}); assert.deepStrictEqual(actual.local.updated, {}); assert.deepStrictEqual(actual.local.removed, []); assert.deepStrictEqual(actual.conflicts, []); assert.deepStrictEqual(actual.remote.added, {}); assert.deepStrictEqual(actual.remote.updated, {}); assert.deepStrictEqual(actual.remote.removed, []); }); test('merge when a new entry is added to remote', async () => { const local = { 'html.json': htmlSnippet1 }; const remote = { 'html.json': htmlSnippet1, 'typescript.json': tsSnippet1 }; const actual = merge(local, remote, null); assert.deepStrictEqual(actual.local.added, { 'typescript.json': tsSnippet1 }); assert.deepStrictEqual(actual.local.updated, {}); assert.deepStrictEqual(actual.local.removed, []); assert.deepStrictEqual(actual.conflicts, []); assert.deepStrictEqual(actual.remote.added, {}); assert.deepStrictEqual(actual.remote.updated, {}); assert.deepStrictEqual(actual.remote.removed, []); }); test('merge when multiple new entries are added to remote', async () => { const local = {}; const remote = { 'html.json': htmlSnippet1, 'typescript.json': tsSnippet1 }; const actual = merge(local, remote, null); assert.deepStrictEqual(actual.local.added, remote); assert.deepStrictEqual(actual.local.updated, {}); assert.deepStrictEqual(actual.local.removed, []); assert.deepStrictEqual(actual.conflicts, []); assert.deepStrictEqual(actual.remote.added, {}); assert.deepStrictEqual(actual.remote.updated, {}); assert.deepStrictEqual(actual.remote.removed, []); }); test('merge when new entry is added to remote from base and local has not changed', async () => { const local = { 'html.json': htmlSnippet1 }; const remote = { 'html.json': htmlSnippet1, 'typescript.json': tsSnippet1 }; const actual = merge(local, remote, local); assert.deepStrictEqual(actual.local.added, { 'typescript.json': tsSnippet1 }); assert.deepStrictEqual(actual.local.updated, {}); assert.deepStrictEqual(actual.local.removed, []); assert.deepStrictEqual(actual.conflicts, []); assert.deepStrictEqual(actual.remote.added, {}); assert.deepStrictEqual(actual.remote.updated, {}); assert.deepStrictEqual(actual.remote.removed, []); }); test('merge when an entry is removed from remote from base and local has not changed', async () => { const local = { 'html.json': htmlSnippet1, 'typescript.json': tsSnippet1 }; const remote = { 'html.json': htmlSnippet1 }; const actual = merge(local, remote, local); assert.deepStrictEqual(actual.local.added, {}); assert.deepStrictEqual(actual.local.updated, {}); assert.deepStrictEqual(actual.local.removed, ['typescript.json']); assert.deepStrictEqual(actual.conflicts, []); assert.deepStrictEqual(actual.remote.added, {}); assert.deepStrictEqual(actual.remote.updated, {}); assert.deepStrictEqual(actual.remote.removed, []); }); test('merge when all entries are removed from base and local has not changed', async () => { const local = { 'html.json': htmlSnippet1, 'typescript.json': tsSnippet1 }; const remote = {}; const actual = merge(local, remote, local); assert.deepStrictEqual(actual.local.added, {}); assert.deepStrictEqual(actual.local.updated, {}); assert.deepStrictEqual(actual.local.removed, ['html.json', 'typescript.json']); assert.deepStrictEqual(actual.conflicts, []); assert.deepStrictEqual(actual.remote.added, {}); assert.deepStrictEqual(actual.remote.updated, {}); assert.deepStrictEqual(actual.remote.removed, []); }); test('merge when an entry is updated in remote from base and local has not changed', async () => { const local = { 'html.json': htmlSnippet1 }; const remote = { 'html.json': htmlSnippet2 }; const actual = merge(local, remote, local); assert.deepStrictEqual(actual.local.added, {}); assert.deepStrictEqual(actual.local.updated, { 'html.json': htmlSnippet2 }); assert.deepStrictEqual(actual.local.removed, []); assert.deepStrictEqual(actual.conflicts, []); assert.deepStrictEqual(actual.remote.added, {}); assert.deepStrictEqual(actual.remote.updated, {}); assert.deepStrictEqual(actual.remote.removed, []); }); test('merge when remote has moved forwarded with multiple changes and local stays with base', async () => { const local = { 'html.json': htmlSnippet1, 'typescript.json': tsSnippet1 }; const remote = { 'html.json': htmlSnippet2, 'c.json': cSnippet }; const actual = merge(local, remote, local); assert.deepStrictEqual(actual.local.added, { 'c.json': cSnippet }); assert.deepStrictEqual(actual.local.updated, { 'html.json': htmlSnippet2 }); assert.deepStrictEqual(actual.local.removed, ['typescript.json']); assert.deepStrictEqual(actual.conflicts, []); assert.deepStrictEqual(actual.remote.added, {}); assert.deepStrictEqual(actual.remote.updated, {}); assert.deepStrictEqual(actual.remote.removed, []); }); test('merge when a new entries are added to local', async () => { const local = { 'html.json': htmlSnippet1, 'typescript.json': tsSnippet1, 'c.json': cSnippet }; const remote = { 'html.json': htmlSnippet1, 'typescript.json': tsSnippet1 }; const actual = merge(local, remote, null); assert.deepStrictEqual(actual.local.added, {}); assert.deepStrictEqual(actual.local.updated, {}); assert.deepStrictEqual(actual.local.removed, []); assert.deepStrictEqual(actual.conflicts, []); assert.deepStrictEqual(actual.remote.added, { 'c.json': cSnippet }); assert.deepStrictEqual(actual.remote.updated, {}); assert.deepStrictEqual(actual.remote.removed, []); }); test('merge when multiple new entries are added to local from base and remote is not changed', async () => { const local = { 'html.json': htmlSnippet1, 'typescript.json': tsSnippet1, 'c.json': cSnippet }; const remote = { 'typescript.json': tsSnippet1 }; const actual = merge(local, remote, remote); assert.deepStrictEqual(actual.local.added, {}); assert.deepStrictEqual(actual.local.updated, {}); assert.deepStrictEqual(actual.local.removed, []); assert.deepStrictEqual(actual.conflicts, []); assert.deepStrictEqual(actual.remote.added, { 'html.json': htmlSnippet1, 'c.json': cSnippet }); assert.deepStrictEqual(actual.remote.updated, {}); assert.deepStrictEqual(actual.remote.removed, []); }); test('merge when an entry is removed from local from base and remote has not changed', async () => { const local = { 'html.json': htmlSnippet1 }; const remote = { 'html.json': htmlSnippet1, 'typescript.json': tsSnippet1 }; const actual = merge(local, remote, remote); assert.deepStrictEqual(actual.local.added, {}); assert.deepStrictEqual(actual.local.updated, {}); assert.deepStrictEqual(actual.local.removed, []); assert.deepStrictEqual(actual.conflicts, []); assert.deepStrictEqual(actual.remote.added, {}); assert.deepStrictEqual(actual.remote.updated, {}); assert.deepStrictEqual(actual.remote.removed, ['typescript.json']); }); test('merge when an entry is updated in local from base and remote has not changed', async () => { const local = { 'html.json': htmlSnippet2, 'typescript.json': tsSnippet1 }; const remote = { 'html.json': htmlSnippet1, 'typescript.json': tsSnippet1 }; const actual = merge(local, remote, remote); assert.deepStrictEqual(actual.local.added, {}); assert.deepStrictEqual(actual.local.updated, {}); assert.deepStrictEqual(actual.local.removed, []); assert.deepStrictEqual(actual.conflicts, []); assert.deepStrictEqual(actual.remote.added, {}); assert.deepStrictEqual(actual.remote.updated, { 'html.json': htmlSnippet2 }); assert.deepStrictEqual(actual.remote.removed, []); }); test('merge when local has moved forwarded with multiple changes and remote stays with base', async () => { const local = { 'html.json': htmlSnippet2, 'c.json': cSnippet }; const remote = { 'html.json': htmlSnippet1, 'typescript.json': tsSnippet1 }; const actual = merge(local, remote, remote); assert.deepStrictEqual(actual.local.added, {}); assert.deepStrictEqual(actual.local.updated, {}); assert.deepStrictEqual(actual.local.removed, []); assert.deepStrictEqual(actual.conflicts, []); assert.deepStrictEqual(actual.remote.added, { 'c.json': cSnippet }); assert.deepStrictEqual(actual.remote.updated, { 'html.json': htmlSnippet2 }); assert.deepStrictEqual(actual.remote.removed, ['typescript.json']); }); test('merge when local and remote with one entry but different value', async () => { const local = { 'html.json': htmlSnippet1 }; const remote = { 'html.json': htmlSnippet2 }; const actual = merge(local, remote, null); assert.deepStrictEqual(actual.local.added, {}); assert.deepStrictEqual(actual.local.updated, {}); assert.deepStrictEqual(actual.local.removed, []); assert.deepStrictEqual(actual.conflicts, ['html.json']); assert.deepStrictEqual(actual.remote.added, {}); assert.deepStrictEqual(actual.remote.updated, {}); assert.deepStrictEqual(actual.remote.removed, []); }); test('merge when the entry is removed in remote but updated in local and a new entry is added in remote', async () => { const base = { 'html.json': htmlSnippet1 }; const local = { 'html.json': htmlSnippet2 }; const remote = { 'typescript.json': tsSnippet1 }; const actual = merge(local, remote, base); assert.deepStrictEqual(actual.local.added, { 'typescript.json': tsSnippet1 }); assert.deepStrictEqual(actual.local.updated, {}); assert.deepStrictEqual(actual.local.removed, []); assert.deepStrictEqual(actual.conflicts, ['html.json']); assert.deepStrictEqual(actual.remote.added, {}); assert.deepStrictEqual(actual.remote.updated, {}); assert.deepStrictEqual(actual.remote.removed, []); }); test('merge with single entry and local is empty', async () => { const base = { 'html.json': htmlSnippet1 }; const local = {}; const remote = { 'html.json': htmlSnippet2 }; const actual = merge(local, remote, base); assert.deepStrictEqual(actual.local.added, { 'html.json': htmlSnippet2 }); assert.deepStrictEqual(actual.local.updated, {}); assert.deepStrictEqual(actual.local.removed, []); assert.deepStrictEqual(actual.conflicts, []); assert.deepStrictEqual(actual.remote.added, {}); assert.deepStrictEqual(actual.remote.updated, {}); assert.deepStrictEqual(actual.remote.removed, []); }); test('merge when local and remote has moved forwareded with conflicts', async () => { const base = { 'html.json': htmlSnippet1, 'typescript.json': tsSnippet1 }; const local = { 'html.json': htmlSnippet2, 'c.json': cSnippet }; const remote = { 'typescript.json': tsSnippet2 }; const actual = merge(local, remote, base); assert.deepStrictEqual(actual.local.added, { 'typescript.json': tsSnippet2 }); assert.deepStrictEqual(actual.local.updated, {}); assert.deepStrictEqual(actual.local.removed, []); assert.deepStrictEqual(actual.conflicts, ['html.json']); assert.deepStrictEqual(actual.remote.added, { 'c.json': cSnippet }); assert.deepStrictEqual(actual.remote.updated, {}); assert.deepStrictEqual(actual.remote.removed, []); }); test('merge when local and remote has moved forwareded with multiple conflicts', async () => { const base = { 'html.json': htmlSnippet1, 'typescript.json': tsSnippet1 }; const local = { 'html.json': htmlSnippet2, 'typescript.json': tsSnippet2, 'c.json': cSnippet }; const remote = { 'c.json': cSnippet }; const actual = merge(local, remote, base); assert.deepStrictEqual(actual.local.added, {}); assert.deepStrictEqual(actual.local.updated, {}); assert.deepStrictEqual(actual.local.removed, []); assert.deepStrictEqual(actual.conflicts, ['html.json', 'typescript.json']); assert.deepStrictEqual(actual.remote.added, {}); assert.deepStrictEqual(actual.remote.updated, {}); assert.deepStrictEqual(actual.remote.removed, []); }); });
the_stack
import { TestFactory } from './tests/factories/test-factory'; import { DocumentCollection } from './document-collection'; import { IDocumentResource } from './interfaces/data-object'; import { IParamsResource } from './interfaces/params-resource'; import { DocumentResource } from './document-resource'; import { Core } from './core'; import { PathBuilder } from './services/path-builder'; import { Resource } from './resource'; import { of } from 'rxjs'; describe('resource', () => { // it('should be reset()', () => { // resource.id = 'some-id'; // expect(resource.id).toBe('some-id'); // resource.reset(); // expect(resource.id).toBe(''); // }); it('hasManyRelated()', () => { // @todo relation alias is not present // @todo relation alias is present, but data is an empty array // @todo relation alias is present, but data is not present }); it('hasOneRelated()', () => { // @todo relation alias is not present // @todo relation alias is present, but data is a null // @todo relation alias is present, but data is undefined }); it('should save the resource without relationships that dont refer to a resource or mean to remove the relationship', async () => { let resource = new Resource(); spyOn(resource, 'getService').and.returnValue(false); spyOn(PathBuilder.prototype, 'applyParams'); resource.id = '1234'; resource.type = 'tests'; resource.attributes = { name: 'test_name' }; resource.relationships = { has_one_relationship: new DocumentResource(), has_many_relationship: new DocumentCollection() }; resource.links = {}; resource.is_new = false; resource.is_saving = false; resource.is_loading = false; resource.loaded = true; resource.source = 'store'; resource.cache_last_update = 0; let response = Object.create(resource); let exec_spy = spyOn(Core, 'exec').and.returnValue(of({ data: response })); await resource.save(); resource.relationships = {}; let expected_resource_in_save = { data: { type: 'tests', id: '1234', attributes: { name: 'test_name' }, relationships: {} } }; expect(exec_spy).toHaveBeenCalledWith('1234', 'PATCH', expected_resource_in_save, true); resource.relationships.has_many_relationship = new DocumentCollection(); resource.relationships.has_many_relationship.builded = true; resource.relationships.has_one_relationship = <any>{ data: null }; await resource.save(); let second_expected_resource_in_save = { data: { type: 'tests', id: '1234', attributes: { name: 'test_name' }, relationships: { has_many_relationship: { data: [] }, has_one_relationship: { data: null } } } }; expect(exec_spy).toHaveBeenCalledWith('1234', 'PATCH', second_expected_resource_in_save, true); }); it('toObject method should parse the resouce in a new IDocumentResource', () => { let mocked_service_data: { [key: string]: any } = { parseToServer: false }; spyOn(Resource.prototype, 'getService').and.returnValue(mocked_service_data); let new_resource: Resource = new Resource(); new_resource.type = 'main'; new_resource.id = '1'; new_resource.attributes = { main_attribute: '123456789' }; new_resource.relationships = { resource_relationship: new DocumentResource() }; let resource_relationship: Resource = new Resource(); resource_relationship.type = 'resource_relationship'; resource_relationship.id = '123'; resource_relationship.attributes = { first: '1' }; new_resource.addRelationship(resource_relationship); let params: IParamsResource = { beforepath: '', include: ['resource_relationship'], ttl: 0 // id: '', }; let to_object_resource: IDocumentResource = new_resource.toObject(params); expect(to_object_resource.data.id).toBe('1'); expect(to_object_resource.data.type).toBe('main'); expect(to_object_resource.data.attributes.main_attribute).toBe('123456789'); expect((to_object_resource.data.relationships as any).resource_relationship.data.id).toBe('123'); expect((to_object_resource.data.relationships as any).resource_relationship.data.type).toBe('resource_relationship'); expect(to_object_resource.included[0].id).toBe('123'); expect(to_object_resource.included[0].type).toBe('resource_relationship'); expect(to_object_resource.included[0].attributes.first).toBe('1'); }); }); describe('resource.toObject() method', () => { it('(toObject) If the service has a parseToServer method, ir should be applied in toObject method', () => { let mocked_service_data = { parseToServer: (attr: { [key: string]: any }): { [key: string]: any } => { attr.main_attribute = parseInt(attr.main_attribute, 10); return attr; } }; spyOn(Resource.prototype, 'getService').and.returnValue(mocked_service_data); let new_resource: Resource = new Resource(); new_resource.type = 'main'; new_resource.id = '1'; new_resource.attributes = { main_attribute: '123456789' }; new_resource.relationships = { resource_relationship: new DocumentResource() }; let resource_relationship: Resource = new Resource(); resource_relationship.type = 'resource_relationship'; resource_relationship.id = '123'; resource_relationship.attributes = { first: '1' }; new_resource.addRelationship(resource_relationship); let params: IParamsResource = { beforepath: '', include: ['resource_relationship'], ttl: 0 // id: '', }; let to_object_resource = new_resource.toObject(params); expect(to_object_resource.data.attributes.main_attribute).toBe(123456789); }); it('(toObject) If a relationship is not a document resource or document collection instance, a warn should be reaised', () => { let console_warn_spy = spyOn(console, 'warn'); let mocked_service_data: { [key: string]: any } = { parseToServer: false }; spyOn(Resource.prototype, 'getService').and.returnValue(mocked_service_data); let new_resource: Resource = new Resource(); new_resource.type = 'main'; new_resource.id = '1'; new_resource.attributes = { main_attribute: '123456789' }; (new_resource.relationships as any) = { resource_relationship: {} }; let resource_relationship: Resource = new Resource(); resource_relationship.type = 'resource_relationship'; resource_relationship.id = '123'; resource_relationship.attributes = { first: '1' }; new_resource.addRelationship(resource_relationship); let params: IParamsResource = { beforepath: '', include: ['resource_relationship'], ttl: 0 // id: '', }; let to_object_resource: IDocumentResource = new_resource.toObject(params); expect(to_object_resource).toBeTruthy(); expect(console_warn_spy).toHaveBeenCalled(); }); it('(toObject) If a relationship is not in the include param, it should not be included in the resulting include field', () => { spyOn(Resource.prototype, 'getService').and.returnValue({}); let console_warn_spy = spyOn(console, 'warn'); let new_resource: Resource = new Resource(); new_resource.type = 'main'; new_resource.id = '1'; new_resource.attributes = { main_attribute: '123456789' }; new_resource.relationships = { resource_relationship: new DocumentResource() }; let resource_relationship: Resource = new Resource(); resource_relationship.type = 'resource_relationship'; resource_relationship.id = '123'; resource_relationship.attributes = { first: '1' }; new_resource.addRelationship(resource_relationship); let params: IParamsResource = { beforepath: '', include: [], ttl: 0 // id: '', }; let to_object_resource: IDocumentResource = new_resource.toObject(params); expect(to_object_resource).toBeTruthy(); expect(to_object_resource.included).toBeFalsy(); }); it('(toObject) hasMany empty and untouched relationship should be removed from the resulting relationships', () => { spyOn(Resource.prototype, 'getService').and.returnValue({}); let book = TestFactory.getBook('5'); // TODO: revisar test... cómo vamos a eliminar relaciones hasMany cuando haya solo una? book.relationships.photos.data = []; let params: IParamsResource = { beforepath: '', include: ['resource_relationships'], ttl: 0 }; let book_object = book.toObject(params); expect(book_object.data.relationships.photos).toBeUndefined(); expect(book_object.included).toBeFalsy(); }); it('(toObject) hasMany empty and builded relationship should return an emtpy relationship', () => { spyOn(Resource.prototype, 'getService').and.returnValue({}); let book = TestFactory.getBook('1'); book.relationships.photos.data = []; book.addRelationship(TestFactory.getPhoto('5'), 'photos'); expect(book.toObject().data.relationships.photos.data[0].id).toBe('5'); book.removeRelationship('photos', '5'); expect(book.relationships.photos.builded).toBe(true); expect(book.relationships.photos.content).toBe('collection'); expect(book.toObject().data.relationships.photos.data).toEqual([]); }); it('(toObject) hasMany whith only ids and builded relationship should be return a relationship with ids', () => { spyOn(Resource.prototype, 'getService').and.returnValue({}); let book = TestFactory.getBook('1'); book.relationships.photos.fill({ data: [{ id: '4', type: 'photos' }] }); expect(book.relationships.photos.builded).toBe(false); expect(book.relationships.photos.content).toBe('ids'); expect(book.toObject().data.relationships.photos.data.length).toBe(1); expect(book.toObject().data.relationships.photos.data[0]).toMatchObject({ id: '4', type: 'photos' }); }); it('(toObject) hasMany relationships that are OK should be included in the resulting relationships', () => { spyOn(Resource.prototype, 'getService').and.returnValue({}); let new_resource: Resource = new Resource(); new_resource.type = 'main'; new_resource.id = '1'; new_resource.attributes = { main_attribute: '123456789' }; new_resource.relationships = { resource_relationships: new DocumentCollection() }; let resource_relationships: DocumentCollection = new DocumentCollection(); let resource_relationship: Resource = new Resource(); resource_relationship.type = 'resource_relationship'; resource_relationship.id = '123'; resource_relationship.attributes = { first: '1' }; resource_relationships.data.push(resource_relationship); new_resource.relationships.resource_relationships = resource_relationships; let params: IParamsResource = { beforepath: '', include: ['resource_relationships'], ttl: 0 // id: '', }; let to_object_resource: IDocumentResource = new_resource.toObject(params); expect(to_object_resource).toBeTruthy(); expect((to_object_resource.data.relationships as any).resource_relationships.data[0].id).toBe('123'); expect(to_object_resource.included[0].id).toBe('123'); }); it('(toObject) hasOne empty data and untouched relationship should be removed from the resulting relationships', () => { spyOn(Resource.prototype, 'getService').and.returnValue({}); let book = TestFactory.getBook('5'); // TODO: revisar test... book.relationships.author.data = undefined; let book_object = book.toObject(); // expect(book_object.data.relationships.author).toBeUndefined(); // TODO: fix test or library: is returning data: undefined expect(book_object.included).toBeFalsy(); }); it('(toObject) hasOne data null relationship should be return a data nulled relationship', () => { spyOn(Resource.prototype, 'getService').and.returnValue({}); let book = TestFactory.getBook('5'); book.addRelationship(TestFactory.getAuthor('1'), 'author'); expect(book.toObject().data.relationships.author.data.id).toBe('1'); book.removeRelationship('author', '1'); expect(book.relationships.author.data).toBeNull(); let book_object = book.toObject(); expect(book_object.data.relationships.author.data).toBeNull(); expect(book_object.included).toBeFalsy(); }); it('(toObject) hasOne data filled relationship should be return a simple object relationship', () => { spyOn(Resource.prototype, 'getService').and.returnValue({}); let book = TestFactory.getBook('5'); book.addRelationship(TestFactory.getAuthor('1'), 'author'); let book_object = book.toObject(); expect(book_object.data.relationships.author.data.id).toBe('1'); expect(book_object.included).toBeFalsy(); }); }); describe('resource.save() method', () => { it('if set, te save method should send the "meta" property when saving a resource', async () => { let resource = new Resource(); spyOn(resource, 'getService').and.returnValue(false); spyOn(PathBuilder.prototype, 'applyParams'); resource.id = '1234'; resource.type = 'tests'; resource.attributes = { name: 'test_name' }; resource.relationships = { has_one_relationship: new DocumentResource(), has_many_relationship: new DocumentCollection() }; resource.links = {}; resource.is_new = true; resource.is_saving = false; resource.is_loading = false; resource.loaded = true; resource.source = 'store'; resource.cache_last_update = 0; resource.relationships = {}; resource.meta = { some_data: 'some_data' }; let response = Object.create(resource); let exec_spy = spyOn(Core, 'exec').and.returnValue(of({ data: response })); await resource.save(); let expected_resource_in_save = { data: { type: 'tests', id: '1234', attributes: { name: 'test_name' }, relationships: {}, meta: { some_data: 'some_data' } } }; expect(exec_spy).toHaveBeenCalledWith('1234', 'POST', expected_resource_in_save, true); }); it('top level meta object should be included in the request if available', async () => { let resource = new Resource(); spyOn(resource, 'getService').and.returnValue(false); spyOn(PathBuilder.prototype, 'applyParams'); resource.id = '1234'; resource.type = 'tests'; resource.attributes = { name: 'test_name' }; resource.relationships = { has_one_relationship: new DocumentResource(), has_many_relationship: new DocumentCollection() }; resource.links = {}; resource.is_new = true; resource.is_saving = false; resource.is_loading = false; resource.loaded = true; resource.source = 'store'; resource.cache_last_update = 0; resource.relationships = {}; let response = Object.create(resource); let exec_spy = spyOn(Core, 'exec').and.returnValue(of({ data: response })); await resource.save({ meta: { restore: true } }); let expected_resource_in_save = { data: { type: 'tests', id: '1234', attributes: { name: 'test_name' }, relationships: {} }, meta: { restore: true } }; expect(exec_spy).toHaveBeenCalledWith('1234', 'POST', expected_resource_in_save, true); }); it('restore method should set top level meta to restore the resource (according to Reyesoft specification extension)', async () => { let resource = new Resource(); spyOn(resource, 'getService').and.returnValue(false); spyOn(PathBuilder.prototype, 'applyParams'); resource.id = '1234'; resource.type = 'tests'; resource.attributes = { name: 'test_name' }; resource.relationships = { has_one_relationship: new DocumentResource(), has_many_relationship: new DocumentCollection() }; resource.links = {}; resource.is_new = true; resource.is_saving = false; resource.is_loading = false; resource.loaded = true; resource.source = 'store'; resource.cache_last_update = 0; resource.relationships = {}; let response = Object.create(resource); let exec_spy = spyOn(Core, 'exec').and.returnValue(of({ data: response })); await resource.restore(); let expected_resource_in_save = { data: { type: 'tests', id: '1234', attributes: { name: 'test_name' }, relationships: {} }, meta: { restore: true } }; expect(exec_spy).toHaveBeenCalledWith('1234', 'POST', expected_resource_in_save, true); }); // @todo fill from store to more new version of resource // for example store has more lationships, but we are filling a resource created from server. // is possible this scenario? });
the_stack
import {Bundle} from "./model/bundle"; import {StructureDefinition} from "./model/structure-definition"; import {ElementDefinition} from "./model/element-definition"; import {ParseConformance} from "./parseConformance"; /** * Responsible for creating snapshots on StructureDefinition resources based on the differential of the profile. */ export class SnapshotGenerator { /** * A string that represents all options possible in STU3 and R4 for choice elements, ex: value[x], effective[x], etc.) * It is used to create a regex that tests that value[x] matches valueQuantity in an ElementDefinition.path. */ private readonly choiceRegexString = '(Instant|Time|Date|DateTime|Decimal|Boolean|Integer|String|Uri|Base64Binary|Code|Id|Oid|UnsignedInt|PositiveInt|Markdown|Url|Canonical|Uuid|Identifier|HumanName|Address|ContactPoint|Timing|Quantity|SimpleQuantity|Attachment|Range|Period|Ratio|CodeableConcept|Coding|SampledData|Age|Distance|Duration|Count|Money|MoneyQuantity|Annotation|Signature|ContactDetail|Contributor|DataRequirement|ParameterDefinition|RelatedArtifact|TriggerDefinition|UsageContext|Expression|Reference|Narrative|Extension|Meta|ElementDefinition|Dosage|Xhtml)'; /** * The parser containing FHIR versioning and base profile information */ private readonly parser: ParseConformance; /** * The bundle passed into the constructor whose structure definitions should have snapshots generated */ private readonly bundle: Bundle; /** * A field that tracks what profiles have been processed during the .generate() operation, so that profiles are not processed multiple times in a single run. */ private processedUrls: string[] = []; /** * * @param parser (ParseConformance) The parser that holds FHIR version information, and has base FHIR structures loaded in it * @param bundle The bundle including structure definitions whose snapshot should be generated */ constructor(parser: ParseConformance, bundle: Bundle) { this.parser = parser; this.bundle = bundle; } /** * Creates a bundle out of StructureDefinition resources. This is just for making it easier to pass a bundle to the constructor of this class. * @param structureDefinitions */ static createBundle(...structureDefinitions: StructureDefinition[]) { const entries = structureDefinitions.map((sd: StructureDefinition) => { return {resource: sd}; }); const bundle: Bundle = { resourceType: 'Bundle', total: structureDefinitions.length, entry: entries }; return bundle; } /** * Gets a StructureDefinition based on the url and type. First determines if the url represents a base resource in the FHIR spec, then looks through * the bundle passed to the constructor of the class to find the structure. * @param url The url of the profile to retrieve * @param type The type of resource the profile constrains (ex: Composition, or Patient, or Person, etc.) */ private getStructureDefinition(url: string, type: string) { const isBaseProfile = this.parser.isBaseProfile(url); const fhirBase = isBaseProfile ? this.parser.structureDefinitions.find(sd => sd.url.toLowerCase() === ('http://hl7.org/fhir/StructureDefinition/' + type).toLowerCase()) : null; if (isBaseProfile && !fhirBase) { throw new Error(`Base profile for ${url} not found. Perhaps the structures have not been loaded?`); } if (fhirBase) { return fhirBase; } const parentEntry = this.bundle.entry.find(entry => entry.resource.url === url); if (!parentEntry) { throw new Error(`Cannot find base definition "${url}" in bundle or core FHIR specification.`) } this.process(parentEntry.resource); return parentEntry.resource; } private merge(diff: any, snapshot: any) { const dest = JSON.parse(JSON.stringify(snapshot)); const explicitOverwrites = ['id', 'representation', 'sliceName', 'sliceIsConstraining', 'label', 'code', 'short', 'definition', 'comment', 'requirements', 'alias', 'min', 'max', 'contentReference', 'meaningWhenMissing', 'orderMeaning', 'maxLength', 'condition', 'mustSupport', 'isModifier', 'isModifierReason', 'isSummary', 'example']; for (let eo of explicitOverwrites) { if (diff.hasOwnProperty(eo)) dest[eo] = diff[eo]; } if (diff.slicing && dest.slicing) { if (diff.slicing.hasOwnProperty('discriminator')) dest.slicing.discriminator = diff.slicing.discriminator; if (diff.slicing.hasOwnProperty('description')) dest.slicing.description = diff.slicing.description; if (diff.slicing.hasOwnProperty('ordered')) dest.slicing.ordered = diff.slicing.ordered; if (diff.slicing.hasOwnProperty('rules')) dest.slicing.rules = diff.slicing.rules; } else if (diff.slicing) { dest.slicing = diff.slicing; } if (diff.base && dest.base) { if (diff.base.hasOwnProperty('path')) dest.base.path = diff.base.path; if (diff.base.hasOwnProperty('min')) dest.base.min = diff.base.min; if (diff.base.hasOwnProperty('max')) dest.base.max = diff.base.max; } else if (diff.base) { dest.base = diff.base; } if (diff.type && dest.type) { for (let dt of dest.type) { const diffType = diff.type.find(t => t.code === dt.code); if (diffType) { if (diffType.hasOwnProperty('profile')) dt.profile = diffType.profile; if (diffType.hasOwnProperty('targetProfile')) dt.targetProfile = diffType.targetProfile; if (diffType.hasOwnProperty('aggregation')) dt.aggregation = diffType.aggregation; if (diffType.hasOwnProperty('versioning')) dt.versioning = diffType.versioning; } } for (let diffType of diff.type) { if (!dest.type.find(t => t.code === diffType.code)) { dest.type.push(JSON.parse(JSON.stringify(diffType))); } } } else if (diff.type) { dest.type = diff.type; } if (diff.constraint && dest.constraint) { for (let dc of dest.constraint) { const diffConstraint = diff.constraint.find(c => c.key === dc.key); if (diffConstraint) { if (diffConstraint.hasOwnProperty('requirements')) dc.requirements = diffConstraint.requirements; if (diffConstraint.hasOwnProperty('severity')) dc.severity = diffConstraint.severity; if (diffConstraint.hasOwnProperty('human')) dc.human = diffConstraint.human; if (diffConstraint.hasOwnProperty('expression')) dc.expression = diffConstraint.expression; if (diffConstraint.hasOwnProperty('xpath')) dc.xpath = diffConstraint.xpath; if (diffConstraint.hasOwnProperty('source')) dc.source = diffConstraint.source; } } for (let diffConstraint of diff.constraint) { if (!dest.constraint.find(c => c.key === diffConstraint.key)) { dest.constraint.push(JSON.parse(JSON.stringify(diffConstraint))); } } } else if (diff.constraint) { dest.constraint = diff.constraint; } const diffKeys = Object.keys(diff); const destKeys = Object.keys(dest); const diffDefaultValueKey = diffKeys.find(k => k.startsWith('defaultValue')); const diffMinValueKey = diffKeys.find(k => k.startsWith('minValue')); const diffMaxValueKey = diffKeys.find(k => k.startsWith('maxValue')); const diffFixedKey = diffKeys.find(k => k.startsWith('fixed')); const diffPatternKey = diffKeys.find(k => k.startsWith('pattern')); const destDefaultValueKey = destKeys.find(k => k.startsWith('defaultValue')); const destMinValueKey = destKeys.find(k => k.startsWith('minValue')); const destMaxValueKey = destKeys.find(k => k.startsWith('maxValue')); const destFixedKey = destKeys.find(k => k.startsWith('fixed')); const destPatternKey = destKeys.find(k => k.startsWith('pattern')); if (diffDefaultValueKey) { if (destDefaultValueKey) delete dest[destDefaultValueKey]; dest[diffDefaultValueKey] = diff[diffDefaultValueKey]; } if (diffMinValueKey) { if (destMinValueKey) delete dest[destMinValueKey]; dest[diffMinValueKey] = diff[diffMinValueKey]; } if (diffMaxValueKey) { if (destMaxValueKey) delete dest[destMaxValueKey]; dest[diffMaxValueKey] = diff[diffMaxValueKey]; } if (diffFixedKey) { if (destFixedKey) delete dest[destFixedKey]; dest[diffFixedKey] = diff[diffFixedKey]; } if (diffPatternKey) { if (destPatternKey) delete dest[destPatternKey]; dest[diffPatternKey] = diff[diffPatternKey]; } return dest; } /** * Generates a snapshot for the specified structure definition. If the structure definition is based on another custom profile, that * custom profile is found in the bundle passed to the constructor, and the snapshot is generated for the base profile, as well (recursively). * @param structureDefinition The profile to create a snapshot for */ private process(structureDefinition: StructureDefinition) { if (this.parser.isBaseProfile(structureDefinition.url) || this.processedUrls.indexOf(structureDefinition.url) >= 0) { return; } if (!structureDefinition.differential || !structureDefinition.differential.element || structureDefinition.differential.element.length === 0) { throw new Error(`Structure ${structureDefinition.url} does not have a differential.`); } const base = this.getStructureDefinition(structureDefinition.baseDefinition, structureDefinition.type); const newElements: ElementDefinition[] = JSON.parse(JSON.stringify(base.snapshot.element)); const matched = newElements.filter(newElement => { if (newElement.path === structureDefinition.type) { return false; } const choiceName = newElement.path.match(/^(.*\.)?(.+)\[x\]/); const matching = structureDefinition.differential.element.filter((element) => { const regexString = newElement.path .replace(/\[x\]/g, this.choiceRegexString) .replace(/\./g, '\\.'); const regex = new RegExp(regexString, 'gm'); const isMatch = regex.test(element.path); return isMatch; }); return matching.length > 0; }); matched.forEach((snapshotElement) => { const snapshotIndex = newElements.indexOf(snapshotElement); const differentialElements = structureDefinition.differential.element.filter(element => { const regexString = snapshotElement.path .replace(/\[x\]/g, this.choiceRegexString) .replace(/\./g, '\\.') + '(\\..*)?'; const regex = new RegExp(regexString, 'gm'); return regex.test(element.path); }); const removeElements = newElements.filter((next) => next === snapshotElement || next.path.indexOf(snapshotElement.path + '.') === 0); removeElements.forEach(removeElement => { const index = newElements.indexOf(removeElement); newElements.splice(index, 1); }); for (let i = differentialElements.length - 1; i >= 0; i--) { const found = (base.snapshot && base.snapshot.element ? base.snapshot.element : []) .find(e => e.path === differentialElements[i].path); const diff = found ? this.merge(differentialElements[i], found) : differentialElements[i]; newElements.splice(snapshotIndex, 0, diff); } }); structureDefinition.snapshot = { element: newElements }; // Record this profile as having been processed so that we don't re-process it later this.processedUrls.push(structureDefinition.url); } /** * Generates a snapshot for all structure definitions in the bundle. If a structure definition in the bundle is a base FHIR structure definition, it is * assumed the structure definition already has a snapshot, and it is ignored. */ generate() { this.processedUrls = []; if (this.bundle && this.bundle.entry) { this.bundle.entry.forEach((entry) => { if (!entry.resource || entry.resource.resourceType !== 'StructureDefinition') { return; } this.process(entry.resource); }); } } }
the_stack
import { captureStackTrace, IResolvable, IResolveContext, Token, Tokenization } from '@aws-cdk/core'; import { IntrinsicParser, IntrinsicExpression } from './intrinstics'; const JSON_PATH_TOKEN_SYMBOL = Symbol.for('@aws-cdk/aws-stepfunctions.JsonPathToken'); export class JsonPathToken implements IResolvable { public static isJsonPathToken(x: IResolvable): x is JsonPathToken { return (x as any)[JSON_PATH_TOKEN_SYMBOL] === true; } public readonly creationStack: string[]; public displayHint: string; constructor(public readonly path: string) { this.creationStack = captureStackTrace(); this.displayHint = path.replace(/^[^a-zA-Z]+/, ''); Object.defineProperty(this, JSON_PATH_TOKEN_SYMBOL, { value: true }); } public resolve(_ctx: IResolveContext): any { return this.path; } public toString() { return Token.asString(this, { displayHint: this.displayHint }); } public toJSON() { return `<path:${this.path}>`; } } /** * Deep render a JSON object to expand JSON path fields, updating the key to end in '.$' */ export function renderObject(obj: object | undefined): object | undefined { return recurseObject(obj, { handleString: renderString, handleList: renderStringList, handleNumber: renderNumber, handleBoolean: renderBoolean, handleResolvable: renderResolvable, }); } /** * Return all JSON paths that are used in the given structure */ export function findReferencedPaths(obj: object | undefined): Set<string> { const found = new Set<string>(); recurseObject(obj, { handleString(_key: string, x: string) { for (const p of findPathsInIntrinsicFunctions(jsonPathString(x))) { found.add(p); } return {}; }, handleList(_key: string, x: string[]) { for (const p of findPathsInIntrinsicFunctions(jsonPathStringList(x))) { found.add(p); } return {}; }, handleNumber(_key: string, x: number) { for (const p of findPathsInIntrinsicFunctions(jsonPathNumber(x))) { found.add(p); } return {}; }, handleBoolean(_key: string, _x: boolean) { return {}; }, handleResolvable(_key: string, x: IResolvable) { for (const p of findPathsInIntrinsicFunctions(jsonPathFromAny(x))) { found.add(p); } return {}; }, }); return found; } /** * From an expression, return the list of JSON paths referenced in it */ function findPathsInIntrinsicFunctions(expression?: string): string[] { if (!expression) { return []; } const ret = new Array<string>(); try { const parsed = new IntrinsicParser(expression).parseTopLevelIntrinsic(); recurse(parsed); return ret; } catch (e) { // Not sure that our parsing is 100% correct. We don't want to break anyone, so // fall back to legacy behavior if we can't parse this string. return [expression]; } function recurse(p: IntrinsicExpression) { switch (p.type) { case 'path': ret.push(p.path); break; case 'fncall': for (const arg of p.arguments) { recurse(arg); } } } } interface FieldHandlers { handleString(key: string, x: string): {[key: string]: string}; handleList(key: string, x: string[]): {[key: string]: string[] | string }; handleNumber(key: string, x: number): {[key: string]: number | string}; handleBoolean(key: string, x: boolean): {[key: string]: boolean}; handleResolvable(key: string, x: IResolvable): {[key: string]: any}; } export function recurseObject(obj: object | undefined, handlers: FieldHandlers, visited: object[] = []): object | undefined { // If the argument received is not actually an object (string, number, boolean, undefined, ...) or null // just return it as is as there's nothing to be rendered. This should only happen in the original call to // recurseObject as any recursive calls to it are checking for typeof value === 'object' && value !== null if (typeof obj !== 'object' || obj === null) { return obj; } // Avoiding infinite recursion if (visited.includes(obj)) { return {}; } // Marking current object as visited for the current recursion path visited.push(obj); const ret: any = {}; for (const [key, value] of Object.entries(obj)) { if (typeof value === 'string') { Object.assign(ret, handlers.handleString(key, value)); } else if (typeof value === 'number') { Object.assign(ret, handlers.handleNumber(key, value)); } else if (Array.isArray(value)) { Object.assign(ret, recurseArray(key, value, handlers, visited)); } else if (typeof value === 'boolean') { Object.assign(ret, handlers.handleBoolean(key, value)); } else if (value === null || value === undefined) { // Nothing } else if (typeof value === 'object') { if (Tokenization.isResolvable(value)) { Object.assign(ret, handlers.handleResolvable(key, value)); } else { ret[key] = recurseObject(value, handlers, visited); } } } // Removing from visited after leaving the current recursion path // Allowing it to be visited again if it's not causing a recursion (circular reference) visited.pop(); return ret; } /** * Render an array that may or may not contain a string list token */ function recurseArray(key: string, arr: any[], handlers: FieldHandlers, visited: object[] = []): {[key: string]: any[] | string} { if (isStringArray(arr)) { const path = jsonPathStringList(arr); if (path !== undefined) { return handlers.handleList(key, arr); } // Fall through to correctly reject encoded strings inside an array. // They cannot be represented because there is no key to append a '.$' to. } return { [key]: arr.map(value => { if ((typeof value === 'string' && jsonPathString(value) !== undefined) || (typeof value === 'number' && jsonPathNumber(value) !== undefined) || (isStringArray(value) && jsonPathStringList(value) !== undefined)) { throw new Error('Cannot use JsonPath fields in an array, they must be used in objects'); } if (typeof value === 'object' && value !== null) { return recurseObject(value, handlers, visited); } return value; }), }; } function isStringArray(x: any): x is string[] { return Array.isArray(x) && x.every(el => typeof el === 'string'); } /** * Render a parameter string * * If the string value starts with '$.', render it as a path string, otherwise as a direct string. */ function renderString(key: string, value: string): {[key: string]: string} { const path = jsonPathString(value); if (path !== undefined) { return { [key + '.$']: path }; } else { return { [key]: value }; } } /** * Render a resolvable * * If we can extract a Path from it, render as a path string, otherwise as itself (will * be resolved later */ function renderResolvable(key: string, value: IResolvable): {[key: string]: any} { const path = jsonPathFromAny(value); if (path !== undefined) { return { [key + '.$']: path }; } else { return { [key]: value }; } } /** * Render a parameter string list * * If the string value starts with '$.', render it as a path string, otherwise as a direct string. */ function renderStringList(key: string, value: string[]): {[key: string]: string[] | string} { const path = jsonPathStringList(value); if (path !== undefined) { return { [key + '.$']: path }; } else { return { [key]: value }; } } /** * Render a parameter number * * If the string value starts with '$.', render it as a path string, otherwise as a direct string. */ function renderNumber(key: string, value: number): {[key: string]: number | string} { const path = jsonPathNumber(value); if (path !== undefined) { return { [key + '.$']: path }; } else { return { [key]: value }; } } /** * Render a parameter boolean */ function renderBoolean(key: string, value: boolean): {[key: string]: boolean} { return { [key]: value }; } /** * If the indicated string is an encoded JSON path, return the path * * Otherwise return undefined. */ export function jsonPathString(x: string): string | undefined { const fragments = Tokenization.reverseString(x); const jsonPathTokens = fragments.tokens.filter(JsonPathToken.isJsonPathToken); if (jsonPathTokens.length > 0 && fragments.length > 1) { throw new Error(`Field references must be the entire string, cannot concatenate them (found '${x}')`); } if (jsonPathTokens.length > 0) { return jsonPathTokens[0].path; } return undefined; } export function jsonPathFromAny(x: any) { if (!x) { return undefined; } if (typeof x === 'string') { return jsonPathString(x); } return pathFromToken(Tokenization.reverse(x)); } /** * If the indicated string list is an encoded JSON path, return the path * * Otherwise return undefined. */ function jsonPathStringList(x: string[]): string | undefined { return pathFromToken(Tokenization.reverseList(x)); } /** * If the indicated number is an encoded JSON path, return the path * * Otherwise return undefined. */ function jsonPathNumber(x: number): string | undefined { return pathFromToken(Tokenization.reverseNumber(x)); } function pathFromToken(token: IResolvable | undefined) { return token && (JsonPathToken.isJsonPathToken(token) ? token.path : undefined); } /** * Render the string in a valid JSON Path expression. * * If the string is a Tokenized JSON path reference -- return the JSON path reference inside it. * Otherwise, single-quote it. * * Call this function whenever you're building compound JSONPath expressions, in * order to avoid having tokens-in-tokens-in-tokens which become very hard to parse. */ export function renderInExpression(x: string) { const path = jsonPathString(x); return path ?? singleQuotestring(x); } function singleQuotestring(x: string) { const ret = new Array<string>(); ret.push("'"); for (const c of x) { if (c === "'") { ret.push("\\'"); } else if (c === '\\') { ret.push('\\\\'); } else if (c === '\n') { ret.push('\\n'); } else { ret.push(c); } } ret.push("'"); return ret.join(''); }
the_stack
import * as coreHttp from "@azure/core-http"; /** * A model definition and metadata for that model. */ export interface DigitalTwinsModelData { /** * A language map that contains the localized display names as specified in the model definition. */ displayName?: { [propertyName: string]: string }; /** * A language map that contains the localized descriptions as specified in the model definition. */ description?: { [propertyName: string]: string }; /** * The id of the model as specified in the model definition. */ id: string; /** * The time the model was uploaded to the service. */ uploadTime?: Date; /** * Indicates if the model is decommissioned. Decommissioned models cannot be referenced by newly created digital twins. */ decommissioned?: boolean; /** * The model definition. */ model?: any; } /** * Error response. */ export interface ErrorResponse { /** * The error details. */ error?: ErrorModel; } /** * Error definition. */ export interface ErrorModel { /** * Service specific error code which serves as the substatus for the HTTP error code. */ readonly code?: string; /** * A human-readable representation of the error. */ readonly message?: string; /** * Internal error details. */ readonly details?: ErrorModel[]; /** * An object containing more specific information than the current object about the error. */ innererror?: InnerError; } /** * A more specific error description than was provided by the containing error. */ export interface InnerError { /** * A more specific error code than was provided by the containing error. */ code?: string; /** * An object containing more specific information than the current object about the error. */ innererror?: InnerError; } /** * A collection of DigitalTwinsModelData objects. */ export interface PagedDigitalTwinsModelDataCollection { /** * The DigitalTwinsModelData objects. */ value?: DigitalTwinsModelData[]; /** * A URI to retrieve the next page of objects. */ nextLink?: string; } /** * A query specification containing either a query statement or a continuation token from a previous query result. */ export interface QuerySpecification { /** * The query to execute. This value is ignored if a continuation token is provided. */ query?: string; /** * A token which is used to retrieve the next set of results from a previous query. */ continuationToken?: string; } /** * The results of a query operation and an optional continuation token. */ export interface QueryResult { /** * The query results. */ value?: any[]; /** * A token which can be used to construct a new QuerySpecification to retrieve the next set of results. */ continuationToken?: string; } /** * A collection of relationships which relate digital twins together. */ export interface RelationshipCollection { /** * The relationship objects. */ value?: any[]; /** * A URI to retrieve the next page of objects. */ nextLink?: string; } /** * A collection of incoming relationships which relate digital twins together. */ export interface IncomingRelationshipCollection { value?: IncomingRelationship[]; /** * A URI to retrieve the next page of objects. */ nextLink?: string; } /** * An incoming relationship. */ export interface IncomingRelationship { /** * A user-provided string representing the id of this relationship, unique in the context of the source digital twin, i.e. sourceId + relationshipId is unique in the context of the service. */ relationshipId?: string; /** * The id of the source digital twin. */ sourceId?: string; /** * The name of the relationship. */ relationshipName?: string; /** * Link to the relationship, to be used for deletion. */ relationshipLink?: string; } /** * A collection of EventRoute objects. */ export interface EventRouteCollection { /** * The EventRoute objects. */ value?: EventRoute[]; /** * A URI to retrieve the next page of results. */ nextLink?: string; } /** * A route which directs notification and telemetry events to an endpoint. Endpoints are a destination outside of Azure Digital Twins such as an EventHub. */ export interface EventRoute { /** * The id of the event route. */ readonly id?: string; /** * The name of the endpoint this event route is bound to. */ endpointName: string; /** * An expression which describes the events which are routed to the endpoint. */ filter: string; } /** * Defines headers for Query_queryTwins operation. */ export interface QueryQueryTwinsHeaders { /** * The query charge. */ queryCharge?: number; } /** * Defines headers for DigitalTwins_getById operation. */ export interface DigitalTwinsGetByIdHeaders { /** * Weak Etag. */ etag?: string; } /** * Defines headers for DigitalTwins_add operation. */ export interface DigitalTwinsAddHeaders { /** * Weak Etag. */ etag?: string; } /** * Defines headers for DigitalTwins_update operation. */ export interface DigitalTwinsUpdateHeaders { /** * Weak Etag. */ etag?: string; } /** * Defines headers for DigitalTwins_getRelationshipById operation. */ export interface DigitalTwinsGetRelationshipByIdHeaders { /** * Weak Etag. */ etag?: string; } /** * Defines headers for DigitalTwins_addRelationship operation. */ export interface DigitalTwinsAddRelationshipHeaders { /** * Weak Etag. */ etag?: string; } /** * Defines headers for DigitalTwins_updateRelationship operation. */ export interface DigitalTwinsUpdateRelationshipHeaders { /** * Weak Etag. */ etag?: string; } /** * Defines headers for DigitalTwins_getComponent operation. */ export interface DigitalTwinsGetComponentHeaders { /** * Weak Etag. */ etag?: string; } /** * Defines headers for DigitalTwins_updateComponent operation. */ export interface DigitalTwinsUpdateComponentHeaders { /** * Weak Etag. */ etag?: string; } /** * Optional parameters. */ export interface DigitalTwinModelsAddOptionalParams extends coreHttp.OperationOptions { /** * An array of models to add. */ models?: any[]; /** * Identifies the request in a distributed tracing system. */ traceparent?: string; /** * Provides vendor-specific trace identification information and is a companion to traceparent. */ tracestate?: string; } /** * Contains response data for the add operation. */ export type DigitalTwinModelsAddResponse = DigitalTwinsModelData[] & { /** * The underlying HTTP response. */ _response: coreHttp.HttpResponse & { /** * The response body as text (string format) */ bodyAsText: string; /** * The response body as parsed JSON or XML */ parsedBody: DigitalTwinsModelData[]; }; }; /** * Optional parameters. */ export interface DigitalTwinModelsListOptionalParams extends coreHttp.OperationOptions { /** * Identifies the request in a distributed tracing system. */ traceparent?: string; /** * Provides vendor-specific trace identification information and is a companion to traceparent. */ tracestate?: string; /** * The set of the models which will have their dependencies retrieved. If omitted, all models are retrieved. */ dependenciesFor?: string[]; /** * When true the model definition will be returned as part of the result. */ includeModelDefinition?: boolean; /** * The maximum number of items to retrieve per request. The server may choose to return less than the requested number. */ maxItemsPerPage?: number; } /** * Contains response data for the list operation. */ export type DigitalTwinModelsListResponse = PagedDigitalTwinsModelDataCollection & { /** * The underlying HTTP response. */ _response: coreHttp.HttpResponse & { /** * The response body as text (string format) */ bodyAsText: string; /** * The response body as parsed JSON or XML */ parsedBody: PagedDigitalTwinsModelDataCollection; }; }; /** * Optional parameters. */ export interface DigitalTwinModelsGetByIdOptionalParams extends coreHttp.OperationOptions { /** * Identifies the request in a distributed tracing system. */ traceparent?: string; /** * Provides vendor-specific trace identification information and is a companion to traceparent. */ tracestate?: string; /** * When true the model definition will be returned as part of the result. */ includeModelDefinition?: boolean; } /** * Contains response data for the getById operation. */ export type DigitalTwinModelsGetByIdResponse = DigitalTwinsModelData & { /** * The underlying HTTP response. */ _response: coreHttp.HttpResponse & { /** * The response body as text (string format) */ bodyAsText: string; /** * The response body as parsed JSON or XML */ parsedBody: DigitalTwinsModelData; }; }; /** * Optional parameters. */ export interface DigitalTwinModelsUpdateOptionalParams extends coreHttp.OperationOptions { /** * Identifies the request in a distributed tracing system. */ traceparent?: string; /** * Provides vendor-specific trace identification information and is a companion to traceparent. */ tracestate?: string; } /** * Optional parameters. */ export interface DigitalTwinModelsDeleteOptionalParams extends coreHttp.OperationOptions { /** * Identifies the request in a distributed tracing system. */ traceparent?: string; /** * Provides vendor-specific trace identification information and is a companion to traceparent. */ tracestate?: string; } /** * Optional parameters. */ export interface DigitalTwinModelsListNextOptionalParams extends coreHttp.OperationOptions { /** * Identifies the request in a distributed tracing system. */ traceparent?: string; /** * Provides vendor-specific trace identification information and is a companion to traceparent. */ tracestate?: string; /** * The set of the models which will have their dependencies retrieved. If omitted, all models are retrieved. */ dependenciesFor?: string[]; /** * When true the model definition will be returned as part of the result. */ includeModelDefinition?: boolean; /** * The maximum number of items to retrieve per request. The server may choose to return less than the requested number. */ maxItemsPerPage?: number; } /** * Contains response data for the listNext operation. */ export type DigitalTwinModelsListNextResponse = PagedDigitalTwinsModelDataCollection & { /** * The underlying HTTP response. */ _response: coreHttp.HttpResponse & { /** * The response body as text (string format) */ bodyAsText: string; /** * The response body as parsed JSON or XML */ parsedBody: PagedDigitalTwinsModelDataCollection; }; }; /** * Optional parameters. */ export interface QueryQueryTwinsOptionalParams extends coreHttp.OperationOptions { /** * Identifies the request in a distributed tracing system. */ traceparent?: string; /** * Provides vendor-specific trace identification information and is a companion to traceparent. */ tracestate?: string; /** * The maximum number of items to retrieve per request. The server may choose to return less than the requested number. */ maxItemsPerPage?: number; } /** * Contains response data for the queryTwins operation. */ export type QueryQueryTwinsResponse = QueryQueryTwinsHeaders & QueryResult & { /** * The underlying HTTP response. */ _response: coreHttp.HttpResponse & { /** * The response body as text (string format) */ bodyAsText: string; /** * The response body as parsed JSON or XML */ parsedBody: QueryResult; /** * The parsed HTTP response headers. */ parsedHeaders: QueryQueryTwinsHeaders; }; }; /** * Optional parameters. */ export interface DigitalTwinsGetByIdOptionalParams extends coreHttp.OperationOptions { /** * Identifies the request in a distributed tracing system. */ traceparent?: string; /** * Provides vendor-specific trace identification information and is a companion to traceparent. */ tracestate?: string; } /** * Contains response data for the getById operation. */ export type DigitalTwinsGetByIdResponse = DigitalTwinsGetByIdHeaders & { /** * The parsed response body. */ body: any; /** * The underlying HTTP response. */ _response: coreHttp.HttpResponse & { /** * The response body as text (string format) */ bodyAsText: string; /** * The response body as parsed JSON or XML */ parsedBody: any; /** * The parsed HTTP response headers. */ parsedHeaders: DigitalTwinsGetByIdHeaders; }; }; /** * Optional parameters. */ export interface DigitalTwinsAddOptionalParams extends coreHttp.OperationOptions { /** * Identifies the request in a distributed tracing system. */ traceparent?: string; /** * Provides vendor-specific trace identification information and is a companion to traceparent. */ tracestate?: string; /** * Only perform the operation if the entity does not already exist. */ ifNoneMatch?: string; } /** * Contains response data for the add operation. */ export type DigitalTwinsAddResponse = DigitalTwinsAddHeaders & { /** * The parsed response body. */ body: any; /** * The underlying HTTP response. */ _response: coreHttp.HttpResponse & { /** * The response body as text (string format) */ bodyAsText: string; /** * The response body as parsed JSON or XML */ parsedBody: any; /** * The parsed HTTP response headers. */ parsedHeaders: DigitalTwinsAddHeaders; }; }; /** * Optional parameters. */ export interface DigitalTwinsDeleteOptionalParams extends coreHttp.OperationOptions { /** * Identifies the request in a distributed tracing system. */ traceparent?: string; /** * Provides vendor-specific trace identification information and is a companion to traceparent. */ tracestate?: string; /** * Only perform the operation if the entity's etag matches one of the etags provided or * is provided. */ ifMatch?: string; } /** * Optional parameters. */ export interface DigitalTwinsUpdateOptionalParams extends coreHttp.OperationOptions { /** * Identifies the request in a distributed tracing system. */ traceparent?: string; /** * Provides vendor-specific trace identification information and is a companion to traceparent. */ tracestate?: string; /** * Only perform the operation if the entity's etag matches one of the etags provided or * is provided. */ ifMatch?: string; } /** * Contains response data for the update operation. */ export type DigitalTwinsUpdateResponse = DigitalTwinsUpdateHeaders & { /** * The underlying HTTP response. */ _response: coreHttp.HttpResponse & { /** * The parsed HTTP response headers. */ parsedHeaders: DigitalTwinsUpdateHeaders; }; }; /** * Optional parameters. */ export interface DigitalTwinsGetRelationshipByIdOptionalParams extends coreHttp.OperationOptions { /** * Identifies the request in a distributed tracing system. */ traceparent?: string; /** * Provides vendor-specific trace identification information and is a companion to traceparent. */ tracestate?: string; } /** * Contains response data for the getRelationshipById operation. */ export type DigitalTwinsGetRelationshipByIdResponse = DigitalTwinsGetRelationshipByIdHeaders & { /** * The parsed response body. */ body: any; /** * The underlying HTTP response. */ _response: coreHttp.HttpResponse & { /** * The response body as text (string format) */ bodyAsText: string; /** * The response body as parsed JSON or XML */ parsedBody: any; /** * The parsed HTTP response headers. */ parsedHeaders: DigitalTwinsGetRelationshipByIdHeaders; }; }; /** * Optional parameters. */ export interface DigitalTwinsAddRelationshipOptionalParams extends coreHttp.OperationOptions { /** * Identifies the request in a distributed tracing system. */ traceparent?: string; /** * Provides vendor-specific trace identification information and is a companion to traceparent. */ tracestate?: string; /** * Only perform the operation if the entity does not already exist. */ ifNoneMatch?: string; } /** * Contains response data for the addRelationship operation. */ export type DigitalTwinsAddRelationshipResponse = DigitalTwinsAddRelationshipHeaders & { /** * The parsed response body. */ body: any; /** * The underlying HTTP response. */ _response: coreHttp.HttpResponse & { /** * The response body as text (string format) */ bodyAsText: string; /** * The response body as parsed JSON or XML */ parsedBody: any; /** * The parsed HTTP response headers. */ parsedHeaders: DigitalTwinsAddRelationshipHeaders; }; }; /** * Optional parameters. */ export interface DigitalTwinsDeleteRelationshipOptionalParams extends coreHttp.OperationOptions { /** * Identifies the request in a distributed tracing system. */ traceparent?: string; /** * Provides vendor-specific trace identification information and is a companion to traceparent. */ tracestate?: string; /** * Only perform the operation if the entity's etag matches one of the etags provided or * is provided. */ ifMatch?: string; } /** * Optional parameters. */ export interface DigitalTwinsUpdateRelationshipOptionalParams extends coreHttp.OperationOptions { /** * Identifies the request in a distributed tracing system. */ traceparent?: string; /** * Provides vendor-specific trace identification information and is a companion to traceparent. */ tracestate?: string; /** * Only perform the operation if the entity's etag matches one of the etags provided or * is provided. */ ifMatch?: string; } /** * Contains response data for the updateRelationship operation. */ export type DigitalTwinsUpdateRelationshipResponse = DigitalTwinsUpdateRelationshipHeaders & { /** * The underlying HTTP response. */ _response: coreHttp.HttpResponse & { /** * The parsed HTTP response headers. */ parsedHeaders: DigitalTwinsUpdateRelationshipHeaders; }; }; /** * Optional parameters. */ export interface DigitalTwinsListRelationshipsOptionalParams extends coreHttp.OperationOptions { /** * Identifies the request in a distributed tracing system. */ traceparent?: string; /** * Provides vendor-specific trace identification information and is a companion to traceparent. */ tracestate?: string; /** * The name of the relationship. */ relationshipName?: string; } /** * Contains response data for the listRelationships operation. */ export type DigitalTwinsListRelationshipsResponse = RelationshipCollection & { /** * The underlying HTTP response. */ _response: coreHttp.HttpResponse & { /** * The response body as text (string format) */ bodyAsText: string; /** * The response body as parsed JSON or XML */ parsedBody: RelationshipCollection; }; }; /** * Optional parameters. */ export interface DigitalTwinsListIncomingRelationshipsOptionalParams extends coreHttp.OperationOptions { /** * Identifies the request in a distributed tracing system. */ traceparent?: string; /** * Provides vendor-specific trace identification information and is a companion to traceparent. */ tracestate?: string; } /** * Contains response data for the listIncomingRelationships operation. */ export type DigitalTwinsListIncomingRelationshipsResponse = IncomingRelationshipCollection & { /** * The underlying HTTP response. */ _response: coreHttp.HttpResponse & { /** * The response body as text (string format) */ bodyAsText: string; /** * The response body as parsed JSON or XML */ parsedBody: IncomingRelationshipCollection; }; }; /** * Optional parameters. */ export interface DigitalTwinsSendTelemetryOptionalParams extends coreHttp.OperationOptions { /** * Identifies the request in a distributed tracing system. */ traceparent?: string; /** * Provides vendor-specific trace identification information and is a companion to traceparent. */ tracestate?: string; /** * An RFC 3339 timestamp that identifies the time the telemetry was measured. */ telemetrySourceTime?: string; } /** * Optional parameters. */ export interface DigitalTwinsSendComponentTelemetryOptionalParams extends coreHttp.OperationOptions { /** * Identifies the request in a distributed tracing system. */ traceparent?: string; /** * Provides vendor-specific trace identification information and is a companion to traceparent. */ tracestate?: string; /** * An RFC 3339 timestamp that identifies the time the telemetry was measured. */ telemetrySourceTime?: string; } /** * Optional parameters. */ export interface DigitalTwinsGetComponentOptionalParams extends coreHttp.OperationOptions { /** * Identifies the request in a distributed tracing system. */ traceparent?: string; /** * Provides vendor-specific trace identification information and is a companion to traceparent. */ tracestate?: string; } /** * Contains response data for the getComponent operation. */ export type DigitalTwinsGetComponentResponse = DigitalTwinsGetComponentHeaders & { /** * The parsed response body. */ body: any; /** * The underlying HTTP response. */ _response: coreHttp.HttpResponse & { /** * The response body as text (string format) */ bodyAsText: string; /** * The response body as parsed JSON or XML */ parsedBody: any; /** * The parsed HTTP response headers. */ parsedHeaders: DigitalTwinsGetComponentHeaders; }; }; /** * Optional parameters. */ export interface DigitalTwinsUpdateComponentOptionalParams extends coreHttp.OperationOptions { /** * Identifies the request in a distributed tracing system. */ traceparent?: string; /** * Provides vendor-specific trace identification information and is a companion to traceparent. */ tracestate?: string; /** * Only perform the operation if the entity's etag matches one of the etags provided or * is provided. */ ifMatch?: string; } /** * Contains response data for the updateComponent operation. */ export type DigitalTwinsUpdateComponentResponse = DigitalTwinsUpdateComponentHeaders & { /** * The underlying HTTP response. */ _response: coreHttp.HttpResponse & { /** * The parsed HTTP response headers. */ parsedHeaders: DigitalTwinsUpdateComponentHeaders; }; }; /** * Optional parameters. */ export interface DigitalTwinsListRelationshipsNextOptionalParams extends coreHttp.OperationOptions { /** * Identifies the request in a distributed tracing system. */ traceparent?: string; /** * Provides vendor-specific trace identification information and is a companion to traceparent. */ tracestate?: string; /** * The name of the relationship. */ relationshipName?: string; } /** * Contains response data for the listRelationshipsNext operation. */ export type DigitalTwinsListRelationshipsNextResponse = RelationshipCollection & { /** * The underlying HTTP response. */ _response: coreHttp.HttpResponse & { /** * The response body as text (string format) */ bodyAsText: string; /** * The response body as parsed JSON or XML */ parsedBody: RelationshipCollection; }; }; /** * Optional parameters. */ export interface DigitalTwinsListIncomingRelationshipsNextOptionalParams extends coreHttp.OperationOptions { /** * Identifies the request in a distributed tracing system. */ traceparent?: string; /** * Provides vendor-specific trace identification information and is a companion to traceparent. */ tracestate?: string; } /** * Contains response data for the listIncomingRelationshipsNext operation. */ export type DigitalTwinsListIncomingRelationshipsNextResponse = IncomingRelationshipCollection & { /** * The underlying HTTP response. */ _response: coreHttp.HttpResponse & { /** * The response body as text (string format) */ bodyAsText: string; /** * The response body as parsed JSON or XML */ parsedBody: IncomingRelationshipCollection; }; }; /** * Optional parameters. */ export interface EventRoutesListOptionalParams extends coreHttp.OperationOptions { /** * Identifies the request in a distributed tracing system. */ traceparent?: string; /** * Provides vendor-specific trace identification information and is a companion to traceparent. */ tracestate?: string; /** * The maximum number of items to retrieve per request. The server may choose to return less than the requested number. */ maxItemsPerPage?: number; } /** * Contains response data for the list operation. */ export type EventRoutesListResponse = EventRouteCollection & { /** * The underlying HTTP response. */ _response: coreHttp.HttpResponse & { /** * The response body as text (string format) */ bodyAsText: string; /** * The response body as parsed JSON or XML */ parsedBody: EventRouteCollection; }; }; /** * Optional parameters. */ export interface EventRoutesGetByIdOptionalParams extends coreHttp.OperationOptions { /** * Identifies the request in a distributed tracing system. */ traceparent?: string; /** * Provides vendor-specific trace identification information and is a companion to traceparent. */ tracestate?: string; } /** * Contains response data for the getById operation. */ export type EventRoutesGetByIdResponse = EventRoute & { /** * The underlying HTTP response. */ _response: coreHttp.HttpResponse & { /** * The response body as text (string format) */ bodyAsText: string; /** * The response body as parsed JSON or XML */ parsedBody: EventRoute; }; }; /** * Optional parameters. */ export interface EventRoutesAddOptionalParams extends coreHttp.OperationOptions { /** * Identifies the request in a distributed tracing system. */ traceparent?: string; /** * Provides vendor-specific trace identification information and is a companion to traceparent. */ tracestate?: string; /** * The event route data */ eventRoute?: EventRoute; } /** * Optional parameters. */ export interface EventRoutesDeleteOptionalParams extends coreHttp.OperationOptions { /** * Identifies the request in a distributed tracing system. */ traceparent?: string; /** * Provides vendor-specific trace identification information and is a companion to traceparent. */ tracestate?: string; } /** * Optional parameters. */ export interface EventRoutesListNextOptionalParams extends coreHttp.OperationOptions { /** * Identifies the request in a distributed tracing system. */ traceparent?: string; /** * Provides vendor-specific trace identification information and is a companion to traceparent. */ tracestate?: string; /** * The maximum number of items to retrieve per request. The server may choose to return less than the requested number. */ maxItemsPerPage?: number; } /** * Contains response data for the listNext operation. */ export type EventRoutesListNextResponse = EventRouteCollection & { /** * The underlying HTTP response. */ _response: coreHttp.HttpResponse & { /** * The response body as text (string format) */ bodyAsText: string; /** * The response body as parsed JSON or XML */ parsedBody: EventRouteCollection; }; }; /** * Optional parameters. */ export interface AzureDigitalTwinsAPIOptionalParams extends coreHttp.ServiceClientOptions { /** * server parameter */ $host?: string; /** * Api Version */ apiVersion?: string; /** * Overrides client endpoint. */ endpoint?: string; }
the_stack
import { UpgradeSpendTier } from '@destinyitemmanager/dim-api-types'; import { D2ManifestDefinitions } from 'app/destiny2/d2-definitions'; import { DimItem, PluggableInventoryItemDefinition } from 'app/inventory/item-types'; import { isPluggableItem } from 'app/inventory/store/sockets'; import { generateModPermutations } from 'app/loadout/mod-permutations'; import { armor2PlugCategoryHashesByName, armorBuckets } from 'app/search/d2-known-values'; import { combatCompatiblePlugCategoryHashes, ModSocketMetadata, } from 'app/search/specialty-modslots'; import { chainComparator, compareBy } from 'app/utils/comparators'; import { getModTypeTagByPlugCategoryHash, getSpecialtySocketMetadatas, isArmor2Mod, } from 'app/utils/item-utils'; import { DestinyEnergyType, DestinyInventoryItemDefinition } from 'bungie-api-ts/destiny2'; import { PlugCategoryHashes } from 'data/d2/generated-enums'; import raidModPlugCategoryHashes from 'data/d2/raid-mod-plug-category-hashes.json'; import _ from 'lodash'; import { canSwapEnergyFromUpgradeSpendTier, upgradeSpendTierToMaxEnergy, } from './armor-upgrade-utils'; import { knownModPlugCategoryHashes } from './known-values'; /** The plug category hashes that belong to the 5th mod slot, such as raid and nightmare mods. */ export const activityModPlugCategoryHashes = [ ...raidModPlugCategoryHashes, PlugCategoryHashes.EnhancementsSeasonMaverick, ]; export const bucketsToCategories = { [armorBuckets.helmet]: armor2PlugCategoryHashesByName.helmet, [armorBuckets.gauntlets]: armor2PlugCategoryHashesByName.gauntlets, [armorBuckets.chest]: armor2PlugCategoryHashesByName.chest, [armorBuckets.leg]: armor2PlugCategoryHashesByName.leg, [armorBuckets.classitem]: armor2PlugCategoryHashesByName.classitem, }; /** * Sorts PluggableInventoryItemDefinition's by the following list of comparators. * 1. The known plug category hashes, see ./types#knownModPlugCategoryHashes for ordering * 2. itemTypeDisplayName, so that legacy and combat mods are ordered alphabetically by their category name * 3. energyType, so mods in each category go Any, Arc, Solar, Void * 4. by energy cost, so cheaper mods come before more expensive mods * 5. by mod name, so mods in the same category with the same energy type and cost are alphabetical */ export const sortMods = chainComparator<PluggableInventoryItemDefinition>( compareBy((mod) => { const knownIndex = knownModPlugCategoryHashes.indexOf(mod.plug.plugCategoryHash); return knownIndex === -1 ? knownModPlugCategoryHashes.length : knownIndex; }), compareBy((mod) => mod.itemTypeDisplayName), compareBy((mod) => mod.plug.energyCost?.energyType), compareBy((mod) => mod.plug.energyCost?.energyCost), compareBy((mod) => mod.displayProperties.name) ); /** Sorts an array of PluggableInventoryItemDefinition[]'s by the order of hashes in * loadout/know-values#knownModPlugCategoryHashes and then sorts those not found in there by name. * * This assumes that each PluggableInventoryItemDefinition in each PluggableInventoryItemDefinition[] * has the same plugCategoryHash as it pulls it from the first PluggableInventoryItemDefinition. */ export const sortModGroups = chainComparator( compareBy((mods: PluggableInventoryItemDefinition[]) => { // We sort by known knownModPlugCategoryHashes so that it general, helmet, ..., classitem, raid, others. const knownIndex = knownModPlugCategoryHashes.indexOf(mods[0].plug.plugCategoryHash); return knownIndex === -1 ? knownModPlugCategoryHashes.length : knownIndex; }), compareBy((mods: PluggableInventoryItemDefinition[]) => mods[0].itemTypeDisplayName) ); /** Figures out if a definition is an insertable armor 2.0 mod. To do so it does the following * 1. Figures out if the def is pluggable (def.plug exists) * 2. Checks to see if the plugCategoryHash is in one of our known plugCategoryHashes (relies on d2ai). * 3. Checks to see if plug.insertionMaterialRequirementHash is non zero or plug.energyCost a thing. This rules out deprecated mods. * 4. Makes sure that itemTypeDisplayName is a thing, this rules out classified items. */ export function isInsertableArmor2Mod( def: DestinyInventoryItemDefinition ): def is PluggableInventoryItemDefinition { return Boolean( isPluggableItem(def) && isArmor2Mod(def) && (def.plug.insertionMaterialRequirementHash !== 0 || def.plug.energyCost) && def.itemTypeDisplayName !== undefined ); } /** * Generates a unique key for a mod when rendering. As mods can appear multiple times as * siblings we need to count them and append a number to its hash to make it unique. * * Note that counts is mutated and a new object should be passed in with each render. */ export const getModRenderKey = ( mod: PluggableInventoryItemDefinition, /** A supplied object to store the counts in. This is mutated. */ counts: Record<number, number> ) => { if (!counts[mod.hash]) { counts[mod.hash] = 0; } return `${mod.hash}-${counts[mod.hash]++}`; }; /** Used to track assigned and unassigned mods during the mod assignment algorithm. */ interface ModAssignments { [itemId: string]: { assigned: PluggableInventoryItemDefinition[]; unassigned: PluggableInventoryItemDefinition[]; }; } /** * This finds the cheapest possible mod assignments for an armour set and a set of mods. It * doesn't need to assign all mods but it will find a set with as many assigned as possible. * * It uses the idea of total energy spent and wasted to rank mod assignments. * * To do this we create permutations of general, combat and activity mods and loop over each * set of permutations and validate the combination. Validate is done via a lower number of * unassigned mods or an equal amount of unassigned mods and a lower energy cost. */ export function getCheapestModAssignments( items: DimItem[], mods: PluggableInventoryItemDefinition[], defs: D2ManifestDefinitions | undefined, upgradeSpendTier: UpgradeSpendTier, lockItemEnergyType: boolean ): { itemModAssignments: Map<string, PluggableInventoryItemDefinition[]>; unassignedMods: PluggableInventoryItemDefinition[]; } { if (!defs) { return { itemModAssignments: new Map(), unassignedMods: [] }; } let bucketIndependentAssignments: ModAssignments = {}; const bucketSpecificAssignments: ModAssignments = {}; // just an arbitrarily large number let assignmentEnergyCost = 10000; let assignmentUnassignedModCount = 10000; for (const item of items) { bucketSpecificAssignments[item.id] = { assigned: [], unassigned: [] }; bucketIndependentAssignments[item.id] = { assigned: [], unassigned: [] }; } // An object of item id's to specialty socket metadata, this is used to ensure that // combat and activity mods can be slotted into an item. const itemSocketMetadata = _.mapValues( _.keyBy(items, (item) => item.id), (item) => getSpecialtySocketMetadatas(item) ); const generalMods: PluggableInventoryItemDefinition[] = []; const combatMods: PluggableInventoryItemDefinition[] = []; const activityMods: PluggableInventoryItemDefinition[] = []; // Divide up the locked mods into general, combat and activity mod arrays. Also we // take the bucket specific mods and put them in a map of item id's to mods so // we can calculate the used energy values for each item for (const mod of mods) { if (mod.plug.plugCategoryHash === armor2PlugCategoryHashesByName.general) { generalMods.push(mod); } else if (combatCompatiblePlugCategoryHashes.includes(mod.plug.plugCategoryHash)) { combatMods.push(mod); } else if (activityModPlugCategoryHashes.includes(mod.plug.plugCategoryHash)) { activityMods.push(mod); } else { const itemForMod = items.find( (item) => mod.plug.plugCategoryHash === bucketsToCategories[item.bucket.hash] ); if ( itemForMod && isBucketSpecificModValid( defs, upgradeSpendTier, lockItemEnergyType, itemForMod, mod, bucketSpecificAssignments[itemForMod.id].assigned ) ) { bucketSpecificAssignments[itemForMod.id].assigned.push(mod); } else if (itemForMod) { bucketSpecificAssignments[itemForMod.id].unassigned.push(mod); } } } // A object of item id's to energy information. This is so we can precalculate // working energy used, capacity and type and use this to validate whether a mod // can be used in an item. const itemEnergies = _.mapValues( _.keyBy(items, (item) => item.id), (item) => buildItemEnergy( defs, item, bucketSpecificAssignments[item.id].assigned, upgradeSpendTier, lockItemEnergyType ) ); const generalModPermutations = generateModPermutations(generalMods); const combatModPermutations = generateModPermutations(combatMods); const activityModPermutations = generateModPermutations(activityMods); for (const activityPermutation of activityModPermutations) { for (const combatPermutation of combatModPermutations) { modLoop: for (const generalPermutation of generalModPermutations) { let unassignedModCount = 0; const assignments: ModAssignments = {}; for (let i = 0; i < items.length; i++) { const assigned = []; const unassigned = []; const item = items[i]; const activityMod = activityPermutation[i]; if ( activityMod && isActivityModValid(activityMod, itemSocketMetadata[item.id], itemEnergies[item.id]) ) { assigned.push(activityMod); } else if (activityMod) { unassigned.push(activityMod); } const combatMod = combatPermutation[i]; if ( combatMod && isCombatModValid( combatMod, assigned, itemSocketMetadata[item.id], itemEnergies[item.id] ) ) { assigned.push(combatMod); } else if (combatMod) { unassigned.push(combatMod); } const generalMod = generalPermutation[i]; if (generalMod && isModEnergyValid(itemEnergies[item.id], generalMod, ...assigned)) { assigned.push(generalMod); } else if (generalMod) { unassigned.push(generalMod); } if (unassignedModCount + unassigned.length > assignmentUnassignedModCount) { continue modLoop; } unassignedModCount += unassigned.length; assignments[item.id] = { assigned, unassigned }; } // This is after the item loop let energyUsedAndWasted = 0; for (const [itemId, { assigned }] of Object.entries(assignments)) { energyUsedAndWasted += calculateEnergyChange(itemEnergies[itemId], assigned); } // if the cost of the new assignment set is better than the old one // we replace it and carry on until we have exhausted all permutations. if ( unassignedModCount < assignmentUnassignedModCount || (unassignedModCount <= assignmentUnassignedModCount && energyUsedAndWasted < assignmentEnergyCost) ) { bucketIndependentAssignments = assignments; assignmentEnergyCost = energyUsedAndWasted; assignmentUnassignedModCount = unassignedModCount; } } } } const mergedResults = new Map<string, PluggableInventoryItemDefinition[]>(); let unassignedMods: PluggableInventoryItemDefinition[] = []; for (const item of items) { const independentAssignments = bucketIndependentAssignments[item.id]; const specificAssignments = bucketSpecificAssignments[item.id]; mergedResults.set(item.id, [ ...independentAssignments.assigned, ...specificAssignments.assigned, ]); unassignedMods = [ ...unassignedMods, ...independentAssignments.unassigned, ...specificAssignments.unassigned, ]; } return { itemModAssignments: mergedResults, unassignedMods }; } interface ItemEnergy { used: number; originalCapacity: number; derivedCapacity: number; originalType: DestinyEnergyType; derivedType: DestinyEnergyType; } function buildItemEnergy( defs: D2ManifestDefinitions, item: DimItem, assignedMods: PluggableInventoryItemDefinition[], upgradeSpendTier: UpgradeSpendTier, lockItemEnergyType: boolean ): ItemEnergy { return { used: _.sumBy(assignedMods, (mod) => mod.plug.energyCost?.energyCost || 0), originalCapacity: item.energy?.energyCapacity || 0, derivedCapacity: upgradeSpendTierToMaxEnergy(defs, upgradeSpendTier, item), originalType: item.energy?.energyType || DestinyEnergyType.Any, derivedType: getItemEnergyType(defs, item, upgradeSpendTier, lockItemEnergyType, assignedMods), }; } function isBucketSpecificModValid( defs: D2ManifestDefinitions, upgradeSpendTier: UpgradeSpendTier, lockItemEnergyType: boolean, item: DimItem, mod: PluggableInventoryItemDefinition, assignedMods: PluggableInventoryItemDefinition[] ) { const itemEnergyCapacity = upgradeSpendTierToMaxEnergy(defs, upgradeSpendTier, item); const itemEnergyType = getItemEnergyType( defs, item, upgradeSpendTier, lockItemEnergyType, assignedMods ); const energyUsed = _.sumBy(assignedMods, (mod) => mod.plug.energyCost?.energyCost || 0); const modCost = mod.plug.energyCost?.energyCost || 0; const modEnergyType = mod.plug.energyCost?.energyType || DestinyEnergyType.Any; const energyTypeIsValid = modEnergyType === itemEnergyType || modEnergyType === DestinyEnergyType.Any || itemEnergyType === DestinyEnergyType.Any; return energyTypeIsValid && energyUsed + modCost <= itemEnergyCapacity; } function isActivityModValid( activityMod: PluggableInventoryItemDefinition, itemSocketMetadata: ModSocketMetadata[] | undefined, itemEnergy: ItemEnergy ) { const modTag = getModTypeTagByPlugCategoryHash(activityMod.plug.plugCategoryHash); // The activity mods wont fit in the item set so move on to the next set of mods return ( isModEnergyValid(itemEnergy, activityMod) && modTag && itemSocketMetadata?.some((metadata) => metadata.compatibleModTags.includes(modTag)) ); } function isCombatModValid( combatMod: PluggableInventoryItemDefinition, assignedMods: PluggableInventoryItemDefinition[], itemSocketMetadata: ModSocketMetadata[] | undefined, itemEnergy: ItemEnergy ) { const modTag = getModTypeTagByPlugCategoryHash(combatMod.plug.plugCategoryHash); // The activity mods wont fit in the item set so move on to the next set of mods return ( isModEnergyValid(itemEnergy, combatMod, ...assignedMods) && modTag && itemSocketMetadata?.some((metadata) => metadata.compatibleModTags.includes(modTag)) ); } function calculateEnergyChange( itemEnergy: ItemEnergy, assignedMods: PluggableInventoryItemDefinition[] ) { let finalEnergy = itemEnergy.derivedType; for (const mod of assignedMods) { if (finalEnergy !== DestinyEnergyType.Any) { break; } else if (mod.plug.energyCost?.energyType) { finalEnergy = mod.plug.energyCost.energyType; } } const modCost = itemEnergy.used + _.sumBy(assignedMods, (mod) => mod.plug.energyCost?.energyCost || 0); const energyUsedAndWasted = modCost + itemEnergy.originalCapacity; const energyInvested = Math.max(0, modCost - itemEnergy.originalCapacity); return finalEnergy === itemEnergy.originalType || finalEnergy === DestinyEnergyType.Any ? energyInvested : energyUsedAndWasted; } /** * This is used to figure out the energy type of an item used in mod assignments. * * It first considers if there are bucket specific mods applied, and returns that * energy type if it's not Any. If not then it considers armour upgrade options * and returns the appropriate energy type from that. * * It can return the Any energy type if armour upgrade options allow energy changes. */ export function getItemEnergyType( defs: D2ManifestDefinitions, item: DimItem, upgradeSpendTier: UpgradeSpendTier, lockItemEnergyType: boolean, bucketSpecificMods?: PluggableInventoryItemDefinition[] ) { if (!item.energy) { return DestinyEnergyType.Any; } const bucketSpecificModType = bucketSpecificMods?.find( (mod) => mod.plug.energyCost && mod.plug.energyCost.energyType !== DestinyEnergyType.Any )?.plug.energyCost?.energyType; // if we find bucket specific mods with an energy type we have to use that if (bucketSpecificModType) { return bucketSpecificModType; } return canSwapEnergyFromUpgradeSpendTier(defs, upgradeSpendTier, item, lockItemEnergyType) ? DestinyEnergyType.Any : item.energy.energyType; } /** * Validates whether a mod can be assigned to an item in the mod assignments algorithm. * * This checks that the summed mod energies are within the derived mod capacity for * an item (derived from armour upgrade options). It also ensures that all the mod * energy types align and that the mod can be slotted into an item socket based on * item energy type. */ export function isModEnergyValid( itemEnergy: ItemEnergy, modToAssign: PluggableInventoryItemDefinition, ...assignedMods: (PluggableInventoryItemDefinition | null)[] ) { const modToAssignCost = modToAssign.plug.energyCost?.energyCost || 0; const modToAssignType = modToAssign.plug.energyCost?.energyType || DestinyEnergyType.Any; const assignedModsCost = _.sumBy(assignedMods, (mod) => mod?.plug.energyCost?.energyCost || 0); return ( itemEnergy.used + modToAssignCost + assignedModsCost <= itemEnergy.derivedCapacity && energyTypesAreCompatible(itemEnergy.derivedType, modToAssignType) && assignedMods.every((mod) => energyTypesAreCompatible( modToAssignType, mod?.plug.energyCost?.energyType || DestinyEnergyType.Any ) ) ); } function energyTypesAreCompatible(first: DestinyEnergyType, second: DestinyEnergyType) { return first === second || first === DestinyEnergyType.Any || second === DestinyEnergyType.Any; }
the_stack
import * as matRipple from '../matRipple/matRipple'; import '../utils/base'; import {getMatBlazorInstance, MatBlazorComponent} from "../utils/base"; export interface IMatFileUploadEntry { info: IMatFileUploadEntryInfo; file: any; arrayBufferPromise?: Promise<ArrayBuffer>; } export interface IMatFileUploadEntryInfo { id: number; lastModified: Date; name: string; size: number; type: string; } export class MatFileUpload extends MatBlazorComponent { files: IMatFileUploadEntry[] = []; constructor(ref, private inputRef: HTMLInputElement, private componentRef) { super(ref); matRipple.init(this.ref); this.inputRef.addEventListener('change', (event) => { // console.log('this.inputRef', this.inputRef); var items = Array.from(this.inputRef.files).map((file) => { var info = <IMatFileUploadEntryInfo>{ id: this.files.length, lastModified: new Date(file.lastModified), name: file.name, size: file.size, type: file.type }; this.files.push(<IMatFileUploadEntry>{ info: info, file: file, }); return info; }); this.componentRef.invokeMethodAsync('NotifyChange', items).then(null, function (err) { throw new Error(err); }); }); } readDataAsArrayBufferAsync(entry: IMatFileUploadEntry): Promise<ArrayBuffer> { if (!entry.arrayBufferPromise) { entry.arrayBufferPromise = readAsArrayBufferAsync(entry.file); } return entry.arrayBufferPromise; } async readDataAsync(fileId: number, position: number, count: number): Promise<string> { // console.log('readDataAsync2 1'); var entry = this.files[fileId]; // console.log('readDataAsync2 11', entry); var arrayBuffer = await this.readDataAsArrayBufferAsync(entry); // console.log('readDataAsync2 2', arrayBuffer); var uint8Array = new Uint8Array(arrayBuffer, position, Math.min(count, arrayBuffer.byteLength - position)); var data = uint8ToBase64()(uint8Array); // console.log('readDataAsync 3', data); return data; } } export function init(ref, inputRef, componentRef) { new MatFileUpload(ref, inputRef, componentRef); } export async function readDataAsync(ref, fileId: number, position: number, count: number): Promise<string> { try { // console.log("Request", position.toLocaleString()); var componentRef = getMatBlazorInstance<MatFileUpload>(ref); // console.log("readDataAsync getMatBlazorInstance", componentRef) var result = await componentRef.readDataAsync(fileId, position, count); // console.log("readDataAsync readDataAsync", result) // console.log(result); // console.log("Response", position.toLocaleString()); return result; } catch (e) { // console.log('readDataAsync error', e); throw e; } } // export function readDataAsync2(ref, fileId: number, position: number, count: number): Promise<string> { // return new Promise<string>((resolve, reject)=>{ // resolve("qqq"); // }); // } export function readAsArrayBufferAsync(file): Promise<ArrayBuffer> { return new Promise<ArrayBuffer>((resolve, reject) => { var reader = new FileReader(); reader.onload = function () { resolve(<ArrayBuffer>reader.result); }; reader.onerror = function (err) { reject(err); }; reader.readAsArrayBuffer(file); }); } // // /** // * @property {MatFileUploadItem[]} items // */ // class MatFileUpload { // ref; // inputRef; // jsHelper; // items; // nextItemId; // // constructor(ref, inputRef, jsHelper) { // this.ref = ref; // this.inputRef = inputRef; // this.jsHelper = jsHelper; // this.items = {}; // this.nextItemId = 0; // } // // // init() { // matRipple.init(this.ref); // // // // this.inputRef.addEventListener('change', (event) => { // // // // var items = this.inputRef.files.map((file) => { // // var item = { // // id: ++this.nextItemId, // // lastModified: new Date(file.lastModified).toISOString(), // // name: file.name, // // size: file.size, // // type: file.type // // }; // // elem._blazorFilesById[result.id] = result; // // // // // Attach the blob data itself as a non-enumerable property so it doesn't appear in the JSON // // Object.defineProperty(result, 'blob', {value: file}); // // // // return result; // // }); // // // // componentInstance.invokeMethodAsync('NotifyChange', fileList).then(null, function (err) { // // throw new Error(err); // // }); // // }); // // // } // // // } // // // class MatFileUploadItem { // // entry; // file; // // /** // * @param {MatFileUploadItem} config // */ // // constructor(config) { // Object.assign(this, config); // } // } // // // class MatFileUploadEntry { // id; // lastModified; // name; // size; // type; // } // // // export function init(ref, inputRef, jsHelper) { // var instance = setMatBlazorInstance(ref, new MatFileUpload(ref, inputRef, jsHelper)); // return instance.init(); // }; // // export function readFileData(elem, fileId, startOffset, count) { // // return '123'; // var readPromise = getArrayBufferFromFileAsync(elem, fileId); // // return readPromise.then(function (arrayBuffer) { // // var uint8Array = new Uint8Array(arrayBuffer, startOffset, count); // var base64 = uint8ToBase64(uint8Array); // console.log('readFileData', base64); // return base64; // }); // }; // // export function ensureArrayBufferReadyForSharedMemoryInterop(elem, fileId) { // return getArrayBufferFromFileAsync(elem, fileId).then(function (arrayBuffer) { // getFileById(elem, fileId).arrayBuffer = arrayBuffer; // }); // }; // // export function readFileDataSharedMemory(readRequest) { // // This uses various unsupported internal APIs. Beware that if you also use them, // // your code could become broken by any update. // var inputFileElementReferenceId = Blazor.platform.readStringField(readRequest, 0); // var inputFileElement = document.querySelector('[_bl_' + inputFileElementReferenceId + ']'); // var fileId = Blazor.platform.readInt32Field(readRequest, 4); // var sourceOffset = Blazor.platform.readUint64Field(readRequest, 8); // var destination = Blazor.platform.readInt32Field(readRequest, 16); // var destinationOffset = Blazor.platform.readInt32Field(readRequest, 20); // var maxBytes = Blazor.platform.readInt32Field(readRequest, 24); // // var sourceArrayBuffer = getFileById(inputFileElement, fileId).arrayBuffer; // var bytesToRead = Math.min(maxBytes, sourceArrayBuffer.byteLength - sourceOffset); // var sourceUint8Array = new Uint8Array(sourceArrayBuffer, sourceOffset, bytesToRead); // // var destinationUint8Array = Blazor.platform.toUint8Array(destination); // destinationUint8Array.set(sourceUint8Array, destinationOffset); // // return bytesToRead; // }; // // function getFileById(elem, fileId) { // var file = elem._blazorFilesById[fileId]; // if (!file) { // throw new Error('There is no file with ID ' + fileId + '. The file list may have changed'); // } // // return file; // } // // function getArrayBufferFromFileAsync(elem, fileId) { // var file = getFileById(elem, fileId); // // // On the first read, convert the FileReader into a Promise<ArrayBuffer> // if (!file.readPromise) { // file.readPromise = new Promise(function (resolve, reject) { // var reader = new FileReader(); // reader.onload = function () { // resolve(reader.result); // }; // reader.onerror = function (err) { // reject(err); // }; // reader.readAsArrayBuffer(file.blob); // }); // } // // return file.readPromise; // } // var uint8ToBase64 = (function () { // Code from https://github.com/beatgammit/base64-js/ // License: MIT var lookup = []; var code = 'ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789+/'; for (var i = 0, len = code.length; i < len; ++i) { lookup[i] = code[i]; } function tripletToBase64(num) { return lookup[num >> 18 & 0x3F] + lookup[num >> 12 & 0x3F] + lookup[num >> 6 & 0x3F] + lookup[num & 0x3F]; } function encodeChunk(uint8, start, end) { var tmp; var output = []; for (var i = start; i < end; i += 3) { tmp = ((uint8[i] << 16) & 0xFF0000) + ((uint8[i + 1] << 8) & 0xFF00) + (uint8[i + 2] & 0xFF); output.push(tripletToBase64(tmp)); } return output.join(''); } return function fromByteArray(uint8) { var tmp; var len = uint8.length; var extraBytes = len % 3; // if we have 1 byte left, pad 2 bytes var parts = []; var maxChunkLength = 16383; // must be multiple of 3 // go through the array every three bytes, we'll deal with trailing stuff later for (var i = 0, len2 = len - extraBytes; i < len2; i += maxChunkLength) { parts.push(encodeChunk( uint8, i, (i + maxChunkLength) > len2 ? len2 : (i + maxChunkLength) )); } // pad the end with zeros, but make sure to not forget the extra bytes if (extraBytes === 1) { tmp = uint8[len - 1]; parts.push( lookup[tmp >> 2] + lookup[(tmp << 4) & 0x3F] + '==' ); } else if (extraBytes === 2) { tmp = (uint8[len - 2] << 8) + uint8[len - 1]; parts.push( lookup[tmp >> 10] + lookup[(tmp >> 4) & 0x3F] + lookup[(tmp << 2) & 0x3F] + '=' ); } return parts.join(''); }; });
the_stack
import { PdfDocument, PdfPage, PdfStandardFont, PdfFontFamily, PdfGraphicsState, PdfGridRowStyle } from './../../../src/index'; import { PdfSolidBrush, PdfColor, PdfFont, PdfPageOrientation, PdfBitmap, PdfGrid, PdfGridRow } from './../../../src/index'; import { PointF, SizeF, RectangleF, PdfPageRotateAngle, PdfGraphics, PdfGridCellStyle, PdfPen, PdfGridCell, PdfGridBeginCellDrawEventArgs, PdfSection, PdfGridLayoutResult, PdfTextWebLink, PdfDocumentLinkAnnotation, PdfDestination, PdfStringFormat, PdfTextAlignment, PdfTextElement, PdfLayoutResult } from './../../../src/index'; import { PdfHorizontalOverflowType, PdfVerticalAlignment, PdfSubSuperScript } from './../../../src/index'; import { Utils } from './../utils.spec'; describe('UTC-09: Paragraph with PointF(100, page1.graphics.clientSize.height - 50) : Left Alignment', () => { it('-Web Link Annotation', (done) => { // create a new PDF document let document : PdfDocument = new PdfDocument(); // add pages to the document. let page1 : PdfPage = document.pages.add(); let input : string = 'Lorem ipsum dolor sit amet, consectetur adipiscing elit, sed do eiusmod tempor incididunt ut labore et dolore magna aliqua. Ut enim ad minim veniam, quis nostrud exercitation ullamco laboris nisi ut aliquip ex ea commodo consequat. Lorem ipsum dolor sit amet, consectetur adipiscing elit, sed do eiusmod tempor incididunt ut labore et dolore magna aliqua. Ut enim ad minim veniam, quis nostrud exercitation ullamco laboris nisi ut aliquip ex ea commodo consequat. Lorem ipsum dolor sit amet, consectetur adipiscing elit, sed do eiusmod tempor incididunt ut labore et dolore magna aliqua. Ut enim ad minim veniam, quis nostrud exercitation ullamco laboris nisi ut aliquip ex ea commodo consequat.'; // set the font. let font : PdfFont = new PdfStandardFont(PdfFontFamily.TimesRoman, 20); let blackBrush : PdfSolidBrush = new PdfSolidBrush(new PdfColor(0, 0, 0)); // draw the text. page1.graphics.drawString(input, font, null, blackBrush, 100, page1.graphics.clientSize.height - 50, null); //Save the document. document.save().then((xlBlob: { blobData: Blob }) => { if (Utils.isDownloadEnabled) { Utils.download(xlBlob.blobData, 'utc_working_with_text_09.pdf'); } let reader: FileReader = new FileReader(); reader.readAsArrayBuffer(xlBlob.blobData); reader.onload = (): void => { if (reader.readyState == 2) { // DONE == 2 expect((reader.result as ArrayBuffer).byteLength).toBeGreaterThanOrEqual(0); done(); } } }); document.destroy(); // document.save('utc_working_with_text_09.pdf'); }) }); describe('UTC-10: Paragraph with PointF(100, page1.graphics.clientSize.height - 50) : Right Alignment', () => { it('-Web Link Annotation', (done) => { // create a new PDF document let document : PdfDocument = new PdfDocument(); // add pages to the document. let page1 : PdfPage = document.pages.add(); // set the font. let font : PdfFont = new PdfStandardFont(PdfFontFamily.TimesRoman, 20); let blackBrush : PdfSolidBrush = new PdfSolidBrush(new PdfColor(0, 0, 0)); let format : PdfStringFormat = new PdfStringFormat(PdfTextAlignment.Right); let input : string = 'Lorem ipsum dolor sit amet, consectetur adipiscing elit, sed do eiusmod tempor incididunt ut labore et dolore magna aliqua. Ut enim ad minim veniam, quis nostrud exercitation ullamco laboris nisi ut aliquip ex ea commodo consequat. Lorem ipsum dolor sit amet, consectetur adipiscing elit, sed do eiusmod tempor incididunt ut labore et dolore magna aliqua. Ut enim ad minim veniam, quis nostrud exercitation ullamco laboris nisi ut aliquip ex ea commodo consequat. Lorem ipsum dolor sit amet, consectetur adipiscing elit, sed do eiusmod tempor incididunt ut labore et dolore magna aliqua. Ut enim ad minim veniam, quis nostrud exercitation ullamco laboris nisi ut aliquip ex ea commodo consequat.'; // draw the text. page1.graphics.drawString(input, font, null, blackBrush, 100, page1.graphics.clientSize.height - 50, format); //Save the document. document.save().then((xlBlob: { blobData: Blob }) => { if (Utils.isDownloadEnabled) { Utils.download(xlBlob.blobData, 'utc_working_with_text_10.pdf'); } let reader: FileReader = new FileReader(); reader.readAsArrayBuffer(xlBlob.blobData); reader.onload = (): void => { if (reader.readyState == 2) { // DONE == 2 expect((reader.result as ArrayBuffer).byteLength).toBeGreaterThanOrEqual(0); done(); } } }); document.destroy(); // document.save('utc_working_with_text_10.pdf'); }) }); describe('UTC-11: Paragraph with PointF(100, page1.graphics.clientSize.height - 50) : Center Alignment', () => { it('-Web Link Annotation', (done) => { // create a new PDF document let document : PdfDocument = new PdfDocument(); // add pages to the document. let page1 : PdfPage = document.pages.add(); // set the font. let font : PdfFont = new PdfStandardFont(PdfFontFamily.TimesRoman, 20); let blackBrush : PdfSolidBrush = new PdfSolidBrush(new PdfColor(0, 0, 0)); let format : PdfStringFormat = new PdfStringFormat(PdfTextAlignment.Center); let input : string = 'Lorem ipsum dolor sit amet, consectetur adipiscing elit, sed do eiusmod tempor incididunt ut labore et dolore magna aliqua. Ut enim ad minim veniam, quis nostrud exercitation ullamco laboris nisi ut aliquip ex ea commodo consequat. Lorem ipsum dolor sit amet, consectetur adipiscing elit, sed do eiusmod tempor incididunt ut labore et dolore magna aliqua. Ut enim ad minim veniam, quis nostrud exercitation ullamco laboris nisi ut aliquip ex ea commodo consequat. Lorem ipsum dolor sit amet, consectetur adipiscing elit, sed do eiusmod tempor incididunt ut labore et dolore magna aliqua. Ut enim ad minim veniam, quis nostrud exercitation ullamco laboris nisi ut aliquip ex ea commodo consequat.'; // draw the text. page1.graphics.drawString(input, font, null, blackBrush, 100, (page1.graphics.clientSize.height - 50), format); //Save the document. document.save().then((xlBlob: { blobData: Blob }) => { if (Utils.isDownloadEnabled) { Utils.download(xlBlob.blobData, 'utc_working_with_text_11.pdf'); } let reader: FileReader = new FileReader(); reader.readAsArrayBuffer(xlBlob.blobData); reader.onload = (): void => { if (reader.readyState == 2) { // DONE == 2 expect((reader.result as ArrayBuffer).byteLength).toBeGreaterThanOrEqual(0); done(); } } }); document.destroy(); // document.save('utc_working_with_text_11.pdf'); }) }); describe('UTC-12: Paragraph with PointF(100, page1.graphics.clientSize.height - 50) : Justify Alignment', () => { it('-Web Link Annotation', (done) => { // create a new PDF document let document : PdfDocument = new PdfDocument(); // add pages to the document. let page1 : PdfPage = document.pages.add(); // set the font. let font : PdfFont = new PdfStandardFont(PdfFontFamily.TimesRoman, 20); let blackBrush : PdfSolidBrush = new PdfSolidBrush(new PdfColor(0, 0, 0)); let format : PdfStringFormat = new PdfStringFormat(PdfTextAlignment.Justify); let input : string = 'Lorem ipsum dolor sit amet, consectetur adipiscing elit, sed do eiusmod tempor incididunt ut labore et dolore magna aliqua. Ut enim ad minim veniam, quis nostrud exercitation ullamco laboris nisi ut aliquip ex ea commodo consequat. Lorem ipsum dolor sit amet, consectetur adipiscing elit, sed do eiusmod tempor incididunt ut labore et dolore magna aliqua. Ut enim ad minim veniam, quis nostrud exercitation ullamco laboris nisi ut aliquip ex ea commodo consequat. Lorem ipsum dolor sit amet, consectetur adipiscing elit, sed do eiusmod tempor incididunt ut labore et dolore magna aliqua. Ut enim ad minim veniam, quis nostrud exercitation ullamco laboris nisi ut aliquip ex ea commodo consequat.'; // draw the text. page1.graphics.drawString(input, font, null, blackBrush, 100, (page1.graphics.clientSize.height - 50), format); //Save the document. document.save().then((xlBlob: { blobData: Blob }) => { if (Utils.isDownloadEnabled) { Utils.download(xlBlob.blobData, 'utc_working_with_text_12.pdf'); } let reader: FileReader = new FileReader(); reader.readAsArrayBuffer(xlBlob.blobData); reader.onload = (): void => { if (reader.readyState == 2) { // DONE == 2 expect((reader.result as ArrayBuffer).byteLength).toBeGreaterThanOrEqual(0); done(); } } }); document.destroy(); // document.save('utc_working_with_text_12.pdf'); }) }); describe('UTC-13: Paragraph with Rectangle bounds : Left Alignment', () => { it('-Web Link Annotation', (done) => { // create a new PDF document let document : PdfDocument = new PdfDocument(); // add pages to the document. let page1 : PdfPage = document.pages.add(); // set the font. let font : PdfFont = new PdfStandardFont(PdfFontFamily.TimesRoman, 20); let blackBrush : PdfSolidBrush = new PdfSolidBrush(new PdfColor(0, 0, 0)); let format : PdfStringFormat = new PdfStringFormat(PdfTextAlignment.Left); let input : string = 'Lorem ipsum dolor sit amet, consectetur adipiscing elit, sed do eiusmod tempor incididunt ut labore et dolore magna aliqua. Ut enim ad minim veniam, quis nostrud exercitation ullamco laboris nisi ut aliquip ex ea commodo consequat. Lorem ipsum dolor sit amet, consectetur adipiscing elit, sed do eiusmod tempor incididunt ut labore et dolore magna aliqua. Ut enim ad minim veniam, quis nostrud exercitation ullamco laboris nisi ut aliquip ex ea commodo consequat. Lorem ipsum dolor sit amet, consectetur adipiscing elit, sed do eiusmod tempor incididunt ut labore et dolore magna aliqua. Ut enim ad minim veniam, quis nostrud exercitation ullamco laboris nisi ut aliquip ex ea commodo consequat.'; // draw the text. page1.graphics.drawString(input, font, null, blackBrush, 100, page1.graphics.clientSize.height - 50, page1.graphics.clientSize.width - 150, 200, format); //Save the document. document.save().then((xlBlob: { blobData: Blob }) => { if (Utils.isDownloadEnabled) { Utils.download(xlBlob.blobData, 'utc_working_with_text_13.pdf'); } let reader: FileReader = new FileReader(); reader.readAsArrayBuffer(xlBlob.blobData); reader.onload = (): void => { if (reader.readyState == 2) { // DONE == 2 expect((reader.result as ArrayBuffer).byteLength).toBeGreaterThanOrEqual(0); done(); } } }); document.destroy(); // document.save('utc_working_with_text_13.pdf'); }) }); describe('UTC-14: Paragraph with Rectangle bounds : Right Alignment', () => { it('-Web Link Annotation', (done) => { // create a new PDF document let document : PdfDocument = new PdfDocument(); // add pages to the document. let page1 : PdfPage = document.pages.add(); // set the font. let font : PdfFont = new PdfStandardFont(PdfFontFamily.TimesRoman, 20); let blackBrush : PdfSolidBrush = new PdfSolidBrush(new PdfColor(0, 0, 0)); let format : PdfStringFormat = new PdfStringFormat(PdfTextAlignment.Right); let input : string = 'Lorem ipsum dolor sit amet, consectetur adipiscing elit, sed do eiusmod tempor incididunt ut labore et dolore magna aliqua. Ut enim ad minim veniam, quis nostrud exercitation ullamco laboris nisi ut aliquip ex ea commodo consequat. Lorem ipsum dolor sit amet, consectetur adipiscing elit, sed do eiusmod tempor incididunt ut labore et dolore magna aliqua. Ut enim ad minim veniam, quis nostrud exercitation ullamco laboris nisi ut aliquip ex ea commodo consequat. Lorem ipsum dolor sit amet, consectetur adipiscing elit, sed do eiusmod tempor incididunt ut labore et dolore magna aliqua. Ut enim ad minim veniam, quis nostrud exercitation ullamco laboris nisi ut aliquip ex ea commodo consequat.'; // draw the text. page1.graphics.drawString(input, font, null, blackBrush, 100, page1.graphics.clientSize.height - 50, page1.graphics.clientSize.width - 150, 200, format); //Save the document. document.save().then((xlBlob: { blobData: Blob }) => { if (Utils.isDownloadEnabled) { Utils.download(xlBlob.blobData, 'utc_working_with_text_14.pdf'); } let reader: FileReader = new FileReader(); reader.readAsArrayBuffer(xlBlob.blobData); reader.onload = (): void => { if (reader.readyState == 2) { // DONE == 2 expect((reader.result as ArrayBuffer).byteLength).toBeGreaterThanOrEqual(0); done(); } } }); document.destroy(); // document.save('utc_working_with_text_14.pdf'); }) }); describe('UTC-15: Paragraph with Rectangle bounds : Center Alignment', () => { it('-Web Link Annotation', (done) => { // create a new PDF document let document : PdfDocument = new PdfDocument(); // add pages to the document. let page1 : PdfPage = document.pages.add(); // set the font. let font : PdfFont = new PdfStandardFont(PdfFontFamily.TimesRoman, 20); let blackBrush : PdfSolidBrush = new PdfSolidBrush(new PdfColor(0, 0, 0)); let format : PdfStringFormat = new PdfStringFormat(PdfTextAlignment.Center); let input : string = 'Lorem ipsum dolor sit amet, consectetur adipiscing elit, sed do eiusmod tempor incididunt ut labore et dolore magna aliqua. Ut enim ad minim veniam, quis nostrud exercitation ullamco laboris nisi ut aliquip ex ea commodo consequat. Lorem ipsum dolor sit amet, consectetur adipiscing elit, sed do eiusmod tempor incididunt ut labore et dolore magna aliqua. Ut enim ad minim veniam, quis nostrud exercitation ullamco laboris nisi ut aliquip ex ea commodo consequat. Lorem ipsum dolor sit amet, consectetur adipiscing elit, sed do eiusmod tempor incididunt ut labore et dolore magna aliqua. Ut enim ad minim veniam, quis nostrud exercitation ullamco laboris nisi ut aliquip ex ea commodo consequat.'; // draw the text. page1.graphics.drawString(input, font, null ,blackBrush, 100, page1.graphics.clientSize.height - 50, page1.graphics.clientSize.width - 150, 200, format); //Save the document. document.save().then((xlBlob: { blobData: Blob }) => { if (Utils.isDownloadEnabled) { Utils.download(xlBlob.blobData, 'utc_working_with_text_15.pdf'); } let reader: FileReader = new FileReader(); reader.readAsArrayBuffer(xlBlob.blobData); reader.onload = (): void => { if (reader.readyState == 2) { // DONE == 2 expect((reader.result as ArrayBuffer).byteLength).toBeGreaterThanOrEqual(0); done(); } } }); document.destroy(); // document.save('utc_working_with_text_15.pdf'); }) }); describe('UTC-16: Paragraph with Rectangle bounds : Justify Alignment', () => { it('-Web Link Annotation', (done) => { // create a new PDF document let document : PdfDocument = new PdfDocument(); // add pages to the document. let page1 : PdfPage = document.pages.add(); // set the font. let font : PdfFont = new PdfStandardFont(PdfFontFamily.TimesRoman, 20); let blackBrush : PdfSolidBrush = new PdfSolidBrush(new PdfColor(0, 0, 0)); let format : PdfStringFormat = new PdfStringFormat(PdfTextAlignment.Justify); let input : string = 'Lorem ipsum dolor sit amet, consectetur adipiscing elit, sed do eiusmod tempor incididunt ut labore et dolore magna aliqua. Ut enim ad minim veniam, quis nostrud exercitation ullamco laboris nisi ut aliquip ex ea commodo consequat. Lorem ipsum dolor sit amet, consectetur adipiscing elit, sed do eiusmod tempor incididunt ut labore et dolore magna aliqua. Ut enim ad minim veniam, quis nostrud exercitation ullamco laboris nisi ut aliquip ex ea commodo consequat. Lorem ipsum dolor sit amet, consectetur adipiscing elit, sed do eiusmod tempor incididunt ut labore et dolore magna aliqua. Ut enim ad minim veniam, quis nostrud exercitation ullamco laboris nisi ut aliquip ex ea commodo consequat.'; // draw the text. page1.graphics.drawString(input, font, null, blackBrush, 100, page1.graphics.clientSize.height - 50, page1.graphics.clientSize.width - 150, 200, format); //Save the document. document.save().then((xlBlob: { blobData: Blob }) => { if (Utils.isDownloadEnabled) { Utils.download(xlBlob.blobData, 'utc_working_with_text_16.pdf'); } let reader: FileReader = new FileReader(); reader.readAsArrayBuffer(xlBlob.blobData); reader.onload = (): void => { if (reader.readyState == 2) { // DONE == 2 expect((reader.result as ArrayBuffer).byteLength).toBeGreaterThanOrEqual(0); done(); } } }); document.destroy(); // document.save('utc_working_with_text_16.pdf'); }) }); describe('UTC-17: Text Element : Left Alignment', () => { it('-Web Link Annotation', (done) => { // create a new PDF document let document : PdfDocument = new PdfDocument(); // add pages to the document. let page1 : PdfPage = document.pages.add(); // set the font. let font : PdfFont = new PdfStandardFont(PdfFontFamily.TimesRoman, 20); let blackBrush : PdfSolidBrush = new PdfSolidBrush(new PdfColor(0, 0, 0)); let format : PdfStringFormat = new PdfStringFormat(PdfTextAlignment.Left); let input1 : string = 'Lorem ipsum dolor sit amet, consectetur adipiscing elit, sed do eiusmod tempor incididunt ut labore et dolore magna aliqua. Ut enim ad minim veniam, quis nostrud exercitation ullamco laboris nisi ut aliquip ex ea commodo consequat. Lorem ipsum dolor sit amet, consectetur adipiscing elit, sed do eiusmod tempor incididunt ut labore et dolore magna aliqua. Ut enim ad minim veniam, quis nostrud exercitation ullamco laboris nisi ut aliquip ex ea commodo consequat. Lorem ipsum dolor sit amet, consectetur adipiscing elit, sed do eiusmod tempor incididunt ut labore et dolore magna aliqua. Ut enim ad minim veniam, quis nostrud exercitation ullamco laboris nisi ut aliquip ex ea commodo consequat.'; let input2 : string = 'Lorem ipsum dolor sit amet, consectetur adipiscing elit, sed do eiusmod tempor incididunt ut labore et dolore magna aliqua. Ut enim ad minim veniam, quis nostrud exercitation ullamco laboris nisi ut aliquip ex ea commodo consequat. Lorem ipsum dolor sit amet, consectetur adipiscing elit, sed do eiusmod tempor incididunt ut labore et dolore magna aliqua. Ut enim ad minim veniam, quis nostrud exercitation ullamco laboris nisi ut aliquip ex ea commodo consequat. Lorem ipsum dolor sit amet, consectetur adipiscing elit, sed do eiusmod tempor incididunt ut labore et dolore magna aliqua. Ut enim ad minim veniam, quis nostrud exercitation ullamco laboris nisi ut aliquip ex ea commodo consequat.'; // draw the text. let element : PdfTextElement = new PdfTextElement(input1); element.stringFormat = format; element.font = font; element.brush = blackBrush; let result : PdfLayoutResult = element.drawText(page1, new PointF(100, page1.getClientSize().height - 30)); element = new PdfTextElement(input2); element.stringFormat = format; element.font = font; element.brush = blackBrush; result = element.drawText(result.page, new RectangleF(100, page1.getClientSize().height - 30, 200, page1.getClientSize().height)); //Save the document. document.save().then((xlBlob: { blobData: Blob }) => { if (Utils.isDownloadEnabled) { Utils.download(xlBlob.blobData, 'utc_working_with_text_17.pdf'); } let reader: FileReader = new FileReader(); reader.readAsArrayBuffer(xlBlob.blobData); reader.onload = (): void => { if (reader.readyState == 2) { // DONE == 2 expect((reader.result as ArrayBuffer).byteLength).toBeGreaterThanOrEqual(0); done(); } } }); document.destroy(); // document.save('utc_working_with_text_17.pdf'); }) }); describe('UTC-18: Text Element : Right Alignment', () => { it('-Web Link Annotation', (done) => { // create a new PDF document let document : PdfDocument = new PdfDocument(); // add pages to the document. let page1 : PdfPage = document.pages.add(); // set the font. let font : PdfFont = new PdfStandardFont(PdfFontFamily.TimesRoman, 20); let blackBrush : PdfSolidBrush = new PdfSolidBrush(new PdfColor(0, 0, 0)); let format : PdfStringFormat = new PdfStringFormat(PdfTextAlignment.Right); let input1 : string = 'Lorem ipsum dolor sit amet, consectetur adipiscing elit, sed do eiusmod tempor incididunt ut labore et dolore magna aliqua. Ut enim ad minim veniam, quis nostrud exercitation ullamco laboris nisi ut aliquip ex ea commodo consequat. Lorem ipsum dolor sit amet, consectetur adipiscing elit, sed do eiusmod tempor incididunt ut labore et dolore magna aliqua. Ut enim ad minim veniam, quis nostrud exercitation ullamco laboris nisi ut aliquip ex ea commodo consequat. Lorem ipsum dolor sit amet, consectetur adipiscing elit, sed do eiusmod tempor incididunt ut labore et dolore magna aliqua. Ut enim ad minim veniam, quis nostrud exercitation ullamco laboris nisi ut aliquip ex ea commodo consequat.'; let input2 : string = 'Lorem ipsum dolor sit amet, consectetur adipiscing elit, sed do eiusmod tempor incididunt ut labore et dolore magna aliqua. Ut enim ad minim veniam, quis nostrud exercitation ullamco laboris nisi ut aliquip ex ea commodo consequat. Lorem ipsum dolor sit amet, consectetur adipiscing elit, sed do eiusmod tempor incididunt ut labore et dolore magna aliqua. Ut enim ad minim veniam, quis nostrud exercitation ullamco laboris nisi ut aliquip ex ea commodo consequat. Lorem ipsum dolor sit amet, consectetur adipiscing elit, sed do eiusmod tempor incididunt ut labore et dolore magna aliqua. Ut enim ad minim veniam, quis nostrud exercitation ullamco laboris nisi ut aliquip ex ea commodo consequat.'; // draw the text. let element : PdfTextElement = new PdfTextElement(input1); element.stringFormat = format; element.font = font; element.brush = blackBrush; let result : PdfLayoutResult = element.drawText(page1, new PointF(100, page1.getClientSize().height - 30)); element = new PdfTextElement(input2); element.stringFormat = format; element.font = font; element.brush = blackBrush; result = element.drawText(result.page, new RectangleF(100, page1.getClientSize().height - 30, 200, page1.getClientSize().height)); //Save the document. document.save().then((xlBlob: { blobData: Blob }) => { if (Utils.isDownloadEnabled) { Utils.download(xlBlob.blobData, 'utc_working_with_text_18.pdf'); } let reader: FileReader = new FileReader(); reader.readAsArrayBuffer(xlBlob.blobData); reader.onload = (): void => { if (reader.readyState == 2) { // DONE == 2 expect((reader.result as ArrayBuffer).byteLength).toBeGreaterThanOrEqual(0); done(); } } }); document.destroy(); // document.save('utc_working_with_text_18.pdf'); }) }); describe('UTC-19: Text Element : Center Alignment', () => { it('-Web Link Annotation', (done) => { // create a new PDF document let document : PdfDocument = new PdfDocument(); // add pages to the document. let page1 : PdfPage = document.pages.add(); // set the font. let font : PdfFont = new PdfStandardFont(PdfFontFamily.TimesRoman, 20); let blackBrush : PdfSolidBrush = new PdfSolidBrush(new PdfColor(0, 0, 0)); let format : PdfStringFormat = new PdfStringFormat(PdfTextAlignment.Center); let input1 : string = 'Lorem ipsum dolor sit amet, consectetur adipiscing elit, sed do eiusmod tempor incididunt ut labore et dolore magna aliqua. Ut enim ad minim veniam, quis nostrud exercitation ullamco laboris nisi ut aliquip ex ea commodo consequat. Lorem ipsum dolor sit amet, consectetur adipiscing elit, sed do eiusmod tempor incididunt ut labore et dolore magna aliqua. Ut enim ad minim veniam, quis nostrud exercitation ullamco laboris nisi ut aliquip ex ea commodo consequat. Lorem ipsum dolor sit amet, consectetur adipiscing elit, sed do eiusmod tempor incididunt ut labore et dolore magna aliqua. Ut enim ad minim veniam, quis nostrud exercitation ullamco laboris nisi ut aliquip ex ea commodo consequat.'; let input2 : string = 'Lorem ipsum dolor sit amet, consectetur adipiscing elit, sed do eiusmod tempor incididunt ut labore et dolore magna aliqua. Ut enim ad minim veniam, quis nostrud exercitation ullamco laboris nisi ut aliquip ex ea commodo consequat. Lorem ipsum dolor sit amet, consectetur adipiscing elit, sed do eiusmod tempor incididunt ut labore et dolore magna aliqua. Ut enim ad minim veniam, quis nostrud exercitation ullamco laboris nisi ut aliquip ex ea commodo consequat. Lorem ipsum dolor sit amet, consectetur adipiscing elit, sed do eiusmod tempor incididunt ut labore et dolore magna aliqua. Ut enim ad minim veniam, quis nostrud exercitation ullamco laboris nisi ut aliquip ex ea commodo consequat.'; // draw the text. let element : PdfTextElement = new PdfTextElement(input1); element.stringFormat = format; element.font = font; element.brush = blackBrush; let result : PdfLayoutResult = element.drawText(page1, new PointF(100, page1.getClientSize().height - 30)); element = new PdfTextElement(input2); element.stringFormat = format; element.font = font; element.brush = blackBrush; result = element.drawText(result.page, new RectangleF(100, page1.getClientSize().height - 30, 200, page1.getClientSize().height)); //Save the document. document.save().then((xlBlob: { blobData: Blob }) => { if (Utils.isDownloadEnabled) { Utils.download(xlBlob.blobData, 'utc_working_with_text_19.pdf'); } let reader: FileReader = new FileReader(); reader.readAsArrayBuffer(xlBlob.blobData); reader.onload = (): void => { if (reader.readyState == 2) { // DONE == 2 expect((reader.result as ArrayBuffer).byteLength).toBeGreaterThanOrEqual(0); done(); } } }); document.destroy(); // document.save('utc_working_with_text_19.pdf'); }) }); describe('UTC-20: Text Element : Justify Alignment', () => { it('-Web Link Annotation', (done) => { // create a new PDF document let document : PdfDocument = new PdfDocument(); // add pages to the document. let page1 : PdfPage = document.pages.add(); // set the font. let font : PdfFont = new PdfStandardFont(PdfFontFamily.TimesRoman, 20); let blackBrush : PdfSolidBrush = new PdfSolidBrush(new PdfColor(0, 0, 0)); let format : PdfStringFormat = new PdfStringFormat(PdfTextAlignment.Justify); let input1 : string = 'Lorem ipsum dolor sit amet, consectetur adipiscing elit, sed do eiusmod tempor incididunt ut labore et dolore magna aliqua. Ut enim ad minim veniam, quis nostrud exercitation ullamco laboris nisi ut aliquip ex ea commodo consequat. Lorem ipsum dolor sit amet, consectetur adipiscing elit, sed do eiusmod tempor incididunt ut labore et dolore magna aliqua. Ut enim ad minim veniam, quis nostrud exercitation ullamco laboris nisi ut aliquip ex ea commodo consequat. Lorem ipsum dolor sit amet, consectetur adipiscing elit, sed do eiusmod tempor incididunt ut labore et dolore magna aliqua. Ut enim ad minim veniam, quis nostrud exercitation ullamco laboris nisi ut aliquip ex ea commodo consequat.'; let input2 : string = 'Lorem ipsum dolor sit amet, consectetur adipiscing elit, sed do eiusmod tempor incididunt ut labore et dolore magna aliqua. Ut enim ad minim veniam, quis nostrud exercitation ullamco laboris nisi ut aliquip ex ea commodo consequat. Lorem ipsum dolor sit amet, consectetur adipiscing elit, sed do eiusmod tempor incididunt ut labore et dolore magna aliqua. Ut enim ad minim veniam, quis nostrud exercitation ullamco laboris nisi ut aliquip ex ea commodo consequat. Lorem ipsum dolor sit amet, consectetur adipiscing elit, sed do eiusmod tempor incididunt ut labore et dolore magna aliqua. Ut enim ad minim veniam, quis nostrud exercitation ullamco laboris nisi ut aliquip ex ea commodo consequat.'; // draw the text. let element : PdfTextElement = new PdfTextElement(input1); element.stringFormat = format; element.font = font; element.brush = blackBrush; let result : PdfLayoutResult = element.drawText(page1, new PointF(100, page1.getClientSize().height - 30)); element = new PdfTextElement(input2); element.stringFormat = format; element.font = font; element.brush = blackBrush; result = element.drawText(result.page, new RectangleF(100, page1.getClientSize().height - 30, 200, page1.getClientSize().height)); //Save the document. document.save().then((xlBlob: { blobData: Blob }) => { if (Utils.isDownloadEnabled) { Utils.download(xlBlob.blobData, 'utc_working_with_text_20.pdf'); } let reader: FileReader = new FileReader(); reader.readAsArrayBuffer(xlBlob.blobData); reader.onload = (): void => { if (reader.readyState == 2) { // DONE == 2 expect((reader.result as ArrayBuffer).byteLength).toBeGreaterThanOrEqual(0); done(); } } }); document.destroy(); // document.save('utc_working_with_text_20.pdf'); }) }); // describe('UTC-23: horizontal overflow - NextPage', () => { // //Create a new PDF document. // let document : PdfDocument = new PdfDocument(); // let page : PdfPage = document.pages.add(); // let grid : PdfGrid = new PdfGrid(); // //Set AllowHorizontalOverflow for NextPage,LastPage Properties // grid.style.allowHorizontalOverflow = true; // //Set HorizontalOverflowType as NextPage // grid.style.horizontalOverflowType = PdfHorizontalOverflowType.NextPage; // //Add 12 columns. // grid.columns.add(12); // //Add headers. // grid.headers.add(1); // let tempPdfGridHeader : PdfGridRow = grid.headers.getHeader(0); // tempPdfGridHeader.cells.getCell(0).value = "Employee ID 1"; // tempPdfGridHeader.cells.getCell(1).value = "Employee Name"; // tempPdfGridHeader.cells.getCell(2).value = "Salary"; // tempPdfGridHeader.cells.getCell(3).value = "Employee ID 2"; // tempPdfGridHeader.cells.getCell(4).value = "Employee Name"; // tempPdfGridHeader.cells.getCell(5).value = "Salary"; // tempPdfGridHeader.cells.getCell(6).value = "Employee ID 1"; // tempPdfGridHeader.cells.getCell(7).value = "Employee Name"; // tempPdfGridHeader.cells.getCell(8).value = "Salary"; // tempPdfGridHeader.cells.getCell(9).value = "Employee ID 2"; // tempPdfGridHeader.cells.getCell(10).value = "Employee Name"; // tempPdfGridHeader.cells.getCell(11).value = "Salary"; // //Add rows. // for (let i : number = 0; i < 60 ; i++) { // let pdfGridRow1 : PdfGridRow = grid.rows.addRow(); // pdfGridRow1.cells.getCell(0).value = "E" + i + "- 1"; // pdfGridRow1.cells.getCell(1).value = "Clay"; // pdfGridRow1.cells.getCell(2).value = "$15,000"; // pdfGridRow1.cells.getCell(3).value = "E" + i + "- 2"; // pdfGridRow1.cells.getCell(4).value = "David"; // pdfGridRow1.cells.getCell(5).value = "$16,000"; // pdfGridRow1.cells.getCell(6).value = "E" + i + "- 3"; // pdfGridRow1.cells.getCell(7).value = "Clay"; // pdfGridRow1.cells.getCell(8).value = "$15,000"; // pdfGridRow1.cells.getCell(9).value = "E" + i + "- 4"; // pdfGridRow1.cells.getCell(10).value = "David"; // pdfGridRow1.cells.getCell(11).value = "$16,000"; // } // //Drawing a grid. // grid.draw(page, new PointF(0, 10)); // // save the PDF // document.save('utc_text_23.pdf'); // });
the_stack
import TomSelect from 'tom-select/src/tom-select'; import { TomSettings } from 'tom-select/src/types/settings'; import { TomInput } from 'tom-select/src/types'; import TomSelect_remove_button from 'tom-select/src/plugins/remove_button/plugin'; import { escape_html } from 'tom-select/src/utils'; import { IncompleteSelect } from './IncompleteSelect'; import template from 'lodash.template'; import styles from 'sass:./DjangoSelectize.scss'; TomSelect.define('remove_button', TomSelect_remove_button); type Renderer = { [key:string]: (data:any, escape:typeof escape_html) => string | HTMLElement; } class DjangoSelectize extends IncompleteSelect { private readonly numOptions: number = 12; private readonly tomInput: TomInput; private readonly tomSelect: TomSelect; private readonly shadowRoot: ShadowRoot; private readonly observer: MutationObserver; private readonly initialValue: string | string[]; constructor(tomInput: TomInput) { super(tomInput); const pseudoStylesElement = this.convertPseudoClasses(); this.tomInput = tomInput; // @ts-ignore const config: TomSettings = { create: false, valueField: 'id', labelField: 'label', maxItems: 1, searchField: ['label'], render: this.setupRender(tomInput), onBlur: () => this.blurred(), onType: (evt: Event) => this.inputted(evt), }; if (this.isIncomplete) { config.load = (query: string, callback: Function) => this.loadOptions(`query=${encodeURIComponent(query)}`, callback); } let isMultiple = false; if (tomInput.hasAttribute('multiple')) { config.maxItems = parseInt(tomInput.getAttribute('max_items') ?? '3'); const translation = tomInput.parentElement?.querySelector('template.selectize-remove-item'); if (translation) { config.plugins = {remove_button: {title: translation.innerHTML}}; } // tom-select has some issues to initialize items using the original input element const scriptId = `${tomInput.getAttribute('id')}_initial`; config.items = JSON.parse(document.getElementById(scriptId)?.textContent ?? '[]'); // We want to use the CSS styles for <select> without multiple tomInput.removeAttribute('multiple'); isMultiple = true; } const nativeStyles = {...window.getComputedStyle(tomInput)} as CSSStyleDeclaration; if (isMultiple) { // revert the above tomInput.setAttribute('multiple', 'multiple'); } this.numOptions = parseInt(tomInput.getAttribute('options') ?? this.numOptions.toString()); this.tomSelect = new TomSelect(tomInput, config); this.observer = new MutationObserver(mutationsList => this.attributesChanged(mutationsList)); this.observer.observe(this.tomInput, {attributes: true}); this.initialValue = this.tomSelect.getValue(); this.shadowRoot = this.wrapInShadowRoot(); this.transferStyles(tomInput, nativeStyles); this.validateInput(this.initialValue as string); this.tomSelect.on('change', (value: String) => this.validateInput(value)); pseudoStylesElement.remove(); } formResetted(event: Event) { this.tomSelect.setValue(this.initialValue); } private wrapInShadowRoot() : ShadowRoot { const shadowWrapper = document.createElement('div'); shadowWrapper.classList.add('shadow-wrapper'); const shadowRoot = shadowWrapper.attachShadow({mode: 'open', delegatesFocus: true}); const shadowStyleElement = document.createElement('style'); shadowRoot.appendChild(shadowStyleElement).textContent = styles; this.tomInput.insertAdjacentElement('afterend', shadowWrapper); const wrapper = (this.tomInput.parentElement as HTMLElement).removeChild(this.tomSelect.wrapper); shadowRoot.appendChild(wrapper); return shadowRoot; } private blurred() { const wrapper = this.shadowRoot.querySelector('.ts-wrapper'); wrapper?.classList.remove('dirty'); } private inputted(event: Event) { const value = event as unknown as string; const wrapper = this.shadowRoot.querySelector('.ts-wrapper'); wrapper?.classList.toggle('dirty', value.length > 0); } private validateInput(value: String | Array<string>) { const wrapper = this.shadowRoot.querySelector('.ts-wrapper'); wrapper?.classList.remove('dirty'); const selectElem = this.tomInput as HTMLSelectElement; if (this.tomSelect.isRequired) { selectElem.setCustomValidity(value ? "": "Value is missing."); } if (selectElem.multiple) { for (let k = 0; k < selectElem.options.length; k++) { const option = selectElem.options.item(k); if (option) { option.selected = value.indexOf(option.value) >= 0; } } } else { this.tomInput.value = value as string; } } private transferStyles(tomInput: HTMLElement, nativeStyles: CSSStyleDeclaration) { const wrapperStyle = (this.shadowRoot.host as HTMLElement).style; wrapperStyle.setProperty('display', nativeStyles.display); const sheet = this.shadowRoot.styleSheets[0]; for (let index = 0; index < sheet.cssRules.length; index++) { const cssRule = sheet.cssRules.item(index) as CSSStyleRule; const lineHeight = window.getComputedStyle(tomInput).getPropertyValue('line-height'); let extraStyles: string; const optionElement = tomInput.querySelector('option'); switch (cssRule.selectorText) { case '.ts-wrapper': extraStyles = this.extractStyles(tomInput, [ 'font-family', 'font-size', 'font-strech', 'font-style', 'font-weight', 'letter-spacing', 'white-space']); sheet.insertRule(`${cssRule.selectorText}{${extraStyles}}`, ++index); break; case '.ts-wrapper .ts-control': extraStyles = this.extractStyles(tomInput, [ 'background-color', 'border', 'border-radius', 'box-shadow', 'color', 'padding']).concat(`width: ${nativeStyles['width']}; min-height: ${nativeStyles['height']};`); sheet.insertRule(`${cssRule.selectorText}{${extraStyles}}`, ++index); break; case '.ts-wrapper .ts-control > input': case '.ts-wrapper .ts-control > div': if (optionElement) { extraStyles = this.extractStyles(optionElement, ['padding-left', 'padding-right']); sheet.insertRule(`${cssRule.selectorText}{${extraStyles}}`, ++index); } break; case '.ts-wrapper .ts-control > input::placeholder': tomInput.classList.add('-placeholder-'); extraStyles = this.extractStyles(tomInput, ['background-color', 'color']) tomInput.classList.remove('-placeholder-'); sheet.insertRule(`${cssRule.selectorText}{${extraStyles}}`, ++index); break; case '.ts-wrapper.focus .ts-control': tomInput.style.transition = 'none'; tomInput.classList.add('-focus-'); extraStyles = this.extractStyles(tomInput, [ 'background-color', 'border', 'box-shadow', 'color', 'outline', 'transition']) tomInput.classList.remove('-focus-'); sheet.insertRule(`${cssRule.selectorText}{${extraStyles}}`, ++index); tomInput.style.transition = ''; break; case '.ts-wrapper.disabled .ts-control': tomInput.classList.add('-disabled-'); extraStyles = this.extractStyles(tomInput, [ 'background-color', 'border', 'box-shadow', 'color', 'opacity', 'outline', 'transition']) tomInput.classList.remove('-disabled-'); sheet.insertRule(`${cssRule.selectorText}{${extraStyles}}`, ++index); break; case '.ts-wrapper .ts-dropdown': extraStyles = this.extractStyles(tomInput, [ 'border-right', 'border-bottom', 'border-left', 'color', 'padding-left']) .concat(parseFloat(lineHeight) > 0 ? `line-height: calc(${lineHeight} * 1.2);` : 'line-height: 1.2em;'); sheet.insertRule(`${cssRule.selectorText}{${extraStyles}}`, ++index); break; case '.ts-wrapper .ts-dropdown .ts-dropdown-content': if (parseFloat(lineHeight) > 0) { extraStyles = `max-height: calc(${lineHeight} * 1.2 * ${this.numOptions});`; } else { extraStyles = `max-height: ${this.numOptions * 1.2}em;`; } sheet.insertRule(`${cssRule.selectorText}{${extraStyles}}`, ++index); break; default: break; } } } private extractStyles(element: Element, properties: Array<string>): string { let styles = Array<string>(); const style = window.getComputedStyle(element); for (let property of properties) { styles.push(`${property}:${style.getPropertyValue(property)}`); } return styles.join('; ').concat('; '); } private setupRender(tomInput: TomInput) : Renderer { const templ = tomInput.parentElement?.querySelector('template.select-no-results'); return templ ? { no_results: (data: any, escape: Function) => template(templ.innerHTML)(data), } : {}; } private convertPseudoClasses() : HTMLStyleElement { // Iterate over all style sheets, find most pseudo classes and add CSSRules with a // CSS selector where the pseudo class has been replaced by a real counterpart. // This is required, because browsers can not invoke `window.getComputedStyle(element)` // using pseudo classes. // With function `removeConvertedClasses()` the added CSSRules are removed again. const numStyleSheets = document.styleSheets.length; const styleElement = document.createElement('style'); document.head.appendChild(styleElement); for (let index = 0; index < numStyleSheets; index++) { const sheet = document.styleSheets[index]; for (let k = 0; k < sheet.cssRules.length; k++) { const cssRule = sheet.cssRules.item(k); if (cssRule) { this.traverseStyles(cssRule, styleElement.sheet as CSSStyleSheet); } } } return styleElement; } private traverseStyles(cssRule: CSSRule, extraCSSStyleSheet: CSSStyleSheet) { if (cssRule instanceof CSSImportRule) { if (!cssRule.styleSheet) return; for (let subRule of cssRule.styleSheet.cssRules) { this.traverseStyles(subRule, extraCSSStyleSheet); } } else if (cssRule instanceof CSSStyleRule) { if (!cssRule.selectorText) return; const newSelectorText = cssRule.selectorText. replaceAll(':focus', '.-focus-'). replaceAll(':focus-visible', '.-focus-visible-'). replaceAll(':hover', '.-hover-'). replaceAll(':disabled', '.-disabled-'). replaceAll(':invalid', '.-invalid-'). replaceAll(':valid', '.-valid-'). replaceAll('::placeholder-shown', '.-placeholder-shown'). replaceAll(':placeholder-shown', '.-placeholder-shown'). replaceAll('::placeholder', '.-placeholder-'). replaceAll(':placeholder', '.-placeholder-'); if (newSelectorText !== cssRule.selectorText) { extraCSSStyleSheet.insertRule(`${newSelectorText}{${cssRule.style.cssText}}`); } } // else handle other CSSRule types } private attributesChanged(mutationsList: Array<MutationRecord>) { for (const mutation of mutationsList) { if (mutation.type === 'attributes' && mutation.attributeName === 'disabled') { if (this.tomInput.disabled) { if (!this.tomSelect.isDisabled) { this.tomSelect.disable(); } } else { if (this.tomSelect.isDisabled) { this.tomSelect.enable(); } } } } } public get value() : string | string[] { return this.tomSelect.getValue(); } } const DS = Symbol('DjangoSelectize'); export class DjangoSelectizeElement extends HTMLSelectElement { private [DS]: DjangoSelectize; // hides internal implementation private connectedCallback() { this[DS] = new DjangoSelectize(this); } public async getValue() { return this[DS].value; } }
the_stack
import {runIfMain} from "../../../../deps/mocha.ts"; import "../../../../deps/chai.ts"; import {Post} from "./entity/Post.ts"; import {Connection} from "../../../../../src/index.ts"; import {closeTestingConnections, createTestingConnections, reloadTestingDatabases} from "../../../../utils/test-utils.ts"; import {PostWithOptions} from "./entity/PostWithOptions.ts"; import {PostWithoutTypes} from "./entity/PostWithoutTypes.ts"; import {DateUtils} from "../../../../../src/util/DateUtils.ts"; describe("database schema > column types > sap", () => { let connections: Connection[]; const encoder = new TextEncoder(); before(async () => { connections = await createTestingConnections({ entities: [Post, PostWithOptions, PostWithoutTypes], enabledDrivers: ["sap"], }); }); beforeEach(() => reloadTestingDatabases(connections)); after(() => closeTestingConnections(connections)); it("all types should work correctly - persist and hydrate", () => Promise.all(connections.map(async connection => { const postRepository = connection.getRepository(Post); const queryRunner = connection.createQueryRunner(); const table = await queryRunner.getTable("post"); await queryRunner.release(); const post = new Post(); post.id = 1; post.name = "Post"; post.int = 2147483647; post.integer = 2147483647; post.tinyint = 250; post.smallint = 32767; post.bigint = "8223372036854775807"; post.decimal = "8223372036854775807"; post.dec = "8223372036854775807"; post.smalldecimal = "8223372036854775"; post.real = 10.5; post.double = 10.53; post.float = 10.53; post.char = "A"; post.nchar = "A"; post.varchar = "This is varchar"; post.nvarchar = "This is nvarchar"; post.alphanum = "This is alphanum"; post.text = "This is text"; post.shorttext = "This is shorttext"; post.dateObj = new Date(); post.date = "2017-06-21"; post.timeObj = new Date(); post.time = "13:27:05"; post.timestamp = new Date(); post.timestamp.setMilliseconds(0); post.seconddate = new Date(); post.seconddate.setMilliseconds(0); // TODO(uki00a) not fully tested yet. post.blob = encoder.encode("This is blob");/* new Buffer("This is blob"); */ post.clob = "This is clob"; post.nclob = "This is nclob"; post.boolean = true; // post.array = ["A", "B", "C"]; // TODO // TODO(uki00a) not fully tested yet. post.varbinary = encoder.encode("This is varbinary");/* new Buffer("This is varbinary"); */ post.simpleArray = ["A", "B", "C"]; await postRepository.save(post); const loadedPost = (await postRepository.findOne(1))!; loadedPost.id.should.be.equal(post.id); loadedPost.name.should.be.equal(post.name); loadedPost.int.should.be.equal(post.int); loadedPost.integer.should.be.equal(post.integer); loadedPost.tinyint.should.be.equal(post.tinyint); loadedPost.smallint.should.be.equal(post.smallint); loadedPost.bigint.should.be.equal(post.bigint); loadedPost.decimal.should.be.equal(post.decimal); loadedPost.dec.should.be.equal(post.dec); loadedPost.smalldecimal.should.be.equal(post.smalldecimal); loadedPost.real.should.be.equal(post.real); loadedPost.double.should.be.equal(post.double); loadedPost.float.should.be.equal(post.float); loadedPost.char.should.be.equal(post.char); loadedPost.nchar.should.be.equal(post.nchar); loadedPost.varchar.should.be.equal(post.varchar); loadedPost.nvarchar.should.be.equal(post.nvarchar); loadedPost.alphanum.should.be.equal(post.alphanum); loadedPost.text.should.be.equal(post.text); loadedPost.shorttext.should.be.equal(post.shorttext); loadedPost.dateObj.should.be.equal(DateUtils.mixedDateToDateString(post.dateObj)); loadedPost.date.should.be.equal(post.date); loadedPost.timeObj.valueOf().should.be.equal(DateUtils.mixedTimeToString(post.timeObj)); loadedPost.time.should.be.equal(post.time); loadedPost.timestamp.valueOf().should.be.equal(post.timestamp.valueOf()); loadedPost.seconddate.valueOf().should.be.equal(post.seconddate.valueOf()); loadedPost.blob.toString().should.be.equal(post.blob.toString()); loadedPost.clob.toString().should.be.equal(post.clob.toString()); loadedPost.nclob.toString().should.be.equal(post.nclob.toString()); loadedPost.boolean.should.be.equal(post.boolean); loadedPost.varbinary.toString().should.be.equal(post.varbinary.toString()); loadedPost.simpleArray[0].should.be.equal(post.simpleArray[0]); loadedPost.simpleArray[1].should.be.equal(post.simpleArray[1]); loadedPost.simpleArray[2].should.be.equal(post.simpleArray[2]); table!.findColumnByName("id")!.type.should.be.equal("integer"); table!.findColumnByName("name")!.type.should.be.equal("nvarchar"); table!.findColumnByName("int")!.type.should.be.equal("integer"); table!.findColumnByName("integer")!.type.should.be.equal("integer"); table!.findColumnByName("tinyint")!.type.should.be.equal("tinyint"); table!.findColumnByName("smallint")!.type.should.be.equal("smallint"); table!.findColumnByName("bigint")!.type.should.be.equal("bigint"); table!.findColumnByName("decimal")!.type.should.be.equal("decimal"); table!.findColumnByName("dec")!.type.should.be.equal("decimal"); table!.findColumnByName("real")!.type.should.be.equal("real"); table!.findColumnByName("double")!.type.should.be.equal("double"); table!.findColumnByName("float")!.type.should.be.equal("double"); table!.findColumnByName("char")!.type.should.be.equal("char"); table!.findColumnByName("nchar")!.type.should.be.equal("nchar"); table!.findColumnByName("varchar")!.type.should.be.equal("varchar"); table!.findColumnByName("nvarchar")!.type.should.be.equal("nvarchar"); table!.findColumnByName("alphanum")!.type.should.be.equal("alphanum"); table!.findColumnByName("text")!.type.should.be.equal("text"); table!.findColumnByName("shorttext")!.type.should.be.equal("shorttext"); table!.findColumnByName("dateObj")!.type.should.be.equal("date"); table!.findColumnByName("date")!.type.should.be.equal("date"); table!.findColumnByName("timeObj")!.type.should.be.equal("time"); table!.findColumnByName("time")!.type.should.be.equal("time"); table!.findColumnByName("timestamp")!.type.should.be.equal("timestamp"); table!.findColumnByName("seconddate")!.type.should.be.equal("seconddate"); table!.findColumnByName("blob")!.type.should.be.equal("blob"); table!.findColumnByName("clob")!.type.should.be.equal("clob"); table!.findColumnByName("nclob")!.type.should.be.equal("nclob"); table!.findColumnByName("boolean")!.type.should.be.equal("boolean"); table!.findColumnByName("varbinary")!.type.should.be.equal("varbinary"); table!.findColumnByName("simpleArray")!.type.should.be.equal("text"); }))); it("all types should work correctly - persist and hydrate when options are specified on columns", () => Promise.all(connections.map(async connection => { const postRepository = connection.getRepository(PostWithOptions); const queryRunner = connection.createQueryRunner(); const table = await queryRunner.getTable("post_with_options"); await queryRunner.release(); const post = new PostWithOptions(); post.id = 1; post.dec = "60.00"; post.decimal = "70.000"; post.varchar = "This is varchar"; post.nvarchar = "This is nvarchar"; post.alphanum = "This is alphanum"; post.shorttext = "This is shorttext"; await postRepository.save(post); const loadedPost = (await postRepository.findOne(1))!; loadedPost.id.should.be.equal(post.id); loadedPost.dec.should.be.equal(post.dec); loadedPost.decimal.should.be.equal(post.decimal); loadedPost.varchar.should.be.equal(post.varchar); loadedPost.nvarchar.should.be.equal(post.nvarchar); loadedPost.alphanum.should.be.equal(post.alphanum); loadedPost.shorttext.should.be.equal(post.shorttext); table!.findColumnByName("id")!.type.should.be.equal("integer"); table!.findColumnByName("dec")!.type.should.be.equal("decimal"); table!.findColumnByName("dec")!.precision!.should.be.equal(10); table!.findColumnByName("dec")!.scale!.should.be.equal(2); table!.findColumnByName("decimal")!.type.should.be.equal("decimal"); table!.findColumnByName("decimal")!.precision!.should.be.equal(10); table!.findColumnByName("decimal")!.scale!.should.be.equal(3); table!.findColumnByName("varchar")!.type.should.be.equal("varchar"); table!.findColumnByName("varchar")!.length!.should.be.equal("50"); table!.findColumnByName("nvarchar")!.type.should.be.equal("nvarchar"); table!.findColumnByName("nvarchar")!.length!.should.be.equal("50"); table!.findColumnByName("alphanum")!.type.should.be.equal("alphanum"); table!.findColumnByName("alphanum")!.length!.should.be.equal("50"); table!.findColumnByName("shorttext")!.type.should.be.equal("shorttext"); table!.findColumnByName("shorttext")!.length!.should.be.equal("50"); }))); it("all types should work correctly - persist and hydrate when types are not specified on columns", () => Promise.all(connections.map(async connection => { const postRepository = connection.getRepository(PostWithoutTypes); const queryRunner = connection.createQueryRunner(); const table = await queryRunner.getTable("post_without_types"); await queryRunner.release(); const post = new PostWithoutTypes(); post.id = 1; post.name = "Post"; post.boolean = true; // TODO(uki00a) not fully tested yet. post.blob = encoder.encode("This is blob");/* new Buffer("This is blob"); */ post.timestamp = new Date(); await postRepository.save(post); const loadedPost = (await postRepository.findOne(1))!; loadedPost.id.should.be.equal(post.id); loadedPost.name.should.be.equal(post.name); loadedPost.boolean.should.be.equal(post.boolean); loadedPost.blob.toString().should.be.equal(post.blob.toString()); loadedPost.timestamp.valueOf().should.be.equal(post.timestamp.valueOf()); table!.findColumnByName("id")!.type.should.be.equal("integer"); table!.findColumnByName("name")!.type.should.be.equal("nvarchar"); table!.findColumnByName("boolean")!.type.should.be.equal("boolean"); table!.findColumnByName("blob")!.type.should.be.equal("blob"); table!.findColumnByName("timestamp")!.type.should.be.equal("timestamp"); }))); }); runIfMain(import.meta);
the_stack
// Create an account label function createAccountLabels() { const labelName = "INSERT_LABEL_NAME_HERE"; AdsManagerApp.createAccountLabel(labelName); Logger.log("Label with text = '%s' created.", labelName); } // Apply an account label to multiple accounts function applyAccountLabels() { const accountIds = ["INSERT_ACCOUNT_ID_HERE", "INSERT_ACCOUNT_ID_HERE"]; const labelName = "INSERT_LABEL_NAME_HERE"; const accounts = AdsManagerApp.accounts().withIds(accountIds).get(); while (accounts.hasNext()) { const account = accounts.next(); account.applyLabel(labelName); Logger.log('Label with text = "%s" applied to customer id %s.', labelName, account.getCustomerId()); } } // Remove an account label from multiple accounts function removeLabelFromAccounts() { const accountIds = ["INSERT_ACCOUNT_ID_HERE", "INSERT_ACCOUNT_ID_HERE"]; const labelName = "INSERT_LABEL_NAME_HERE"; const accounts = AdsManagerApp.accounts().withIds(accountIds).get(); while (accounts.hasNext()) { const account = accounts.next(); account.removeLabel(labelName); Logger.log('Label with text = "%s" removed from customer id %s.', labelName, account.getCustomerId()); } } // Select an account by label name function selectAccountsByLabelName() { const labelName = "INSERT_LABEL_NAME_HERE"; const accountIterator = AdsManagerApp.accounts() .withCondition("LabelNames CONTAINS '" + labelName + "'") .get(); while (accountIterator.hasNext()) { const account = accountIterator.next(); const accountName = account.getName() ? account.getName() : "--"; Logger.log( "%s,%s,%s,%s", account.getCustomerId(), accountName, account.getTimeZone(), account.getCurrencyCode(), ); } } // Select an account by label ID function selectAccountsByLabelId() { const labelId = "INSERT_LABEL_ID_HERE"; const accountIterator = AdsManagerApp.accounts() .withCondition("LabelIds IN ['" + labelId + "']") .get(); while (accountIterator.hasNext()) { const account = accountIterator.next(); const accountName = account.getName() ? account.getName() : "--"; Logger.log( "%s,%s,%s,%s", account.getCustomerId(), accountName, account.getTimeZone(), account.getCurrencyCode(), ); } } // Retrieve all account labels function getAllAccountLabels() { const labelIterator = AdsManagerApp.accountLabels().get(); while (labelIterator.hasNext()) { const label = labelIterator.next(); Logger.log("Label with id = %s and text = %s was found.", label.getId().toFixed(0), label.getName()); } } // Retrieve an account label by its name function getLabelByName() { const labelName = "INSERT_LABEL_NAME_HERE"; const labelIterator = AdsManagerApp.accountLabels() .withCondition("Name CONTAINS '" + labelName + "'") .get(); while (labelIterator.hasNext()) { const label = labelIterator.next(); Logger.log("Label with id = %s and text = %s was found.", label.getId().toFixed(0), label.getName()); } } // Retrieve account labels by their IDs function getLabelById() { const labelIterator = AdsManagerApp.accountLabels() .withIds([12345, 67890]) // Replace with label IDs here .get(); while (labelIterator.hasNext()) { const label = labelIterator.next(); Logger.log("Label with id = %s and text = '%s' was found.", label.getId().toFixed(0), label.getName()); } } // Get details on the current account function getCurrentAccountDetails() { const currentAccount = AdsApp.currentAccount(); Logger.log( "Customer ID: " + currentAccount.getCustomerId() + ", Currency Code: " + currentAccount.getCurrencyCode() + ", Timezone: " + currentAccount.getTimeZone(), ); const stats = currentAccount.getStatsFor("LAST_MONTH"); Logger.log(stats.getClicks() + " clicks, " + stats.getImpressions() + " impressions last month"); } // Create an ad customizer data source function createAdCustomizerSource() { AdsApp.newAdCustomizerSourceBuilder() .withName("Flowers") .addAttribute("flower", "text") .addAttribute("price", "price") .build(); } // Find an ad customizer data source by name function getAdCustomizerSource() { const sources = AdsApp.adCustomizerSources().get(); while (sources.hasNext()) { const source = sources.next(); if (source.getName() === "Flowers") { Logger.log(source.getName() + " " + source.getAttributes()); } } } // Get a data source's customizer items function getAdCustomizerItems() { const source = AdsApp.adCustomizerSources().get().next(); const items = source.items().get(); while (items.hasNext()) { const item = items.next(); Logger.log(item.getAttributeValues()); } } // Create ad customizers function createAdCustomizers() { const source = AdsApp.newAdCustomizerSourceBuilder() .withName("Flowers") .addAttribute("flower", "text") .addAttribute("price", "price") .build() .getResult(); } // Create text ad with ad customizers function setupCustomizedAd() { // If you have multiple ad groups with the same name, this snippet will // pick an arbitrary matching ad group each time. In such cases, just // filter on the campaign name as well: // // AdsApp.adGroups() // .withCondition('Name = "INSERT_ADGROUP_NAME_HERE"') // .withCondition('CampaignName = "INSERT_CAMPAIGN_NAME_HERE"') const adGroupIterator = AdsApp.adGroups().withCondition('Name = "INSERT_ADGROUP_NAME_HERE"').get(); if (adGroupIterator.hasNext()) { const adGroup = adGroupIterator.next(); // This ad will try to fill in the blanks using the 'flower' and 'price' // attributes from the 'Flower' data source. adGroup .newAd() .expandedTextAdBuilder() .withHeadlinePart1("Flowers for sale") .withHeadlinePart2("Fresh cut {=Flowers.flower}") .withDescription("starting at {=Flowers.price}") .withFinalUrl("http://example.com/flowers") .build(); } } // Add an ad group function addAdGroup() { const campaignIterator = AdsApp.campaigns().withCondition('Name = "INSERT_CAMPAIGN_NAME_HERE"').get(); if (campaignIterator.hasNext()) { const campaign = campaignIterator.next(); const adGroupOperation = campaign.newAdGroupBuilder().withName("INSERT_ADGROUP_NAME_HERE").withCpc(1.2).build(); } } // Update an ad group function updateAdGroup() { const adGroupIterator = AdsApp.adGroups().withCondition('Name = "INSERT_ADGROUP_NAME_HERE"').get(); if (adGroupIterator.hasNext()) { const adGroup = adGroupIterator.next(); adGroup.bidding().setCpc(1.2); // update other properties as required here } } // Get all ad groups function getAlladGroups() { // AdsApp.adGroups() will return all ad groups that are not removed by // default. const adGroupIterator = AdsApp.adGroups().get(); Logger.log("Total adGroups found : " + adGroupIterator.totalNumEntities()); while (adGroupIterator.hasNext()) { const adGroup = adGroupIterator.next(); Logger.log("AdGroup Name: " + adGroup.getName()); } } // Get an ad group by name function getAdGroupByName() { const adGroupIterator = AdsApp.adGroups().withCondition('Name = "INSERT_ADGROUP_NAME_HERE"').get(); if (adGroupIterator.hasNext()) { const adGroup = adGroupIterator.next(); Logger.log("AdGroup Name: " + adGroup.getName()); Logger.log("Enabled: " + adGroup.isEnabled()); } } // Get an ad group's stats function getadGroupstats() { const adGroupIterator = AdsApp.adGroups().withCondition('Name = "INSERT_ADGROUP_NAME_HERE"').get(); if (adGroupIterator.hasNext()) { const adGroup = adGroupIterator.next(); // You can also request reports for pre-defined date ranges. See // https://developers.google.com/adwords/api/docs/guides/awql, // DateRangeLiteral section for possible values. const stats = adGroup.getStatsFor("LAST_MONTH"); Logger.log(adGroup.getName() + ", " + stats.getClicks() + ", " + stats.getImpressions()); } } // Pause an ad group function pauseAdGroup() { const adGroupIterator = AdsApp.adGroups().withCondition('Name = "INSERT_ADGROUP_NAME_HERE"').get(); if (adGroupIterator.hasNext()) { const adGroup = adGroupIterator.next(); adGroup.pause(); Logger.log("AdGroup with name = " + adGroup.getName() + " has paused status : " + adGroup.isPaused()); } } // Get an ad group's device bid modifiers function getAdGroupBidModifiers() { const adGroupIterator = AdsApp.adGroups().withCondition('Name = "INSERT_ADGROUP_NAME_HERE"').get(); if (adGroupIterator.hasNext()) { const adGroup = adGroupIterator.next(); Logger.log("AdGroup name: " + adGroup.getName()); Logger.log("Mobile bid modifier: " + adGroup.devices().getMobileBidModifier()); Logger.log("Tablet bid modifier: " + adGroup.devices().getTabletBidModifier()); Logger.log("Desktop bid modifier: " + adGroup.devices().getDesktopBidModifier()); } } // Create text ad with ad parameters for an ad group function setupAdParamsInAdGroup() { // If you have multiple adGroups with the same name, this snippet will // pick an arbitrary matching ad group each time. In such cases, just // filter on the campaign name as well: // // AdsApp.adGroups() // .withCondition('Name = "INSERT_ADGROUP_NAME_HERE"') // .withCondition('CampaignName = "INSERT_CAMPAIGN_NAME_HERE"') const adGroupIterator = AdsApp.adGroups().withCondition('Name = "INSERT_ADGROUP_NAME_HERE"').get(); if (adGroupIterator.hasNext()) { const adGroup = adGroupIterator.next(); adGroup .newAd() .expandedTextAdBuilder() .withHeadlinePart1("Holiday sale") .withHeadlinePart2("Starts in {param1: a few} days {param2: and} hours!") .withDescription("Everything must go!") .withFinalUrl("http://www.example.com/holidaysales") .build(); const keywordIterator = adGroup.keywords().get(); if (keywordIterator.hasNext()) { const keyword = keywordIterator.next(); // Setup Ad to show as 'Doors open in 5 days, 7 hours!' when searched // using this keyword. If the ad is triggered using a keyword // without ad param, the ad shows as // 'Doors open in a few days, and hours!' keyword.setAdParam(1, "5"); keyword.setAdParam(2, "7"); } } } // Get ad parameters for a keyword function getAdParamsForKeyword() { // If you have multiple adGroups with the same name, this snippet will // pick an arbitrary matching ad group each time. In such cases, just // filter on the campaign name as well: // // AdsApp.adGroups() // .withCondition('Name = "INSERT_ADGROUP_NAME_HERE"') // .withCondition('CampaignName = "INSERT_CAMPAIGN_NAME_HERE"') const adGroupIterator = AdsApp.adGroups().withCondition('Name = "INSERT_ADGROUP_NAME_HERE"').get(); if (adGroupIterator.hasNext()) { const adGroup = adGroupIterator.next(); const keywordIterator = adGroup.keywords().withCondition('Text = "Holiday sales"').get(); if (keywordIterator.hasNext()) { const keyword = keywordIterator.next(); const adParamIterator = keyword.adParams().get(); while (adParamIterator.hasNext()) { const adParam = adParamIterator.next(); } } } } // Add an expanded text ad function addExpandedTextAd() { // If you have multiple adGroups with the same name, this snippet will // pick an arbitrary matching ad group each time. In such cases, just // filter on the campaign name as well: // // AdsApp.adGroups() // .withCondition('Name = "INSERT_ADGROUP_NAME_HERE"') // .withCondition('CampaignName = "INSERT_CAMPAIGN_NAME_HERE"') const adGroupIterator = AdsApp.adGroups().withCondition('Name = "INSERT_ADGROUP_NAME_HERE"').get(); if (adGroupIterator.hasNext()) { const adGroup = adGroupIterator.next(); adGroup .newAd() .expandedTextAdBuilder() .withHeadlinePart1("First headline of ad") .withHeadlinePart2("Second headline of ad") .withDescription("Ad description") .withPath1("path1") .withPath2("path2") .withFinalUrl("http://www.example.com") .build(); // ExpandedTextAdBuilder has additional options. // For more details, see // https://developers.google.com/google-ads/scripts/docs/reference/adsapp/adsapp_expandedtextadbuilder } } // Add an image ad function addImageAd() { // If you have multiple adGroups with the same name, this snippet will // pick an arbitrary matching ad group each time. In such cases, just // filter on the campaign name as well: // // AdsApp.adGroups() // .withCondition('Name = "INSERT_ADGROUP_NAME_HERE"') // .withCondition('CampaignName = "INSERT_CAMPAIGN_NAME_HERE"') const adGroupIterator = AdsApp.adGroups().withCondition('Name = "INSERT_ADGROUP_NAME_HERE"').get(); const mediaIterator = AdsApp.adMedia().media().withCondition('Name = "INSERT_IMAGE_NAME_HERE"').get(); if (adGroupIterator.hasNext() && mediaIterator.hasNext()) { const adGroup = adGroupIterator.next(); const image = mediaIterator.next(); adGroup .newAd() .imageAdBuilder() .withName("Ad name") .withImage(image) .withDisplayUrl("http://www.example.com") .withFinalUrl("http://www.example.com") .build(); // ImageAdBuilder has additional options. // For more details, see // https://developers.google.com/google-ads/scripts/docs/reference/adsapp/adsapp_imageadbuilder } } // Pause ads in an ad group function pauseAdsInAdGroup() { const adGroupIterator = AdsApp.adGroups().withCondition('Name = "INSERT_ADGROUP_NAME_HERE"').get(); if (adGroupIterator.hasNext()) { const adGroup = adGroupIterator.next(); const adsIterator = adGroup.ads().get(); while (adsIterator.hasNext()) { const ad = adsIterator.next(); ad.pause(); } } } // Get expanded text ads in an ad group function getExpandedTextAdsInAdGroup() { const adGroupIterator = AdsApp.adGroups().withCondition('Name = "INSERT_ADGROUP_NAME_HERE"').get(); if (adGroupIterator.hasNext()) { const adGroup = adGroupIterator.next(); const adsIterator = adGroup.ads().withCondition("Type=EXPANDED_TEXT_AD").get(); while (adsIterator.hasNext()) { const ad = adsIterator.next().asType().expandedTextAd(); } } } // Get stats for ads in an ad group function getAdStats() { const adGroupIterator = AdsApp.adGroups().withCondition('Name = "INSERT_ADGROUP_NAME_HERE"').get(); if (adGroupIterator.hasNext()) { const adGroup = adGroupIterator.next(); // If you want to restrict your search to some ads only, then you could // apply a label and retrieve ads as // // const label = AdsApp.labels() // .withCondition('Name="INSERT_LABEL_NAME_HERE"') // .get() // .next(); // const adsIterator = label.ads().get(); const adsIterator = adGroup.ads().get(); while (adsIterator.hasNext()) { const ad = adsIterator.next(); // You can also request reports for pre-defined date ranges. See // https://developers.google.com/adwords/api/docs/guides/awql, // DateRangeLiteral section for possible values. const stats = ad.getStatsFor("LAST_MONTH"); Logger.log(adGroup.getName() + ", " + stats.getClicks() + ", " + stats.getImpressions()); } } } // Get bidding strategies function getBiddingStrategies() { const biddingStrategies = AdsApp.biddingStrategies().get(); while (biddingStrategies.hasNext()) { const biddingStrategy = biddingStrategies.next(); Logger.log( "Bidding strategy with id = %s, name = %s and type = " + "%s was found.", biddingStrategy.getId().toFixed(0), biddingStrategy.getName(), biddingStrategy.getType(), ); } } // Get bidding strategy by name function getBiddingStrategyByName() { const biddingStrategies = AdsApp.biddingStrategies().withCondition('Name="INSERT_BIDDING_STRATEGY_NAME_HERE"').get(); while (biddingStrategies.hasNext()) { const biddingStrategy = biddingStrategies.next(); const stats = biddingStrategy.getStatsFor("LAST_MONTH"); Logger.log( "Bidding strategy with id = %s, name = %s and type = " + "%s was found.", biddingStrategy.getId().toFixed(0), biddingStrategy.getName(), biddingStrategy.getType(), ); Logger.log( "Clicks: %s, Impressions: %s, Cost: %s.", stats.getClicks(), stats.getImpressions(), stats.getCost(), ); } } // Set campaign bidding strategy function setCampaignBiddingStrategy() { const campaign = AdsApp.campaigns().withCondition('Name="INSERT_CAMPAIGN_NAME_HERE"').get().next(); // You may also set a flexible bidding strategy for the campaign // using the setStrategy() method. Use the // AdsApp.biddingStrategies() method to retrieve flexible bidding // strategies in your account. campaign.bidding().setStrategy("MANUAL_CPM"); } // Set an ad group's default CPC bids function setAdGroupDefaultCpcBid() { const adGroup = AdsApp.adGroups() .withCondition('CampaignName = "INSERT_CAMPAIGN_NAME_HERE"') .withCondition('Name = "INSERT_ADGROUP_NAME_HERE"') .get() .next(); // This bid will only be used for auction if a corresponding cpc // bidding strategy is set to the ad group. E.g. // // adGroup.bidding().setStrategy('MANUAL_CPC'); adGroup.bidding().setCpc(3.0); } // Set a keyword's CPC bid function setKeywordCpcBid() { const keyword = AdsApp.keywords() .withCondition('CampaignName = "INSERT_CAMPAIGN_NAME_HERE"') .withCondition('AdGroupName = "INSERT_ADGROUP_NAME_HERE"') .withCondition('KeywordText = "INSERT_KEYWORD_TEXT_HERE"') .get() .next(); // This bid will only be used for auction if a corresponding cpc // bidding strategy is set to the parent ad group. E.g. // // adGroup.bidding().setStrategy('MANUAL_CPC'); keyword.bidding().setCpc(3.0); } // Retrieve base spending limit of budget order function getBaseSpendingLimit() { const budgetOrderIterator = AdsApp.budgetOrders().get(); while (budgetOrderIterator.hasNext()) { const budgetOrder = budgetOrderIterator.next(); let limitText: string | number = ""; if (budgetOrder.getSpendingLimit() === null) { limitText = "unlimited"; } else if (budgetOrder.getTotalAdjustments() === null) { limitText = budgetOrder.getSpendingLimit(); } else { limitText = budgetOrder.getSpendingLimit() - budgetOrder.getTotalAdjustments(); } Logger.log("Budget Order [" + budgetOrder.getName() + "] base spending limit: " + limitText); } } // Retrieve the active budget order function getActiveBudgetOrder() { // There will only be one active budget order at any given time. const budgetOrderIterator = AdsApp.budgetOrders().withCondition('status="ACTIVE"').get(); while (budgetOrderIterator.hasNext()) { const budgetOrder = budgetOrderIterator.next(); Logger.log("Budget Order [" + budgetOrder.getName() + "] is currently active."); } } // Retrieve all budget orders function getAllBudgetOrders() { const budgetOrderIterator = AdsApp.budgetOrders().get(); while (budgetOrderIterator.hasNext()) { const budgetOrder = budgetOrderIterator.next(); Logger.log("Budget Order [" + budgetOrder.getName() + "]"); } } // Set campaign budget function setCampaignBudget() { const campaignIterator = AdsApp.campaigns().withCondition('Name = "INSERT_CAMPAIGN_NAME_HERE"').get(); if (campaignIterator.hasNext()) { const campaign = campaignIterator.next(); campaign.getBudget().setAmount(100); Logger.log("Campaign with name = " + campaign.getName() + " has budget = " + campaign.getBudget().getAmount()); } } // Get campaign budget function getBudgetDetails() { const campaignIterator = AdsApp.campaigns().withCondition('Name = "INSERT_CAMPAIGN_NAME_HERE"').get(); if (campaignIterator.hasNext()) { const campaign = campaignIterator.next(); const budget = campaign.getBudget(); const budgetCampaignIterator = budget.campaigns().get(); Logger.log("Budget amount : " + budget.getAmount()); Logger.log("Delivery method : " + budget.getDeliveryMethod()); Logger.log("Explicitly shared : " + budget.isExplicitlyShared()); Logger.log("Associated campaigns : " + budgetCampaignIterator.totalNumEntities()); Logger.log("Details"); Logger.log("=========="); // Get all the campaigns associated with this budget. There could be // more than one campaign if this is a shared budget. while (budgetCampaignIterator.hasNext()) { const associatedCampaign = budgetCampaignIterator.next(); Logger.log(associatedCampaign.getName()); } } } // Get all campaigns function getAllCampaigns() { // AdsApp.campaigns() will return all campaigns that are not removed by // default. const campaignIterator = AdsApp.campaigns().get(); Logger.log("Total campaigns found : " + campaignIterator.totalNumEntities()); while (campaignIterator.hasNext()) { const campaign = campaignIterator.next(); Logger.log(campaign.getName()); } } // Get a campaign by name function getCampaignsByName() { const campaignIterator = AdsApp.campaigns().withCondition('Name = "INSERT_CAMPAIGN_NAME_HERE"').get(); if (campaignIterator.hasNext()) { const campaign = campaignIterator.next(); Logger.log("Campaign Name: " + campaign.getName()); Logger.log("Enabled: " + campaign.isEnabled()); Logger.log("Bidding strategy: " + campaign.getBiddingStrategyType()); Logger.log("Ad rotation: " + campaign.getAdRotationType()); Logger.log("Start date: " + formatDate(campaign.getStartDate())); Logger.log("End date: " + formatDate(campaign.getEndDate())); } } function formatDate(date: GoogleAdsScripts.AdsApp.GoogleAdsDate) { function zeroPad(number: number) { return Utilities.formatString("%02d", number); } return date === null ? "None" : zeroPad(date.year) + zeroPad(date.month) + zeroPad(date.day); } // Get a campaign's stats function getCampaignStats() { const campaignIterator = AdsApp.campaigns().withCondition('Name = "INSERT_CAMPAIGN_NAME_HERE"').get(); if (campaignIterator.hasNext()) { const campaign = campaignIterator.next(); // You can also request reports for pre-defined date ranges. See // https://developers.google.com/google-ads/scripts/docs/reference/adsapp/adsapp_campaign#getStatsFor_1, // DateRangeLiteral section for possible values. const stats = campaign.getStatsFor("LAST_MONTH"); Logger.log( campaign.getName() + ", " + stats.getClicks() + "clicks, " + stats.getImpressions() + " impressions", ); } } // Add a placement to an existing ad group function addPlacementToAdGroup() { const adGroup = AdsApp.adGroups() .withCondition("Name = 'INSERT_ADGROUP_NAME_HERE'") .withCondition('CampaignName = "INSERT_CAMPAIGN_NAME_HERE"') .get() .next(); // Other display criteria can be built in a similar manner using the // corresponding builder method in the AdsApp.Display, // AdsApp.CampaignDisplay or AdsApp.AdGroupDisplay class. const placementOperation = adGroup .display() .newPlacementBuilder() .withUrl("http://www.site.com") // required .withCpc(0.5) // optional .build(); const placement = placementOperation.getResult(); } // Retrieve all topics in an existing ad group function getAllTopics() { const adGroup = AdsApp.adGroups() .withCondition('Name = "INSERT_ADGROUP_NAME_HERE"') .withCondition('CampaignName = "INSERT_CAMPAIGN_NAME_HERE"') .get() .next(); // Other display criteria can be retrieved in a similar manner using // the corresponding selector methods in the AdsApp.Display, // AdsApp.CampaignDisplay or AdsApp.AdGroupDisplay class. const topicIterator = AdsApp.display() .topics() .withCondition("Impressions > 100") .forDateRange("LAST_MONTH") .orderBy("Clicks DESC") .get(); while (topicIterator.hasNext()) { const topic = topicIterator.next(); // The list of all topic IDs can be found on // https://developers.google.com/adwords/api/docs/appendix/verticals Logger.log( "Topic with criterion id = %s and topic id = %s was " + "found.", topic.getId().toFixed(0), topic.getTopicId().toFixed(0), ); } } // Get stats for all audiences in an existing ad group function getAudienceStats() { const adGroup = AdsApp.adGroups() .withCondition('Name = "INSERT_ADGROUP_NAME_HERE"') .withCondition('CampaignName = "INSERT_CAMPAIGN_NAME_HERE"') .get() .next(); // Other display criteria can be retrieved in a similar manner using // the corresponding selector methods in the AdsApp.Display, // AdsApp.CampaignDisplay or AdsApp.AdGroupDisplay class. const audienceIterator = adGroup.display().audiences().get(); Logger.log("ID, Audience ID, Clicks, Impressions, Cost"); while (audienceIterator.hasNext()) { const audience = audienceIterator.next(); const stats = audience.getStatsFor("LAST_MONTH"); // User List IDs (List IDs) are available on the details page of // a User List (found under the Audiences section of the Shared // Library) Logger.log( "%s, %s, %s, %s, %s", audience.getId().toFixed(0), audience.getAudienceId(), stats.getClicks(), stats.getImpressions(), stats.getCost(), ); } } // Create a draft campaign function createDraft() { const campaign = AdsApp.campaigns().withCondition("Name = 'INSERT_CAMPAIGN_NAME_HERE'").get().next(); const draftBuilder = campaign.newDraftBuilder().withName("INSERT_NEW_DRAFT_NAME_HERE").build(); const draft = draftBuilder.getResult(); } // Get draft campaigns function getDrafts() { // Get all drafts. const drafts = AdsApp.drafts().get(); Logger.log(drafts.totalNumEntities()); while (drafts.hasNext()) { const draft = drafts.next(); Logger.log("Draft: " + draft.getName()); } // Get a specific draft. const campaignIterator = AdsApp.drafts().withCondition("DraftName = 'INSERT_DRAFT_NAME'").get(); while (campaignIterator.hasNext()) { Logger.log(campaignIterator.next().getName()); } } // Create an experiment function createExperiment() { const draft = AdsApp.drafts().withCondition("DraftName = INSERT_DRAFT_NAME").get().next(); const experimentBuilder = draft.newExperimentBuilder(); experimentBuilder.withName("INSERT_NEW_EXPERIMENT_NAME_HERE").withTrafficSplitPercent(50).startBuilding(); } // Get experiments function getExperiments() { // Get all experiments. const exps = AdsApp.experiments().get(); Logger.log(exps.totalNumEntities()); while (exps.hasNext()) { const exp = exps.next(); Logger.log("Experiment: " + exp.getName()); } // Get specific experiment. const campaignIterator = AdsApp.experiments().withCondition("Name = 'INSERT_EXPERIMENT_NAME'").get(); while (campaignIterator.hasNext()) { Logger.log(campaignIterator.next().getName()); } } // Show all the shared excluded placements in an excluded placement list function showAllExcludedPlacementsFromList() { const EXCLUDED_PLACEMENT_LIST_NAME = "INSERT_LIST_NAME_HERE"; const excludedPlacementListIterator = AdsApp.excludedPlacementLists() .withCondition('Name = "' + EXCLUDED_PLACEMENT_LIST_NAME + '"') .get(); if (excludedPlacementListIterator.totalNumEntities() === 1) { const excludedPlacementList = excludedPlacementListIterator.next(); const sharedExcludedPlacementIterator = excludedPlacementList.excludedPlacements().get(); while (sharedExcludedPlacementIterator.hasNext()) { const sharedExcludedPlacement = sharedExcludedPlacementIterator.next(); Logger.log(sharedExcludedPlacement.getUrl()); } } } // Add a keyword to an existing ad group function addKeyword() { // If you have multiple adGroups with the same name, this snippet will // pick an arbitrary matching ad group each time. In such cases, just // filter on the campaign name as well: // // AdsApp.adGroups() // .withCondition('Name = "INSERT_ADGROUP_NAME_HERE"') // .withCondition('CampaignName = "INSERT_CAMPAIGN_NAME_HERE"') const adGroupIterator = AdsApp.adGroups().withCondition('Name = "INSERT_ADGROUP_NAME_HERE"').get(); if (adGroupIterator.hasNext()) { const adGroup = adGroupIterator.next(); adGroup .newKeywordBuilder() .withText("Hello world") .withCpc(1.25) // Optional .withFinalUrl("http://www.example.com") // Optional .build(); // KeywordBuilder has a number of other options. For more details see // https://developers.google.com/google-ads/scripts/docs/reference/adsapp/adsapp_keywordbuilder } } // Pause an existing keyword in an ad group function pauseKeywordInAdGroup() { const adGroupIterator = AdsApp.adGroups().withCondition('Name = "INSERT_ADGROUP_NAME_HERE"').get(); if (adGroupIterator.hasNext()) { const adGroup = adGroupIterator.next(); const keywordIterator = adGroup.keywords().withCondition('Text="INSERT_KEYWORDS_HERE"').get(); while (keywordIterator.hasNext()) { const keyword = keywordIterator.next(); keyword.pause(); } } } // Get all keywords in an ad group function getKeywordsInAdGroup() { const keywordIterator = AdsApp.keywords().withCondition('AdGroupName = "INSERT_ADGROUP_NAME_HERE"').get(); if (keywordIterator.hasNext()) { while (keywordIterator.hasNext()) { const keyword = keywordIterator.next(); } } } // Get stats for all keywords in an ad group function getKeywordStats() { const adGroupIterator = AdsApp.adGroups().withCondition('Name = "INSERT_ADGROUP_NAME_HERE"').get(); if (adGroupIterator.hasNext()) { const adGroup = adGroupIterator.next(); const keywordIterator = adGroup.keywords().get(); while (keywordIterator.hasNext()) { const keyword = keywordIterator.next(); // You can also request reports for pre-defined date ranges. See // https://developers.google.com/adwords/api/docs/guides/awql, // DateRangeLiteral section for possible values. const stats = keyword.getStatsFor("LAST_MONTH"); Logger.log( adGroup.getName() + ", " + keyword.getText() + ", " + stats.getClicks() + ", " + stats.getImpressions(), ); } } } // Get all labels from a user's account function getAllLabels() { const labelIterator = AdsApp.labels().get(); while (labelIterator.hasNext()) { const label = labelIterator.next(); Logger.log(label.getName()); } } // Get a label by name function getLabelsByName() { const labelIterator = AdsApp.labels().withCondition('Name = "INSERT_LABEL_NAME_HERE"').get(); if (labelIterator.hasNext()) { const label = labelIterator.next(); Logger.log("Name: " + label.getName()); Logger.log("Description: " + label.getDescription()); Logger.log("Color: " + label.getColor()); Logger.log("Number of campaigns: " + label.campaigns().get().totalNumEntities()); Logger.log("Number of ad groups: " + label.adGroups().get().totalNumEntities()); Logger.log("Number of ads: " + label.ads().get().totalNumEntities()); Logger.log("Number of keywords: " + label.keywords().get().totalNumEntities()); } } // Apply a label to a campaign function applyLabel() { // Retrieve a campaign, and apply a label to it. Applying labels to other // object types are similar. const campaignIterator = AdsApp.campaigns().withCondition('Name = "INSERT_CAMPAIGN_NAME_HERE"').get(); if (campaignIterator.hasNext()) { const campaign = campaignIterator.next(); campaign.applyLabel("Test"); } } // Remove a label from a campaign function removeLabel() { const campaignIterator = AdsApp.campaigns().withCondition('Name = "INSERT_CAMPAIGN_NAME_HERE"').get(); if (campaignIterator.hasNext()) { const campaign = campaignIterator.next(); campaign.removeLabel("Test"); } } // Construct a new negative keyword list and add it to a campaign function addNegativeKeywordListToCampaign() { const NEGATIVE_KEYWORD_LIST_NAME = "INSERT_LIST_NAME_HERE"; const CAMPAIGN_NAME = "INSERT_CAMPAIGN_NAME_HERE"; const negativeKeywordListOperator = AdsApp.newNegativeKeywordListBuilder() .withName(NEGATIVE_KEYWORD_LIST_NAME) .build(); if (negativeKeywordListOperator.isSuccessful()) { const negativeKeywordList = negativeKeywordListOperator.getResult(); if (!negativeKeywordList) return; negativeKeywordList.addNegativeKeywords([ "broad match keyword", '"phrase match keyword"', "[exact match keyword]", ]); const campaign = AdsApp.campaigns() .withCondition('Name = "' + CAMPAIGN_NAME + '"') .get() .next(); campaign.addNegativeKeywordList(negativeKeywordList); } else { Logger.log("Could not add Negative Keyword List."); } } // Add negative keyword to a campaign function addNegativeKeywordToCampaign() { const campaignIterator = AdsApp.campaigns().withCondition('Name = "INSERT_CAMPAIGN_NAME_HERE"').get(); if (campaignIterator.hasNext()) { const campaign = campaignIterator.next(); campaign.createNegativeKeyword("[Budget hotels]"); } } // Get negative keywords in a campaign function getNegativeKeywordForCampaign() { const campaignIterator = AdsApp.campaigns().withCondition('Name = "INSERT_CAMPAIGN_NAME_HERE"').get(); if (campaignIterator.hasNext()) { const campaign = campaignIterator.next(); const negativeKeywordIterator = campaign.negativeKeywords().get(); while (negativeKeywordIterator.hasNext()) { const negativeKeyword = negativeKeywordIterator.next(); Logger.log("Text: " + negativeKeyword.getText() + ", MatchType: " + negativeKeyword.getMatchType()); } } } // Add a negative keyword to an ad group function addNegativeKeywordToAdGroup() { // If you have multiple ad groups with the same name, this snippet will // pick an arbitrary matching ad group each time. In such cases, just // filter on the campaign name as well: // // AdsApp.adGroups() // .withCondition('Name = "INSERT_ADGROUP_NAME_HERE"') // .withCondition('CampaignName = "INSERT_CAMPAIGN_NAME_HERE"') const adGroupIterator = AdsApp.adGroups().withCondition('Name = "INSERT_ADGROUP_NAME_HERE"').get(); if (adGroupIterator.hasNext()) { const adGroup = adGroupIterator.next(); adGroup.createNegativeKeyword("[Budget hotels]"); } } // Get negative keywords in an ad group function getNegativeKeywordForAdGroup() { // If you have multiple ad groups with the same name, this snippet will // pick an arbitrary matching ad group each time. In such cases, just // filter on the campaign name as well: // // AdsApp.adGroups() // .withCondition('Name = "INSERT_ADGROUP_NAME_HERE"') // .withCondition('CampaignName = "INSERT_CAMPAIGN_NAME_HERE"') const adGroupIterator = AdsApp.adGroups().withCondition('Name = "INSERT_ADGROUP_NAME_HERE"').get(); if (adGroupIterator.hasNext()) { const adGroup = adGroupIterator.next(); const negativeKeywordIterator = adGroup.negativeKeywords().get(); while (negativeKeywordIterator.hasNext()) { const negativeKeyword = negativeKeywordIterator.next(); Logger.log("Text: " + negativeKeyword.getText() + ", MatchType: " + negativeKeyword.getMatchType()); } } } // Add search audience to an ad group function addSearchAudienceToAdGroup() { const AUDIENCE_LIST_ID = 1; // INSERT_AUDIENCE_ID_HERE const CAMPAIGN_NAME = "INSERT_CAMPAIGN_NAME_HERE"; const ADGROUP_NAME = "INSERT_ADGROUP_NAME_HERE"; // Retrieve the ad group. const adGroup = AdsApp.adGroups() .withCondition('Name = "' + ADGROUP_NAME + '"') .withCondition('CampaignName = "' + CAMPAIGN_NAME + '"') .get() .next(); // Create the search audience. const searchAudience = adGroup .targeting() .newUserListBuilder() .withAudienceId(AUDIENCE_LIST_ID) .withBidModifier(1.3) .build() .getResult(); if (!searchAudience) return; // Display the results. Logger.log( "Search audience with name = %s and ID = %s was added to ad " + "group ID: %s", searchAudience.getName(), searchAudience.getId().toFixed(0), adGroup.getId().toFixed(0), ); } // Get ad group search audience by name function getAdGroupSearchAudienceByName() { const CAMPAIGN_NAME = "INSERT_CAMPAIGN_NAME_HERE"; const ADGROUP_NAME = "INSERT_ADGROUP_NAME_HERE"; const AUDIENCE_NAME = "INSERT_AUDIENCE_NAME_HERE"; // Retrieve the search audience. const searchAudience = AdsApp.adGroupTargeting() .audiences() .withCondition("CampaignName = " + CAMPAIGN_NAME) .withCondition("AdGroupName = " + ADGROUP_NAME) .withCondition('UserListName = "' + AUDIENCE_NAME + '"') .get() .next(); // Display the results. Logger.log( "Search audience with name = %s and ID = %s was found.", searchAudience.getName(), searchAudience.getId(), ); } // Filter ad group search audience by stats function filterAdGroupAudienceByStats() { const CAMPAIGN_NAME = "INSERT_CAMPAIGN_NAME_HERE"; const ADGROUP_NAME = "INSERT_ADGROUP_NAME_HERE"; // Retrieve top performing search audiences. const topPerformingAudiences = AdsApp.adGroupTargeting() .audiences() .withCondition("CampaignName = " + CAMPAIGN_NAME) .withCondition("AdGroupName = " + ADGROUP_NAME) .withCondition("Clicks > 30") .forDateRange("LAST_MONTH") .get(); while (topPerformingAudiences.hasNext()) { const audience = topPerformingAudiences.next(); Logger.log( "Search audience with ID = %s, name = %s and audience list " + "ID = %s has %s clicks.", audience.getId().toFixed(0), audience.getName(), audience.getAudienceId(), audience.getStatsFor("THIS_MONTH").getClicks(), ); } } // Exclude search audience from a campaign function addExcludedAudienceToCampaign() { const CAMPAIGN_NAME = ""; // INSERT_CAMPAIGN_NAME_HERE const AUDIENCE_LIST_ID = 0; // INSERT_AUDIENCE_ID_HERE // Retrieve the campaign. const campaign = AdsApp.campaigns() .withCondition('Name = "' + CAMPAIGN_NAME + '"') .get() .next(); // Create the excluded audience. const audience = campaign.targeting().newUserListBuilder().withAudienceId(AUDIENCE_LIST_ID).exclude().getResult(); if (!audience) return; Logger.log( "Excluded audience with ID = %s and audience list ID = %s was " + 'created for campaign: "%s".', audience.getId(), audience.getAudienceId(), campaign.getName(), ); } // Get excluded search audiences for a campaign function getExcludedAudiencesForCampaign() { const CAMPAIGN_NAME = ""; // INSERT_CAMPAIGN_NAME_HERE // Retrieve the campaign. const campaign = AdsApp.campaigns() .withCondition('Name = "' + CAMPAIGN_NAME + '"') .get() .next(); const excludedAudiences = campaign.targeting().excludedAudiences().get(); while (excludedAudiences.hasNext()) { const audience = excludedAudiences.next(); Logger.log( "Excluded audience with ID = %s, name = %s and audience list " + "ID = %s was found.", audience.getId(), audience.getName(), audience.getAudienceId(), ); } } // Set AdGroup targeting setting function setAdGroupTargetSetting() { const CAMPAIGN_NAME = "INSERT_CAMPAIGN_NAME_HERE"; const ADGROUP_NAME = "INSERT_ADGROUP_NAME_HERE"; // Retrieve the ad group. const adGroup = AdsApp.adGroups() .withCondition('Name = "' + ADGROUP_NAME + '"') .withCondition('CampaignName = "' + CAMPAIGN_NAME + '"') .get() .next(); // Change the target setting to TARGET_ALL. adGroup.targeting().setTargetingSetting("USER_INTEREST_AND_LIST", "TARGET_ALL_TRUE"); } // Update audience bid modifier function updateAudienceBidModifer() { const CAMPAIGN_NAME = "INSERT_CAMPAIGN_NAME_HERE"; const ADGROUP_NAME = "INSERT_ADGROUP_NAME_HERE"; const AUDIENCE_NAME = "INSERT_AUDIENCE_NAME_HERE"; // Create the search audience. const searchAudience = AdsApp.adGroupTargeting() .audiences() .withCondition("CampaignName = " + CAMPAIGN_NAME) .withCondition("AdGroupName = " + ADGROUP_NAME) .withCondition('UserListName = "' + AUDIENCE_NAME + '"') .get() .next(); searchAudience.bidding().setBidModifier(1.6); // Display the results. Logger.log( 'Bid modifier for Search Audience with Name = "%s" in ' + 'Ad Group ID: "%s" was set to %s.', searchAudience.getName(), searchAudience.getAdGroup().getId().toFixed(0), searchAudience.bidding().getBidModifier(), ); } // Retrieve all shopping campaigns function getAllShoppingCampaigns() { const retval = []; const campaignIterator = AdsApp.shoppingCampaigns().get(); while (campaignIterator.hasNext()) { const campaign = campaignIterator.next(); // Optional: Comment out if you don't need to print details. Logger.log("Campaign Name: %s", campaign.getName()); retval.push(campaign); } return retval; } // Retrieve a shopping campaign by its name function getShoppingCampaignByName(campaignName: string) { const campaignIterator = AdsApp.shoppingCampaigns() .withCondition("CampaignName = '" + campaignName + "'") .get(); while (campaignIterator.hasNext()) { const campaign = campaignIterator.next(); Logger.log("Campaign Name: %s", campaign.getName()); } } // Retrieve a shopping adgroup by its name function getShoppingAdGroup() { const campaignName = "INSERT_CAMPAIGN_NAME_HERE"; const adGroupName = "INSERT_ADGROUP_NAME_HERE"; const adGroupIterator = AdsApp.shoppingAdGroups() .withCondition("CampaignName = '" + campaignName + "' and AdGroupName = '" + adGroupName + "'") .get(); while (adGroupIterator.hasNext()) { const adGroup = adGroupIterator.next(); Logger.log( "AdGroup Name: %s, CPC = %s, Mobile Bid " + "Modifier = %s", adGroup.getName(), adGroup.bidding().getCpc(), adGroup.devices().getMobileBidModifier(), ); } } // Create a shopping ad group function createShoppingAdGroup() { const campaignName = "INSERT_CAMPAIGN_NAME_HERE"; const shoppingCampaign = AdsApp.shoppingCampaigns() .withCondition("CampaignName = '" + campaignName + "'") .get() .next(); const adGroupOperation = shoppingCampaign.newAdGroupBuilder().build(); const adGroup = adGroupOperation.getResult(); Logger.log(adGroup); } // Create a shopping product group hierarchy function createTree() { const campaignName = "INSERT_CAMPAIGN_NAME_HERE"; const adGroupName = "INSERT_ADGROUP_NAME_HERE"; const shoppingAdGroup = AdsApp.shoppingAdGroups() .withCondition("CampaignName = '" + campaignName + "' and AdGroupName = '" + adGroupName + "'") .get() .next(); const root = shoppingAdGroup.rootProductGroup(); // The structure created is // - root // - cardcow brand // - New // - Refurbished // - Other conditions // - Other brands // Add a brand product group for "cardcow" under root product group. const brandNode = root.newChild().brandBuilder().withName("cardcow").withBid(1.2).build().getResult(); if (!brandNode) return; // Add new conditions for New and Refurbished cardcow brand items. const newItems = brandNode.newChild().conditionBuilder().withCondition("NEW").build().getResult(); const refurbishedItems = brandNode .newChild() .conditionBuilder() .withCondition("REFURBISHED") .withBid(0.9) .build() .getResult(); } // Traverses the product group hierarchy function walkProductPartitionTree() { const campaignName = "INSERT_CAMPAIGN_NAME_HERE"; const adGroupName = "INSERT_ADGROUP_NAME_HERE"; const shoppingAdGroup = AdsApp.shoppingAdGroups() .withCondition("CampaignName = '" + campaignName + "' and AdGroupName = '" + adGroupName + "'") .get() .next(); const root = shoppingAdGroup.rootProductGroup(); walkHierarchy(root, 0); } function walkHierarchy(productGroup: GoogleAdsScripts.AdsApp.ProductGroup, level: number) { let description = ""; if (productGroup.isOtherCase()) { description = "Other"; } else if (productGroup.getDimension() === "CATEGORY") { // Shows how to process a product group differently based on its type. description = productGroup.asCategory().getName(); } else { description = productGroup.getValue(); } const padding = new Array(level + 1).join("-"); // Note: Child product groups may not have a max cpc if it has been excluded. Logger.log( "%s %s, %s, %s, %s, %s", padding, description, productGroup.getDimension(), productGroup.getMaxCpc(), productGroup.isOtherCase(), productGroup.getId().toFixed(), ); const childProductGroups = productGroup.children().get(); while (childProductGroups.hasNext()) { const childProductGroup = childProductGroups.next(); walkHierarchy(childProductGroup, level + 1); } } // Gets the 'Everything else' product group function getEverythingElseProductGroup() { const campaignName = "INSERT_CAMPAIGN_NAME_HERE"; const adGroupName = "INSERT_ADGROUP_NAME_HERE"; const shoppingAdGroup = AdsApp.shoppingAdGroups() .withCondition("CampaignName = '" + campaignName + "' and AdGroupName = '" + adGroupName + "'") .get() .next(); const rootProductGroup = shoppingAdGroup.rootProductGroup(); const childProductGroups = rootProductGroup.children().get(); while (childProductGroups.hasNext()) { const childProductGroup = childProductGroups.next(); if (childProductGroup.isOtherCase()) { // Note: Child product groups may not have a max cpc if it has been // excluded. Logger.log( '"Everything else" product group found. Type of the product ' + "group is %s and bid is %s.", childProductGroup.getDimension(), childProductGroup.getMaxCpc(), ); return; } } Logger.log('"Everything else" product group not found under root ' + "product group."); } // Update bids for product groups function updateProductGroupBid() { const productGroups = AdsApp.productGroups() .withCondition("Clicks > 5") .withCondition("Ctr > 0.01") .forDateRange("LAST_MONTH") .get(); while (productGroups.hasNext()) { const productGroup = productGroups.next(); productGroup.setMaxCpc(productGroup.getMaxCpc() + 0.01); } } // Retrieve product ads function getProductAds() { const adGroupName = "INSERT_ADGROUP_NAME_HERE"; const shoppingAdGroup = AdsApp.shoppingAdGroups() .withCondition("AdGroupName = '" + adGroupName + "'") .get() .next(); const productAds = shoppingAdGroup.ads().get(); while (productAds.hasNext()) { const productAd = productAds.next(); Logger.log("Ad with ID = %s was found.", productAd.getId().toFixed(0)); } } // Create product ads function createProductAd() { const adGroupName = "INSERT_ADGROUP_NAME_HERE"; const shoppingAdGroup = AdsApp.shoppingAdGroups() .withCondition("AdGroupName = '" + adGroupName + "'") .get() .next(); const adOperation = shoppingAdGroup.newAdBuilder().withMobilePreferred(true).build(); const productAd = adOperation.getResult(); if (!productAd) return; Logger.log("Ad with ID = %s was created.", productAd.getId().toFixed(0)); } // Retrieve all user lists function getAllUserLists() { const userlistIt = AdsApp.userlists().get(); while (userlistIt.hasNext()) { const userList = userlistIt.next(); Logger.log("Name: " + userList.getName() + " Type: " + userList.getType() + " ID: " + userList.getId()); Logger.log( " Desc: " + userList.getDescription() + " IsOpen: " + userList.isOpen() + " MembershipLifeSpan: " + userList.getMembershipLifeSpan(), ); Logger.log( " SizeForDisplay: " + userList.getSizeForDisplay() + " SizeRangeForDisplay: " + userList.getSizeRangeForDisplay(), ); Logger.log( " SizeForSearch: " + userList.getSizeForSearch() + " SizeRangeForSearch: " + userList.getSizeRangeForSearch(), ); Logger.log( " IsReadOnly: " + userList.isReadOnly() + " IsEligibleForSearch: " + userList.isEligibleForSearch() + " IsEligibleForDisplay: " + userList.isEligibleForDisplay(), ); Logger.log(" "); } } // Get the number of members in a user list function getUserListMemberCount() { const iterator = AdsApp.userlists().get(); while (iterator.hasNext()) { const userlist = iterator.next(); Logger.log( "User List [" + userlist.getName() + "] has " + userlist.getSizeForDisplay() + " members for Search campaigns and " + userlist.getSizeRangeForDisplay() + " members for Display campaigns.", ); } } // Open a user list function openUserLists() { const iterator = AdsApp.userlists().get(); while (iterator.hasNext()) { const userlist = iterator.next(); if (userlist.isClosed()) { userlist.open(); } } } // Retrieve search campaigns targeted by a user list function getSearchCampaignsTargetedByUserList() { const userlistIterator = AdsApp.userlists().get(); while (userlistIterator.hasNext()) { const userList = userlistIterator.next(); const campaignIterator = userList.targetedCampaigns().get(); const campaignNames = []; while (campaignIterator.hasNext()) { const campaign = campaignIterator.next(); campaignNames.push(campaign.getName()); } Logger.log("User List [" + userList.getName() + "] is targeting [ " + campaignNames.join(",") + "]"); } } // Retrieve all video campaigns function getAllVideoCampaigns() { // AdsApp.videoCampaigns() will return all campaigns that are not // removed by default. const videoCampaigns = []; const videoCampaignIterator = AdsApp.videoCampaigns().get(); Logger.log("Total campaigns found : " + videoCampaignIterator.totalNumEntities()); while (videoCampaignIterator.hasNext()) { const videoCampaign = videoCampaignIterator.next(); Logger.log(videoCampaign.getName()); videoCampaigns.push(videoCampaign); } return videoCampaigns; } // Retrieve a video campaign by its name function getVideoCampaignByName() { const videoCampaignIterator = AdsApp.videoCampaigns().withCondition('Name = "INSERT_CAMPAIGN_NAME_HERE"').get(); if (videoCampaignIterator.hasNext()) { const videoCampaign = videoCampaignIterator.next(); Logger.log("Campaign Name: " + videoCampaign.getName()); Logger.log("Enabled: " + videoCampaign.isEnabled()); Logger.log("Bidding strategy: " + videoCampaign.getBiddingStrategyType()); Logger.log("Ad rotation: " + videoCampaign.getAdRotationType()); Logger.log("Start date: " + formatDate(videoCampaign.getStartDate())); Logger.log("End date: " + formatDate(videoCampaign.getEndDate())); return videoCampaign; } return null; } // Retrieve a video campaign's stats function getVideoCampaignStats() { const videoCampaignIterator = AdsApp.videoCampaigns().withCondition('Name = "INSERT_CAMPAIGN_NAME_HERE"').get(); if (videoCampaignIterator.hasNext()) { const videoCampaign = videoCampaignIterator.next(); // Fetch stats for the last month. See the DateRangeLiteral section at // https://developers.google.com/adwords/api/docs/guides/awql#formal_grammar // for a list of all supported pre-defined date ranges. // Note: Reports can also be used to fetch stats. See // https://developers.google.com/google-ads/scripts/docs/features/reports // for more information. const stats = videoCampaign.getStatsFor("LAST_MONTH"); Logger.log( videoCampaign.getName() + ", " + stats.getImpressions() + " impressions, " + stats.getViews() + " views", ); return stats; } return null; } // Pause a video campaign function pauseVideoCampaign() { const videoCampaignIterator = AdsApp.videoCampaigns().withCondition('Name = "INSERT_CAMPAIGN_NAME_HERE"').get(); if (videoCampaignIterator.hasNext()) { const videoCampaign = videoCampaignIterator.next(); videoCampaign.pause(); } } // Add a video ad group function addVideoAdGroup() { const videoCampaignIterator = AdsApp.videoCampaigns().withCondition('Name = "INSERT_CAMPAIGN_NAME_HERE"').get(); if (videoCampaignIterator.hasNext()) { const videoCampaign = videoCampaignIterator.next(); const videoAdGroupOperation = videoCampaign .newVideoAdGroupBuilder() .withName("INSERT_ADGROUP_NAME_HERE") // This can also be 'TRUE_VIEW_IN_DISPLAY' .withAdGroupType("TRUE_VIEW_IN_STREAM") .withCpv(1.2) .build(); } } // Update a video ad group function updateVideoAdGroup() { const videoAdGroupIterator = AdsApp.videoAdGroups().withCondition('Name = "INSERT_ADGROUP_NAME_HERE"').get(); if (videoAdGroupIterator.hasNext()) { const videoAdGroup = videoAdGroupIterator.next(); videoAdGroup.bidding().setCpv(1.2); // update other properties as required here } } // Retrieve all video ad groups function getAllVideoAdGroups() { // AdsApp.videoAdGroups() will return all ad groups that are not removed by // default. const videoAdGroups = []; const videoAdGroupIterator = AdsApp.videoAdGroups().get(); Logger.log("Total adGroups found : " + videoAdGroupIterator.totalNumEntities()); while (videoAdGroupIterator.hasNext()) { const videoAdGroup = videoAdGroupIterator.next(); Logger.log("AdGroup Name: " + videoAdGroup.getName() + ", AdGroup Type: " + videoAdGroup.getAdGroupType()); videoAdGroups.push(videoAdGroup); } return videoAdGroups; } // Retrieve a video ad group by name function getVideoAdGroupByName() { const videoAdGroupIterator = AdsApp.videoAdGroups().withCondition('Name = "INSERT_ADGROUP_NAME_HERE"').get(); if (videoAdGroupIterator.hasNext()) { const videoAdGroup = videoAdGroupIterator.next(); Logger.log("AdGroup Name: " + videoAdGroup.getName()); Logger.log("AdGroup Type: " + videoAdGroup.getAdGroupType()); Logger.log("Enabled: " + videoAdGroup.isEnabled()); return videoAdGroup; } return null; } // Retrieve a video ad group's stats function getVideoAdGroupStats() { const videoAdGroupIterator = AdsApp.videoAdGroups().withCondition('Name = "INSERT_ADGROUP_NAME_HERE"').get(); if (videoAdGroupIterator.hasNext()) { const videoAdGroup = videoAdGroupIterator.next(); // You can also request reports for pre-defined date ranges. See // https://developers.google.com/adwords/api/docs/guides/awql, // DateRangeLiteral section for possible values. const stats = videoAdGroup.getStatsFor("LAST_MONTH"); Logger.log(videoAdGroup.getName() + ", " + stats.getImpressions() + ", " + stats.getViews()); return stats; } return null; } // Pause a video ad group function pauseVideoAdGroup() { const videoAdGroupIterator = AdsApp.videoAdGroups().withCondition('Name = "INSERT_ADGROUP_NAME_HERE"').get(); if (videoAdGroupIterator.hasNext()) { const videoAdGroup = videoAdGroupIterator.next(); videoAdGroup.pause(); Logger.log("AdGroup with name: " + videoAdGroup.getName() + " has paused status: " + videoAdGroup.isPaused()); } } // Retrieve any video for use in an ad function getVideo() { // This will just get the first valid YouTube video in the account. // It demonstrates how to filter to see if a video is valid for video ads. const videos = AdsApp.adMedia().media().withCondition("Type = VIDEO").get(); let video = null; while (videos.hasNext()) { video = videos.next(); // You have to use a YouTube video for True View ads, so only return if // the YouTubeVideoId exists. if (video.getYouTubeVideoId()) { return video; } } return null; } // Retrieve a specific video for use in an ad function getVideoByYouTubeId() { // You can filter on the YouTubeVideoId if you already have that video in // your account to fetch the exact one you want right away. const videos = AdsApp.adMedia().media().withCondition("Type = VIDEO AND YouTubeVideoId = ABCDEFGHIJK").get(); if (videos.hasNext()) { return videos.next(); } return null; } // Add an in-stream video ad function addInStreamVideoAd() { // If you have multiple adGroups with the same name, this snippet will // pick an arbitrary matching ad group each time. In such cases, just // filter on the campaign name as well: // // AdsApp.videoAdGroups() // .withCondition('Name = "INSERT_ADGROUP_NAME_HERE"') // .withCondition('CampaignName = "INSERT_CAMPAIGN_NAME_HERE"') const videoAdGroupIterator = AdsApp.videoAdGroups().withCondition('Name = "INSERT_ADGROUP_NAME_HERE"').get(); const video = getVideo(); // Defined above if (!video) return; if (videoAdGroupIterator.hasNext()) { const videoAdGroup = videoAdGroupIterator.next(); videoAdGroup .newVideoAd() .inStreamAdBuilder() .withAdName("In Stream Ad") .withDisplayUrl("http://www.example.com") .withFinalUrl("http://www.example.com") .withVideo(video) .build(); } } // Add video discovery ad function addVideoDiscoveryAd() { const videoAdGroupIterator = AdsApp.videoAdGroups().withCondition('Name = "INSERT_ADGROUP_NAME_HERE"').get(); const video = getVideo(); // Defined above if (!video) return; if (videoAdGroupIterator.hasNext()) { const videoAdGroup = videoAdGroupIterator.next(); videoAdGroup .newVideoAd() .videoDiscoveryAdBuilder() .withAdName("Video Discovery Ad") .withDescription1("Description line 1") .withDescription2("Description line 2") .withHeadline("Headline") .withThumbnail("THUMBNAIL1") .withDestinationPage("WATCH") .withVideo(video) .build(); } } // Pause video ads in video ad group function pauseVideoAdsInVideoAdGroup() { const videoAdGroupIterator = AdsApp.videoAdGroups().withCondition('Name = "INSERT_ADGROUP_NAME_HERE"').get(); if (videoAdGroupIterator.hasNext()) { const videoAdGroup = videoAdGroupIterator.next(); const videoAdsIterator = videoAdGroup.videoAds().get(); while (videoAdsIterator.hasNext()) { const videoAd = videoAdsIterator.next(); videoAd.pause(); } } } // Retrieve video ads in video ad group function getInStreamAdsInVideoAdGroup() { const videoAds = []; const videoAdGroupIterator = AdsApp.videoAdGroups().withCondition('Name = "INSERT_ADGROUP_NAME_HERE"').get(); if (videoAdGroupIterator.hasNext()) { const videoAdGroup = videoAdGroupIterator.next(); const videoAdsIterator = videoAdGroup.videoAds().withCondition('Type="TRUE_VIEW_IN_STREAM_VIDEO_AD"').get(); while (videoAdsIterator.hasNext()) { const videoAd = videoAdsIterator.next(); videoAds.push(videoAd); } } return videoAds; } // Retrieve ad stats from a video ad group function getVideoAdGroupAdStats() { const statsList = []; const videoAdGroupIterator = AdsApp.videoAdGroups().withCondition('Name = "INSERT_ADGROUP_NAME_HERE"').get(); if (videoAdGroupIterator.hasNext()) { const videoAdGroup = videoAdGroupIterator.next(); const videoAdsIterator = videoAdGroup.videoAds().get(); while (videoAdsIterator.hasNext()) { const videoAd = videoAdsIterator.next(); // You can also request reports for pre-defined date ranges. See // https://developers.google.com/adwords/api/docs/guides/awql, // DateRangeLiteral section for possible values. const stats = videoAd.getStatsFor("LAST_MONTH"); Logger.log(videoAd.getVideoAdGroup().getName() + ", " + stats.getViews() + ", " + stats.getImpressions()); statsList.push(stats); } } return statsList; } // Add in-market audience to a video ad group function addInMarketAudienceToVideoAdGroup() { const ag = AdsApp.videoAdGroups().withCondition("CampaignStatus != REMOVED").get().next(); Logger.log("AdGroup ID %s Campaign ID %s", ag.getId().toString(), ag.getVideoCampaign().getId().toString()); // Get the audience ID from the list here: // https://developers.google.com/adwords/api/docs/appendix/codes-formats#in-market-categories const audience = ag .videoTargeting() .newAudienceBuilder() .withAudienceId(80428) .withAudienceType("USER_INTEREST") .build() .getResult(); if (!audience) return; Logger.log("Added Audience ID %s", audience.getId().toString()); const audiences = ag.videoTargeting().audiences().get(); while (audiences.hasNext()) { const aud = audiences.next(); Logger.log("Retrieved Audience ID %s", aud.getId().toString()); } } // Bulk upload from Google Drive function bulkUploadFromGoogleDrive() { // See https://developers.google.com/google-ads/scripts/docs/features/bulk-upload // for the list of supported bulk upload templates. // You can upload a CSV file, or an EXCEL sheet. const file = DriveApp.getFilesByName("BulkCampaignUpload.csv").next(); const upload = AdsApp.bulkUploads().newFileUpload(file); upload.forCampaignManagement(); // Use upload.apply() to make changes without previewing. upload.preview(); } // Bulk upload from remote server function bulkUploadFromRemoteServer() { // See https://developers.google.com/google-ads/scripts/docs/features/bulk-upload // for the list of supported bulk upload templates. const dataUrl = "INSERT_CSV_FILE_URL_HERE"; const mimeType = ""; const blob = UrlFetchApp.fetch(dataUrl).getBlob().getAs(mimeType); const upload = AdsApp.bulkUploads().newFileUpload(blob); upload.forCampaignManagement(); // Use upload.apply() to make changes without previewing. upload.preview(); } // Bulk upload from Google Sheets function bulkUploadFromGoogleSpreadsheet() { // The format of this spreadsheet should match a valid bulk upload template. // See https://developers.google.com/google-ads/scripts/docs/features/bulk-upload // for the list of supported bulk upload templates. const SPREADSHEET_URL = "INSERT_SPREADSHEET_URL_HERE"; const spreadSheet = SpreadsheetApp.openByUrl(SPREADSHEET_URL); const sheet = spreadSheet.getActiveSheet(); const upload = AdsApp.bulkUploads().newFileUpload(sheet); upload.forCampaignManagement(); // Use upload.apply() to make changes without previewing. upload.preview(); } // Bulk upload from Google Ads reports function bulkUploadFromGoogleAdsReports() { // Run a report to fetch all campaigns that spent more than $1000 // this month. const query = "SELECT CampaignId,CampaignName,CampaignStatus,Amount " + "FROM CAMPAIGN_PERFORMANCE_REPORT " + "WHERE Amount > 1000000000 " + "DURING THIS_MONTH"; const report = AdsApp.report(query); // Create an upload with the report columns. const upload = AdsApp.bulkUploads().newCsvUpload([ report.getColumnHeader("CampaignId").getBulkUploadColumnName(), report.getColumnHeader("CampaignName").getBulkUploadColumnName(), report.getColumnHeader("CampaignStatus").getBulkUploadColumnName(), ]); upload.forCampaignManagement(); const rows = report.rows(); while (rows.hasNext()) { const row = rows.next(); // Pause the campaigns. row.CampaignStatus = "paused"; // Convert the report row into an upload row. upload.append(row.formatForUpload()); } // Use upload.apply() to make changes without previewing. upload.preview(); } // Create/update campaigns function createOrUpdateCampaigns() { // See https://developers.google.com/google-ads/scripts/docs/features/bulk-upload // for the list of supported bulk upload templates and their column names. const columns = ["Campaign", "Budget", "Bid Strategy type", "Campaign type"]; const upload = AdsApp.bulkUploads().newCsvUpload(columns, { moneyInMicros: false }); // Google Ads identify existing campaigns using its name. To create a new // campaign, use a campaign name that doesn't exist in your account. upload.append({ Campaign: "Test Campaign 1", Budget: 234, "Bid Strategy type": "cpc", "Campaign type": "Search Only", }); // Use upload.apply() to make changes without previewing. upload.preview(); } // Retrieve column names in reports function getColumnsFromReport() { const report = AdsApp.report( "SELECT CampaignName, CampaignStatus " + "FROM CAMPAIGN_PERFORMANCE_REPORT " + "DURING TODAY", ); Logger.log( "%s, %s", report.getColumnHeader("CampaignName").getBulkUploadColumnName(), report.getColumnHeader("CampaignStatus").getBulkUploadColumnName(), ); } // Create a text report function runReport() { // Google Ads reports return data faster than campaign management methods // and can be used to retrieve basic structural information on // your Account, Campaigns, AdGroups, Ads, Keywords, etc. You can refer to // https://developers.google.com/adwords/api/docs/guides/structure-reports // for more details. // See https://developers.google.com/adwords/api/docs/appendix/reports // for all the supported report types. // See https://developers.google.com/adwords/api/docs/guides/awql for // details on how to use AWQL. // See https://developers.google.com/adwords/api/docs/guides/uireports // for details on how to map an Google Ads UI feature to the corresponding // reporting API feature. const report = AdsApp.report( "SELECT CampaignName, Clicks, Impressions, Cost " + "FROM CAMPAIGN_PERFORMANCE_REPORT " + "WHERE Impressions < 10 " + "DURING LAST_30_DAYS", ); const rows = report.rows(); while (rows.hasNext()) { const row = rows.next(); const campaignName = row["CampaignName"]; const clicks = row["Clicks"]; const impressions = row["Impressions"]; const cost = row["Cost"]; Logger.log(campaignName + "," + clicks + "," + impressions + "," + cost); } } // Create a spreadsheet report function exportReportToSpreadsheet() { const spreadsheet = SpreadsheetApp.create("INSERT_REPORT_NAME_HERE"); const report = AdsApp.report( "SELECT CampaignName, Clicks, Impressions, Cost " + "FROM CAMPAIGN_PERFORMANCE_REPORT " + "WHERE Impressions < 10 " + "DURING LAST_30_DAYS", ); report.exportToSheet(spreadsheet.getActiveSheet()); } // Filter entities by label function filterReportByLabelIds() { const label = AdsApp.labels().withCondition("Name = 'High performance campaigns'").get().next(); const query = "SELECT CampaignName, Clicks, Impressions, Cost from " + "CAMPAIGN_PERFORMANCE_REPORT where Labels CONTAINS_ANY " + "[" + label.getId() + "] during THIS_MONTH"; const report = AdsApp.report(query); const rows = report.rows(); while (rows.hasNext()) { const row = rows.next(); const campaignName = row["CampaignName"]; const clicks = row["Clicks"]; const impressions = row["Impressions"]; const cost = row["Cost"]; Logger.log(campaignName + "," + clicks + "," + impressions + "," + cost); } } // Get accounts from customer IDs function getAllAccounts() { const accountIterator = AdsManagerApp.accounts().get(); while (accountIterator.hasNext()) { const account = accountIterator.next(); const accountName = account.getName() ? account.getName() : "--"; Logger.log( "%s,%s,%s,%s", account.getCustomerId(), accountName, account.getTimeZone(), account.getCurrencyCode(), ); } } // Get accounts by label function getAccountsByLabel() { // Only CONTAINS and DOES_NOT_CONTAIN operators are supported. const accountIterator = AdsManagerApp.accounts().withCondition("LabelNames CONTAINS 'High spend accounts'").get(); while (accountIterator.hasNext()) { const account = accountIterator.next(); const accountName = account.getName() ? account.getName() : "--"; Logger.log( "%s,%s,%s,%s", account.getCustomerId(), accountName, account.getTimeZone(), account.getCurrencyCode(), ); } } // Get accounts by stats function getAccountByStats() { // This is useful when you need to identify accounts that were performing // well (or poorly) in a given time frame. const accountIterator = AdsManagerApp.accounts() .withCondition("Clicks > 10") .forDateRange("LAST_MONTH") .orderBy("Clicks DESC") .get(); while (accountIterator.hasNext()) { const account = accountIterator.next(); const stats = account.getStatsFor("LAST_MONTH"); Logger.log( "%s,%s,%s", account.getCustomerId(), stats.getClicks().toFixed(0), stats.getImpressions().toFixed(0), ); } } // Get accounts under a child account function getAccountsUnderAChildManagerAccount() { // This is useful if you want to restrict your script to process only accounts // under a specific child manager account. This allows you to manage specific // child manager account hierarchies from the top-level manager account // without having to duplicate your script in the child manager account. const accountIterator = AdsManagerApp.accounts().withCondition("ManagerCustomerId = '1234567890'").get(); while (accountIterator.hasNext()) { const account = accountIterator.next(); const accountName = account.getName() ? account.getName() : "--"; Logger.log( "%s,%s,%s,%s", account.getCustomerId(), accountName, account.getTimeZone(), account.getCurrencyCode(), ); } } // Update multiple accounts in series function updateAccountsInSeries() { // You can use this approach when you have only minimal processing to // perform in each of your client accounts. // Select the accounts to be processed. const accountIterator = AdsManagerApp.accounts().withCondition("LabelNames CONTAINS 'Cars'").get(); // Save the manager account, to switch back later. const managerAccount = AdsApp.currentAccount(); while (accountIterator.hasNext()) { const account = accountIterator.next(); // Switch to the account you want to process. AdsManagerApp.select(account); // Retrieve all campaigns to be paused. const campaignIterator = AdsApp.campaigns().withCondition("LabelNames = 'Christmas promotion'").get(); while (campaignIterator.hasNext()) { const campaign = campaignIterator.next(); Logger.log("Pausing campaign %s in account %s", campaign.getName(), account.getCustomerId()); campaign.pause(); } } } // Update multiple accounts in parallel function updateAccountsInParallel() { // You can use this approach when you have a large amount of processing // to do in each of your client accounts. // Select the accounts to be processed. You can process up to 50 accounts. const accountSelector = AdsManagerApp.accounts() .withCondition("LabelNames CONTAINS 'High spend accounts'") .withLimit(50); // Process the account in parallel. The callback method is optional. accountSelector.executeInParallel("processAccount", "allFinished"); } /** * Process one account at a time. This method is called by the executeInParallel * method call in updateAccountsInParallel function for every account that * it processes. * * @return The number of campaigns paused by this method. */ function processAccount() { // executeInParallel will automatically switch context to the account being // processed, so all calls to AdsApp will apply to the selected account. const account = AdsApp.currentAccount(); const campaignIterator = AdsApp.campaigns().withCondition("LabelNames = 'Christmas promotion'").get(); while (campaignIterator.hasNext()) { const campaign = campaignIterator.next(); Logger.log("Pausing campaign %s in account %s", campaign.getName(), account.getCustomerId()); campaign.pause(); } // Optional: return a string value. If you have a more complex JavaScript // object to return from this method, use JSON.stringify(value). This value // will be passed on to the callback method, if specified, in the // executeInParallel method call. return campaignIterator.totalNumEntities().toFixed(0); } /** * Post-process the results from processAccount. This method will be called * once all the accounts have been processed by the executeInParallel method * call. * * @param results An array of ExecutionResult objects, * one for each account that was processed by the executeInParallel method. */ function allFinished(results: GoogleAdsScripts.AdsManagerApp.ExecutionResult[]) { // tslint:disable-next-line: prefer-for-of for (let i = 0; i < results.length; i++) { // Get the ExecutionResult for an account. const result = results[i]; Logger.log("Customer ID: %s; status = %s.", result.getCustomerId(), result.getStatus()); // Check the execution status. This can be one of ERROR, OK, or TIMEOUT. if (result.getStatus() === "ERROR") { Logger.log("-- Failed with error: '%s'.", result.getError()); } else if (result.getStatus() === "OK") { // This is the value you returned from processAccount method. If you // used JSON.stringify(value) in processAccount, you can use // JSON.parse(text) to reconstruct the JavaScript object. const retval = result.getReturnValue(); Logger.log("--Processed %s campaigns.", retval); } else { // Handle timeouts here. } } }
the_stack
import * as anchor from '@project-serum/anchor'; import { assert } from 'chai'; import { Program } from '@project-serum/anchor'; import { Keypair } from '@solana/web3.js'; import { Admin, BN, MARK_PRICE_PRECISION, ClearingHouse, PositionDirection, ClearingHouseUser, Wallet, getMarketOrderParams, OrderTriggerCondition, getTriggerMarketOrderParams, getTriggerLimitOrderParams, } from '../sdk/src'; import { mockOracle, mockUSDCMint, mockUserUSDCAccount, setFeedPrice, } from './testHelpers'; import { BASE_PRECISION, ZERO } from '../sdk'; describe('trigger orders', () => { const provider = anchor.AnchorProvider.local(); const connection = provider.connection; anchor.setProvider(provider); const chProgram = anchor.workspace.ClearingHouse as Program; let fillerClearingHouse: Admin; let fillerClearingHouseUser: ClearingHouseUser; let usdcMint; let userUSDCAccount; // ammInvariant == k == x * y const mantissaSqrtScale = new BN(Math.sqrt(MARK_PRICE_PRECISION.toNumber())); const ammInitialQuoteAssetReserve = new anchor.BN(5 * 10 ** 13).mul( mantissaSqrtScale ); const ammInitialBaseAssetReserve = new anchor.BN(5 * 10 ** 13).mul( mantissaSqrtScale ); const usdcAmount = new BN(10 * 10 ** 6); const marketIndex = new BN(0); let solUsd; before(async () => { usdcMint = await mockUSDCMint(provider); userUSDCAccount = await mockUserUSDCAccount(usdcMint, usdcAmount, provider); fillerClearingHouse = Admin.from( connection, provider.wallet, chProgram.programId ); await fillerClearingHouse.initialize(usdcMint.publicKey, true); await fillerClearingHouse.subscribeToAll(); solUsd = await mockOracle(1); const periodicity = new BN(60 * 60); // 1 HOUR await fillerClearingHouse.initializeMarket( marketIndex, solUsd, ammInitialBaseAssetReserve, ammInitialQuoteAssetReserve, periodicity ); await fillerClearingHouse.initializeUserAccountAndDepositCollateral( usdcAmount, userUSDCAccount.publicKey ); fillerClearingHouseUser = ClearingHouseUser.from( fillerClearingHouse, provider.wallet.publicKey ); await fillerClearingHouseUser.subscribe(); }); beforeEach(async () => { await fillerClearingHouse.moveAmmPrice( ammInitialBaseAssetReserve, ammInitialQuoteAssetReserve, ZERO ); await setFeedPrice(anchor.workspace.Pyth, 1, solUsd); }); after(async () => { await fillerClearingHouse.unsubscribe(); await fillerClearingHouseUser.unsubscribe(); }); it('stop market for long', async () => { const keypair = new Keypair(); await provider.connection.requestAirdrop(keypair.publicKey, 10 ** 9); const wallet = new Wallet(keypair); const userUSDCAccount = await mockUserUSDCAccount( usdcMint, usdcAmount, provider, keypair.publicKey ); const clearingHouse = ClearingHouse.from( connection, wallet, chProgram.programId ); await clearingHouse.subscribe(); await clearingHouse.initializeUserAccountAndDepositCollateral( usdcAmount, userUSDCAccount.publicKey ); const clearingHouseUser = ClearingHouseUser.from( clearingHouse, keypair.publicKey ); await clearingHouseUser.subscribe(); const marketIndex = new BN(0); const baseAssetAmount = BASE_PRECISION; const marketOrderParams = getMarketOrderParams( marketIndex, PositionDirection.LONG, ZERO, baseAssetAmount, false ); await clearingHouse.placeAndFillOrder(marketOrderParams); const stopOrderParams = getTriggerMarketOrderParams( marketIndex, PositionDirection.SHORT, baseAssetAmount, MARK_PRICE_PRECISION.div(new BN(2)), OrderTriggerCondition.BELOW, false, undefined, undefined, 1 ); await clearingHouse.placeOrder(stopOrderParams); await clearingHouseUser.fetchAccounts(); const order = clearingHouseUser.getOrderByUserOrderId(1); try { // fill should fail since price is above trigger await fillerClearingHouse.fillOrder( await clearingHouseUser.getUserAccountPublicKey(), await clearingHouseUser.getUserOrdersAccountPublicKey(), order ); assert(false); } catch (e) { // no op } await fillerClearingHouse.moveAmmPrice( ammInitialBaseAssetReserve.mul(new BN(10)), ammInitialQuoteAssetReserve, marketIndex ); await setFeedPrice(anchor.workspace.Pyth, 0.1, solUsd); await fillerClearingHouse.fillOrder( await clearingHouseUser.getUserAccountPublicKey(), await clearingHouseUser.getUserOrdersAccountPublicKey(), order ); await clearingHouseUser.fetchAccounts(); assert( clearingHouseUser .getUserPositionsAccount() .positions[0].baseAssetAmount.eq(ZERO) ); await clearingHouse.unsubscribe(); await clearingHouseUser.unsubscribe(); }); it('stop limit for long', async () => { const keypair = new Keypair(); await provider.connection.requestAirdrop(keypair.publicKey, 10 ** 9); const wallet = new Wallet(keypair); const userUSDCAccount = await mockUserUSDCAccount( usdcMint, usdcAmount, provider, keypair.publicKey ); const clearingHouse = ClearingHouse.from( connection, wallet, chProgram.programId ); await clearingHouse.subscribe(); await clearingHouse.initializeUserAccountAndDepositCollateral( usdcAmount, userUSDCAccount.publicKey ); const clearingHouseUser = ClearingHouseUser.from( clearingHouse, keypair.publicKey ); await clearingHouseUser.subscribe(); const marketIndex = new BN(0); const baseAssetAmount = BASE_PRECISION.mul(new BN(10)); const marketOrderParams = getMarketOrderParams( marketIndex, PositionDirection.LONG, ZERO, baseAssetAmount, false ); await clearingHouse.placeAndFillOrder(marketOrderParams); const stopLimitOrderParams = getTriggerLimitOrderParams( marketIndex, PositionDirection.SHORT, baseAssetAmount, MARK_PRICE_PRECISION.div(new BN(10)), MARK_PRICE_PRECISION.div(new BN(2)), OrderTriggerCondition.BELOW, false, undefined, undefined, 1 ); await clearingHouse.placeOrder(stopLimitOrderParams); await clearingHouseUser.fetchAccounts(); const order = clearingHouseUser.getOrderByUserOrderId(1); try { // fill should fail since price is above trigger await fillerClearingHouse.fillOrder( await clearingHouseUser.getUserAccountPublicKey(), await clearingHouseUser.getUserOrdersAccountPublicKey(), order ); assert(false); } catch (e) { // no op } await fillerClearingHouse.moveAmmPrice( ammInitialBaseAssetReserve.mul(new BN(5)), ammInitialQuoteAssetReserve, marketIndex ); await setFeedPrice(anchor.workspace.Pyth, 0.2, solUsd); await fillerClearingHouse.fillOrder( await clearingHouseUser.getUserAccountPublicKey(), await clearingHouseUser.getUserOrdersAccountPublicKey(), order ); await clearingHouseUser.fetchAccounts(); assert( clearingHouseUser .getUserPositionsAccount() .positions[0].baseAssetAmount.eq(ZERO) ); await clearingHouse.unsubscribe(); await clearingHouseUser.unsubscribe(); }); it('stop market for short', async () => { const keypair = new Keypair(); await provider.connection.requestAirdrop(keypair.publicKey, 10 ** 9); const wallet = new Wallet(keypair); const userUSDCAccount = await mockUserUSDCAccount( usdcMint, usdcAmount, provider, keypair.publicKey ); const clearingHouse = ClearingHouse.from( connection, wallet, chProgram.programId ); await clearingHouse.subscribe(); await clearingHouse.initializeUserAccountAndDepositCollateral( usdcAmount, userUSDCAccount.publicKey ); const clearingHouseUser = ClearingHouseUser.from( clearingHouse, keypair.publicKey ); await clearingHouseUser.subscribe(); const marketIndex = new BN(0); const baseAssetAmount = BASE_PRECISION; const marketOrderParams = getMarketOrderParams( marketIndex, PositionDirection.SHORT, ZERO, baseAssetAmount, false ); await clearingHouse.placeAndFillOrder(marketOrderParams); const stopOrderParams = getTriggerMarketOrderParams( marketIndex, PositionDirection.LONG, baseAssetAmount, MARK_PRICE_PRECISION.mul(new BN(2)), OrderTriggerCondition.ABOVE, false, undefined, undefined, 1 ); await clearingHouse.placeOrder(stopOrderParams); await clearingHouseUser.fetchAccounts(); const order = clearingHouseUser.getOrderByUserOrderId(1); try { // fill should fail since price is above trigger await fillerClearingHouse.fillOrder( await clearingHouseUser.getUserAccountPublicKey(), await clearingHouseUser.getUserOrdersAccountPublicKey(), order ); assert(false); } catch (e) { // no op } await fillerClearingHouse.moveAmmPrice( ammInitialBaseAssetReserve.div(new BN(10)), ammInitialQuoteAssetReserve, marketIndex ); await setFeedPrice(anchor.workspace.Pyth, 10, solUsd); await fillerClearingHouse.fillOrder( await clearingHouseUser.getUserAccountPublicKey(), await clearingHouseUser.getUserOrdersAccountPublicKey(), order ); await clearingHouseUser.fetchAccounts(); assert( clearingHouseUser .getUserPositionsAccount() .positions[0].baseAssetAmount.eq(ZERO) ); await clearingHouse.unsubscribe(); await clearingHouseUser.unsubscribe(); }); it('stop limit for short', async () => { const keypair = new Keypair(); await provider.connection.requestAirdrop(keypair.publicKey, 10 ** 9); const wallet = new Wallet(keypair); const userUSDCAccount = await mockUserUSDCAccount( usdcMint, usdcAmount, provider, keypair.publicKey ); const clearingHouse = ClearingHouse.from( connection, wallet, chProgram.programId ); await clearingHouse.subscribe(); await clearingHouse.initializeUserAccountAndDepositCollateral( usdcAmount, userUSDCAccount.publicKey ); const clearingHouseUser = ClearingHouseUser.from( clearingHouse, keypair.publicKey ); await clearingHouseUser.subscribe(); const marketIndex = new BN(0); const baseAssetAmount = BASE_PRECISION.mul(new BN(10)); const marketOrderParams = getMarketOrderParams( marketIndex, PositionDirection.SHORT, ZERO, baseAssetAmount, false ); await clearingHouse.placeAndFillOrder(marketOrderParams); const stopLimitOrderParams = getTriggerLimitOrderParams( marketIndex, PositionDirection.LONG, baseAssetAmount, MARK_PRICE_PRECISION.mul(new BN(10)), MARK_PRICE_PRECISION.mul(new BN(2)), OrderTriggerCondition.ABOVE, false, undefined, undefined, 1 ); await clearingHouse.placeOrder(stopLimitOrderParams); await clearingHouseUser.fetchAccounts(); const order = clearingHouseUser.getOrderByUserOrderId(1); try { // fill should fail since price is above trigger await fillerClearingHouse.fillOrder( await clearingHouseUser.getUserAccountPublicKey(), await clearingHouseUser.getUserOrdersAccountPublicKey(), order ); assert(false); } catch (e) { // no op } await fillerClearingHouse.moveAmmPrice( ammInitialBaseAssetReserve.div(new BN(5)), ammInitialQuoteAssetReserve, marketIndex ); await setFeedPrice(anchor.workspace.Pyth, 5, solUsd); await fillerClearingHouse.fillOrder( await clearingHouseUser.getUserAccountPublicKey(), await clearingHouseUser.getUserOrdersAccountPublicKey(), order ); await clearingHouseUser.fetchAccounts(); assert( clearingHouseUser .getUserPositionsAccount() .positions[0].baseAssetAmount.eq(ZERO) ); await clearingHouse.unsubscribe(); await clearingHouseUser.unsubscribe(); }); it('take profit for long', async () => { const keypair = new Keypair(); await provider.connection.requestAirdrop(keypair.publicKey, 10 ** 9); const wallet = new Wallet(keypair); const userUSDCAccount = await mockUserUSDCAccount( usdcMint, usdcAmount, provider, keypair.publicKey ); const clearingHouse = ClearingHouse.from( connection, wallet, chProgram.programId ); await clearingHouse.subscribe(); await clearingHouse.initializeUserAccountAndDepositCollateral( usdcAmount, userUSDCAccount.publicKey ); const clearingHouseUser = ClearingHouseUser.from( clearingHouse, keypair.publicKey ); await clearingHouseUser.subscribe(); const marketIndex = new BN(0); const baseAssetAmount = BASE_PRECISION; const marketOrderParams = getMarketOrderParams( marketIndex, PositionDirection.LONG, ZERO, baseAssetAmount, false ); await clearingHouse.placeAndFillOrder(marketOrderParams); const stopOrderParams = getTriggerMarketOrderParams( marketIndex, PositionDirection.SHORT, baseAssetAmount, MARK_PRICE_PRECISION.mul(new BN(2)), OrderTriggerCondition.ABOVE, false, undefined, undefined, 1 ); await clearingHouse.placeOrder(stopOrderParams); await clearingHouseUser.fetchAccounts(); const order = clearingHouseUser.getOrderByUserOrderId(1); try { // fill should fail since price is above trigger await fillerClearingHouse.fillOrder( await clearingHouseUser.getUserAccountPublicKey(), await clearingHouseUser.getUserOrdersAccountPublicKey(), order ); assert(false); } catch (e) { // no op } await fillerClearingHouse.moveAmmPrice( ammInitialBaseAssetReserve.div(new BN(10)), ammInitialQuoteAssetReserve, marketIndex ); await setFeedPrice(anchor.workspace.Pyth, 10, solUsd); await fillerClearingHouse.fillOrder( await clearingHouseUser.getUserAccountPublicKey(), await clearingHouseUser.getUserOrdersAccountPublicKey(), order ); await clearingHouseUser.fetchAccounts(); assert( clearingHouseUser .getUserPositionsAccount() .positions[0].baseAssetAmount.eq(ZERO) ); await clearingHouse.unsubscribe(); await clearingHouseUser.unsubscribe(); }); it('take profit limit for long', async () => { const keypair = new Keypair(); await provider.connection.requestAirdrop(keypair.publicKey, 10 ** 9); const wallet = new Wallet(keypair); const userUSDCAccount = await mockUserUSDCAccount( usdcMint, usdcAmount, provider, keypair.publicKey ); const clearingHouse = ClearingHouse.from( connection, wallet, chProgram.programId ); await clearingHouse.subscribe(); await clearingHouse.initializeUserAccountAndDepositCollateral( usdcAmount, userUSDCAccount.publicKey ); const clearingHouseUser = ClearingHouseUser.from( clearingHouse, keypair.publicKey ); await clearingHouseUser.subscribe(); const marketIndex = new BN(0); const baseAssetAmount = BASE_PRECISION.mul(new BN(10)); const marketOrderParams = getMarketOrderParams( marketIndex, PositionDirection.LONG, ZERO, baseAssetAmount, false ); await clearingHouse.placeAndFillOrder(marketOrderParams); const stopLimitOrderParams = getTriggerLimitOrderParams( marketIndex, PositionDirection.SHORT, baseAssetAmount, MARK_PRICE_PRECISION.mul(new BN(2)), MARK_PRICE_PRECISION.mul(new BN(2)), OrderTriggerCondition.ABOVE, false, undefined, undefined, 1 ); await clearingHouse.placeOrder(stopLimitOrderParams); await clearingHouseUser.fetchAccounts(); const order = clearingHouseUser.getOrderByUserOrderId(1); try { // fill should fail since price is above trigger await fillerClearingHouse.fillOrder( await clearingHouseUser.getUserAccountPublicKey(), await clearingHouseUser.getUserOrdersAccountPublicKey(), order ); assert(false); } catch (e) { // no op } await fillerClearingHouse.moveAmmPrice( ammInitialBaseAssetReserve.div(new BN(5)), ammInitialQuoteAssetReserve, marketIndex ); await setFeedPrice(anchor.workspace.Pyth, 5, solUsd); await fillerClearingHouse.fillOrder( await clearingHouseUser.getUserAccountPublicKey(), await clearingHouseUser.getUserOrdersAccountPublicKey(), order ); await clearingHouseUser.fetchAccounts(); assert( clearingHouseUser .getUserPositionsAccount() .positions[0].baseAssetAmount.eq(ZERO) ); await clearingHouse.unsubscribe(); await clearingHouseUser.unsubscribe(); }); it('take profit for short', async () => { const keypair = new Keypair(); await provider.connection.requestAirdrop(keypair.publicKey, 10 ** 9); const wallet = new Wallet(keypair); const userUSDCAccount = await mockUserUSDCAccount( usdcMint, usdcAmount, provider, keypair.publicKey ); const clearingHouse = ClearingHouse.from( connection, wallet, chProgram.programId ); await clearingHouse.subscribe(); await clearingHouse.initializeUserAccountAndDepositCollateral( usdcAmount, userUSDCAccount.publicKey ); const clearingHouseUser = ClearingHouseUser.from( clearingHouse, keypair.publicKey ); await clearingHouseUser.subscribe(); const marketIndex = new BN(0); const baseAssetAmount = BASE_PRECISION; const marketOrderParams = getMarketOrderParams( marketIndex, PositionDirection.SHORT, ZERO, baseAssetAmount, false ); await clearingHouse.placeAndFillOrder(marketOrderParams); const stopOrderParams = getTriggerMarketOrderParams( marketIndex, PositionDirection.LONG, baseAssetAmount, MARK_PRICE_PRECISION.div(new BN(2)), OrderTriggerCondition.BELOW, false, undefined, undefined, 1 ); await clearingHouse.placeOrder(stopOrderParams); await clearingHouseUser.fetchAccounts(); const order = clearingHouseUser.getOrderByUserOrderId(1); try { // fill should fail since price is above trigger await fillerClearingHouse.fillOrder( await clearingHouseUser.getUserAccountPublicKey(), await clearingHouseUser.getUserOrdersAccountPublicKey(), order ); assert(false); } catch (e) { // no op } await fillerClearingHouse.moveAmmPrice( ammInitialBaseAssetReserve.mul(new BN(10)), ammInitialQuoteAssetReserve, marketIndex ); await setFeedPrice(anchor.workspace.Pyth, 0.1, solUsd); await fillerClearingHouse.fillOrder( await clearingHouseUser.getUserAccountPublicKey(), await clearingHouseUser.getUserOrdersAccountPublicKey(), order ); await clearingHouseUser.fetchAccounts(); assert( clearingHouseUser .getUserPositionsAccount() .positions[0].baseAssetAmount.eq(ZERO) ); await clearingHouse.unsubscribe(); await clearingHouseUser.unsubscribe(); }); it('take profit limit for short', async () => { const keypair = new Keypair(); await provider.connection.requestAirdrop(keypair.publicKey, 10 ** 9); const wallet = new Wallet(keypair); const userUSDCAccount = await mockUserUSDCAccount( usdcMint, usdcAmount, provider, keypair.publicKey ); const clearingHouse = ClearingHouse.from( connection, wallet, chProgram.programId ); await clearingHouse.subscribe(); await clearingHouse.initializeUserAccountAndDepositCollateral( usdcAmount, userUSDCAccount.publicKey ); const clearingHouseUser = ClearingHouseUser.from( clearingHouse, keypair.publicKey ); await clearingHouseUser.subscribe(); const marketIndex = new BN(0); const baseAssetAmount = BASE_PRECISION.mul(new BN(10)); const marketOrderParams = getMarketOrderParams( marketIndex, PositionDirection.SHORT, ZERO, baseAssetAmount, false ); await clearingHouse.placeAndFillOrder(marketOrderParams); const stopLimitOrderParams = getTriggerLimitOrderParams( marketIndex, PositionDirection.LONG, baseAssetAmount, MARK_PRICE_PRECISION.div(new BN(2)), MARK_PRICE_PRECISION.div(new BN(2)), OrderTriggerCondition.BELOW, false, undefined, undefined, 1 ); await clearingHouse.placeOrder(stopLimitOrderParams); await clearingHouseUser.fetchAccounts(); const order = clearingHouseUser.getOrderByUserOrderId(1); try { // fill should fail since price is above trigger await fillerClearingHouse.fillOrder( await clearingHouseUser.getUserAccountPublicKey(), await clearingHouseUser.getUserOrdersAccountPublicKey(), order ); assert(false); } catch (e) { // no op } await fillerClearingHouse.moveAmmPrice( ammInitialBaseAssetReserve.mul(new BN(5)), ammInitialQuoteAssetReserve, marketIndex ); await setFeedPrice(anchor.workspace.Pyth, 0.2, solUsd); await fillerClearingHouse.fillOrder( await clearingHouseUser.getUserAccountPublicKey(), await clearingHouseUser.getUserOrdersAccountPublicKey(), order ); await clearingHouseUser.fetchAccounts(); assert( clearingHouseUser .getUserPositionsAccount() .positions[0].baseAssetAmount.eq(ZERO) ); await clearingHouse.unsubscribe(); await clearingHouseUser.unsubscribe(); }); });
the_stack
import { toolbar, SortByDefault, dialogAddons } from './annotations'; import Column, { widthChanged, labelChanged, metaDataChanged, dirty, dirtyHeader, dirtyValues, rendererTypeChanged, groupRendererChanged, summaryRendererChanged, visibilityChanged, dirtyCaches, } from './Column'; import type { dataLoaded } from './ValueColumn'; import type ValueColumn from './ValueColumn'; import type { IKeyValue } from './IArrayColumn'; import { IDataRow, ECompareValueType, ITypeFactory } from './interfaces'; import { EAdvancedSortMethod, IAdvancedBoxPlotColumn, INumberDesc, INumberFilter, IMappingFunction, IColorMappingFunction, } from './INumberColumn'; import MapColumn, { IMapColumnDesc } from './MapColumn'; import { restoreMapping } from './MappingFunction'; import { isMissingValue } from './missing'; import NumberColumn from './NumberColumn'; import { IEventListener, IAdvancedBoxPlotData, boxplotBuilder } from '../internal'; import { format } from 'd3-format'; import { DEFAULT_FORMATTER, noNumberFilter, toCompareBoxPlotValue, getBoxPlotNumber, isDummyNumberFilter, restoreNumberFilter, } from './internalNumber'; import { integrateDefaults } from './internal'; export interface INumberMapDesc extends INumberDesc { readonly sort?: EAdvancedSortMethod; } export declare type INumberMapColumnDesc = INumberMapDesc & IMapColumnDesc<number>; /** * emitted when the mapping property changes * @asMemberOf NumberMapColumn * @event */ export declare function mappingChanged_NMC(previous: IMappingFunction, current: IMappingFunction): void; /** * emitted when the color mapping property changes * @asMemberOf NumberMapColumn * @event */ export declare function colorMappingChanged_NMC(previous: IColorMappingFunction, current: IColorMappingFunction): void; /** * emitted when the sort method property changes * @asMemberOf NumberMapColumn * @event */ export declare function sortMethodChanged_NMC(previous: EAdvancedSortMethod, current: EAdvancedSortMethod): void; /** * emitted when the filter property changes * @asMemberOf NumberMapColumn * @event */ export declare function filterChanged_NMC(previous: INumberFilter | null, current: INumberFilter | null): void; @toolbar('rename', 'filterNumber', 'colorMapped', 'editMapping') @dialogAddons('sort', 'sortNumbers') @SortByDefault('descending') export default class NumberMapColumn extends MapColumn<number> implements IAdvancedBoxPlotColumn { static readonly EVENT_MAPPING_CHANGED = NumberColumn.EVENT_MAPPING_CHANGED; static readonly EVENT_COLOR_MAPPING_CHANGED = NumberColumn.EVENT_COLOR_MAPPING_CHANGED; static readonly EVENT_SORTMETHOD_CHANGED = NumberColumn.EVENT_SORTMETHOD_CHANGED; static readonly EVENT_FILTER_CHANGED = NumberColumn.EVENT_FILTER_CHANGED; private readonly numberFormat: (n: number) => string = DEFAULT_FORMATTER; private sort: EAdvancedSortMethod; private mapping: IMappingFunction; private original: IMappingFunction; private colorMapping: IColorMappingFunction; /** * currently active filter * @type {{min: number, max: number}} * @private */ private currentFilter: INumberFilter = noNumberFilter(); constructor(id: string, desc: Readonly<INumberMapColumnDesc>, factory: ITypeFactory) { super( id, integrateDefaults(desc, { renderer: 'mapbars', }) ); this.mapping = restoreMapping(desc, factory); this.original = this.mapping.clone(); this.colorMapping = factory.colorMappingFunction(desc.colorMapping || desc.color); this.sort = desc.sort || EAdvancedSortMethod.median; if (desc.numberFormat) { this.numberFormat = format(desc.numberFormat); } } getNumberFormat() { return this.numberFormat; } toCompareValue(row: IDataRow): number { return toCompareBoxPlotValue(this, row); } toCompareValueType() { return ECompareValueType.FLOAT; } getBoxPlotData(row: IDataRow): IAdvancedBoxPlotData | null { const data = this.getRawValue(row); if (data == null) { return null; } const b = boxplotBuilder(); for (const d of data) { b.push(isMissingValue(d.value) ? NaN : this.mapping.apply(d.value)); } return b.build(); } getRange() { return this.mapping.getRange(this.numberFormat); } getRawBoxPlotData(row: IDataRow): IAdvancedBoxPlotData | null { const data = this.getRawValue(row); if (data == null) { return null; } const b = boxplotBuilder(); for (const d of data) { b.push(isMissingValue(d.value) ? NaN : d.value); } return b.build(); } getNumber(row: IDataRow): number { return getBoxPlotNumber(this, row, 'normalized'); } getRawNumber(row: IDataRow): number { return getBoxPlotNumber(this, row, 'raw'); } iterNumber(row: IDataRow) { const r = this.getValue(row); return r ? r.map((d) => d.value) : [NaN]; } iterRawNumber(row: IDataRow) { const r = this.getRawValue(row); return r ? r.map((d) => d.value) : [NaN]; } getValue(row: IDataRow) { const values = this.getRawValue(row); return values.length === 0 ? null : values.map(({ key, value }) => ({ key, value: isMissingValue(value) ? NaN : this.mapping.apply(value) })); } getRawValue(row: IDataRow): IKeyValue<number>[] { const r = super.getValue(row); return r == null ? [] : r; } getExportValue(row: IDataRow, format: 'text' | 'json'): any { return format === 'json' ? this.getRawValue(row) : super.getExportValue(row, format); } getLabels(row: IDataRow) { const v = this.getRawValue(row); return v.map(({ key, value }) => ({ key, value: this.numberFormat(value) })); } getSortMethod() { return this.sort; } setSortMethod(sort: EAdvancedSortMethod) { if (this.sort === sort) { return; } this.fire([NumberMapColumn.EVENT_SORTMETHOD_CHANGED], this.sort, (this.sort = sort)); // sort by me if not already sorted by me if (!this.isSortedByMe().asc) { this.sortByMe(); } } dump(toDescRef: (desc: any) => any): any { const r = super.dump(toDescRef); r.sortMethod = this.getSortMethod(); r.filter = !isDummyNumberFilter(this.currentFilter) ? this.currentFilter : null; r.map = this.mapping.toJSON(); r.colorMapping = this.colorMapping.toJSON(); return r; } restore(dump: any, factory: ITypeFactory) { super.restore(dump, factory); if (dump.sortMethod) { this.sort = dump.sortMethod; } if (dump.filter) { this.currentFilter = restoreNumberFilter(dump.filter); } if (dump.map || dump.domain) { this.mapping = restoreMapping(dump, factory); } if (dump.colorMapping) { this.colorMapping = factory.colorMappingFunction(dump.colorMapping); } } protected createEventList() { return super .createEventList() .concat([ NumberMapColumn.EVENT_COLOR_MAPPING_CHANGED, NumberMapColumn.EVENT_MAPPING_CHANGED, NumberMapColumn.EVENT_SORTMETHOD_CHANGED, NumberMapColumn.EVENT_FILTER_CHANGED, ]); } on(type: typeof NumberMapColumn.EVENT_COLOR_MAPPING_CHANGED, listener: typeof colorMappingChanged_NMC | null): this; on(type: typeof NumberMapColumn.EVENT_MAPPING_CHANGED, listener: typeof mappingChanged_NMC | null): this; on(type: typeof NumberMapColumn.EVENT_SORTMETHOD_CHANGED, listener: typeof sortMethodChanged_NMC | null): this; on(type: typeof NumberMapColumn.EVENT_FILTER_CHANGED, listener: typeof filterChanged_NMC | null): this; on(type: typeof ValueColumn.EVENT_DATA_LOADED, listener: typeof dataLoaded | null): this; on(type: typeof Column.EVENT_WIDTH_CHANGED, listener: typeof widthChanged | null): this; on(type: typeof Column.EVENT_LABEL_CHANGED, listener: typeof labelChanged | null): this; on(type: typeof Column.EVENT_METADATA_CHANGED, listener: typeof metaDataChanged | null): this; on(type: typeof Column.EVENT_DIRTY, listener: typeof dirty | null): this; on(type: typeof Column.EVENT_DIRTY_HEADER, listener: typeof dirtyHeader | null): this; on(type: typeof Column.EVENT_DIRTY_VALUES, listener: typeof dirtyValues | null): this; on(type: typeof Column.EVENT_DIRTY_CACHES, listener: typeof dirtyCaches | null): this; on(type: typeof Column.EVENT_RENDERER_TYPE_CHANGED, listener: typeof rendererTypeChanged | null): this; on(type: typeof Column.EVENT_GROUP_RENDERER_TYPE_CHANGED, listener: typeof groupRendererChanged | null): this; on(type: typeof Column.EVENT_SUMMARY_RENDERER_TYPE_CHANGED, listener: typeof summaryRendererChanged | null): this; on(type: typeof Column.EVENT_VISIBILITY_CHANGED, listener: typeof visibilityChanged | null): this; on(type: string | string[], listener: IEventListener | null): this; // required for correct typings in *.d.ts on(type: string | string[], listener: IEventListener | null): this { return super.on(type as any, listener); } getOriginalMapping() { return this.original.clone(); } getMapping() { return this.mapping.clone(); } setMapping(mapping: IMappingFunction) { if (this.mapping.eq(mapping)) { return; } this.fire( [NumberMapColumn.EVENT_MAPPING_CHANGED, Column.EVENT_DIRTY_VALUES, Column.EVENT_DIRTY], this.mapping.clone(), (this.mapping = mapping) ); } getColor(row: IDataRow) { return NumberColumn.prototype.getColor.call(this, row); } getColorMapping() { return this.colorMapping.clone(); } setColorMapping(mapping: IColorMappingFunction) { if (this.colorMapping.eq(mapping)) { return; } this.fire( [NumberMapColumn.EVENT_COLOR_MAPPING_CHANGED, Column.EVENT_DIRTY_VALUES, Column.EVENT_DIRTY], this.colorMapping.clone(), (this.colorMapping = mapping) ); } isFiltered() { return NumberColumn.prototype.isFiltered.call(this); } getFilter(): INumberFilter { return NumberColumn.prototype.getFilter.call(this); } setFilter(value: INumberFilter | null) { NumberColumn.prototype.setFilter.call(this, value); } filter(row: IDataRow) { return NumberColumn.prototype.filter.call(this, row); } clearFilter() { return NumberColumn.prototype.clearFilter.call(this); } }
the_stack
declare module com { export module bumptech { export module glide { export class GeneratedAppGlideModuleImpl { public static class: java.lang.Class<com.bumptech.glide.GeneratedAppGlideModuleImpl>; public registerComponents(param0: globalAndroid.content.Context, param1: com.bumptech.glide.Glide, param2: com.bumptech.glide.Registry): void; public applyOptions(param0: globalAndroid.content.Context, param1: com.bumptech.glide.GlideBuilder): void; public getExcludedModuleClasses(): java.util.Set<java.lang.Class<any>>; public isManifestParsingEnabled(): boolean; } } } } declare module com { export module bumptech { export module glide { export class GeneratedRequestManagerFactory { public static class: java.lang.Class<com.bumptech.glide.GeneratedRequestManagerFactory>; public build(param0: com.bumptech.glide.Glide, param1: com.bumptech.glide.manager.Lifecycle, param2: com.bumptech.glide.manager.RequestManagerTreeNode, param3: globalAndroid.content.Context): com.bumptech.glide.RequestManager; } } } } declare module com { export module github { export module triniwiz { export module imagecacheit { export class BuildConfig { public static class: java.lang.Class<com.github.triniwiz.imagecacheit.BuildConfig>; public static DEBUG: boolean; public static LIBRARY_PACKAGE_NAME: string; public static APPLICATION_ID: string; public static BUILD_TYPE: string; public static FLAVOR: string; public static VERSION_CODE: number; public static VERSION_NAME: string; public constructor(); } } } } } declare module com { export module github { export module triniwiz { export module imagecacheit { export class ColoredRoundedCornerBorders { public static class: java.lang.Class<com.github.triniwiz.imagecacheit.ColoredRoundedCornerBorders>; public equals(param0: any): boolean; public toString(): string; public transform(param0: globalAndroid.content.Context, param1: com.bumptech.glide.load.engine.bitmap_recycle.BitmapPool, param2: globalAndroid.graphics.Bitmap, param3: number, param4: number): globalAndroid.graphics.Bitmap; public constructor(param0: number, param1: number, param2: com.github.triniwiz.imagecacheit.ColoredRoundedCornerBorders.CornerType, param3: number, param4: number, param5: number, param6: number); public hashCode(): number; public updateDiskCacheKey(param0: java.security.MessageDigest): void; public constructor(param0: number, param1: number); } export module ColoredRoundedCornerBorders { export class CornerType { public static class: java.lang.Class<com.github.triniwiz.imagecacheit.ColoredRoundedCornerBorders.CornerType>; public static ALL: com.github.triniwiz.imagecacheit.ColoredRoundedCornerBorders.CornerType; public static TOP_LEFT: com.github.triniwiz.imagecacheit.ColoredRoundedCornerBorders.CornerType; public static TOP_RIGHT: com.github.triniwiz.imagecacheit.ColoredRoundedCornerBorders.CornerType; public static BOTTOM_LEFT: com.github.triniwiz.imagecacheit.ColoredRoundedCornerBorders.CornerType; public static BOTTOM_RIGHT: com.github.triniwiz.imagecacheit.ColoredRoundedCornerBorders.CornerType; public static TOP: com.github.triniwiz.imagecacheit.ColoredRoundedCornerBorders.CornerType; public static BOTTOM: com.github.triniwiz.imagecacheit.ColoredRoundedCornerBorders.CornerType; public static LEFT: com.github.triniwiz.imagecacheit.ColoredRoundedCornerBorders.CornerType; public static RIGHT: com.github.triniwiz.imagecacheit.ColoredRoundedCornerBorders.CornerType; public static OTHER_TOP_LEFT: com.github.triniwiz.imagecacheit.ColoredRoundedCornerBorders.CornerType; public static OTHER_TOP_RIGHT: com.github.triniwiz.imagecacheit.ColoredRoundedCornerBorders.CornerType; public static OTHER_BOTTOM_LEFT: com.github.triniwiz.imagecacheit.ColoredRoundedCornerBorders.CornerType; public static OTHER_BOTTOM_RIGHT: com.github.triniwiz.imagecacheit.ColoredRoundedCornerBorders.CornerType; public static DIAGONAL_FROM_TOP_LEFT: com.github.triniwiz.imagecacheit.ColoredRoundedCornerBorders.CornerType; public static DIAGONAL_FROM_TOP_RIGHT: com.github.triniwiz.imagecacheit.ColoredRoundedCornerBorders.CornerType; public static BORDER_ALL: com.github.triniwiz.imagecacheit.ColoredRoundedCornerBorders.CornerType; public static BORDER_TOP: com.github.triniwiz.imagecacheit.ColoredRoundedCornerBorders.CornerType; public static BORDER_RIGHT: com.github.triniwiz.imagecacheit.ColoredRoundedCornerBorders.CornerType; public static BORDER_BOTTOM: com.github.triniwiz.imagecacheit.ColoredRoundedCornerBorders.CornerType; public static BORDER_LEFT: com.github.triniwiz.imagecacheit.ColoredRoundedCornerBorders.CornerType; public static values(): native.Array<com.github.triniwiz.imagecacheit.ColoredRoundedCornerBorders.CornerType>; public static valueOf(param0: string): com.github.triniwiz.imagecacheit.ColoredRoundedCornerBorders.CornerType; } } } } } } declare module com { export module github { export module triniwiz { export module imagecacheit { export class GlideApp { public static class: java.lang.Class<com.github.triniwiz.imagecacheit.GlideApp>; public static tearDown(): void; public static with(param0: globalAndroid.app.Activity): com.github.triniwiz.imagecacheit.GlideRequests; public static getPhotoCacheDir(param0: globalAndroid.content.Context): java.io.File; public static get(param0: globalAndroid.content.Context): com.bumptech.glide.Glide; public static with(param0: androidx.fragment.app.FragmentActivity): com.github.triniwiz.imagecacheit.GlideRequests; public static with(param0: androidx.fragment.app.Fragment): com.github.triniwiz.imagecacheit.GlideRequests; public static getPhotoCacheDir(param0: globalAndroid.content.Context, param1: string): java.io.File; public static with(param0: globalAndroid.content.Context): com.github.triniwiz.imagecacheit.GlideRequests; public static with(param0: globalAndroid.view.View): com.github.triniwiz.imagecacheit.GlideRequests; public static init(param0: globalAndroid.content.Context, param1: com.bumptech.glide.GlideBuilder): void; /** @deprecated */ public static init(param0: com.bumptech.glide.Glide): void; /** @deprecated */ public static with(param0: globalAndroid.app.Fragment): com.github.triniwiz.imagecacheit.GlideRequests; } } } } } declare module com { export module github { export module triniwiz { export module imagecacheit { export class GlideOptions { public static class: java.lang.Class<com.github.triniwiz.imagecacheit.GlideOptions>; public clone(): com.github.triniwiz.imagecacheit.GlideOptions; public format(param0: com.bumptech.glide.load.DecodeFormat): com.github.triniwiz.imagecacheit.GlideOptions; public static noAnimation(): com.github.triniwiz.imagecacheit.GlideOptions; public static priorityOf(param0: com.bumptech.glide.Priority): com.github.triniwiz.imagecacheit.GlideOptions; public circleCrop(): com.github.triniwiz.imagecacheit.GlideOptions; public static placeholderOf(param0: globalAndroid.graphics.drawable.Drawable): com.github.triniwiz.imagecacheit.GlideOptions; public static circleCropTransform(): com.github.triniwiz.imagecacheit.GlideOptions; public optionalCenterCrop(): com.github.triniwiz.imagecacheit.GlideOptions; public constructor(); public centerInside(): com.github.triniwiz.imagecacheit.GlideOptions; public static encodeFormatOf(param0: globalAndroid.graphics.Bitmap.CompressFormat): com.github.triniwiz.imagecacheit.GlideOptions; public decode(param0: java.lang.Class<any>): com.github.triniwiz.imagecacheit.GlideOptions; public override(param0: number, param1: number): com.github.triniwiz.imagecacheit.GlideOptions; public timeout(param0: number): com.github.triniwiz.imagecacheit.GlideOptions; public onlyRetrieveFromCache(param0: boolean): com.github.triniwiz.imagecacheit.GlideOptions; public downsample(param0: com.bumptech.glide.load.resource.bitmap.DownsampleStrategy): com.github.triniwiz.imagecacheit.GlideOptions; public placeholder(param0: globalAndroid.graphics.drawable.Drawable): com.github.triniwiz.imagecacheit.GlideOptions; public dontAnimate(): com.github.triniwiz.imagecacheit.GlideOptions; public static diskCacheStrategyOf(param0: com.bumptech.glide.load.engine.DiskCacheStrategy): com.github.triniwiz.imagecacheit.GlideOptions; public optionalTransform(param0: java.lang.Class, param1: com.bumptech.glide.load.Transformation): com.github.triniwiz.imagecacheit.GlideOptions; /** @deprecated */ public transforms(param0: native.Array<com.bumptech.glide.load.Transformation<globalAndroid.graphics.Bitmap>>): com.github.triniwiz.imagecacheit.GlideOptions; public set(param0: com.bumptech.glide.load.Option, param1: any): com.github.triniwiz.imagecacheit.GlideOptions; public lock(): com.github.triniwiz.imagecacheit.GlideOptions; public apply(param0: com.bumptech.glide.request.BaseRequestOptions<any>): com.github.triniwiz.imagecacheit.GlideOptions; public transform(param0: native.Array<com.bumptech.glide.load.Transformation<globalAndroid.graphics.Bitmap>>): com.github.triniwiz.imagecacheit.GlideOptions; public placeholder(param0: number): com.github.triniwiz.imagecacheit.GlideOptions; public static signatureOf(param0: com.bumptech.glide.load.Key): com.github.triniwiz.imagecacheit.GlideOptions; public static centerCropTransform(): com.github.triniwiz.imagecacheit.GlideOptions; public disallowHardwareConfig(): com.github.triniwiz.imagecacheit.GlideOptions; public sizeMultiplier(param0: number): com.github.triniwiz.imagecacheit.GlideOptions; public encodeFormat(param0: globalAndroid.graphics.Bitmap.CompressFormat): com.github.triniwiz.imagecacheit.GlideOptions; public static fitCenterTransform(): com.github.triniwiz.imagecacheit.GlideOptions; public static formatOf(param0: com.bumptech.glide.load.DecodeFormat): com.github.triniwiz.imagecacheit.GlideOptions; public static centerInsideTransform(): com.github.triniwiz.imagecacheit.GlideOptions; public useAnimationPool(param0: boolean): com.github.triniwiz.imagecacheit.GlideOptions; public static timeoutOf(param0: number): com.github.triniwiz.imagecacheit.GlideOptions; public override(param0: number): com.github.triniwiz.imagecacheit.GlideOptions; public optionalFitCenter(): com.github.triniwiz.imagecacheit.GlideOptions; public static bitmapTransform(param0: com.bumptech.glide.load.Transformation<globalAndroid.graphics.Bitmap>): com.github.triniwiz.imagecacheit.GlideOptions; public dontTransform(): com.github.triniwiz.imagecacheit.GlideOptions; public static sizeMultiplierOf(param0: number): com.github.triniwiz.imagecacheit.GlideOptions; public static skipMemoryCacheOf(param0: boolean): com.github.triniwiz.imagecacheit.GlideOptions; public static option(param0: com.bumptech.glide.load.Option, param1: any): com.github.triniwiz.imagecacheit.GlideOptions; public useUnlimitedSourceGeneratorsPool(param0: boolean): com.github.triniwiz.imagecacheit.GlideOptions; public optionalCircleCrop(): com.github.triniwiz.imagecacheit.GlideOptions; public static placeholderOf(param0: number): com.github.triniwiz.imagecacheit.GlideOptions; public static frameOf(param0: number): com.github.triniwiz.imagecacheit.GlideOptions; public static errorOf(param0: number): com.github.triniwiz.imagecacheit.GlideOptions; public optionalTransform(param0: com.bumptech.glide.load.Transformation<globalAndroid.graphics.Bitmap>): com.github.triniwiz.imagecacheit.GlideOptions; public frame(param0: number): com.github.triniwiz.imagecacheit.GlideOptions; public static overrideOf(param0: number, param1: number): com.github.triniwiz.imagecacheit.GlideOptions; public theme(param0: globalAndroid.content.res.Resources.Theme): com.github.triniwiz.imagecacheit.GlideOptions; public diskCacheStrategy(param0: com.bumptech.glide.load.engine.DiskCacheStrategy): com.github.triniwiz.imagecacheit.GlideOptions; public centerCrop(): com.github.triniwiz.imagecacheit.GlideOptions; public static errorOf(param0: globalAndroid.graphics.drawable.Drawable): com.github.triniwiz.imagecacheit.GlideOptions; public static noTransformation(): com.github.triniwiz.imagecacheit.GlideOptions; public error(param0: globalAndroid.graphics.drawable.Drawable): com.github.triniwiz.imagecacheit.GlideOptions; public error(param0: number): com.github.triniwiz.imagecacheit.GlideOptions; public signature(param0: com.bumptech.glide.load.Key): com.github.triniwiz.imagecacheit.GlideOptions; public autoClone(): com.github.triniwiz.imagecacheit.GlideOptions; public fitCenter(): com.github.triniwiz.imagecacheit.GlideOptions; public static overrideOf(param0: number): com.github.triniwiz.imagecacheit.GlideOptions; public skipMemoryCache(param0: boolean): com.github.triniwiz.imagecacheit.GlideOptions; public transform(param0: java.lang.Class, param1: com.bumptech.glide.load.Transformation): com.github.triniwiz.imagecacheit.GlideOptions; public priority(param0: com.bumptech.glide.Priority): com.github.triniwiz.imagecacheit.GlideOptions; public static encodeQualityOf(param0: number): com.github.triniwiz.imagecacheit.GlideOptions; public encodeQuality(param0: number): com.github.triniwiz.imagecacheit.GlideOptions; public fallback(param0: globalAndroid.graphics.drawable.Drawable): com.github.triniwiz.imagecacheit.GlideOptions; public fallback(param0: number): com.github.triniwiz.imagecacheit.GlideOptions; public transform(param0: com.bumptech.glide.load.Transformation<globalAndroid.graphics.Bitmap>): com.github.triniwiz.imagecacheit.GlideOptions; public static decodeTypeOf(param0: java.lang.Class<any>): com.github.triniwiz.imagecacheit.GlideOptions; public static downsampleOf(param0: com.bumptech.glide.load.resource.bitmap.DownsampleStrategy): com.github.triniwiz.imagecacheit.GlideOptions; public optionalCenterInside(): com.github.triniwiz.imagecacheit.GlideOptions; } } } } } declare module com { export module github { export module triniwiz { export module imagecacheit { export class GlideRequest<TranscodeType> extends com.bumptech.glide.RequestBuilder<any> implements java.lang.Cloneable { public static class: java.lang.Class<com.github.triniwiz.imagecacheit.GlideRequest<any>>; public theme(param0: globalAndroid.content.res.Resources.Theme): com.github.triniwiz.imagecacheit.GlideRequest<any>; public override(param0: number, param1: number): com.github.triniwiz.imagecacheit.GlideRequest<any>; public circleCrop(): com.github.triniwiz.imagecacheit.GlideRequest<any>; public fitCenter(): com.github.triniwiz.imagecacheit.GlideRequest<any>; public thumbnail(param0: com.bumptech.glide.RequestBuilder<any>): com.github.triniwiz.imagecacheit.GlideRequest<any>; public clone(): com.github.triniwiz.imagecacheit.GlideRequest<any>; public thumbnail(param0: number): com.github.triniwiz.imagecacheit.GlideRequest<any>; public sizeMultiplier(param0: number): com.github.triniwiz.imagecacheit.GlideRequest<any>; public format(param0: com.bumptech.glide.load.DecodeFormat): com.github.triniwiz.imagecacheit.GlideRequest<any>; public transition(param0: com.bumptech.glide.TransitionOptions<any,any>): com.github.triniwiz.imagecacheit.GlideRequest<any>; public optionalFitCenter(): com.github.triniwiz.imagecacheit.GlideRequest<any>; public placeholder(param0: number): com.github.triniwiz.imagecacheit.GlideRequest<any>; public dontTransform(): com.github.triniwiz.imagecacheit.GlideRequest<any>; public load(param0: string): com.github.triniwiz.imagecacheit.GlideRequest<any>; public encodeQuality(param0: number): com.github.triniwiz.imagecacheit.GlideRequest<any>; public centerCrop(): com.github.triniwiz.imagecacheit.GlideRequest<any>; public optionalTransform(param0: java.lang.Class, param1: com.bumptech.glide.load.Transformation): com.github.triniwiz.imagecacheit.GlideRequest<any>; public error(param0: com.bumptech.glide.RequestBuilder<any>): com.github.triniwiz.imagecacheit.GlideRequest<any>; public error(param0: globalAndroid.graphics.drawable.Drawable): com.github.triniwiz.imagecacheit.GlideRequest<any>; public onlyRetrieveFromCache(param0: boolean): com.github.triniwiz.imagecacheit.GlideRequest<any>; public priority(param0: com.bumptech.glide.Priority): com.github.triniwiz.imagecacheit.GlideRequest<any>; public fallback(param0: globalAndroid.graphics.drawable.Drawable): com.github.triniwiz.imagecacheit.GlideRequest<any>; public useAnimationPool(param0: boolean): com.github.triniwiz.imagecacheit.GlideRequest<any>; public override(param0: number): com.github.triniwiz.imagecacheit.GlideRequest<any>; public load(param0: native.Array<number>): com.github.triniwiz.imagecacheit.GlideRequest<any>; public placeholder(param0: globalAndroid.graphics.drawable.Drawable): com.github.triniwiz.imagecacheit.GlideRequest<any>; public dontAnimate(): com.github.triniwiz.imagecacheit.GlideRequest<any>; /** @deprecated */ public transforms(param0: native.Array<com.bumptech.glide.load.Transformation<globalAndroid.graphics.Bitmap>>): com.github.triniwiz.imagecacheit.GlideRequest<any>; public downsample(param0: com.bumptech.glide.load.resource.bitmap.DownsampleStrategy): com.github.triniwiz.imagecacheit.GlideRequest<any>; public listener(param0: com.bumptech.glide.request.RequestListener<any>): com.github.triniwiz.imagecacheit.GlideRequest<any>; public load(param0: any): com.github.triniwiz.imagecacheit.GlideRequest<any>; public skipMemoryCache(param0: boolean): com.github.triniwiz.imagecacheit.GlideRequest<any>; public centerInside(): com.github.triniwiz.imagecacheit.GlideRequest<any>; public optionalTransform(param0: com.bumptech.glide.load.Transformation<globalAndroid.graphics.Bitmap>): com.github.triniwiz.imagecacheit.GlideRequest<any>; public set(param0: com.bumptech.glide.load.Option, param1: any): com.github.triniwiz.imagecacheit.GlideRequest<any>; public optionalCenterCrop(): com.github.triniwiz.imagecacheit.GlideRequest<any>; public load(param0: globalAndroid.net.Uri): com.github.triniwiz.imagecacheit.GlideRequest<any>; public load(param0: globalAndroid.graphics.drawable.Drawable): com.github.triniwiz.imagecacheit.GlideRequest<any>; public signature(param0: com.bumptech.glide.load.Key): com.github.triniwiz.imagecacheit.GlideRequest<any>; public load(param0: java.io.File): com.github.triniwiz.imagecacheit.GlideRequest<any>; public diskCacheStrategy(param0: com.bumptech.glide.load.engine.DiskCacheStrategy): com.github.triniwiz.imagecacheit.GlideRequest<any>; public decode(param0: java.lang.Class<any>): com.github.triniwiz.imagecacheit.GlideRequest<any>; public apply(param0: com.bumptech.glide.request.BaseRequestOptions<any>): com.github.triniwiz.imagecacheit.GlideRequest<any>; public timeout(param0: number): com.github.triniwiz.imagecacheit.GlideRequest<any>; public getDownloadOnlyRequest(): com.github.triniwiz.imagecacheit.GlideRequest<java.io.File>; public optionalCenterInside(): com.github.triniwiz.imagecacheit.GlideRequest<any>; public encodeFormat(param0: globalAndroid.graphics.Bitmap.CompressFormat): com.github.triniwiz.imagecacheit.GlideRequest<any>; public optionalCircleCrop(): com.github.triniwiz.imagecacheit.GlideRequest<any>; public transform(param0: java.lang.Class, param1: com.bumptech.glide.load.Transformation): com.github.triniwiz.imagecacheit.GlideRequest<any>; public transform(param0: native.Array<com.bumptech.glide.load.Transformation<globalAndroid.graphics.Bitmap>>): com.github.triniwiz.imagecacheit.GlideRequest<any>; public useUnlimitedSourceGeneratorsPool(param0: boolean): com.github.triniwiz.imagecacheit.GlideRequest<any>; public thumbnail(param0: native.Array<com.bumptech.glide.RequestBuilder<any>>): com.github.triniwiz.imagecacheit.GlideRequest<any>; public load(param0: java.lang.Integer): com.github.triniwiz.imagecacheit.GlideRequest<any>; public fallback(param0: number): com.github.triniwiz.imagecacheit.GlideRequest<any>; public error(param0: number): com.github.triniwiz.imagecacheit.GlideRequest<any>; public frame(param0: number): com.github.triniwiz.imagecacheit.GlideRequest<any>; public addListener(param0: com.bumptech.glide.request.RequestListener<any>): com.github.triniwiz.imagecacheit.GlideRequest<any>; public load(param0: globalAndroid.graphics.Bitmap): com.github.triniwiz.imagecacheit.GlideRequest<any>; /** @deprecated */ public load(param0: java.net.URL): com.github.triniwiz.imagecacheit.GlideRequest<any>; public transform(param0: com.bumptech.glide.load.Transformation<globalAndroid.graphics.Bitmap>): com.github.triniwiz.imagecacheit.GlideRequest<any>; public disallowHardwareConfig(): com.github.triniwiz.imagecacheit.GlideRequest<any>; } } } } } declare module com { export module github { export module triniwiz { export module imagecacheit { export class GlideRequests { public static class: java.lang.Class<com.github.triniwiz.imagecacheit.GlideRequests>; public load(param0: globalAndroid.graphics.drawable.Drawable): com.github.triniwiz.imagecacheit.GlideRequest<globalAndroid.graphics.drawable.Drawable>; public load(param0: native.Array<number>): com.github.triniwiz.imagecacheit.GlideRequest<globalAndroid.graphics.drawable.Drawable>; public addDefaultRequestListener(param0: com.bumptech.glide.request.RequestListener<any>): com.github.triniwiz.imagecacheit.GlideRequests; public load(param0: java.io.File): com.github.triniwiz.imagecacheit.GlideRequest<globalAndroid.graphics.drawable.Drawable>; public downloadOnly(): com.github.triniwiz.imagecacheit.GlideRequest<java.io.File>; public applyDefaultRequestOptions(param0: com.bumptech.glide.request.RequestOptions): com.github.triniwiz.imagecacheit.GlideRequests; public setRequestOptions(param0: com.bumptech.glide.request.RequestOptions): void; public asGif(): com.github.triniwiz.imagecacheit.GlideRequest<com.bumptech.glide.load.resource.gif.GifDrawable>; public asDrawable(): com.github.triniwiz.imagecacheit.GlideRequest<globalAndroid.graphics.drawable.Drawable>; public load(param0: string): com.github.triniwiz.imagecacheit.GlideRequest<globalAndroid.graphics.drawable.Drawable>; public download(param0: any): com.github.triniwiz.imagecacheit.GlideRequest<java.io.File>; public constructor(param0: com.bumptech.glide.Glide, param1: com.bumptech.glide.manager.Lifecycle, param2: com.bumptech.glide.manager.RequestManagerTreeNode, param3: globalAndroid.content.Context); public load(param0: any): com.github.triniwiz.imagecacheit.GlideRequest<globalAndroid.graphics.drawable.Drawable>; public as(param0: java.lang.Class): com.github.triniwiz.imagecacheit.GlideRequest<any>; public setDefaultRequestOptions(param0: com.bumptech.glide.request.RequestOptions): com.github.triniwiz.imagecacheit.GlideRequests; public asFile(): com.github.triniwiz.imagecacheit.GlideRequest<java.io.File>; public load(param0: java.lang.Integer): com.github.triniwiz.imagecacheit.GlideRequest<globalAndroid.graphics.drawable.Drawable>; public load(param0: globalAndroid.net.Uri): com.github.triniwiz.imagecacheit.GlideRequest<globalAndroid.graphics.drawable.Drawable>; /** @deprecated */ public load(param0: java.net.URL): com.github.triniwiz.imagecacheit.GlideRequest<globalAndroid.graphics.drawable.Drawable>; public asBitmap(): com.github.triniwiz.imagecacheit.GlideRequest<globalAndroid.graphics.Bitmap>; public load(param0: globalAndroid.graphics.Bitmap): com.github.triniwiz.imagecacheit.GlideRequest<globalAndroid.graphics.drawable.Drawable>; } } } } } declare module com { export module github { export module triniwiz { export module imagecacheit { export class ImageCache { public static class: java.lang.Class<com.github.triniwiz.imagecacheit.ImageCache>; public static init(param0: globalAndroid.content.Context): void; public static hasItem(param0: string, param1: com.github.triniwiz.imagecacheit.ImageCache.Callback): void; public static getItem(param0: string, param1: java.util.Map<string,string>, param2: com.github.triniwiz.imagecacheit.ImageCache.Callback): void; public constructor(); public static clear(): void; } export module ImageCache { export class Callback { public static class: java.lang.Class<com.github.triniwiz.imagecacheit.ImageCache.Callback>; /** * Constructs a new instance of the com.github.triniwiz.imagecacheit.ImageCache$Callback interface with the provided implementation. An empty constructor exists calling super() when extending the interface class. */ public constructor(implementation: { onSuccess(param0: any): void; onError(param0: any): void; }); public constructor(); public onSuccess(param0: any): void; public onError(param0: any): void; } } } } } } declare module com { export module github { export module triniwiz { export module imagecacheit { export class ImageView { public static class: java.lang.Class<com.github.triniwiz.imagecacheit.ImageView>; public TAG: string; public setImageDrawable(param0: globalAndroid.graphics.drawable.Drawable): void; public getBorderBottomLeftRadius(): number; public hasUniformBorderWidth(): boolean; public setFallbackImage(param0: globalAndroid.graphics.Bitmap): void; public setPlaceHolder(param0: number): void; public setBorderRightColor(param0: number): void; public setBorderTopRightRadius(param0: number): void; public setPlaceHolder(param0: globalAndroid.graphics.Bitmap): void; public constructor(param0: globalAndroid.content.Context, param1: globalAndroid.util.AttributeSet); public setImageURI(param0: globalAndroid.net.Uri): void; public setErrorHolder(param0: globalAndroid.net.Uri): void; public setFallbackImage(param0: globalAndroid.net.Uri): void; public getBorderLeftWidth(): number; public getBorderTopWidth(): number; public setBorderWidth(param0: number): void; public setBorderLeftWidth(param0: number): void; public setErrorHolder(param0: number): void; public setBorderTopColor(param0: number): void; public setBorderTopLeftRadius(param0: number): void; public setFallbackImage(): void; public onDraw(param0: globalAndroid.graphics.Canvas): void; public getBorderTopLeftRadius(): number; public setBorderBottomLeftRadius(param0: number): void; public getBorderTopColor(): number; public setBorderBottomWidth(param0: number): void; public setImageBitmap(param0: globalAndroid.graphics.Bitmap): void; public setDrawableSrc(param0: globalAndroid.graphics.drawable.Drawable): void; public setErrorHolder(param0: globalAndroid.graphics.Bitmap): void; public setFallbackImage(param0: globalAndroid.graphics.drawable.Drawable): void; public getBorderBottomRightRadius(): number; public hasUniformBorderRadius(): boolean; public hasUniformBorderColor(): boolean; public getUniformBorderColor(): number; public getBorderRightColor(): number; public setBorderRightWidth(param0: number): void; public setPlaceHolder(param0: globalAndroid.graphics.drawable.Drawable): void; public setErrorHolder(param0: globalAndroid.graphics.drawable.Drawable): void; public getUniformBorderWidth(): number; public setBorderLeftColor(param0: number): void; public setBorderRadius(param0: number): void; public setListener(): void; public getBorderBottomWidth(): number; public setBorderColor(param0: number): void; public hasBorderColor(): boolean; public setPlaceHolder(param0: globalAndroid.net.Uri): void; public getBorderLeftColor(): number; public setBorderTopWidth(param0: number): void; public setBorderBottomColor(param0: number): void; public getUniformBorderRadius(): number; public getBorderBottomColor(): number; public onSizeChanged(param0: number, param1: number, param2: number, param3: number): void; public getBorderRightWidth(): number; public hasBorderRadius(): boolean; public getBorderTopRightRadius(): number; public hasBorderWidth(): boolean; public hasUniformBorder(): boolean; public setBitmapSrc(param0: globalAndroid.graphics.Bitmap): void; public setUriSrc(param0: globalAndroid.net.Uri): void; public setFallbackImage(param0: number): void; public setBorderBottomRightRadius(param0: number): void; } } } } } declare module com { export module github { export module triniwiz { export module imagecacheit { export class MyAppGlideModule { public static class: java.lang.Class<com.github.triniwiz.imagecacheit.MyAppGlideModule>; public registerComponents(param0: globalAndroid.content.Context, param1: com.bumptech.glide.Glide, param2: com.bumptech.glide.Registry): void; public constructor(); } } } } } //Generics information: //com.github.triniwiz.imagecacheit.GlideRequest:1
the_stack
import { Alarm, AlarmRule, AlarmState, CompositeAlarm, Metric } from '@aws-cdk/aws-cloudwatch'; import { Port, SecurityGroup, SubnetType, Vpc } from '@aws-cdk/aws-ec2'; import { Repository } from '@aws-cdk/aws-ecr'; import { AwsLogDriver, CfnPrimaryTaskSet, CfnService, CfnTaskDefinition, CfnTaskSet, Cluster, ContainerImage, DeploymentControllerType, FargateTaskDefinition, LaunchType, PropagatedTagSource } from '@aws-cdk/aws-ecs'; import { ApplicationLoadBalancer, ApplicationProtocol, ApplicationTargetGroup, CfnListener, CfnTargetGroup, HttpCodeTarget, ListenerAction, Protocol, TargetType } from '@aws-cdk/aws-elasticloadbalancingv2'; import { RecordTarget, ARecord, HostedZone } from '@aws-cdk/aws-route53'; import { LoadBalancerTarget } from '@aws-cdk/aws-route53-targets'; import { StringParameter } from '@aws-cdk/aws-ssm'; import cdk = require('@aws-cdk/core'); interface TriviaBackendStackProps extends cdk.StackProps { domainName: string; domainZone: string; deploymentHooksStack: string; } /** * Always use the "cdk --no-version-reporting" flag with this example. * The CodeDeploy template hook prevents changes to the ECS resources and changes to non-ECS resources * from occurring in the same stack update, because the stack update cannot be done in a safe blue-green * fashion. By default, the CDK inserts a `AWS::CDK::Metadata` resource into the template it generates. * If not using the `--no-version-reporting` option and the CDK libraries are upgraded, the * `AWS::CDK::Metadata` resource will change and can result in a validation error from the CodeDeploy hook * about non-ECS resource changes. */ class TriviaBackendStack extends cdk.Stack { constructor(parent: cdk.App, name: string, props: TriviaBackendStackProps) { super(parent, name, props); // Look up container image to deploy. // Note that the image tag MUST be static in the generated CloudFormation template // (for example, the tag value cannot come from a CFN stack parameter), or else CodeDeploy // will not recognize when the tag changes and will not orchestrate any blue-green deployments. const imageRepo = Repository.fromRepositoryName(this, 'Repo', 'reinvent-trivia-backend'); const tag = (process.env.IMAGE_TAG) ? process.env.IMAGE_TAG : 'latest'; const image = ContainerImage.fromEcrRepository(imageRepo, tag) // Network infrastructure // // Note: Generally, the best practice is to minimize the number of resources in the template that // are not involved in the CodeDeploy blue-green deployment (i.e. that are not referenced by the // CodeDeploy blue-green hook). As mentioned above, the CodeDeploy hook prevents stack updates // that combine 'infrastructure' resource changes and 'blue-green' resource changes. Separating // infrastructure resources like VPC, security groups, clusters, etc into a different stack and // then referencing them in this stack would minimize the likelihood of that happening. But, for // the simplicity of this example, these resources are all created in the same stack. const vpc = new Vpc(this, 'VPC', { maxAzs: 2 }); const cluster = new Cluster(this, 'Cluster', { clusterName: props.domainName.replace(/\./g, '-'), vpc, containerInsights: true }); const serviceSG = new SecurityGroup(this, 'ServiceSecurityGroup', { vpc }); // Lookup pre-existing TLS certificate const certificateArn = StringParameter.fromStringParameterAttributes(this, 'CertArnParameter', { parameterName: 'CertificateArn-' + props.domainName }).stringValue; // Public load balancer const loadBalancer = new ApplicationLoadBalancer(this, 'LoadBalancer', { vpc, internetFacing: true }); serviceSG.connections.allowFrom(loadBalancer, Port.tcp(80)); new cdk.CfnOutput(this, 'ServiceURL', { value: 'https://' + props.domainName + '/api/docs/'}); new cdk.CfnOutput(this, 'LoadBalancerDnsName', { value: loadBalancer.loadBalancerDnsName }); const domainZone = HostedZone.fromLookup(this, 'Zone', { domainName: props.domainZone }); new ARecord(this, 'DNS', { zone: domainZone, recordName: props.domainName, target: RecordTarget.fromAlias(new LoadBalancerTarget(loadBalancer)), }); // Target groups: // We need two target groups that the ECS containers can be registered to. // CodeDeploy will shift traffic between these two target groups. const tg1 = new ApplicationTargetGroup(this, 'ServiceTargetGroupBlue', { port: 80, protocol: ApplicationProtocol.HTTP, targetType: TargetType.IP, vpc, deregistrationDelay: cdk.Duration.seconds(5), healthCheck: { interval: cdk.Duration.seconds(5), path: '/', protocol: Protocol.HTTP, healthyHttpCodes: '200', healthyThresholdCount: 2, unhealthyThresholdCount: 3, timeout: cdk.Duration.seconds(4) } }); const tg2 = new ApplicationTargetGroup(this, 'ServiceTargetGroupGreen', { port: 80, protocol: ApplicationProtocol.HTTP, targetType: TargetType.IP, vpc, deregistrationDelay: cdk.Duration.seconds(5), healthCheck: { interval: cdk.Duration.seconds(5), path: '/', protocol: Protocol.HTTP, healthyHttpCodes: '200', healthyThresholdCount: 2, unhealthyThresholdCount: 3, timeout: cdk.Duration.seconds(4) } }); // Listeners: // CodeDeploy will shift traffic from blue to green and vice-versa // in both the production and test listeners. // The production listener is used for normal, production traffic. // The test listener is used for test traffic, like integration tests // which can run as part of a CodeDeploy lifecycle event hook prior to // traffic being shifted in the production listener. // Both listeners initially point towards the blue target group. const listener = loadBalancer.addListener('ProductionListener', { port: 443, protocol: ApplicationProtocol.HTTPS, open: true, certificateArns: [certificateArn], defaultAction: ListenerAction.weightedForward([{ targetGroup: tg1, weight: 100 }]) }); let testListener = loadBalancer.addListener('TestListener', { port: 9002, // test traffic port protocol: ApplicationProtocol.HTTPS, open: true, certificateArns: [certificateArn], defaultAction: ListenerAction.weightedForward([{ targetGroup: tg1, weight: 100 }]) }); // ECS Resources: task definition, service, task set, etc // The CodeDeploy blue-green hook will take care of orchestrating the sequence of steps // that CloudFormation takes during the deployment: the creation of the 'green' task set, // shifting traffic to the new task set, and draining/deleting the 'blue' task set. // The 'blue' task set is initially provisioned, pointing to the 'blue' target group. const taskDefinition = new FargateTaskDefinition(this, 'TaskDefinition', {}); const container = taskDefinition.addContainer('web', { image, logging: new AwsLogDriver({ streamPrefix: 'Service' }), }); container.addPortMappings({ containerPort: 80 }); const service = new CfnService(this, 'Service', { cluster: cluster.clusterName, desiredCount: 3, deploymentController: { type: DeploymentControllerType.EXTERNAL }, propagateTags: PropagatedTagSource.SERVICE, }); service.node.addDependency(tg1); service.node.addDependency(tg2); service.node.addDependency(listener); service.node.addDependency(testListener); const taskSet = new CfnTaskSet(this, 'TaskSet', { cluster: cluster.clusterName, service: service.attrName, scale: { unit: 'PERCENT', value: 100 }, taskDefinition: taskDefinition.taskDefinitionArn, launchType: LaunchType.FARGATE, loadBalancers: [ { containerName: 'web', containerPort: 80, targetGroupArn: tg1.targetGroupArn, } ], networkConfiguration: { awsVpcConfiguration: { assignPublicIp: 'DISABLED', securityGroups: [ serviceSG.securityGroupId ], subnets: vpc.selectSubnets({ subnetType: SubnetType.PRIVATE }).subnetIds, } }, }); new CfnPrimaryTaskSet(this, 'PrimaryTaskSet', { cluster: cluster.clusterName, service: service.attrName, taskSetId: taskSet.attrId, }); // CodeDeploy hook and transform to configure the blue-green deployments. // // Note: Stack updates that contain changes in the template to both ECS resources and non-ECS resources // will result in the following error from the CodeDeploy hook: // "Additional resource diff other than ECS application related resource update is detected, // CodeDeploy can't perform BlueGreen style update properly." // In this case, you can either: // 1) Separate the resources into multiple, separate stack updates: First, deploy the changes to the // non-ECS resources only, using the same container image tag during the template synthesis that is // currently deployed to the ECS service. Then, deploy the changes to the ECS service, for example // deploying a new container image tag. This is the best practice. // 2) Temporarily disable the CodeDeploy blue-green hook: Comment out the CodeDeploy transform and hook // code below. The next stack update will *not* deploy the ECS service changes in a blue-green fashion. // Once the stack update is completed, uncomment the CodeDeploy transform and hook code to re-enable // blue-green deployments. this.addTransform('AWS::CodeDeployBlueGreen'); const taskDefLogicalId = this.getLogicalId(taskDefinition.node.defaultChild as CfnTaskDefinition) const taskSetLogicalId = this.getLogicalId(taskSet) new cdk.CfnCodeDeployBlueGreenHook(this, 'CodeDeployBlueGreenHook', { trafficRoutingConfig: { type: cdk.CfnTrafficRoutingType.TIME_BASED_CANARY, timeBasedCanary: { // Shift 20% of prod traffic, then wait 15 minutes stepPercentage: 20, bakeTimeMins: 15 } }, additionalOptions: { // After canary period, shift 100% of prod traffic, then wait 30 minutes terminationWaitTimeInMinutes: 30 }, lifecycleEventHooks: { // invoke lifecycle event hook function after test traffic is live, but before prod traffic is live afterAllowTestTraffic: 'CodeDeployHook_-' + props.deploymentHooksStack + '-pre-traffic-hook' }, serviceRole: 'CodeDeployHookRole_' + props.deploymentHooksStack, applications: [{ target: { type: service.cfnResourceType, logicalId: this.getLogicalId(service) }, ecsAttributes: { taskDefinitions: [ taskDefLogicalId, taskDefLogicalId + 'Green' ], taskSets: [ taskSetLogicalId, taskSetLogicalId + 'Green' ], trafficRouting: { prodTrafficRoute: { type: CfnListener.CFN_RESOURCE_TYPE_NAME, logicalId: this.getLogicalId(listener.node.defaultChild as CfnListener) }, testTrafficRoute: { type: CfnListener.CFN_RESOURCE_TYPE_NAME, logicalId: this.getLogicalId(testListener.node.defaultChild as CfnListener) }, targetGroups: [ this.getLogicalId(tg1.node.defaultChild as CfnTargetGroup), this.getLogicalId(tg2.node.defaultChild as CfnTargetGroup) ] } } }] }); // Alarms: // These resources alarm on unhealthy hosts and HTTP 500s at the target group level. // In order to have stack updates automatically rollback based on these alarms, // the alarms need to manually be configured as rollback triggers on the stack // after the stack is created. const tg1UnhealthyHosts = new Alarm(this, 'TargetGroupBlueUnhealthyHosts', { alarmName: this.stackName + '-Unhealthy-Hosts-Blue', metric: new Metric({ namespace: 'AWS/ApplicationELB', metricName: 'UnHealthyHostCount', statistic: 'Average', dimensions: { TargetGroup: tg1.targetGroupFullName, LoadBalancer: loadBalancer.loadBalancerFullName, }, }), threshold: 1, evaluationPeriods: 2, }); const tg1ApiFailure = new Alarm(this, 'TargetGroupBlue5xx', { alarmName: this.stackName + '-Http-500-Blue', metric: new Metric({ namespace: 'AWS/ApplicationELB', metricName: HttpCodeTarget.TARGET_5XX_COUNT, statistic: 'Sum', dimensions: { TargetGroup: tg1.targetGroupFullName, LoadBalancer: loadBalancer.loadBalancerFullName, }, }), threshold: 1, evaluationPeriods: 1, period: cdk.Duration.minutes(1) }); const tg2UnhealthyHosts = new Alarm(this, 'TargetGroupGreenUnhealthyHosts', { alarmName: this.stackName + '-Unhealthy-Hosts-Green', metric: new Metric({ namespace: 'AWS/ApplicationELB', metricName: 'UnHealthyHostCount', statistic: 'Average', dimensions: { TargetGroup: tg2.targetGroupFullName, LoadBalancer: loadBalancer.loadBalancerFullName, }, }), threshold: 1, evaluationPeriods: 2, }); const tg2ApiFailure = new Alarm(this, 'TargetGroupGreen5xx', { alarmName: this.stackName + '-Http-500-Green', metric: new Metric({ namespace: 'AWS/ApplicationELB', metricName: HttpCodeTarget.TARGET_5XX_COUNT, statistic: 'Sum', dimensions: { TargetGroup: tg2.targetGroupFullName, LoadBalancer: loadBalancer.loadBalancerFullName, }, }), threshold: 1, evaluationPeriods: 1, period: cdk.Duration.minutes(1) }); new CompositeAlarm(this, 'CompositeUnhealthyHosts', { compositeAlarmName: this.stackName + '-Unhealthy-Hosts', alarmRule: AlarmRule.anyOf( AlarmRule.fromAlarm(tg1UnhealthyHosts, AlarmState.ALARM), AlarmRule.fromAlarm(tg2UnhealthyHosts, AlarmState.ALARM)) }); new CompositeAlarm(this, 'Composite5xx', { compositeAlarmName: this.stackName + '-Http-500', alarmRule: AlarmRule.anyOf( AlarmRule.fromAlarm(tg1ApiFailure, AlarmState.ALARM), AlarmRule.fromAlarm(tg2ApiFailure, AlarmState.ALARM)) }); } } const app = new cdk.App(); new TriviaBackendStack(app, 'TriviaBackendTest', { domainName: 'api-test.reinvent-trivia.com', domainZone: 'reinvent-trivia.com', deploymentHooksStack: 'TriviaBackendHooksTest', env: { account: process.env['CDK_DEFAULT_ACCOUNT'], region: 'us-east-1' }, tags: { project: 'reinvent-trivia' } }); new TriviaBackendStack(app, 'TriviaBackendProd', { domainName: 'api.reinvent-trivia.com', domainZone: 'reinvent-trivia.com', deploymentHooksStack: 'TriviaBackendHooksProd', env: { account: process.env['CDK_DEFAULT_ACCOUNT'], region: 'us-east-1' }, tags: { project: 'reinvent-trivia' } }); app.synth();
the_stack
import memoize from 'lru-memoize'; import { TEdge } from '@jaegertracing/plexus/lib/types'; import getDerivedViewModifiers from './getDerivedViewModifiers'; import getEdgeId from './getEdgeId'; import getPathElemHasher, { FOCAL_KEY } from './getPathElemHasher'; import { decode, encode } from '../visibility-codec'; import { PathElem, ECheckedStatus, EDdgDensity, EDirection, TDdgDistanceToPathElems, TDdgModel, TDdgVertex, } from '../types'; export { default as getEdgeId } from './getEdgeId'; export default class GraphModel { readonly getDerivedViewModifiers = memoize(3)(getDerivedViewModifiers.bind(this)); private readonly getPathElemHasher = getPathElemHasher; readonly density: EDdgDensity; readonly distanceToPathElems: TDdgDistanceToPathElems; readonly pathElemToEdge: Map<PathElem, TEdge>; readonly pathElemToVertex: Map<PathElem, TDdgVertex>; readonly showOp: boolean; readonly vertexToPathElems: Map<TDdgVertex, Set<PathElem>>; readonly vertices: Map<string, TDdgVertex>; readonly visIdxToPathElem: PathElem[]; constructor({ ddgModel, density, showOp }: { ddgModel: TDdgModel; density: EDdgDensity; showOp: boolean }) { this.density = density; this.distanceToPathElems = new Map(ddgModel.distanceToPathElems); this.pathElemToEdge = new Map(); this.pathElemToVertex = new Map(); this.showOp = showOp; this.vertexToPathElems = new Map(); this.vertices = new Map(); this.visIdxToPathElem = ddgModel.visIdxToPathElem.slice(); const focalOperations: Set<string> = new Set(); const hasher = this.getPathElemHasher(); const edgesById = new Map<string, TEdge>(); this.visIdxToPathElem.forEach(pathElem => { // If there is a compatible vertex for this pathElem, use it, else, make a new vertex const key = hasher(pathElem); const isFocalNode = !pathElem.distance; const operation = this.showOp ? pathElem.operation.name : null; if (isFocalNode && operation) focalOperations.add(operation); let vertex: TDdgVertex | undefined = this.vertices.get(key); if (!vertex) { vertex = { key, isFocalNode, service: pathElem.operation.service.name, operation, }; this.vertices.set(key, vertex); this.vertexToPathElems.set(vertex, new Set([pathElem])); } else { const pathElemsForVertex = this.vertexToPathElems.get(vertex); /* istanbul ignore next */ if (!pathElemsForVertex) { throw new Error(`Vertex exists without pathElems, vertex: ${vertex}`); } // Link vertex back to this pathElem pathElemsForVertex.add(pathElem); } // Link pathElem to its vertex this.pathElemToVertex.set(pathElem, vertex); // If the newly-visible PathElem is not the focalNode, it needs to be connected to the rest of the graph const connectedElem = pathElem.focalSideNeighbor; if (connectedElem) { const connectedVertex = this.pathElemToVertex.get(connectedElem); // If the connectedElem does not have a vertex, then the current pathElem cannot be connected to the // focalNode if (!connectedVertex) { throw new Error(`Non-focal pathElem cannot be connected to graph. PathElem: ${pathElem}`); } // Create edge connecting current vertex to connectedVertex const from = pathElem.distance > 0 ? connectedVertex.key : vertex.key; const to = pathElem.distance > 0 ? vertex.key : connectedVertex.key; const edgeId = getEdgeId(from, to); let edge = edgesById.get(edgeId); if (!edge) { edge = { from, to }; edgesById.set(edgeId, edge); } this.pathElemToEdge.set(pathElem, edge); } }); if (focalOperations.size > 1) { const focalVertex = this.vertices.get(FOCAL_KEY); // istanbul ignore next : focalVertex cannot be missing if focalOperations.size is not 0 if (focalVertex) focalVertex.operation = Array.from(focalOperations); } Object.freeze(this.distanceToPathElems); Object.freeze(this.pathElemToEdge); Object.freeze(this.pathElemToVertex); Object.freeze(this.vertexToPathElems); Object.freeze(this.vertices); Object.freeze(this.visIdxToPathElem); } private getDefaultVisiblePathElems() { return ([] as PathElem[]).concat( this.distanceToPathElems.get(-2) || [], this.distanceToPathElems.get(-1) || [], this.distanceToPathElems.get(0) || [], this.distanceToPathElems.get(1) || [], this.distanceToPathElems.get(2) || [] ); } private getGeneration = (vertexKey: string, direction: EDirection, visEncoding?: string): PathElem[] => { const rv: PathElem[] = []; const elems = this.getVertexVisiblePathElems(vertexKey, visEncoding); if (!elems) return rv; elems.forEach(({ focalSideNeighbor, memberIdx, memberOf }) => { const generationMember = memberOf.members[memberIdx + direction]; if (generationMember && generationMember !== focalSideNeighbor) rv.push(generationMember); }); return rv; }; public getGenerationVisibility = ( vertexKey: string, direction: EDirection, visEncoding?: string ): ECheckedStatus | null => { const generation = this.getGeneration(vertexKey, direction, visEncoding); if (!generation.length) return null; const visibleIndices = this.getVisibleIndices(visEncoding); const visibleGeneration = generation.filter(({ visibilityIdx }) => visibleIndices.has(visibilityIdx)); if (visibleGeneration.length === generation.length) return ECheckedStatus.Full; if (visibleGeneration.length) return ECheckedStatus.Partial; return ECheckedStatus.Empty; }; private getVisiblePathElems(visEncoding?: string) { if (visEncoding == null) return this.getDefaultVisiblePathElems(); return decode(visEncoding) .map(visIdx => this.visIdxToPathElem[visIdx]) .filter(Boolean); } public getVisibleIndices(visEncoding?: string): Set<number> { return new Set(this.getVisiblePathElems(visEncoding).map(({ visibilityIdx }) => visibilityIdx)); } public getVisible: (visEncoding?: string) => { edges: TEdge[]; vertices: TDdgVertex[] } = memoize(10)( (visEncoding?: string): { edges: TEdge[]; vertices: TDdgVertex[] } => { const edges: Set<TEdge> = new Set(); const vertices: Set<TDdgVertex> = new Set(); const pathElems = this.getVisiblePathElems(visEncoding); pathElems.forEach(pathElem => { const edge = this.pathElemToEdge.get(pathElem); if (edge) edges.add(edge); const vertex = this.pathElemToVertex.get(pathElem); if (vertex && !vertex.isFocalNode) vertices.add(vertex); }); if (this.visIdxToPathElem.length) { const focalVertex = this.vertices.get(FOCAL_KEY); // istanbul ignore next : If there are pathElems without a focal vertex the constructor would throw if (!focalVertex) throw new Error('No focal vertex found'); const visibleFocalElems = this.getVertexVisiblePathElems(FOCAL_KEY, visEncoding); if (visibleFocalElems && visibleFocalElems.length) { if (!this.showOp) vertices.add(focalVertex); else { const visibleFocalOps = Array.from( new Set(visibleFocalElems.map(({ operation }) => operation.name)) ); const potentiallyPartialFocalVertex = { ...focalVertex, operation: visibleFocalOps.length === 1 ? visibleFocalOps[0] : visibleFocalOps, }; vertices.add(potentiallyPartialFocalVertex); } } } return { edges: Array.from(edges), vertices: Array.from(vertices), }; } ); private static getUiFindMatches(vertices: TDdgVertex[], uiFind?: string): Set<string> { const keySet: Set<string> = new Set(); if (!uiFind || /^\s+$/.test(uiFind)) return keySet; const uiFindArr = uiFind .trim() .toLowerCase() .split(/\s+/); for (let i = 0; i < vertices.length; i++) { const { service, operation } = vertices[i]; const svc = service.toLowerCase(); const ops = operation && (Array.isArray(operation) ? operation : [operation]).map(op => op.toLowerCase()); for (let j = 0; j < uiFindArr.length; j++) { if (svc.includes(uiFindArr[j]) || (ops && ops.some(op => op.includes(uiFindArr[j])))) { keySet.add(vertices[i].key); break; } } } return keySet; } public getHiddenUiFindMatches: (uiFind?: string, visEncoding?: string) => Set<string> = memoize(10)( (uiFind?: string, visEncoding?: string): Set<string> => { const visible = new Set(this.getVisible(visEncoding).vertices); const hidden: TDdgVertex[] = Array.from(this.vertices.values()).filter( vertex => !visible.has(vertex) && !vertex.isFocalNode ); if (this.visIdxToPathElem.length) { const focalVertex = this.vertices.get(FOCAL_KEY); // istanbul ignore next : If there are pathElems without a focal vertex the constructor would throw if (!focalVertex) throw new Error('No focal vertex found'); const focalElems = this.vertexToPathElems.get(focalVertex); // istanbul ignore next : If there are pathElems without a focal vertex the constructor would throw if (!focalElems) throw new Error('No focal elems found'); const visibleFocalElems = new Set(this.getVertexVisiblePathElems(FOCAL_KEY, visEncoding)); const hiddenFocalOperations = Array.from(focalElems) .filter(elem => !visibleFocalElems.has(elem)) .map(({ operation }) => operation.name); if (hiddenFocalOperations.length) { hidden.push({ ...focalVertex, operation: hiddenFocalOperations, }); } } return GraphModel.getUiFindMatches(hidden, uiFind); } ); public getVisibleUiFindMatches: (uiFind?: string, visEncoding?: string) => Set<string> = memoize(10)( (uiFind?: string, visEncoding?: string): Set<string> => { const { vertices } = this.getVisible(visEncoding); return GraphModel.getUiFindMatches(vertices, uiFind); } ); private getVisWithoutElems(elems: PathElem[], visEncoding?: string) { const visible = this.getVisibleIndices(visEncoding); elems.forEach(({ externalPath }) => { externalPath.forEach(({ visibilityIdx }) => { visible.delete(visibilityIdx); }); }); return encode(Array.from(visible)); } public getVisWithoutVertex(vertexKey: string, visEncoding?: string): string | undefined { const elems = this.getVertexVisiblePathElems(vertexKey, visEncoding); if (elems && elems.length) return this.getVisWithoutElems(elems, visEncoding); return undefined; } private getVisWithElems(elems: PathElem[], visEncoding?: string) { const visible = this.getVisibleIndices(visEncoding); elems.forEach(({ focalPath }) => focalPath.forEach(({ visibilityIdx }) => { visible.add(visibilityIdx); }) ); return encode(Array.from(visible)); } public getVisWithUpdatedGeneration( vertexKey: string, direction: EDirection, visEncoding?: string ): { visEncoding: string; update: ECheckedStatus } | null { const generationElems = this.getGeneration(vertexKey, direction, visEncoding); const currCheckedStatus = this.getGenerationVisibility(vertexKey, direction, visEncoding); if (!generationElems.length || !currCheckedStatus) return null; if (currCheckedStatus === ECheckedStatus.Full) { return { visEncoding: this.getVisWithoutElems(generationElems, visEncoding), update: ECheckedStatus.Empty, }; } return { visEncoding: this.getVisWithElems(generationElems, visEncoding), update: ECheckedStatus.Full, }; } public getVisWithVertices(vertexKeys: string[], visEncoding?: string) { const elemSet: PathElem[] = []; vertexKeys.forEach(vertexKey => { const vertex = this.vertices.get(vertexKey); if (!vertex) throw new Error(`${vertexKey} does not exist in graph`); const elems = this.vertexToPathElems.get(vertex); // istanbul ignore next : If a vertex exists it must have elems if (!elems) throw new Error(`${vertexKey} does not exist in graph`); elemSet.push(...elems); }); return this.getVisWithElems(elemSet, visEncoding); } public getVertexVisiblePathElems( vertexKey: string, visEncoding: string | undefined ): PathElem[] | undefined { const vertex = this.vertices.get(vertexKey); if (vertex) { const pathElems = this.vertexToPathElems.get(vertex); if (pathElems && pathElems.size) { const visIndices = this.getVisibleIndices(visEncoding); return Array.from(pathElems).filter(elem => { return visIndices.has(elem.visibilityIdx); }); } } return undefined; } } export const makeGraph = memoize(10)( (ddgModel: TDdgModel, showOp: boolean, density: EDdgDensity) => new GraphModel({ ddgModel, density, showOp }) );
the_stack
import {Component, ElementRef, Inject, Input, OnInit, ViewChild} from '@angular/core'; import {TestStepResult} from "../../models/test-step-result.model"; import {TestStepType} from "../../enums/test-step-type.enum"; import {MatDialog} from "@angular/material/dialog"; import {ElementFormComponent} from "./element-form.component"; import {ScreenShortOverlayComponent} from "./screen-short-overlay.component"; import {defaultPageScrollConfig, PageScrollService} from "ngx-page-scroll-core"; import {DOCUMENT} from "@angular/common"; import {TestStepResultService} from "../../services/test-step-result.service"; import {ElementService} from "../../shared/services/element.service"; import {BaseComponent} from "../../shared/components/base.component"; import {AuthenticationGuard} from "../../shared/guards/authentication.guard"; import {NotificationsService} from 'angular2-notifications'; import {TranslateService} from '@ngx-translate/core'; import {ToastrService} from "ngx-toastr"; import {WorkspaceVersionService} from "../../shared/services/workspace-version.service"; import {WorkspaceVersion} from "../../models/workspace-version.model"; import {TestStepService} from "../../services/test-step.service"; import {TestStep} from "../../models/test-step.model"; import {Element} from "../../models/element.model"; import {ActivatedRoute} from "@angular/router"; import {AddonElementData} from "../../models/addon-element-data.model"; import {AddonTestStepTestData} from "../../models/addon-test-step-test-data.model"; import {TestDeviceResultService} from "../../shared/services/test-device-result.service"; import {TestDeviceResult} from "../../models/test-device-result.model"; import {UploadService} from "../../shared/services/upload.service"; @Component({ selector: 'app-action-step-result-details', templateUrl: './action-step-result-details.component.html', styles: [] }) export class ActionStepResultDetailsComponent extends BaseComponent implements OnInit { @Input('testStepResult') testStepResult: TestStepResult; public TestStepType: typeof TestStepType = TestStepType; public isScreenshotBroken: boolean = false; public isScreenshotExpired: boolean = false; public isShowMetaData: boolean = false; public isShowAttachment: boolean = false; public isShowAddonLogs: boolean = false; public preRequestStep: TestStepResult; @ViewChild('stepDetailsRef', {static: false}) public stepDetailsRef: ElementRef; public isSelected: string = 'step_data'; public version: WorkspaceVersion; public testStep: TestStep; public environmentResult: TestDeviceResult; private showScreenShortFlag: Boolean = false; public isCapabilities: Boolean = false; public showDetails: boolean = false; public element: Element; public addonElementData: AddonElementData[]; public addonTestStepTestData: AddonTestStepTestData[]; public appDetails: JSON = JSON.parse('{}'); public ElementDetails; elementDetails: {}; isShowElementDetails: boolean; stepElementDetails: IElementDetails = {}; constructor( public authGuard: AuthenticationGuard, public notificationsService: NotificationsService, public translate: TranslateService, public toastrService: ToastrService, private matDialog: MatDialog, private pageScrollService: PageScrollService, @Inject(DOCUMENT) private document: any, private elementService: ElementService, private versionService: WorkspaceVersionService, private testStepService: TestStepService, private environmentResultService: TestDeviceResultService, private testStepResultService: TestStepResultService, private uploadService: UploadService, private router: ActivatedRoute) { super(authGuard, notificationsService, translate, toastrService); defaultPageScrollConfig.scrollOffset = 200; defaultPageScrollConfig.duration = 20; } ngOnInit() { if (this.testStepResult) { let currentDate = new Date(); let executionStartTime = new Date(this.testStepResult.startTime); let diffInMillis = currentDate.getTime() - executionStartTime.getTime(); if (((diffInMillis) / (1000 * 60 * 60 * 24)) > 30) { this.isScreenshotExpired = true; } if (this.testStepResult?.addonElements) { this.addonElementData = this.getElements(this.testStepResult?.addonElements); } if (this.testStepResult?.addonTestData) { this.addonTestStepTestData = this.getTestData(this.testStepResult?.addonTestData); } this.isScreenshotBroken = false; } } ngOnChanges() { this.fetchElementDetails(this.testStepResult?.stepDetails?.dataMap?.elementString); this.preRequestStep = undefined; if (this.testStepResult?.testCase?.workspaceVersionId) this.versionService.show(this.testStepResult?.testCase?.workspaceVersionId).subscribe(res => this.version = res) if (this.testStepResult?.metadata?.preRequisite) { this.setPreRequisiteStep(this.testStepResult?.metadata?.preRequisite); } if (this.testStepResult?.envRunId) { this.environmentResultService.show(this.testStepResult?.envRunId).subscribe(data => { this.environmentResult = data; this.getAppDetails(); }) } // this.fetchElementDetailsByName(this.testStepResult?.stepDetails?.dataMap?.elementString); if (this.testStepResult?.addonElements) { this.addonElementData = this.getElements(this.testStepResult?.addonElements); } if (this.testStepResult?.addonTestData) { this.addonTestStepTestData = this.getTestData(this.testStepResult?.addonTestData); } if (this.testStepResult?.stepId && !this.testStepResult?.testStep) { this.testStepService.findAll("id:" + this.testStepResult.stepId).subscribe(res => { this.testStep = res?.content[0]; if (this.testStep?.preRequisiteStepId && !this.preRequestStep) this.setPreRequisiteStep(this.testStep?.preRequisiteStepId) }) } else if (this.testStepResult?.testStep) { this.testStep = this.testStepResult?.testStep; } this.isScreenshotBroken = false; } getElementDetails() { if (!this.ElementDetails) this.ElementDetails = this.getElements(this.testStepResult?.elementDetails, true); return this.ElementDetails.length || this.element?.locatorValue;//TODO Fallback element details need to clean } isEmptyObject(obj){ return Object.keys(obj).length==0; } canShowCustomFunctionsParameters(args){ return args ? Object.keys(args).length : 0; } setPreRequisiteStep(stepId: Number) { this.testStepResultService.findAll("stepId:" + stepId + ",testCaseResultId:" + this.testStepResult.testCaseResultId).subscribe(response => { this.preRequestStep = response.content[0]; }); } get preRequisiteStep() { return this.preRequestStep?.testStep?.stepDisplayNumber ? this.preRequestStep?.testStep?.stepDisplayNumber : (<number>this.preRequestStep?.stepDetail?.order_id + 1) } fetchElementByName(elementName, addonElement?) { this.elementService.findAll('name:' + encodeURIComponent(elementName) + ',workspaceVersionId:' + this.testStepResult?.testCase?.workspaceVersionId).subscribe( (res) => { if(res.numberOfElements > 1) console.warn('more than one element found with the name: '+elementName); let currentStepElement = res.content[0]; this.setElementDetails(currentStepElement); this.testStepResult.isElementChanged = res?.content?.length == 0; if (addonElement) { addonElement.isElementChanged = res?.content?.length == 0; addonElement.element = res.content[0]; } if (!this.testStepResult.isElementChanged) this.element = res.content[0]; }, (err) => { addonElement ? addonElement.isElementChanged = true : ''; this.testStepResult.isElementChanged = true; } ) } fetchElementDetailsByName(elementName: String) { if(!elementName) this.setElementDetails(null); else { this.elementService.findAll('name:' + encodeURIComponent(elementName.toString()) + ',workspaceVersionId:' + this.testStepResult?.testCase?.workspaceVersionId).subscribe( (res) => { if(res.numberOfElements > 1) console.warn('More than one element found with the name: '+ elementName); let currentStepElement = res.content[0]; this.setElementDetails(currentStepElement); }, (err) => { console.debug('Error while finding elements:: '+err); } ) } } setElementDetails(currentStepElement: Element) { if(currentStepElement) { this.stepElementDetails = {}; this.stepElementDetails.elementName = currentStepElement.name.toString(); this.stepElementDetails.locatorType = currentStepElement.locatorType.toString(); this.stepElementDetails.locator = currentStepElement.locatorValue.toString(); this.stepElementDetails.createdType = currentStepElement.createdType.toString(); // this.stepElementDetails.status = currentStepElement.status.toString(); } else { this.stepElementDetails = {}; this.stepElementDetails.elementName = this.translate.instant('element.step.not_found'); } } setBrokenImage() { this.isScreenshotBroken = true; } setRefreshImage() { this.showScreenShortFlag = false; this.showScreenShortFlag = true; this.isScreenshotBroken = false; } openEditElement(name, isAddonElement?: boolean) { this.matDialog.open(ElementFormComponent, { height: "100vh", width: '60%', position: {top: '0px', right: '0px'}, data: { name: name, versionId: this.testStepResult?.testCase?.workspaceVersionId, testCaseResultId: this.testStepResult.testCaseResultId }, panelClass: ['mat-dialog', 'rds-none'] }).afterClosed().subscribe((res: Element) => { if (res && res instanceof Element) { if (isAddonElement) this.updateAddonElements(name, res.name); else this.testStep.element = res.name; this.testStepService.update(this.testStep).subscribe() this.testStepResult.isElementChanged = true; } }) } toggleAttachment() { this.isShowAttachment = !this.isShowAttachment; } toggleMetadata() { this.isShowMetaData = !this.isShowMetaData; } toggleAddonLogs() { this.isShowAddonLogs = !this.isShowAddonLogs; } toggleCapabilities() { this.isCapabilities = !this.isCapabilities } openScreenShort() { this.matDialog.open(ScreenShortOverlayComponent, { width: '100vw', height: '100vh', position: {top: '0', left: '0', right: '0', bottom: '0'}, data: {screenShortUrl: this.testStepResult.screenShotURL}, panelClass: ['mat-dialog', 'full-width', 'rds-none'] }) } get showScreenShort() { return !(this.testStepResult?.isStepGroup || this.testStepResult?.isForLoop || this.testStepResult?.isRestStep || this.testStepResult?.stepGroup || this.version?.workspace?.isRest); } get ShowFixElementCheck(): Boolean { return this.testStepResult?.canShowFixElement; } getElements(elements: Map<string, any>, isUpdate?) { let result = []; if (elements) Object.keys(elements).forEach(key => { if (!isUpdate) this.fetchElementByName(elements[key].name, elements[key]); result.push(elements[key]); }); return result; } getTestData(testDataMap: Map<String, AddonTestStepTestData>) { let result = []; Object.keys(testDataMap).forEach(key => { result.push(testDataMap[key]); }); return result; } updateAddonElements(oldName, newName) { let testStepResultElements = this.getElements(this.testStepResult?.addonElements, true); let testStepElements = this.getElements(this.testStep?.addonElements, true); for (let i = 0; i < testStepElements.length; i++) { if (testStepElements[i].name == oldName) { testStepElements[i].name = newName; testStepResultElements[i].isElementChanged = true; testStepElements[i].isElementChanged = true; } } } toggleShowDetails() { this.showDetails = !this.showDetails; } getAppDetails() { let json: JSON = JSON.parse("{}"); if (this.environmentResult.testDeviceSettings.appPackage) json['appPackage'] = this.environmentResult.testDeviceSettings.appPackage; if (this.environmentResult.testDeviceSettings.appActivity) json['appActivity'] = this.environmentResult.testDeviceSettings.appActivity; // if(this.testDeviceResult.testDeviceSettings.app) // json['app']= this.testDeviceResult.testDeviceSettings.app; if (this.environmentResult.testDeviceSettings.appUrl) json['appUrl'] = this.environmentResult.testDeviceSettings.appUrl; if (this.environmentResult.testDeviceSettings.appId) json['appId'] = this.environmentResult.testDeviceSettings.appId; this.appDetails = json; if (this.environmentResult.testDeviceSettings.appUploadId || this.environmentResult.testDeviceSettings.appId) this.uploadService.find(this.environmentResult.testDeviceSettings.appUploadId || this.environmentResult.testDeviceSettings.appId).subscribe(app => { this.appDetails['appName'] = app.name; }) } canShowDetails() { return Object.keys(this.appDetails).length > 0; } processJsonCapabilities() { if (this.environmentResult?.testDeviceSettings?.capabilities) { this.environmentResult?.testDeviceSettings?.capabilities.forEach(data => { if (data.type == 'java.lang.String') { data.type = 'String' } else if (data.type == 'java.lang.integer') { data.type = 'Integer' } else if (data.type == 'java.lang.boolean') { data.type = 'Boolean' } }) } return this.environmentResult?.testDeviceSettings?.capabilities; } //TODO Fallback element details need to clean get elementName(){ return this.ElementDetails[0]?.elementName ? this.ElementDetails[0]?.elementName : this.element.name; } get elementValue() { return this.ElementDetails[0]?.locatorValue ? this.ElementDetails[0]?.locatorValue : this.element.locatorValue; } get elementType() { return this.ElementDetails[0]?.findByType ? this.ElementDetails[0]?.findByType : this.element.locatorType; } fetchElementDetails(elementName){ this.elementDetails = { 'element name': this.testStepResult.elementDetails['element']?.elementName, 'locator type': this.testStepResult.elementDetails['element']?.locatorStrategyName, 'locator': this.testStepResult.elementDetails['element']?.locatorValue } } toggleElementDetails() { this.isShowElementDetails = !this.isShowElementDetails; } get hasDefaultActionElements() { return !this.testStepResult?.isRestStep && this.testStepResult?.stepDetails?.dataMap?.elementString && !this.testStepResult?.addonElements; } get hasAddonActionElements() { return !this.testStepResult?.isRestStep && this.testStepResult?.addonElements; } get canShowFrameInfo() { return !(this.testStepResult?.isPassed || this.testStepResult?.isQueued || this.testStepResult?.isNotExecuted) && (this.element?.metadata?.currentElement?.['isFrameElement']) } } interface IElementDetails { elementName?: string; locatorType?: string; locator?: string; createdType?: string; status?: string; }
the_stack
import * as React from "react"; import { NonIdealState, Tabs, Tab, FormGroup, NumericInput, RadioGroup, Radio, InputGroup, Switch, Button, Intent, ButtonGroup, SwitchProps } from '@blueprintjs/core'; import { tr } from "../api/i18n"; import { ExprOr, isEvaluatable, IPointIconStyle, IBasicPointCircleStyle, IBasicVectorPointStyle, DEFAULT_POINT_CIRCLE_STYLE, DEFAULT_POINT_ICON_STYLE, IBasicVectorLineStyle, IBasicVectorPolygonStyle, IVectorFeatureStyle, DEFAULT_LINE_STYLE, DEFAULT_POLY_STYLE, IVectorLayerStyle, IVectorLabelSettings, IBasicStroke, IBasicFill } from '../api/ol-style-contracts'; import { DEFAULT_STYLE_KEY } from '../api/ol-style-helpers'; import { Parser } from "expr-eval"; import { ColorExprEditor, NumberExprEditor, SliderExprEditor, StringExprEditor } from "./layer-manager/common"; import { STR_EMPTY } from "../utils/string"; import { getLegendImage } from "./layer-manager/legend"; import { vectorStyleToStyleMap } from "../api/ol-style-map-set"; interface IExprEditorProps<T> { converter: (value: string) => ExprOr<T>; expr: ExprOr<T>; onExprChanged: (value: ExprOr<T>) => void; } function assertValue<T>(val: ExprOr<T>): asserts val is T { if (isEvaluatable(val)) throw new Error("Value is expression instead of a raw value"); } function ExprEditor<T>(props: IExprEditorProps<T>) { assertValue(props.expr); return <>Expr: <input type="text" value={`${props.expr}`} onChange={e => props.onExprChanged(props.converter(e.target.value))} /></>; } const DynamicSwitch = (props: Omit<Omit<SwitchProps, "checked">, "onChange"> & Omit<IExprEditorProps<boolean>, "converter">) => { if (isEvaluatable(props.expr)) { return <ExprEditor<boolean> {...props} converter={v => v?.toLowerCase() == "true"} /> } else { const { expr, onExprChanged, ...rest } = props; const innerProps = { ...rest, checked: props.expr, onChange: (e: any) => props.onExprChanged(e.target.checked) }; return <Switch {...innerProps} />; } } interface ILabelStyleEditor { isLine?: boolean; style: IVectorLabelSettings; locale: string; onChange: (style: IVectorLabelSettings) => void; } //TODO: Either surface the font as another editable property or offload to configuration const buildFont = (size: number, bold: boolean, italic: boolean, font = "sans-serif") => `${bold ? "bold" : STR_EMPTY} ${italic ? "italic" : STR_EMPTY} ${size}px ${font}`; function coalesceExpr<T>(expr: ExprOr<T> | undefined, defaultVal: T): T { if (isEvaluatable(expr)) { return defaultVal; } return expr ?? defaultVal; } const DEFAULT_FONT_SIZE = 14; const LabelStyleEditor: React.FC<ILabelStyleEditor> = props => { const { style, locale, onChange, isLine } = props; const [bold, setBold] = React.useState(false); const [italic, setItalic] = React.useState(false); const [localBgColor, setLocalBgColor] = React.useState<ExprOr<string>>(style.label?.fill?.color ?? "#000000"); const [localBgColorAlpha, setLocalColorAlpha] = React.useState<ExprOr<number>>(style.label?.fill?.alpha ?? 255); const [localStrokeColor, setLocalStrokeColor] = React.useState<ExprOr<string>>(style.label?.stroke?.color ?? "#ffffff"); const [localStrokeWidth, setLocalStrokeWidth] = React.useState<ExprOr<number>>(style.label?.stroke?.width ?? 1); const [localFontSize, setLocalFontSize] = React.useState(DEFAULT_FONT_SIZE); const [localLabel, setLocalLabel] = React.useState({ font: buildFont(localFontSize, bold, italic), ...style.label }); const [hasLabel, setHasLabel] = React.useState(style.label != null); const onToggleLinePlacement = React.useCallback(() => { if (localLabel.placement == "line") { const { placement, ...rest } = localLabel; setLocalLabel(rest); } else { setLocalLabel({ ...localLabel, placement: "line" }); } }, [localLabel]); React.useEffect(() => { if (hasLabel) { onChange({ ...style, label: localLabel }); } else { const { label, ...rest } = style; onChange(rest); } }, [localLabel, hasLabel]); React.useEffect(() => { setLocalLabel({ ...localLabel, font: buildFont(localFontSize, bold, italic) }); }, [localFontSize, bold, italic]); React.useEffect(() => { setLocalLabel({ ...localLabel, fill: { ...localLabel.fill, color: localBgColor, alpha: localBgColorAlpha } as IBasicFill, stroke: { ...localLabel.stroke, color: localStrokeColor, width: localStrokeWidth } as IBasicStroke }) }, [localStrokeColor, localStrokeWidth, localBgColorAlpha, localBgColor]); return <> <Switch checked={hasLabel} onChange={(e: any) => setHasLabel(e.target.checked)} label={tr("ENABLE_LABELS", locale)} /> {hasLabel && <FormGroup label={tr("LABEL_TEXT", locale)}> <StringExprEditor locale={locale} value={localLabel.text} onChange={t => setLocalLabel({ ...localLabel, text: t })} /> </FormGroup>} {hasLabel && <FormGroup label={tr("LABEL_SIZE", locale)}> <NumberExprEditor locale={locale} value={localFontSize} onChange={t => setLocalFontSize(coalesceExpr(t, DEFAULT_FONT_SIZE))} /> </FormGroup>} {hasLabel && <ButtonGroup> <Button intent={Intent.PRIMARY} active={bold} onClick={(e: any) => setBold(!bold)}>{tr("LABEL_BOLD", locale)}</Button> <Button intent={Intent.PRIMARY} active={italic} onClick={(e: any) => setItalic(!italic)}>{tr("LABEL_ITALIC", locale)}</Button> {isLine && <Button intent={Intent.PRIMARY} active={localLabel.placement == "line"} onClick={(e: any) => onToggleLinePlacement()}>{tr("LABEL_LINE_PLACEMENT", locale)}</Button>} </ButtonGroup>} {hasLabel && <FormGroup label={tr("LABEL_COLOR", locale)}> <ColorExprEditor locale={locale} value={localBgColor} onChange={(c: any) => setLocalBgColor(c)} /> </FormGroup>} {hasLabel && <FormGroup label={tr("LABEL_OUTLINE_COLOR", locale)}> <ColorExprEditor locale={locale} value={localStrokeColor} onChange={(c: any) => setLocalStrokeColor(c)} /> </FormGroup>} {hasLabel && <FormGroup label={tr("LABEL_OUTLINE_THICKNESS", locale)}> <NumberExprEditor locale={locale} value={localStrokeWidth} onChange={t => setLocalStrokeWidth(t!)} /> </FormGroup>} </>; } interface ISubStyleEditorProps<TStyle> { style: TStyle; locale: string; onChange: (style: TStyle) => void; } const PointIconStyleEditor = ({ style, onChange, locale }: ISubStyleEditorProps<IPointIconStyle>) => { const [localSrc, setLocalSrc] = React.useState(style.src); React.useEffect(() => { setLocalSrc(style.src); }, [style.src]); const onSrcChange = (e: any) => { onChange({ ...style, src: localSrc }); }; return <div> <FormGroup label={tr("VSED_PT_ICON_SRC", locale)}> <StringExprEditor value={localSrc} onChange={e => setLocalSrc(e!)} locale={locale} /> {!isEvaluatable(style.src) && <img src={style.src} />} </FormGroup> <FormGroup label={tr("VSED_PT_ICON_ANCHOR", locale)}> {tr("VSED_PT_ICON_ANCHOR_H", locale)} <NumericInput value={style.anchor[0]} min={0} onValueChange={e => onChange({ ...style, anchor: [e, style.anchor[1]] })} /> {tr("VSED_PT_ICON_ANCHOR_V", locale)} <NumericInput value={style.anchor[1]} min={0} onValueChange={e => onChange({ ...style, anchor: [style.anchor[0], e] })} /> </FormGroup> <DynamicSwitch label={tr("VSED_PT_ICON_ROTATE_WITH_VIEW", locale)} expr={style.rotateWithView} onExprChanged={(e: any) => onChange({ ...style, rotateWithView: e })} /> <FormGroup label={tr("VSED_PT_ICON_ROTATION", locale)}> <SliderExprEditor locale={locale} min={0} max={360} labelStepSize={360} value={style.rotation} onChange={(n: any) => onChange({ ...style, rotation: n })} /> </FormGroup> {/*<FormGroup label={tr("VSED_PT_ICON_OPACITY", locale)}> <DynamicSlider min={0} max={255} labelStepSize={255} expr={style.opacity} onExprChanged={(n: any) => onChange({ ...style, opacity: n })} /> </FormGroup>*/} <FormGroup label={tr("VSED_PT_ICON_SCALE", locale)}> <NumberExprEditor value={style.scale} onChange={n => onChange({ ...style, scale: n! })} locale={locale} /> </FormGroup> </div>; }; const PointCircleStyleEditor = ({ style, onChange, locale }: ISubStyleEditorProps<IBasicPointCircleStyle>) => { return <div> <FormGroup label={tr("VSED_PT_FILL_COLOR", locale)}> <ColorExprEditor locale={locale} value={style.fill.color} onChange={(c: any) => onChange({ ...style, fill: { color: c, alpha: style.fill.alpha } })} /> </FormGroup> <FormGroup label={tr("VSED_PT_FILL_COLOR_ALPHA", locale)}> <SliderExprEditor locale={locale} min={0} max={255} labelStepSize={255} value={style.fill.alpha} onChange={(n: any) => onChange({ ...style, fill: { color: style.fill.color, alpha: n } })} /> </FormGroup> <FormGroup label={tr("VSED_PT_RADIUS", locale)}> <NumberExprEditor locale={locale} value={style.radius} min={1} onChange={(n: any) => onChange({ ...style, radius: n })} /> </FormGroup> <FormGroup label={tr("VSED_PT_OUTLINE_COLOR", locale)}> <ColorExprEditor locale={locale} value={style.stroke.color} onChange={(c: any) => onChange({ ...style, stroke: { color: c, width: style.stroke.width, alpha: style.stroke.alpha } })} /> </FormGroup> <FormGroup label={tr("VSED_PT_OUTLINE_COLOR_ALPHA", locale)}> <SliderExprEditor locale={locale} min={0} max={255} labelStepSize={255} value={style.stroke.alpha} onChange={(n: any) => onChange({ ...style, stroke: { color: style.stroke.color, width: style.stroke.width, alpha: n } })} /> </FormGroup> <FormGroup label={tr("VSED_PT_OUTLINE_WIDTH", locale)}> <NumberExprEditor locale={locale} value={style.stroke.width} min={1} onChange={(n: any) => onChange({ ...style, stroke: { color: style.stroke.color, width: n, alpha: style.stroke.alpha } })} /> </FormGroup> </div>; }; const PointStyleEditor = ({ style, onChange, locale }: ISubStyleEditorProps<IBasicVectorPointStyle>) => { const [iconStyle, setIconStyle] = React.useState<IPointIconStyle | undefined>(undefined); const [circleStyle, setCircleStyle] = React.useState<IBasicPointCircleStyle | undefined>(undefined); const [currentStyle, setCurrentStyle] = React.useState(style); const applyCurrentStyle = (s: IBasicVectorPointStyle) => { setCurrentStyle(s); switch (s.type) { case "Circle": setCircleStyle(s); break; case "Icon": setIconStyle(s); break; } } const onStyleTypeChange = (type: "Icon" | "Circle") => { switch (type) { case "Circle": if (circleStyle) { setCurrentStyle(circleStyle); onChange(circleStyle); } else { const s = { ...DEFAULT_POINT_CIRCLE_STYLE }; setCircleStyle(s); setCurrentStyle(s); onChange(s); } break; case "Icon": if (iconStyle) { setCurrentStyle(iconStyle); onChange(iconStyle); } else { const s = { ...DEFAULT_POINT_ICON_STYLE }; setIconStyle(s); setCurrentStyle(s); onChange(s); } break; } } React.useEffect(() => { applyCurrentStyle(style); }, [style]); return <div> <RadioGroup inline label={tr("VSED_PT_TYPE", locale)} onChange={(e: any) => onStyleTypeChange(e.target.value)} selectedValue={currentStyle.type}> <Radio label={tr("VSED_PT_TYPE_CIRCLE", locale)} value="Circle" /> <Radio label={tr("VSED_PT_TYPE_ICON", locale)} value="Icon" /> </RadioGroup> {currentStyle.type == "Icon" && <PointIconStyleEditor style={currentStyle} onChange={onChange} locale={locale} />} {currentStyle.type == "Circle" && <PointCircleStyleEditor style={currentStyle} onChange={onChange} locale={locale} />} <LabelStyleEditor style={currentStyle} locale={locale} onChange={onChange} /> </div> } const LineStyleEditor = ({ style, onChange, locale }: ISubStyleEditorProps<IBasicVectorLineStyle>) => { return <div> <FormGroup label={tr("VSED_LN_OUTLINE_COLOR", locale)}> <ColorExprEditor locale={locale} value={style.color} onChange={(c: any) => onChange({ ...style, color: c, width: style.width, alpha: style.alpha })} /> </FormGroup> <FormGroup label={tr("VSED_LN_OUTLINE_COLOR_ALPHA", locale)}> <SliderExprEditor locale={locale} min={0} max={255} labelStepSize={255} value={style.alpha} onChange={(n: any) => onChange({ ...style, color: style.color, width: style.width, alpha: n })} /> </FormGroup> <FormGroup label={tr("VSED_LN_OUTLINE_THICKNESS", locale)}> <NumberExprEditor locale={locale} min={1} value={style.width} onChange={(n: any) => onChange({ ...style, color: style.color, width: n, alpha: style.alpha })} /> </FormGroup> <LabelStyleEditor style={style} locale={locale} onChange={onChange} isLine /> </div>; } const PolygonStyleEditor = ({ style, onChange, locale }: ISubStyleEditorProps<IBasicVectorPolygonStyle>) => { return <div> <FormGroup label={tr("VSED_PL_FILL_COLOR", locale)}> <ColorExprEditor locale={locale} value={style.fill.color} onChange={(c: any) => onChange({ ...style, fill: { color: c, alpha: style.fill.alpha } })} /> </FormGroup> <FormGroup label={tr("VSED_PL_FILL_COLOR_ALPHA", locale)}> <SliderExprEditor locale={locale} min={0} max={255} labelStepSize={255} value={style.fill.alpha} onChange={(n: any) => onChange({ ...style, fill: { color: style.fill.color, alpha: n } })} /> </FormGroup> <FormGroup label={tr("VSED_PL_OUTLINE_COLOR", locale)}> <ColorExprEditor locale={locale} value={style.stroke.color} onChange={(c: any) => onChange({ ...style, stroke: { color: c, width: style.stroke.width, alpha: style.stroke.alpha } })} /> </FormGroup> <FormGroup label={tr("VSED_PL_OUTLINE_COLOR_ALPHA", locale)}> <SliderExprEditor locale={locale} min={0} max={255} labelStepSize={255} value={style.stroke.alpha} onChange={(n: any) => onChange({ ...style, stroke: { color: style.stroke.color, width: style.stroke.width, alpha: n } })} /> </FormGroup> <FormGroup label={tr("VSED_PL_OUTLINE_THICKNESS", locale)}> <NumberExprEditor locale={locale} value={style.stroke.width} min={1} onChange={(n: any) => onChange({ ...style, stroke: { color: style.stroke.color, width: n, alpha: style.stroke.alpha } })} /> </FormGroup> <LabelStyleEditor style={style} locale={locale} onChange={onChange} /> </div>; } /** * Vector style editor props * @since 0.13 */ export interface IVectorStyleEditorProps { style?: IVectorFeatureStyle; onChange?: (style: IVectorFeatureStyle) => void; enablePoint: boolean; enableLine: boolean; enablePolygon: boolean; locale: string; } type TabId = "pointStyle" | "lineStyle" | "polyStyle"; /** * A vector style editor component * * @since 0.13 */ export const VectorStyleEditor = (props: IVectorStyleEditorProps) => { const { locale, style, onChange, enableLine, enablePoint, enablePolygon } = props; const [selectedTab, setSelectedTab] = React.useState<TabId | undefined>(undefined); const [pointStyle, setPointStyle] = React.useState(style?.point ?? DEFAULT_POINT_CIRCLE_STYLE); const [lineStyle, setLineStyle] = React.useState(style?.line ?? DEFAULT_LINE_STYLE); const [polyStyle, setPolyStyle] = React.useState(style?.polygon ?? DEFAULT_POLY_STYLE); React.useEffect(() => { setPointStyle(style?.point ?? DEFAULT_POINT_CIRCLE_STYLE); setLineStyle(style?.line ?? DEFAULT_LINE_STYLE); setPolyStyle(style?.polygon ?? DEFAULT_POLY_STYLE); }, [style]); const onStyleChanged = (point: IBasicVectorPointStyle, line: IBasicVectorLineStyle, poly: IBasicVectorPolygonStyle) => { const newStyle: IVectorFeatureStyle = { label: style?.label }; if (enablePoint) { newStyle.point = point; } if (enableLine) { newStyle.line = line; } if (enablePolygon) { newStyle.polygon = poly; } onChange?.(newStyle); if (newStyle.point) { setPointStyle(newStyle.point); } if (newStyle.line) { setLineStyle(newStyle.line); } if (newStyle.polygon) { setPolyStyle(newStyle.polygon); } }; if (!enableLine && !enablePoint && !enablePolygon) { return <NonIdealState icon="warning-sign" title={tr("VSED_NO_STYLES_TITLE", locale)} description={tr("VSED_NO_STYLES_DESC", locale)} /> } else { const onPointStyleChanged = (st: IBasicPointCircleStyle) => { onStyleChanged(st, lineStyle, polyStyle); }; const onLineStyleChanged = (st: IBasicVectorLineStyle) => { onStyleChanged(pointStyle, st, polyStyle); }; const onPolygonStyleChanged = (st: IBasicVectorPolygonStyle) => { onStyleChanged(pointStyle, lineStyle, st); }; return <Tabs onChange={(t: any) => setSelectedTab(t)} selectedTabId={selectedTab}> {enablePoint && <Tab id="pointStyle" title={tr("VSED_TAB_POINT", locale)} panel={<PointStyleEditor style={pointStyle} locale={locale} onChange={onPointStyleChanged} />} />} {enableLine && <Tab id="lineStyle" title={tr("VSED_TAB_LINE", locale)} panel={<LineStyleEditor style={lineStyle} locale={locale} onChange={onLineStyleChanged} />} />} {enablePolygon && <Tab id="polyStyle" title={tr("VSED_TAB_POLY", locale)} panel={<PolygonStyleEditor style={polyStyle} locale={locale} onChange={onPolygonStyleChanged} />} />} </Tabs> } } /** * Vector layer style editor props * @since 0.14 */ export interface IVectorLayerStyleEditorProps { style: IVectorLayerStyle; onChange?: (style: IVectorLayerStyle) => void; enablePoint: boolean; enableLine: boolean; enablePolygon: boolean; locale: string; } interface IFilterItemProps extends Omit<IVectorLayerStyleEditorProps, "onChange" | "style"> { onChange: (filter: string, style: IVectorFeatureStyle) => void; featureStyle: IVectorFeatureStyle; filter?: string; isDefault: boolean; isStyleEditorOpen: boolean; onToggleStyleEditor: (visible: boolean) => void; } const parser = new Parser(); const FilterItem = (props: IFilterItemProps) => { const { filter, isDefault, isStyleEditorOpen, featureStyle, onChange } = props; const [localFilter, setLocalFilter] = React.useState(filter ?? ""); const [isLocalFilterValid, setIsLocalFilterValid] = React.useState(true); const [pointStyleUrl, setPointStyleUrl] = React.useState<string | undefined>(undefined); const [lineStyleUrl, setLineStyleUrl] = React.useState<string | undefined>(undefined); const [polyStyleUrl, setPolyStyleUrl] = React.useState<string | undefined>(undefined); React.useEffect(() => { setLocalFilter(localFilter); }, [filter]); React.useEffect(() => { try { const expr: any = parser.parse(localFilter); let bHaveVar = false; let bHaveOperator = false; for (const t of expr.tokens) { switch (t.type) { case "IVAR": bHaveVar = true; break; case "IOP2": bHaveOperator = true; break; } } setIsLocalFilterValid(bHaveVar && bHaveOperator && expr.tokens.length == 3); } catch (e) { setIsLocalFilterValid(false); } }, [localFilter]); React.useEffect(() => { let fs = featureStyle; // A default clustered style will have a dynamic expression for the radius, the legend preview isn't // smart enough to know what this should be since we don't (and can't) pass an "example" feature to // know what this value should be. So in the event we find a clustered point style, we'll replace // the dynamic radius expression with a constant value if (featureStyle?.point?.type == "Circle" && isEvaluatable(featureStyle.point.radius)) { fs = JSON.parse(JSON.stringify(featureStyle)); if (fs.point?.type == "Circle") { fs.point.radius = 5; } } const olstyle = vectorStyleToStyleMap(fs); let pos: any; let ls: any; let pls: any; if (typeof(olstyle) == 'function') { pos = (feat: any) => olstyle(feat, undefined)["Point"]; ls = (feat: any) => olstyle(feat, undefined)["LineString"]; pls = (feat: any) => olstyle(feat, undefined)["Polygon"]; } else { pos = olstyle.Point; ls = olstyle.LineString; pls = olstyle.Polygon; } const cPoint = getLegendImage({ typeGeom: "Point", style: pos }); const cLineString = getLegendImage({ typeGeom: "LineString", style: ls }); const cPolygon = getLegendImage({ typeGeom: "Polygon", style: pls }); setPointStyleUrl(cPoint.toDataURL()); setLineStyleUrl(cLineString.toDataURL()); setPolyStyleUrl(cPolygon.toDataURL()); }, [featureStyle]); const onToggle = () => { props.onToggleStyleEditor(!isStyleEditorOpen); }; const onInnerStyleChanged = (style: IVectorFeatureStyle) => { onChange?.(isDefault ? DEFAULT_STYLE_KEY : localFilter, style); } let outerModifier; if (!isLocalFilterValid) { outerModifier = Intent.DANGER; } let colSpan = 5; if (!props.enableLine) colSpan--; if (!props.enablePoint) colSpan--; if (!props.enablePolygon) colSpan--; const filterExprEd = <span>{featureStyle.label}</span> //<InputGroup intent={outerModifier} fill leftIcon={(isLocalFilterValid ? "tick" : "warning-sign")} title={localFilter} value={localFilter} onChange={e => setLocalFilter(e.target.value)} />; return <> <tr> {props.enablePoint && <td>{pointStyleUrl && <img src={pointStyleUrl} />}</td>} {props.enableLine && <td>{lineStyleUrl && <img src={lineStyleUrl} />}</td>} {props.enablePolygon && <td>{polyStyleUrl && <img src={polyStyleUrl} />}</td>} <td>{isDefault ? <strong>Default Style</strong> : filterExprEd}</td> <td><Button intent={isStyleEditorOpen ? Intent.DANGER : Intent.PRIMARY} onClick={onToggle} icon={isStyleEditorOpen ? "cross" : "edit"} /></td> </tr> {isStyleEditorOpen && <tr> <td colSpan={colSpan}> <VectorStyleEditor style={featureStyle} onChange={onInnerStyleChanged} enableLine={props.enableLine} enablePoint={props.enablePoint} enablePolygon={props.enablePolygon} locale={props.locale} /> </td> </tr>} </> } export const VectorLayerStyleEditor = (props: IVectorLayerStyleEditorProps) => { const filters = Object.keys(props.style).filter(k => k != DEFAULT_STYLE_KEY); const [openStyleEditors, setOpenStyleEditors] = React.useState<{ [filter: string]: boolean }>({}); const onFeatureStyleChanged = (filter: string, style: IVectorFeatureStyle) => { const updatedStyle = { ...props.style }; updatedStyle[filter] = style; props.onChange?.(updatedStyle); }; const onToggleStyleEditor = (index: number | string, visible: boolean) => { const opEds = { ...openStyleEditors }; if (!visible) { delete opEds[index]; } else { opEds[index] = true; } setOpenStyleEditors(opEds); }; return <table style={{ width: "100%" }}> <colgroup> {props.enablePoint && <col span={1} style={{ width: 24 }} />} {props.enableLine && <col span={1} style={{ width: 24 }} />} {props.enablePolygon && <col span={1} style={{ width: 24 }} />} <col span={1} /> <col span={1} style={{ width: 32 }} /> </colgroup> <tbody> {filters.map((f, i) => <FilterItem key={`filter-${i}`} filter={f} isDefault={false} onChange={(f, s) => onFeatureStyleChanged( f, s)} featureStyle={props.style[filters[i]]} isStyleEditorOpen={openStyleEditors[f] === true} onToggleStyleEditor={(isVisible) => onToggleStyleEditor(f, isVisible)} locale={props.locale} enableLine={props.enableLine} enablePoint={props.enablePoint} enablePolygon={props.enablePolygon} />)} <FilterItem isDefault onChange={(f, s) => onFeatureStyleChanged(DEFAULT_STYLE_KEY, s)} featureStyle={props.style.default} isStyleEditorOpen={openStyleEditors[DEFAULT_STYLE_KEY] === true} onToggleStyleEditor={(isVisible) => onToggleStyleEditor(DEFAULT_STYLE_KEY, isVisible)} locale={props.locale} enableLine={props.enableLine} enablePoint={props.enablePoint} enablePolygon={props.enablePolygon} /> </tbody> </table>; }
the_stack
import fs from "fs-extra"; import chalk from "chalk"; import memoize from "mem"; import { dirname, relative, basename } from "path"; import { cosmiconfigSync } from "cosmiconfig"; import { EmittedAsset, InputOption, InputOptions, OutputBundle, PluginContext, TransformPluginContext } from "rollup"; import { ChromeExtensionManifest, Background } from "../manifest"; import { deriveFiles } from "../manifest-input/manifest-parser"; import { reduceToRecord } from "../manifest-input/reduceToRecord"; import { ManifestInputPluginCache, NormalizedChromeExtensionOptions } from "../plugin-options"; import { cloneObject } from "../utils/cloneObject"; import { manifestName } from "../manifest-input/common/constants"; import { getAssets, getChunk } from "../utils/bundle"; import { validateManifest, ValidationErrorsArray, } from "../manifest-input/manifest-parser/validate"; import { ContentScriptProcessor } from "./content-script/content-script"; import { PermissionProcessor, PermissionProcessorOptions } from "./permission"; import { BackgroundProcesser } from "./background/background"; export const explorer = cosmiconfigSync("manifest", { cache: false, }); export type ExtendManifest = | Partial<ChromeExtensionManifest> | ((manifest: ChromeExtensionManifest) => ChromeExtensionManifest); export type ChromeExtensionConfigurationInfo = { filepath: string, config: ChromeExtensionManifest, isEmpty?: true, }; export class ManifestProcessor { public cache = { assetChanged: false, assets: [], iife: [], input: [], inputAry: [], inputObj: {}, dynamicImportContentScripts: [], permsHash: "", readFile: new Map<string, any>(), srcDir: null, } as ManifestInputPluginCache; public manifest?: ChromeExtensionManifest; public contentScriptProcessor: ContentScriptProcessor; public permissionProcessor: PermissionProcessor; public backgroundProcessor: BackgroundProcesser; public constructor(private options = {} as NormalizedChromeExtensionOptions) { this.contentScriptProcessor = new ContentScriptProcessor(options); this.permissionProcessor = new PermissionProcessor(new PermissionProcessorOptions()); this.backgroundProcessor = new BackgroundProcesser(options); } /** * Load content from manifest.json * @param options: rollup input options */ public load(options: InputOptions) { /* --------------- GET MANIFEST.JSON PATH --------------- */ const inputManifestPath = this.resolveManifestPath(options); /* --------------- LOAD CONTENT FROM MANIFEST.JSON --------------- */ const configResult = explorer.load(inputManifestPath) as ChromeExtensionConfigurationInfo; /* --------------- VALIDATE MANIFEST.JSON CONTENT --------------- */ this.validateManifestContent(configResult); /* --------------- APPLY USER CUSTOM CONFIG --------------- */ this.manifest = this.applyExternalManifestConfiguration(configResult); /* --------------- RECORD OPTIONS --------------- */ this.options.manifestPath = configResult.filepath; this.options.srcDir = dirname(this.options.manifestPath); return this.manifest; } /** * Resolve input files for rollup * @param input: Input not in manifest.json but specify by user * @returns */ public resolveInput(input?: InputOption): { [entryAlias: string]: string; } { if (!this.manifest || !this.options.srcDir) { throw new TypeError("manifest and options.srcDir not initialized"); } // Derive all static resources from manifest // Dynamic entries will emit in transform hook const { js, html, css, img, others } = deriveFiles( this.manifest, this.options.srcDir, ); // Cache derived inputs this.cache.input = [...this.cache.inputAry, ...js, ...html]; this.cache.assets = [...new Set([...css, ...img, ...others])]; const inputs = this.cache.input.reduce( reduceToRecord(this.options.srcDir), this.cache.inputObj); return inputs; } public transform(context: TransformPluginContext, code: string, id: string, ssr?: boolean) { const { code:updatedCode, imports } = this.backgroundProcessor.resolveDynamicImports(context, code); this.cache.dynamicImportContentScripts.push(...imports); return updatedCode; } public isDynamicImportedContentScript(referenceId: string) { return this.cache.dynamicImportContentScripts.includes(referenceId); } /** * Add watch files * @param context Rollup Plugin Context */ public addWatchFiles(context: PluginContext) { // watch manifest.json file context.addWatchFile(this.options.manifestPath!); // watch asset files this.cache.assets.forEach(srcPath => context.addWatchFile(srcPath)); } public async emitFiles(context: PluginContext) { // Copy asset files const assets: EmittedAsset[] = await Promise.all( this.cache.assets.map(async (srcPath) => { const source = await this.readAssetAsBuffer(srcPath); return { type: "asset" as const, source, fileName: relative(this.options.srcDir!, srcPath), }; }), ); assets.forEach((asset) => { context.emitFile(asset); }); } public clearCacheById(id: string) { if (id.endsWith(manifestName)) { // Dump cache.manifest if manifest changes delete this.manifest; this.cache.assetChanged = false; } else { // Force new read of changed asset this.cache.assetChanged = this.cache.readFile.delete(id); } } public async generateBundle(context: PluginContext, bundle: OutputBundle) { if (!this.manifest) { throw new Error("[generate bundle] Manifest cannot be empty"); } /* ----------------- GET CHUNKS -----------------*/ const chunks = getChunk(bundle); const assets = getAssets(bundle); /* ----------------- UPDATE PERMISSIONS ----------------- */ this.permissionProcessor.derivePermissions(context, chunks, this.manifest); /* ----------------- UPDATE CONTENT SCRIPTS ----------------- */ await this.contentScriptProcessor.generateBundle(context, bundle, this.manifest); await this.contentScriptProcessor.generateBundleFromDynamicImports(context, bundle, this.cache.dynamicImportContentScripts); /* ----------------- SETUP BACKGROUND SCRIPTS ----------------- */ await this.backgroundProcessor.generateBundle(context, bundle, this.manifest); /* ----------------- SETUP ASSETS IN WEB ACCESSIBLE RESOURCES ----------------- */ /* ----------------- STABLE EXTENSION ID ----------------- */ /* ----------------- OUTPUT MANIFEST.JSON ----------------- */ /* ----------- OUTPUT MANIFEST.JSON ---------- */ this.generateManifest(context, this.manifest); // validate manifest this.validateManifest(); } private resolveManifestPath(options: InputOptions): string { if (!options.input) { console.log(chalk.red("No input is provided.")) throw new Error("No input is provided.") } let inputManifestPath: string | undefined; if (Array.isArray(options.input)) { const manifestIndex = options.input.findIndex(i => basename(i) === "manifest.json"); if (manifestIndex > -1) { inputManifestPath = options.input[manifestIndex]; this.cache.inputAry = options.input.splice(manifestIndex, 1); } else { console.log(chalk.red("RollupOptions.input array must contain a Chrome extension manifest with filename 'manifest.json'.")); throw new Error("RollupOptions.input array must contain a Chrome extension manifest with filename 'manifest.json'."); } } else if (typeof options.input === "object") { if (options.input.manifest) { inputManifestPath = options.input.manifest; delete options.input["manifest"]; this.cache.inputObj = cloneObject(options.input); } else { console.log(chalk.red("RollupOptions.input object must contain a Chrome extension manifest with Key manifest.")); throw new Error("RollupOptions.input object must contain a Chrome extension manifest with Key manifest."); } } else { inputManifestPath = options.input; delete options.input; } /* --------------- VALIDATE MANIFEST.JSON PATH --------------- */ if (basename(inputManifestPath) !== "manifest.json") { throw new TypeError("Input for a Chrome extension manifest must have filename 'manifest.json'."); } return inputManifestPath; } private validateManifestContent(config: ChromeExtensionConfigurationInfo) { if (config.isEmpty) { throw new Error(`${config.filepath} is an empty file.`); } const { options_page, options_ui } = config.config; if ( options_page !== undefined && options_ui !== undefined ) { throw new Error( "options_ui and options_page cannot both be defined in manifest.json.", ); } } private validateManifest() { if (this.manifest) { validateManifest(this.manifest) } else { throw new Error("Manifest cannot be empty"); } } private applyExternalManifestConfiguration( config: ChromeExtensionConfigurationInfo ): ChromeExtensionManifest { if (typeof this.options.extendManifest === "function") { return this.options.extendManifest(config.config); } else if (typeof this.options.extendManifest === "object") { return { ...config.config, ...this.options.extendManifest, }; } else { return config.config; } } private readAssetAsBuffer = memoize( (filepath: string) => { return fs.readFile(filepath); }, { cache: this.cache.readFile, }, ); private generateManifest( context: PluginContext, manifest: ChromeExtensionManifest, ) { const manifestJson = JSON.stringify(manifest, null, 4) // SMELL: is this necessary? .replace(/\.[jt]sx?"/g, '.js"'); // Emit manifest.json context.emitFile({ type: "asset", fileName: manifestName, source: manifestJson, }); } }
the_stack
import * as React from "react"; import { CSSProperties, useState } from "react"; import { getDocumentService, getModalDialogService, getOutputPaneService, getSideBarService, getState, getStore, getThemeService, getToolAreaService, } from "@core/service-registry"; import { useDispatch, useStore } from "react-redux"; import { ideLoadUiAction } from "@state/ide-loaded-reducer"; import { toStyleString } from "../ide/utils/css-utils"; import { EmuViewOptions, ToolFrameState } from "@state/AppState"; import { useLayoutEffect } from "react"; import Splitter from "../../emu-ide/components/Splitter"; import { useEffect } from "react"; import { changeActivityAction, setActivitiesAction, } from "@state/activity-bar-reducer"; import { OpenEditorsPanelDescriptor } from "./explorer-tools/OpenEditorsPanel"; import { ProjectFilesPanelDescriptor } from "./explorer-tools/ProjectFilesPanel"; import { Z80RegistersPanelDescriptor } from "../machines/sidebar-panels/Z80RegistersPanel"; import { UlaInformationPanelDescriptor } from "../machines/zx-spectrum/UlaInformationPanel"; import { BlinkInformationPanelDescriptor } from "../machines/cambridge-z88/BlinkInformationPanel"; import { CallStackPanelDescriptor } from "../machines/sidebar-panels/CallStackPanel"; import { IoLogsPanelDescription } from "../machines/sidebar-panels/IoLogsPanel"; import { TestRunnerPanelDescription } from "./test-tools/TestRunnerPanel"; import { InteractiveToolPanelDescriptor } from "./tool-area/InteractiveToolPanel"; import { OutputToolPanelDescriptor } from "./tool-area/OutputToolPanel"; import { VmOutputPanelDescriptor } from "../machines/sidebar-panels/VmOutputPane"; import { CompilerOutputPanelDescriptor } from "./tool-area/CompilerOutputPane"; import IdeContextMenu from "./context-menu/ContextMenu"; import ModalDialog from "../../emu-ide/components/ModalDialog"; import ActivityBar from "./activity-bar/ActivityBar"; import IdeStatusbar from "./IdeStatusbar"; import SideBar from "./side-bar/SideBar"; import IdeDocumentFrame from "./document-area/IdeDocumentsFrame"; import ToolFrame from "./tool-area/ToolFrame"; import "./ide-message-processor"; import { registerKliveCommands } from "./commands/register-commands"; import { Z80DisassemblyPanelDescriptor } from "../machines/sidebar-panels/DisassemblyPanel"; import { MemoryPanelDescriptor } from "../machines/sidebar-panels/MemoryPanel"; import { virtualMachineToolsService } from "../machines/core/VitualMachineToolBase"; import { ZxSpectrum48Tools } from "../machines/zx-spectrum/ZxSpectrum48Core"; import { CambridgeZ88Tools } from "../machines/cambridge-z88/CambridgeZ88Core"; import { newProjectDialog, NEW_PROJECT_DIALOG_ID, } from "./explorer-tools/NewProjectDialog"; import { newFolderDialog, NEW_FOLDER_DIALOG_ID, } from "./explorer-tools/NewFolderDialog"; import { newFileDialog, NEW_FILE_DIALOG_ID, } from "./explorer-tools/NewFileDialog"; import { renameFileDialog, RENAME_FILE_DIALOG_ID, } from "./explorer-tools/RenameFileDialog"; import { renameFolderDialog, RENAME_FOLDER_DIALOG_ID, } from "./explorer-tools/RenameFolderDialog"; import { asmkZ80LanguageProvider as asmkZ80LanguageProvider } from "./languages/asm-z80-provider"; import { mpmZ80LanguageProvider } from "./languages/mpm-z80-provider"; import { Activity } from "@core/abstractions/activity"; import { BreakpointsPanelDescriptor } from "../machines/sidebar-panels/BreakpointsPanel"; // --- App component literal constants const WORKBENCH_ID = "ideWorkbench"; const STATUS_BAR_ID = "ideStatusBar"; const ACTIVITY_BAR_ID = "ideActivityBar"; const SIDEBAR_ID = "ideSidebar"; const MAIN_DESK_ID = "ideMainDesk"; const DOCUMENT_FRAME_ID = "ideDocumentFrame"; const TOOL_FRAME_ID = "ideToolFrame"; const VERTICAL_SPLITTER_ID = "ideVerticalSplitter"; const HORIZONTAL_SPLITTER_ID = "ideHorizontalSplitter"; const SPLITTER_SIZE = 4; // --- Panel sizes const MIN_SIDEBAR_WIDTH = 200; const MIN_DESK_WIDTH = 440; const MIN_DESK_HEIGHT = 100; // --- These variables keep the state of the IdeApp component outside // --- of it (for performance reasins). It can be done, as IdeApp is a // --- singleton component. let mounted = false; let firstRender = true; let lastDocumentFrameHeight = 0; let lastToolFrameHeight = 0; let restoreLayout = false; let workbenchWidth = 0; let workbenchHeight = 0; let splitterStartPosition = 0; let activityBarWidth = 0; let deskWidth = 0; let sidebarWidth = 0; let mainDeskLeft = 0; let mainDeskWidth = 0; let documentFrameHeight = 200; let toolFrameHeight = 100; let verticalSplitterPos = 0; let horizontalSplitterPos = 0; let showDocumentFrame = true; let showToolFrame = true; /** * Represents the emulator app's root component. * * Thic component has a single instance as is re-rendered infrequenctly. * Because of its singleton nature, a part of its state is kept in module-local * variables and not in React state. The component logic takes care of * updating the component state according to the module-local variables. * * Screen layout: * * |--- Vertical splitter * ------------v--------------------------- * | A | S || Document Frame | * | c | i || | * | t | d || | * | i | e || | * | v | b || | * | i | a || | * | t | r || | * | i | ||=========================|<--- Horizontal splitter * | | || Tool Frame | * | B | || | * | a | || | * | r | || | * ---------------------------------------- * | Status Bar | * ---------------------------------------- * * Main desk: The panel with the Document Frame, Tool Frame, and the splitter * between them. * Workbench: The upper part of the screen without the Status Bar. * * For performance and UX reasons, this component implements its layout * management -- including resizing the panels -- with direct access to HTML * elements. */ export default function IdeApp() { // --- Let's use the store for dispatching actions const store = useStore(); const dispatch = useDispatch(); // --- Component state (changes of them triggers re-rendering) const [themeStyle, setThemeStyle] = useState<CSSProperties>({}); const [themeClass, setThemeClass] = useState(""); const [documentFrameVisible, setDocumentFrameVisible] = useState(true); const [toolFrameVisible, setToolFrameVisible] = useState(true); const [showStatusBar, setShowStatusBar] = useState( getState()?.emuViewOptions?.showStatusBar ?? false ); useEffect(() => { const themeService = getThemeService(); // --- State change event handlers const isWindowsChanged = (isWindows: boolean) => { themeService.isWindows = isWindows; updateThemeState(); }; const themeChanged = (theme: string) => { themeService.setTheme(theme); updateThemeState(); }; const viewOptionsChanged = (viewOptions: EmuViewOptions) => { setShowStatusBar(viewOptions.showStatusBar); onResize(); }; const toolFrameChanged = (toolFrame: ToolFrameState) => { showToolFrame = toolFrame.visible; setToolFrameVisible(showToolFrame); showDocumentFrame = !toolFrame.maximized; setDocumentFrameVisible(showDocumentFrame); }; if (!mounted) { // --- Mount logic, executed only once during the app's life cycle mounted = true; dispatch(ideLoadUiAction()); updateThemeState(); getStore().themeChanged.on(themeChanged); getStore().isWindowsChanged.on(isWindowsChanged); getStore().emuViewOptionsChanged.on(viewOptionsChanged); getStore().toolFrameChanged.on(toolFrameChanged); // --- Set up activities const activities: Activity[] = [ { id: "file-view", title: "Explorer", iconName: "files", }, { id: "debug-view", title: "Debug", iconName: "debug-alt", commands: [ { commandId: "klive.debugVm", }, { commandId: "klive.pauseVm", }, { commandId: "klive.stopVm", }, { commandId: "klive.stepIntoVm", }, { commandId: "klive.stepOverVm", }, { commandId: "klive.stepOutVm", }, ], }, { id: "log-view", title: "Machine logs", iconName: "output", }, { id: "test-view", title: "Testing", iconName: "beaker", }, { id: "settings", title: "Manage", iconName: "settings-gear", isSystemActivity: true, }, ]; store.dispatch(setActivitiesAction(activities)); // --- Register side bar panels const sideBarService = getSideBarService(); // (Explorer) sideBarService.registerSideBarPanel( "file-view", new OpenEditorsPanelDescriptor() ); sideBarService.registerSideBarPanel( "file-view", new ProjectFilesPanelDescriptor() ); // (Run and Debug) sideBarService.registerSideBarPanel( "debug-view", new Z80RegistersPanelDescriptor() ); sideBarService.registerSideBarPanel( "debug-view", new UlaInformationPanelDescriptor(), ["sp48", "sp128"] ); sideBarService.registerSideBarPanel( "debug-view", new BlinkInformationPanelDescriptor(), ["cz88"] ); sideBarService.registerSideBarPanel( "debug-view", new Z80DisassemblyPanelDescriptor() ); sideBarService.registerSideBarPanel( "debug-view", new MemoryPanelDescriptor() ); sideBarService.registerSideBarPanel( "debug-view", new CallStackPanelDescriptor() ); sideBarService.registerSideBarPanel( "debug-view", new BreakpointsPanelDescriptor() ); // (Machine logs) sideBarService.registerSideBarPanel( "log-view", new IoLogsPanelDescription() ); // (Testing) sideBarService.registerSideBarPanel( "test-view", new TestRunnerPanelDescription() ); // --- Register tool panels const toolAreaService = getToolAreaService(); toolAreaService.registerTool(new OutputToolPanelDescriptor(), false); const outputPaneService = getOutputPaneService(); outputPaneService.registerOutputPane(new VmOutputPanelDescriptor()); outputPaneService.registerOutputPane(new CompilerOutputPanelDescriptor()); toolAreaService.registerTool(new InteractiveToolPanelDescriptor(), true); // --- Register custom languages const documentService = getDocumentService(); documentService.registerCustomLanguage(asmkZ80LanguageProvider); documentService.registerCustomLanguage(mpmZ80LanguageProvider); // --- Register document panels and editors documentService.registerCodeEditor(".project", { language: "json", }); documentService.registerCodeEditor(".asm.kz80", { language: "asm-kz80", allowBuildRoot: true, }); documentService.registerCodeEditor(".mpm.z80", { language: "mpm-z80", }); // --- Register virtual machine tools virtualMachineToolsService.registerTools("sp48", new ZxSpectrum48Tools()); virtualMachineToolsService.registerTools("cz88", new CambridgeZ88Tools()); // --- Register modal dialogs const modalDialogService = getModalDialogService(); modalDialogService.registerModalDescriptor( NEW_PROJECT_DIALOG_ID, newProjectDialog ); modalDialogService.registerModalDescriptor( NEW_FOLDER_DIALOG_ID, newFolderDialog ); modalDialogService.registerModalDescriptor( NEW_FILE_DIALOG_ID, newFileDialog ); modalDialogService.registerModalDescriptor( RENAME_FILE_DIALOG_ID, renameFileDialog ); modalDialogService.registerModalDescriptor( RENAME_FOLDER_DIALOG_ID, renameFolderDialog ); // --- Register available commands registerKliveCommands(); // --- Select the file-view activity dispatch(changeActivityAction(0)); } return () => { // --- Unsubscribe getStore().toolFrameChanged.off(toolFrameChanged); getStore().emuViewOptionsChanged.off(viewOptionsChanged); getStore().isWindowsChanged.off(isWindowsChanged); getStore().themeChanged.off(themeChanged); }; }, [store]); // --- Apply styles to body so that dialogs, context menus can use it, too. document.body.setAttribute("style", toStyleString(themeStyle)); document.body.setAttribute("class", themeClass); // --- Take care of resizing IdeApp whenever the window size changes useLayoutEffect(() => { const _onResize = async () => onResize(); window.addEventListener("resize", _onResize); // --- Recognize when both Frames are visible so that their dimensions // --- can be restored if (!firstRender && showToolFrame && showDocumentFrame) { restoreLayout = true; } onResize(); return () => { window.removeEventListener("resize", _onResize); }; }, [documentFrameVisible, toolFrameVisible]); // --- Display the status bar when it's visible //const ideViewOptions = useSelector((s: AppState) => s.emuViewOptions); const statusBarStyle: CSSProperties = { height: showStatusBar ? 28 : 0, width: "100%", backgroundColor: "blue", }; return ( <div id="klive_ide_app" style={ideAppStyle}> <div id={WORKBENCH_ID} style={workbenchStyle}> <div id={ACTIVITY_BAR_ID} style={activityBarStyle}> <ActivityBar /> </div> <div id={SIDEBAR_ID} style={sidebarStyle}> <SideBar /> </div> <Splitter id={VERTICAL_SPLITTER_ID} direction="vertical" size={SPLITTER_SIZE} position={verticalSplitterPos} length={workbenchHeight} onStartMove={() => startVerticalSplitter()} onMove={(delta) => moveVerticalSplitter(delta)} /> <div id={MAIN_DESK_ID} style={mainDeskStyle}> {showDocumentFrame && ( <div id={DOCUMENT_FRAME_ID} style={documentFrameStyle}> <IdeDocumentFrame /> </div> )} {showDocumentFrame && showToolFrame && ( <Splitter id={HORIZONTAL_SPLITTER_ID} direction="horizontal" size={SPLITTER_SIZE} position={horizontalSplitterPos} length={mainDeskWidth} shift={mainDeskLeft} onStartMove={() => startHorizontalSplitter()} onMove={(delta) => moveHorizontalSplitter(delta)} /> )} {showToolFrame && ( <div id={TOOL_FRAME_ID} style={toolFrameStyle}> <ToolFrame /> </div> )} </div> </div> <div id={STATUS_BAR_ID} style={statusBarStyle}> <IdeStatusbar /> </div> <IdeContextMenu target="#klive_ide_app" /> <ModalDialog targetId="#app" /> </div> ); /** * Updates the current theme to dislay the app * @returns */ function updateThemeState(): void { const themeService = getThemeService(); const theme = themeService.getActiveTheme(); if (!theme) { return; } setThemeStyle(themeService.getThemeStyle()); setThemeClass(`app-container ${theme.name}-theme`); } /** * Recalculate the IdeApp layout */ function onResize(): void { // --- Calculate workbench dimensions const statusBarDiv = document.getElementById(STATUS_BAR_ID); workbenchWidth = window.innerWidth; workbenchHeight = Math.floor( window.innerHeight - (statusBarDiv?.offsetHeight ?? 0) ); const workBenchDiv = document.getElementById(WORKBENCH_ID); workBenchDiv.style.width = `${workbenchWidth}px`; workBenchDiv.style.height = `${workbenchHeight}px`; // --- Calculate sidebar and main desk dimensions const activityBarDiv = document.getElementById(ACTIVITY_BAR_ID); const sidebarDiv = document.getElementById(SIDEBAR_ID); activityBarWidth = activityBarDiv.offsetWidth; const newDeskWidth = window.innerWidth - activityBarDiv.offsetWidth; deskWidth = newDeskWidth; let newSideBarWidth = firstRender ? newDeskWidth * 0.25 : sidebarDiv.offsetWidth; if (newDeskWidth - newSideBarWidth < MIN_DESK_WIDTH) { newSideBarWidth = newDeskWidth - MIN_DESK_WIDTH; } setSidebarAndDesk(newSideBarWidth); // --- Calculate document and tool panel sizes const docFrameDiv = document.getElementById(DOCUMENT_FRAME_ID); const docFrameHeight = docFrameDiv?.offsetHeight ?? 0; if (restoreLayout) { // --- We need to restore the state of both panels documentFrameHeight = (lastDocumentFrameHeight * workbenchHeight) / (lastDocumentFrameHeight + lastToolFrameHeight); } else { // --- Calculate the height of the panel the normal way documentFrameHeight = showDocumentFrame ? showToolFrame ? firstRender ? workbenchHeight * 0.75 : docFrameHeight : workbenchHeight : 0; if ( showToolFrame && workbenchHeight - documentFrameHeight < MIN_DESK_HEIGHT ) { documentFrameHeight = workbenchHeight - MIN_DESK_HEIGHT; } } // --- Set the Document Frame height const documentFrameDiv = document.getElementById(DOCUMENT_FRAME_ID); if (documentFrameDiv) { documentFrameDiv.style.height = `${documentFrameHeight}px`; documentFrameDiv.style.width = `${mainDeskWidth}px`; } // --- Set the Tool Frame height const toolFrameDiv = document.getElementById(TOOL_FRAME_ID); toolFrameHeight = Math.round(workbenchHeight - documentFrameHeight); toolFrameHeight = toolFrameHeight; if (toolFrameDiv) { toolFrameDiv.style.height = `${toolFrameHeight}px`; } // --- Put the horizontal splitter between the document frame and the tool frame const horizontalSplitterDiv = document.getElementById( HORIZONTAL_SPLITTER_ID ); if (horizontalSplitterDiv) { horizontalSplitterPos = documentFrameHeight - SPLITTER_SIZE / 2; horizontalSplitterDiv.style.top = `${horizontalSplitterPos}px`; } // --- Save the layout temporarily if (showDocumentFrame && showToolFrame) { lastDocumentFrameHeight = documentFrameHeight; lastToolFrameHeight = toolFrameHeight; } // --- Now, we're over the first render and the restore firstRender = false; restoreLayout = false; } /** * Recalculate the dimensions of the workbench whenever the size of * the Sidebar changes * @param newSidebarWidth Width of the side bar */ function setSidebarAndDesk(newSidebarWidth: number): void { // --- Get element to calculate from const activityBarDiv = document.getElementById(ACTIVITY_BAR_ID); const sidebarDiv = document.getElementById(SIDEBAR_ID); const documentFrameDiv = document.getElementById(DOCUMENT_FRAME_ID); const toolFrameDiv = document.getElementById(TOOL_FRAME_ID); const verticalSplitterDiv = document.getElementById(VERTICAL_SPLITTER_ID); const horizontalSplitterDiv = document.getElementById( HORIZONTAL_SPLITTER_ID ); // --- Set sidebar dimesions sidebarWidth = newSidebarWidth; sidebarDiv.style.width = `${newSidebarWidth}px`; // --- Set main desk dimensions const mainDeskDiv = document.getElementById(MAIN_DESK_ID); mainDeskLeft = activityBarDiv.offsetWidth + newSidebarWidth; mainDeskDiv.style.left = `${mainDeskLeft}px`; const newMainDeskWidth = Math.round(deskWidth - newSidebarWidth); mainDeskWidth = newMainDeskWidth; mainDeskDiv.style.width = `${newMainDeskWidth}px`; // --- Calculate document and tool panel width if (documentFrameDiv) { documentFrameDiv.style.width = `${newMainDeskWidth}px`; } if (toolFrameDiv) { toolFrameDiv.style.width = `${newMainDeskWidth}px`; } // --- Put the vertical splitter between the side bar and the main desk verticalSplitterPos = activityBarDiv.offsetWidth + newSidebarWidth - SPLITTER_SIZE / 2; verticalSplitterDiv.style.left = `${verticalSplitterPos}px`; verticalSplitterDiv.style.height = `${workbenchHeight}px`; // --- Update the horizontal splitter's position if (horizontalSplitterDiv) { horizontalSplitterDiv.style.left = `${ activityBarDiv.offsetWidth + newSidebarWidth }px`; horizontalSplitterDiv.style.width = `${newMainDeskWidth}px`; } } /** * Make a note of the vertical splitter position when start moving it */ function startVerticalSplitter(): void { splitterStartPosition = sidebarWidth; } /** * Resize the workbench when moving the vertical splitter * @param delta Movement delta value */ function moveVerticalSplitter(delta: number): void { let newSideBarWidth = Math.min( Math.max(Math.round(splitterStartPosition + delta), MIN_SIDEBAR_WIDTH), Math.round(workbenchWidth - activityBarWidth - MIN_DESK_WIDTH) ); setSidebarAndDesk(newSideBarWidth); } /** * Make a note of the horizontal splitter position when start moving it */ function startHorizontalSplitter(): void { splitterStartPosition = documentFrameHeight; } /** * Resize the workbench when moving the horizontal splitter * @param delta Movement delta value */ function moveHorizontalSplitter(delta: number): void { documentFrameHeight = Math.min( Math.max(Math.round(splitterStartPosition + delta), MIN_DESK_HEIGHT), Math.round(workbenchHeight - MIN_DESK_HEIGHT) ); // --- New Document Frame height const documentFrameDiv = document.getElementById(DOCUMENT_FRAME_ID); if (documentFrameDiv) { documentFrameDiv.style.height = `${documentFrameHeight}px`; } lastDocumentFrameHeight = documentFrameHeight; // --- New Tool Frame height const toolFrameDiv = document.getElementById(TOOL_FRAME_ID); toolFrameHeight = Math.round(workbenchHeight - documentFrameHeight); if (toolFrameDiv) { toolFrameDiv.style.height = `${toolFrameHeight}px`; } lastToolFrameHeight = toolFrameHeight; // --- Put the horizontal splitter between the document frame and the tool frame const horizontalSplitterDiv = document.getElementById( HORIZONTAL_SPLITTER_ID ); if (horizontalSplitterDiv) { horizontalSplitterPos = documentFrameHeight - SPLITTER_SIZE / 2; horizontalSplitterDiv.style.top = `${horizontalSplitterPos}px`; } // --- Save the heights lastDocumentFrameHeight = documentFrameHeight; lastToolFrameHeight = toolFrameHeight; } } // ============================================================================ // Style constants const ideAppStyle: CSSProperties = { width: "100%", height: "100%", overflow: "hidden", }; const activityBarStyle: CSSProperties = { display: "inline-block", height: "100%", width: 48, verticalAlign: "top", overflow: "hidden", }; const workbenchStyle: CSSProperties = { width: workbenchWidth, height: workbenchHeight, }; const sidebarStyle: CSSProperties = { display: "inline-block", height: "100%", width: sidebarWidth, verticalAlign: "top", overflow: "hidden", }; const mainDeskStyle: CSSProperties = { display: "inline-block", height: "100%", width: mainDeskWidth, }; const documentFrameStyle: CSSProperties = { display: "flex", flexGrow: 0, flexShrink: 0, height: documentFrameHeight, width: mainDeskWidth, }; const toolFrameStyle: CSSProperties = { display: "flex", flexGrow: 0, flexShrink: 0, height: toolFrameHeight, width: mainDeskWidth, };
the_stack
import * as _ from 'lodash'; import * as m from 'mochainon'; import * as parallel from 'mocha.parallel'; import { balena, credentials, givenInitialOrganization, givenLoggedInUser, } from '../setup'; import type * as BalenaSdk from '../../..'; const { expect } = m.chai; import { assertDeepMatchAndLength, timeSuite } from '../../util'; import { itShouldSetGetAndRemoveTags, itShouldGetAllTagsByResource, } from './tags'; import type * as tagsHelper from './tags'; const keyAlternatives = [ ['id', (member: BalenaSdk.OrganizationMembership) => member.id], [ 'alternate key', (member: BalenaSdk.OrganizationMembership) => _.mapValues( _.pick(member, ['user', 'is_member_of__organization']), (obj: BalenaSdk.PineDeferred | [{ id: number }]): number => '__id' in obj ? obj.__id : obj[0].id, ), ], ] as const; describe('Organization Membership Model', function () { timeSuite(before); givenLoggedInUser(before); givenInitialOrganization(before); let ctx: Mocha.Context; before(async function () { ctx = this; this.userId = await balena.auth.getUserId(); const roles = await balena.pine.get({ resource: 'organization_membership_role', options: { $select: ['id', 'name'] }, }); this.orgRoleMap = _.keyBy(roles, 'name'); roles.forEach((role) => { expect(role).to.be.an('object'); expect(role).to.have.property('id').that.is.a('number'); }); this.orgAdminRole = this.orgRoleMap['administrator']; this.orgMemberRole = this.orgRoleMap['member']; [this.orgAdminRole, this.orgMemberRole].forEach((role) => { expect(role).to.be.an('object'); }); }); parallel('balena.models.organization.membership.getAll()', function () { it(`shoud return only the user's own memberships [Promise]`, async function () { const memberships = await balena.models.organization.membership.getAll(); assertDeepMatchAndLength(memberships, [ { user: { __id: ctx.userId }, is_member_of__organization: { __id: ctx.initialOrg.id }, organization_membership_role: { __id: ctx.orgAdminRole.id }, }, ]); }); it(`shoud return only the user's own membership [callback]`, function (done) { balena.models.organization.membership.getAll( // @ts-expect-error (_err: Error, memberships: BalenaSdk.OrganizationMembership[]) => { try { assertDeepMatchAndLength(memberships, [ { user: { __id: ctx.userId }, is_member_of__organization: { __id: ctx.initialOrg.id }, organization_membership_role: { __id: ctx.orgAdminRole.id }, }, ]); done(); } catch (err) { done(err); } }, ); }); }); describe('given a membership [read operations]', function () { let membership: BalenaSdk.OrganizationMembership | undefined; before(async function () { membership = (await balena.models.organization.membership.getAll())[0]; }); parallel('balena.models.organization.membership.get()', function () { it(`should reject when the organization membership is not found`, async function () { const promise = balena.models.organization.membership.get( Math.floor(Date.now() / 1000), ); await expect(promise).to.be.rejectedWith( 'Organization Membership not found', ); }); keyAlternatives.forEach(([title, keyGetter]) => { it(`should be able to retrieve a membership by ${title}`, async function () { const key = keyGetter(membership!); const result = await balena.models.organization.membership.get(key, { $select: 'id', $expand: { user: { $select: 'username', }, organization_membership_role: { $select: 'name', }, }, }); expect(result).to.have.nested.property( 'user[0].username', credentials.username, ); expect(result).to.have.nested.property( 'organization_membership_role[0].name', 'administrator', ); }); }); }); describe('balena.models.organization.membership.getAllByOrganization()', function () { it(`shoud return only the user's own membership`, async function () { const memberships = await balena.models.organization.membership.getAllByOrganization( this.initialOrg.id, ); assertDeepMatchAndLength(memberships, [ { user: { __id: this.userId }, is_member_of__organization: { __id: this.initialOrg.id }, organization_membership_role: { __id: this.orgAdminRole.id }, }, ]); }); }); }); describe('given a new organization', function () { givenInitialOrganization(before); before(async function () { this.organization = this.initialOrg; await balena.pine.delete({ resource: 'organization_membership', options: { $filter: { user: { $ne: this.userId }, is_member_of__organization: this.organization.id, }, }, }); }); describe('balena.models.organization.membership.create()', function () { before(function () { ctx = this; }); parallel('[read operations]', function () { it(`should not be able to add a new member to the organization usign a wrong role name`, async function () { const promise = balena.models.organization.membership.create({ organization: ctx.organization.id, username: credentials.member.username, // @ts-expect-error roleName: 'unknown role', }); await expect(promise).to.be.rejected.and.eventually.have.property( 'code', 'BalenaOrganizationMembershipRoleNotFound', ); }); const randomOrdInfo = { id: Math.floor(Date.now() / 1000), handle: `random_sdk_test_org_handle_${Math.floor(Date.now() / 1000)}`, }; ['id', 'handle'].forEach((field) => { it(`should not be able to add a new member when using an not existing organization ${field}`, async function () { const promise = balena.models.organization.membership.create({ organization: randomOrdInfo[field], username: credentials.member.username, roleName: 'member', }); await expect(promise).to.be.rejected.and.eventually.have.property( 'code', 'BalenaOrganizationNotFound', ); }); }); }); describe('[mutating operations]', function () { let membership: BalenaSdk.OrganizationMembership | undefined; afterEach(async function () { await balena.models.organization.membership.remove(membership!.id); }); ['id', 'handle'].forEach(function (field) { it(`should be able to add a new member to the organization by ${field}`, async function () { membership = await balena.models.organization.membership.create({ organization: this.organization[field], username: credentials.member.username, }); expect(membership) .to.be.an('object') .that.has.nested.property('organization_membership_role.__id') .that.equals(this.orgMemberRole.id); }); }); it(`should be able to add a new member to the organization without providing a role`, async function () { membership = await balena.models.organization.membership.create({ organization: this.organization.id, username: credentials.member.username, }); expect(membership) .to.be.an('object') .that.has.nested.property('organization_membership_role.__id') .that.equals(this.orgMemberRole.id); }); (['member', 'administrator'] as const).forEach(function (roleName) { it(`should be able to add a new member to the organization with a given role [${roleName}]`, async function () { membership = await balena.models.organization.membership.create({ organization: this.organization.id, username: credentials.member.username, roleName, }); expect(membership) .to.be.an('object') .that.has.nested.property('organization_membership_role.__id') .that.equals(this.orgRoleMap[roleName].id); }); }); }); }); describe('given a member organization membership [contained scenario]', function () { let membership: BalenaSdk.OrganizationMembership | undefined; beforeEach(async function () { membership = await balena.models.organization.membership.create({ organization: this.organization.id, username: credentials.member.username, }); }); describe('balena.models.organization.membership.remove()', function () { keyAlternatives.forEach(([title, keyGetter]) => { it(`should be able to remove a member by ${title}`, async function () { const key = keyGetter(membership!); await balena.models.organization.membership.remove(key); const promise = balena.models.organization.membership.get( membership!.id, ); await expect(promise).to.be.rejectedWith( 'Organization Membership not found', ); }); }); }); }); describe('given an administrator organization membership [contained scenario]', function () { let membership: BalenaSdk.OrganizationMembership | undefined; before(async function () { membership = await balena.models.organization.membership.create({ organization: this.organization.id, username: credentials.member.username, roleName: 'administrator', }); }); describe('balena.models.organization.membership.changeRole()', function () { it(`should not be able to change an organization membership to an unknown role`, async function () { const promise = balena.models.organization.membership.changeRole( membership!.id, 'unknown role', ); await expect(promise).to.be.rejected.and.eventually.have.property( 'code', 'BalenaOrganizationMembershipRoleNotFound', ); }); const roleChangeTest = ( rolenName: BalenaSdk.OrganizationMembershipRoles, [title, keyGetter]: typeof keyAlternatives[number], ) => { it(`should be able to change an organization membership to "${rolenName}" by ${title}`, async function () { const key = keyGetter(membership!); await balena.models.organization.membership.changeRole( key, rolenName, ); membership = await balena.models.organization.membership.get( membership!.id, { $select: 'id', $expand: { user: { $select: ['id', 'username'], }, is_member_of__organization: { $select: ['id'], }, organization_membership_role: { $select: 'name', }, }, }, ); expect(membership).to.have.nested.property( 'user[0].username', credentials.member.username, ); expect(membership).to.have.nested.property( 'is_member_of__organization[0].id', this.organization.id, ); expect(membership).to.have.nested.property( 'organization_membership_role[0].name', rolenName, ); }); }; keyAlternatives.forEach((keyAlternative) => { roleChangeTest('member', keyAlternative); roleChangeTest('administrator', keyAlternative); }); }); describe('balena.models.organization.membership.remove()', function () { it(`should be able to remove an administrator`, async function () { await balena.models.organization.membership.remove(membership!.id); const promise = balena.models.organization.membership.get( membership!.id, ); await expect(promise).to.be.rejectedWith( 'Organization Membership not found', ); }); it(`should not be able to remove the last membership of the organization`, async function () { const [lastAdminMembership] = await balena.models.organization.membership.getAllByOrganization( this.organization.id, { $select: 'id', $filter: { user: this.userId }, }, ); expect(lastAdminMembership).to.be.an('object'); expect(lastAdminMembership) .to.have.property('id') .that.is.a('number'); const promise = balena.models.organization.membership.remove( lastAdminMembership.id, ); await expect(promise).to.be.rejectedWith( `It is necessary that each organization that is active, includes at least one organization membership that has an organization membership role that has a name (Auth) that is equal to "administrator"`, ); }); }); }); describe('balena.models.organization.membership.tags', function () { describe('[contained scenario]', function () { const orgTagTestOptions: tagsHelper.Options<BalenaSdk.OrganizationMembershipTag> = { model: balena.models.organization.membership .tags as tagsHelper.TagModelBase<BalenaSdk.OrganizationMembershipTag>, modelNamespace: 'balena.models.organization.membership.tags', resourceName: 'organization', uniquePropertyNames: ['id', 'handle'], }; const orgMembershipTagTestOptions: tagsHelper.Options<BalenaSdk.OrganizationMembershipTag> = { model: balena.models.organization.membership .tags as tagsHelper.TagModelBase<BalenaSdk.OrganizationMembershipTag>, modelNamespace: 'balena.models.organization.membership.tags', resourceName: 'organization_membership', uniquePropertyNames: ['id'], }; before(async function () { const [membership] = await balena.models.organization.membership.getAllByOrganization( this.organization.id, { $filter: { user: this.userId }, }, ); expect(membership).to.be.an('object'); expect(membership).to.have.property('id').that.is.a('number'); orgTagTestOptions.resourceProvider = () => this.organization; // used for tag creation during the // device.tags.getAllByOrganization() test orgTagTestOptions.setTagResourceProvider = () => membership; orgMembershipTagTestOptions.resourceProvider = () => membership; // Clear all tags, since this is not a fresh organization await balena.pine.delete({ resource: 'organization_membership_tag', options: { $filter: { 1: 1 }, }, }); }); itShouldSetGetAndRemoveTags(orgMembershipTagTestOptions); describe('balena.models.organization.membership.tags.getAllByOrganization()', function () { itShouldGetAllTagsByResource(orgTagTestOptions); }); describe('balena.models.organization.membership.tags.getAllByOrganizationMembership()', function () { itShouldGetAllTagsByResource(orgMembershipTagTestOptions); }); }); }); }); });
the_stack
import { ObjectValidation, ValidationTypes } from '../IstioObjects'; import { parseKialiValidations } from '../AceValidations'; const fs = require('fs'); const destinationRuleValidations: ObjectValidation = { name: 'details', objectType: 'destinationrule', valid: false, checks: [ { message: "Host doesn't have a valid service", severity: ValidationTypes.Error, path: 'spec/host' } ] }; const vsInvalidHosts: ObjectValidation = { name: 'productpage', objectType: 'virtualservice', valid: false, checks: [ { message: "Hosts doesn't have a valid service", severity: ValidationTypes.Error, path: 'spec/hosts' } ] }; const vsInvalidHttpFirstRoute: ObjectValidation = { name: 'productpage', objectType: 'virtualservice', valid: false, checks: [ { message: 'All routes should have weight', severity: ValidationTypes.Error, path: 'spec/http[0]/route' } ] }; const vsInvalidHttpSecondRoute: ObjectValidation = { name: 'productpage', objectType: 'virtualservice', valid: false, checks: [ { message: 'All routes should have weight', severity: ValidationTypes.Error, path: 'spec/http[1]/route' } ] }; const vsInvalidHttpThirdRoute: ObjectValidation = { name: 'productpage', objectType: 'virtualservice', valid: false, checks: [ { message: 'All routes should have weight', severity: ValidationTypes.Error, path: 'spec/http[2]/route' } ] }; const vsInvalidHttpSecondSecondDestinationField: ObjectValidation = { name: 'productpage', objectType: 'virtualservice', valid: false, checks: [ { message: 'Destination field is mandatory', severity: ValidationTypes.Error, path: 'spec/http[1]/route[1]' } ] }; const vsInvalidHttpThirdFirstDestinationField: ObjectValidation = { name: 'productpage', objectType: 'virtualservice', valid: false, checks: [ { message: 'Destination field is mandatory', severity: ValidationTypes.Error, path: 'spec/http[2]/route[0]' } ] }; const vsInvalidHttpThirdFirstSubsetNotFound: ObjectValidation = { name: 'productpage', objectType: 'virtualservice', valid: false, checks: [ { message: 'Subset not found', severity: ValidationTypes.Warning, path: 'spec/http[2]/route[0]/destination' } ] }; const vsInvalidHttpFirstSecondSubsetNotFound: ObjectValidation = { name: 'productpage', objectType: 'virtualservice', valid: false, checks: [ { message: 'Subset not found', severity: ValidationTypes.Warning, path: 'spec/http[0]/route[1]/destination' } ] }; const vsInvalidHttpFourthFirstWeigth: ObjectValidation = { name: 'productpage', objectType: 'virtualservice', valid: false, checks: [ { message: 'Weight must be a number', severity: ValidationTypes.Warning, path: 'spec/http[3]/route[0]/weigth/25a' } ] }; const vsInvalidHttpFifthSecondWeigth: ObjectValidation = { name: 'productpage', objectType: 'virtualservice', valid: false, checks: [ { message: 'Weight must be a number', severity: ValidationTypes.Warning, path: 'spec/http[4]/route[1]/weigth/28a' } ] }; const destinationRuleYaml = fs.readFileSync(`./src/types/__testData__/destinationRule.yaml`).toString(); const virtualServiceYaml = fs.readFileSync(`./src/types/__testData__/virtualService.yaml`).toString(); describe('#parseKialiValidations in DestinationRule', () => { it('should mark an invalid host', () => { const aceValidations = parseKialiValidations(destinationRuleYaml, destinationRuleValidations); expect(aceValidations).toBeDefined(); expect(aceValidations.markers.length).toBe(1); expect(aceValidations.annotations.length).toBe(1); /* Check it marks lines 3-4 (starting to count in 0 instead of 1) host: details */ const marker = aceValidations.markers[0]; expect(marker).toBeDefined(); expect(marker.startRow).toEqual(3); expect(marker.endRow).toEqual(3); expect(marker.startCol).toEqual(0); expect(marker.endCol).toEqual(0); const annotation = aceValidations.annotations[0]; expect(annotation).toBeDefined(); expect(annotation.column).toEqual(0); expect(annotation.row).toEqual(3); expect(annotation.type).toEqual('error'); expect(annotation.text).toEqual("Host doesn't have a valid service"); }); }); describe('#parseKialiValidations in VirtualService', () => { it('should detect invalid hosts', () => { const aceValidations = parseKialiValidations(virtualServiceYaml, vsInvalidHosts); expect(aceValidations).toBeDefined(); expect(aceValidations.markers.length).toBe(1); expect(aceValidations.annotations.length).toBe(1); /* Check it marks lines 3-5 (starting to count in 0): hosts: - productpage */ const marker = aceValidations.markers[0]; expect(marker).toBeDefined(); expect(marker.startRow).toEqual(3); expect(marker.endRow).toEqual(4); expect(marker.startCol).toEqual(0); expect(marker.endCol).toEqual(0); const annotation = aceValidations.annotations[0]; expect(annotation).toBeDefined(); expect(annotation.column).toEqual(0); expect(annotation.row).toEqual(3); expect(annotation.type).toEqual('error'); expect(annotation.text).toEqual("Hosts doesn't have a valid service"); }); it('should detect invalid first http route', () => { const aceValidations = parseKialiValidations(virtualServiceYaml, vsInvalidHttpFirstRoute); expect(aceValidations).toBeDefined(); expect(aceValidations.markers.length).toBe(1); expect(aceValidations.annotations.length).toBe(1); /* Check it marks lines 12-19 (starting to count in 0): route: - destination: name: productpage subset: v1 - destination: name: productpage subset: v2 */ const marker = aceValidations.markers[0]; expect(marker).toBeDefined(); expect(marker.startRow).toBe(12); expect(marker.endRow).toBe(18); expect(marker.startCol).toBe(4); expect(marker.endCol).toBe(0); const annotation = aceValidations.annotations[0]; expect(annotation).toBeDefined(); expect(annotation.column).toBe(0); expect(annotation.row).toBe(12); expect(annotation.type).toBe('error'); expect(annotation.text).toBe('All routes should have weight'); }); it('should detect invalid second http route', () => { const aceValidations = parseKialiValidations(virtualServiceYaml, vsInvalidHttpSecondRoute); expect(aceValidations).toBeDefined(); expect(aceValidations.markers.length).toBe(1); expect(aceValidations.annotations.length).toBe(1); /* Check it marks lines 22-29 (starting to count in 0): route: - destination: name: productpage subset: v3 - destination: name: productpage subset: v4 */ const marker = aceValidations.markers[0]; expect(marker).toBeDefined(); expect(marker.startRow).toEqual(22); expect(marker.endRow).toEqual(28); expect(marker.startCol).toEqual(4); expect(marker.endCol).toEqual(0); const annotation = aceValidations.annotations[0]; expect(annotation).toBeDefined(); expect(annotation.column).toEqual(0); expect(annotation.row).toEqual(22); expect(annotation.type).toEqual('error'); expect(annotation.text).toEqual('All routes should have weight'); }); it('should detect invalid third http route', () => { const aceValidations = parseKialiValidations(virtualServiceYaml, vsInvalidHttpThirdRoute); expect(aceValidations).toBeDefined(); expect(aceValidations.markers.length).toBe(1); expect(aceValidations.annotations.length).toBe(1); /* Check it marks lines 32-39 (starting to count in 0): route: - destination: name: productpage subset: v5 - destination: name: productpage subset: v6 */ const marker = aceValidations.markers[0]; expect(marker).toBeDefined(); expect(marker.startRow).toEqual(32); expect(marker.endRow).toEqual(38); expect(marker.startCol).toEqual(4); expect(marker.endCol).toEqual(0); const annotation = aceValidations.annotations[0]; expect(annotation).toBeDefined(); expect(annotation.column).toEqual(0); expect(annotation.row).toEqual(32); expect(annotation.type).toEqual('error'); expect(annotation.text).toEqual('All routes should have weight'); }); it('should detect invalid second http second destination field', () => { const aceValidations = parseKialiValidations(virtualServiceYaml, vsInvalidHttpSecondSecondDestinationField); expect(aceValidations).toBeDefined(); expect(aceValidations.markers.length).toBe(1); expect(aceValidations.annotations.length).toBe(1); /* Check it marks lines 26-29 (starting to count in 0): - destination: name: productpage subset: v4 */ const marker = aceValidations.markers[0]; expect(marker).toBeDefined(); expect(marker.startRow).toEqual(26); expect(marker.endRow).toEqual(28); expect(marker.startCol).toEqual(4); expect(marker.endCol).toEqual(0); const annotation = aceValidations.annotations[0]; expect(annotation).toBeDefined(); expect(annotation.column).toEqual(0); expect(annotation.row).toEqual(26); expect(annotation.type).toEqual('error'); expect(annotation.text).toEqual('Destination field is mandatory'); }); it('should detect invalid third http first destination field', () => { const aceValidations = parseKialiValidations(virtualServiceYaml, vsInvalidHttpThirdFirstDestinationField); expect(aceValidations).toBeDefined(); expect(aceValidations.markers.length).toBe(1); expect(aceValidations.annotations.length).toBe(1); /* Check it marks lines 33-36 (starting to count in 0): - destination: name: productpage subset: v4 */ const marker = aceValidations.markers[0]; expect(marker).toBeDefined(); expect(marker.startRow).toEqual(33); expect(marker.endRow).toEqual(35); expect(marker.startCol).toEqual(6); expect(marker.endCol).toEqual(0); const annotation = aceValidations.annotations[0]; expect(annotation).toBeDefined(); expect(annotation.column).toEqual(0); expect(annotation.row).toEqual(33); expect(annotation.type).toEqual('error'); expect(annotation.text).toEqual('Destination field is mandatory'); }); it('should detect invalid third http first destination field subset not found', () => { const aceValidations = parseKialiValidations(virtualServiceYaml, vsInvalidHttpThirdFirstSubsetNotFound); expect(aceValidations).toBeDefined(); expect(aceValidations.markers.length).toBe(1); expect(aceValidations.annotations.length).toBe(1); /* Check it marks lines 33-36 (starting to count in 0): - destination: name: productpage subset: v4 */ const marker = aceValidations.markers[0]; expect(marker).toBeDefined(); expect(marker.startRow).toEqual(33); expect(marker.endRow).toEqual(35); expect(marker.startCol).toEqual(8); expect(marker.endCol).toEqual(0); const annotation = aceValidations.annotations[0]; expect(annotation).toBeDefined(); expect(annotation.column).toEqual(0); expect(annotation.row).toEqual(33); expect(annotation.type).toEqual('warning'); expect(annotation.text).toEqual('Subset not found'); }); it('should detect invalid first http second destination field subset not found', () => { const aceValidations = parseKialiValidations(virtualServiceYaml, vsInvalidHttpFirstSecondSubsetNotFound); expect(aceValidations).toBeDefined(); expect(aceValidations.markers.length).toBe(1); expect(aceValidations.annotations.length).toBe(1); /* Check it marks lines 16-19 (starting to count in 0): - destination: name: productpage subset: v4 */ const marker = aceValidations.markers[0]; expect(marker).toBeDefined(); expect(marker.startRow).toEqual(16); expect(marker.endRow).toEqual(18); expect(marker.startCol).toEqual(8); expect(marker.endCol).toEqual(0); const annotation = aceValidations.annotations[0]; expect(annotation).toBeDefined(); expect(annotation.column).toEqual(0); expect(annotation.row).toEqual(16); expect(annotation.type).toEqual('warning'); expect(annotation.text).toEqual('Subset not found'); }); it('should detect invalid fourth http first weight', () => { const aceValidations = parseKialiValidations(virtualServiceYaml, vsInvalidHttpFourthFirstWeigth); expect(aceValidations).toBeDefined(); expect(aceValidations.markers.length).toBe(1); expect(aceValidations.annotations.length).toBe(1); /* Check it marks lines 46-47 (starting to count in 0): weight: 25a */ const marker = aceValidations.markers[0]; expect(marker).toBeDefined(); expect(marker.startRow).toEqual(46); expect(marker.endRow).toEqual(46); expect(marker.startCol).toEqual(16); expect(marker.endCol).toEqual(0); const annotation = aceValidations.annotations[0]; expect(annotation).toBeDefined(); expect(annotation.column).toEqual(0); expect(annotation.row).toEqual(46); expect(annotation.type).toEqual('warning'); expect(annotation.text).toEqual('Weight must be a number'); }); it('should detect invalid fifth http second weight', () => { const aceValidations = parseKialiValidations(virtualServiceYaml, vsInvalidHttpFifthSecondWeigth); expect(aceValidations).toBeDefined(); expect(aceValidations.markers.length).toEqual(1); expect(aceValidations.annotations.length).toEqual(1); /* Check it marks lines 62-63 (starting to count in 0): weight: 28a */ const marker = aceValidations.markers[0]; expect(marker).toBeDefined(); expect(marker.startRow).toEqual(62); expect(marker.endRow).toEqual(62); expect(marker.startCol).toEqual(16); expect(marker.endCol).toEqual(0); const annotation = aceValidations.annotations[0]; expect(annotation).toBeDefined(); expect(annotation.column).toEqual(0); expect(annotation.row).toEqual(62); expect(annotation.type).toEqual('warning'); expect(annotation.text).toEqual('Weight must be a number'); }); });
the_stack
import type { ReactElement } from 'react'; import { useContext } from 'react'; import React, { useMemo } from 'react'; import { Row, Col, Form, Divider, ConfigProvider } from 'antd'; import type { FormInstance, FormProps } from 'antd/lib/form/Form'; import RcResizeObserver from 'rc-resize-observer'; import { useIntl } from '@ant-design/pro-provider'; import { isBrowser, useMountMergeState } from '@ant-design/pro-utils'; import useMergedState from 'rc-util/lib/hooks/useMergedState'; import type { CommonFormProps } from '../../BaseForm'; import BaseForm from '../../BaseForm'; import type { ActionsProps } from './Actions'; import Actions from './Actions'; import classNames from 'classnames'; import './index.less'; const CONFIG_SPAN_BREAKPOINTS = { xs: 513, sm: 513, md: 785, lg: 992, xl: 1057, xxl: Infinity, }; /** 配置表单列变化的容器宽度断点 */ const BREAKPOINTS = { vertical: [ // [breakpoint, cols, layout] [513, 1, 'vertical'], [785, 2, 'vertical'], [1057, 3, 'vertical'], [Infinity, 4, 'vertical'], ], default: [ [513, 1, 'vertical'], [701, 2, 'vertical'], [1062, 3, 'horizontal'], [1352, 3, 'horizontal'], [Infinity, 4, 'horizontal'], ], }; /** * 合并用户和默认的配置 * * @param layout * @param width */ const getSpanConfig = ( layout: FormProps['layout'], width: number, span?: SpanConfig, ): { span: number; layout: FormProps['layout'] } => { if (span && typeof span === 'number') { return { span, layout, }; } const spanConfig = span ? Object.keys(span).map((key) => [CONFIG_SPAN_BREAKPOINTS[key], 24 / span[key], 'horizontal']) : BREAKPOINTS[layout || 'default']; const breakPoint = (spanConfig || BREAKPOINTS.default).find( (item: [number, number, FormProps['layout']]) => width < item[0] + 16, // 16 = 2 * (ant-row -8px margin) ); return { span: 24 / breakPoint[1], layout: breakPoint[2], }; }; export type SpanConfig = | number | { xs: number; sm: number; md: number; lg: number; xl: number; xxl: number; }; export type BaseQueryFilterProps = Omit<ActionsProps, 'submitter' | 'setCollapsed' | 'isForm'> & { defaultCollapsed?: boolean; layout?: FormProps['layout']; defaultColsNumber?: number; labelWidth?: number | 'auto'; split?: boolean; className?: string; /** 配置列数 */ span?: SpanConfig; /** 查询按钮的文本 */ searchText?: string; /** 重置按钮的文本 */ resetText?: string; form?: FormProps['form']; /** * @param searchConfig 基础的配置 * @param props 更加详细的配置 { * type?: 'form' | 'list' | 'table' | 'cardList' | undefined; * form: FormInstance; * submit: () => void; * collapse: boolean; * setCollapse: (collapse: boolean) => void; * showCollapseButton: boolean; } * @name 底部操作栏的 render */ optionRender?: | (( searchConfig: Omit<BaseQueryFilterProps, 'submitter' | 'isForm'>, props: Omit<BaseQueryFilterProps, 'searchConfig'>, dom: React.ReactNode[], ) => React.ReactNode[]) | false; /** 忽略 Form.Item 规则 */ ignoreRules?: boolean; }; const flatMapItems = (items: React.ReactNode[], ignoreRules?: boolean): React.ReactNode[] => { return items.flatMap((item: any) => { if (item?.type.displayName === 'ProForm-Group' && !item.props?.title) { return item.props.children; } if (ignoreRules && React.isValidElement(item)) { return React.cloneElement(item, { ...(item.props as any), formItemProps: { ...(item.props as any)?.formItemProps, rules: [], }, }); } return item; }); }; export type QueryFilterProps<T = Record<string, any>> = Omit<FormProps<T>, 'onFinish'> & CommonFormProps<T> & BaseQueryFilterProps & { onReset?: (values: T) => void; }; const QueryFilterContent: React.FC<{ defaultCollapsed: boolean; onCollapse: undefined | ((collapsed: boolean) => void); collapsed: boolean | undefined; resetText: string | undefined; searchText: string | undefined; split?: boolean; form: FormInstance<any>; items: React.ReactNode[]; submitter?: JSX.Element | false; showLength: number; collapseRender: QueryFilterProps<any>['collapseRender']; spanSize: { span: number; layout: FormProps['layout']; }; optionRender: BaseQueryFilterProps['optionRender']; ignoreRules?: boolean; preserve?: boolean; }> = (props) => { const intl = useIntl(); const resetText = props.resetText || intl.getMessage('tableForm.reset', '重置'); const searchText = props.searchText || intl.getMessage('tableForm.search', '搜索'); const [collapsed, setCollapsed] = useMergedState<boolean>( () => props.defaultCollapsed && !!props.submitter, { value: props.collapsed, onChange: props.onCollapse, }, ); const { optionRender, collapseRender, split, items, spanSize, showLength } = props; const submitter = useMemo(() => { if (!props.submitter || optionRender === false) { return null; } return React.cloneElement(props.submitter, { searchConfig: { resetText, submitText: searchText, }, render: optionRender ? (_: any, dom: React.ReactNode[]) => optionRender( { ...props, resetText, searchText, }, props, dom, ) : optionRender, ...props.submitter.props, }); }, [props, resetText, searchText, optionRender]); // totalSpan 统计控件占的位置,计算 offset 保证查询按钮在最后一列 let totalSpan = 0; let itemLength = 0; // for split compute let currentSpan = 0; const doms = flatMapItems(items, props.ignoreRules).map( (item: React.ReactNode, index: number) => { // 如果 formItem 自己配置了 hidden,默认使用它自己的 const colSize = React.isValidElement<any>(item) ? item?.props?.colSize : 1; const colSpan = Math.min(spanSize.span * (colSize || 1), 24); // 计算总的 totalSpan 长度 totalSpan += colSpan; const hidden: boolean = (item as ReactElement<{ hidden: boolean }>)?.props?.hidden || // 如果收起了 (collapsed && // 如果 超过显示长度 且 总长度超过了 24 index >= showLength - 1 && !!index && totalSpan >= 24); itemLength += 1; // 每一列的key, 一般是存在的 const itemKey = (React.isValidElement(item) && (item.key || `${item.props?.name}`)) || index; if (React.isValidElement(item) && hidden) { if (!props.preserve) { return null; } return React.cloneElement(item, { hidden: true, key: itemKey || index, }); } if (24 - (currentSpan % 24) < colSpan) { // 如果当前行空余位置放不下,那么折行 totalSpan += 24 - (currentSpan % 24); currentSpan += 24 - (currentSpan % 24); } currentSpan += colSpan; const colItem = ( <Col key={itemKey} span={colSpan}> {item} </Col> ); if (split && currentSpan % 24 === 0 && index < itemLength - 1) { return [ colItem, <Col span="24" key="line"> <Divider style={{ marginTop: -8, marginBottom: 16 }} dashed /> </Col>, ]; } return colItem; }, ); /** 是否需要展示 collapseRender */ const needCollapseRender = useMemo(() => { if (totalSpan < 24 || itemLength < showLength) { return false; } return true; }, [itemLength, showLength, totalSpan]); const offset = useMemo(() => { const offsetSpan = (currentSpan % 24) + spanSize.span; return 24 - offsetSpan; }, [currentSpan, spanSize.span]); return ( <Row gutter={24} justify="start" key="resize-observer-row"> {doms} {submitter && ( <Col key="submitter" span={spanSize.span} offset={offset} style={{ textAlign: 'right', }} > <Form.Item label=" " colon={false} className="pro-form-query-filter-actions"> <Actions key="pro-form-query-filter-actions" collapsed={collapsed} collapseRender={needCollapseRender ? collapseRender : false} submitter={submitter} setCollapsed={setCollapsed} /> </Form.Item> </Col> )} </Row> ); }; const defaultWidth = isBrowser() ? document.body.clientWidth : 1024; function QueryFilter<T = Record<string, any>>(props: QueryFilterProps<T>) { const { collapsed: controlCollapsed, layout, defaultCollapsed = true, defaultColsNumber, span, searchText, resetText, optionRender, collapseRender, onReset, onCollapse, labelWidth = '80', style, split, preserve = true, ignoreRules, ...rest } = props; const context = useContext(ConfigProvider.ConfigContext); const baseClassName = context.getPrefixCls('pro-form-query-filter'); const [width, setWidth] = useMountMergeState( () => (typeof style?.width === 'number' ? style?.width : defaultWidth) as number, ); const spanSize = useMemo(() => getSpanConfig(layout, width + 16, span), [layout, width, span]); const showLength = useMemo(() => { if (defaultColsNumber !== undefined) { return defaultColsNumber; } return Math.max(1, 24 / spanSize.span); }, [defaultColsNumber, spanSize.span]); const labelFlexStyle = useMemo(() => { if (labelWidth && spanSize.layout !== 'vertical' && labelWidth !== 'auto') { return `0 0 ${labelWidth}px`; } return undefined; }, [spanSize.layout, labelWidth]); return ( <RcResizeObserver key="resize-observer" onResize={(offset) => { if (width !== offset.width && offset.width > 17) { setWidth(offset.width); } }} > <BaseForm isKeyPressSubmit preserve={preserve} {...rest} className={classNames(baseClassName, rest.className)} onReset={onReset} style={style} layout={spanSize.layout} fieldProps={{ style: { width: '100%', }, }} formItemProps={{ labelCol: { flex: labelFlexStyle, }, }} groupProps={{ titleStyle: { display: 'inline-block', marginRight: 16, }, }} contentRender={(items, renderSubmitter, form) => ( <QueryFilterContent spanSize={spanSize} collapsed={controlCollapsed} form={form} collapseRender={collapseRender} defaultCollapsed={defaultCollapsed} onCollapse={onCollapse} optionRender={optionRender} submitter={renderSubmitter} items={items} split={split} resetText={props.resetText} searchText={props.searchText} preserve={preserve} ignoreRules={ignoreRules} showLength={showLength} /> )} /> </RcResizeObserver> ); } export default QueryFilter;
the_stack
import { GaxiosPromise } from 'gaxios'; import { Compute, JWT, OAuth2Client, UserRefreshClient } from 'google-auth-library'; import { APIRequestContext, BodyResponseCallback, GlobalOptions, GoogleConfigurable, MethodOptions } from 'googleapis-common'; export declare namespace identitytoolkit_v3 { interface Options extends GlobalOptions { version: 'v3'; } interface StandardParameters { /** * Data format for the response. */ alt?: string; /** * Selector specifying which fields to include in a partial response. */ fields?: string; /** * API key. Your API key identifies your project and provides you with API * access, quota, and reports. Required unless you provide an OAuth 2.0 * token. */ key?: string; /** * OAuth 2.0 token for the current user. */ oauth_token?: string; /** * Returns response with indentations and line breaks. */ prettyPrint?: boolean; /** * An opaque string that represents a user for quota purposes. Must not * exceed 40 characters. */ quotaUser?: string; /** * Deprecated. Please use quotaUser instead. */ userIp?: string; } /** * Google Identity Toolkit API * * Help the third party sites to implement federated login. * * @example * const {google} = require('googleapis'); * const identitytoolkit = google.identitytoolkit('v3'); * * @namespace identitytoolkit * @type {Function} * @version v3 * @variation v3 * @param {object=} options Options for Identitytoolkit */ class Identitytoolkit { context: APIRequestContext; relyingparty: Resource$Relyingparty; constructor(options: GlobalOptions, google?: GoogleConfigurable); } /** * Response of creating the IDP authentication URL. */ interface Schema$CreateAuthUriResponse { /** * all providers the user has once used to do federated login */ allProviders?: string[]; /** * The URI used by the IDP to authenticate the user. */ authUri?: string; /** * True if captcha is required. */ captchaRequired?: boolean; /** * True if the authUri is for user&#39;s existing provider. */ forExistingProvider?: boolean; /** * The fixed string identitytoolkit#CreateAuthUriResponse&quot;. */ kind?: string; /** * The provider ID of the auth URI. */ providerId?: string; /** * Whether the user is registered if the identifier is an email. */ registered?: boolean; /** * Session ID which should be passed in the following verifyAssertion * request. */ sessionId?: string; /** * All sign-in methods this user has used. */ signinMethods?: string[]; } /** * Respone of deleting account. */ interface Schema$DeleteAccountResponse { /** * The fixed string &quot;identitytoolkit#DeleteAccountResponse&quot;. */ kind?: string; } /** * Response of downloading accounts in batch. */ interface Schema$DownloadAccountResponse { /** * The fixed string &quot;identitytoolkit#DownloadAccountResponse&quot;. */ kind?: string; /** * The next page token. To be used in a subsequent request to return the * next page of results. */ nextPageToken?: string; /** * The user accounts data. */ users?: Schema$UserInfo[]; } /** * Response of email signIn. */ interface Schema$EmailLinkSigninResponse { /** * The user&#39;s email. */ email?: string; /** * Expiration time of STS id token in seconds. */ expiresIn?: string; /** * The STS id token to login the newly signed in user. */ idToken?: string; /** * Whether the user is new. */ isNewUser?: boolean; /** * The fixed string &quot;identitytoolkit#EmailLinkSigninResponse&quot;. */ kind?: string; /** * The RP local ID of the user. */ localId?: string; /** * The refresh token for the signed in user. */ refreshToken?: string; } /** * Template for an email template. */ interface Schema$EmailTemplate { /** * Email body. */ body?: string; /** * Email body format. */ format?: string; /** * From address of the email. */ from?: string; /** * From display name. */ fromDisplayName?: string; /** * Reply-to address. */ replyTo?: string; /** * Subject of the email. */ subject?: string; } /** * Response of getting account information. */ interface Schema$GetAccountInfoResponse { /** * The fixed string &quot;identitytoolkit#GetAccountInfoResponse&quot;. */ kind?: string; /** * The info of the users. */ users?: Schema$UserInfo[]; } /** * Response of getting a code for user confirmation (reset password, change * email etc.). */ interface Schema$GetOobConfirmationCodeResponse { /** * The email address that the email is sent to. */ email?: string; /** * The fixed string * &quot;identitytoolkit#GetOobConfirmationCodeResponse&quot;. */ kind?: string; /** * The code to be send to the user. */ oobCode?: string; } /** * Response of getting recaptcha param. */ interface Schema$GetRecaptchaParamResponse { /** * The fixed string &quot;identitytoolkit#GetRecaptchaParamResponse&quot;. */ kind?: string; /** * Site key registered at recaptcha. */ recaptchaSiteKey?: string; /** * The stoken field for the recaptcha widget, used to request captcha * challenge. */ recaptchaStoken?: string; } /** * Request to get the IDP authentication URL. */ interface Schema$IdentitytoolkitRelyingpartyCreateAuthUriRequest { /** * The app ID of the mobile app, base64(CERT_SHA1):PACKAGE_NAME for Android, * BUNDLE_ID for iOS. */ appId?: string; /** * Explicitly specify the auth flow type. Currently only support * &quot;CODE_FLOW&quot; type. The field is only used for Google provider. */ authFlowType?: string; /** * The relying party OAuth client ID. */ clientId?: string; /** * The opaque value used by the client to maintain context info between the * authentication request and the IDP callback. */ context?: string; /** * The URI to which the IDP redirects the user after the federated login * flow. */ continueUri?: string; /** * The query parameter that client can customize by themselves in auth url. * The following parameters are reserved for server so that they cannot be * customized by clients: client_id, response_type, scope, redirect_uri, * state, oauth_token. */ customParameter?: { [key: string]: string; }; /** * The hosted domain to restrict sign-in to accounts at that domain for * Google Apps hosted accounts. */ hostedDomain?: string; /** * The email or federated ID of the user. */ identifier?: string; /** * The developer&#39;s consumer key for OpenId OAuth Extension */ oauthConsumerKey?: string; /** * Additional oauth scopes, beyond the basid user profile, that the user * would be prompted to grant */ oauthScope?: string; /** * Optional realm for OpenID protocol. The sub string * &quot;scheme://domain:port&quot; of the param &quot;continueUri&quot; is * used if this is not set. */ openidRealm?: string; /** * The native app package for OTA installation. */ otaApp?: string; /** * The IdP ID. For white listed IdPs it&#39;s a short domain name e.g. * google.com, aol.com, live.net and yahoo.com. For other OpenID IdPs * it&#39;s the OP identifier. */ providerId?: string; /** * The session_id passed by client. */ sessionId?: string; /** * For multi-tenant use cases, in order to construct sign-in URL with the * correct IDP parameters, Firebear needs to know which Tenant to retrieve * IDP configs from. */ tenantId?: string; /** * Tenant project number to be used for idp discovery. */ tenantProjectNumber?: string; } /** * Request to delete account. */ interface Schema$IdentitytoolkitRelyingpartyDeleteAccountRequest { /** * GCP project number of the requesting delegated app. Currently only * intended for Firebase V1 migration. */ delegatedProjectNumber?: string; /** * The GITKit token or STS id token of the authenticated user. */ idToken?: string; /** * The local ID of the user. */ localId?: string; } /** * Request to download user account in batch. */ interface Schema$IdentitytoolkitRelyingpartyDownloadAccountRequest { /** * GCP project number of the requesting delegated app. Currently only * intended for Firebase V1 migration. */ delegatedProjectNumber?: string; /** * The max number of results to return in the response. */ maxResults?: number; /** * The token for the next page. This should be taken from the previous * response. */ nextPageToken?: string; /** * Specify which project (field value is actually project id) to operate. * Only used when provided credential. */ targetProjectId?: string; } /** * Request to sign in with email. */ interface Schema$IdentitytoolkitRelyingpartyEmailLinkSigninRequest { /** * The email address of the user. */ email?: string; /** * Token for linking flow. */ idToken?: string; /** * The confirmation code. */ oobCode?: string; } /** * Request to get the account information. */ interface Schema$IdentitytoolkitRelyingpartyGetAccountInfoRequest { /** * GCP project number of the requesting delegated app. Currently only * intended for Firebase V1 migration. */ delegatedProjectNumber?: string; /** * The list of emails of the users to inquiry. */ email?: string[]; /** * The GITKit token of the authenticated user. */ idToken?: string; /** * The list of local ID&#39;s of the users to inquiry. */ localId?: string[]; /** * Privileged caller can query users by specified phone number. */ phoneNumber?: string[]; } /** * Response of getting the project configuration. */ interface Schema$IdentitytoolkitRelyingpartyGetProjectConfigResponse { /** * Whether to allow password user sign in or sign up. */ allowPasswordUser?: boolean; /** * Browser API key, needed when making http request to Apiary. */ apiKey?: string; /** * Authorized domains. */ authorizedDomains?: string[]; /** * Change email template. */ changeEmailTemplate?: Schema$EmailTemplate; dynamicLinksDomain?: string; /** * Whether anonymous user is enabled. */ enableAnonymousUser?: boolean; /** * OAuth2 provider configuration. */ idpConfig?: Schema$IdpConfig[]; /** * Legacy reset password email template. */ legacyResetPasswordTemplate?: Schema$EmailTemplate; /** * Project ID of the relying party. */ projectId?: string; /** * Reset password email template. */ resetPasswordTemplate?: Schema$EmailTemplate; /** * Whether to use email sending provided by Firebear. */ useEmailSending?: boolean; /** * Verify email template. */ verifyEmailTemplate?: Schema$EmailTemplate; } /** * Respone of getting public keys. */ interface Schema$IdentitytoolkitRelyingpartyGetPublicKeysResponse { } /** * Request to reset the password. */ interface Schema$IdentitytoolkitRelyingpartyResetPasswordRequest { /** * The email address of the user. */ email?: string; /** * The new password inputted by the user. */ newPassword?: string; /** * The old password inputted by the user. */ oldPassword?: string; /** * The confirmation code. */ oobCode?: string; } /** * Request for Identitytoolkit-SendVerificationCode */ interface Schema$IdentitytoolkitRelyingpartySendVerificationCodeRequest { /** * Receipt of successful app token validation with APNS. */ iosReceipt?: string; /** * Secret delivered to iOS app via APNS. */ iosSecret?: string; /** * The phone number to send the verification code to in E.164 format. */ phoneNumber?: string; /** * Recaptcha solution. */ recaptchaToken?: string; } /** * Response for Identitytoolkit-SendVerificationCode */ interface Schema$IdentitytoolkitRelyingpartySendVerificationCodeResponse { /** * Encrypted session information */ sessionInfo?: string; } /** * Request to set the account information. */ interface Schema$IdentitytoolkitRelyingpartySetAccountInfoRequest { /** * The captcha challenge. */ captchaChallenge?: string; /** * Response to the captcha. */ captchaResponse?: string; /** * The timestamp when the account is created. */ createdAt?: string; /** * The custom attributes to be set in the user&#39;s id token. */ customAttributes?: string; /** * GCP project number of the requesting delegated app. Currently only * intended for Firebase V1 migration. */ delegatedProjectNumber?: string; /** * The attributes users request to delete. */ deleteAttribute?: string[]; /** * The IDPs the user request to delete. */ deleteProvider?: string[]; /** * Whether to disable the user. */ disableUser?: boolean; /** * The name of the user. */ displayName?: string; /** * The email of the user. */ email?: string; /** * Mark the email as verified or not. */ emailVerified?: boolean; /** * The GITKit token of the authenticated user. */ idToken?: string; /** * Instance id token of the app. */ instanceId?: string; /** * Last login timestamp. */ lastLoginAt?: string; /** * The local ID of the user. */ localId?: string; /** * The out-of-band code of the change email request. */ oobCode?: string; /** * The new password of the user. */ password?: string; /** * Privileged caller can update user with specified phone number. */ phoneNumber?: string; /** * The photo url of the user. */ photoUrl?: string; /** * The associated IDPs of the user. */ provider?: string[]; /** * Whether return sts id token and refresh token instead of gitkit token. */ returnSecureToken?: boolean; /** * Mark the user to upgrade to federated login. */ upgradeToFederatedLogin?: boolean; /** * Timestamp in seconds for valid login token. */ validSince?: string; } /** * Request to set the project configuration. */ interface Schema$IdentitytoolkitRelyingpartySetProjectConfigRequest { /** * Whether to allow password user sign in or sign up. */ allowPasswordUser?: boolean; /** * Browser API key, needed when making http request to Apiary. */ apiKey?: string; /** * Authorized domains for widget redirect. */ authorizedDomains?: string[]; /** * Change email template. */ changeEmailTemplate?: Schema$EmailTemplate; /** * GCP project number of the requesting delegated app. Currently only * intended for Firebase V1 migration. */ delegatedProjectNumber?: string; /** * Whether to enable anonymous user. */ enableAnonymousUser?: boolean; /** * Oauth2 provider configuration. */ idpConfig?: Schema$IdpConfig[]; /** * Legacy reset password email template. */ legacyResetPasswordTemplate?: Schema$EmailTemplate; /** * Reset password email template. */ resetPasswordTemplate?: Schema$EmailTemplate; /** * Whether to use email sending provided by Firebear. */ useEmailSending?: boolean; /** * Verify email template. */ verifyEmailTemplate?: Schema$EmailTemplate; } /** * Response of setting the project configuration. */ interface Schema$IdentitytoolkitRelyingpartySetProjectConfigResponse { /** * Project ID of the relying party. */ projectId?: string; } /** * Request to sign out user. */ interface Schema$IdentitytoolkitRelyingpartySignOutUserRequest { /** * Instance id token of the app. */ instanceId?: string; /** * The local ID of the user. */ localId?: string; } /** * Response of signing out user. */ interface Schema$IdentitytoolkitRelyingpartySignOutUserResponse { /** * The local ID of the user. */ localId?: string; } /** * Request to signup new user, create anonymous user or anonymous user reauth. */ interface Schema$IdentitytoolkitRelyingpartySignupNewUserRequest { /** * The captcha challenge. */ captchaChallenge?: string; /** * Response to the captcha. */ captchaResponse?: string; /** * Whether to disable the user. Only can be used by service account. */ disabled?: boolean; /** * The name of the user. */ displayName?: string; /** * The email of the user. */ email?: string; /** * Mark the email as verified or not. Only can be used by service account. */ emailVerified?: boolean; /** * The GITKit token of the authenticated user. */ idToken?: string; /** * Instance id token of the app. */ instanceId?: string; /** * Privileged caller can create user with specified user id. */ localId?: string; /** * The new password of the user. */ password?: string; /** * Privileged caller can create user with specified phone number. */ phoneNumber?: string; /** * The photo url of the user. */ photoUrl?: string; /** * For multi-tenant use cases, in order to construct sign-in URL with the * correct IDP parameters, Firebear needs to know which Tenant to retrieve * IDP configs from. */ tenantId?: string; /** * Tenant project number to be used for idp discovery. */ tenantProjectNumber?: string; } /** * Request to upload user account in batch. */ interface Schema$IdentitytoolkitRelyingpartyUploadAccountRequest { /** * Whether allow overwrite existing account when user local_id exists. */ allowOverwrite?: boolean; blockSize?: number; /** * The following 4 fields are for standard scrypt algorithm. */ cpuMemCost?: number; /** * GCP project number of the requesting delegated app. Currently only * intended for Firebase V1 migration. */ delegatedProjectNumber?: string; dkLen?: number; /** * The password hash algorithm. */ hashAlgorithm?: string; /** * Memory cost for hash calculation. Used by scrypt similar algorithms. */ memoryCost?: number; parallelization?: number; /** * Rounds for hash calculation. Used by scrypt and similar algorithms. */ rounds?: number; /** * The salt separator. */ saltSeparator?: string; /** * If true, backend will do sanity check(including duplicate email and * federated id) when uploading account. */ sanityCheck?: boolean; /** * The key for to hash the password. */ signerKey?: string; /** * Specify which project (field value is actually project id) to operate. * Only used when provided credential. */ targetProjectId?: string; /** * The account info to be stored. */ users?: Schema$UserInfo[]; } /** * Request to verify the IDP assertion. */ interface Schema$IdentitytoolkitRelyingpartyVerifyAssertionRequest { /** * When it&#39;s true, automatically creates a new account if the user * doesn&#39;t exist. When it&#39;s false, allows existing user to sign in * normally and throws exception if the user doesn&#39;t exist. */ autoCreate?: boolean; /** * GCP project number of the requesting delegated app. Currently only * intended for Firebase V1 migration. */ delegatedProjectNumber?: string; /** * The GITKit token of the authenticated user. */ idToken?: string; /** * Instance id token of the app. */ instanceId?: string; /** * The GITKit token for the non-trusted IDP pending to be confirmed by the * user. */ pendingIdToken?: string; /** * The post body if the request is a HTTP POST. */ postBody?: string; /** * The URI to which the IDP redirects the user back. It may contain * federated login result params added by the IDP. */ requestUri?: string; /** * Whether return 200 and IDP credential rather than throw exception when * federated id is already linked. */ returnIdpCredential?: boolean; /** * Whether to return refresh tokens. */ returnRefreshToken?: boolean; /** * Whether return sts id token and refresh token instead of gitkit token. */ returnSecureToken?: boolean; /** * Session ID, which should match the one in previous createAuthUri request. */ sessionId?: string; /** * For multi-tenant use cases, in order to construct sign-in URL with the * correct IDP parameters, Firebear needs to know which Tenant to retrieve * IDP configs from. */ tenantId?: string; /** * Tenant project number to be used for idp discovery. */ tenantProjectNumber?: string; } /** * Request to verify a custom token */ interface Schema$IdentitytoolkitRelyingpartyVerifyCustomTokenRequest { /** * GCP project number of the requesting delegated app. Currently only * intended for Firebase V1 migration. */ delegatedProjectNumber?: string; /** * Instance id token of the app. */ instanceId?: string; /** * Whether return sts id token and refresh token instead of gitkit token. */ returnSecureToken?: boolean; /** * The custom token to verify */ token?: string; } /** * Request to verify the password. */ interface Schema$IdentitytoolkitRelyingpartyVerifyPasswordRequest { /** * The captcha challenge. */ captchaChallenge?: string; /** * Response to the captcha. */ captchaResponse?: string; /** * GCP project number of the requesting delegated app. Currently only * intended for Firebase V1 migration. */ delegatedProjectNumber?: string; /** * The email of the user. */ email?: string; /** * The GITKit token of the authenticated user. */ idToken?: string; /** * Instance id token of the app. */ instanceId?: string; /** * The password inputed by the user. */ password?: string; /** * The GITKit token for the non-trusted IDP, which is to be confirmed by the * user. */ pendingIdToken?: string; /** * Whether return sts id token and refresh token instead of gitkit token. */ returnSecureToken?: boolean; /** * For multi-tenant use cases, in order to construct sign-in URL with the * correct IDP parameters, Firebear needs to know which Tenant to retrieve * IDP configs from. */ tenantId?: string; /** * Tenant project number to be used for idp discovery. */ tenantProjectNumber?: string; } /** * Request for Identitytoolkit-VerifyPhoneNumber */ interface Schema$IdentitytoolkitRelyingpartyVerifyPhoneNumberRequest { code?: string; idToken?: string; operation?: string; phoneNumber?: string; /** * The session info previously returned by * IdentityToolkit-SendVerificationCode. */ sessionInfo?: string; temporaryProof?: string; verificationProof?: string; } /** * Response for Identitytoolkit-VerifyPhoneNumber */ interface Schema$IdentitytoolkitRelyingpartyVerifyPhoneNumberResponse { expiresIn?: string; idToken?: string; isNewUser?: boolean; localId?: string; phoneNumber?: string; refreshToken?: string; temporaryProof?: string; temporaryProofExpiresIn?: string; verificationProof?: string; verificationProofExpiresIn?: string; } /** * Template for a single idp configuration. */ interface Schema$IdpConfig { /** * OAuth2 client ID. */ clientId?: string; /** * Whether this IDP is enabled. */ enabled?: boolean; /** * Percent of users who will be prompted/redirected federated login for this * IDP. */ experimentPercent?: number; /** * OAuth2 provider. */ provider?: string; /** * OAuth2 client secret. */ secret?: string; /** * Whitelisted client IDs for audience check. */ whitelistedAudiences?: string[]; } /** * Request of getting a code for user confirmation (reset password, change * email etc.) */ interface Schema$Relyingparty { /** * whether or not to install the android app on the device where the link is * opened */ androidInstallApp?: boolean; /** * minimum version of the app. if the version on the device is lower than * this version then the user is taken to the play store to upgrade the app */ androidMinimumVersion?: string; /** * android package name of the android app to handle the action code */ androidPackageName?: string; /** * whether or not the app can handle the oob code without first going to web */ canHandleCodeInApp?: boolean; /** * The recaptcha response from the user. */ captchaResp?: string; /** * The recaptcha challenge presented to the user. */ challenge?: string; /** * The url to continue to the Gitkit app */ continueUrl?: string; /** * The email of the user. */ email?: string; /** * The user&#39;s Gitkit login token for email change. */ idToken?: string; /** * iOS app store id to download the app if it&#39;s not already installed */ iOSAppStoreId?: string; /** * the iOS bundle id of iOS app to handle the action code */ iOSBundleId?: string; /** * The fixed string &quot;identitytoolkit#relyingparty&quot;. */ kind?: string; /** * The new email if the code is for email change. */ newEmail?: string; /** * The request type. */ requestType?: string; /** * The IP address of the user. */ userIp?: string; } /** * Response of resetting the password. */ interface Schema$ResetPasswordResponse { /** * The user&#39;s email. If the out-of-band code is for email recovery, the * user&#39;s original email. */ email?: string; /** * The fixed string &quot;identitytoolkit#ResetPasswordResponse&quot;. */ kind?: string; /** * If the out-of-band code is for email recovery, the user&#39;s new email. */ newEmail?: string; /** * The request type. */ requestType?: string; } /** * Respone of setting the account information. */ interface Schema$SetAccountInfoResponse { /** * The name of the user. */ displayName?: string; /** * The email of the user. */ email?: string; /** * If email has been verified. */ emailVerified?: boolean; /** * If idToken is STS id token, then this field will be expiration time of * STS id token in seconds. */ expiresIn?: string; /** * The Gitkit id token to login the newly sign up user. */ idToken?: string; /** * The fixed string &quot;identitytoolkit#SetAccountInfoResponse&quot;. */ kind?: string; /** * The local ID of the user. */ localId?: string; /** * The new email the user attempts to change to. */ newEmail?: string; /** * The user&#39;s hashed password. */ passwordHash?: string; /** * The photo url of the user. */ photoUrl?: string; /** * The user&#39;s profiles at the associated IdPs. */ providerUserInfo?: Array<{ displayName?: string; federatedId?: string; photoUrl?: string; providerId?: string; }>; /** * If idToken is STS id token, then this field will be refresh token. */ refreshToken?: string; } /** * Response of signing up new user, creating anonymous user or anonymous user * reauth. */ interface Schema$SignupNewUserResponse { /** * The name of the user. */ displayName?: string; /** * The email of the user. */ email?: string; /** * If idToken is STS id token, then this field will be expiration time of * STS id token in seconds. */ expiresIn?: string; /** * The Gitkit id token to login the newly sign up user. */ idToken?: string; /** * The fixed string &quot;identitytoolkit#SignupNewUserResponse&quot;. */ kind?: string; /** * The RP local ID of the user. */ localId?: string; /** * If idToken is STS id token, then this field will be refresh token. */ refreshToken?: string; } /** * Respone of uploading accounts in batch. */ interface Schema$UploadAccountResponse { /** * The error encountered while processing the account info. */ error?: Array<{ index?: number; message?: string; }>; /** * The fixed string &quot;identitytoolkit#UploadAccountResponse&quot;. */ kind?: string; } /** * Template for an individual account info. */ interface Schema$UserInfo { /** * User creation timestamp. */ createdAt?: string; /** * The custom attributes to be set in the user&#39;s id token. */ customAttributes?: string; /** * Whether the user is authenticated by the developer. */ customAuth?: boolean; /** * Whether the user is disabled. */ disabled?: boolean; /** * The name of the user. */ displayName?: string; /** * The email of the user. */ email?: string; /** * Whether the email has been verified. */ emailVerified?: boolean; /** * last login timestamp. */ lastLoginAt?: string; /** * The local ID of the user. */ localId?: string; /** * The user&#39;s hashed password. */ passwordHash?: string; /** * The timestamp when the password was last updated. */ passwordUpdatedAt?: number; /** * User&#39;s phone number. */ phoneNumber?: string; /** * The URL of the user profile photo. */ photoUrl?: string; /** * The IDP of the user. */ providerUserInfo?: Array<{ displayName?: string; email?: string; federatedId?: string; phoneNumber?: string; photoUrl?: string; providerId?: string; rawId?: string; screenName?: string; }>; /** * The user&#39;s plain text password. */ rawPassword?: string; /** * The user&#39;s password salt. */ salt?: string; /** * User&#39;s screen name at Twitter or login name at Github. */ screenName?: string; /** * Timestamp in seconds for valid login token. */ validSince?: string; /** * Version of the user&#39;s password. */ version?: number; } /** * Response of verifying the IDP assertion. */ interface Schema$VerifyAssertionResponse { /** * The action code. */ action?: string; /** * URL for OTA app installation. */ appInstallationUrl?: string; /** * The custom scheme used by mobile app. */ appScheme?: string; /** * The opaque value used by the client to maintain context info between the * authentication request and the IDP callback. */ context?: string; /** * The birth date of the IdP account. */ dateOfBirth?: string; /** * The display name of the user. */ displayName?: string; /** * The email returned by the IdP. NOTE: The federated login user may not own * the email. */ email?: string; /** * It&#39;s true if the email is recycled. */ emailRecycled?: boolean; /** * The value is true if the IDP is also the email provider. It means the * user owns the email. */ emailVerified?: boolean; /** * Client error code. */ errorMessage?: string; /** * If idToken is STS id token, then this field will be expiration time of * STS id token in seconds. */ expiresIn?: string; /** * The unique ID identifies the IdP account. */ federatedId?: string; /** * The first name of the user. */ firstName?: string; /** * The full name of the user. */ fullName?: string; /** * The ID token. */ idToken?: string; /** * It&#39;s the identifier param in the createAuthUri request if the * identifier is an email. It can be used to check whether the user input * email is different from the asserted email. */ inputEmail?: string; /** * True if it&#39;s a new user sign-in, false if it&#39;s a returning user. */ isNewUser?: boolean; /** * The fixed string &quot;identitytoolkit#VerifyAssertionResponse&quot;. */ kind?: string; /** * The language preference of the user. */ language?: string; /** * The last name of the user. */ lastName?: string; /** * The RP local ID if it&#39;s already been mapped to the IdP account * identified by the federated ID. */ localId?: string; /** * Whether the assertion is from a non-trusted IDP and need account linking * confirmation. */ needConfirmation?: boolean; /** * Whether need client to supply email to complete the federated login flow. */ needEmail?: boolean; /** * The nick name of the user. */ nickName?: string; /** * The OAuth2 access token. */ oauthAccessToken?: string; /** * The OAuth2 authorization code. */ oauthAuthorizationCode?: string; /** * The lifetime in seconds of the OAuth2 access token. */ oauthExpireIn?: number; /** * The OIDC id token. */ oauthIdToken?: string; /** * The user approved request token for the OpenID OAuth extension. */ oauthRequestToken?: string; /** * The scope for the OpenID OAuth extension. */ oauthScope?: string; /** * The OAuth1 access token secret. */ oauthTokenSecret?: string; /** * The original email stored in the mapping storage. It&#39;s returned when * the federated ID is associated to a different email. */ originalEmail?: string; /** * The URI of the public accessible profiel picture. */ photoUrl?: string; /** * The IdP ID. For white listed IdPs it&#39;s a short domain name e.g. * google.com, aol.com, live.net and yahoo.com. If the * &quot;providerId&quot; param is set to OpenID OP identifer other than the * whilte listed IdPs the OP identifier is returned. If the * &quot;identifier&quot; param is federated ID in the createAuthUri * request. The domain part of the federated ID is returned. */ providerId?: string; /** * Raw IDP-returned user info. */ rawUserInfo?: string; /** * If idToken is STS id token, then this field will be refresh token. */ refreshToken?: string; /** * The screen_name of a Twitter user or the login name at Github. */ screenName?: string; /** * The timezone of the user. */ timeZone?: string; /** * When action is &#39;map&#39;, contains the idps which can be used for * confirmation. */ verifiedProvider?: string[]; } /** * Response from verifying a custom token */ interface Schema$VerifyCustomTokenResponse { /** * If idToken is STS id token, then this field will be expiration time of * STS id token in seconds. */ expiresIn?: string; /** * The GITKit token for authenticated user. */ idToken?: string; /** * True if it&#39;s a new user sign-in, false if it&#39;s a returning user. */ isNewUser?: boolean; /** * The fixed string &quot;identitytoolkit#VerifyCustomTokenResponse&quot;. */ kind?: string; /** * If idToken is STS id token, then this field will be refresh token. */ refreshToken?: string; } /** * Request of verifying the password. */ interface Schema$VerifyPasswordResponse { /** * The name of the user. */ displayName?: string; /** * The email returned by the IdP. NOTE: The federated login user may not own * the email. */ email?: string; /** * If idToken is STS id token, then this field will be expiration time of * STS id token in seconds. */ expiresIn?: string; /** * The GITKit token for authenticated user. */ idToken?: string; /** * The fixed string &quot;identitytoolkit#VerifyPasswordResponse&quot;. */ kind?: string; /** * The RP local ID if it&#39;s already been mapped to the IdP account * identified by the federated ID. */ localId?: string; /** * The OAuth2 access token. */ oauthAccessToken?: string; /** * The OAuth2 authorization code. */ oauthAuthorizationCode?: string; /** * The lifetime in seconds of the OAuth2 access token. */ oauthExpireIn?: number; /** * The URI of the user&#39;s photo at IdP */ photoUrl?: string; /** * If idToken is STS id token, then this field will be refresh token. */ refreshToken?: string; /** * Whether the email is registered. */ registered?: boolean; } class Resource$Relyingparty { context: APIRequestContext; constructor(context: APIRequestContext); /** * identitytoolkit.relyingparty.createAuthUri * @desc Creates the URI used by the IdP to authenticate the user. * @alias identitytoolkit.relyingparty.createAuthUri * @memberOf! () * * @param {object} params Parameters for request * @param {().IdentitytoolkitRelyingpartyCreateAuthUriRequest} params.resource Request body data * @param {object} [options] Optionally override request options, such as `url`, `method`, and `encoding`. * @param {callback} callback The callback that handles the response. * @return {object} Request object */ createAuthUri(params?: Params$Resource$Relyingparty$Createauthuri, options?: MethodOptions): GaxiosPromise<Schema$CreateAuthUriResponse>; createAuthUri(params: Params$Resource$Relyingparty$Createauthuri, options: MethodOptions | BodyResponseCallback<Schema$CreateAuthUriResponse>, callback: BodyResponseCallback<Schema$CreateAuthUriResponse>): void; createAuthUri(params: Params$Resource$Relyingparty$Createauthuri, callback: BodyResponseCallback<Schema$CreateAuthUriResponse>): void; createAuthUri(callback: BodyResponseCallback<Schema$CreateAuthUriResponse>): void; /** * identitytoolkit.relyingparty.deleteAccount * @desc Delete user account. * @alias identitytoolkit.relyingparty.deleteAccount * @memberOf! () * * @param {object} params Parameters for request * @param {().IdentitytoolkitRelyingpartyDeleteAccountRequest} params.resource Request body data * @param {object} [options] Optionally override request options, such as `url`, `method`, and `encoding`. * @param {callback} callback The callback that handles the response. * @return {object} Request object */ deleteAccount(params?: Params$Resource$Relyingparty$Deleteaccount, options?: MethodOptions): GaxiosPromise<Schema$DeleteAccountResponse>; deleteAccount(params: Params$Resource$Relyingparty$Deleteaccount, options: MethodOptions | BodyResponseCallback<Schema$DeleteAccountResponse>, callback: BodyResponseCallback<Schema$DeleteAccountResponse>): void; deleteAccount(params: Params$Resource$Relyingparty$Deleteaccount, callback: BodyResponseCallback<Schema$DeleteAccountResponse>): void; deleteAccount(callback: BodyResponseCallback<Schema$DeleteAccountResponse>): void; /** * identitytoolkit.relyingparty.downloadAccount * @desc Batch download user accounts. * @alias identitytoolkit.relyingparty.downloadAccount * @memberOf! () * * @param {object} params Parameters for request * @param {().IdentitytoolkitRelyingpartyDownloadAccountRequest} params.resource Request body data * @param {object} [options] Optionally override request options, such as `url`, `method`, and `encoding`. * @param {callback} callback The callback that handles the response. * @return {object} Request object */ downloadAccount(params?: Params$Resource$Relyingparty$Downloadaccount, options?: MethodOptions): GaxiosPromise<Schema$DownloadAccountResponse>; downloadAccount(params: Params$Resource$Relyingparty$Downloadaccount, options: MethodOptions | BodyResponseCallback<Schema$DownloadAccountResponse>, callback: BodyResponseCallback<Schema$DownloadAccountResponse>): void; downloadAccount(params: Params$Resource$Relyingparty$Downloadaccount, callback: BodyResponseCallback<Schema$DownloadAccountResponse>): void; downloadAccount(callback: BodyResponseCallback<Schema$DownloadAccountResponse>): void; /** * identitytoolkit.relyingparty.emailLinkSignin * @desc Reset password for a user. * @alias identitytoolkit.relyingparty.emailLinkSignin * @memberOf! () * * @param {object} params Parameters for request * @param {().IdentitytoolkitRelyingpartyEmailLinkSigninRequest} params.resource Request body data * @param {object} [options] Optionally override request options, such as `url`, `method`, and `encoding`. * @param {callback} callback The callback that handles the response. * @return {object} Request object */ emailLinkSignin(params?: Params$Resource$Relyingparty$Emaillinksignin, options?: MethodOptions): GaxiosPromise<Schema$EmailLinkSigninResponse>; emailLinkSignin(params: Params$Resource$Relyingparty$Emaillinksignin, options: MethodOptions | BodyResponseCallback<Schema$EmailLinkSigninResponse>, callback: BodyResponseCallback<Schema$EmailLinkSigninResponse>): void; emailLinkSignin(params: Params$Resource$Relyingparty$Emaillinksignin, callback: BodyResponseCallback<Schema$EmailLinkSigninResponse>): void; emailLinkSignin(callback: BodyResponseCallback<Schema$EmailLinkSigninResponse>): void; /** * identitytoolkit.relyingparty.getAccountInfo * @desc Returns the account info. * @alias identitytoolkit.relyingparty.getAccountInfo * @memberOf! () * * @param {object} params Parameters for request * @param {().IdentitytoolkitRelyingpartyGetAccountInfoRequest} params.resource Request body data * @param {object} [options] Optionally override request options, such as `url`, `method`, and `encoding`. * @param {callback} callback The callback that handles the response. * @return {object} Request object */ getAccountInfo(params?: Params$Resource$Relyingparty$Getaccountinfo, options?: MethodOptions): GaxiosPromise<Schema$GetAccountInfoResponse>; getAccountInfo(params: Params$Resource$Relyingparty$Getaccountinfo, options: MethodOptions | BodyResponseCallback<Schema$GetAccountInfoResponse>, callback: BodyResponseCallback<Schema$GetAccountInfoResponse>): void; getAccountInfo(params: Params$Resource$Relyingparty$Getaccountinfo, callback: BodyResponseCallback<Schema$GetAccountInfoResponse>): void; getAccountInfo(callback: BodyResponseCallback<Schema$GetAccountInfoResponse>): void; /** * identitytoolkit.relyingparty.getOobConfirmationCode * @desc Get a code for user action confirmation. * @alias identitytoolkit.relyingparty.getOobConfirmationCode * @memberOf! () * * @param {object} params Parameters for request * @param {().Relyingparty} params.resource Request body data * @param {object} [options] Optionally override request options, such as `url`, `method`, and `encoding`. * @param {callback} callback The callback that handles the response. * @return {object} Request object */ getOobConfirmationCode(params?: Params$Resource$Relyingparty$Getoobconfirmationcode, options?: MethodOptions): GaxiosPromise<Schema$GetOobConfirmationCodeResponse>; getOobConfirmationCode(params: Params$Resource$Relyingparty$Getoobconfirmationcode, options: MethodOptions | BodyResponseCallback<Schema$GetOobConfirmationCodeResponse>, callback: BodyResponseCallback<Schema$GetOobConfirmationCodeResponse>): void; getOobConfirmationCode(params: Params$Resource$Relyingparty$Getoobconfirmationcode, callback: BodyResponseCallback<Schema$GetOobConfirmationCodeResponse>): void; getOobConfirmationCode(callback: BodyResponseCallback<Schema$GetOobConfirmationCodeResponse>): void; /** * identitytoolkit.relyingparty.getProjectConfig * @desc Get project configuration. * @alias identitytoolkit.relyingparty.getProjectConfig * @memberOf! () * * @param {object=} params Parameters for request * @param {string=} params.delegatedProjectNumber Delegated GCP project number of the request. * @param {string=} params.projectNumber GCP project number of the request. * @param {object} [options] Optionally override request options, such as `url`, `method`, and `encoding`. * @param {callback} callback The callback that handles the response. * @return {object} Request object */ getProjectConfig(params?: Params$Resource$Relyingparty$Getprojectconfig, options?: MethodOptions): GaxiosPromise<Schema$IdentitytoolkitRelyingpartyGetProjectConfigResponse>; getProjectConfig(params: Params$Resource$Relyingparty$Getprojectconfig, options: MethodOptions | BodyResponseCallback<Schema$IdentitytoolkitRelyingpartyGetProjectConfigResponse>, callback: BodyResponseCallback<Schema$IdentitytoolkitRelyingpartyGetProjectConfigResponse>): void; getProjectConfig(params: Params$Resource$Relyingparty$Getprojectconfig, callback: BodyResponseCallback<Schema$IdentitytoolkitRelyingpartyGetProjectConfigResponse>): void; getProjectConfig(callback: BodyResponseCallback<Schema$IdentitytoolkitRelyingpartyGetProjectConfigResponse>): void; /** * identitytoolkit.relyingparty.getPublicKeys * @desc Get token signing public key. * @alias identitytoolkit.relyingparty.getPublicKeys * @memberOf! () * * @param {object=} params Parameters for request * @param {object} [options] Optionally override request options, such as `url`, `method`, and `encoding`. * @param {callback} callback The callback that handles the response. * @return {object} Request object */ getPublicKeys(params?: Params$Resource$Relyingparty$Getpublickeys, options?: MethodOptions): GaxiosPromise<Schema$IdentitytoolkitRelyingpartyGetPublicKeysResponse>; getPublicKeys(params: Params$Resource$Relyingparty$Getpublickeys, options: MethodOptions | BodyResponseCallback<Schema$IdentitytoolkitRelyingpartyGetPublicKeysResponse>, callback: BodyResponseCallback<Schema$IdentitytoolkitRelyingpartyGetPublicKeysResponse>): void; getPublicKeys(params: Params$Resource$Relyingparty$Getpublickeys, callback: BodyResponseCallback<Schema$IdentitytoolkitRelyingpartyGetPublicKeysResponse>): void; getPublicKeys(callback: BodyResponseCallback<Schema$IdentitytoolkitRelyingpartyGetPublicKeysResponse>): void; /** * identitytoolkit.relyingparty.getRecaptchaParam * @desc Get recaptcha secure param. * @alias identitytoolkit.relyingparty.getRecaptchaParam * @memberOf! () * * @param {object=} params Parameters for request * @param {object} [options] Optionally override request options, such as `url`, `method`, and `encoding`. * @param {callback} callback The callback that handles the response. * @return {object} Request object */ getRecaptchaParam(params?: Params$Resource$Relyingparty$Getrecaptchaparam, options?: MethodOptions): GaxiosPromise<Schema$GetRecaptchaParamResponse>; getRecaptchaParam(params: Params$Resource$Relyingparty$Getrecaptchaparam, options: MethodOptions | BodyResponseCallback<Schema$GetRecaptchaParamResponse>, callback: BodyResponseCallback<Schema$GetRecaptchaParamResponse>): void; getRecaptchaParam(params: Params$Resource$Relyingparty$Getrecaptchaparam, callback: BodyResponseCallback<Schema$GetRecaptchaParamResponse>): void; getRecaptchaParam(callback: BodyResponseCallback<Schema$GetRecaptchaParamResponse>): void; /** * identitytoolkit.relyingparty.resetPassword * @desc Reset password for a user. * @alias identitytoolkit.relyingparty.resetPassword * @memberOf! () * * @param {object} params Parameters for request * @param {().IdentitytoolkitRelyingpartyResetPasswordRequest} params.resource Request body data * @param {object} [options] Optionally override request options, such as `url`, `method`, and `encoding`. * @param {callback} callback The callback that handles the response. * @return {object} Request object */ resetPassword(params?: Params$Resource$Relyingparty$Resetpassword, options?: MethodOptions): GaxiosPromise<Schema$ResetPasswordResponse>; resetPassword(params: Params$Resource$Relyingparty$Resetpassword, options: MethodOptions | BodyResponseCallback<Schema$ResetPasswordResponse>, callback: BodyResponseCallback<Schema$ResetPasswordResponse>): void; resetPassword(params: Params$Resource$Relyingparty$Resetpassword, callback: BodyResponseCallback<Schema$ResetPasswordResponse>): void; resetPassword(callback: BodyResponseCallback<Schema$ResetPasswordResponse>): void; /** * identitytoolkit.relyingparty.sendVerificationCode * @desc Send SMS verification code. * @alias identitytoolkit.relyingparty.sendVerificationCode * @memberOf! () * * @param {object} params Parameters for request * @param {().IdentitytoolkitRelyingpartySendVerificationCodeRequest} params.resource Request body data * @param {object} [options] Optionally override request options, such as `url`, `method`, and `encoding`. * @param {callback} callback The callback that handles the response. * @return {object} Request object */ sendVerificationCode(params?: Params$Resource$Relyingparty$Sendverificationcode, options?: MethodOptions): GaxiosPromise<Schema$IdentitytoolkitRelyingpartySendVerificationCodeResponse>; sendVerificationCode(params: Params$Resource$Relyingparty$Sendverificationcode, options: MethodOptions | BodyResponseCallback<Schema$IdentitytoolkitRelyingpartySendVerificationCodeResponse>, callback: BodyResponseCallback<Schema$IdentitytoolkitRelyingpartySendVerificationCodeResponse>): void; sendVerificationCode(params: Params$Resource$Relyingparty$Sendverificationcode, callback: BodyResponseCallback<Schema$IdentitytoolkitRelyingpartySendVerificationCodeResponse>): void; sendVerificationCode(callback: BodyResponseCallback<Schema$IdentitytoolkitRelyingpartySendVerificationCodeResponse>): void; /** * identitytoolkit.relyingparty.setAccountInfo * @desc Set account info for a user. * @alias identitytoolkit.relyingparty.setAccountInfo * @memberOf! () * * @param {object} params Parameters for request * @param {().IdentitytoolkitRelyingpartySetAccountInfoRequest} params.resource Request body data * @param {object} [options] Optionally override request options, such as `url`, `method`, and `encoding`. * @param {callback} callback The callback that handles the response. * @return {object} Request object */ setAccountInfo(params?: Params$Resource$Relyingparty$Setaccountinfo, options?: MethodOptions): GaxiosPromise<Schema$SetAccountInfoResponse>; setAccountInfo(params: Params$Resource$Relyingparty$Setaccountinfo, options: MethodOptions | BodyResponseCallback<Schema$SetAccountInfoResponse>, callback: BodyResponseCallback<Schema$SetAccountInfoResponse>): void; setAccountInfo(params: Params$Resource$Relyingparty$Setaccountinfo, callback: BodyResponseCallback<Schema$SetAccountInfoResponse>): void; setAccountInfo(callback: BodyResponseCallback<Schema$SetAccountInfoResponse>): void; /** * identitytoolkit.relyingparty.setProjectConfig * @desc Set project configuration. * @alias identitytoolkit.relyingparty.setProjectConfig * @memberOf! () * * @param {object} params Parameters for request * @param {().IdentitytoolkitRelyingpartySetProjectConfigRequest} params.resource Request body data * @param {object} [options] Optionally override request options, such as `url`, `method`, and `encoding`. * @param {callback} callback The callback that handles the response. * @return {object} Request object */ setProjectConfig(params?: Params$Resource$Relyingparty$Setprojectconfig, options?: MethodOptions): GaxiosPromise<Schema$IdentitytoolkitRelyingpartySetProjectConfigResponse>; setProjectConfig(params: Params$Resource$Relyingparty$Setprojectconfig, options: MethodOptions | BodyResponseCallback<Schema$IdentitytoolkitRelyingpartySetProjectConfigResponse>, callback: BodyResponseCallback<Schema$IdentitytoolkitRelyingpartySetProjectConfigResponse>): void; setProjectConfig(params: Params$Resource$Relyingparty$Setprojectconfig, callback: BodyResponseCallback<Schema$IdentitytoolkitRelyingpartySetProjectConfigResponse>): void; setProjectConfig(callback: BodyResponseCallback<Schema$IdentitytoolkitRelyingpartySetProjectConfigResponse>): void; /** * identitytoolkit.relyingparty.signOutUser * @desc Sign out user. * @alias identitytoolkit.relyingparty.signOutUser * @memberOf! () * * @param {object} params Parameters for request * @param {().IdentitytoolkitRelyingpartySignOutUserRequest} params.resource Request body data * @param {object} [options] Optionally override request options, such as `url`, `method`, and `encoding`. * @param {callback} callback The callback that handles the response. * @return {object} Request object */ signOutUser(params?: Params$Resource$Relyingparty$Signoutuser, options?: MethodOptions): GaxiosPromise<Schema$IdentitytoolkitRelyingpartySignOutUserResponse>; signOutUser(params: Params$Resource$Relyingparty$Signoutuser, options: MethodOptions | BodyResponseCallback<Schema$IdentitytoolkitRelyingpartySignOutUserResponse>, callback: BodyResponseCallback<Schema$IdentitytoolkitRelyingpartySignOutUserResponse>): void; signOutUser(params: Params$Resource$Relyingparty$Signoutuser, callback: BodyResponseCallback<Schema$IdentitytoolkitRelyingpartySignOutUserResponse>): void; signOutUser(callback: BodyResponseCallback<Schema$IdentitytoolkitRelyingpartySignOutUserResponse>): void; /** * identitytoolkit.relyingparty.signupNewUser * @desc Signup new user. * @alias identitytoolkit.relyingparty.signupNewUser * @memberOf! () * * @param {object} params Parameters for request * @param {().IdentitytoolkitRelyingpartySignupNewUserRequest} params.resource Request body data * @param {object} [options] Optionally override request options, such as `url`, `method`, and `encoding`. * @param {callback} callback The callback that handles the response. * @return {object} Request object */ signupNewUser(params?: Params$Resource$Relyingparty$Signupnewuser, options?: MethodOptions): GaxiosPromise<Schema$SignupNewUserResponse>; signupNewUser(params: Params$Resource$Relyingparty$Signupnewuser, options: MethodOptions | BodyResponseCallback<Schema$SignupNewUserResponse>, callback: BodyResponseCallback<Schema$SignupNewUserResponse>): void; signupNewUser(params: Params$Resource$Relyingparty$Signupnewuser, callback: BodyResponseCallback<Schema$SignupNewUserResponse>): void; signupNewUser(callback: BodyResponseCallback<Schema$SignupNewUserResponse>): void; /** * identitytoolkit.relyingparty.uploadAccount * @desc Batch upload existing user accounts. * @alias identitytoolkit.relyingparty.uploadAccount * @memberOf! () * * @param {object} params Parameters for request * @param {().IdentitytoolkitRelyingpartyUploadAccountRequest} params.resource Request body data * @param {object} [options] Optionally override request options, such as `url`, `method`, and `encoding`. * @param {callback} callback The callback that handles the response. * @return {object} Request object */ uploadAccount(params?: Params$Resource$Relyingparty$Uploadaccount, options?: MethodOptions): GaxiosPromise<Schema$UploadAccountResponse>; uploadAccount(params: Params$Resource$Relyingparty$Uploadaccount, options: MethodOptions | BodyResponseCallback<Schema$UploadAccountResponse>, callback: BodyResponseCallback<Schema$UploadAccountResponse>): void; uploadAccount(params: Params$Resource$Relyingparty$Uploadaccount, callback: BodyResponseCallback<Schema$UploadAccountResponse>): void; uploadAccount(callback: BodyResponseCallback<Schema$UploadAccountResponse>): void; /** * identitytoolkit.relyingparty.verifyAssertion * @desc Verifies the assertion returned by the IdP. * @alias identitytoolkit.relyingparty.verifyAssertion * @memberOf! () * * @param {object} params Parameters for request * @param {().IdentitytoolkitRelyingpartyVerifyAssertionRequest} params.resource Request body data * @param {object} [options] Optionally override request options, such as `url`, `method`, and `encoding`. * @param {callback} callback The callback that handles the response. * @return {object} Request object */ verifyAssertion(params?: Params$Resource$Relyingparty$Verifyassertion, options?: MethodOptions): GaxiosPromise<Schema$VerifyAssertionResponse>; verifyAssertion(params: Params$Resource$Relyingparty$Verifyassertion, options: MethodOptions | BodyResponseCallback<Schema$VerifyAssertionResponse>, callback: BodyResponseCallback<Schema$VerifyAssertionResponse>): void; verifyAssertion(params: Params$Resource$Relyingparty$Verifyassertion, callback: BodyResponseCallback<Schema$VerifyAssertionResponse>): void; verifyAssertion(callback: BodyResponseCallback<Schema$VerifyAssertionResponse>): void; /** * identitytoolkit.relyingparty.verifyCustomToken * @desc Verifies the developer asserted ID token. * @alias identitytoolkit.relyingparty.verifyCustomToken * @memberOf! () * * @param {object} params Parameters for request * @param {().IdentitytoolkitRelyingpartyVerifyCustomTokenRequest} params.resource Request body data * @param {object} [options] Optionally override request options, such as `url`, `method`, and `encoding`. * @param {callback} callback The callback that handles the response. * @return {object} Request object */ verifyCustomToken(params?: Params$Resource$Relyingparty$Verifycustomtoken, options?: MethodOptions): GaxiosPromise<Schema$VerifyCustomTokenResponse>; verifyCustomToken(params: Params$Resource$Relyingparty$Verifycustomtoken, options: MethodOptions | BodyResponseCallback<Schema$VerifyCustomTokenResponse>, callback: BodyResponseCallback<Schema$VerifyCustomTokenResponse>): void; verifyCustomToken(params: Params$Resource$Relyingparty$Verifycustomtoken, callback: BodyResponseCallback<Schema$VerifyCustomTokenResponse>): void; verifyCustomToken(callback: BodyResponseCallback<Schema$VerifyCustomTokenResponse>): void; /** * identitytoolkit.relyingparty.verifyPassword * @desc Verifies the user entered password. * @alias identitytoolkit.relyingparty.verifyPassword * @memberOf! () * * @param {object} params Parameters for request * @param {().IdentitytoolkitRelyingpartyVerifyPasswordRequest} params.resource Request body data * @param {object} [options] Optionally override request options, such as `url`, `method`, and `encoding`. * @param {callback} callback The callback that handles the response. * @return {object} Request object */ verifyPassword(params?: Params$Resource$Relyingparty$Verifypassword, options?: MethodOptions): GaxiosPromise<Schema$VerifyPasswordResponse>; verifyPassword(params: Params$Resource$Relyingparty$Verifypassword, options: MethodOptions | BodyResponseCallback<Schema$VerifyPasswordResponse>, callback: BodyResponseCallback<Schema$VerifyPasswordResponse>): void; verifyPassword(params: Params$Resource$Relyingparty$Verifypassword, callback: BodyResponseCallback<Schema$VerifyPasswordResponse>): void; verifyPassword(callback: BodyResponseCallback<Schema$VerifyPasswordResponse>): void; /** * identitytoolkit.relyingparty.verifyPhoneNumber * @desc Verifies ownership of a phone number and creates/updates the user * account accordingly. * @alias identitytoolkit.relyingparty.verifyPhoneNumber * @memberOf! () * * @param {object} params Parameters for request * @param {().IdentitytoolkitRelyingpartyVerifyPhoneNumberRequest} params.resource Request body data * @param {object} [options] Optionally override request options, such as `url`, `method`, and `encoding`. * @param {callback} callback The callback that handles the response. * @return {object} Request object */ verifyPhoneNumber(params?: Params$Resource$Relyingparty$Verifyphonenumber, options?: MethodOptions): GaxiosPromise<Schema$IdentitytoolkitRelyingpartyVerifyPhoneNumberResponse>; verifyPhoneNumber(params: Params$Resource$Relyingparty$Verifyphonenumber, options: MethodOptions | BodyResponseCallback<Schema$IdentitytoolkitRelyingpartyVerifyPhoneNumberResponse>, callback: BodyResponseCallback<Schema$IdentitytoolkitRelyingpartyVerifyPhoneNumberResponse>): void; verifyPhoneNumber(params: Params$Resource$Relyingparty$Verifyphonenumber, callback: BodyResponseCallback<Schema$IdentitytoolkitRelyingpartyVerifyPhoneNumberResponse>): void; verifyPhoneNumber(callback: BodyResponseCallback<Schema$IdentitytoolkitRelyingpartyVerifyPhoneNumberResponse>): void; } interface Params$Resource$Relyingparty$Createauthuri extends StandardParameters { /** * Auth client or API Key for the request */ auth?: string | OAuth2Client | JWT | Compute | UserRefreshClient; /** * Request body metadata */ requestBody?: Schema$IdentitytoolkitRelyingpartyCreateAuthUriRequest; } interface Params$Resource$Relyingparty$Deleteaccount extends StandardParameters { /** * Auth client or API Key for the request */ auth?: string | OAuth2Client | JWT | Compute | UserRefreshClient; /** * Request body metadata */ requestBody?: Schema$IdentitytoolkitRelyingpartyDeleteAccountRequest; } interface Params$Resource$Relyingparty$Downloadaccount extends StandardParameters { /** * Auth client or API Key for the request */ auth?: string | OAuth2Client | JWT | Compute | UserRefreshClient; /** * Request body metadata */ requestBody?: Schema$IdentitytoolkitRelyingpartyDownloadAccountRequest; } interface Params$Resource$Relyingparty$Emaillinksignin extends StandardParameters { /** * Auth client or API Key for the request */ auth?: string | OAuth2Client | JWT | Compute | UserRefreshClient; /** * Request body metadata */ requestBody?: Schema$IdentitytoolkitRelyingpartyEmailLinkSigninRequest; } interface Params$Resource$Relyingparty$Getaccountinfo extends StandardParameters { /** * Auth client or API Key for the request */ auth?: string | OAuth2Client | JWT | Compute | UserRefreshClient; /** * Request body metadata */ requestBody?: Schema$IdentitytoolkitRelyingpartyGetAccountInfoRequest; } interface Params$Resource$Relyingparty$Getoobconfirmationcode extends StandardParameters { /** * Auth client or API Key for the request */ auth?: string | OAuth2Client | JWT | Compute | UserRefreshClient; /** * Request body metadata */ requestBody?: Schema$Relyingparty; } interface Params$Resource$Relyingparty$Getprojectconfig extends StandardParameters { /** * Auth client or API Key for the request */ auth?: string | OAuth2Client | JWT | Compute | UserRefreshClient; /** * Delegated GCP project number of the request. */ delegatedProjectNumber?: string; /** * GCP project number of the request. */ projectNumber?: string; } interface Params$Resource$Relyingparty$Getpublickeys extends StandardParameters { /** * Auth client or API Key for the request */ auth?: string | OAuth2Client | JWT | Compute | UserRefreshClient; } interface Params$Resource$Relyingparty$Getrecaptchaparam extends StandardParameters { /** * Auth client or API Key for the request */ auth?: string | OAuth2Client | JWT | Compute | UserRefreshClient; } interface Params$Resource$Relyingparty$Resetpassword extends StandardParameters { /** * Auth client or API Key for the request */ auth?: string | OAuth2Client | JWT | Compute | UserRefreshClient; /** * Request body metadata */ requestBody?: Schema$IdentitytoolkitRelyingpartyResetPasswordRequest; } interface Params$Resource$Relyingparty$Sendverificationcode extends StandardParameters { /** * Auth client or API Key for the request */ auth?: string | OAuth2Client | JWT | Compute | UserRefreshClient; /** * Request body metadata */ requestBody?: Schema$IdentitytoolkitRelyingpartySendVerificationCodeRequest; } interface Params$Resource$Relyingparty$Setaccountinfo extends StandardParameters { /** * Auth client or API Key for the request */ auth?: string | OAuth2Client | JWT | Compute | UserRefreshClient; /** * Request body metadata */ requestBody?: Schema$IdentitytoolkitRelyingpartySetAccountInfoRequest; } interface Params$Resource$Relyingparty$Setprojectconfig extends StandardParameters { /** * Auth client or API Key for the request */ auth?: string | OAuth2Client | JWT | Compute | UserRefreshClient; /** * Request body metadata */ requestBody?: Schema$IdentitytoolkitRelyingpartySetProjectConfigRequest; } interface Params$Resource$Relyingparty$Signoutuser extends StandardParameters { /** * Auth client or API Key for the request */ auth?: string | OAuth2Client | JWT | Compute | UserRefreshClient; /** * Request body metadata */ requestBody?: Schema$IdentitytoolkitRelyingpartySignOutUserRequest; } interface Params$Resource$Relyingparty$Signupnewuser extends StandardParameters { /** * Auth client or API Key for the request */ auth?: string | OAuth2Client | JWT | Compute | UserRefreshClient; /** * Request body metadata */ requestBody?: Schema$IdentitytoolkitRelyingpartySignupNewUserRequest; } interface Params$Resource$Relyingparty$Uploadaccount extends StandardParameters { /** * Auth client or API Key for the request */ auth?: string | OAuth2Client | JWT | Compute | UserRefreshClient; /** * Request body metadata */ requestBody?: Schema$IdentitytoolkitRelyingpartyUploadAccountRequest; } interface Params$Resource$Relyingparty$Verifyassertion extends StandardParameters { /** * Auth client or API Key for the request */ auth?: string | OAuth2Client | JWT | Compute | UserRefreshClient; /** * Request body metadata */ requestBody?: Schema$IdentitytoolkitRelyingpartyVerifyAssertionRequest; } interface Params$Resource$Relyingparty$Verifycustomtoken extends StandardParameters { /** * Auth client or API Key for the request */ auth?: string | OAuth2Client | JWT | Compute | UserRefreshClient; /** * Request body metadata */ requestBody?: Schema$IdentitytoolkitRelyingpartyVerifyCustomTokenRequest; } interface Params$Resource$Relyingparty$Verifypassword extends StandardParameters { /** * Auth client or API Key for the request */ auth?: string | OAuth2Client | JWT | Compute | UserRefreshClient; /** * Request body metadata */ requestBody?: Schema$IdentitytoolkitRelyingpartyVerifyPasswordRequest; } interface Params$Resource$Relyingparty$Verifyphonenumber extends StandardParameters { /** * Auth client or API Key for the request */ auth?: string | OAuth2Client | JWT | Compute | UserRefreshClient; /** * Request body metadata */ requestBody?: Schema$IdentitytoolkitRelyingpartyVerifyPhoneNumberRequest; } }
the_stack
import { action, observable, computed, isObservable, toJS, reaction, comparer, IReactionDisposer, override, makeObservable, } from "mobx"; import { Field, ProcessValue, ValidationMessage, ProcessOptions, errorMessage, } from "./form"; import { AnyFormState } from "./state"; import { FormAccessorBase } from "./form-accessor-base"; import { currentValidationProps } from "./validation-props"; import { ValidateOptions } from "./validate-options"; import { References, NoReferences, IReferences } from "./references"; import { pathToFieldref } from "./utils"; import { IAccessor, IAnyFormAccessor } from "./interfaces"; import { AccessorBase } from "./accessor-base"; import { isModelType, getType, getIdentifier, isStateTreeNode, } from "mobx-state-tree"; export class FieldAccessor<R, V> extends AccessorBase implements IAccessor { @observable _raw: R | undefined; @observable _value: V; @observable _originalValue: any; _disposer: IReactionDisposer | undefined; references: IReferences<any, any, any>; constructor( public state: AnyFormState, public field: Field<R, V>, parent: IAnyFormAccessor, public name: string ) { super(parent); makeObservable(this); this.createDerivedReaction(); this._value = state.getValue(this.path); this.setOriginalValue(); if (field.options && field.options.references) { const options = field.options.references; const dependentQuery = options.dependentQuery || (() => ({})); this.references = new References(options.source, () => dependentQuery(this) ); } else { this.references = new NoReferences(); } } @action setOriginalValue(): void { if (isStateTreeNode(this._value) && isModelType(getType(this._value))) { this._originalValue = getIdentifier(this._value); return; } this._originalValue = toJS(this._value); } @computed get path(): string { return ( (this.parent as FormAccessorBase<any, any, any>).path + "/" + this.name ); } dispose() { if (this.references.isEnabled()) { this.references.clearAutoLoadReaction(); } if (this._disposer == null) { return; } this._disposer(); } clear() { this.dispose(); } @override get fieldref(): string { return pathToFieldref(this.path); } @override get context(): any { return this.state.context; } @computed get isEmpty(): boolean { if (this.field.converter.emptyImpossible) { return false; } const raw = this.raw; const emptyRaw = this.field.converter.emptyRaw; if (Array.isArray(raw) && Array.isArray(emptyRaw)) { return raw.length === emptyRaw.length; } return raw === emptyRaw; } @computed get isEmptyAndRequired(): boolean { return this.isEmpty && this.required; } createDerivedReaction() { const derivedFunc = this.field.derivedFunc; if (derivedFunc == null) { return; } if (this._disposer != null) { return; } // XXX when we have a node that's undefined, we don't // try to do any work. This isn't ideal but can happen // if the path a node was pointing to has been removed. const disposer = reaction( () => { return this.node != null ? derivedFunc(this.node) : undefined; }, (derivedValue: any) => { if (derivedValue === undefined) { return; } this.setRaw( this.field.render( derivedValue, this.state.stateConverterOptionsWithContext(this) ) ); } ); this._disposer = disposer; } // XXX I think this should become private (_node), unless I // guarantee the type without a lot of complication @computed get node(): any { // XXX it's possible for this to be called for a node that has since // been removed. It's not ideal but we return undefined in such a case. try { return this.state.getValue( (this.parent as FormAccessorBase<any, any, any>).path ); } catch { return undefined; } } @computed get addMode(): boolean { if (this._raw !== undefined) { return false; } // field accessor overrides this to look at raw value return ( this._addMode || (this.parent as FormAccessorBase<any, any, any>).addMode ); } @computed get raw(): R { const result = this._raw; if (result !== undefined) { // this is an object reference. don't convert to JS if (isObservable(result) && !(result instanceof Array)) { return result as R; } // anything else, including arrays, convert to JS // XXX what if we have an array of object references? cross that // bridge when we support it return toJS(result) as R; } if (this.addMode) { return this.field.converter.emptyRaw; } return this.field.render( this.value, this.state.stateConverterOptionsWithContext(this) ); } @action setValue(value: V) { // if there are no changes, don't do anything if (comparer.structural(this._value, value)) { return; } this._value = value; this.state.setValueWithoutRawUpdate(this.path, value); // XXX maybe rename this to 'update' as change might imply onChange // this is why I named 'updateFunc' on state that way instead of // 'changeFunc' const changeFunc = this.field.changeFunc; if (changeFunc != null) { changeFunc(this.node, value); } const updateFunc = this.state.updateFunc; if (updateFunc != null) { updateFunc(this); } } @action setValueAndRawWithoutChangeEvent(value: V) { // if there are no changes, don't do anything if (comparer.structural(this._value, value)) { return; } this._value = value; this.state.setValueWithoutRawUpdate(this.path, value); this._raw = this.field.render( value, this.state.stateConverterOptionsWithContext(this) ); } @computed get value(): V { if (this.addMode) { throw new Error( "Cannot access field in add mode until it has been set once" ); } return this._value; } @override get required(): boolean { return ( !this.field.converter.neverRequired && (this.field.required || this._isRequired || this.state.isRequiredFunc(this)) ); } validate(options?: ValidateOptions): boolean { const ignoreRequired = options != null ? options.ignoreRequired : false; const ignoreGetError = options != null ? options.ignoreGetError : false; this.setValueFromRaw(this.raw, { ignoreRequired }); if (ignoreGetError) { return this.isInternallyValid; } return this.isValid; } // XXX move into interface @computed get isInternallyValid(): boolean { // is internally valid even if getError gives an error return this._error === undefined; } @computed get isValid(): boolean { return this.errorValue === undefined; } @computed get isDirty(): boolean { if (this.addMode) { return false; } if (Array.isArray(this.value)) { const jsValue = toJS(this.value); if (jsValue.length !== this._originalValue.length) { return true; } return JSON.stringify(jsValue) !== JSON.stringify(this._originalValue); } if (isStateTreeNode(this.value) && isModelType(getType(this.value))) { return getIdentifier(this.value) !== this._originalValue; } const jsValue = toJS(this.value); if (jsValue != null && (jsValue as any).constructor == {}.constructor) { return JSON.stringify(jsValue) !== JSON.stringify(this._originalValue); } return jsValue !== this._originalValue; } restore(): void { // If this accessor is not dirty, don't bother to restore. if (!this.isDirty) { return; } this.setValueAndUpdateRaw(this._originalValue); this.resetDirtyState(); } resetDirtyState(): void { this.setOriginalValue(); } @computed get requiredError(): string { const requiredError = this.field.requiredError || this.state._requiredError; return errorMessage(requiredError, this.state.context); } @action setValueFromRaw(raw: R, options?: ProcessOptions) { const stateConverterOptions = this.state.stateConverterOptionsWithContext(this); raw = this.field.converter.preprocessRaw(raw, stateConverterOptions); if (this.field.isRequired(raw, this.required, options)) { if (!this.field.converter.emptyImpossible) { this.setValue(this.field.converter.emptyValue); } this.setError(this.requiredError); return; } let processResult; try { processResult = this.field.process(raw, stateConverterOptions); } catch (e) { this.setError("Something went wrong"); return; } if (processResult instanceof ValidationMessage) { this.setError(processResult.message); return; } else { this.clearError(); } if (!(processResult instanceof ProcessValue)) { throw new Error("Unknown process result"); } const extraResult = this.state.extraValidationFunc( this, processResult.value ); // XXX possible flicker? if (typeof extraResult === "string" && extraResult) { this.setError(extraResult); } this.setValue(processResult.value); } @action setRaw(raw: R, options?: ProcessOptions) { if (this.state.saveStatus === "rightAfter") { this.state.setSaveStatus("after"); } this._raw = raw; this.setValueFromRaw(raw, options); } @action setRawFromValue() { // we get the value ignoring add mode // this is why we can't use this.value const value = this.state.getValue(this.path); this._value = value; // we don't use setRaw on the field as the value is already // correct. setting raw causes addMode for the field // to be disabled this._raw = this.field.render( value, this.state.stateConverterOptionsWithContext(this) ); // trigger validation this.validate(); } @action setValueAndUpdateRaw(value: V) { // We want to update a value through the accessor and also update the raw this.setValue(value); this.setRawFromValue(); } // XXX should these go into interface / base class? @action setError(error: string) { this._error = error; } // backward compatibility -- use setRaw instead handleChange = (...args: any[]) => { const raw = this.field.getRaw(...args); this.setRaw(raw); }; handleFocus = (event: any) => { if (this.state.focusFunc == null) { return; } this.state.focusFunc(event, this); }; handleBlur = (event: any) => { if (this.field.postprocess && !this._error) { this.setRawFromValue(); } if (this.state.blurFunc != null) { this.state.blurFunc(event, this); } }; @computed get inputProps() { const result: any = this.field.controlled(this); result.disabled = this.disabled; if (this.readOnly) { result.readOnly = this.readOnly; } if (this.state.focusFunc != null) { result.onFocus = this.handleFocus; } if (this.state.blurFunc != null || this.field.postprocess) { result.onBlur = this.handleBlur; } return result; } @computed get validationProps(): Record<string, unknown> { return currentValidationProps(this); } accessBySteps(_steps: string[]): IAccessor { throw new Error("Cannot step through field accessor"); } }
the_stack