text
stringlengths
2.5k
6.39M
kind
stringclasses
3 values
import type { MetricData } from "./metrics.api"; import { metricsApi } from "./metrics.api"; import type { DerivedKubeApiOptions, IgnoredKubeApiOptions, ResourceDescriptor } from "../kube-api"; import { KubeApi } from "../kube-api"; import type { RequireExactlyOne } from "type-fest"; import type { KubeObjectMetadata, LocalObjectReference, Affinity, Toleration, LabelSelector, KubeObjectScope } from "../kube-object"; import type { SecretReference } from "./secret.api"; import type { PersistentVolumeClaimSpec } from "./persistent-volume-claim.api"; import { KubeObject } from "../kube-object"; import { isDefined } from "../../utils"; export class PodApi extends KubeApi<Pod> { constructor(opts: DerivedKubeApiOptions & IgnoredKubeApiOptions = {}) { super({ ...opts, objectConstructor: Pod, }); } async getLogs(params: ResourceDescriptor, query?: PodLogsQuery): Promise<string> { const path = `${this.getUrl(params)}/log`; return this.request.get(path, { query }); } } export function getMetricsForPods(pods: Pod[], namespace: string, selector = "pod, namespace"): Promise<PodMetricData> { const podSelector = pods.map(pod => pod.getName()).join("|"); const opts = { category: "pods", pods: podSelector, namespace, selector }; return metricsApi.getMetrics({ cpuUsage: opts, cpuRequests: opts, cpuLimits: opts, memoryUsage: opts, memoryRequests: opts, memoryLimits: opts, fsUsage: opts, fsWrites: opts, fsReads: opts, networkReceive: opts, networkTransmit: opts, }, { namespace, }); } export interface PodMetricData extends Partial<Record<string, MetricData>> { cpuUsage: MetricData; memoryUsage: MetricData; fsUsage: MetricData; fsWrites: MetricData; fsReads: MetricData; networkReceive: MetricData; networkTransmit: MetricData; cpuRequests?: MetricData; cpuLimits?: MetricData; memoryRequests?: MetricData; memoryLimits?: MetricData; } // Reference: https://kubernetes.io/docs/reference/generated/kubernetes-api/v1.19/#read-log-pod-v1-core export interface PodLogsQuery { container?: string; tailLines?: number; timestamps?: boolean; sinceTime?: string; // Date.toISOString()-format follow?: boolean; previous?: boolean; } export enum PodStatusPhase { TERMINATED = "Terminated", FAILED = "Failed", PENDING = "Pending", RUNNING = "Running", SUCCEEDED = "Succeeded", EVICTED = "Evicted", } export interface ContainerPort { containerPort: number; hostIP?: string; hostPort?: number; name?: string; protocol?: "UDP" | "TCP" | "SCTP"; } export interface VolumeMount { name: string; readOnly?: boolean; mountPath: string; mountPropagation?: string; subPath?: string; subPathExpr?: string; } export interface PodContainer extends Partial<Record<PodContainerProbe, IContainerProbe>> { name: string; image: string; command?: string[]; args?: string[]; ports?: ContainerPort[]; resources?: { limits?: { cpu: string; memory: string; }; requests?: { cpu: string; memory: string; }; }; terminationMessagePath?: string; terminationMessagePolicy?: string; env?: { name: string; value?: string; valueFrom?: { fieldRef?: { apiVersion: string; fieldPath: string; }; secretKeyRef?: { key: string; name: string; }; configMapKeyRef?: { key: string; name: string; }; }; }[]; envFrom?: { configMapRef?: LocalObjectReference; secretRef?: LocalObjectReference; }[]; volumeMounts?: VolumeMount[]; imagePullPolicy?: string; } export type PodContainerProbe = "livenessProbe" | "readinessProbe" | "startupProbe"; interface IContainerProbe { httpGet?: { path?: string; /** * either a port number or an IANA_SVC_NAME string referring to a port defined in the container */ port: number | string; scheme: string; host?: string; }; exec?: { command: string[]; }; tcpSocket?: { port: number; }; initialDelaySeconds?: number; timeoutSeconds?: number; periodSeconds?: number; successThreshold?: number; failureThreshold?: number; } export interface ContainerStateRunning { startedAt: string; } export interface ContainerStateWaiting { reason: string; message: string; } export interface ContainerStateTerminated { startedAt: string; finishedAt: string; exitCode: number; reason: string; containerID?: string; message?: string; signal?: number; } /** * ContainerState holds a possible state of container. Only one of its members * may be specified. If none of them is specified, the default one is * `ContainerStateWaiting`. */ export interface ContainerState { running?: ContainerStateRunning; waiting?: ContainerStateWaiting; terminated?: ContainerStateTerminated; } export interface PodContainerStatus { name: string; state?: ContainerState; lastState?: ContainerState; ready: boolean; restartCount: number; image: string; imageID: string; containerID?: string; started?: boolean; } export interface AwsElasticBlockStoreSource { volumeID: string; fsType: string; } export interface AzureDiskSource { /** * The name of the VHD blob object OR the name of an Azure managed data disk if `kind` is `"Managed"`. */ diskName: string; /** * The URI of the vhd blob object OR the `resourceID` of an Azure managed data disk if `kind` is `"Managed"`. */ diskURI: string; /** * Kind of disk * @default "Shared" */ kind?: "Shared" | "Dedicated" | "Managed"; /** * Disk caching mode. * @default "None" */ cachingMode?: "None" | "ReadOnly" | "ReadWrite"; /** * The filesystem type to mount. * @default "ext4" */ fsType?: string; /** * Whether the filesystem is used as readOnly. * @default false */ readonly?: boolean; } export interface AzureFileSource { /** * The name of the secret that contains both Azure storage account name and key. */ secretName: string; /** * The share name to be used. */ shareName: string; /** * In case the secret is stored in a different namespace. * @default "default" */ secretNamespace?: string; /** * Whether the filesystem is used as readOnly. */ readOnly: boolean; } export interface CephfsSource { /** * List of Ceph monitors */ monitors: string[]; /** * Used as the mounted root, rather than the full Ceph tree. * @default "/" */ path?: string; /** * The RADOS user name. * @default "admin" */ user?: string; /** * The path to the keyring file. * @default "/etc/ceph/user.secret" */ secretFile?: string; /** * Reference to Ceph authentication secrets. If provided, then the secret overrides `secretFile` */ secretRef?: SecretReference; /** * Whether the filesystem is used as readOnly. * * @default false */ readOnly?: boolean; } export interface CinderSource { volumeID: string; fsType: string; /** * @default false */ readOnly?: boolean; secretRef?: SecretReference; } export interface ConfigMapSource { name: string; items: { key: string; path: string; }[]; } export interface DownwardApiSource { items: { path: string; fieldRef: { fieldPath: string; }; }[]; } export interface EphemeralSource { volumeClaimTemplate: { /** * All the rest of the fields are ignored and rejected during validation */ metadata?: Pick<KubeObjectMetadata, "labels" | "annotations">; spec: PersistentVolumeClaimSpec; }; } export interface EmptyDirSource { medium?: string; sizeLimit?: string; } export interface FiberChannelSource { /** * A list of World Wide Names */ targetWWNs: string[]; /** * Logical Unit number */ lun: number; /** * The type of filesystem * @default "ext4" */ fsType?: string; readOnly: boolean; } export interface FlockerSource { datasetName: string; } export interface FlexVolumeSource { driver: string; fsType?: string; secretRef?: LocalObjectReference; /** * @default false */ readOnly?: boolean; options?: Record<string, string>; } export interface GcePersistentDiskSource { pdName: string; fsType: string; } export interface GitRepoSource { repository: string; revision: string; } export interface GlusterFsSource { /** * The name of the Endpoints object that represents a Gluster cluster configuration. */ endpoints: string; /** * The Glusterfs volume name. */ path: string; /** * The boolean that sets the mountpoint readOnly or readWrite. */ readOnly: boolean; } export interface HostPathSource { path: string; /** * Determines the sorts of checks that will be done * @default "" */ type?: "" | "DirectoryOrCreate" | "Directory" | "FileOrCreate" | "File" | "Socket" | "CharDevice" | "BlockDevice"; } export interface IScsiSource { targetPortal: string; iqn: string; lun: number; fsType: string; readOnly: boolean; chapAuthDiscovery?: boolean; chapAuthSession?: boolean; secretRef?: SecretReference; } export interface LocalSource { path: string; } export interface NetworkFsSource { server: string; path: string; readOnly?: boolean; } export interface PersistentVolumeClaimSource { claimName: string; } export interface PhotonPersistentDiskSource { pdID: string; /** * @default "ext4" */ fsType?: string; } export interface PortworxVolumeSource { volumeID: string; fsType?: string; readOnly?: boolean; } export interface KeyToPath { key: string; path: string; mode?: number; } export interface ConfigMapProjection { name: string; items?: KeyToPath[]; optional?: boolean; } export interface ObjectFieldSelector { fieldPath: string; apiVersion?: string; } export interface ResourceFieldSelector { resource: string; containerName?: string; divisor?: string; } export interface DownwardAPIVolumeFile { path: string; fieldRef?: ObjectFieldSelector; resourceFieldRef?: ResourceFieldSelector; mode?: number; } export interface DownwardAPIProjection { items?: DownwardAPIVolumeFile[]; } export interface SecretProjection { name: string; items?: KeyToPath[]; optional?: boolean; } export interface ServiceAccountTokenProjection { audience?: string; expirationSeconds?: number; path: string; } export interface VolumeProjection { secret?: SecretProjection; downwardAPI?: DownwardAPIProjection; configMap?: ConfigMapProjection; serviceAccountToken?: ServiceAccountTokenProjection; } export interface ProjectedSource { sources?: VolumeProjection[]; defaultMode?: number; } export interface QuobyteSource { registry: string; volume: string; /** * @default false */ readOnly?: boolean; /** * @default "serivceaccount" */ user?: string; group?: string; tenant?: string; } export interface RadosBlockDeviceSource { monitors: string[]; image: string; /** * @default "ext4" */ fsType?: string; /** * @default "rbd" */ pool?: string; /** * @default "admin" */ user?: string; /** * @default "/etc/ceph/keyring" */ keyring?: string; secretRef?: SecretReference; /** * @default false */ readOnly?: boolean; } export interface ScaleIoSource { gateway: string; system: string; secretRef?: LocalObjectReference; /** * @default false */ sslEnabled?: boolean; protectionDomain?: string; storagePool?: string; /** * @default "ThinProvisioned" */ storageMode?: "ThickProvisioned" | "ThinProvisioned"; volumeName: string; /** * @default "xfs" */ fsType?: string; /** * @default false */ readOnly?: boolean; } export interface SecretSource { secretName: string; items?: { key: string; path: string; mode?: number; }[]; defaultMode?: number; optional?: boolean; } export interface StorageOsSource { volumeName: string; /** * @default Pod.metadata.namespace */ volumeNamespace?: string; /** * @default "ext4" */ fsType?: string; /** * @default false */ readOnly?: boolean; secretRef?: LocalObjectReference; } export interface VsphereVolumeSource { volumePath: string; /** * @default "ext4" */ fsType?: string; storagePolicyName?: string; storagePolicyID?: string; } export interface ContainerStorageInterfaceSource { driver: string; /** * @default false */ readOnly?: boolean; /** * @default "ext4" */ fsType?: string; volumeAttributes?: Record<string, string>; controllerPublishSecretRef?: SecretReference; nodeStageSecretRef?: SecretReference; nodePublishSecretRef?: SecretReference; controllerExpandSecretRef?: SecretReference; } export interface PodVolumeVariants { awsElasticBlockStore: AwsElasticBlockStoreSource; azureDisk: AzureDiskSource; azureFile: AzureFileSource; cephfs: CephfsSource; cinder: CinderSource; configMap: ConfigMapSource; csi: ContainerStorageInterfaceSource; downwardAPI: DownwardApiSource; emptyDir: EmptyDirSource; ephemeral: EphemeralSource; fc: FiberChannelSource; flexVolume: FlexVolumeSource; flocker: FlockerSource; gcePersistentDisk: GcePersistentDiskSource; gitRepo: GitRepoSource; glusterfs: GlusterFsSource; hostPath: HostPathSource; iscsi: IScsiSource; local: LocalSource; nfs: NetworkFsSource; persistentVolumeClaim: PersistentVolumeClaimSource; photonPersistentDisk: PhotonPersistentDiskSource; portworxVolume: PortworxVolumeSource; projected: ProjectedSource; quobyte: QuobyteSource; rbd: RadosBlockDeviceSource; scaleIO: ScaleIoSource; secret: SecretSource; storageos: StorageOsSource; vsphereVolume: VsphereVolumeSource; } /** * The valid kinds of volume */ export type PodVolumeKind = keyof PodVolumeVariants; export type PodSpecVolume = RequireExactlyOne<PodVolumeVariants> & { name: string; }; export interface HostAlias { ip: string; hostnames: string[]; } export interface SELinuxOptions { level?: string; role?: string; type?: string; user?: string; } export interface SeccompProfile { localhostProfile?: string; type: string; } export interface Sysctl { name: string; value: string; } export interface WindowsSecurityContextOptions { labelSelector?: LabelSelector; maxSkew: number; topologyKey: string; whenUnsatisfiable: string; } export interface PodSecurityContext { fsGroup?: number; fsGroupChangePolicy?: string; runAsGroup?: number; runAsNonRoot?: boolean; runAsUser?: number; seLinuxOptions?: SELinuxOptions; seccompProfile?: SeccompProfile; supplementalGroups?: number[]; sysctls?: Sysctl; windowsOptions?: WindowsSecurityContextOptions; } export interface TopologySpreadConstraint { } export interface PodSpec { activeDeadlineSeconds?: number; affinity?: Affinity; automountServiceAccountToken?: boolean; containers?: PodContainer[]; dnsPolicy?: string; enableServiceLinks?: boolean; ephemeralContainers?: unknown[]; hostAliases?: HostAlias[]; hostIPC?: boolean; hostname?: string; hostNetwork?: boolean; hostPID?: boolean; imagePullSecrets?: LocalObjectReference[]; initContainers?: PodContainer[]; nodeName?: string; nodeSelector?: Partial<Record<string, string>>; overhead?: Partial<Record<string, string>>; preemptionPolicy?: string; priority?: number; priorityClassName?: string; readinessGates?: unknown[]; restartPolicy?: string; runtimeClassName?: string; schedulerName?: string; securityContext?: PodSecurityContext; serviceAccount?: string; serviceAccountName?: string; setHostnameAsFQDN?: boolean; shareProcessNamespace?: boolean; subdomain?: string; terminationGracePeriodSeconds?: number; tolerations?: Toleration[]; topologySpreadConstraints?: TopologySpreadConstraint[]; volumes?: PodSpecVolume[]; } export interface PodCondition { lastProbeTime?: number; lastTransitionTime?: string; message?: string; reason?: string; type: string; status: string; } export interface PodStatus { phase: string; conditions: PodCondition[]; hostIP: string; podIP: string; podIPs?: { ip: string; }[]; startTime: string; initContainerStatuses?: PodContainerStatus[]; containerStatuses?: PodContainerStatus[]; qosClass?: string; reason?: string; } export class Pod extends KubeObject<PodStatus, PodSpec, KubeObjectScope.Namespace> { static kind = "Pod"; static namespaced = true; static apiBase = "/api/v1/pods"; getAffinityNumber() { return Object.keys(this.getAffinity()).length; } getInitContainers() { return this.spec?.initContainers ?? []; } getContainers() { return this.spec?.containers ?? []; } getAllContainers() { return [...this.getContainers(), ...this.getInitContainers()]; } getRunningContainers() { const runningContainerNames = new Set( this.getContainerStatuses() .filter(({ state }) => state?.running) .map(({ name }) => name), ); return this.getAllContainers() .filter(({ name }) => runningContainerNames.has(name)); } getContainerStatuses(includeInitContainers = true) { const { containerStatuses = [], initContainerStatuses = [] } = this.status ?? {}; if (includeInitContainers) { return [...containerStatuses, ...initContainerStatuses]; } return [...containerStatuses]; } getRestartsCount(): number { const { containerStatuses = [] } = this.status ?? {}; return containerStatuses.reduce((totalCount, { restartCount }) => totalCount + restartCount, 0); } getQosClass() { return this.status?.qosClass || ""; } getReason() { return this.status?.reason || ""; } getPriorityClassName() { return this.spec?.priorityClassName || ""; } getStatus(): PodStatusPhase { const phase = this.getStatusPhase(); const reason = this.getReason(); const trueConditionTypes = new Set(this.getConditions() .filter(({ status }) => status === "True") .map(({ type }) => type)); const isInGoodCondition = ["Initialized", "Ready"].every(condition => trueConditionTypes.has(condition)); if (reason === PodStatusPhase.EVICTED) { return PodStatusPhase.EVICTED; } if (phase === PodStatusPhase.FAILED) { return PodStatusPhase.FAILED; } if (phase === PodStatusPhase.SUCCEEDED) { return PodStatusPhase.SUCCEEDED; } if (phase === PodStatusPhase.RUNNING && isInGoodCondition) { return PodStatusPhase.RUNNING; } return PodStatusPhase.PENDING; } // Returns pod phase or container error if occurred getStatusMessage(): string { if (this.getReason() === PodStatusPhase.EVICTED) { return "Evicted"; } if (this.metadata.deletionTimestamp) { return "Terminating"; } return this.getStatusPhase() || "Waiting"; } getStatusPhase() { return this.status?.phase; } getConditions() { return this.status?.conditions ?? []; } getVolumes() { return this.spec?.volumes ?? []; } getSecrets(): string[] { return this.getVolumes() .map(vol => vol.secret?.secretName) .filter(isDefined); } getNodeSelectors(): string[] { return Object.entries(this.spec?.nodeSelector ?? {}) .map(values => values.join(": ")); } getTolerations() { return this.spec?.tolerations ?? []; } getAffinity(): Affinity { return this.spec?.affinity ?? {}; } hasIssues() { for (const { type, status } of this.getConditions()) { if (type === "Ready" && status !== "True") { return true; } } for (const { state } of this.getContainerStatuses()) { if (state?.waiting?.reason === "CrashLookBackOff") { return true; } } return this.getStatusPhase() !== "Running"; } getLivenessProbe(container: PodContainer) { return this.getProbe(container, "livenessProbe"); } getReadinessProbe(container: PodContainer) { return this.getProbe(container, "readinessProbe"); } getStartupProbe(container: PodContainer) { return this.getProbe(container, "startupProbe"); } private getProbe(container: PodContainer, field: PodContainerProbe): string[] { const probe: string[] = []; const probeData = container[field]; if (!probeData) { return probe; } const { httpGet, exec, tcpSocket, initialDelaySeconds = 0, timeoutSeconds = 0, periodSeconds = 0, successThreshold = 0, failureThreshold = 0, } = probeData; // HTTP Request if (httpGet) { const { path = "", port, host = "", scheme } = httpGet; const resolvedPort = typeof port === "number" ? port // Try and find the port number associated witht the name or fallback to the name itself : container.ports?.find(containerPort => containerPort.name === port)?.containerPort || port; probe.push( "http-get", `${scheme.toLowerCase()}://${host}:${resolvedPort}${path}`, ); } // Command if (exec?.command) { probe.push(`exec [${exec.command.join(" ")}]`); } // TCP Probe if (tcpSocket?.port) { probe.push(`tcp-socket :${tcpSocket.port}`); } probe.push( `delay=${initialDelaySeconds}s`, `timeout=${timeoutSeconds}s`, `period=${periodSeconds}s`, `#success=${successThreshold}`, `#failure=${failureThreshold}`, ); return probe; } getNodeName(): string | undefined { return this.spec?.nodeName; } getSelectedNodeOs(): string | undefined { return this.spec?.nodeSelector?.["kubernetes.io/os"] || this.spec?.nodeSelector?.["beta.kubernetes.io/os"]; } getIPs(): string[] { const podIPs = this.status?.podIPs ?? []; return podIPs.map(value => value.ip); } }
the_stack
import React from 'react'; import userEvent from '@testing-library/user-event'; import { render, fireEvent } from 'garden-test-utils'; import { KEY_CODES } from '@zendeskgarden/container-utilities'; import { default as Pagination, IPaginationProps, PAGE_TYPE } from './Pagination'; describe('Pagination', () => { it('passes ref to underlying DOM element', () => { const ref = React.createRef<HTMLUListElement>(); const { container } = render(<Pagination totalPages={0} currentPage={0} ref={ref} />); expect(container.firstChild).toBe(ref.current); }); let onChange: jest.Mock; const BasicExample = ({ currentPage = 1, totalPages = 5, ...other }: Partial<IPaginationProps> = {}) => ( <Pagination totalPages={totalPages} currentPage={currentPage} onChange={onChange} {...other} /> ); beforeEach(() => { onChange = jest.fn(); }); describe('transformPageProps', () => { let transformPageProps: any; beforeEach(() => { transformPageProps = jest.fn((pageType, props) => props); }); it('calls provided transform function with correct page type', () => { render( <BasicExample currentPage={1} totalPages={10} transformPageProps={transformPageProps} /> ); expect(transformPageProps).toHaveBeenCalledTimes(11); expect(transformPageProps.mock.calls[0][0]).toBe('previous'); expect(transformPageProps.mock.calls[1][0]).toBe('page'); expect(transformPageProps.mock.calls[2][0]).toBe('page'); expect(transformPageProps.mock.calls[3][0]).toBe('page'); expect(transformPageProps.mock.calls[4][0]).toBe('page'); expect(transformPageProps.mock.calls[5][0]).toBe('page'); expect(transformPageProps.mock.calls[6][0]).toBe('page'); expect(transformPageProps.mock.calls[7][0]).toBe('page'); expect(transformPageProps.mock.calls[8][0]).toBe('gap'); expect(transformPageProps.mock.calls[9][0]).toBe('page'); expect(transformPageProps.mock.calls[10][0]).toBe('next'); }); it('applies transformed props if transform is supplied', () => { const CUSTOM_PROP_VALUE = 'custom-prop'; transformPageProps = (type: PAGE_TYPE, props: any) => { props['data-test-id'] = CUSTOM_PROP_VALUE; return props; }; const { container } = render( <BasicExample currentPage={1} totalPages={10} transformPageProps={transformPageProps} /> ); [...container.firstElementChild!.children].forEach(child => { expect(child).toHaveAttribute('data-test-id', CUSTOM_PROP_VALUE); }); }); }); describe('Previous Page', () => { it('is visible if currentPage is first page', () => { const { container } = render(<BasicExample currentPage={1} />); expect(container.firstElementChild!.children[0]).toHaveAttribute('hidden'); }); it('is visible otherwise', () => { const { container } = render(<BasicExample currentPage={2} />); expect(container.firstElementChild!.children[0]).not.toHaveAttribute('hidden'); }); it('decrements currentPage when selected', () => { const { container } = render(<BasicExample currentPage={3} />); userEvent.click(container.firstElementChild!.children[0]); expect(onChange).toHaveBeenCalledWith(2); }); it('focuses first page when visibility is lost', () => { const { container } = render(<Pagination totalPages={5} currentPage={2} />); const previousPage = container.firstElementChild!.children[0]; fireEvent.focus(previousPage); fireEvent.keyDown(previousPage, { keyCode: KEY_CODES.ENTER }); expect(container.firstElementChild!.children[1]).toHaveAttribute('tabindex', '0'); expect(container.firstElementChild!.children[2]).toHaveAttribute('aria-current', 'true'); }); }); describe('Next Page', () => { it('is visible if currentPage is final page', () => { const { container } = render(<BasicExample currentPage={5} totalPages={5} />); expect( container.firstElementChild!.children[container.firstElementChild!.children.length - 1] ).toHaveAttribute('hidden'); }); it('is visible otherwise', () => { const { container } = render(<BasicExample currentPage={2} totalPages={5} />); expect( container.firstElementChild!.children[container.firstElementChild!.children.length - 1] ).not.toHaveAttribute('hidden'); }); it('decrements currentPage when selected', () => { const { container } = render(<BasicExample currentPage={3} totalPages={5} />); userEvent.click( container.firstElementChild!.children[container.firstElementChild!.children.length - 1] ); expect(onChange).toHaveBeenCalledWith(4); }); it('focuses last page when visibility is lost', () => { const { container } = render( <Pagination totalPages={5} currentPage={4} onChange={onChange} /> ); const paginationWrapper = container.firstElementChild!; const nextPage = paginationWrapper.children[paginationWrapper.children.length - 1]; userEvent.click(nextPage); userEvent.type(nextPage, '{enter}'); expect(onChange).toHaveBeenCalledWith(5); }); }); describe('Pages', () => { it('updates onStateChange with currentPage when selected', () => { const { getByText } = render(<BasicExample currentPage={1} totalPages={5} />); userEvent.click(getByText('2')); expect(onChange).toHaveBeenCalledWith(2); }); it('updates onChange with currentPage when selected', () => { const { getByText } = render(<BasicExample currentPage={1} totalPages={5} />); userEvent.click(getByText('2')); expect(onChange).toHaveBeenCalledWith(2); }); const transformPageProps = (pageType: PAGE_TYPE, props: any) => { props[`data-test-${pageType}`] = true; return props; }; it('hides front gap when currentPage is within padding range', () => { const { container } = render( <BasicExample currentPage={1} totalPages={25} transformPageProps={transformPageProps} /> ); const children = container.firstElementChild!.children; expect(children[0]).toHaveAttribute('data-test-previous'); expect(children[1]).toHaveAttribute('data-test-page'); expect(children[2]).toHaveAttribute('data-test-page'); expect(children[3]).toHaveAttribute('data-test-page'); expect(children[4]).toHaveAttribute('data-test-page'); expect(children[5]).toHaveAttribute('data-test-page'); expect(children[6]).toHaveAttribute('data-test-page'); expect(children[7]).toHaveAttribute('data-test-page'); expect(children[8]).toHaveAttribute('data-test-gap'); expect(children[9]).toHaveAttribute('data-test-page'); expect(children[10]).toHaveAttribute('data-test-next'); }); it('hides back gap when currentPage is within padding range', () => { const { container } = render( <BasicExample currentPage={25} totalPages={25} transformPageProps={transformPageProps} /> ); const children = container.firstElementChild!.children; expect(children[0]).toHaveAttribute('data-test-previous'); expect(children[1]).toHaveAttribute('data-test-page'); expect(children[2]).toHaveAttribute('data-test-gap'); expect(children[3]).toHaveAttribute('data-test-page'); expect(children[4]).toHaveAttribute('data-test-page'); expect(children[5]).toHaveAttribute('data-test-page'); expect(children[6]).toHaveAttribute('data-test-page'); expect(children[7]).toHaveAttribute('data-test-page'); expect(children[8]).toHaveAttribute('data-test-page'); expect(children[9]).toHaveAttribute('data-test-page'); expect(children[10]).toHaveAttribute('data-test-next'); }); it('displays both gaps if not within padding range and totalPages is greater than padding limit', () => { const { container } = render( <BasicExample currentPage={15} totalPages={25} transformPageProps={transformPageProps} /> ); const children = container.firstElementChild!.children; expect(children[0]).toHaveAttribute('data-test-previous'); expect(children[1]).toHaveAttribute('data-test-page'); expect(children[2]).toHaveAttribute('data-test-gap'); expect(children[3]).toHaveAttribute('data-test-page'); expect(children[4]).toHaveAttribute('data-test-page'); expect(children[5]).toHaveAttribute('data-test-page'); expect(children[6]).toHaveAttribute('data-test-page'); expect(children[7]).toHaveAttribute('data-test-page'); expect(children[8]).toHaveAttribute('data-test-gap'); expect(children[9]).toHaveAttribute('data-test-page'); expect(children[10]).toHaveAttribute('data-test-next'); }); it('displays no gaps if less than padding limit', () => { const { container } = render( <BasicExample currentPage={1} totalPages={9} transformPageProps={transformPageProps} /> ); const children = container.firstElementChild!.children; expect(children[0]).toHaveAttribute('data-test-previous'); expect(children[1]).toHaveAttribute('data-test-page'); expect(children[2]).toHaveAttribute('data-test-page'); expect(children[3]).toHaveAttribute('data-test-page'); expect(children[4]).toHaveAttribute('data-test-page'); expect(children[5]).toHaveAttribute('data-test-page'); expect(children[6]).toHaveAttribute('data-test-page'); expect(children[7]).toHaveAttribute('data-test-page'); expect(children[8]).toHaveAttribute('data-test-page'); expect(children[9]).toHaveAttribute('data-test-page'); expect(children[10]).toHaveAttribute('data-test-next'); }); it('displays previous and next with zero total pages', () => { const { container } = render( <BasicExample totalPages={0} transformPageProps={transformPageProps} /> ); const children = container.firstElementChild!.children; expect(children[0]).toHaveAttribute('data-test-previous'); expect(children[1]).toHaveAttribute('data-test-next'); }); }); describe('Padding', () => { const transformPageProps = (pageType: PAGE_TYPE, props: any) => { props[`data-test-${pageType}`] = true; return props; }; it('renders as expected with reduced page padding', () => { const { container } = render( <BasicExample totalPages={9} currentPage={5} pagePadding={1} transformPageProps={transformPageProps} /> ); const children = container.firstElementChild!.children; expect(children[0]).toHaveAttribute('data-test-previous'); expect(children[1]).toHaveAttribute('data-test-page'); expect(children[2]).toHaveAttribute('data-test-gap'); expect(children[3]).toHaveAttribute('data-test-page'); expect(children[4]).toHaveAttribute('data-test-page'); expect(children[5]).toHaveAttribute('data-test-page'); expect(children[6]).toHaveAttribute('data-test-gap'); expect(children[7]).toHaveAttribute('data-test-page'); expect(children[8]).toHaveAttribute('data-test-next'); }); it('renders as expected with expanded page padding', () => { const { container } = render( <BasicExample totalPages={20} currentPage={10} pagePadding={3} transformPageProps={transformPageProps} /> ); const children = container.firstElementChild!.children; expect(children[0]).toHaveAttribute('data-test-previous'); expect(children[1]).toHaveAttribute('data-test-page'); expect(children[2]).toHaveAttribute('data-test-gap'); expect(children[3]).toHaveAttribute('data-test-page'); expect(children[4]).toHaveAttribute('data-test-page'); expect(children[5]).toHaveAttribute('data-test-page'); expect(children[6]).toHaveAttribute('data-test-page'); expect(children[7]).toHaveAttribute('data-test-page'); expect(children[8]).toHaveAttribute('data-test-page'); expect(children[9]).toHaveAttribute('data-test-page'); expect(children[10]).toHaveAttribute('data-test-gap'); expect(children[11]).toHaveAttribute('data-test-page'); expect(children[12]).toHaveAttribute('data-test-next'); }); }); describe('Gap', () => { const transformPageProps = (pageType: PAGE_TYPE, props: any) => { props[`data-test-${pageType}`] = true; return props; }; it('renders as expected with greater gap positioning', () => { const { container } = render( <BasicExample totalPages={20} currentPage={10} pageGap={3} transformPageProps={transformPageProps} /> ); const children = container.firstElementChild!.children; expect(children[0]).toHaveAttribute('data-test-previous'); expect(children[1]).toHaveAttribute('data-test-page'); expect(children[2]).toHaveAttribute('data-test-page'); expect(children[3]).toHaveAttribute('data-test-gap'); expect(children[4]).toHaveAttribute('data-test-page'); expect(children[5]).toHaveAttribute('data-test-page'); expect(children[6]).toHaveAttribute('data-test-page'); expect(children[7]).toHaveAttribute('data-test-page'); expect(children[8]).toHaveAttribute('data-test-page'); expect(children[9]).toHaveAttribute('data-test-gap'); expect(children[10]).toHaveAttribute('data-test-page'); expect(children[11]).toHaveAttribute('data-test-page'); expect(children[12]).toHaveAttribute('data-test-next'); }); it('renders with lesser gap positioning', () => { const { container } = render( <BasicExample totalPages={9} currentPage={5} pageGap={1} transformPageProps={transformPageProps} /> ); const children = container.firstElementChild!.children; expect(children[0]).toHaveAttribute('data-test-previous'); expect(children[1]).toHaveAttribute('data-test-gap'); expect(children[2]).toHaveAttribute('data-test-page'); expect(children[3]).toHaveAttribute('data-test-page'); expect(children[4]).toHaveAttribute('data-test-page'); expect(children[5]).toHaveAttribute('data-test-page'); expect(children[6]).toHaveAttribute('data-test-page'); expect(children[7]).toHaveAttribute('data-test-gap'); expect(children[8]).toHaveAttribute('data-test-next'); }); }); });
the_stack
import { IExecuteFunctions, ILoadOptionsFunctions, } from 'n8n-core'; import { IDataObject, INodeExecutionData, INodePropertyOptions, INodeType, INodeTypeDescription, NodeApiError, } from 'n8n-workflow'; import { extractID, googleApiRequest, googleApiRequestAllItems, hasKeys, upperFirst, } from './GenericFunctions'; import { documentFields, documentOperations, } from './DocumentDescription'; import { IUpdateBody, IUpdateFields, } from './interfaces'; export class GoogleDocs implements INodeType { description: INodeTypeDescription = { displayName: 'Google Docs', name: 'googleDocs', icon: 'file:googleDocs.svg', group: ['input'], version: 1, subtitle: '={{$parameter["operation"] + ": " + $parameter["resource"]}}', description: 'Consume Google Docs API.', defaults: { name: 'Google Docs', }, inputs: ['main'], outputs: ['main'], credentials: [ { name: 'googleApi', required: true, displayOptions: { show: { authentication: [ 'serviceAccount', ], }, }, }, { name: 'googleDocsOAuth2Api', required: true, displayOptions: { show: { authentication: [ 'oAuth2', ], }, }, }, ], properties: [ { displayName: 'Authentication', name: 'authentication', type: 'options', options: [ { name: 'Service Account', value: 'serviceAccount', }, { name: 'OAuth2', value: 'oAuth2', }, ], default: 'serviceAccount', }, { displayName: 'Resource', name: 'resource', type: 'options', options: [ { name: 'Document', value: 'document', }, ], default: 'document', description: 'The resource to operate on.', }, ...documentOperations, ...documentFields, ], }; methods = { loadOptions: { // Get all the drives to display them to user so that he can // select them easily async getDrives(this: ILoadOptionsFunctions): Promise<INodePropertyOptions[]> { const returnData: INodePropertyOptions[] = [ { name: 'My Drive', value: 'myDrive', }, { name: 'Shared with me', value: 'sharedWithMe', }, ]; let drives; try { drives = await googleApiRequestAllItems.call(this, 'drives', 'GET', '', {}, {}, 'https://www.googleapis.com/drive/v3/drives'); } catch (error) { throw new NodeApiError(this.getNode(), error, { message: 'Error in loading Drives' }); } for (const drive of drives) { returnData.push({ name: drive.name as string, value: drive.id as string, }); } return returnData; }, async getFolders(this: ILoadOptionsFunctions): Promise<INodePropertyOptions[]> { const returnData: INodePropertyOptions[] = [ { name: '/', value: 'default', }, ]; const driveId = this.getNodeParameter('driveId'); const qs = { q: `mimeType = \'application/vnd.google-apps.folder\' ${driveId === 'sharedWithMe' ? 'and sharedWithMe = true' : ' and \'root\' in parents'}`, ...(driveId && driveId !== 'myDrive' && driveId !== 'sharedWithMe') ? { driveId } : {}, }; let folders; try { folders = await googleApiRequestAllItems.call(this, 'files', 'GET', '', {}, qs, 'https://www.googleapis.com/drive/v3/files'); } catch (error) { throw new NodeApiError(this.getNode(), error, { message: 'Error in loading Folders' }); } for (const folder of folders) { returnData.push({ name: folder.name as string, value: folder.id as string, }); } return returnData; }, }, }; async execute(this: IExecuteFunctions): Promise<INodeExecutionData[][]> { const items = this.getInputData(); const returnData: IDataObject[] = []; const length = items.length; let responseData; const resource = this.getNodeParameter('resource', 0) as string; const operation = this.getNodeParameter('operation', 0) as string; for (let i = 0; i < length; i++) { try { if (resource === 'document') { if (operation === 'create') { // https://developers.google.com/docs/api/reference/rest/v1/documents/create const folderId = this.getNodeParameter('folderId', i) as string; const body: IDataObject = { name: this.getNodeParameter('title', i) as string, mimeType: 'application/vnd.google-apps.document', ...(folderId && folderId !== 'default') ? { parents: [folderId] } : {}, }; responseData = await googleApiRequest.call(this, 'POST', '', body, {}, 'https://www.googleapis.com/drive/v3/files'); } else if (operation === 'get') { // https://developers.google.com/docs/api/reference/rest/v1/documents/get const documentURL = this.getNodeParameter('documentURL', i) as string; const simple = this.getNodeParameter('simple', i) as boolean; let documentId = extractID(documentURL); if (!documentId) { documentId = documentURL; } responseData = await googleApiRequest.call(this, 'GET', `/documents/${documentId}`); if (simple) { const content = (responseData.body.content as IDataObject[]) .reduce((arr: string[], contentItem) => { if (contentItem && contentItem.paragraph) { const texts = ((contentItem.paragraph as IDataObject).elements as IDataObject[]) .map(element => { if (element && element.textRun) { return (element.textRun as IDataObject).content as string; } }) as string[]; arr = [...arr, ...texts]; } return arr; }, []) .join(''); responseData = { documentId, content, }; } } else if (operation === 'update') { // https://developers.google.com/docs/api/reference/rest/v1/documents/batchUpdate const documentURL = this.getNodeParameter('documentURL', i) as string; let documentId = extractID(documentURL); const simple = this.getNodeParameter('simple', i) as boolean; const actionsUi = this.getNodeParameter('actionsUi', i) as { actionFields: IDataObject[] }; const { writeControlObject } = this.getNodeParameter('updateFields', i) as IUpdateFields; if (!documentId) { documentId = documentURL; } const body = { requests: [], } as IUpdateBody; if (hasKeys(writeControlObject)) { const { control, value } = writeControlObject; body.writeControl = { [control]: value, }; } if (actionsUi) { let requestBody: IDataObject; actionsUi.actionFields.forEach(actionField => { const { action, object } = actionField; if (object === 'positionedObject') { if (action === 'delete') { requestBody = { objectId: actionField.objectId, }; } } else if (object === 'pageBreak') { if (action === 'insert') { const { insertSegment, segmentId, locationChoice, index } = actionField; requestBody = { [locationChoice as string]: { segmentId: (insertSegment !== 'body') ? segmentId : '', ...(locationChoice === 'location') ? { index } : {}, }, }; } } else if (object === 'table') { if (action === 'insert') { const { rows, columns, insertSegment, locationChoice, segmentId, index } = actionField; requestBody = { rows, columns, [locationChoice as string]: { segmentId: (insertSegment !== 'body') ? segmentId : '', ...(locationChoice === 'location') ? { index } : {}, }, }; } } else if (object === 'footer') { if (action === 'create') { const { insertSegment, locationChoice, segmentId, index } = actionField; requestBody = { type: 'DEFAULT', sectionBreakLocation: { segmentId: (insertSegment !== 'body') ? segmentId : '', ...(locationChoice === 'location') ? { index } : {}, }, }; } else if (action === 'delete') { requestBody = { footerId: actionField.footerId, }; } } else if (object === 'header') { if (action === 'create') { const { insertSegment, locationChoice, segmentId, index } = actionField; requestBody = { type: 'DEFAULT', sectionBreakLocation: { segmentId: (insertSegment !== 'body') ? segmentId : '', ...(locationChoice === 'location') ? { index } : {}, }, }; } else if (action === 'delete') { requestBody = { headerId: actionField.headerId, }; } } else if (object === 'tableColumn') { if (action === 'insert') { const { insertPosition, rowIndex, columnIndex, insertSegment, segmentId, index } = actionField; requestBody = { insertRight: insertPosition, tableCellLocation: { rowIndex, columnIndex, tableStartLocation: { segmentId: (insertSegment !== 'body') ? segmentId : '', index, }, }, }; } else if (action === 'delete') { const { rowIndex, columnIndex, insertSegment, segmentId, index } = actionField; requestBody = { tableCellLocation: { rowIndex, columnIndex, tableStartLocation: { segmentId: (insertSegment !== 'body') ? segmentId : '', index, }, }, }; } } else if (object === 'tableRow') { if (action === 'insert') { const { insertPosition, rowIndex, columnIndex, insertSegment, segmentId, index } = actionField; requestBody = { insertBelow: insertPosition, tableCellLocation: { rowIndex, columnIndex, tableStartLocation: { segmentId: (insertSegment !== 'body') ? segmentId : '', index, }, }, }; } else if (action === 'delete') { const { rowIndex, columnIndex, insertSegment, segmentId, index } = actionField; requestBody = { tableCellLocation: { rowIndex, columnIndex, tableStartLocation: { segmentId: (insertSegment !== 'body') ? segmentId : '', index, }, }, }; } } else if (object === 'text') { if (action === 'insert') { const { text, locationChoice, insertSegment, segmentId, index } = actionField; requestBody = { text, [locationChoice as string]: { segmentId: (insertSegment !== 'body') ? segmentId : '', ...(locationChoice === 'location') ? { index } : {}, }, }; } else if (action === 'replaceAll') { const { text, replaceText, matchCase } = actionField; requestBody = { replaceText, containsText: { text, matchCase }, }; } } else if (object === 'paragraphBullets') { if (action === 'create') { const { bulletPreset, startIndex, insertSegment, segmentId, endIndex } = actionField; requestBody = { bulletPreset, range: { segmentId: (insertSegment !== 'body') ? segmentId : '', startIndex, endIndex }, }; } else if (action === 'delete') { const { startIndex, insertSegment, segmentId, endIndex } = actionField; requestBody = { range: { segmentId: (insertSegment !== 'body') ? segmentId : '', startIndex, endIndex }, }; } } else if (object === 'namedRange') { if (action === 'create') { const { name, insertSegment, segmentId, startIndex, endIndex } = actionField; requestBody = { name, range: { segmentId: (insertSegment !== 'body') ? segmentId : '', startIndex, endIndex }, }; } else if (action === 'delete') { const { namedRangeReference, value } = actionField; requestBody = { [namedRangeReference as string]: value, }; } } body.requests.push({ [`${action}${upperFirst(object as string)}`]: requestBody, }); }); } responseData = await googleApiRequest.call(this, 'POST', `/documents/${documentId}:batchUpdate`, body); if (simple === true) { if (Object.keys(responseData.replies[0]).length !== 0) { const key = Object.keys(responseData.replies[0])[0]; responseData = responseData.replies[0][key]; } else { responseData = {}; } } responseData.documentId = documentId; } } } catch (error) { if (this.continueOnFail()) { returnData.push({ error: error.message }); continue; } throw error; } Array.isArray(responseData) ? returnData.push(...responseData) : returnData.push(responseData); } return [this.helpers.returnJsonArray(returnData)]; } }
the_stack
import { Component, Input, Output, forwardRef, DoCheck, ViewChild, ViewChildren, QueryList, OnInit, HostListener, ElementRef, Optional, Inject, Directive, TemplateRef, ViewContainerRef, ContentChild, ChangeDetectionStrategy, ChangeDetectorRef, AfterViewInit, OnDestroy, HostBinding, Renderer2, } from '@angular/core'; import { DOCUMENT } from '@angular/common'; import { EventEmitter } from '@angular/core'; import { NG_VALUE_ACCESSOR, ControlValueAccessor, FormControl } from '@angular/forms'; import { TemplatePortalDirective } from '@angular/cdk/portal'; import { coerceBooleanProperty } from '@angular/cdk/coercion'; import { UP_ARROW, DOWN_ARROW, ESCAPE, LEFT_ARROW, RIGHT_ARROW, DELETE, BACKSPACE, ENTER, SPACE, TAB, HOME, } from '@angular/cdk/keycodes'; import { MatChip } from '@angular/material/chips'; import { MatInput } from '@angular/material/input'; import { MatOption } from '@angular/material/core'; import { MatAutocompleteTrigger } from '@angular/material/autocomplete'; import { Observable, Subscription, timer, merge, fromEvent } from 'rxjs'; import { filter, debounceTime } from 'rxjs/operators'; import { ICanDisable, mixinDisabled, IControlValueAccessor, mixinControlValueAccessor } from '@covalent/core/common'; @Directive({ selector: '[td-chip]ng-template', }) export class TdChipDirective extends TemplatePortalDirective { constructor(templateRef: TemplateRef<any>, viewContainerRef: ViewContainerRef) { super(templateRef, viewContainerRef); } } @Directive({ selector: '[td-autocomplete-option]ng-template', }) export class TdAutocompleteOptionDirective extends TemplatePortalDirective { constructor(templateRef: TemplateRef<any>, viewContainerRef: ViewContainerRef) { super(templateRef, viewContainerRef); } } export class TdChipsBase { constructor(public _changeDetectorRef: ChangeDetectorRef) {} } /* tslint:disable-next-line */ export const _TdChipsMixinBase = mixinControlValueAccessor(mixinDisabled(TdChipsBase), []); @Component({ providers: [ { provide: NG_VALUE_ACCESSOR, useExisting: forwardRef(() => TdChipsComponent), multi: true, }, ], selector: 'td-chips', inputs: ['disabled', 'value'], styleUrls: ['./chips.component.scss'], templateUrl: './chips.component.html', changeDetection: ChangeDetectionStrategy.OnPush, }) export class TdChipsComponent extends _TdChipsMixinBase implements IControlValueAccessor, DoCheck, OnInit, AfterViewInit, OnDestroy, ICanDisable { private _outsideClickSubs: Subscription = Subscription.EMPTY; private _inputValueChangesSubs: Subscription = Subscription.EMPTY; private _isMousedown: boolean = false; private _items: any[]; private _length: number = 0; private _stacked: boolean = false; private _requireMatch: boolean = false; private _color: 'primary' | 'accent' | 'warn' = 'primary'; private _inputPosition: 'before' | 'after' = 'after'; private _chipAddition: boolean = true; private _chipRemoval: boolean = true; private _focused: boolean = false; private _required: boolean = false; private _tabIndex: number = 0; private _touchendDebounce: number = 100; _internalClick: boolean = false; _internalActivateOption: boolean = false; @ViewChild('input', { static: true }) _nativeInput: ElementRef; @ViewChild(MatInput, { static: true }) _inputChild: MatInput; @ViewChild(MatAutocompleteTrigger, { static: true }) _autocompleteTrigger: MatAutocompleteTrigger; @ViewChildren(MatChip) _chipsChildren: QueryList<MatChip>; @ContentChild(TdChipDirective) _chipTemplate: TdChipDirective; @ContentChild(TdAutocompleteOptionDirective) _autocompleteOptionTemplate: TdAutocompleteOptionDirective; @ViewChildren(MatOption) _options: QueryList<MatOption>; /** * Flag that is true when autocomplete is focused. */ get focused(): boolean { return this._focused; } /** * FormControl for the matInput element. */ inputControl: FormControl = new FormControl(); /** * items?: any[] * Renders the `mat-autocomplete` with the provided list to display as options. */ @Input('items') set items(items: any[]) { this._items = items; this._setFirstOptionActive(); this._changeDetectorRef.markForCheck(); } get items(): any[] { return this._items; } /** * stacked?: boolean * Set stacked or horizontal chips depending on value. * Defaults to false. */ @Input('stacked') set stacked(stacked: boolean) { this._stacked = coerceBooleanProperty(stacked); } get stacked(): boolean { return this._stacked; } /** * inputPosition?: 'before' | 'after' * Set input position before or after the chips. * Defaults to 'after'. */ @Input('inputPosition') set inputPosition(inputPosition: 'before' | 'after') { this._inputPosition = inputPosition; } get inputPosition(): 'before' | 'after' { return this._inputPosition; } /** * requireMatch?: boolean * Blocks custom inputs and only allows selections from the autocomplete list. */ @Input('requireMatch') set requireMatch(requireMatch: boolean) { this._requireMatch = coerceBooleanProperty(requireMatch); } get requireMatch(): boolean { return this._requireMatch; } /** * required?: boolean * Value is set to true if at least one chip is needed * Defaults to false */ @Input('required') set required(required: boolean) { this._required = coerceBooleanProperty(required); } get required(): boolean { return this._required; } /** * chipAddition?: boolean * Disables the ability to add chips. When setting disabled as true, this will be overriden. * Defaults to true. */ @Input('chipAddition') set chipAddition(chipAddition: boolean) { this._chipAddition = chipAddition; this._toggleInput(); } get chipAddition(): boolean { return this._chipAddition; } /** * Checks if not in disabled state and if chipAddition is set to 'true' * States if a chip can be added and if the input is available */ get canAddChip(): boolean { return this.chipAddition && !this.disabled; } /** * chipRemoval?: boolean * Disables the ability to remove chips. If it doesn't exist chip remmoval defaults to true. * When setting disabled as true, this will be overriden to false. */ @Input('chipRemoval') set chipRemoval(chipRemoval: boolean) { this._chipRemoval = chipRemoval; } get chipRemoval(): boolean { return this._chipRemoval; } /** * Checks if not in disabled state and if chipRemoval is set to 'true' * States if a chip can be removed */ get canRemoveChip(): boolean { return this.chipRemoval && !this.disabled; } /** * returns the display placeholder */ get displayPlaceHolder(): string { if (!this.canAddChip) { return ''; } return this._required ? `${this.placeholder} *` : this.placeholder; } /** * placeholder?: string * Placeholder for the autocomplete input. */ @Input() placeholder: string; /** * debounce?: number * Debounce timeout between keypresses. Defaults to 200. */ @Input() debounce: number = 200; /** * color?: 'primary' | 'accent' | 'warn' * Sets the color for the input and focus/selected state of the chips. * Defaults to 'primary' */ @Input('color') set color(color: 'primary' | 'accent' | 'warn') { if (color) { this._renderer.removeClass(this._elementRef.nativeElement, 'mat-' + this._color); this._color = color; this._renderer.addClass(this._elementRef.nativeElement, 'mat-' + this._color); } } get color(): 'primary' | 'accent' | 'warn' { return this._color; } /** * add?: function * Method to be executed when a chip is added. * Sends chip value as event. */ @Output() add: EventEmitter<any> = new EventEmitter<any>(); /** * remove?: function * Method to be executed when a chip is removed. * Sends chip value as event. */ @Output() remove: EventEmitter<any> = new EventEmitter<any>(); /** * inputChange?: function * Method to be executed when the value in the autocomplete input changes. * Sends string value as event. */ @Output() inputChange: EventEmitter<string> = new EventEmitter<string>(); /** * chipFocus?: function * Method to be executed when a chip is focused. * Sends chip value as event. */ @Output() chipFocus: EventEmitter<any> = new EventEmitter<any>(); /** * blur?: function * Method to be executed when a chip is blurred. * Sends chip value as event. */ @Output() chipBlur: EventEmitter<any> = new EventEmitter<any>(); /** * Hostbinding to set the a11y of the TdChipsComponent depending on its state */ @HostBinding('attr.tabindex') get tabIndex(): number { return this.disabled ? -1 : this._tabIndex; } constructor( private _elementRef: ElementRef, private _renderer: Renderer2, @Optional() @Inject(DOCUMENT) private _document: any, _changeDetectorRef: ChangeDetectorRef, ) { super(_changeDetectorRef); this._renderer.addClass(this._elementRef.nativeElement, 'mat-' + this._color); } /** * compareWith? function * Function used to check whether a chip value already exists. * Defaults to strict equality comparison === */ @Input() compareWith: (o1: any, o2: any) => boolean = (o1: any, o2: any) => { return o1 === o2; }; /** * Listens to host focus event to act on it */ @HostListener('focus', ['$event']) focusListener(event: FocusEvent): void { // should only focus if its not via mousedown to prevent clashing with autocomplete if (!this._isMousedown) { this.focus(); } event.preventDefault(); } /** * Listens to host mousedown event to act on it */ @HostListener('mousedown', ['$event']) mousedownListener(event: FocusEvent): void { // sets a flag to know if there was a mousedown and then it returns it back to false this._isMousedown = true; timer() .toPromise() .then(() => { this._isMousedown = false; }); } /** * If clicking on :host or `td-chips-wrapper`, then we stop the click propagation so the autocomplete * doesnt close automatically. */ @HostListener('click', ['$event']) clickListener(event: Event): void { const clickTarget: HTMLElement = <HTMLElement>event.target; if (clickTarget === this._elementRef.nativeElement || clickTarget.className.indexOf('td-chips-wrapper') > -1) { this.focus(); event.preventDefault(); event.stopPropagation(); } } /** * Listens to host keydown event to act on it depending on the keypress */ @HostListener('keydown', ['$event']) keydownListener(event: KeyboardEvent): void { switch (event.keyCode) { case TAB: // if tabing out, then unfocus the component timer() .toPromise() .then(() => { this.removeFocusedState(); }); break; case ESCAPE: if (this._inputChild.focused) { this._nativeInput.nativeElement.blur(); this.removeFocusedState(); this._closeAutocomplete(); } else { this.focus(); } break; default: // default } } ngOnInit(): void { this._inputValueChangesSubs = this.inputControl.valueChanges .pipe(debounceTime(this.debounce)) .subscribe((value: string) => { this.inputChange.emit(value ? value : ''); }); this._changeDetectorRef.markForCheck(); } ngAfterViewInit(): void { this._watchOutsideClick(); this._changeDetectorRef.markForCheck(); } ngDoCheck(): void { // Throw onChange event only if array changes size. if (this.value && this.value.length !== this._length) { this._length = this.value.length; this.onChange(this.value); } } ngOnDestroy(): void { this._outsideClickSubs.unsubscribe(); this._inputValueChangesSubs.unsubscribe(); } _setInternalClick(): void { this._internalClick = true; } /** Method executed when the disabled value changes */ onDisabledChange(v: boolean): void { this._toggleInput(); } /** * Method that is executed when trying to create a new chip from the autocomplete. * It check if [requireMatch] is enabled, and tries to add the first active option * else if just adds the value thats on the input * returns 'true' if successful, 'false' if it fails. */ _handleAddChip(): boolean { let value: any; if (this.requireMatch) { const selectedOptions: MatOption[] = this._options.toArray().filter((option: MatOption) => { return option.active; }); if (selectedOptions.length > 0) { value = selectedOptions[0].value; selectedOptions[0].setInactiveStyles(); } if (!value) { return false; } } else { // if there is a selection, then use that // else use the input value as chip if (this._autocompleteTrigger.activeOption) { value = this._autocompleteTrigger.activeOption.value; this._autocompleteTrigger.activeOption.setInactiveStyles(); } else { value = this._inputChild.value; if (value.trim() === '') { return false; } } } return this.addChip(value); } /** * Method thats exectuted when trying to add a value as chip * returns 'true' if successful, 'false' if it fails. */ addChip(value: any): boolean { /** * add a debounce ms delay when reopening the autocomplete to give it time * to rerender the next list and at the correct spot */ this._closeAutocomplete(); timer(this.debounce) .toPromise() .then(() => { this.setFocusedState(); this._setFirstOptionActive(); this._openAutocomplete(); }); this.inputControl.setValue(''); // check if value is already part of the model if (this.value.findIndex((item: any) => this.compareWith(item, value)) > -1) { return false; } this.value.push(value); this.add.emit(value); this.onChange(this.value); this._changeDetectorRef.markForCheck(); return true; } /** * Method that is executed when trying to remove a chip. * returns 'true' if successful, 'false' if it fails. */ removeChip(index: number): boolean { const removedValues: any[] = this.value.splice(index, 1); if (removedValues.length === 0) { return false; } /** * Checks if deleting last single chip, to focus input afterwards * Else check if its not the last chip of the list to focus the next one. */ if (index === this._totalChips - 1 && index === 0) { this._inputChild.focus(); } else if (index < this._totalChips - 1) { this._focusChip(index + 1); } else if (index > 0) { this._focusChip(index - 1); } this.remove.emit(removedValues[0]); this.onChange(this.value); this.inputControl.setValue(''); this._changeDetectorRef.markForCheck(); return true; } /** * Sets blur of chip and sends out event */ _handleChipBlur(event: FocusEvent, value: any): void { this.chipBlur.emit(value); } /** * Sets focus of chip and sends out event */ _handleChipFocus(event: FocusEvent, value: any): void { this.setFocusedState(); this.chipFocus.emit(value); } _handleFocus(): boolean { this.setFocusedState(); this._setFirstOptionActive(); return true; } /** * Sets focus state of the component */ setFocusedState(): void { if (!this.disabled) { this._focused = true; this._tabIndex = -1; this._changeDetectorRef.markForCheck(); } } /** * Removes focus state of the component */ removeFocusedState(): void { this._focused = false; this._tabIndex = 0; this._changeDetectorRef.markForCheck(); } /** * Programmatically focus the input or first chip. Since its the component entry point * depending if a user can add or remove chips */ focus(): void { if (this.canAddChip) { this._inputChild.focus(); } else if (!this.disabled) { this._focusFirstChip(); } } /** * Passes relevant input key presses. */ _inputKeydown(event: KeyboardEvent): void { switch (event.keyCode) { case UP_ARROW: /** * Since the first item is highlighted on [requireMatch], we need to inactivate it * when pressing the up key */ if (this.requireMatch) { const length: number = this._options.length; if (length > 1 && this._options.toArray()[0].active && this._internalActivateOption) { this._options.toArray()[0].setInactiveStyles(); this._internalActivateOption = false; // prevent default window scrolling event.preventDefault(); } } break; case LEFT_ARROW: case DELETE: case BACKSPACE: this._closeAutocomplete(); /** Check to see if input is empty when pressing left arrow to move to the last chip */ if (!this._inputChild.value) { this._focusLastChip(); // prevent default window scrolling event.preventDefault(); } break; case RIGHT_ARROW: this._closeAutocomplete(); /** Check to see if input is empty when pressing right arrow to move to the first chip */ if (!this._inputChild.value) { this._focusFirstChip(); // prevent default window scrolling event.preventDefault(); } break; default: // default } } /** * Passes relevant chip key presses. */ _chipKeydown(event: KeyboardEvent, index: number): void { switch (event.keyCode) { case DELETE: case BACKSPACE: /** Check to see if we can delete a chip */ if (this.canRemoveChip) { this.removeChip(index); } break; case UP_ARROW: case LEFT_ARROW: /** * Check to see if left/down arrow was pressed while focusing the first chip to focus input next * Also check if input should be focused */ if (index === 0) { // only try to target input if pressing left if (this.canAddChip && event.keyCode === LEFT_ARROW) { this._inputChild.focus(); } else { this._focusLastChip(); } } else if (index > 0) { this._focusChip(index - 1); } // prevent default window scrolling event.preventDefault(); break; case DOWN_ARROW: case RIGHT_ARROW: /** * Check to see if right/up arrow was pressed while focusing the last chip to focus input next * Also check if input should be focused */ if (index === this._totalChips - 1) { // only try to target input if pressing right if (this.canAddChip && event.keyCode === RIGHT_ARROW) { this._inputChild.focus(); } else { this._focusFirstChip(); } } else if (index < this._totalChips - 1) { this._focusChip(index + 1); } // prevent default window scrolling event.preventDefault(); break; default: // default } } /** * Method to remove from display the value added from the autocomplete since it goes directly as chip. */ _removeInputDisplay(): string { return ''; } /** * Method to open the autocomplete manually if its not already opened */ _openAutocomplete(): void { if (!this._autocompleteTrigger.panelOpen) { this._autocompleteTrigger.openPanel(); this._changeDetectorRef.markForCheck(); } } /** * Method to close the autocomplete manually if its not already closed */ _closeAutocomplete(): void { if (this._autocompleteTrigger.panelOpen) { this._autocompleteTrigger.closePanel(); this._changeDetectorRef.markForCheck(); } } /** * Get total of chips */ get _totalChips(): number { const chips: MatChip[] = this._chipsChildren.toArray(); return chips.length; } /** * Method to focus a desired chip by index */ private _focusChip(index: number): void { /** check to see if index exists in the array before focusing */ if (index > -1 && this._totalChips > index) { this._chipsChildren.toArray()[index].focus(); } } /** Method to focus first chip */ private _focusFirstChip(): void { this._focusChip(0); } /** Method to focus last chip */ private _focusLastChip(): void { this._focusChip(this._totalChips - 1); } /** * Method to toggle the disable state of input * Checks if not in disabled state and if chipAddition is set to 'true' */ private _toggleInput(): void { if (this.canAddChip) { this.inputControl.enable(); } else { this.inputControl.disable(); } this._changeDetectorRef.markForCheck(); } /** * Sets first option as active to let the user know which one will be added when pressing enter * Only if [requireMatch] has been set */ private _setFirstOptionActive(): void { if (this.requireMatch) { // need to use a timer here to wait until the autocomplete has been opened (end of queue) timer() .toPromise() .then(() => { if (this.focused && this._options && this._options.length > 0) { // clean up of previously active options this._options.toArray().forEach((option: MatOption) => { option.setInactiveStyles(); }); // set the first one as active this._options.toArray()[0].setActiveStyles(); this._internalActivateOption = true; this._changeDetectorRef.markForCheck(); } }); } } /** * Watches clicks outside of the component to remove the focus * The autocomplete panel is considered inside the component so we * need to use a flag to find out when its clicked. */ private _watchOutsideClick(): void { if (this._document) { this._outsideClickSubs = merge(fromEvent(this._document, 'click'), fromEvent(this._document, 'touchend')) .pipe( debounceTime(this._touchendDebounce), filter((event: MouseEvent) => { const clickTarget: HTMLElement = <HTMLElement>event.target; setTimeout(() => { this._internalClick = false; }); return ( this.focused && clickTarget !== this._elementRef.nativeElement && !this._elementRef.nativeElement.contains(clickTarget) && !this._internalClick ); }), ) .subscribe(() => { if (this.focused) { this._autocompleteTrigger.closePanel(); this.removeFocusedState(); this.onTouched(); this._changeDetectorRef.markForCheck(); } }); } return undefined; } }
the_stack
import composeRefs from '@seznam/compose-react-refs'; import { Dispatch, ReactNode, Ref, SetStateAction } from 'react'; import { AnyExtension, ErrorConstant, Framework, FrameworkOptions, FrameworkProps, GetSchema, invariant, isArray, object, shouldUseDomEnvironment, STATE_OVERRIDE, UpdateStateProps, } from '@remirror/core'; import type { EditorState } from '@remirror/pm/state'; import type { EditorView } from '@remirror/pm/view'; import { ReactPlaceholderExtension } from '@remirror/preset-react'; import { createEditorView, RemirrorSSR } from '@remirror/react-ssr'; import { addKeyToElement } from '@remirror/react-utils'; import type { GetRootPropsConfig, ReactFrameworkOutput, RefKeyRootProps } from './react-types'; export class ReactFramework<Extension extends AnyExtension> extends Framework< Extension, ReactFrameworkProps<Extension>, ReactFrameworkOutput<Extension> > { /** * Whether to render the client immediately. */ #getShouldRenderClient: () => boolean | undefined; /** * Update the should render client state input. */ #setShouldRenderClient: SetShouldRenderClient; /** * Stores the Prosemirror EditorView dom element. */ #editorRef?: HTMLElement; /** * Used when suppressHydrationWarning is true to determine when it's okay to * render the client content. */ private get shouldRenderClient(): boolean | undefined { return this.#getShouldRenderClient(); } /** * Keep track of whether the get root props has been called during the most recent render. */ private rootPropsConfig = { called: false, count: 0, }; get name() { return 'react' as const; } constructor(props: ReactFrameworkOptions<Extension>) { super(props); const { getShouldRenderClient, setShouldRenderClient } = props; this.#getShouldRenderClient = getShouldRenderClient; this.#setShouldRenderClient = setShouldRenderClient; if (this.manager.view) { this.manager.view.setProps({ state: this.manager.view.state, dispatchTransaction: this.dispatchTransaction, attributes: () => this.getAttributes(), editable: () => this.props.editable ?? true, }); return; } this.manager .getExtension(ReactPlaceholderExtension) .setOptions({ placeholder: this.props.placeholder ?? '' }); } /** * This is called to update props on every render so that values don't become stale. */ update(props: ReactFrameworkOptions<Extension>): this { super.update(props); const { getShouldRenderClient, setShouldRenderClient } = props; this.#getShouldRenderClient = getShouldRenderClient; this.#setShouldRenderClient = setShouldRenderClient; return this; } /** * Create the prosemirror editor view. */ protected createView(state: EditorState<GetSchema<Extension>>): EditorView<GetSchema<Extension>> { return createEditorView<GetSchema<Extension>>( undefined, { state, dispatchTransaction: this.dispatchTransaction, attributes: () => this.getAttributes(), editable: () => this.props.editable ?? true, }, this.manager.settings.forceEnvironment, ); } /** * The external `getRootProps` that is used to spread props onto a desired * holder element for the prosemirror view. */ private readonly getRootProps = <RefKey extends string = 'ref'>( options?: GetRootPropsConfig<RefKey>, ) => { return this.internalGetRootProps(options, null); }; /** * Creates the props that should be spread on the root element inside which * the prosemirror instance will be rendered. * * TODO - this is useless - REFACTOR */ private readonly internalGetRootProps = <RefKey extends string = 'ref'>( options?: GetRootPropsConfig<RefKey>, children?: ReactNode, ): RefKeyRootProps<RefKey> => { // Ensure that this is the first time `getRootProps` is being called during // this commit phase of the . // invariant(!this.rootPropsConfig.called, { code: ErrorConstant.REACT_GET_ROOT_PROPS }); this.rootPropsConfig.called = true; const { refKey: refKey = 'ref', ref, ...config } = options ?? object<GetRootPropsConfig<RefKey>>(); return { [refKey]: composeRefs(ref as Ref<HTMLElement>, this.onRef), key: this.uid, ...config, children: this.renderChildren(children), } as any; }; /** * Stores the Prosemirror editor dom instance for this component using `refs`. */ private readonly onRef: Ref<HTMLElement> = (element) => { if (!element) { return; } this.rootPropsConfig.count += 1; invariant(this.rootPropsConfig.count <= 1, { code: ErrorConstant.REACT_GET_ROOT_PROPS, message: `Called ${this.rootPropsConfig.count} times`, }); this.#editorRef = element; this.onRefLoad(); }; /** * Updates the state either by calling `onChange` when it exists or * directly setting the internal state via a `setState` call. */ protected updateState({ state, ...rest }: UpdateStateProps<GetSchema<Extension>>): void { const { triggerChange = true, tr, transactions } = rest; if (this.props.state) { const { onChange } = this.props; invariant(onChange, { code: ErrorConstant.REACT_CONTROLLED, message: 'You are required to provide the `onChange` handler when creating a controlled editor.', }); invariant(triggerChange, { code: ErrorConstant.REACT_CONTROLLED, message: 'Controlled editors do not support `clearContent` or `setContent` where `triggerChange` is `true`. Update the `state` prop instead.', }); if (!this.previousStateOverride) { this.previousStateOverride = this.getState(); } this.onChange({ state, tr }); return; } // Check if this is a fresh update directly applied by the developer (without // transactions or commands). if (!tr && !transactions) { state = state.apply(state.tr.setMeta(STATE_OVERRIDE, {})); } // Update the internal prosemirror state. This happens before we update // the component's copy of the state. this.view.updateState(state); if (triggerChange) { // Update the `onChange` handler before notifying the manager but only when a change should be triggered. this.onChange({ state, tr }); } this.manager.onStateUpdate({ previousState: this.previousState, state, tr, transactions }); } /** * Update the controlled state when the value changes and notify the extension * of this update. */ updateControlledState( state: EditorState<GetSchema<Extension>>, previousState?: EditorState<GetSchema<Extension>>, ): void { this.previousStateOverride = previousState; // Mark this as a state override so that extensions and plugins know to // ignore the transaction. state = state.apply(state.tr.setMeta(STATE_OVERRIDE, {})); this.view.updateState(state); this.manager.onStateUpdate({ previousState: this.previousState, state }); this.previousStateOverride = undefined; } /** * Adds the prosemirror view to the dom in the position specified via the * component props. */ private addProsemirrorViewToDom(element: HTMLElement, viewDom: Element) { if (this.props.insertPosition === 'start') { element.insertBefore(viewDom, element.firstChild); } else { element.append(viewDom); } } /** * Called once the container dom node (`this.editorRef`) has been initialized * after the component mounts. * * This method handles the cases where the dom is not focused. */ private onRefLoad() { invariant(this.#editorRef, { code: ErrorConstant.REACT_EDITOR_VIEW, message: 'Something went wrong when initializing the text editor. Please check your setup.', }); const { autoFocus } = this.props; this.addProsemirrorViewToDom(this.#editorRef, this.view.dom); if (autoFocus) { this.focus(autoFocus); } this.onChange(); this.addFocusListeners(); } onMount(): void { const { suppressHydrationWarning } = this.props; if (suppressHydrationWarning) { this.#setShouldRenderClient(true); } } /** * Called for every update of the props and state. */ onUpdate(): void { // Ensure that `children` is still a render prop // propIsFunction(this.props.children); // Check whether the editable prop has been updated if (this.view && this.#editorRef) { this.view.setProps({ ...this.view.props, editable: () => this.props.editable ?? true }); } } /** * Get the framework output. */ get frameworkOutput(): ReactFrameworkOutput<Extension> { return { ...this.baseOutput, getRootProps: this.getRootProps, portalContainer: this.manager.store.portalContainer, renderSsr: this.renderSsr, }; } /** * Checks whether this is an SSR environment and returns a child array with * the SSR component * * @param children * * TODO - this is useless and should be refactored. */ private renderChildren(child: ReactNode = null) { const { insertPosition = 'end', suppressHydrationWarning } = this.props; const children = isArray(child) ? child : [child]; if ( shouldUseDomEnvironment(this.manager.settings.forceEnvironment) && (!suppressHydrationWarning || this.shouldRenderClient) ) { return children; } const ssrElement = this.renderSsr(); return (insertPosition === 'start' ? [ssrElement, ...children] : [...children, ssrElement]).map( addKeyToElement, ); } /** * Return a JSX Element to be used within the ssr rendering phase. */ renderSsr = (): ReactNode => { const { suppressHydrationWarning, editable } = this.props; if ( shouldUseDomEnvironment(this.manager.settings.forceEnvironment) && (!suppressHydrationWarning || this.shouldRenderClient) ) { return null; } return ( <RemirrorSSR attributes={this.getAttributes(true)} state={this.getState()} manager={this.manager} editable={editable ?? true} /> ); }; /** * Reset the called status of `getRootProps`. */ resetRender(): void { // Reset the status of roots props being called this.rootPropsConfig.called = false; this.rootPropsConfig.count = 0; } } export interface ReactFrameworkProps<Extension extends AnyExtension> extends FrameworkProps<Extension> { /** * When `onChange` is defined this prop is used to set the next editor * state value of the Editor. The value is an instance of the **ProseMirror** * [[`EditorState`]]. * * @remarks * * When this is provided the editor becomes a controlled component. Nothing * will be updated unless you explicitly set the value prop to the updated * state. * * Be careful not to set and unset the value as this will trigger an error. * * When the Editor is set to be controlled there are a number of things to be * aware of. * * - **The last dispatch wins** - Calling multiple dispatches synchronously * during an update is no longer possible since each dispatch needs to be * processed within the `onChange` handler and updated via `setState` call. * Only the most recent call is updated. * - **Use chained commands** - These can help resolve the above limitation * for handling multiple updates. */ state?: EditorState<GetSchema<Extension>> | null; /** * Set to true to ignore the hydration warning for a mismatch between the * rendered server and client content. * * @remarks * * This is a potential solution for those who require server side rendering. * * While on the server the prosemirror document is transformed into a react * component so that it can be rendered. The moment it enters the DOM * environment prosemirror takes over control of the root element. The problem * is that this will always see this hydration warning on the client: * * `Warning: Did not expect server HTML to contain a <div> in <div>.` * * Setting this to true removes the warning at the cost of a slightly slower * start up time. It uses the two pass solution mentioned in the react docs. * See {@link https://reactjs.org/docs/react-dom.html#hydrate}. * * For ease of use this prop copies the name used by react for DOM Elements. * See {@link * https://reactjs.org/docs/dom-elements.html#suppresshydrationwarning. */ suppressHydrationWarning?: boolean; /** * Determine whether the Prosemirror view is inserted at the `start` or `end` * of it's container DOM element. * * @default 'end' */ insertPosition?: 'start' | 'end'; /** * The placeholder to set for the editor. */ placeholder?: string; } /** * The options that are passed into the [[`ReactFramework`]] constructor. */ export interface ReactFrameworkOptions<Extension extends AnyExtension> extends FrameworkOptions<Extension, ReactFrameworkProps<Extension>> { getShouldRenderClient: () => boolean | undefined; setShouldRenderClient: SetShouldRenderClient; } export type SetShouldRenderClient = Dispatch<SetStateAction<boolean | undefined>>;
the_stack
import { InputController, KeyMappings } from "./input_controller"; import { Nes } from "./nes"; declare var rivets, $, NoSleep, toastr, compiler, Diff, saveAs; export class Rom { name: string = ''; url: string = ''; } //this is a good technique //so i don't need to keep casting from window.app var app: MyApp; export class MyApp { inputController: InputController; rom_name: string = ''; canvasSize: number = 400; lblStatus: string = ''; mobileMode: boolean = false; platform: string = ''; useragent: string = ''; dblist: string[] = []; remapDefault = true; remapWait = false; romList: Rom[] = []; audioContext: AudioContext; nes: Nes; chkDebugChecked = false; chkSound = true; romdevMode = false; lblCompiler = ''; smbMode = true; constructor() { try { this.platform = navigator.platform.toLocaleLowerCase(); this.useragent = navigator.userAgent.toLocaleLowerCase(); } catch (err) { console.log('could not detect platform'); } document.getElementById('file-upload').addEventListener('change', this.uploadRom.bind(this)); this.nes = new Nes(); this.createDB(); this.initRivets(); this.detectMobile(); this.calculateInitialHeight(); this.setHeight(); this.finishedLoading(); } runUnitTests(): boolean { let testsPassed = true; let result = 0; //test0 result = this.nes.memory.ram[0x400] console.log('test0 result: ' + result); if (result != 2) { console.log('test0 failed'); testsPassed = false; } //test1 result = this.nes.memory.ram[0x401] console.log('test1 result: ' + result); if (result != 0x20) { console.log('test1 failed'); testsPassed = false; } //test2 result = this.nes.memory.ram[0x402] console.log('test2 result: ' + result); if (result != 0x14) { console.log('test2 failed'); testsPassed = false; } //test3 result = this.nes.memory.ram[0x403] console.log('test3 result: ' + result); if (result != 14) { console.log('test3 failed'); testsPassed = false; } //test4 result = this.nes.memory.ram[0x404] console.log('test4 result: ' + result); if (result != 30) { console.log('test4 failed'); testsPassed = false; } //test5 result = this.nes.memory.ram[0x405] console.log('test5 result: ' + result); if (result != 0x12) { console.log('test5 failed'); testsPassed = false; } //test 6 result = this.nes.memory.ram[0x406] console.log('test6 result: ' + result); if (result != 0x92) { console.log('test6 failed'); testsPassed = false; } //test 7 result = this.nes.memory.ram[0x407] console.log('test7 result: ' + result); if (result != 0x84) { console.log('test7 failed'); testsPassed = false; } //test 8 result = this.nes.memory.ram[0x408] console.log('test8 result: ' + result); if (result != 0x23) { console.log('test8 failed'); testsPassed = false; } //test 9 result = this.nes.memory.ram[0x409] console.log('test9 result: ' + result); if (result != 0x14) { console.log('test9 failed'); testsPassed = false; } //test 10 result = this.nes.memory.ram[0x40A] console.log('test10 result: ' + result); if (result != 0x15) { console.log('test10 failed'); testsPassed = false; } //test 11 result = this.nes.memory.ram[0x40B] console.log('test11 result: ' + result); if (result != 0x0D) { console.log('test11 failed'); testsPassed = false; } //test 12 result = this.nes.memory.ram[0x40C] console.log('test12 result: ' + result); if (result != 0x14) { console.log('test12 failed'); testsPassed = false; } //test 13 result = this.nes.memory.ram[0x40D] console.log('test13 result: ' + result); if (result != 0x40) { console.log('test13 failed'); testsPassed = false; } //test 14 result = this.nes.memory.ram[0x40E] console.log('test14 result: ' + result); if (result != 3) { console.log('test14 failed'); testsPassed = false; } //test 15 result = this.nes.memory.ram[0x40F] console.log('test15 result: ' + result); if (result != 0x15) { console.log('test15 failed'); testsPassed = false; } //test 16 result = this.nes.memory.ram[0x410] console.log('test16 result: ' + result); if (result != 0x40) { console.log('test16 failed'); testsPassed = false; } //test 17 result = this.nes.memory.ram[0x411] console.log('test17 result: ' + result); if (result != 4) { console.log('test17 failed'); testsPassed = false; } //test 18 result = this.nes.memory.ram[0x412] console.log('test18 result: ' + result); if (result != 0x1B) { console.log('test18 failed'); testsPassed = false; } //test 19 result = this.nes.memory.ram[0x413] console.log('test19 result: ' + result); if (result != 9) { console.log('test19 failed'); testsPassed = false; } //test 20 result = this.nes.memory.ram[0x414] console.log('test20 result: ' + result); if (result != 0x80) { console.log('test20 failed'); testsPassed = false; } //test 21 result = this.nes.memory.ram[0x415] console.log('test21 result: ' + result); if (result != 0x80) { console.log('test21 failed'); testsPassed = false; } //test 22 result = this.nes.memory.ram[0x416] console.log('test22 result: ' + result); if (result != 0x40) { console.log('test22 failed'); testsPassed = false; } //test 23 result = this.nes.memory.ram[0x417] console.log('test23 result: ' + result); if (result != 0x40) { console.log('test23 failed'); testsPassed = false; } //test 24 result = this.nes.memory.ram[0x418] console.log('test24 result: ' + result); if (result != 0x2C) { console.log('test24 failed'); testsPassed = false; } //test 25 result = this.nes.memory.ram[0x419] console.log('test25 result: ' + result); if (result != 0x12) { console.log('test25 failed'); testsPassed = false; } //test 26 result = this.nes.memory.ram[0x41A] console.log('test26 result: ' + result); if (result != 0x12) { console.log('test26 failed'); testsPassed = false; } //test 27 result = this.nes.memory.ram[0x41B] console.log('test27 result: ' + result); if (result != 17) { console.log('test27 failed'); testsPassed = false; } //test 28 result = this.nes.memory.ram[0x41C] console.log('test28 result: ' + result); if (result != 2) { console.log('test28 failed'); testsPassed = false; } //test 29 result = this.nes.memory.ram[0x41D] console.log('test29 result: ' + result); if (result != 0x40) { console.log('test29 failed'); testsPassed = false; } //test 30 result = this.nes.memory.ram[0x41E] console.log('test30 result: ' + result); if (result != 0x7) { console.log('test30 failed'); testsPassed = false; } return testsPassed; } saveASM() { localStorage.setItem('nes-compiler-asm', window["myEditor"].getValue()); toastr.success("ASM Saved"); } clearASM() { localStorage.removeItem('nes-compiler-asm'); // toastr.success("ASM Cleared"); this.newRom(); } originalSrc:string = ''; newSrc:string = ''; initialLoad() { this.configEmulator(); this.rom_name = 'app.nes'; this.logApp(); this.hideShowExportButton(); if (this.smbMode){ $.get('source/disassembly.asm', (data) => { window["myEditor"].setValue(data); this.originalSrc = data; this.compile(); }) }else{ $.get('source/myasm.asm', (data) => { window["myEditor"].setValue(data); this.originalSrc = data; this.compile(); }) } } hideShowExportButton(){ if (this.nes.cartridge.smbChecksPassed){ // $("#btnExport").show(); } } myasmSRC(){ $.get('source/myasm.asm', (data) => { window["myEditor"].setValue(data); this.compile(); }) } marioSRC(){ $.get('source/disassembly.asm', (data) => { window["myEditor"].setValue(data); this.compile(); }) } nesLoaded: boolean = false; compile() { try { let compiled_data = ''; let asm_code = window["myEditor"].getValue(); compiled_data = compiler.nes_compiler(asm_code); this.newSrc = asm_code; if (this.nesLoaded == false) { app.nes_load_upload('canvas', compiled_data); this.nesLoaded = true; } else { //compile was successful app.nes.reload_rom_data = compiled_data; app.nes.reloadState(); if (this.nes.PAUSED) { if (this.chkSound) this.nes.apu.unMuteAll(); this.nes.PAUSED = false; } if (this.mobileMode) this.btnHideMenu(); } app.lblCompiler = ''; $("#lblCompiler").hide(); } catch (error) { //TODO show number of errors console.log('an error'); var errorString = ''; error.forEach(err => { try { if (err.children == null) { var lineNumber = err.line; errorString += '<b>Line: ' + lineNumber + ' - </b> ' + JSON.stringify(err) + '<br>'; } else { var lineNumber = err.children[0].line; errorString += '<b>Line: ' + lineNumber + ' - </b> ' + JSON.stringify(err) + '<br>'; } } catch (error2) { errorString += '<b>No Line Number - </b> ' + JSON.stringify(err) + '<br>'; } }); errorString += '<br><b>' + error.length + ' ERROR'; if (error.length > 1) errorString += 'S'; errorString += '</b>' app.lblCompiler = errorString; $("#lblCompiler").show(); this.nes.PAUSED = true; } } getDiffs():any[] { var alldiffs = []; if (this.newSrc.length<600000) return alldiffs; try { var diffs = Diff.diffLines(this.originalSrc, this.newSrc); let linecounter = 1; for (let i = 0; i < diffs.length; i++) { let diff = diffs[i]; if (diff.removed) { let newDiff = { status: 'removed', value: diff.value, line: linecounter }; alldiffs.push(newDiff); } else if (diff.added) { let newDiff = { status: 'added', value: diff.value, line: linecounter }; alldiffs.push(newDiff); linecounter += diff.count; } else { linecounter += diff.count; } } } catch (error) { } return alldiffs; } min_height: number = 400; height: number = 0; calculateInitialHeight() { this.height = window.innerHeight - 300; if (this.height < this.min_height) this.height = this.min_height; } setHeight() { document.getElementById('monContainer').style['min-height'] = this.height + 'px'; document.getElementById('monContainer').style['max-height'] = this.height + 'px'; } initRivets() { //init rivets rivets.formatters.ev = function (value, arg) { // console.log('eval: ' + value + arg); return eval(value + arg); } rivets.formatters.ev_string = function (value, arg) { let eval_string = "'" + value + "'" + arg; // console.log('eval: ' + eval_string); return eval(eval_string); } rivets.bind(document.getElementsByTagName('body')[0], { data: this }); } saveState() { app.nes.saveState(); if (this.mobileMode) this.btnHideMenu(); } loadState() { app.nes.loadState(); if (this.mobileMode) this.btnHideMenu(); } finishedLoading() { $('#loadingDiv').hide(); $('#btnSampleCode').prop("disabled", false); $('#btnUploadRom').prop("disabled", false); } //needs to be called after //user input or button click getAudioContext() { console.log('getting audio context'); try { this.audioContext = new AudioContext(); } catch (error) { try { //try for mobile this.audioContext = new window['webkitAudioContext'](); (this.audioContext as AudioContext).resume(); console.log('found mobile audio'); //disable phone locking on mobile devices // app.lblStatus = 'No Sleep Enabled'; } catch (error2) { console.log('could not initialize audio'); } } if (this.mobileMode) { var noSleep = new NoSleep(); noSleep.enable(); } // if (this.chkSound) { this.enableSound(); // } } enableSound() { this.nes.apu.unMuteAll(); this.nes.apu.initialize(this.audioContext); } detectMobile() { if (window.innerWidth < 600 || this.useragent.includes('iphone') || this.useragent.includes('ipad') || this.useragent.includes('android')) { this.mobileMode = true; } //on second thought if it's a big //screen then don't do mobile mode if (window.innerWidth > 600) this.mobileMode = false; } configEmulator() { this.getAudioContext(); if (this.chkDebugChecked) this.mobileMode = false; } uploadBrowse() { document.getElementById('file-upload').click(); } configureEditor(){ $('#divMonOuter').show(); $('#hideAfterLoad').hide(); // $('#githubLink2').show(); require(["compiler/compiler"],function(){ window["myApp"].nes.PAUSED = false; if (window["myApp"].mobileMode) { document.getElementById('divMonOuter').classList.replace("col-sm-8","col-sm-12") } require(['vs/editor/editor.main'], function (monaco) { var options:any = {}; options.value = "Loading..."; options.language = 'scheme'; options.theme = 'vs-light'; options.automaticLayout = true; options.mouseWheelZoom = true; window["myEditor"] = monaco.editor.create(document.getElementById('monContainer'), options); window["myEditor"].addCommand(monaco.KeyMod.CtrlCmd | monaco.KeyCode.KEY_S, function(){ window["myApp"].compile(); }); window["myEditor"].addCommand(monaco.KeyMod.CtrlCmd | monaco.KeyCode.KEY_P, function(){ window["myApp"].btnPause(); }); window["myApp"].initialLoad(); }); }); } useTestRom(){ this.smbMode = false; try { //scroll back to top document.body.scrollTop = 0; // For Safari document.documentElement.scrollTop = 0; // For Chrome, Firefox, IE and Opera }catch(error){} app.configureEditor(); } fileSize = 0; uploadRom(event: Event) { this.lblStatus = 'Uploading...'; var file = (event.currentTarget as any).files[0] as File; console.log(file); this.rom_name = file.name; var reader = new FileReader(); reader.onprogress = function (e) { console.log('loaded: ' + e.loaded); }; reader.onload = function (e) { console.log('finished loading'); app.lblStatus = ''; app.nes.cartridge.loadChr(this.result as string); app.smbMode = true; app.fileSize = (this.result as string).length; app.configureEditor(); // app.nes_load_upload('canvas', this.result); // let romString = this.result as string; // var ia = new TextEncoder().encode(romString); // app.saveToDatabase(ia); }; // reader.readAsArrayBuffer(file); reader.readAsBinaryString(file) } saveToDatabase(data: Uint8Array) { if (!window["indexedDB"] == undefined) { console.log('indexedDB not available'); return; } console.log('save to database called: ', data.length); var request = indexedDB.open('NeilNESDB'); request.onsuccess = function (ev: any) { var db = ev.target.result as IDBDatabase; var romStore = db.transaction("NESROMS", "readwrite").objectStore("NESROMS"); var addRequest = romStore.put(data, app.rom_name); addRequest.onsuccess = function (event) { console.log('data added'); }; addRequest.onerror = function (event) { console.log('error adding data'); console.log(event); }; } } clearDatabase() { var request = indexedDB.deleteDatabase('NeilNESDB'); request.onerror = function (event) { console.log("Error deleting database."); app.lblStatus = "Error deleting database."; }; request.onsuccess = function (event) { console.log("Database deleted successfully"); app.lblStatus = "Database deleted successfully"; app.newRom(); }; } newRom() { window.location.reload(); } showCanvasAndInput() { //hide controls no longer needed $('#showAfterLoad').show(); //height of most games // this.canvas.height=224; if (this.mobileMode) { $("#mobileDiv").show(); $('#canvas').width(window.innerWidth); $('#canvas').appendTo("#mobileCanvas"); if (this.nes.DEBUGMODE) $('#debugpanel').appendTo("#mobileCanvas"); $("#mainCard").hide(); $("#mainContainer").hide(); $("#btnFullScreen").hide(); $("#btnRemap").hide(); // $("#divZoom").hide(); $("#btnHidePanel").show(); $("#btnTurboButtons").show(); let halfWidth = (window.innerWidth / 2) - 35; document.getElementById("menuDiv").style.left = halfWidth + "px"; this.inputController = new InputController('divTouchSurface'); // if (this.nes.DEBUGMODE == false) { // document.getElementById('canvas').addEventListener('touchstart', function (e) { e.preventDefault(); }, false); // document.getElementById('canvas').addEventListener('touchend', function (e) { e.preventDefault(); }, false); // document.getElementById('canvas').addEventListener('touchmove', function (e) { e.preventDefault(); }, false); // } } else { this.inputController = new InputController('canvas'); let size = localStorage.getItem('nes-size'); if (size) { console.log('size found'); let sizeNum = parseInt(size); this.canvasSize = sizeNum; } this.resizeCanvas(); } //try to load keymappings from localstorage try { let keymappings = localStorage.getItem('nes_mappings'); if (keymappings) { let keymappings_object = JSON.parse(keymappings); //check that it's not the old mappings file if (keymappings_object.Joy_Mapping_Action_Start) keymappings = keymappings_object; } } catch (error) { } this.inputController.setupGamePad(); this.inputController.loop(); this.nes.inputController = this.inputController; $("#loadingDiv2").hide(); $('#mainCard').css("visibility", "visible"); } logApp(){ if (document.location.href.toLocaleLowerCase().indexOf('neilb.net')>1) { let referrer = document.referrer; if(referrer==null || referrer=="") referrer = "NONE"; let mode = 'smb'; if (this.smbMode==false) mode = 'myasm'; let stats = 'Filesize: ' + this.fileSize; $.get('https://neilb.net/tetrisjsbackend/api/compiler/addmariocompiler?mode=' + mode + '&stats=' + stats + '&referrer=' + referrer); } } frameLimiter() { if (this.nes.fps_controller.frame_limiter_enabled) this.nes.fps_controller.frame_limiter_enabled = false; else this.nes.fps_controller.frame_limiter_enabled = true; } canvasDebugSize = 400; canvasDebugClick() { if (this.canvasDebugSize == 400) this.canvasDebugSize = 600; else this.canvasDebugSize = 400; $('#canvasDebug').width(this.canvasDebugSize); } btnTurboButtons() { if (this.nes.inputController.TurboButtons) this.nes.inputController.TurboButtons = false; else this.nes.inputController.TurboButtons = true; this.btnHideMenu(); } btnMemPrev() { this.nes.debugMemPage -= 256; } btnMemNext() { this.nes.debugMemPage += 256; } btnPause() { if (this.nes.PAUSED) { if (this.chkSound) this.nes.apu.unMuteAll(); this.nes.PAUSED = false; } else { if (this.chkSound) this.nes.apu.muteAll(); this.nes.PAUSED = true; } } export(){ let asm_code = window["myEditor"].getValue(); var compiled_data = compiler.nes_compiler(asm_code); var filearray = new Uint8Array(compiled_data.length + this.nes.cartridge.chrData.length); //prg data for(let i = 0;i<compiled_data.length;i++) { filearray[i] = compiled_data.charCodeAt(i) & 0xff; } //chr data for(let i = 0;i<this.nes.cartridge.chrData.length;i++) { filearray[compiled_data.length + i] = this.nes.cartridge.chrData[i]; } //microsoft edge fix if (navigator.msSaveBlob){ console.log('ms edge save'); var blob = new Blob([filearray],{type: "text/plain; charset=x-user-defined"}); (blob as any).name = "export.nes"; (blob as any).lastModifiedDate = new Date; saveAs(blob); }else{ var file = new File([filearray], "export.nes", {type: "text/plain; charset=x-user-defined"}); saveAs(file); } if (document.location.href.toLocaleLowerCase().indexOf('neilb.net')>1){ var stats = 'Filesize: ' + filearray.length; $.get('https://neilb.net/tetrisjsbackend/api/compiler/addmariocompiler?mode=export&stats=' + stats + '&referrer=NONE'); } } fullScreen() { // if (this.nes.DEBUGMODE) // this.nes.canvasDebug.requestFullscreen(); // else this.nes.canvas.requestFullscreen(); } resizeCanvas() { console.log('canvas resized'); $('#canvas').width(this.canvasSize); // $('#canvasDebug').width(this.canvasSize); } btnHideMenu() { $('#mainContainer').hide(); $('#menuDiv').show(); } zoomOut() { this.canvasSize -= 50; localStorage.setItem('nes-size', this.canvasSize.toString()); this.resizeCanvas(); } zoomIn() { this.canvasSize += 50; localStorage.setItem('nes-size', this.canvasSize.toString()); this.resizeCanvas(); } pressStart() { app.nes.inputController.Key_Action_Start = true; setTimeout(() => { app.nes.inputController.Key_Action_Start = false; }, 300); } square1Enable() { if (this.nes.apu.square1.enabled) this.nes.apu.square1.disable(); else this.nes.apu.square1.enable(); } square2Enable() { if (this.nes.apu.square2.enabled) this.nes.apu.square2.disable(); else this.nes.apu.square2.enable(); } triangleEnable() { if (this.nes.apu.triangle.enabled) this.nes.apu.triangle.disable(); else this.nes.apu.triangle.enable(); } noiseEnable() { if (this.nes.apu.noise.enabled) this.nes.apu.noise.disable(); else this.nes.apu.noise.enable(); } soundStats() { if (this.nes.debugSoundMode) this.nes.debugSoundMode = false; else this.nes.debugSoundMode = true; } recMusic() { if (this.nes.recordMusicMode == false) this.nes.startRecordingMusic(); else this.nes.stopRecordingMusic(); } stopRec() { this.nes.stopRecordingMusic(); } playRec() { if (this.nes.playBackMusicMode == false) this.nes.playRecordedMusic(); else this.nes.stopPlaybackMusic(); } createDB() { if (window["indexedDB"] == undefined) { console.log('indexedDB not available'); return; } var request = indexedDB.open('NeilNESDB'); request.onupgradeneeded = function (ev: any) { console.log('upgrade needed'); let db = ev.target.result as IDBDatabase; let objectStore = db.createObjectStore('NESROMS', { autoIncrement: true }); objectStore.transaction.oncomplete = function (event) { console.log('db created'); }; } request.onsuccess = function (ev: any) { var db = ev.target.result as IDBDatabase; var romStore = db.transaction("NESROMS", "readwrite").objectStore("NESROMS"); try { //rewrote using cursor instead of getAllKeys //for compatibility with MS EDGE romStore.openCursor().onsuccess = function (ev: any) { var cursor = ev.target.result as IDBCursor; if (cursor) { let rom = cursor.key.toString(); if (!rom.endsWith('sav')) app.dblist.push(rom); cursor.continue(); } else { if (app.dblist.length > 0) { // let romselect = document.getElementById('dbselect') as HTMLSelectElement; // romselect.selectedIndex = 0; // $('#dbContainer').show(); // $('#btnLoadDB').show(); } } } } catch (error) { console.log('error reading keys'); console.log(error); } } } btnDebugViewChr() { this.nes.SCREEN_DEBUG.clearScreen(); this.nes.debug_view_chr = true; this.nes.debug_view_nametable = false; } btnDebugViewNametable() { this.nes.SCREEN_DEBUG.clearScreen(); this.nes.debug_view_chr = false; this.nes.debug_view_nametable = true; } btnSwapNametable() { if (this.nes.debugNametable == 0) this.nes.debugNametable = 1; else this.nes.debugNametable = 0; } btnDisableSprites() { if (this.nes.debugDisableSprites) this.nes.debugDisableSprites = false; else this.nes.debugDisableSprites = true; } remappings: KeyMappings; remapMode = ''; currKey: number; currJoy: number; chkUseJoypad = false; showRemapModal() { if (this.inputController.Gamepad_Process_Axis) // (document.getElementById('chkUseJoypad') as any).checked = true; this.chkUseJoypad = true; this.remappings = JSON.parse(JSON.stringify(this.inputController.KeyMappings)); this.remapDefault = true; this.remapWait = false; $("#buttonsModal").modal(); } saveRemap() { // if ((document.getElementById('chkUseJoypad') as any).checked) if (this.chkUseJoypad) this.inputController.Gamepad_Process_Axis = true; else this.inputController.Gamepad_Process_Axis = false; this.inputController.KeyMappings = JSON.parse(JSON.stringify(this.remappings)); this.inputController.setGamePadButtons(); localStorage.setItem('nes_mappings', JSON.stringify(this.remappings)); $("#buttonsModal").modal('hide'); } btnRemapKey(keynum: number) { this.currKey = keynum; this.remapMode = 'Key'; this.readyRemap(); } btnRemapJoy(joynum: number) { this.currJoy = joynum; this.remapMode = 'Button'; this.readyRemap(); } readyRemap() { this.remapDefault = false; this.remapWait = true; this.inputController.Key_Last = ''; this.inputController.Joy_Last = null; this.inputController.Remap_Check = true; } remapPressed() { if (this.remapMode == 'Key') { var keyLast = this.inputController.Key_Last; if (this.currKey == 1) this.remappings.Mapping_Up = keyLast; if (this.currKey == 2) this.remappings.Mapping_Down = keyLast; if (this.currKey == 3) this.remappings.Mapping_Left = keyLast; if (this.currKey == 4) this.remappings.Mapping_Right = keyLast; if (this.currKey == 5) this.remappings.Mapping_Action_A = keyLast; if (this.currKey == 6) this.remappings.Mapping_Action_B = keyLast; if (this.currKey == 8) this.remappings.Mapping_Action_Start = keyLast; if (this.currKey == 7) this.remappings.Mapping_Action_Select = keyLast; } if (this.remapMode == 'Button') { var joyLast = this.inputController.Joy_Last; if (this.currJoy == 1) this.remappings.Joy_Mapping_Up = joyLast; if (this.currJoy == 2) this.remappings.Joy_Mapping_Down = joyLast; if (this.currJoy == 3) this.remappings.Joy_Mapping_Left = joyLast; if (this.currJoy == 4) this.remappings.Joy_Mapping_Right = joyLast; if (this.currJoy == 5) this.remappings.Joy_Mapping_Action_A = joyLast; if (this.currJoy == 6) this.remappings.Joy_Mapping_Action_B = joyLast; if (this.currJoy == 8) this.remappings.Joy_Mapping_Action_Start = joyLast; if (this.currJoy == 7) this.remappings.Joy_Mapping_Action_Select = joyLast; } this.remapDefault = true; this.remapWait = false; } nes_init() { if (this.chkDebugChecked) app.nes.DEBUGMODE = true; else app.nes.DEBUGMODE = false; app.nes.initCanvases(); } onAnimationFrame() { window.requestAnimationFrame(app.onAnimationFrame); //run a single frame app.nes.frame(); } nes_boot(rom_data) { app.showCanvasAndInput(); app.nes.loadROM(rom_data, this.rom_name); window.requestAnimationFrame(app.onAnimationFrame); } nes_load_upload(canvas_id, rom_data) { app.nes_init(); app.nes_boot(rom_data); } nes_load_url(canvas_id, path) { app.nes_init(); console.log('loading ' + path); var req = new XMLHttpRequest(); req.open("GET", path); req.overrideMimeType("text/plain; charset=x-user-defined"); req.onerror = () => console.log(`Error loading ${path}: ${req.statusText}`); req.onload = function () { if (this.status === 200) { app.nes_boot(this.responseText); } else if (this.status === 0) { // Aborted, so ignore error } else { // req.onerror(); // console.log('error'); } }; req.send(); } } app = new MyApp(); window["myApp"] = app;
the_stack
import { WebGLRenderTarget, Vector2, Shader, ShaderMaterial, WebGLRenderer, PerspectiveCamera, DepthTexture } from 'three'; import { FullScreenQuad } from 'three/examples/jsm/postprocessing/Pass'; import { BlendShader } from 'three/examples/jsm/shaders/BlendShader'; import { GaussianBlurShader, GaussianBlurDirection } from './shaders/effect/gaussian-blur-shader'; import { RGBShiftShader } from 'three/examples/jsm/shaders/RGBShiftShader'; import { VignetteShader } from 'three/examples/jsm/shaders/VignetteShader'; import { VignetteBlendShader } from './shaders/effect/vignette-blend-shader'; import { MotionBlurShader } from './shaders/effect/motion-blur-shader'; import { GlitchShader } from './shaders/transition/glitch-shader'; import { ShaderUtils, Uniforms } from './shaders/shader-utils'; enum EffectType { Blur = 'Blur', Bloom = 'Bloom', RgbShift = 'RgbShift', Vignette = 'Vignette', VignetteBlur = 'VignetteBlur', MotionBlur = 'MotionBlur', Glitch = 'Glitch', } interface IEffect { render(...args: any[]); setSize?(width: number, height: number); getUniforms(): Uniforms; updateUniforms(uniforms: Uniforms); clearUniforms(); dispose(); } class Effect implements IEffect { protected _quad: FullScreenQuad = new FullScreenQuad(); /** * Contructs an effect. * @param {Shader} shader - a shader definition. * @param {Uniforms} uniforms - uniforms for the shader. */ constructor(shader: Shader, uniforms: Uniforms = {}) { this._quad.material = ShaderUtils.createShaderMaterial(shader, uniforms); } /** * Returns the current uniforms for the effect. * @returns Uniforms */ getUniforms(): Uniforms { return ShaderUtils.getUniforms(this._quad.material as ShaderMaterial); } /** * Updates the specified uniforms for the effect. * @param {Uniforms} uniforms */ updateUniforms(uniforms: Uniforms = {}): void { ShaderUtils.updateUniforms(this._quad.material as ShaderMaterial, uniforms); } /** * Resets the uniforms for the effect back to its default values. */ clearUniforms(): void { ShaderUtils.clearUniforms(this._quad.material as ShaderMaterial); } /** * Renders the effect. * @param {WebGLRenderer} renderer - the renderer to use. * @param {WebGLRenderTarget | null} writeBuffer - the buffer to render to, or null to render directly to screen. * @param {WebGLRenderTarget} readBuffer - the buffer to read from. * @param {Uniforms} uniforms - uniforms values to update before rendering. */ render(renderer: WebGLRenderer, writeBuffer: WebGLRenderTarget | null, readBuffer: WebGLRenderTarget, uniforms: Uniforms = {}): void { renderer.setRenderTarget(writeBuffer); this.updateUniforms({ ...uniforms, tDiffuse: readBuffer.texture, }); this._quad.render(renderer); } /** * Disposes this object. Call when this object is no longer needed, otherwise leaks may occur. */ dispose(): void { this._quad.material.dispose(); } } class TransitionEffect extends Effect { /** * Renders the effect. * @param {WebGLRenderer} renderer - the renderer to use. * @param {WebGLRenderTarget | null} writeBuffer - the buffer to render to, or null to render directly to screen. * @param {WebGLRenderTarget} fromBuffer - the buffer to transition from. * @param {WebGLRenderTarget} toBuffer - the buffer to transition to. * @param {Uniforms} uniforms - uniform values to update before rendering. */ render(renderer: WebGLRenderer, writeBuffer: WebGLRenderTarget | null, fromBuffer: WebGLRenderTarget, toBuffer: WebGLRenderTarget, uniforms: Uniforms = {}): void { renderer.setRenderTarget(writeBuffer); this.updateUniforms({ ...uniforms, tDiffuse1: fromBuffer.texture, tDiffuse2: toBuffer.texture, }); this._quad.render(renderer); } } class MotionBlurEffect extends Effect { camera: PerspectiveCamera; depthTexture: DepthTexture; /** * Constructs a MotionBlurEffect. * @param {PerspectiveCamera} camera - a three.js PerspectiveCamera. * @param {DepthTexture} depthTexture - a three.js DepthTexture. * @param {Uniforms} uniforms - uniforms for the shader. */ constructor(camera: PerspectiveCamera, depthTexture: DepthTexture, uniforms: Uniforms = {}) { super(MotionBlurShader, uniforms); this.camera = camera; this.depthTexture = depthTexture; } /** * Renders the effect. * @param {WebGLRenderer} renderer - the renderer to use. * @param {WebGLRenderTarget | null} writeBuffer - the buffer to render to, or null to render directly to screen. * @param {WebGLRenderTarget} readBuffer - the buffer to read from. * @param {Uniforms} uniforms - uniform values to update before rendering. */ render(renderer: WebGLRenderer, writeBuffer: WebGLRenderTarget | null, readBuffer: WebGLRenderTarget, uniforms: Uniforms = {}): void { const { clipToWorldMatrix, prevWorldToClipMatrix } = this.getUniforms(); // the clip to world space matrix is calculated using the inverse projection-view matrix // NOTE: camera.matrixWorld is the inverse view matrix of the camera (instead of matrixWorldInverse) super.render(renderer, writeBuffer, readBuffer, { ...uniforms, tDepth: this.depthTexture, clipToWorldMatrix: clipToWorldMatrix.copy(this.camera.projectionMatrixInverse).multiply(this.camera.matrixWorld), }); // the world to clip space matrix is calculated using the view-projection matrix prevWorldToClipMatrix.copy(this.camera.matrixWorldInverse).multiply(this.camera.projectionMatrix); } } class GaussianBlurEffect extends Effect { private _width: number; private _height: number; private _buffer: WebGLRenderTarget; // the number of blur passes to perform - more passes are expensive but result in stronger blurs and less artifacts. passes = 1; /** * Constructs a GaussianBlurEffect. * @param {number} width * @param {number} height * @param {Uniforms} uniforms - uniforms for the shader. */ constructor(width: number, height: number, uniforms: Uniforms = {}) { super(GaussianBlurShader, uniforms); this._width = width; this._height = height; this._buffer = new WebGLRenderTarget(width, height); } /** * Sets the size of the effect. * @param {number} width * @param {number} height */ setSize(width: number, height: number): void { this._width = width; this._height = height; this._buffer.setSize(width, height); } /** * Renders the effect. * @param {WebGLRenderer} renderer - the renderer to use. * @param {WebGLRenderTarget} writeBuffer - the buffer to render to. * @param {WebGLRenderTarget} readBuffer - the buffer to read from. * @param {Uniforms} uniforms - uniform values to update before rendering. */ render(renderer: WebGLRenderer, writeBuffer: WebGLRenderTarget, readBuffer: WebGLRenderTarget, uniforms: Uniforms = {}): void { for (let i = 0; i < this.passes; ++i) { super.render(renderer, this._buffer, i === 0 ? readBuffer : writeBuffer, { ...uniforms, direction: GaussianBlurDirection.HORIZONTAL, resolution: this._width, }); super.render(renderer, writeBuffer, this._buffer, { ...uniforms, direction: GaussianBlurDirection.VERTICAL, resolution: this._height, }); } } /** * Disposes this object. Call when this object is no longer needed, otherwise leaks may occur. */ dispose(): void { this._buffer.dispose(); super.dispose(); } } class BloomEffect implements IEffect { private _blurEffect: GaussianBlurEffect; private _blendEffect: TransitionEffect; private _blendBuffer: WebGLRenderTarget; /** * Constructs a BloomEffect. * @param {number} width * @param {number} height * @param {Uniforms} uniforms - uniforms for the shader. */ constructor(width: number, height: number, uniforms: Uniforms = {}) { this._blurEffect = new GaussianBlurEffect(width, height); this._blendEffect = new TransitionEffect(BlendShader, { mixRatio: 0.5 }); this._blendBuffer = new WebGLRenderTarget(width, height); this.updateUniforms(uniforms); } /** * The number of blur passes to perform. More passes are expensive but result in stronger blurs and less artifacts. * @returns number */ get passes(): number { return this._blurEffect.passes; } /** * @param {number} value */ set passes(value: number) { this._blurEffect.passes = value; } /** * Sets the size of the effect. * @param {number} width * @param {number} height */ setSize(width: number, height: number): void { this._blurEffect.setSize(width, height); this._blendBuffer.setSize(width, height); } /** * Returns the current uniforms for the effect. * @returns Uniforms */ getUniforms(): Uniforms { const { opacity } = this._blendEffect.getUniforms(); return { ...this._blurEffect.getUniforms(), opacity }; } /** * Updates the specified uniforms for the effect. * @param {Uniforms} uniforms */ updateUniforms(uniforms: Uniforms = {}): void { const blendUniforms = this._blendEffect.getUniforms(); const { opacity = blendUniforms.opacity, ...blurUniforms } = uniforms; this._blurEffect.updateUniforms(blurUniforms); this._blendEffect.updateUniforms({ opacity }); } /** * Resets the uniforms for the effect back to its default values. */ clearUniforms(): void { this._blurEffect.clearUniforms(); this._blendEffect.clearUniforms(); this._blendEffect.updateUniforms({ mixRatio: 0.5 }); } /** * Renders the effect. * @param {WebGLRenderer} renderer - the renderer to use. * @param {WebGLRenderTarget | null} writeBuffer - the buffer to render to, or null to render directly to screen. * @param {WebGLRenderTarget} readBuffer - the buffer to read from. * @param {Uniforms} uniforms - uniform values to update before rendering. */ render(renderer: WebGLRenderer, writeBuffer: WebGLRenderTarget | null, readBuffer: WebGLRenderTarget, uniforms: Uniforms = {}): void { this._blurEffect.render(renderer, this._blendBuffer, readBuffer, uniforms); this._blendEffect.render(renderer, writeBuffer, readBuffer, this._blendBuffer); } /** * Disposes this object. Call when this object is no longer needed, otherwise leaks may occur. */ dispose(): void { this._blendEffect.dispose(); this._blendBuffer.dispose(); } } class RGBShiftEffect extends Effect { /** * Contructs a VignetteEffect. * @param {Uniforms} uniforms - uniforms for the shader. */ constructor(uniforms: Uniforms = {}) { super(RGBShiftShader, uniforms); } } class VignetteEffect extends Effect { /** * Contructs a VignetteEffect. * @param {Uniforms} uniforms - uniforms for the shader. */ constructor(uniforms: Uniforms = {}) { super(VignetteShader, uniforms); } } class VignetteBlurEffect implements IEffect { private _blurEffect: GaussianBlurEffect; private _blendEffect: TransitionEffect; private _blendBuffer: WebGLRenderTarget; /** * Constructs a VignetteBlurEffect. * @param {number} width * @param {number} height * @param {Uniforms} uniforms - uniforms for the shader. */ constructor(width: number, height: number, uniforms: Uniforms = {}) { this._blurEffect = new GaussianBlurEffect(width, height); this._blendEffect = new TransitionEffect(VignetteBlendShader); this._blendBuffer = new WebGLRenderTarget(width, height); this.updateUniforms(uniforms); } /** * The number of blur passes to perform. More passes are expensive but result in stronger blurs and less artifacts. * @returns number */ get passes(): number { return this._blurEffect.passes; } /** * @param {number} value */ set passes(value: number) { this._blurEffect.passes = value; } /** * Sets the size of the effect. * @param {number} width * @param {number} height */ setSize(width: number, height: number): void { this._blurEffect.setSize(width, height); this._blendBuffer.setSize(width, height); } /** * Returns the current uniforms for the effect. * @returns Uniforms */ getUniforms(): Uniforms { const { size } = this._blendEffect.getUniforms(); return { ...this._blurEffect.getUniforms(), size }; } /** * Updates the specified uniforms for the effect. * @param {Uniforms} uniforms */ updateUniforms(uniforms: Uniforms = {}): void { const blendUniforms = this._blendEffect.getUniforms(); const { size = blendUniforms.size, ...blurUniforms } = uniforms; this._blurEffect.updateUniforms(blurUniforms); this._blendEffect.updateUniforms({ size }); } /** * Resets the uniforms for the effect back to its default values. */ clearUniforms(): void { this._blurEffect.clearUniforms(); this._blendEffect.clearUniforms(); } /** * Renders the effect. * @param {WebGLRenderer} renderer - the renderer to use. * @param {WebGLRenderTarget | null} writeBuffer - the buffer to render to, or null to render directly to screen. * @param {WebGLRenderTarget} readBuffer - the buffer to read from. * @param {Uniforms} uniforms - uniform values to update before rendering. */ render(renderer: WebGLRenderer, writeBuffer: WebGLRenderTarget | null, readBuffer: WebGLRenderTarget, uniforms: Uniforms = {}): void { this._blurEffect.render(renderer, this._blendBuffer, readBuffer, uniforms); this._blendEffect.render(renderer, writeBuffer, readBuffer, this._blendBuffer); } /** * Disposes this object. Call when this object is no longer needed, otherwise leaks may occur. */ dispose(): void { this._blurEffect.dispose(); this._blendEffect.dispose(); this._blendBuffer.dispose(); } } class GlitchEffect implements IEffect { private _resolution: Vector2; private _glitchEffect: TransitionEffect; private _blurEffect: GaussianBlurEffect; private _blurBuffer: WebGLRenderTarget; /** * Constructs a GlitchEffect. * @param {number} width * @param {number} height * @param {Uniforms} uniforms - uniforms for the shader. */ constructor(width: number, height: number, uniforms: Uniforms = {}) { this._resolution = new Vector2(width, height); this._glitchEffect = new TransitionEffect(GlitchShader); this._blurEffect = new GaussianBlurEffect(width, height, { radius: 3 }); this._blurEffect.passes = 2; this._blurBuffer = new WebGLRenderTarget(width, height); this.updateUniforms(uniforms); } /** * Sets the size for the effect. * @param {number} width * @param {number} height */ setSize(width: number, height: number): void { this._resolution.set(width, height); this._blurEffect.setSize(width, height); this._blurBuffer.setSize(width, height); } /** * Returns the current uniforms for the effect. * @returns Uniforms */ getUniforms(): Uniforms { return this._glitchEffect.getUniforms(); } /** * Updates the specified uniforms for the effect. * @param {Uniforms} uniforms */ updateUniforms(uniforms: Uniforms = {}): void { this._glitchEffect.updateUniforms(uniforms); } /** * Resets the uniforms for the effect back to its default values. */ clearUniforms(): void { this._glitchEffect.clearUniforms(); } /** * Renders the effect. * @param {WebGLRenderer} renderer - the renderer to use. * @param {WebGLRenderTarget | null} writeBuffer - the buffer to render to, or null to render directly to screen. * @param {WebGLRenderTarget} readBuffer - the buffer to read from. * @param {Uniforms} uniforms - uniform values to update before rendering. */ render(renderer: WebGLRenderer, writeBuffer: WebGLRenderTarget | null, readBuffer: WebGLRenderTarget, uniforms: Uniforms = {}): void { this._blurEffect.render(renderer, this._blurBuffer, readBuffer); this._glitchEffect.render(renderer, writeBuffer, readBuffer, this._blurBuffer, { ...uniforms, resolution: this._resolution, }); } /** * Disposes this object. Call when this object is no longer needed, otherwise leaks may occur. */ dispose(): void { this._glitchEffect.dispose(); this._blurEffect.dispose(); this._blurBuffer.dispose(); } } export { EffectType, IEffect, Effect, TransitionEffect, GaussianBlurEffect, BloomEffect, RGBShiftEffect, VignetteEffect, VignetteBlurEffect, MotionBlurEffect, GlitchEffect, };
the_stack
import path from 'path'; import { Dirent, promises as fsPromises } from 'fs'; import { File, MutationRange } from '@stryker-mutator/api/core'; import { SourceFile } from '@stryker-mutator/api/report'; import { assertions, factory, testInjector, tick } from '@stryker-mutator/test-helpers'; import { Task } from '@stryker-mutator/util'; import { expect } from 'chai'; import sinon from 'sinon'; import { coreTokens } from '../../../src/di'; import { InputFileResolver } from '../../../src/input'; import { BroadcastReporter } from '../../../src/reporters/broadcast-reporter'; import { Mock, mock } from '../../helpers/producers'; describe(InputFileResolver.name, () => { let reporterMock: Mock<BroadcastReporter>; let readFileStub: sinon.SinonStub; let readdirStub: sinon.SinonStubbedMember<typeof fsPromises.readdir>; beforeEach(() => { reporterMock = mock(BroadcastReporter); readdirStub = sinon.stub(fsPromises, 'readdir'); readFileStub = sinon.stub(fsPromises, 'readFile'); }); it('should log a warning if no files were resolved', async () => { stubFileSystem({}); // emtpy dir const sut = createSut(); await sut.resolve(); expect(testInjector.logger.warn).calledWith( `No files found in directory ${process.cwd()} using ignore rules: ["node_modules",".git","/reports","*.tsbuildinfo","/stryker.log",".stryker-tmp"]. Make sure you run Stryker from the root directory of your project with the correct "ignorePatterns".` ); }); describe('file resolving', () => { it('should discover files recursively using readdir', async () => { // Arrange stubFileSystem({ app: { 'app.component.js': '@Component()', }, util: { 'index.js': 'foo.bar', object: { 'object-helper.js': 'export const helpers = {}', }, }, }); const sut = createSut(); // Act const result = await sut.resolve(); assertions.expectTextFilesEqual(result.files, [ new File(path.resolve('app', 'app.component.js'), '@Component()'), new File(path.resolve('util', 'index.js'), 'foo.bar'), new File(path.resolve('util', 'object', 'object-helper.js'), 'export const helpers = {}'), ]); expect(readdirStub).calledWith(process.cwd(), { withFileTypes: true }); }); it('should respect ignore patterns', async () => { stubFileSystem({ src: { 'index.js': 'export * from "./app"' }, dist: { 'index.js': 'module.exports = require("./app")' }, }); testInjector.options.ignorePatterns = ['dist']; const sut = createSut(); const result = await sut.resolve(); assertions.expectTextFilesEqual(result.files, [new File(path.resolve('src', 'index.js'), 'export * from "./app"')]); }); it('should respect deep ignore patterns', async () => { stubFileSystem({ packages: { app: { src: { 'index.js': 'export * from "./app"' }, dist: { 'index.js': 'module.exports = require("./app")' }, }, }, }); testInjector.options.ignorePatterns = ['/packages/*/dist']; const sut = createSut(); const { files } = await sut.resolve(); expect(files).lengthOf(1); expect(files[0].name).eq(path.resolve('packages', 'app', 'src', 'index.js')); }); it('should ignore node_modules, .git, reports, stryker.log, *.tsbuildinfo and .stryker-tmp by default', async () => { // Arrange stubFileSystem({ '.git': { config: '' }, node_modules: { rimraf: { 'index.js': '' } }, '.stryker-tmp': { 'stryker-sandbox-123': { src: { 'index.js': '' } } }, 'index.js': '', 'stryker.log': '', 'tsconfig.src.tsbuildinfo': '', dist: { 'tsconfig.tsbuildinfo': '', }, reports: { mutation: { 'mutation.json': '' } }, }); const sut = createSut(); // Act const { files } = await sut.resolve(); // Assert expect(files).lengthOf(1); expect(files[0].name).eq(path.resolve('index.js')); }); it('should not ignore deep report directories by default', async () => { // Arrange stubFileSystem({ app: { reports: { 'reporter.component.js': '' } }, }); const sut = createSut(); // Act const { files } = await sut.resolve(); // Assert expect(files).lengthOf(1); expect(files[0].name).eq(path.resolve('app', 'reports', 'reporter.component.js')); }); it('should ignore a deep node_modules directory by default', async () => { // Arrange stubFileSystem({ testResources: { 'require-resolve': { node_modules: { bar: { 'index.js': '' } } } }, }); const sut = createSut(); // Act const { files } = await sut.resolve(); // Assert expect(files).lengthOf(0); }); it('should ignore an alternative stryker-tmp dir', async () => { // Arrange stubFileSystem({ '.git': { config: '' }, node_modules: { rimraf: { 'index.js': '' } }, 'stryker-tmp': { 'stryker-sandbox-123': { src: { 'index.js': '' } } }, 'index.js': '', }); testInjector.options.tempDirName = 'stryker-tmp'; const sut = createSut(); // Act const { files } = await sut.resolve(); // Assert expect(files).lengthOf(1); expect(files[0].name).eq(path.resolve('index.js')); }); it('should allow un-ignore', async () => { // Arrange stubFileSystem({ '.git': { config: '' }, node_modules: { rimraf: { 'index.js': '' } }, '.stryker-tmp': { 'stryker-sandbox-123': { src: { 'index.js': '' } } }, 'index.js': '', }); testInjector.options.ignorePatterns = ['!node_modules']; const sut = createSut(); // Act const { files } = await sut.resolve(); // Assert expect(files).lengthOf(2); expect(files[0].name).eq(path.resolve('index.js')); expect(files[1].name).eq(path.resolve('node_modules', 'rimraf', 'index.js')); }); it('should allow un-ignore deep node_modules directory', async () => { // Arrange stubFileSystem({ node_modules: { rimraf: { 'index.js': '' } }, testResources: { 'require-resolve': { node_modules: { bar: { 'index.js': '' } } } }, }); testInjector.options.ignorePatterns = ['!testResources/**/node_modules']; const sut = createSut(); // Act const { files } = await sut.resolve(); // Assert expect(files).lengthOf(1); expect(files[0].name).eq(path.resolve('testResources', 'require-resolve', 'node_modules', 'bar', 'index.js')); }); it('should reject if fs commands fail', async () => { const expectedError = factory.fileNotFoundError(); readdirStub.rejects(expectedError); await expect(createSut().resolve()).rejectedWith(expectedError); }); it('should allow whitelisting with "**"', async () => { stubFileSystem({ src: { 'index.js': 'export * from "./app"' }, dist: { 'index.js': 'module.exports = require("./app")' }, }); testInjector.options.ignorePatterns = ['**', '!src/**/*.js']; const sut = createSut(); const { files } = await sut.resolve(); assertions.expectTextFilesEqual(files, [new File(path.resolve('src', 'index.js'), 'export * from "./app"')]); }); it('should allow deep whitelisting with "**"', async () => { stubFileSystem({ app: { src: { 'index.js': 'export * from "./app"' }, }, dist: { 'index.js': 'module.exports = require("./app")' }, }); testInjector.options.ignorePatterns = ['**', '!app/src/index.js']; const sut = createSut(); const { files } = await sut.resolve(); assertions.expectTextFilesEqual(files, [new File(path.resolve('app', 'src', 'index.js'), 'export * from "./app"')]); }); it('should not open too many file handles', async () => { // Arrange const maxFileIO = 256; const sut = createSut(); const fileHandles: Array<{ fileName: string; task: Task<Buffer> }> = []; for (let i = 0; i < maxFileIO + 1; i++) { const fileName = `file_${i}.js`; const readFileTask = new Task<Buffer>(); fileHandles.push({ fileName, task: readFileTask }); readFileStub.withArgs(sinon.match(fileName)).returns(readFileTask.promise); } readdirStub.withArgs(process.cwd(), sinon.match.object).resolves(fileHandles.map(({ fileName }) => createDirent(fileName, false))); // Act const onGoingWork = sut.resolve(); await tick(); expect(readFileStub).callCount(maxFileIO); fileHandles[0].task.resolve(Buffer.from('content')); await tick(); // Assert expect(readFileStub).callCount(maxFileIO + 1); fileHandles.forEach(({ task }) => task.resolve(Buffer.from('content'))); await onGoingWork; }); }); describe('without mutate files', () => { beforeEach(() => { stubFileSystem({ 'file1.js': 'file 1 content', 'file2.js': 'file 2 content', 'file3.js': 'file 3 content', 'mute1.js': 'mutate 1 content', 'mute2.js': 'mutate 2 content', }); }); it('should warn about dry-run', async () => { const sut = createSut(); await sut.resolve(); expect(testInjector.logger.warn).calledWith( 'No files marked to be mutated, Stryker will perform a dry-run without actually mutating anything. You can configure the `mutate` property in your config file (or use `--mutate` via command line).' ); }); }); function stubFileSystemWith5Files() { stubFileSystem({ 'file1.js': 'file 1 content', 'file2.js': 'file 2 content', 'file3.js': 'file 3 content', 'mute1.js': 'mutate 1 content', 'mute2.js': 'mutate 2 content', }); } describe('with mutation range definitions', () => { beforeEach(() => { stubFileSystem({ 'file1.js': 'file 1 content', 'file2.js': 'file 2 content', 'file3.js': 'file 3 content', 'mute1.js': 'mutate 1 content', 'mute2.js': 'mutate 2 content', }); }); it('should remove specific mutant descriptors when matching with line and column', async () => { testInjector.options.mutate = ['mute1.js:1:2-2:2']; testInjector.options.files = ['file1', 'mute1', 'file2', 'mute2', 'file3']; const sut = createSut(); const result = await sut.resolve(); expect(result.filesToMutate.map((_) => _.name)).to.deep.equal([path.resolve('mute1.js')]); }); it('should parse the mutation range', async () => { testInjector.options.mutate = ['mute1:1:2-2:2']; testInjector.options.files = ['file1', 'mute1', 'file2', 'mute2', 'file3']; const sut = createSut(); const result = await sut.resolve(); const expectedRanges: MutationRange[] = [ { start: { column: 2, line: 0, // internally, Stryker works 0-based }, end: { column: 2, line: 1, }, fileName: path.resolve('mute1'), }, ]; expect(result.mutationRanges).deep.eq(expectedRanges); }); it('should default column numbers if not present', async () => { testInjector.options.mutate = ['mute1:6-12']; testInjector.options.files = ['file1', 'mute1', 'file2', 'mute2', 'file3']; const sut = createSut(); const result = await sut.resolve(); expect(result.mutationRanges[0].start).deep.eq({ column: 0, line: 5 }); expect(result.mutationRanges[0].end).deep.eq({ column: Number.MAX_SAFE_INTEGER, line: 11 }); }); }); describe('with mutate file patterns', () => { it('should result in the expected mutate files', async () => { stubFileSystemWith5Files(); testInjector.options.mutate = ['mute*']; const sut = createSut(); const result = await sut.resolve(); expect(result.filesToMutate.map((_) => _.name)).to.deep.equal([path.resolve('mute1.js'), path.resolve('mute2.js')]); expect(result.files.map((file) => file.name)).to.deep.equal([ path.resolve('file1.js'), path.resolve('file2.js'), path.resolve('file3.js'), path.resolve('mute1.js'), path.resolve('mute2.js'), ]); }); it('should only report a mutate file when it is included in the resolved files', async () => { stubFileSystemWith5Files(); testInjector.options.mutate = ['mute*']; testInjector.options.ignorePatterns = ['mute2.js']; const sut = createSut(); const result = await sut.resolve(); expect(result.filesToMutate.map((_) => _.name)).to.deep.equal([path.resolve('mute1.js')]); }); it('should report OnAllSourceFilesRead', async () => { stubFileSystemWith5Files(); testInjector.options.mutate = ['mute*']; const sut = createSut(); await sut.resolve(); const expected: SourceFile[] = [ { path: path.resolve('file1.js'), content: 'file 1 content' }, { path: path.resolve('file2.js'), content: 'file 2 content' }, { path: path.resolve('file3.js'), content: 'file 3 content' }, { path: path.resolve('mute1.js'), content: 'mutate 1 content' }, { path: path.resolve('mute2.js'), content: 'mutate 2 content' }, ]; expect(reporterMock.onAllSourceFilesRead).calledWith(expected); }); it('should report OnSourceFileRead', async () => { stubFileSystemWith5Files(); testInjector.options.mutate = ['mute*']; const sut = createSut(); await sut.resolve(); const expected: SourceFile[] = [ { path: path.resolve('file1.js'), content: 'file 1 content' }, { path: path.resolve('file2.js'), content: 'file 2 content' }, { path: path.resolve('file3.js'), content: 'file 3 content' }, { path: path.resolve('mute1.js'), content: 'mutate 1 content' }, { path: path.resolve('mute2.js'), content: 'mutate 2 content' }, ]; expected.forEach((sourceFile) => expect(reporterMock.onSourceFileRead).calledWith(sourceFile)); }); it('should warn about useless patterns custom "mutate" patterns', async () => { testInjector.options.mutate = ['src/**/*.js', '!src/index.js', 'types/global.d.ts']; stubFileSystem({ src: { 'foo.js': 'foo();', }, }); const sut = createSut(); await sut.resolve(); expect(testInjector.logger.warn).calledTwice; expect(testInjector.logger.warn).calledWith('Glob pattern "!src/index.js" did not exclude any files.'); expect(testInjector.logger.warn).calledWith('Glob pattern "types/global.d.ts" did not result in any files.'); }); it('should not warn about useless patterns if "mutate" isn\'t overridden', async () => { stubFileSystem({ src: { 'foo.js': 'foo();', }, }); const sut = createSut(); await sut.resolve(); expect(testInjector.logger.warn).not.called; }); }); function createSut() { return testInjector.injector.provideValue(coreTokens.reporter, reporterMock).injectClass(InputFileResolver); } // eslint-disable-next-line @typescript-eslint/consistent-indexed-object-style type DirectoryEntry = string | { [name: string]: DirectoryEntry }; function stubFileSystem(dirEntry: DirectoryEntry, fullName = process.cwd()) { if (typeof dirEntry === 'string') { readFileStub.withArgs(fullName).resolves(Buffer.from(dirEntry)); } else { readdirStub .withArgs(fullName, sinon.match.object) .resolves(Object.entries(dirEntry).map(([name, value]) => createDirent(name, typeof value !== 'string'))); Object.entries(dirEntry).map(([name, value]) => stubFileSystem(value, path.resolve(fullName, name))); } } function createDirent(name: string, isDirectory: boolean): Dirent { const dummy = () => true; return { isBlockDevice: dummy, isCharacterDevice: dummy, isDirectory: () => isDirectory, isFIFO: dummy, isFile: () => !isDirectory, isSocket: dummy, isSymbolicLink: dummy, name, }; } });
the_stack
import { MonacoEditorTSLibrariesMetaMods } from '../../../monaco-editor/monaco-editor'; import { Polymer } from '../../../../../../../tools/definitions/polymer'; import { PaperDropdownBehavior } from '../../../../inputs/paper-dropdown-behavior/paper-dropdown-behavior'; import { I18NKeys } from '../../../../../../_locales/i18n-keys'; import { I18NClass } from '../../../../../../js/shared'; declare const browserAPI: browserAPI; namespace PaperLibrariesSelectorElement { export const paperLibrariesSelectorProperties: { usedlibraries: CRM.Library[]; libraries: LibrarySelectorLibrary[]; selected: number[]; installedLibraries: CRM.InstalledLibrary[]; mode: 'main'|'background'; noroot: boolean; } = { /** * The libraries currently in use by the script */ usedlibraries: { type: Array, notify: true }, /** * The libraries for use in the HTML, already marked up */ libraries: { type: Array, notify: true }, /** * The currently selected (used) libraries' indexes */ selected: { type: Array, notify: true }, /** * The libraries installed in the extension */ installedLibraries: { type: Array }, /** * The type of script that's currenly being edited (main or background) */ mode: { type: String, value: 'main' }, /** * Don't have the "libraries" root item */ noroot: { type: Boolean, value: false } } as any; interface LibrarySelectorLibrary { name?: string; isLibrary?: boolean; url?: string; code?: string; classes?: string; selected?: 'true'|'false'; } export class PLS implements I18NClass { static is: string = 'paper-libraries-selector'; static properties = paperLibrariesSelectorProperties; private static _editingInstance: { name: string; wasFullscreen: boolean; library: LibrarySelectorLibrary; } = null; private static _eventListeners: { target: HTMLElement; event: string; listener: Function; }[] = []; private static _srcNode: CRM.ScriptNode = null; private static _viewLibs: { anonymous: LibrarySelectorLibrary[]; libraries: LibrarySelectorLibrary[]; } = null; static ready(this: PaperLibrariesSelector) { browserAPI.storage.local.get<CRM.StorageLocal>().then((keys) => { if (keys.libraries) { this.installedLibraries = keys.libraries; } else { this.installedLibraries = []; browserAPI.storage.local.set({ libaries: this.installedLibraries } as any); } }); browserAPI.storage.onChanged.addListener((changes, areaName) => { if (areaName === 'local' && changes['libraries']) { this.installedLibraries = changes['libraries'].newValue; } }); }; static sortByName(first: LibrarySelectorLibrary, second: LibrarySelectorLibrary): number { return first.name[0].toLowerCase().charCodeAt(0) - second.name[0].toLowerCase().charCodeAt(0); } static categorizeLibraries(this: PaperLibrariesSelector) { const anonymous: LibrarySelectorLibrary[] = []; const selectedObj: { [key: string]: boolean; } = {}; this.usedlibraries.forEach(function (item) { if (!item.name) { anonymous.push(item as any); } else { selectedObj[item.name.toLowerCase()] = true; } }); return { anonymous, selectedObj } } private static _getLibraries(this: PaperLibrariesSelector, selectedObj: { [key: string]: boolean; }) { let libraries: LibrarySelectorLibrary[] = []; this.installedLibraries.forEach(function(item) { const itemCopy: LibrarySelectorLibrary = {} as any; itemCopy.name = item.name; itemCopy.isLibrary = true; itemCopy.url = item.url; if (selectedObj[item.name.toLowerCase()]) { itemCopy.classes = 'library iron-selected'; itemCopy.selected = 'true'; } else { itemCopy.classes = 'library'; itemCopy.selected = 'false'; } libraries.push(itemCopy); }); libraries.sort(this.sortByName); return libraries; } private static _setSelectedLibraries(this: PaperLibrariesSelector, libraries: LibrarySelectorLibrary[]) { const selected: number[] = []; libraries.forEach(function(item, index) { if (item.selected === 'true') { selected.push(index); } }); this.selected = selected; } private static _displayLibraries(this: PaperLibrariesSelector, anonymous: LibrarySelectorLibrary[], libraries: LibrarySelectorLibrary[]) { const anonymousLibraries: LibrarySelectorLibrary[] = []; anonymous.forEach((item) => { const itemCopy: LibrarySelectorLibrary = { isLibrary: true, name: `${item.url} (${ this.___(I18NKeys.options.tools.paperLibrariesSelector.anonymous) })`, classes: 'library iron-selected anonymous', selected: 'true' }; anonymousLibraries.push(itemCopy); }); anonymousLibraries.sort(this.sortByName); libraries = libraries.concat(anonymousLibraries); libraries.push({ name: this.___(I18NKeys.options.tools.paperLibrariesSelector.addOwn), classes: 'library addLibrary', selected: 'false', isLibrary: false } as any); this.libraries = libraries; } static onLangChanged(this: PaperLibrariesSelector) { // Not loaded yet, this means that it will be loaded by the element eventually if (!this._viewLibs) return; this._displayLibraries(this._viewLibs.anonymous, this._viewLibs.libraries); } static async init(this: PaperLibrariesSelector, cancelOpen: boolean = false) { if (!this.noroot && this._expanded && !cancelOpen) { this.close(); } if (this.noroot) { this.open(); } if (cancelOpen) { await this.close(); this.open(); } const { anonymous, selectedObj } = this.categorizeLibraries(); let libraries = this._getLibraries(selectedObj) this._setSelectedLibraries(libraries); this._viewLibs = { anonymous, libraries } this._displayLibraries(anonymous, libraries); }; private static _resetAfterAddDecision(this: PaperLibrariesSelector) { for (const { event, listener, target } of this._eventListeners) { target.removeEventListener(event, listener as any); } window.doc.addLibraryUrlInput.invalid = false; } static confirmLibraryFile(this: PaperLibrariesSelector, name: string, isTypescript: boolean, code: string, url: string) { window.doc.addLibraryProcessContainer.style.display = 'none'; window.setDisplayFlex(window.doc.addLibraryLoadingDialog); setTimeout(() => { window.doc.addLibraryConfirmationInput.value = code; const confirmAdditionListener = () => { window.doc.addLibraryConfirmationInput.value = ''; this.addLibraryFile(name, isTypescript, code, url); this._resetAfterAddDecision(); }; const denyAdditionListener = () => { window.doc.addLibraryConfirmationContainer.style.display = 'none'; window.doc.addLibraryProcessContainer.style.display = 'block'; this._resetAfterAddDecision(); window.doc.addLibraryConfirmationInput.value = ''; }; window.doc.addLibraryConfirmAddition.addEventListener('click', confirmAdditionListener); window.doc.addLibraryDenyConfirmation.addEventListener('click', denyAdditionListener); this._eventListeners.push({ target: window.doc.addLibraryConfirmAddition, event: 'click', listener: confirmAdditionListener }, { target: window.doc.addLibraryDenyConfirmation, event: 'click', listener: denyAdditionListener }); window.doc.addLibraryLoadingDialog.style.display = 'none'; window.doc.addLibraryConfirmationContainer.style.display = 'block'; }, 250); }; private static _addLibraryToState(this: PaperLibrariesSelector, name: string, isTypescript: boolean, code: string, url: string) { this.installedLibraries.push({ name, code, url, ts: { enabled: isTypescript, code: {} } }); const srcLibraries = this.mode === 'main' ? this._srcNode.value.libraries : this._srcNode.value.backgroundLibraries; if (!srcLibraries) { if (this.mode === 'main') { this._srcNode.value.libraries = []; } else { this._srcNode.value.backgroundLibraries = []; } } srcLibraries.push({ name, url }); } private static _hideElements<T extends keyof typeof window.doc>(...els: T[]) { for (let i = 0; i < els.length; i++) { (window.doc[els[i]] as any).style.display = 'none'; } } private static _showElements<T extends keyof typeof window.doc>(...els: T[]) { for (let i = 0; i < els.length; i++) { (window.doc[els[i]] as any).style.display = 'block'; } } private static _showElementsFlex<T extends keyof typeof window.doc>(...els: T[]) { for (let i = 0; i < els.length; i++) { window.setDisplayFlex(window.doc[els[i]] as any); } } private static _setLibraries(this: PaperLibrariesSelector, libraries: CRM.InstalledLibrary[]) { browserAPI.storage.local.set({ libraries: libraries } as any); browserAPI.runtime.sendMessage({ type: 'updateStorage', data: { type: 'libraries', libraries: libraries } }); } static async addLibraryFile(this: PaperLibrariesSelector, name: string, isTypescript: boolean, code: string, url: string = null) { window.doc.addLibraryConfirmationContainer.style.display = 'none'; window.setDisplayFlex(window.doc.addLibraryLoadingDialog); if (url) { await new Promise((resolve) => { window.setTimeout(() => { resolve(null); }, 250); }); } this._addLibraryToState(name, isTypescript, code, url); this._setLibraries(this.installedLibraries); this.splice('libraries', this.libraries.length - 1, 0, { name: name, classes: 'library iron-selected', selected: 'true', isLibrary: 'true' }); const dropdownContainer = $(this.$.slotContent); dropdownContainer.animate({ height: dropdownContainer[0].scrollHeight }, { duration: 250, easing: 'swing' }); this._hideElements('addLibraryLoadingDialog', 'addLibraryConfirmationContainer', 'addLibraryProcessContainer', 'addLibraryDialogSuccesCheckmark') this._showElements('addLibraryDialogSucces'); $(window.doc.addLibraryDialogSucces).animate({ backgroundColor: 'rgb(38,153,244)' }, { duration: 300, easing: 'easeOutCubic', complete: () => { this._showElements('addLibraryDialogSuccesCheckmark'); window.doc.addLibraryDialogSuccesCheckmark.classList.add('animateIn'); setTimeout(() => { window.doc.addLibraryDialog.toggle(); this._hideElements('addLibraryDialogSucces'); this._showElementsFlex('addLibraryLoadingDialog'); }, 2500); } }); const contentEl = this.$.slotContent; contentEl.style.height = (~~contentEl.style.height.split('px')[0] + 48) + 'px'; this.init(true); }; private static _getStatusCodeDescr(this: PaperLibrariesSelector, code: number) { switch ((code + '')[0]) { case '2': return 'Success'; case '3': return 'Redirect'; case '4': switch (code) { case 400: return 'Bad request'; case 401: return 'Unauthorized'; case 403: return 'Forbidden'; case 404: return 'Not ound'; case 408: return 'Timeout'; default: return null; } case '5': return 'Server error'; case '0': case '1': default: return null; } } private static async _addLibraryHandler(this: PaperLibrariesSelector) { const input = window.doc.addedLibraryName; const name = input.$$('input').value; let taken = false; for (let i = 0; i < this.installedLibraries.length; i++) { if (this.installedLibraries[i].name === name) { taken = true; } } if (name !== '' && !taken) { input.invalid = false; if (window.doc.addLibraryRadios.selected === 'url') { const libraryInput = window.doc.addLibraryUrlInput; let url = libraryInput.$$('input').value; if (url[0] === '/' && url[1] === '/') { url = 'http:' + url; } window.app.util.xhr(url, false).then((data) => { this.confirmLibraryFile(name, window.doc.addLibraryIsTS.checked, data, url); }).catch(async (statusCode) => { const statusMsg = this._getStatusCodeDescr(statusCode); const msg = statusMsg ? await this.__async( I18NKeys.options.tools.paperLibrariesSelector.xhrFailedMsg, statusCode, statusMsg) : await this.__async( I18NKeys.options.tools.paperLibrariesSelector.xhrFailed, statusCode); window.app.util.showToast(msg); libraryInput.setAttribute('invalid', 'true'); }); } else { this.addLibraryFile(name, window.doc.addLibraryIsTS.checked, (window.doc.addLibraryManualInput .$$('iron-autogrow-textarea') as Polymer.RootElement) .$$('textarea').value); } } else { if (taken) { input.errorMessage = await this.__async( I18NKeys.options.tools.paperLibrariesSelector.nameTaken); } else { input.errorMessage = await this.__async( I18NKeys.options.tools.paperLibrariesSelector.nameMissing); } input.invalid = true; } } private static _addNewLibrary(this: PaperLibrariesSelector) { //Add new library dialog window.doc.addedLibraryName.$$('input').value = ''; window.doc.addLibraryUrlInput.$$('input').value = ''; (window.doc.addLibraryManualInput .$$('iron-autogrow-textarea') as Polymer.RootElement) .$$('textarea').value = ''; window.doc.addLibraryIsTS.checked = false; this._showElements('addLibraryProcessContainer'); this._hideElements('addLibraryLoadingDialog', 'addLibraryConfirmationContainer', 'addLibraryDialogSucces'); window.doc.addedLibraryName.invalid = false; window.doc.addLibraryDialog.open(); const handler = this._addLibraryHandler.bind(this); window.app.$.addLibraryButton.addEventListener('click', handler); this._eventListeners.push({ target: window.app.$.addLibraryButton, listener: handler, event: 'click' }); } private static _handleCheckmarkClick(this: PaperLibrariesSelector, container: HTMLElement & { dataLib: LibrarySelectorLibrary; }) { //Checking or un-checking something const lib = container.dataLib; const changeType: 'addMetaTags' | 'removeMetaTags' = (container.classList.contains('iron-selected') ? 'removeMetaTags' : 'addMetaTags'); const libsArr = this.mode === 'main' ? window.scriptEdit.newSettings.value.libraries : window.scriptEdit.newSettings.value.backgroundLibraries; if (changeType === 'addMetaTags') { libsArr.push({ name: lib.name || null, url: lib.url }); container.classList.add('iron-selected'); container.setAttribute('aria-selected', 'true'); container.querySelector('.menuSelectedCheckmark').style.opacity = '1'; } else { let index = -1; for (let i = 0; i < libsArr.length; i++) { if (libsArr[i].url === lib.url && libsArr[i].name === lib.name) { index = i; break; } } libsArr.splice(index, 1); container.classList.remove('iron-selected'); container.removeAttribute('aria-selected'); container.querySelector('.menuSelectedCheckmark').style.opacity = '0'; } const mainModel = window.scriptEdit.editorManager.getModel('default'); const backgroundModel = window.scriptEdit.editorManager.getModel('background'); const TSLibsMod = window.scriptEdit.editorManager.CustomEditorModes.TS_LIBRARIES_META; type TSLibsMod = MonacoEditorTSLibrariesMetaMods; if (typeof mainModel.editorType === 'object' && mainModel.editorType.mode === TSLibsMod) { (mainModel.handlers[0] as TSLibsMod).updateLibraries(); } if (backgroundModel && typeof backgroundModel.editorType === 'object' && backgroundModel.editorType.mode === TSLibsMod) { (backgroundModel.handlers[0] as TSLibsMod).updateLibraries(); } } static _click(this: PaperLibrariesSelector, e: Polymer.ClickEvent) { const container = window.app.util.findElementWithTagname(e, 'paper-item'); if (container.classList.contains('removeLibrary')) { return; } if (container.classList.contains('addLibrary')) { this._addNewLibrary(); } else if (this.mode === 'main') { this._handleCheckmarkClick(container as any); } }; private static _getInstalledLibrary(this: PaperLibrariesSelector, library: LibrarySelectorLibrary): Promise<CRM.InstalledLibrary> { return new Promise<CRM.InstalledLibrary>((resolve) => { browserAPI.storage.local.get<CRM.StorageLocal>().then((e) => { const libs = e.libraries; for (const lib of libs) { if (lib.name === library.name) { resolve(lib); } } resolve(null); }); }); } private static _revertToNormalEditor(this: PaperLibrariesSelector) { window.app.$.ribbonScriptName.innerText = this._editingInstance.name; window.app.$.fullscreenEditorToggle.style.display = 'block'; if (!this._editingInstance.wasFullscreen) { window.scriptEdit.exitFullScreen(); } } private static _discardLibEditChanges(this: PaperLibrariesSelector) { this._revertToNormalEditor(); } private static async _saveLibEditChanges(this: PaperLibrariesSelector) { const newVal = window.scriptEdit.fullscreenEditorManager.getValue(); const lib = this._editingInstance.library; browserAPI.storage.local.get<CRM.StorageLocal>().then((e) => { const installedLibs = e.libraries; for (const installedLib of installedLibs) { if (installedLib.name === lib.name) { installedLib.code = newVal; } } this._setLibraries(installedLibs); }); this._revertToNormalEditor(); } private static async _genOverlayWidget(this: PaperLibrariesSelector) { const container = document.createElement('div'); container.style.backgroundColor = 'white'; container.style.padding = '10px'; window.setDisplayFlex(container); const cancelButton = document.createElement('paper-button'); cancelButton.setAttribute('raised', ''); cancelButton.innerText = await this.___(I18NKeys.generic.cancel); const saveButton = document.createElement('paper-button'); saveButton.innerText = await this.___(I18NKeys.generic.save); saveButton.setAttribute('raised', ''); saveButton.style.marginLeft = '15px'; cancelButton.style.color = saveButton.style.color = 'rgb(38, 153, 244)'; cancelButton.addEventListener('click', () => { this._discardLibEditChanges(); }); saveButton.addEventListener('click', () => { this._saveLibEditChanges(); }); container.appendChild(cancelButton); container.appendChild(saveButton); const editor = window.scriptEdit.fullscreenEditorManager.editor; if (!window.scriptEdit.fullscreenEditorManager.isDiff(editor)) { (editor as monaco.editor.IStandaloneCodeEditor).addOverlayWidget({ getId() { return 'library.exit.buttons' }, getDomNode() { return container; }, getPosition() { return { preference: monaco.editor.OverlayWidgetPositionPreference.TOP_RIGHT_CORNER } } }); } } private static async _openLibraryEditor(this: PaperLibrariesSelector, library: LibrarySelectorLibrary) { const wasFullscreen = window.scriptEdit.fullscreen; const name = window.app.$.ribbonScriptName.innerText; this._editingInstance = { wasFullscreen, name, library } window.app.$.ribbonScriptName.innerText = await this.___( I18NKeys.options.tools.paperLibrariesSelector.editing, library.name); await window.scriptEdit.enterFullScreen(); const installedLibrary = await this._getInstalledLibrary(library); const isTs = installedLibrary.ts && installedLibrary.ts.enabled; window.scriptEdit.fullscreenEditorManager.switchToModel('libraryEdit', installedLibrary.code, isTs ? window.scriptEdit.fullscreenEditorManager.EditorMode.TS : window.scriptEdit.fullscreenEditorManager.EditorMode.JS); window.app.$.fullscreenEditorToggle.style.display = 'none'; await this._genOverlayWidget(); } static async _edit(this: PaperLibrariesSelector, e: Polymer.ClickEvent) { const manager = window.codeEditBehavior.getEditor(); if (manager.isTextarea(manager.getEditorAsMonaco())) { window.app.util.showToast( this.___(I18NKeys.options.tools.paperLibrariesSelector.pleaseUpdate)); return; } type LibraryElement = HTMLElement & { dataLib: LibrarySelectorLibrary } let parentNode: LibraryElement = null; if (e.target.tagName.toLowerCase() === 'path') { parentNode = e.target.parentElement.parentElement.parentElement as LibraryElement; } else if (e.target.tagName.toLowerCase() === 'svg') { parentNode = e.target.parentElement.parentElement as LibraryElement; } else { parentNode = e.target.parentElement as LibraryElement; } const library = parentNode.dataLib; this._openLibraryEditor(library); } static async _remove(this: PaperLibrariesSelector, e: Polymer.ClickEvent) { type LibraryElement = HTMLElement & { dataLib: LibrarySelectorLibrary } let parentNode: LibraryElement = null; if (e.target.tagName.toLowerCase() === 'path') { parentNode = e.target.parentElement.parentElement.parentElement as LibraryElement; } else if (e.target.tagName.toLowerCase() === 'svg') { parentNode = e.target.parentElement.parentElement as LibraryElement; } else { parentNode = e.target.parentElement as LibraryElement; } const library = parentNode.dataLib; const index = (() => { for (let i = 0 ; i <this.installedLibraries.length; i++) { const installedLibrary = this.installedLibraries[i]; if (installedLibrary.name === library.name) { return i; } } return -1; })(); this.installedLibraries.splice(index, 1); await browserAPI.storage.local.set({ libraries: this.installedLibraries }); //Remove it from view as well this.splice('libraries', this.libraries.indexOf(library), 1); const contentEl = this.$.dropdown; contentEl.style.height = (~~contentEl.getBoundingClientRect().height - 48) + 'px'; } static updateLibraries(this: PaperLibrariesSelector, libraries: LibrarySelectorLibrary[], srcNode: CRM.ScriptNode, mode: 'main'|'background' = 'main') { this.set('usedlibraries', libraries); this._srcNode = srcNode this.mode = mode; this.init(); }; static _getMenu(this: PaperLibrariesSelector) { return this.$.dropdown; } static behaviors = [window.Polymer.PaperDropdownBehavior]; } if (window.objectify) { window.register(PLS); } else { window.addEventListener('RegisterReady', () => { window.register(PLS); }); } } export type PaperLibrariesSelectorBase = Polymer.El<'paper-libraries-selector', typeof PaperLibrariesSelectorElement.PLS & typeof PaperLibrariesSelectorElement.paperLibrariesSelectorProperties >; export type PaperLibrariesSelector = PaperDropdownBehavior<PaperLibrariesSelectorBase>;
the_stack
declare module '@ailhc/enet-pbws' { /** * <p> <code>Byte</code> 类提供用于优化读取、写入以及处理二进制数据的方法和属性。</p> * <p> <code>Byte</code> 类适用于需要在字节层访问数据的高级开发人员。</p> */ export class Byte { /** * <p>主机字节序,是 CPU 存放数据的两种不同顺序,包括小端字节序和大端字节序。通过 <code>getSystemEndian</code> 可以获取当前系统的字节序。</p> * <p> <code>BIG_ENDIAN</code> :大端字节序,地址低位存储值的高位,地址高位存储值的低位。有时也称之为网络字节序。<br/> * <code>LITTLE_ENDIAN</code> :小端字节序,地址低位存储值的低位,地址高位存储值的高位。</p> */ static BIG_ENDIAN: string; /** * <p>主机字节序,是 CPU 存放数据的两种不同顺序,包括小端字节序和大端字节序。通过 <code>getSystemEndian</code> 可以获取当前系统的字节序。</p> * <p> <code>LITTLE_ENDIAN</code> :小端字节序,地址低位存储值的低位,地址高位存储值的高位。<br/> * <code>BIG_ENDIAN</code> :大端字节序,地址低位存储值的高位,地址高位存储值的低位。有时也称之为网络字节序。</p> */ static LITTLE_ENDIAN: string; /**@private */ private static _sysEndian; /**@private 是否为小端数据。*/ protected _xd_: boolean; /**@private */ private _allocated_; /**@private 原始数据。*/ protected _d_: any; /**@private DataView*/ protected _u8d_: any; /**@private */ protected _pos_: number; /**@private */ protected _length: number; /** * <p>获取当前主机的字节序。</p> * <p>主机字节序,是 CPU 存放数据的两种不同顺序,包括小端字节序和大端字节序。</p> * <p> <code>BIG_ENDIAN</code> :大端字节序,地址低位存储值的高位,地址高位存储值的低位。有时也称之为网络字节序。<br/> * <code>LITTLE_ENDIAN</code> :小端字节序,地址低位存储值的低位,地址高位存储值的高位。</p> * @return 当前系统的字节序。 */ static getSystemEndian(): string; /** * 创建一个 <code>Byte</code> 类的实例。 * @param data 用于指定初始化的元素数目,或者用于初始化的TypedArray对象、ArrayBuffer对象。如果为 null ,则预分配一定的内存空间,当可用空间不足时,优先使用这部分内存,如果还不够,则重新分配所需内存。 */ constructor(data?: any); /** * 获取此对象的 ArrayBuffer 数据,数据只包含有效数据部分。 */ get buffer(): ArrayBuffer; /** * <p> <code>Byte</code> 实例的字节序。取值为:<code>BIG_ENDIAN</code> 或 <code>BIG_ENDIAN</code> 。</p> * <p>主机字节序,是 CPU 存放数据的两种不同顺序,包括小端字节序和大端字节序。通过 <code>getSystemEndian</code> 可以获取当前系统的字节序。</p> * <p> <code>BIG_ENDIAN</code> :大端字节序,地址低位存储值的高位,地址高位存储值的低位。有时也称之为网络字节序。<br/> * <code>LITTLE_ENDIAN</code> :小端字节序,地址低位存储值的低位,地址高位存储值的高位。</p> */ get endian(): string; set endian(value: string); /** * <p> <code>Byte</code> 对象的长度(以字节为单位)。</p> * <p>如果将长度设置为大于当前长度的值,则用零填充字节数组的右侧;如果将长度设置为小于当前长度的值,将会截断该字节数组。</p> * <p>如果要设置的长度大于当前已分配的内存空间的字节长度,则重新分配内存空间,大小为以下两者较大者:要设置的长度、当前已分配的长度的2倍,并将原有数据拷贝到新的内存空间中;如果要设置的长度小于当前已分配的内存空间的字节长度,也会重新分配内存空间,大小为要设置的长度,并将原有数据从头截断为要设置的长度存入新的内存空间中。</p> */ set length(value: number); get length(): number; /**@private */ private _resizeBuffer; /** * <p>常用于解析固定格式的字节流。</p> * <p>先从字节流的当前字节偏移位置处读取一个 <code>Uint16</code> 值,然后以此值为长度,读取此长度的字符串。</p> * @return 读取的字符串。 */ readString(): string; /** * 从字节流中 <code>start</code> 参数指定的位置开始,读取 <code>len</code> 参数指定的字节数的数据,用于创建一个 <code>Float32Array</code> 对象并返回此对象。 * @param start 开始位置。 * @param len 需要读取的字节长度。如果要读取的长度超过可读取范围,则只返回可读范围内的值。 * @return 读取的 Float32Array 对象。 */ readFloat32Array(start: number, len: number): any; /** * 从字节流中 <code>start</code> 参数指定的位置开始,读取 <code>len</code> 参数指定的字节数的数据,用于创建一个 <code>Uint8Array</code> 对象并返回此对象。 * @param start 开始位置。 * @param len 需要读取的字节长度。如果要读取的长度超过可读取范围,则只返回可读范围内的值。 * @return 读取的 Uint8Array 对象。 */ readUint8Array(start: number, len: number): Uint8Array; /** * 从字节流中 <code>start</code> 参数指定的位置开始,读取 <code>len</code> 参数指定的字节数的数据,用于创建一个 <code>Int16Array</code> 对象并返回此对象。 * @param start 开始读取的字节偏移量位置。 * @param len 需要读取的字节长度。如果要读取的长度超过可读取范围,则只返回可读范围内的值。 * @return 读取的 Uint8Array 对象。 */ readInt16Array(start: number, len: number): any; /** * 从字节流的当前字节偏移位置处读取一个 IEEE 754 单精度(32 位)浮点数。 * @return 单精度(32 位)浮点数。 */ readFloat32(): number; /** * 从字节流的当前字节偏移量位置处读取一个 IEEE 754 双精度(64 位)浮点数。 * @return 双精度(64 位)浮点数。 */ readFloat64(): number; /** * 在字节流的当前字节偏移量位置处写入一个 IEEE 754 单精度(32 位)浮点数。 * @param value 单精度(32 位)浮点数。 */ writeFloat32(value: number): void; /** * 在字节流的当前字节偏移量位置处写入一个 IEEE 754 双精度(64 位)浮点数。 * @param value 双精度(64 位)浮点数。 */ writeFloat64(value: number): void; /** * 从字节流的当前字节偏移量位置处读取一个 Int32 值。 * @return Int32 值。 */ readInt32(): number; /** * 从字节流的当前字节偏移量位置处读取一个 Uint32 值。 * @return Uint32 值。 */ readUint32(): number; /** * 从字节流的当前字节偏移量位置处读取一个 Uint32 值。读不到不报错,返回undefined; * @return Uint32 值。 */ readUint32NoError(): number; /** * 在字节流的当前字节偏移量位置处写入指定的 Int32 值。 * @param value 需要写入的 Int32 值。 */ writeInt32(value: number): void; /** * 在字节流的当前字节偏移量位置处写入 Uint32 值。 * @param value 需要写入的 Uint32 值。 */ writeUint32(value: number): void; /** * 从字节流的当前字节偏移量位置处读取一个 Int16 值。 * @return Int16 值。 */ readInt16(): number; /** * 从字节流的当前字节偏移量位置处读取一个 Uint16 值。 * @return Uint16 值。 */ readUint16(): number; /** * 在字节流的当前字节偏移量位置处写入指定的 Uint16 值。 * @param value 需要写入的Uint16 值。 */ writeUint16(value: number): void; /** * 在字节流的当前字节偏移量位置处写入指定的 Int16 值。 * @param value 需要写入的 Int16 值。 */ writeInt16(value: number): void; /** * 从字节流的当前字节偏移量位置处读取一个 Uint8 值。 * @return Uint8 值。 */ readUint8(): number; /** * 在字节流的当前字节偏移量位置处写入指定的 Uint8 值。 * @param value 需要写入的 Uint8 值。 */ writeUint8(value: number): void; /** * @internal * 从字节流的指定字节偏移量位置处读取一个 Uint8 值。 * @param pos 字节读取位置。 * @return Uint8 值。 */ _readUInt8(pos: number): number; /** * @internal * 从字节流的指定字节偏移量位置处读取一个 Uint16 值。 * @param pos 字节读取位置。 * @return Uint16 值。 */ _readUint16(pos: number): number; /** * @private * 读取指定长度的 UTF 型字符串。 * @param len 需要读取的长度。 * @return 读取的字符串。 */ private _rUTF; /** * @private * 读取 <code>len</code> 参数指定的长度的字符串。 * @param len 要读取的字符串的长度。 * @return 指定长度的字符串。 */ readCustomString(len: number): string; /** * 移动或返回 Byte 对象的读写指针的当前位置(以字节为单位)。下一次调用读取方法时将在此位置开始读取,或者下一次调用写入方法时将在此位置开始写入。 */ get pos(): number; set pos(value: number); /** * 可从字节流的当前位置到末尾读取的数据的字节数。 */ get bytesAvailable(): number; /** * 清除字节数组的内容,并将 length 和 pos 属性重置为 0。调用此方法将释放 Byte 实例占用的内存。 */ clear(): void; /** * @internal * 获取此对象的 ArrayBuffer 引用。 * @return */ __getBuffer(): ArrayBuffer; /** * <p>将 UTF-8 字符串写入字节流。类似于 writeUTF() 方法,但 writeUTFBytes() 不使用 16 位长度的字为字符串添加前缀。</p> * <p>对应的读取方法为: getUTFBytes 。</p> * @param value 要写入的字符串。 */ writeUTFBytes(value: string): void; /** * <p>将 UTF-8 字符串写入字节流。先写入以字节表示的 UTF-8 字符串长度(作为 16 位整数),然后写入表示字符串字符的字节。</p> * <p>对应的读取方法为: getUTFString 。</p> * @param value 要写入的字符串值。 */ writeUTFString(value: string): void; /** * <p>将 UTF-8 字符串写入字节流。先写入以字节表示的 UTF-8 字符串长度(作为 32 位整数),然后写入表示字符串字符的字节。</p> * @param value 要写入的字符串值。 */ writeUTFString32(value: string): void; /** * @private * 读取 UTF-8 字符串。 * @return 读取的字符串。 */ readUTFString(): string; /** * @private */ readUTFString32(): string; /** * @private * 读字符串,必须是 writeUTFBytes 方法写入的字符串。 * @param len 要读的buffer长度,默认将读取缓冲区全部数据。 * @return 读取的字符串。 */ readUTFBytes(len?: number): string; /** * <p>在字节流中写入一个字节。</p> * <p>使用参数的低 8 位。忽略高 24 位。</p> * @param value */ writeByte(value: number): void; /** * <p>从字节流中读取带符号的字节。</p> * <p>返回值的范围是从 -128 到 127。</p> * @return 介于 -128 和 127 之间的整数。 */ readByte(): number; /** * @internal * <p>保证该字节流的可用长度不小于 <code>lengthToEnsure</code> 参数指定的值。</p> * @param lengthToEnsure 指定的长度。 */ _ensureWrite(lengthToEnsure: number): void; /** * <p>将指定 arraybuffer 对象中的以 offset 为起始偏移量, length 为长度的字节序列写入字节流。</p> * <p>如果省略 length 参数,则使用默认长度 0,该方法将从 offset 开始写入整个缓冲区;如果还省略了 offset 参数,则写入整个缓冲区。</p> * <p>如果 offset 或 length 小于0,本函数将抛出异常。</p> * @param arraybuffer 需要写入的 Arraybuffer 对象。 * @param offset Arraybuffer 对象的索引的偏移量(以字节为单位) * @param length 从 Arraybuffer 对象写入到 Byte 对象的长度(以字节为单位) */ writeArrayBuffer(arraybuffer: any, offset?: number, length?: number): void; /** *<p>将指定 Uint8Array 对象中的以 offset 为起始偏移量, length 为长度的字节序列写入字节流。</p> *<p>如果省略 length 参数,则使用默认长度 0,该方法将从 offset 开始写入整个缓冲区;如果还省略了 offset 参数,则写入整个缓冲区。</p> *<p>如果 offset 或 length 小于0,本函数将抛出异常。</p> *@param uint8Array 需要写入的 Uint8Array 对象。 *@param offset Uint8Array 对象的索引的偏移量(以字节为单位) *@param length 从 Uint8Array 对象写入到 Byte 对象的长度(以字节为单位) */ writeUint8Array(uint8Array: Uint8Array, offset?: number, length?: number): void; /** * 读取ArrayBuffer数据 * @param length * @return */ readArrayBuffer(length: number): ArrayBuffer; } } declare module '@ailhc/enet-pbws' { export enum PackageType { /**握手 */ HANDSHAKE = 1, /**握手回应 */ HANDSHAKE_ACK = 2, /**心跳 */ HEARTBEAT = 3, /**数据 */ DATA = 4, /**踢下线 */ KICK = 5 } } declare module '@ailhc/enet-pbws' { import { PackageType } from '@ailhc/enet-pbws'; import { Byte } from '@ailhc/enet-pbws'; global { interface IHandShakeReq { sys?: { /**客户端类型 */ type?: number | string; /**客户端版本 */ version?: number | string; /**协议版本 */ protoVersion?: number | string; /**rsa 校验 */ rsa?: any; }; user?: any; } /** * 默认数据包协议key,有就做数据协议编码,没有就不做数据协议编码 */ interface IPackageTypeProtoKeyMap { [key: number]: IPackageTypeProtoKey; } interface IPackageTypeProtoKey { type: PackageType; encode?: string; decode?: string; } interface IPbProtoIns { /** * 编码 * @param data */ encode(data: any): protobuf.Writer; /** * 解码 * @param data */ decode(data: Uint8Array): any; /** * 验证 * @param data * @returns 如果验证出数据有问题,则会返回错误信息,没问题,返回为空 */ verify(data: any): any; } } export class PbProtoHandler implements enet.IProtoHandler { protected _protoMap: { [key: string]: IPbProtoIns; }; protected _byteUtil: Byte; /**数据包类型协议 {PackageType: 对应的协议key} */ protected _pkgTypeProtoKeyMap: IPackageTypeProtoKeyMap; protected _handShakeRes: any; /** * * @param pbProtoJs 协议导出js对象 * @param pkgTypeProtoKeys 数据包类型协议 {PackageType} 对应的协议key */ constructor(pbProtoJs: any, pkgTypeProtoKeys?: IPackageTypeProtoKey[]); private _heartbeatCfg; get heartbeatConfig(): enet.IHeartBeatConfig; get handShakeRes(): any; setHandshakeRes<T>(handShakeRes: T): void; protoKey2Key(protoKey: string): string; protected _protoEncode<T>(protoKey: string, data: T): Uint8Array; encodePkg<T>(pkg: enet.IPackage<T>, useCrypto?: boolean): enet.NetData; encodeMsg<T>(msg: enet.IMessage<T, any>, useCrypto?: boolean): enet.NetData; decodePkg<T>(data: enet.NetData): enet.IDecodePackage<T>; } } declare module '@ailhc/enet-pbws' { export * from '@ailhc/enet-pbws'; export * from '@ailhc/enet-pbws'; export * from '@ailhc/enet-pbws'; }
the_stack
import * as React from "react"; import { GridCell, GridCellKind, GridSelection, Rectangle } from "../data-grid/data-grid-types"; import ScrollingDataGrid, { ScrollingDataGridProps } from "../scrolling-data-grid/scrolling-data-grid"; import { SearchWrapper } from "./data-grid-search-style"; import { assert } from "../common/support"; import { InnerGridCell } from "index"; // icons const UpArrow = () => ( <svg className="button-icon" viewBox="0 0 512 512"> <path fill="none" stroke="currentColor" strokeLinecap="round" strokeLinejoin="round" strokeWidth="48" d="M112 244l144-144 144 144M256 120v292" /> </svg> ); const DownArrow = () => ( <svg className="button-icon" viewBox="0 0 512 512"> <path fill="none" stroke="currentColor" strokeLinecap="round" strokeLinejoin="round" strokeWidth="48" d="M112 268l144 144 144-144M256 392V100" /> </svg> ); const CloseX = () => ( <svg className="button-icon" viewBox="0 0 512 512"> <path fill="none" stroke="currentColor" strokeLinecap="round" strokeLinejoin="round" strokeWidth="32" d="M368 368L144 144M368 144L144 368" /> </svg> ); export interface DataGridSearchProps extends Omit<ScrollingDataGridProps, "prelightCells"> { readonly getCellsForSelection?: (selection: Rectangle) => readonly (readonly GridCell[])[]; readonly onSearchResultsChanged?: (results: readonly (readonly [number, number])[], navIndex: number) => void; readonly searchColOffset: number; readonly showSearch?: boolean; readonly onSearchClose?: () => void; } const targetSearchTimeMS = 10; const DataGridSearch: React.FunctionComponent<DataGridSearchProps> = p => { const { onKeyDown, getCellsForSelection, onSearchResultsChanged, searchColOffset, showSearch = false, onSearchClose, ...rest } = p; const { canvasRef, cellYOffset, rows, columns, getCellContent } = p; const [searchString, setSearchString] = React.useState(""); const [searchStatus, setSearchStatus] = React.useState<{ rowsSearched: number; results: number; selectedIndex: number; }>(); const searchStatusRef = React.useRef(searchStatus); searchStatusRef.current = searchStatus; const inputRef = React.useRef<HTMLInputElement | null>(null); const searchHandle = React.useRef<number>(); const [searchResults, setSearchResults] = React.useState<readonly (readonly [number, number])[]>([]); const cancelSearch = React.useCallback(() => { if (searchHandle.current !== undefined) { window.cancelAnimationFrame(searchHandle.current); searchHandle.current = undefined; } }, []); const getCellsForSelectionMangled = React.useCallback( (selection: GridSelection): readonly (readonly InnerGridCell[])[] => { if (getCellsForSelection !== undefined) return getCellsForSelection(selection.range); if (selection.range === undefined) { return [[getCellContent(selection.cell)]]; } const range = selection.range; const result: InnerGridCell[][] = []; for (let row = range.y; row < range.y + range.height; row++) { const inner: InnerGridCell[] = []; for (let col = range.x; col < range.x + range.width; col++) { inner.push(getCellContent([col + searchColOffset, row])); } result.push(inner); } return result; }, [getCellContent, getCellsForSelection, searchColOffset] ); const beginSearch = React.useCallback( (str: string) => { const regex = new RegExp(str.replace(/([.?*+^$[\]\\(){}|-])/g, "\\$1"), "i"); let startY = cellYOffset; // Lets assume we can do 10 rows at a time // This is usually very safe and limits the damage for bad // performing sheets. let searchStride = Math.min(10, rows); let rowsSearched = 0; setSearchStatus(undefined); setSearchResults([]); const runningResult: [number, number][] = []; const tick = () => { const tStart = performance.now(); const rowsLeft = rows - rowsSearched; const data = getCellsForSelectionMangled({ cell: [0, 0], range: { x: 0, y: startY, width: columns.length - searchColOffset, height: Math.min(searchStride, rowsLeft, rows - startY), }, }); let added = false; data.forEach((d, row) => d.forEach((cell, col) => { let testString: string | undefined; switch (cell.kind) { case GridCellKind.Text: case GridCellKind.Number: testString = cell.displayData; break; case GridCellKind.Uri: case GridCellKind.Markdown: testString = cell.data; break; case GridCellKind.Boolean: testString = cell.data.toString(); break; case GridCellKind.Image: case GridCellKind.Bubble: // I know its lazy, but unless someone is actually // searching for the whale emoji, this is pretty side effect // free. And ya know... it's nice and easy to do... testString = cell.data.join("🐳"); break; } if (testString !== undefined && regex.test(testString)) { runningResult.push([col + searchColOffset, row + startY]); added = true; } }) ); const tEnd = performance.now(); if (added) { setSearchResults([...runningResult]); } rowsSearched += data.length; assert(rowsSearched <= rows); const selectedIndex = searchStatusRef.current?.selectedIndex ?? -1; setSearchStatus({ results: runningResult.length, rowsSearched, selectedIndex, }); onSearchResultsChanged?.(runningResult, selectedIndex); if (startY + searchStride >= rows) { startY = 0; } else { startY += searchStride; } const tElapsed = tEnd - tStart; const rounded = Math.max(tElapsed, 1); const scalar = targetSearchTimeMS / rounded; searchStride = Math.ceil(searchStride * scalar); if (rowsSearched < rows && runningResult.length < 1000) { searchHandle.current = window.requestAnimationFrame(tick); } }; cancelSearch(); searchHandle.current = window.requestAnimationFrame(tick); }, [ cancelSearch, cellYOffset, columns.length, getCellsForSelectionMangled, onSearchResultsChanged, rows, searchColOffset, ] ); const cancelEvent = React.useCallback((ev: React.MouseEvent) => { ev.stopPropagation(); }, []); const onClose = React.useCallback(() => { onSearchClose?.(); setSearchStatus(undefined); setSearchResults([]); onSearchResultsChanged?.([], -1); cancelSearch(); canvasRef?.current?.focus(); }, [cancelSearch, canvasRef, onSearchClose, onSearchResultsChanged]); const onSearchChange = React.useCallback( (event: React.ChangeEvent<HTMLInputElement>) => { setSearchString(event.target.value); if (event.target.value === "") { setSearchStatus(undefined); setSearchResults([]); cancelSearch(); } else { beginSearch(event.target.value); } }, [beginSearch, cancelSearch] ); React.useEffect(() => { if (showSearch && inputRef.current !== null) { setSearchString(""); inputRef.current.focus({ preventScroll: true }); } }, [showSearch]); const onNext = React.useCallback( (ev?: React.MouseEvent) => { ev?.stopPropagation?.(); if (searchStatus === undefined) return; const newIndex = (searchStatus.selectedIndex + 1) % searchStatus.results; setSearchStatus({ ...searchStatus, selectedIndex: newIndex, }); onSearchResultsChanged?.(searchResults, newIndex); }, [searchStatus, onSearchResultsChanged, searchResults] ); const onPrev = React.useCallback( (ev?: React.MouseEvent) => { ev?.stopPropagation?.(); if (searchStatus === undefined) return; let newIndex = (searchStatus.selectedIndex - 1) % searchStatus.results; if (newIndex < 0) newIndex += searchStatus.results; setSearchStatus({ ...searchStatus, selectedIndex: newIndex, }); onSearchResultsChanged?.(searchResults, newIndex); }, [onSearchResultsChanged, searchResults, searchStatus] ); const onSearchKeyDown = React.useCallback( (event: React.KeyboardEvent<HTMLInputElement>) => { if (((event.ctrlKey || event.metaKey) && event.key === "f") || event.key === "Escape") { onClose(); event.stopPropagation(); event.preventDefault(); } else if (event.key === "Enter") { if (event.shiftKey) { onPrev(); } else { onNext(); } } }, [onClose, onNext, onPrev] ); const rowsSearchedProgress = Math.floor(((searchStatus?.rowsSearched ?? 0) / rows) * 100); const progressStyle: React.CSSProperties = React.useMemo(() => { return { width: `${rowsSearchedProgress}%`, }; }, [rowsSearchedProgress]); // cancel search if the component is unmounted React.useEffect(() => { return () => { cancelSearch(); }; }, [cancelSearch]); let resultString: string | undefined; if (searchStatus !== undefined) { if (searchStatus.results >= 1000) { resultString = `over 1000`; } else { resultString = `${searchStatus.results} result${searchStatus.results !== 1 ? "s" : ""}`; } if (searchStatus.selectedIndex >= 0) { resultString = `${searchStatus.selectedIndex + 1} of ${resultString}`; } } return ( <> <ScrollingDataGrid {...rest} onKeyDown={onKeyDown} prelightCells={searchResults} /> <SearchWrapper showSearch={showSearch} onMouseDown={cancelEvent} onMouseMove={cancelEvent} onMouseUp={cancelEvent} onClick={cancelEvent}> <div className="search-bar-inner"> <input ref={inputRef} onChange={onSearchChange} value={searchString} tabIndex={showSearch ? undefined : -1} onKeyDownCapture={onSearchKeyDown} /> <button tabIndex={showSearch ? undefined : -1} onClick={onPrev} disabled={(searchStatus?.results ?? 0) === 0}> <UpArrow /> </button> <button tabIndex={showSearch ? undefined : -1} onClick={onNext} disabled={(searchStatus?.results ?? 0) === 0}> <DownArrow /> </button> {onSearchClose !== undefined && ( <button tabIndex={showSearch ? undefined : -1} onClick={onClose}> <CloseX /> </button> )} </div> {searchStatus !== undefined && ( <> <div className="search-status"> <div>{resultString}</div> </div> <div className="search-progress" style={progressStyle} /> </> )} </SearchWrapper> </> ); }; export default DataGridSearch;
the_stack
import { ComponentFactoryResolver, ComponentRef, ElementRef, EventEmitter, Injectable, OnDestroy, Type, ViewContainerRef, } from '@angular/core'; import {Subject} from 'rxjs'; import {SmartFormConfiguration} from '../classes/modal-smart-form'; import {ModalOptions} from '../interfaces/modal-options'; import {ContainerModalService} from '../addons/container-modal/container-modal.service'; import {TlModal} from '../modal'; import {TlBackdrop} from '../../core/components/backdrop/backdrop'; import {ActionsModal} from '../../core/enums/actions-modal'; import {ModalResult} from '../../core/enums/modal-result'; import {TlDialogConfirmation} from '../../dialog/dialog-confirmation/dialog-confirmation'; import {ModalFormConfig} from '../interfaces/modal-smart-form-config'; import {ModalInstance} from '../interfaces/modal-instance'; import {TlDialogInfo} from '../../dialog/dialog-info/dialog-info'; import {I18nService} from '../../i18n/i18n.service'; import * as objectPath from 'object-path'; let lastZIndex = 500; @Injectable() export class ModalService implements OnDestroy { public instanceComponent: ModalInstance; public componentList: ModalInstance[] = []; public changeModal = new Subject(); public frontModal = new Subject(); public activeModal: ComponentRef<any>; public componentInjected: ComponentRef<any>; private modalShow = new Subject(); private component: ComponentRef<TlModal>; private view: ViewContainerRef; private modalConfiguration: SmartFormConfiguration; private selectedModal: ModalInstance; private modalOptions: ModalOptions; private backdrop: ComponentRef<TlBackdrop>; private eventCallback: EventEmitter<any>; private visibleModals = []; private referenceSmartForm; constructor(private i18nService: I18nService, private containerModal: ContainerModalService) { } createModalDialog(component: Type<any>, factoryResolver, mdOptions?: ModalOptions) { this.view = this.containerModal.view; return new Promise((resolve) => { this.setComponentModal(component, factoryResolver, null, null, mdOptions); this.handleCallbackModal(resolve); }); } createModal(component: Type<any>, factoryOrConfig: ComponentFactoryResolver, identifier: string = '', properties?: {}, parentElement: ElementRef = null, mdOptions?: ModalOptions) { this.view = this.containerModal.view; return new Promise((resolve) => { this.setComponentModal(component, factoryOrConfig, identifier, parentElement, mdOptions, properties); this.handleCallbackModal(resolve); }); } createSmartFormModal(component: Type<any>, formConfig: ModalFormConfig, mdOptions?: ModalOptions) { this.view = this.containerModal.view; this.modalConfiguration = Object.assign(new SmartFormConfiguration(), formConfig); return new Promise((resolve) => { this.setComponentModal(component, this.modalConfiguration, null, null, mdOptions); this.handleCallbackModal(resolve); }); } private handleCallbackModal(resolve) { if (this.instanceComponent) { this.instanceComponent.eventCallback.subscribe((value) => { resolve(value); }); } } private isConfigSmartForm(config) { return config instanceof SmartFormConfiguration; } private setInjectedComponent(factory, component) { const factoryInject = factory.resolveComponentFactory(component); this.componentInjected = (<TlModal>this.component.instance).body.createComponent(factoryInject); } private createComponentWrapper(factory: ComponentFactoryResolver) { const componentFactory = factory.resolveComponentFactory(TlModal); this.component = this.view.createComponent(componentFactory); (<TlModal>this.component.instance).setServiceControl(this); (<TlModal>this.component.instance).setComponentRef(this.component); this.reallocateComponent(); } private handleSmartFormTitle(config) { if (this.isConfigSmartForm(config)) { if ((<SmartFormConfiguration>this.instanceComponent.smartForm).titleByAction) { const isActionInsert = (<SmartFormConfiguration>this.instanceComponent.smartForm).isInsertAction(); this.replaceTitleModal(isActionInsert ? this.i18nService.getLocale().Modal.includingMessage : this.i18nService.getLocale().Modal.updatingMessage); } } } private replaceTitleModal(value: string) { this.component.instance.title = `${value} ${this.component.instance.title}`; } private setModalOptions(mdOptions: ModalOptions) { this.modalOptions = null; this.modalOptions = Reflect.getOwnMetadata('annotations', Object.getPrototypeOf(this.componentInjected.instance).constructor); this.modalOptions = Object.assign(this.modalOptions[0], mdOptions); } private setModalProperties(properties) { if (properties) { Object.keys(properties).forEach( (value, index) => { (this.componentInjected.instance)[value] = properties[value]; }); } } private setComponentWrapperProperties(config, identifier, parentElement) { (<TlModal>this.component.instance).setOptions(this.modalOptions); (<TlModal>this.component.instance).setIdentifier(this.isConfigSmartForm(config) ? config['identifier'] : identifier); (<TlModal>this.component.instance).setParentElement(this.isConfigSmartForm(config) ? config['parentElement'] : parentElement); } private setInstanceComponent(config: ComponentFactoryResolver | SmartFormConfiguration) { this.instanceComponent = { id: this.component.instance.id, modal: this.component, componentInjected: this.componentInjected, modalOptions: this.modalOptions, eventCallback: new Subject(), smartForm: config }; } private isModalExists(config) { return this.componentList.filter((value, index, array) => config.identifier === value.id)[0]; } private isUniqueSmartForm(config) { return config.unique; } private validateUnique(config) { return this.isConfigSmartForm(config) && this.isModalExists(config) && this.isUniqueSmartForm(config); } private isSmartFormUpdateDeleteAction(config) { return this.isConfigSmartForm(config) && (this.isUpdateAction(config) || this.isDeleteAction(config)); } private setComponentModal(component: Type<any>, config: SmartFormConfiguration | ComponentFactoryResolver, identifier?, parentElement?, mdOptions?: ModalOptions, properties?) { const factory = this.isConfigSmartForm(config) ? config['factory'] : config; if (this.isSmartFormUpdateDeleteAction(config) && !this.validateDataFormUpdate(config)) { return; } if (this.validateUnique(config) && !this.isDeleteAction(config)) { this.showModal(this.isModalExists(config).modal); return; } this.createComponentWrapper(factory); this.setInitialZIndex(); this.setInjectedComponent(factory, component); this.setModalOptions(mdOptions); this.setModalProperties(properties); this.handleBackDrop(factory); this.setComponentWrapperProperties(config, identifier, parentElement); this.setInstanceComponent(config); this.setActiveModal(this.component); this.addNewComponent(); this.handleSmartFormTitle(config); this.emitChangeListModals(); this.handleDeleteSmartForm(config); } private addNewComponent() { this.componentList.push(this.instanceComponent); } private emitChangeListModals() { this.changeModal.next(); } private handleDeleteSmartForm(config: SmartFormConfiguration | ComponentFactoryResolver) { if (this.isConfigSmartForm(config)) { if (this.isDeleteAction(config)) { this.confirmDelete(this.instanceComponent); } } else { if (this.instanceComponent.componentInjected.instance instanceof TlDialogConfirmation) { if (this.referenceSmartForm) { this.removeOfList(this.referenceSmartForm.id); this.view.remove(this.view.indexOf(this.referenceSmartForm.modal.hostView)); } } } } private isUpdateAction(component) { return component.executeAction === ActionsModal.UPDATE; } private validateDataFormUpdate(component) { if (!component['dataForm']) { this.createModalDialog(TlDialogInfo, component['factory'], { title: component['recordNotFoundMessage']}); this.componentInjected.instance.message = component['recordNotFoundMessage']; return false; } return true; } close(id ?: string) { if (id) { const itemList = this.getComponentById(id); if (itemList) { this.removeOfView(itemList.modal); this.removeBackdrop(itemList.modal); this.removeOfList(id); } this.changeModal.next(); this.handleActiveWindow(); return; } if (this.selectedModal) { this.removeOfView(this.selectedModal.modal); this.removeBackdrop(this.selectedModal.modal); this.removeOfList(this.selectedModal.id); this.changeModal.next(); this.handleActiveWindow(); } } minimizeAll() { this.componentList.forEach((item: ModalInstance) => { this.minimize(item.modal); }); } private removeOfView(modal) { this.view.remove(this.view.indexOf(modal.hostView)); this.view.element.nativeElement.removeChild(modal.location.nativeElement); } closeAll() { if (this.view) { this.view.clear(); this.componentList = []; this.destroyBackdrop(); } } private removeOfList(id: string) { this.componentList = this.componentList.filter((item) => item.id !== id); } getModal(identifier: string) { this.selectedModal = this.componentList.filter((item) => item.id === identifier)[0]; return this; } private handleBackDrop(factory: ComponentFactoryResolver) { if (this.modalOptions.backdrop) { this.createBackdrop(TlBackdrop, factory); } } private setInitialZIndex() { lastZIndex++; (<TlModal>this.component.instance).modal.nativeElement.style.zIndex = lastZIndex; } private setZIndex(componentRef: ComponentRef<TlModal>) { const element = componentRef.instance.getElementModal(); lastZIndex = this.getHighestZIndexModals(this.getZIndexModals()); element.nativeElement.style.zIndex = lastZIndex + 10; this.updateZIndexBackdrop(lastZIndex + 5, this.hasBackdrop(componentRef)); } private updateZIndexBackdrop(index: number, hasBackdrop: boolean) { if (this.backdrop && hasBackdrop) { (<TlBackdrop>this.backdrop.instance).setBackdropOptions({'zIndex': index}); } } private getZIndexModals() { const maxZIndex = []; const modals = this.getVisibleModals(); for (let index = 0; index < modals.length; index++) { const element: any = modals[index]; maxZIndex.push(element.firstElementChild.style.zIndex); } return maxZIndex; } private getHighestZIndexModals(arrayModals: Array<any>) { return Math.max.apply(Math, arrayModals); } hasBackdrop(componentRef) { const modalOptions = this.getCurrentModalOptions(componentRef); if (modalOptions.length > 0) { return modalOptions[0].modalOptions.backdrop; } return false; } setActiveModal(componentRef: ComponentRef<any>) { this.setZIndex(componentRef); this.activeModal = componentRef; this.frontModal.next({activeModal: this.activeModal}); } getCurrentModalOptions(compRef: ComponentRef<any>) { return this.componentList.filter((item, index, array) => item.modal === compRef); } private createBackdrop(backdrop: Type<any>, factoryResolver: ComponentFactoryResolver) { if (!this.backdrop) { this.view = this.containerModal.view; const backdropFactory = factoryResolver.resolveComponentFactory(backdrop); this.backdrop = this.view.createComponent(backdropFactory); (<TlBackdrop>this.backdrop.instance).setBackdropOptions({'zIndex': lastZIndex - 1}); this.reallocateBackdrop(); } } private reallocateComponent() { this.view.element.nativeElement.insertAdjacentElement('afterbegin', (this.component.location.nativeElement)); } private reallocateBackdrop() { this.view.element.nativeElement.insertAdjacentElement('afterbegin', (<TlBackdrop>this.backdrop.instance).backdrop.nativeElement); } showModal(item: ComponentRef<any>) { lastZIndex++; item.location.nativeElement.firstElementChild['style'].zIndex = lastZIndex; item.instance.element.nativeElement.style.display = 'block'; this.handleShowBackdrop(this.hasBackdrop(item)); this.setActiveModal(item); this.modalShow.next(); } minimize(component: ComponentRef<any>) { component.instance.element.nativeElement.style.display = 'none'; this.handleHideBackdrop(this.hasBackdrop(component)); this.handleActiveWindow(); } private getVisibleHighestZIndex() { return this.getHighestZIndexModals(this.getZIndexModals()); } private handleActiveWindow() { const highest = this.getVisibleHighestZIndex(); this.componentList.forEach((value) => { if (this.visibleModals.length === 0) { this.hideBackdrop(); return this.activeModal = null; } if (Number(value.modal.instance.modal.nativeElement.style.zIndex) === Number(highest)) { return this.setActiveModal(value.modal); } }); this.handleResetIndex(); } handleResetIndex() { if (this.componentList.length === 0) { this.resetZIndex(); } } private resetZIndex() { lastZIndex = 500; } hideBackdrop() { if (this.backdrop) { this.backdrop.instance.hideBackdrop(); } } private handleHideBackdrop(hasBackdrop: boolean) { if (this.backdrop && hasBackdrop) { this.backdrop.instance.hideBackdrop(); } } private handleShowBackdrop(hasBackdrop: boolean) { if (this.backdrop && hasBackdrop) { this.backdrop.instance.showBackdrop(); } } private getVisibleModals() { this.visibleModals = []; const modals = document.querySelectorAll('tl-modal'); for (let index = 0; index < modals.length; index++) { const element: any = modals[index]; if (element.style.display !== 'none') { this.visibleModals.push(modals[index]); } } return this.visibleModals; } private removeBackdrop(compRef: ComponentRef<any>) { if (this.backdrop && this.hasBackdrop(compRef)) { this.destroyBackdrop(); } } private destroyBackdrop() { if (this.backdrop) { this.backdrop.destroy(); this.view.element.nativeElement.removeChild(this.backdrop.location.nativeElement); this.backdrop = null; } } private getComponentById(id: string) { return this.componentList.filter((item) => item.id === id)[0]; } execCallBack(result: any, id: string): Promise<any> { const componentModal = this.getComponentById(id); return new Promise((resolve) => { if (this.isResultUndefined(result.mdResult)) { return; } if (!(this.isMdResultEqualsOK(result.mdResult))) { this.close(id); this.handleRelativeDataSource(componentModal); } else if (componentModal.modalOptions.closeOnOK) { this.close(id); this.handleRelativeDataSource(componentModal); } this.resultCallback(componentModal, result); this.handleActiveWindow(); resolve(); }); } private handleRelativeDataSource(componentModal: ModalInstance) { if ( componentModal && componentModal.smartForm && componentModal.smartForm['relativeDataSource']) { componentModal.smartForm['relativeDataSource'].setFocus(); } } private resultCallback(component, result) { if (component && result) { component.eventCallback.next(result); this.handleSmartFormCallback(component, result); } } private confirmDelete(component: ModalInstance) { if (component.smartForm['executeAction'] === ActionsModal.DELETE) { this.referenceSmartForm = component; this.createModalDialog(TlDialogConfirmation, this.referenceSmartForm.smartForm['factory'], { title: this.referenceSmartForm.smartForm['deleteTitleConfirmation'] }).then((value: any) => { if (value.mdResult === ModalResult.MRYES) { this.handleSmartFormCallback(this.referenceSmartForm, {formResult: this.referenceSmartForm.smartForm['dataForm']}); } else { this.handleRelativeDataSource(component); } }); this.componentInjected.instance.message = `${this.referenceSmartForm.smartForm['deleteConfirmationMessage']} ${this.getInfoRecord()}`; return true; } return false; } private isDeleteAction(component) { return component.executeAction === ActionsModal.DELETE; } private getDataForm() { return this.referenceSmartForm.smartForm.dataForm; } private getRecordConfig() { return this.referenceSmartForm.smartForm['recordConfig']; } getInfoRecord() { const recordConfig = this.getRecordConfig(); if ( recordConfig.showOnDelete && recordConfig.keyFromDataForm ) { return `<br><b>${ objectPath.get( this.getDataForm(), recordConfig.keyFromDataForm ) }</b>`; } return ''; } private handleSmartFormCallback(component: ModalInstance, result) { if (this.isResultNotAllowed(component.smartForm, result) || !this.isConfigSmartForm(component.smartForm)) { return; } if (this.mathActionsModal(component.smartForm).length === 0) { throw Error('The Action provided is not valid or is undefined'); } this.handleRelativeDataSource(component); this.executeAction(component.smartForm, result); } private mathActionsModal(component: ComponentFactoryResolver | SmartFormConfiguration) { return Object.keys(ActionsModal).filter((value, index, array) => ActionsModal[value] === component['executeAction']); } private executeAction(smartForm: ComponentFactoryResolver | SmartFormConfiguration, result) { const actions = { 'I': () => { smartForm['actions'].insertCall(result.formResult); }, 'U': () => { smartForm['actions'].updateCall(result.formResult); }, 'D': () => { smartForm['actions'].deleteCall(result.formResult); }, 'V': () => { smartForm['actions'].viewCall(); } }; return actions[smartForm['executeAction']](); } private isResultNotAllowed(smartForm: ComponentFactoryResolver | SmartFormConfiguration, result) { return result.mdResult === ModalResult.MRCANCEL || result.mdResult === ModalResult.MRCLOSE || !smartForm['actions']; } private isResultUndefined(result: ModalResult) { return result === undefined; } private isMdResultEqualsOK(result: ModalResult) { return Number(result) === Number(ModalResult.MROK); } ngOnDestroy() { lastZIndex = 1; } }
the_stack
import * as moment from 'moment/moment'; // import * as moment from 'moment-timezone'; import 'moment/locale/it.js'; import { FIREBASESTORAGE_BASE_URL_IMAGE, STORAGE_PREFIX, TYPE_GROUP } from './constants'; import { environment } from '../../environments/environment'; // ????? import { HttpClient } from '@angular/common/http'; import { TranslateHttpLoader } from '@ngx-translate/http-loader'; import { AngularDelegate, ModalController } from '@ionic/angular'; import { ConversationModel } from '../models/conversation'; import { MAX_WIDTH_IMAGES, TYPE_DIRECT, TYPE_SUPPORT_GROUP } from './constants'; import { avatarPlaceholder, getColorBck, getImageUrlThumbFromFirebasestorage } from './utils-user'; /** * Shortest description for phone and tablet * Nota: eseguendo un test su desktop in realtà lo switch avviene a 921px 767px */ export function windowsMatchMedia() { const mq = window.matchMedia('(max-width: 767px)'); if (mq.matches) { // console.log('window width is less than 767px '); return false; } else { // console.log('window width is at least 767px'); return true; } } /** * chiamata da ChatConversationsHandler * restituisce url '/conversations' * @param tenant */ export function conversationsPathForUserId(tenant, userId) { const urlNodeConversations = '/apps/' + tenant + '/users/' + userId + '/conversations'; return urlNodeConversations; } /** * chiamata da ArchivedConversationsHandler * restituisce url '/archived_conversations' * @param tenant */ export function archivedConversationsPathForUserId(tenant, userId) { const urlNodeConversations = '/apps/' + tenant + '/users/' + userId + '/archived_conversations'; return urlNodeConversations; } /** * chiamata da GroupHandler * restituisce url '/group' * @param tenant */ export function groupsPathForUserId(tenant, userId) { const urlNodeConversations = '/apps/' + tenant + '/users/' + userId + '/groups'; return urlNodeConversations; } /** * chiamata da ChatConversationHandler * restituisce url '/messages' */ export function conversationMessagesRef(tenant, userId) { const urlNode = '/apps/' + tenant + '/users/' + userId + '/messages/'; return urlNode; } /** * chiamata da ChatContactsSynchronizer * restituisce url '/contacts' */ export function contactsRef(tenant) { const urlNodeContacts = '/apps/' + tenant + '/contacts/'; return urlNodeContacts; } /** * chiamata da ChatConversationsHandler * restituisce url '/conversations' * @param tenant */ export function nodeTypingsPath(tenant, conversationWith) { const urlNodeConversations = '/apps/' + tenant + '/typings/' + conversationWith; return urlNodeConversations; } /** * restituiso indice item nell'array con uid == key * @param items * @param key */ export function searchIndexInArrayForUid(items, key) { return items.findIndex(i => i.uid === key); } /** * trasforma url contenuti nel testo passato in tag <a> */ export function urlify(text?, name?) { if (!text) return name; //https://stackoverflow.com/questions/161738/what-is-the-best-regular-expression-to-check-if-a-string-is-a-valid-url var regex = /(([\w]+:)?\/\/)?(([\d\w]|%[a-fA-f\d]{2,2})+(:([\d\w]|%[a-fA-f\d]{2,2})+)?@)?([\d\w][-\d\w]{0,253}[\d\w]\.)+[\w]{2,63}(:[\d]+)?(\/([-+_~.\d\w]|%[a-fA-f\d]{2,2})*)*(\?(&?([-+_~.\d\w]|%[a-fA-f\d]{2,2})=?)*)?(#([-+_~.\d\w]|%[a-fA-f\d]{2,2})*)?/; return text.replace(regex, function (url) { if (url.match(/^[/]/)) { return; } var label = url; if (name) { label = name; } if (url.indexOf('@') !== -1) { return '<a href=\"mailto:' + url + '\">' + label + '</a>'; } else if (!url.match(/^[a-zA-Z]+:\/\//)) { url = 'http://' + url; } let link = '<a href=\"' + url + '\" target=\"_blank\">' + label + '</a>'; return link }) } /** * rimuove il tag html dal testo * ATTUALMENTE NON USATA */ export function removeHtmlTags(text) { return text.replace(/(<([^>]+)>)/ig, ""); } /** * calcolo il tempo trascorso tra due date * e lo formatto come segue: * gg/mm/aaaa; * oggi; * ieri; * giorno della settimana (lunedì, martedì, ecc) */ export function setHeaderDate_old(translate, timestamp, lastDate?): string { var date = new Date(timestamp); let now: Date = new Date(); var LABEL_TODAY;// = translate.get('LABEL_TODAY')['value']; var LABEL_TOMORROW;// = translate.get('LABEL_TOMORROW')['value']; translate.get('LABEL_TODAY').subscribe((res: string) => { LABEL_TODAY = res; }); translate.get('LABEL_TOMORROW').subscribe((res: string) => { LABEL_TOMORROW = res; }); var labelDays: string = LABEL_TODAY; var _MS_PER_DAY = 1000 * 60 * 60 * 24; // Esclude l'ora ed il fuso orario var utc1 = Date.UTC(date.getFullYear(), date.getMonth(), date.getDate()); var utc2 = Date.UTC(now.getFullYear(), now.getMonth(), now.getDate()); const days = Math.floor((utc2 - utc1) / _MS_PER_DAY); // console.log('setHeaderDate days: ********************',days); if (days > 6) { labelDays = date.toLocaleDateString();//date.getDate()+"/"+(date.getMonth()+1)+"/"+date.getFullYear(); } else if (days == 0) { labelDays = LABEL_TODAY; } else if (days == 1) { labelDays = LABEL_TOMORROW; } else { labelDays = convertDayToString(translate, date.getDay()); } // console.log('setHeaderDate labelDays: ********************',labelDays); // se le date sono diverse o la data di riferimento non è impostata // ritorna la data calcolata // altrimenti torna null if (lastDate != labelDays || lastDate == null || lastDate == '') { return labelDays; } else { return null; } } export function setHeaderDate(translate, timestamp): string { // const LABEL_TODAY = translate.get('LABEL_TODAY'); // const LABEL_TOMORROW = translate.get('LABEL_TOMORROW'); const date = new Date(timestamp); const now: Date = new Date(); let labelDays = ''; if (now.getFullYear() !== date.getFullYear()) { // quest'anno: data esatta const month = date.getMonth() + 1; labelDays = date.getDay() + '/' + month + '/' + date.getFullYear(); } else if (now.getMonth() !== date.getMonth()) { // questo mese: data esatta const month = date.getMonth() + 1; labelDays = date.getDay() + '/' + month + '/' + date.getFullYear(); } else if (now.getDay() === date.getDay()) { // oggi: oggi labelDays = moment().calendar(timestamp).split(' ')[0].toLocaleLowerCase(); // labelDays = LABEL_TODAY; } else if (now.getDay() - date.getDay() === 1) { // ieri: ieri labelDays = moment().calendar(timestamp).split(' ')[0].toLocaleLowerCase(); // labelDays = LABEL_TOMORROW; } else { // questa settimana: giorno labelDays = convertDayToString(translate, date.getDay()); } // se le date sono diverse o la data di riferimento non è impostata // ritorna la data calcolata // altrimenti torna null return labelDays; } /** * calcolo il tempo trascorso tra la data passata e adesso * utilizzata per calcolare data ultimo accesso utente * @param timestamp */ export function setLastDate(translate, timestamp): string { const LABEL_TODAY = translate.get('LABEL_TODAY'); const LABEL_TOMORROW = translate.get('LABEL_TOMORROW'); const LABEL_TO = translate.get('LABEL_TO'); const LABEL_LAST_ACCESS = translate.get('LABEL_LAST_ACCESS'); var date = new Date(timestamp); let now: Date = new Date(); var labelDays = ''; if (now.getFullYear() !== date.getFullYear()) { const month = date.getMonth() + 1; labelDays = date.getDay() + '/' + month + '/' + date.getFullYear(); } else if (now.getMonth() !== date.getMonth()) { const month = date.getMonth() + 1; labelDays = date.getDay() + '/' + month + '/' + date.getFullYear(); } else if (now.getDay() === date.getDay()) { labelDays = LABEL_TODAY; } else if (now.getDay() - date.getDay() === 1) { labelDays = LABEL_TOMORROW; } else { labelDays = convertDayToString(translate, date.getDay()); } // aggiungo orario const orario = date.getHours() + ':' + (date.getMinutes() < 10 ? '0' : '') + date.getMinutes(); return LABEL_LAST_ACCESS + ' ' + labelDays + ' ' + LABEL_TO + ' ' + orario; } /** * * @param Map * @param timestamp */ export function setLastDateWithLabels(translationMap: Map<string, string>, timestamp: string): string { const date = new Date(timestamp); const now: Date = new Date(); let labelDays = ''; if (now.getFullYear() !== date.getFullYear()) { const month = date.getMonth() + 1; labelDays = date.getDay() + '/' + month + '/' + date.getFullYear(); } else if (now.getMonth() !== date.getMonth()) { const month = date.getMonth() + 1; labelDays = date.getDay() + '/' + month + '/' + date.getFullYear(); } else if (now.getDay() === date.getDay()) { labelDays = translationMap.get('LABEL_TODAY'); } else if (now.getDay() - date.getDay() === 1) { labelDays = translationMap.get('LABEL_TOMORROW'); } else { const days = translationMap.get('ARRAY_DAYS'); labelDays = days[date.getDay()]; } const orario = date.getHours() + ':' + (date.getMinutes() < 10 ? '0' : '') + date.getMinutes(); return translationMap.get('LABEL_LAST_ACCESS') + ' ' + labelDays + ' ' + translationMap.get('LABEL_TO') + ' ' + orario; } /** * * @param translate * @param day */ export function convertDayToString(translate, day) { const ARRAY_DAYS = translate.get('ARRAY_DAYS'); return ARRAY_DAYS[day]; } export function supports_html5_storage() { try { return 'localStorage' in window && window['localStorage'] !== null; } catch (e) { this.g.wdLog(['> Error :' + e]); return false; } } export function supports_html5_session() { try { return 'sessionStorage' in window && window['sessionStorage'] !== null; } catch (e) { return false; } } export function setStoragePrefix(): string { let prefix = STORAGE_PREFIX; try { prefix = environment.storage_prefix + '_'; } catch (e) { } return prefix + this.g.projectid + '_'; } // function for dynamic sorting export function compareValues(key, order = 'asc') { return function (a, b) { if (!a.hasOwnProperty(key) || !b.hasOwnProperty(key)) { // property doesn't exist on either object return 0; } const varA = (typeof a[key] === 'string') ? a[key].toUpperCase() : a[key]; const varB = (typeof b[key] === 'string') ? b[key].toUpperCase() : b[key]; let comparison = 0; if (varA > varB) { comparison = 1; } else if (varA < varB) { comparison = -1; } return ( (order == 'desc') ? (comparison * -1) : comparison ); }; } /** */ export function getNowTimestamp() { //console.log("timestamp:", moment().valueOf()); return moment().valueOf(); } export function getFormatData(timestamp): string { var dateString = moment.unix(timestamp / 1000).format('L'); // const date = new Date(timestamp); // const labelDays = date.getDay()+"/"+date.getMonth()+"/"+date.getFullYear(); return dateString; } export function getTimeLastMessage(timestamp: string) { const timestampNumber = parseInt(timestamp, null) / 1000; const time = getFromNow(timestampNumber); return time; } export function getFromNow(timestamp): string { // var fullDate = new Date(this.news.date.$date) // console.log('FULL DATE: ', fullDate); // var month = '' + (fullDate.getMonth() + 1) // var day = '' + fullDate.getDate() // var year = fullDate.getFullYear() // var hour = '' + fullDate.getHours() // var min = fullDate.getMinutes() // var sec = fullDate.getSeconds() // if (month.length < 2) month = '0' + month; // if (day.length < 2) day = '0' + day; // if (hour.length < 2) hour = '0' + hour; // console.log('Giorno ', day) // console.log('Mese ', month) // console.log('Anno ', year) // console.log('Ora ', hour) // console.log('Min ', min) // console.log('Sec', sec) // this.dateFromNow = moment(year + month + day, "YYYYMMDD").fromNow() // let date_as_string = moment(year + month + day, "YYYYMMDD").fromNow() // let date_as_string = moment(year + "-" + month + "-" + day + " " + hour + ":" + min + ":" + sec).fromNow() // let date_as_string = moment("2017-07-03 08:33:37").fromNow() //var day = new Date(2017, 8, 16); //let date_as_string = moment(day); // var dateString = moment.unix(timestamp).format("MM/DD/YYYY"); // console.log(moment(dateString).fromNow(), dateString); // var date = "Thu Aug 19 2017 19:58:03 GMT+0000 (GMT)"; // console.log(moment(date).fromNow()); // 1 hour ago // console.log(moment.unix(1483228800).fromNow()); // console.log(moment.unix(1501545600).fromNow()); //console.log("timestamp: ",timestamp, " - 1483228800 - ", moment.unix(1483228800).fromNow()); // console.log(); //console.log("window.navigator.language: ", window.navigator.language); moment.locale(window.navigator.language); let date_as_string = moment.unix(timestamp).fromNow(); return date_as_string; } export function popupUrl(html, title) { const url = this.stripTags(html); const w = 600; const h = screen.height - 40; const left = (screen.width / 2) - (w / 2); const top = (screen.height / 2) - (h / 2); const newWindow = window.open(url, '_blank', 'fullscreen=1, titlebar=0, toolbar=no, location=0, status=0, menubar=0, scrollbars=0, resizable=0, width=' + w + ', height=' + h + ', top=' + top + ', left=' + left); if (window.focus) { newWindow.focus() } } export function isPopupUrl(url) { let TEMP = url.split('popup=')[1]; // può essere seguito da & oppure " if (TEMP) { if (TEMP.startsWith('true')) { //console.log('isPopupUrl::::: ', TEMP.startsWith('true')); return true; } else { return false; } } else { return false; } } export function stripTags(html) { return (html.replace(/<.*?>/g, '')).trim(); } export function htmlEntities(str) { return String(str) .replace(/&/g, '&amp;') .replace(/</g, '&lt;') .replace(/>/g, '&gt;') .replace(/"/g, '&quot;') // .replace(/\n/g, '<br>') } export function htmlEntitiesDecode(str) { return String(str) .replace(/&lt;/g, '<') .replace(/&gt;/g, '>') // .replace(/\n/g, '<br>') } export function replaceEndOfLine(text) { // const newText = text.replace(/\n/g, '<br>') const newText = text.replace(/[\n\r]/g, '<br>'); // const newText = text.replace(/<br\s*[\/]?>/gi, '\n') return newText; } export function isExistInArray(members, currentUid) { return members.includes(currentUid); } export function isInArray(key: string, array: Array<string>) { if (array && array !== undefined && array.indexOf(key) > -1) { return true; } return false; } export function createConfirm(translate, alertCtrl, events, title, message, action, onlyOkButton) { var LABEL_ANNULLA;// = translate.get('CLOSE_ALERT_CANCEL_LABEL')['value']; var LABEL_OK;// = translate.get('CLOSE_ALERT_CONFIRM_LABEL')['value']; translate.get('LABEL_ANNULLA').subscribe((res: string) => { LABEL_ANNULLA = res; }); translate.get('LABEL_OK').subscribe((res: string) => { LABEL_OK = res; }); var buttons; if (onlyOkButton) { buttons = [ { text: LABEL_OK, handler: () => { events.publish('PopupConfirmation', LABEL_OK, action); // console.log('Agree clicked'); } } ] } else { buttons = [ { text: LABEL_ANNULLA, handler: () => { events.publish('PopupConfirmation', LABEL_ANNULLA, action); console.log('Disagree clicked'); } }, { text: LABEL_OK, handler: () => { events.publish('PopupConfirmation', LABEL_OK, action); // console.log('Agree clicked'); } } ] } let confirm = alertCtrl.create({ title: title, message: message, buttons, }); // confirm.present(); return confirm; } export function createLoading(loadinController, message) { let loading = loadinController.create({ spinner: 'circles', content: message, }); // this.loading.present(); return loading; } export function convertMessageAndUrlify(messageText) { //messageText = convert(messageText); messageText = urlify(messageText); return messageText; } export function convertMessage(messageText) { messageText = convert(messageText); return messageText; } function convert(str) { str = str.replace(/&/g, '&amp;'); str = str.replace(/>/g, '&gt;'); str = str.replace(/</g, '&lt;'); str = str.replace(/"/g, '&quot;'); str = str.replace(/'/g, '&#039;'); return str; } /** * * @param conversationWith * @param conversationWithFullname * @param conversationChannelType * @param width * @param height */ export function setConversationAvatar( conversationWith: string, conversationWithFullname: string, conversationChannelType: string, width?: string, height?: string ): any { const conversationWidth = (width) ? width : '40px'; const conversationHeight = (height) ? height : '40px'; const conversationAvatar = { uid: conversationWith, conversation_with_fullname: conversationWithFullname, conversation_with: conversationWith, channelType: conversationChannelType, avatar: avatarPlaceholder(conversationWithFullname), color: getColorBck(conversationWithFullname), width: conversationWidth, height: conversationHeight }; return conversationAvatar; } /** */ export function setChannelType(conversationWith: string): string { let channelType = TYPE_DIRECT; if (conversationWith.includes(TYPE_GROUP + '-')) { channelType = TYPE_GROUP; } return channelType; } export function getImageUrlThumb(FIREBASESTORAGE_BASE_URL_IMAGE: string, uid: string) { let imageurl = FIREBASESTORAGE_BASE_URL_IMAGE + environment['firebaseConfig'].storageBucket + '/o/profiles%2F' + uid + '%2Fthumb_photo.jpg?alt=media'; return imageurl; } // /** */ // export function getImageUrlThumbFromFirebasestorage(uid: string) { // const FIREBASESTORAGE_BASE_URL_IMAGE = environment.FIREBASESTORAGE_BASE_URL_IMAGE; // const urlStorageBucket = environment.firebaseConfig.storageBucket + '/o/profiles%2F'; // const imageurl = FIREBASESTORAGE_BASE_URL_IMAGE + urlStorageBucket + uid + '%2Fthumb_photo.jpg?alt=media'; // return imageurl; // } /** */ export function bypassSecurityTrustResourceUrl(url: string) { return this.Dom.bypassSecurityTrustResourceUrl(url); } // getImageUrlThumb(uid: string){ // try { // let imageurl = this.appConfig.getConfig().FIREBASESTORAGE_BASE_URL_IMAGE + environment['firebaseConfig'].storageBucket + '/o/profiles%2F' + uid + '%2Fthumb_photo.jpg?alt=media'; // return imageurl; // } // // } // export function urlExists(url) { // console.log("imageExists::::::"+url); // url = "https://firebasestorage.googleapis.com/v0/b/chat-v2-dev.appspot.com/o/profiles%2F5ad5bd40c975820014ba9009%2Fthumb_photo.jpg?alt=media"; // return false; // } export function jsonToArray(json) { var array = []; Object.keys(json).forEach(e => { //var item = {key: "+e+", val: "+json[e]+"}; var item = json[e]; array.push(item); //console.log('key='+key +'item='+item+array); //console.log(`key=${e} value=${this.member.decoded[e]}`) }); return array; } export function validateEmail(email) { var re = /^(([^<>()[\]\\.,;:\s@\"]+(\.[^<>()[\]\\.,;:\s@\"]+)*)|(\".+\"))@((\[[0-9]{1,3}\.[0-9]{1,3}\.[0-9]{1,3}\.[0-9]{1,3}\])|(([a-zA-Z\-0-9]+\.)+[a-zA-Z]{2,}))$/; return re.test(email); } export function searchEmailOrUrlInString(item) { item = item.toString(); if (validateEmail(item)) { return "<a href='mailto:" + item + "'>" + item + "</a>"; } else { return urlify(item); } } export function isURL(str: string) { var pattern = new RegExp('^(https?:\/\/)?' + // protocol '((([a-z\d]([a-z\d-]*[a-z\d])*)\.)+[a-z]{2,}|' + // domain name '((\d{1,3}\.){3}\d{1,3}))' + // OR ip (v4) address '(\:\d+)?(\/[-a-z\d%_.~+]*)*' + // port and path '(\?[;&a-z\d%_.~+=-]*)?' + // query string '(\#[-a-z\d_]*)?$', 'i'); // fragment locater // console.log('pattern: ', pattern); if (!pattern.test(str)) { return false; } else { return true; } } // export function isHostname() { // if (environment.supportMode === true) { // return true // } // return false // } export function getParameterByName(name: string) { var url = window.location.href; name = name.replace(/[\[\]]/g, '\\$&'); var regex = new RegExp('[?&]' + name + '(=([^&#]*)|&|#|$)', 'i'), results = regex.exec(url); if (!results) return null; if (!results[2]) return ''; return decodeURIComponent(results[2].replace(/\+/g, ' ')); } // export function emailValidator(str) { // let EMAIL_REGEXP = /^[a-z0-9!#$%&'*+\/=?^_`{|}~.-]+@[a-z0-9]([a-z0-9-]*[a-z0-9])?(\.[a-z0-9]([a-z0-9-]*[a-z0-9])?)*$/i; // if (str != "" && (str.length > 5 || EMAIL_REGEXP.test(str))) { // return true; // } else { // return false; // } // } export async function presentModal(modalController, page, attributes) { // console.log('UTILS - presentModal'); const modal: HTMLIonModalElement = await modalController.create({ component: page, componentProps: attributes, swipeToClose: false, backdropDismiss: false }); await modal.present(); modal.onDidDismiss().then((detail: any) => { if (detail !== null) { // console.log('UTILS - presentModal - detail.data:', detail.data); return 'CLOSE!!!!!'; } }); } export async function closeModal(modalController: ModalController) { // console.log('UTILS - closeModal', modalController); await modalController.getTop(); await modalController.dismiss({ confirmed: true }); // try { // modalController.dismiss({ dismissed: true, animate: false, duration: 0 }); // } catch (err) { // console.log('error closeModal', err); // } } export function createTranslateLoader(http: HttpClient) { return new TranslateHttpLoader(http, '../../../assets/i18n/', '.json'); } export function redirect2(router, IDConv, conversationSelected) { if (window.innerWidth < 768) { // mobile // console.log('mobile::::', window.innerWidth, IDConv, conversationSelected, router); if (!IDConv) { router.navigateByUrl('/conversations-list'); } } else { // desktop // console.log('desktop::::', window.innerWidth, IDConv, conversationSelected, router); if (IDConv) { let navigationExtras = { state: { conversationSelected: this.conversationSelected } }; router.navigate(['conversation-detail/' + conversationSelected.uid], navigationExtras); //this.router.navigateByUrl('/conversation-detail/'+this.IDConv); } } } // https://liftcodeplay.com/2020/02/09/how-to-check-for-file-existance-in-firebase-storage/ // export async function imageExists(urlImage: string ) { // //Using async/await // const ref = firebase.storage().refFromURL(urlImage) // try { // return await ref.getDownloadURL() // } catch(e) { // // console.log(e); // } // // const listRef = firebase.storage() // // .refFromURL(imageurl) // // .getDownloadURL() // // .then((response) => { // // // Found it. Do whatever // // console.log('ok imageurl', imageurl); // // return imageurl // // }) // // .catch((err) => { // // console.log('ERROR imageurl', imageurl); // // return // // // Didn't exist... or some other error // // }) // } /** */ export function checkPlatformIsMobile() { // console.log('UTILS - checkPlatformIsMobile:: ', window.innerWidth); if (window.innerWidth < 768) { return true; } return false; } export function checkWindowWidthIsLessThan991px() { // console.log('UTILS - checkWindowWidthIsLessThan991px:: ', window.innerWidth); if (window.innerWidth < 991) { return true; } return false; } // export function toggleSidebar() { // const element = document.getElementById('tld-sidebar'); // element.classList.toggle('open'); // const elementApp = document.getElementsByTagName('app-root')[0]; // if (elementApp.classList.contains('open')) { // elementApp.classList.remove('open'); // elementApp.classList.add('close'); // } else { // elementApp.classList.remove('close'); // elementApp.classList.add('open'); // } // } export function createExternalSidebar(renderer, srcIframe?, urlIcons?) { if (!urlIcons) { urlIcons = 'https://cdnjs.cloudflare.com/ajax/libs/font-awesome/4.7.0/css/font-awesome.min.css'; } // <link rel="stylesheet" href="https://cdnjs.cloudflare.com/ajax/libs/font-awesome/4.7.0/css/font-awesome.min.css"> document.head.innerHTML += '<link rel="stylesheet" type="text/css" href="' + urlIcons + '" />'; if (!srcIframe || srcIframe === '') { srcIframe = 'https://support-pre.tiledesk.com/dashboard/'; } const elementApp = document.getElementsByTagName('app-root')[0]; elementApp.classList.add('close'); // aggiungo js alla pagina let sidebarFunctions = ''; sidebarFunctions += 'function toggleSidebar() {'; sidebarFunctions += 'var element = document.getElementById("tld-sidebar");'; sidebarFunctions += 'element.classList.toggle("open");'; sidebarFunctions += 'var elementApp = document.getElementsByTagName("app-root")[0];'; // sidebarFunctions += 'elementApp.classList.toggle("open");'; sidebarFunctions += 'if(elementApp.classList.contains("open")){'; sidebarFunctions += 'elementApp.classList.remove("open");'; sidebarFunctions += 'elementApp.classList.add("close");'; sidebarFunctions += '} else {'; sidebarFunctions += 'elementApp.classList.remove("close");'; sidebarFunctions += 'elementApp.classList.add("open");'; sidebarFunctions += '}'; sidebarFunctions += '}'; sidebarFunctions += 'function openSidebar() {'; sidebarFunctions += 'var element = document.getElementById("tld-sidebar");'; sidebarFunctions += 'element.classList.add("open");'; sidebarFunctions += 'var elementApp = document.getElementsByTagName("app-root")[0];'; sidebarFunctions += 'elementApp.classList.remove("close");'; sidebarFunctions += 'elementApp.classList.add("open");'; sidebarFunctions += '}'; sidebarFunctions += 'window.onmessage = function(e){'; // sidebarFunctions += 'window.addEventListener("message", (e) => {'; // sidebarFunctions += 'alert("It works!", e);'; sidebarFunctions += 'if (e.data === "open") {'; sidebarFunctions += 'openSidebar();'; sidebarFunctions += '}'; sidebarFunctions += '};'; const divScript = renderer.createElement('script'); divScript.innerHTML = sidebarFunctions; renderer.appendChild(document.body, divScript); let dataString = '<div class="tld-button">'; dataString += '<button class="btn btn-open" onclick="toggleSidebar()"><i class="fa fa-angle-right"></i></button>'; dataString += '<button class="btn btn-close" onclick="toggleSidebar()"><i class="fa fa-close"></i> Close</button>'; dataString += '</div>'; dataString += '<div class="tld-iframe">'; // tslint:disable-next-line: max-line-length dataString += '<iframe src="' + srcIframe + '#/projects-for-panel" width="300" height="100%" marginwidth="0" marginheight="0" frameborder="no" scrolling="yes" style="border-width:1px; border-color:#00000013; background:#FFF; border-style:solid;"></iframe>'; dataString += '</div>'; dataString += '</div>'; // Use Angular's Renderer2 to create the div element const divSidebar = renderer.createElement('div'); divSidebar.innerHTML = dataString; renderer.setProperty(divSidebar, 'id', 'tld-sidebar'); renderer.appendChild(document.body, divSidebar); } export function isGroup(conv: ConversationModel) { // console.log('isGroup conv', conv) // console.log('isGroup conv recipient', conv.recipient) if (conv.recipient && conv.recipient.startsWith('group-') || conv.recipient && conv.recipient.startsWith('support-group')) { // console.log('isGroup conv HERE Y conv.recipient', conv.recipient) return true }; return false }
the_stack
/// <reference path="../../Scripts/Typings/jquery/jquery.d.ts"/> /// <reference path="../../Scripts/Typings/autosize/autosize.d.ts"/> /// <reference path="jquery.chatjs.adapter.ts"/> /// <reference path="jquery.chatjs.pmwindow.ts"/> /// <reference path="jquery.chatjs.friendswindow.ts"/> // Documentation: http://www.chatjs.net/Docs/options/jquery.chatjs.controller.html // Extends the jQuery static object ($.something..) to have ChatJS interface JQueryStatic { chat: (options:ChatControllerOptions) => ChatController; } // Extends the "this.window" object to have ChatJS interface Window { // will hold the ChatJS controller. This is for debugging only chatJs: ChatController; } class ChatControllerOptions { userId:number; adapter:IAdapter; // available rooms text. availableRoomsText:string; // friends window title. You can only set this options when 'allowRoomSelection' is false friendsTitleText:string; typingText:string; // message when there's no users in a room emptyRoomText:string; allowRoomSelection:boolean; // the id of the current room. This option is only valid if 'allowRoomSelection' is false. roomId:number; enableSound:boolean; // offset in the right for all windows in pixels. All windows will start at this offset from the right. offsetRight:number; // spacing between windows in pixels. windowsSpacing:number; // how the chat state is going to be persisted. Allowed values are: "cookie" and "server". //TODO: only "cookie" is currently implemented persistenceMode:string; // if persistenceMode is set to "cookie" (default), this is the cookie name persistenceCookieName:string; // path to the ChatJS folder chatJsContentPath:string; } class ChatJsState { constructor() { this.pmWindows = []; this.mainWindowState = new ChatFriendsWindowState(); } pmWindows:Array<PmWindowState>; // the state of the main window. This is either a ChatFriendsWindowState or a ChatRoomsWindowState mainWindowState:any; } class ChatController implements IStateObject<ChatJsState> { constructor(options:ChatControllerOptions) { var defaultOptions = new ChatControllerOptions(); defaultOptions.roomId = null; defaultOptions.friendsTitleText = "Friends"; defaultOptions.availableRoomsText = "Available rooms"; defaultOptions.typingText = " is typing..."; defaultOptions.offsetRight = 10; defaultOptions.windowsSpacing = 5; defaultOptions.enableSound = true; defaultOptions.persistenceMode = "cookie"; defaultOptions.persistenceCookieName = "chatjs"; defaultOptions.chatJsContentPath = "/chatjs/"; this.options = $.extend({}, defaultOptions, options); // check required properties if (!this.options.roomId) throw "Room id option is required"; this.pmWindows = []; // getting the adapter started. You cannot call the adapter BEFORE this is done. this.options.adapter.init(() => { var state = this.getState(); // the controller must have a listener to the "messages-changed" event because it has to create // new PM windows when the user receives it this.options.adapter.client.onMessagesChanged(0, (message: ChatMessageInfo) => { var _thisControl = this; if (message.UserToId >= 0 && message.UserToId == this.options.userId && !this.findPmWindowByOtherUserId(message.UserFromId)) { setTimeout(function () { _thisControl.createPmWindow(message.UserFromId, true, true) }, 2000); // Evita o historico nao estar atualizado com as mensagens. } }); this.options.adapter.client.onUserListChanged((userListData: ChatUserListChangedInfo) => { var indexRemove = []; for (var i = 0; i < this.pmWindows.length; i++) { var pmWin = this.pmWindows[i]; var removePmWindow = true; // Ate o momento é para remover, a nao ser que seja encontrado na lista de usuarios novos for (var j = 0; j < userListData.UserList.length; j++) { if (userListData.UserList[j].Id == pmWin.otherUserId) { removePmWindow = false; } } if (removePmWindow) { indexRemove.push(i); } } var indexOffset = 0; for (var i = 0; i < indexRemove.length; i++) { this.pmWindows[i - indexOffset].pmWindow.chatWindow.$window.remove(); this.pmWindows[i - indexOffset].pmWindow.options.onClose(chatJs.pmWindows[i - indexOffset].pmWindow.chatWindow); indexOffset++; } }); // if the user is able to select rooms var friendsWindowOptions = new ChatFriendsWindowOptions(); friendsWindowOptions.roomId = this.options.roomId; friendsWindowOptions.adapter = this.options.adapter; friendsWindowOptions.userId = this.options.userId; friendsWindowOptions.offsetRight = this.options.offsetRight; friendsWindowOptions.titleText = this.options.friendsTitleText; friendsWindowOptions.isMaximized = state ? state.mainWindowState.isMaximized : true; // when the friends window changes state, we must save the state of the controller friendsWindowOptions.onStateChanged = () => { this.saveState(); }; // when the user clicks another user, we must create a pm window friendsWindowOptions.userClicked = (userId) => { if (userId != this.options.userId) { // verify whether there's already a PM window for this user var existingPmWindow = this.findPmWindowByOtherUserId(userId); if (existingPmWindow) existingPmWindow.focus(); else this.createPmWindow(userId, true, true); } }; this.mainWindow = $.chatFriendsWindow(friendsWindowOptions); this.setState(state); }); // for debugging only window.chatJs = this; } // creates a new PM window for the given user createPmWindow(otherUserId:number, isMaximized:boolean, saveState:boolean):ChatPmWindow { var chatPmOptions = new ChatPmWindowOptions(); chatPmOptions.userId = this.options.userId; chatPmOptions.otherUserId = otherUserId; chatPmOptions.adapter = this.options.adapter; chatPmOptions.typingText = this.options.typingText; chatPmOptions.isMaximized = isMaximized; chatPmOptions.chatJsContentPath = this.options.chatJsContentPath; chatPmOptions.onCreated = (pmWindow) => { this.pmWindows.push({ otherUserId: otherUserId, conversationId: null, pmWindow: pmWindow }); this.organizePmWindows(); if (saveState) this.saveState(); }; chatPmOptions.onClose = () => { for (var i = 0; i < this.pmWindows.length; i++) if (this.pmWindows[i].otherUserId == otherUserId) { this.pmWindows.splice(i, 1); this.saveState(); this.organizePmWindows(); break; } }; chatPmOptions.onMaximizedStateChanged = () => { this.saveState(); }; return $.chatPmWindow(chatPmOptions); } // saves the windows states saveState():ChatJsState { var state = new ChatJsState(); // persist pm windows state for (var i = 0; i < this.pmWindows.length; i++) { state.pmWindows.push({ otherUserId: this.pmWindows[i].otherUserId, conversationId: null, isMaximized: this.pmWindows[i].pmWindow.getState().isMaximized }); } // persist rooms state state.mainWindowState = this.mainWindow.getState(); switch (this.options.persistenceMode) { case "cookie": this.createCookie(this.options.persistenceCookieName, state); break; case "server": throw "Server persistence is not supported yet"; default: throw "Invalid persistence mode. Available modes are: cookie and server"; } return state; } getState():ChatJsState { var state:ChatJsState; switch (this.options.persistenceMode) { case "cookie": state = this.readCookie(this.options.persistenceCookieName); break; case "server": throw "Server persistence is not supported yet"; default: throw "Invalid persistence mode. Available modes are: cookie and server"; } return state; } // loads the windows states setState(state:ChatJsState = null) { // if a state hasn't been passed in, gets the state. If it continues to be null/undefined, then there's nothing to be done. if (!state) state = this.getState(); if (!state) return; for (var i = 0; i < state.pmWindows.length; i++) { var shouldCreatePmWindow = true; // if there's already a PM window for the given user, we'll not create it if (this.pmWindows.length) { for (var j = 0; j < this.pmWindows.length; j++) { if (state.pmWindows[i].otherUserId && this.pmWindows[j].otherUserId == state.pmWindows[i].otherUserId) { shouldCreatePmWindow = false; break; } } } if (shouldCreatePmWindow) this.createPmWindow(state.pmWindows[i].otherUserId, state.pmWindows[i].isMaximized, false); } this.mainWindow.setState(state.mainWindowState, false); } private eraseCookie(name:string):void { this.createCookie(name, "", -1); } // reads a cookie. The cookie value will be converted to a JSON object if possible, otherwise the value will be returned as is private readCookie(name:string):any { var nameEq = name + "="; var ca = document.cookie.split(';'); var cookieValue:string; for (var i = 0; i < ca.length; i++) { var c = ca[i]; while (c.charAt(0) == ' ') c = c.substring(1, c.length); if (c.indexOf(nameEq) == 0) { cookieValue = c.substring(nameEq.length, c.length); } } if (cookieValue) { try { return JSON.parse(cookieValue); } catch (e) { return cookieValue; } } else return null; } // creates a cookie. The passed in value will be converted to JSON, if not a string private createCookie(name:string, value:any, days?:number):void { var stringedValue:string; if (typeof value == "string") stringedValue = value; else stringedValue = JSON.stringify(value); if (value) var expires; if (days) { var date = new Date(); date.setTime(date.getTime() + (days * 24 * 60 * 60 * 1000)); expires = "; expires=" + date.toUTCString(); } else { expires = ""; } document.cookie = name + "=" + stringedValue + expires + "; path=/"; } private findPmWindowByOtherUserId(otherUserId:number):ChatPmWindow { for (var i = 0; i < this.pmWindows.length; i++) if (this.pmWindows[i].otherUserId == otherUserId) return this.pmWindows[i].pmWindow; return null; } // organizes the pm windows private organizePmWindows() { // this is the initial right offset var rightOffset = +this.options.offsetRight + this.mainWindow.getWidth() + this.options.windowsSpacing; for (var i = 0; i < this.pmWindows.length; i++) { this.pmWindows[i].pmWindow.setRightOffset(rightOffset); rightOffset += this.pmWindows[i].pmWindow.getWidth() + this.options.windowsSpacing; } } options:ChatControllerOptions; // contains a ChatRoomsWindow or a ChatFriendsWindow component. This property is only set if the 'allowRoomsSelection' option is true mainWindow:IWindow<any>; pmWindows:Array<PmWindowInfo>; } $.chat = options => { var chat = new ChatController(options); return chat; };
the_stack
* @packageDocumentation * @hidden */ import { Mesh } from '../../3d/assets/mesh'; import { AttributeName, BufferUsageBit, FormatInfos, MemoryUsageBit, PrimitiveMode, Attribute, DRAW_INFO_SIZE, Buffer, IndirectBuffer, BufferInfo, DrawInfo } from '../../core/gfx'; import { Color } from '../../core/math/color'; import { scene } from '../../core/renderer'; import { Particle } from '../particle'; import { Material, RenderingSubMesh } from '../../core/assets'; const _uvs = [ 0, 0, // bottom-left 1, 0, // bottom-right 0, 1, // top-left 1, 1, // top-right ]; export default class ParticleBatchModel extends scene.Model { private _capacity: number; private _vertAttrs: Attribute[] | null; private _vertSize: number; private _vBuffer: ArrayBuffer | null; private _vertAttrsFloatCount: number; private _vdataF32: Float32Array | null; private _vdataUint32: Uint32Array | null; private _iaInfo: IndirectBuffer; private _iaInfoBuffer: Buffer | null; private _subMeshData: RenderingSubMesh | null; private _mesh: Mesh | null; private _vertCount = 0; private _indexCount = 0; private _startTimeOffset = 0; private _lifeTimeOffset = 0; private _material: Material | null = null; constructor () { super(); this.type = scene.ModelType.PARTICLE_BATCH; this._capacity = 0; this._vertAttrs = null; this._vertSize = 0; this._vBuffer = null; this._vertAttrsFloatCount = 0; this._vdataF32 = null; this._vdataUint32 = null; this._iaInfo = new IndirectBuffer([new DrawInfo()]); this._iaInfoBuffer = this._device.createBuffer(new BufferInfo( BufferUsageBit.INDIRECT, MemoryUsageBit.HOST | MemoryUsageBit.DEVICE, DRAW_INFO_SIZE, DRAW_INFO_SIZE, )); this._subMeshData = null; this._mesh = null; } public setCapacity (capacity: number) { const capChanged = this._capacity !== capacity; this._capacity = capacity; if (this._subMeshData && capChanged) { this.rebuild(); } } public setVertexAttributes (mesh: Mesh | null, attrs: Attribute[]) { if (this._mesh === mesh && this._vertAttrs === attrs) { return; } this._mesh = mesh; this._vertAttrs = attrs; this._vertSize = 0; for (const a of this._vertAttrs) { (a as any).offset = this._vertSize; this._vertSize += FormatInfos[a.format].size; } this._vertAttrsFloatCount = this._vertSize / 4; // number of float // rebuid this.rebuild(); } private createSubMeshData (): ArrayBuffer { this.destroySubMeshData(); this._vertCount = 4; this._indexCount = 6; if (this._mesh) { this._vertCount = this._mesh.struct.vertexBundles[this._mesh.struct.primitives[0].vertexBundelIndices[0]].view.count; this._indexCount = this._mesh.struct.primitives[0].indexView!.count; } const vertexBuffer = this._device.createBuffer(new BufferInfo( BufferUsageBit.VERTEX | BufferUsageBit.TRANSFER_DST, MemoryUsageBit.HOST | MemoryUsageBit.DEVICE, this._vertSize * this._capacity * this._vertCount, this._vertSize, )); const vBuffer: ArrayBuffer = new ArrayBuffer(this._vertSize * this._capacity * this._vertCount); if (this._mesh) { let vOffset = (this._vertAttrs![this._vertAttrs!.findIndex((val) => val.name === AttributeName.ATTR_TEX_COORD)] as any).offset; this._mesh.copyAttribute(0, AttributeName.ATTR_TEX_COORD, vBuffer, this._vertSize, vOffset); // copy mesh uv to ATTR_TEX_COORD let vIdx = this._vertAttrs!.findIndex((val) => val.name === AttributeName.ATTR_TEX_COORD3); vOffset = (this._vertAttrs![vIdx++] as any).offset; this._mesh.copyAttribute(0, AttributeName.ATTR_POSITION, vBuffer, this._vertSize, vOffset); // copy mesh position to ATTR_TEX_COORD3 vOffset = (this._vertAttrs![vIdx++] as any).offset; this._mesh.copyAttribute(0, AttributeName.ATTR_NORMAL, vBuffer, this._vertSize, vOffset); // copy mesh normal to ATTR_NORMAL vOffset = (this._vertAttrs![vIdx++] as any).offset; if (!this._mesh.copyAttribute(0, AttributeName.ATTR_COLOR, vBuffer, this._vertSize, vOffset)) { // copy mesh color to ATTR_COLOR1 const vb = new Uint32Array(vBuffer); for (let iVertex = 0; iVertex < this._vertCount; ++iVertex) { vb[iVertex * this._vertAttrsFloatCount + vOffset / 4] = Color.WHITE._val; } } const vbFloatArray = new Float32Array(vBuffer); for (let i = 1; i < this._capacity; i++) { vbFloatArray.copyWithin(i * this._vertSize * this._vertCount / 4, 0, this._vertSize * this._vertCount / 4); } } vertexBuffer.update(vBuffer); const indices: Uint16Array = new Uint16Array(this._capacity * this._indexCount); if (this._mesh) { this._mesh.copyIndices(0, indices); for (let i = 1; i < this._capacity; i++) { for (let j = 0; j < this._indexCount; j++) { indices[i * this._indexCount + j] = indices[j] + i * this._vertCount; } } } else { let dst = 0; for (let i = 0; i < this._capacity; ++i) { const baseIdx = 4 * i; indices[dst++] = baseIdx; indices[dst++] = baseIdx + 1; indices[dst++] = baseIdx + 2; indices[dst++] = baseIdx + 3; indices[dst++] = baseIdx + 2; indices[dst++] = baseIdx + 1; } } const indexBuffer: Buffer = this._device.createBuffer(new BufferInfo( BufferUsageBit.INDEX | BufferUsageBit.TRANSFER_DST, MemoryUsageBit.DEVICE, this._capacity * this._indexCount * Uint16Array.BYTES_PER_ELEMENT, Uint16Array.BYTES_PER_ELEMENT, )); indexBuffer.update(indices); this._iaInfo.drawInfos[0].vertexCount = this._capacity * this._vertCount; this._iaInfo.drawInfos[0].indexCount = this._capacity * this._indexCount; if (!this._iaInfoBuffer) { this._iaInfoBuffer = this._device.createBuffer(new BufferInfo( BufferUsageBit.INDIRECT, MemoryUsageBit.HOST | MemoryUsageBit.DEVICE, DRAW_INFO_SIZE, DRAW_INFO_SIZE, )); } this._iaInfoBuffer.update(this._iaInfo); this._subMeshData = new RenderingSubMesh([vertexBuffer], this._vertAttrs!, PrimitiveMode.TRIANGLE_LIST, indexBuffer, this._iaInfoBuffer); this.initSubModel(0, this._subMeshData, this._material!); return vBuffer; } public updateMaterial (mat: Material) { this._material = mat; this.setSubModelMaterial(0, mat); } public addParticleVertexData (index: number, pvdata: any[]) { if (!this._mesh) { let offset: number = index * this._vertAttrsFloatCount; this._vdataF32![offset++] = pvdata[0].x; // position this._vdataF32![offset++] = pvdata[0].y; this._vdataF32![offset++] = pvdata[0].z; this._vdataF32![offset++] = pvdata[1].x; // uv this._vdataF32![offset++] = pvdata[1].y; this._vdataF32![offset++] = pvdata[1].z; // frame idx this._vdataF32![offset++] = pvdata[2].x; // size this._vdataF32![offset++] = pvdata[2].y; this._vdataF32![offset++] = pvdata[2].z; this._vdataF32![offset++] = pvdata[3].x; // rotation this._vdataF32![offset++] = pvdata[3].y; this._vdataF32![offset++] = pvdata[3].z; this._vdataUint32![offset++] = pvdata[4]; // color if (pvdata[5]) { this._vdataF32![offset++] = pvdata[5].x; // velocity this._vdataF32![offset++] = pvdata[5].y; this._vdataF32![offset++] = pvdata[5].z; } } else { for (let i = 0; i < this._vertCount; i++) { let offset: number = (index * this._vertCount + i) * this._vertAttrsFloatCount; this._vdataF32![offset++] = pvdata[0].x; // position this._vdataF32![offset++] = pvdata[0].y; this._vdataF32![offset++] = pvdata[0].z; offset += 2; // this._vdataF32![offset++] = index; // this._vdataF32![offset++] = pvdata[1].y; this._vdataF32![offset++] = pvdata[1].z; // frame idx this._vdataF32![offset++] = pvdata[2].x; // size this._vdataF32![offset++] = pvdata[2].y; this._vdataF32![offset++] = pvdata[2].z; this._vdataF32![offset++] = pvdata[3].x; // rotation this._vdataF32![offset++] = pvdata[3].y; this._vdataF32![offset++] = pvdata[3].z; this._vdataUint32![offset++] = pvdata[4]; // color } } } public addGPUParticleVertexData (p: Particle, num: number, time:number) { let offset = num * this._vertAttrsFloatCount * this._vertCount; for (let i = 0; i < this._vertCount; i++) { let idx = offset; this._vdataF32![idx++] = p.position.x; this._vdataF32![idx++] = p.position.y; this._vdataF32![idx++] = p.position.z; this._vdataF32![idx++] = time; this._vdataF32![idx++] = p.startSize.x; this._vdataF32![idx++] = p.startSize.y; this._vdataF32![idx++] = p.startSize.z; this._vdataF32![idx++] = _uvs[2 * i]; this._vdataF32![idx++] = p.rotation.x; this._vdataF32![idx++] = p.rotation.y; this._vdataF32![idx++] = p.rotation.z; this._vdataF32![idx++] = _uvs[2 * i + 1]; this._vdataF32![idx++] = p.startColor.r / 255.0; this._vdataF32![idx++] = p.startColor.g / 255.0; this._vdataF32![idx++] = p.startColor.b / 255.0; this._vdataF32![idx++] = p.startColor.a / 255.0; this._vdataF32![idx++] = p.velocity.x; this._vdataF32![idx++] = p.velocity.y; this._vdataF32![idx++] = p.velocity.z; this._vdataF32![idx++] = p.startLifetime; this._vdataF32![idx++] = p.randomSeed; offset += this._vertAttrsFloatCount; } } public updateGPUParticles (num: number, time: number, dt: number) { const pSize = this._vertAttrsFloatCount * this._vertCount; let pBaseIndex = 0; let startTime = 0; let lifeTime = 0; let lastBaseIndex = 0; let interval = 0; for (let i = 0; i < num; ++i) { pBaseIndex = i * pSize; startTime = this._vdataF32![pBaseIndex + this._startTimeOffset]; lifeTime = this._vdataF32![pBaseIndex + this._lifeTimeOffset]; interval = time - startTime; if (lifeTime - interval < dt) { lastBaseIndex = --num * pSize; this._vdataF32!.copyWithin(pBaseIndex, lastBaseIndex, lastBaseIndex + pSize); i--; } } return num; } public constructAttributeIndex () { if (!this._vertAttrs) { return; } let vIdx = this._vertAttrs.findIndex((val) => val.name === 'a_position_starttime'); let vOffset = (this._vertAttrs[vIdx] as any).offset; this._startTimeOffset = vOffset / 4 + 3; vIdx = this._vertAttrs.findIndex((val) => val.name === 'a_dir_life'); vOffset = (this._vertAttrs[vIdx] as any).offset; this._lifeTimeOffset = vOffset / 4 + 3; } public updateIA (count: number) { if (count <= 0) { return; } const ia = this._subModels[0].inputAssembler; const byteLength = this._vertAttrsFloatCount * this._vertCount; ia.vertexBuffers[0].update(this._vdataF32!, count * byteLength * 4); // ia.vertexBuffers[0].update(this._vdataF32!); this._iaInfo.drawInfos[0].firstIndex = 0; this._iaInfo.drawInfos[0].indexCount = this._indexCount * count; this._iaInfoBuffer!.update(this._iaInfo); } public clear () { this._subModels[0].inputAssembler.indexCount = 0; } public destroy () { super.destroy(); this._vBuffer = null; this._vdataF32 = null; this.destroySubMeshData(); if (this._iaInfoBuffer) { this._iaInfoBuffer.destroy(); this._iaInfoBuffer = null; } } private rebuild () { this._vBuffer = this.createSubMeshData(); this._vdataF32 = new Float32Array(this._vBuffer); this._vdataUint32 = new Uint32Array(this._vBuffer); } private destroySubMeshData () { if (this._subMeshData) { this._subMeshData.destroy(); this._subMeshData = null; this._iaInfoBuffer = null; } } }
the_stack
import { memoryStorage, RerunBehavior, Umzug } from '../src'; import path = require('path'); import { fsSyncer } from 'fs-syncer'; import { expectTypeOf } from 'expect-type'; import VError = require('verror'); jest.mock('../src/storage', () => { const storage = jest.requireActual('../src/storage'); // to simplify test setup, override JSONStorage with memoryStorage to use the default storage but avoid hitting the disk return { ...storage, // eslint-disable-next-line object-shorthand JSONStorage: function () { Object.assign(this, memoryStorage()); }, }; }); const names = (migrations: Array<{ name: string }>) => migrations.map(m => m.name); describe('basic usage', () => { test('requires script files', async () => { const spy = jest.spyOn(console, 'log').mockImplementation(() => {}); const syncer = fsSyncer(path.join(__dirname, 'generated/umzug/globjs'), { 'm1.js': `exports.up = async params => console.log('up1', params)`, }); syncer.sync(); const umzug = new Umzug({ migrations: { glob: ['*.js', { cwd: syncer.baseDir }], }, context: { someCustomSqlClient: {} }, logger: undefined, }); await umzug.up(); expect(names(await umzug.executed())).toEqual(['m1.js']); expect(spy).toHaveBeenCalledTimes(1); expect(spy).toHaveBeenNthCalledWith(1, 'up1', { context: { someCustomSqlClient: {} }, name: 'm1.js', path: path.join(syncer.baseDir, 'm1.js'), }); }); }); describe('custom context', () => { test(`mutating context doesn't affect separate invocations`, async () => { const spy = jest.fn(); const umzug = new Umzug({ migrations: [{ name: 'm1', up: spy }], context: () => ({ counter: 0 }), logger: undefined, }); umzug.on('beforeCommand', ev => { ev.context.counter++; }); await Promise.all([umzug.up(), umzug.up()]); expect(spy).toHaveBeenCalledTimes(2); expect(spy.mock.calls).toMatchObject([ // because the context is lazy (returned by an inline function), both `up()` calls should // get a fresh counter set to 0, which they each increment to 1 [{ context: { counter: 1 } }], [{ context: { counter: 1 } }], ]); }); test(`create doesn't spawn multiple contexts`, async () => { const syncer = fsSyncer(path.join(__dirname, 'generated/create-context'), {}); syncer.sync(); const spy = jest.fn(); const umzug = new Umzug({ migrations: { glob: ['*.js', { cwd: syncer.baseDir }], }, context: spy, logger: undefined, create: { folder: syncer.baseDir, }, }); await umzug.create({ name: 'test.js' }); expect(spy).toHaveBeenCalledTimes(1); }); describe(`resolve asynchronous context getter before the migrations run`, () => { const sleep = async (ms: number) => new Promise(resolve => setTimeout(resolve, ms)); const getContext = async () => { // It guarantees the initialization scripts or asynchronous stuff finished their work // before the actual migrations workflow begins. // Eg: const externalData = await retrieveExternalData(); await sleep(100); return { innerValue: 'text' }; }; test(`context specified as a function`, async () => { const spy = jest.fn(); const umzug = new Umzug({ migrations: [{ name: 'm2', up: spy }], context: getContext, logger: undefined, }); await umzug.up(); expect(spy.mock.calls).toMatchObject([[{ context: { innerValue: 'text' } }]]); }); test(`context specified as a function call`, async () => { const spy = jest.fn(); const umzug = new Umzug({ migrations: [{ name: 'm3', up: spy }], context: getContext(), logger: undefined, }); await umzug.up(); expect(spy.mock.calls).toMatchObject([[{ context: { innerValue: 'text' } }]]); }); }); }); describe('alternate migration inputs', () => { test('with file globbing', async () => { const spy = jest.fn(); const syncer = fsSyncer(path.join(__dirname, 'generated/umzug/glob'), { 'migration1.sql': 'select true', 'migration2.sql': 'select true', 'should-be-ignored.txt': 'abc', 'migration3.sql': 'select true', }); syncer.sync(); const umzug = new Umzug({ migrations: { glob: ['*.sql', { cwd: syncer.baseDir }], resolve: params => ({ ...params, up: async () => spy(params), }), }, context: { someCustomSqlClient: {} }, logger: undefined, }); await umzug.up(); expect(names(await umzug.executed())).toEqual(['migration1.sql', 'migration2.sql', 'migration3.sql']); expect(spy).toHaveBeenCalledTimes(3); expect(spy).toHaveBeenNthCalledWith(1, { context: { someCustomSqlClient: {} }, name: 'migration1.sql', path: path.join(syncer.baseDir, 'migration1.sql'), }); }); test('up and down functions using `resolve` should receive parameters', async () => { const spy = jest.fn(); const syncer = fsSyncer(path.join(__dirname, 'generated/umzug/parameterless-fns'), { 'migration1.sql': 'select true', }); syncer.sync(); const context = { someCustomSqlClient: {} }; const umzug = new Umzug({ migrations: { glob: ['*.sql', { cwd: syncer.baseDir }], resolve: resolveParams => ({ ...resolveParams, up: async upParams => spy('up', { resolveParams, upParams }), down: async downParams => spy('down', { resolveParams, downParams }), }), }, context, logger: undefined, }); await umzug.up(); expect(spy).toHaveBeenCalledTimes(1); expect(spy).toHaveBeenNthCalledWith(1, 'up', { resolveParams: { name: 'migration1.sql', path: path.join(syncer.baseDir, 'migration1.sql'), context }, upParams: { name: 'migration1.sql', path: path.join(syncer.baseDir, 'migration1.sql'), context }, }); spy.mockClear(); await umzug.down(); expect(spy).toHaveBeenCalledTimes(1); expect(spy).toHaveBeenNthCalledWith(1, 'down', { resolveParams: { name: 'migration1.sql', path: path.join(syncer.baseDir, 'migration1.sql'), context }, downParams: { name: 'migration1.sql', path: path.join(syncer.baseDir, 'migration1.sql'), context }, }); }); test('up and down "to"', async () => { const noop = async () => {}; const umzug = new Umzug({ migrations: [ { name: 'm1', up: noop }, { name: 'm2', up: noop }, { name: 'm3', up: noop }, { name: 'm4', up: noop }, { name: 'm5', up: noop }, { name: 'm6', up: noop }, { name: 'm7', up: noop }, ], logger: undefined, }); await umzug.up(); expect(names(await umzug.executed())).toEqual(['m1', 'm2', 'm3', 'm4', 'm5', 'm6', 'm7']); expect(names(await umzug.pending())).toEqual([]); await umzug.down({}); expect(names(await umzug.executed())).toEqual(['m1', 'm2', 'm3', 'm4', 'm5', 'm6']); expect(names(await umzug.pending())).toEqual(['m7']); await umzug.down({ to: undefined }); expect(names(await umzug.executed())).toEqual(['m1', 'm2', 'm3', 'm4', 'm5']); expect(names(await umzug.pending())).toEqual(['m6', 'm7']); await umzug.down({ to: 'm3' }); expect(names(await umzug.executed())).toEqual(['m1', 'm2']); expect(names(await umzug.pending())).toEqual(['m3', 'm4', 'm5', 'm6', 'm7']); await umzug.down({ to: 0 }); expect(names(await umzug.executed())).toEqual([]); expect(names(await umzug.pending())).toEqual(['m1', 'm2', 'm3', 'm4', 'm5', 'm6', 'm7']); await umzug.up({ to: 'm4' }); expect(names(await umzug.executed())).toEqual(['m1', 'm2', 'm3', 'm4']); expect(names(await umzug.pending())).toEqual(['m5', 'm6', 'm7']); }); test('up and down with step', async () => { const umzug = new Umzug({ migrations: [ { name: 'm1', up: async () => {} }, { name: 'm2', up: async () => {} }, { name: 'm3', up: async () => {} }, { name: 'm4', up: async () => {} }, ], logger: undefined, }); await umzug.up({ step: 3 }); expect(names(await umzug.executed())).toEqual(['m1', 'm2', 'm3']); expect(names(await umzug.pending())).toEqual(['m4']); await umzug.down({ step: 2 }); expect(names(await umzug.executed())).toEqual(['m1']); expect(names(await umzug.pending())).toEqual(['m2', 'm3', 'm4']); }); test('up and down options', async () => { const spy = jest.fn(); const umzug = new Umzug({ migrations: [...Array.from({ length: 7 })] .map((_, i) => `m${i + 1}`) .map(name => ({ name, up: async () => spy('up-' + name), down: async () => spy('down-' + name), })), logger: undefined, }); await umzug.up({ migrations: ['m2', 'm4'] }); expect(names(await umzug.executed())).toEqual(['m2', 'm4']); expect(spy.mock.calls).toEqual([['up-m2'], ['up-m4']]); await expect(umzug.up({ migrations: ['m2', 'm4'] })).rejects.toThrowError( /Couldn't find migration to apply with name "m2"/ ); // rerun behavior 'SKIP' silently ignores already-executed migrations await umzug.up({ migrations: ['m2', 'm4'], rerun: RerunBehavior.SKIP }); expect(names(await umzug.executed())).toEqual(['m2', 'm4']); expect(spy.mock.calls).toEqual([['up-m2'], ['up-m4']]); // rerun behavior 'ALLOW' runs already-executed migrations again await umzug.up({ migrations: ['m2', 'm4'], rerun: RerunBehavior.ALLOW }); expect(names(await umzug.executed())).toEqual(['m2', 'm4']); expect(spy.mock.calls).toEqual([['up-m2'], ['up-m4'], ['up-m2'], ['up-m4']]); // you can use migration names to run migrations in the "wrong" order: await umzug.up({ migrations: ['m5', 'm3'], rerun: RerunBehavior.ALLOW }); expect(names(await umzug.executed())).toEqual(['m2', 'm3', 'm4', 'm5']); expect(spy.mock.calls).toEqual([['up-m2'], ['up-m4'], ['up-m2'], ['up-m4'], ['up-m5'], ['up-m3']]); // invalid migration names result in an error: await expect(umzug.up({ migrations: ['m1', 'typo'], rerun: RerunBehavior.ALLOW })).rejects.toThrowError( /Couldn't find migration to apply with name "typo"/ ); // even though m1 _is_ a valid name, it shouldn't have been called - all listed migrations are verified before running any expect(spy.mock.calls).toEqual([['up-m2'], ['up-m4'], ['up-m2'], ['up-m4'], ['up-m5'], ['up-m3']]); expect(JSON.stringify(spy.mock.calls)).not.toContain('up-m1'); await umzug.up(); expect(names(await umzug.executed())).toEqual(['m1', 'm2', 'm3', 'm4', 'm5', 'm6', 'm7']); spy.mockClear(); await umzug.down({ migrations: ['m1', 'm3', 'm5', 'm7'] }); expect(names(await umzug.executed())).toEqual(['m2', 'm4', 'm6']); expect(spy.mock.calls).toEqual([['down-m1'], ['down-m3'], ['down-m5'], ['down-m7']]); // rerun behavior 'SKIP' ignores down migrations that have already been reverted await umzug.down({ migrations: ['m1', 'm3', 'm5', 'm7'], rerun: RerunBehavior.SKIP }); expect(names(await umzug.executed())).toEqual(['m2', 'm4', 'm6']); expect(spy.mock.calls).toEqual([['down-m1'], ['down-m3'], ['down-m5'], ['down-m7']]); await expect(umzug.down({ migrations: ['m1', 'm3', 'm5', 'm7'] })).rejects.toThrowError( /Couldn't find migration to apply with name "m1"/ ); await umzug.down({ migrations: ['m1', 'm3', 'm5', 'm7'], rerun: RerunBehavior.ALLOW }); expect(names(await umzug.executed())).toEqual(['m2', 'm4', 'm6']); expect(spy.mock.calls).toEqual([ ['down-m1'], ['down-m3'], ['down-m5'], ['down-m7'], ['down-m1'], ['down-m3'], ['down-m5'], ['down-m7'], ]); }); test('up and down return migration meta array', async () => { const umzug = new Umzug({ migrations: [ { name: 'm1', path: 'm1.sql', up: async () => {} }, { name: 'm2', path: 'm2.sql', up: async () => {} }, ], logger: undefined, }); const upResults = await umzug.up(); expect(upResults).toEqual([ { name: 'm1', path: 'm1.sql' }, { name: 'm2', path: 'm2.sql' }, ]); const downResults = await umzug.down({ to: 0 }); expect(downResults).toEqual([ { name: 'm2', path: 'm2.sql' }, { name: 'm1', path: 'm1.sql' }, ]); }); test('custom storage', async () => { const spy = jest.fn(); const umzug = new Umzug({ migrations: [{ name: 'm1', up: async () => {} }], context: { someCustomSqlClient: {} }, storage: { executed: async (...args) => spy('executed', ...args), logMigration: async (...args) => spy('logMigration', ...args), unlogMigration: async (...args) => spy('unlogMigration', ...args), }, logger: undefined, }); await umzug.up(); expect(spy.mock.calls).toEqual([ ['executed', { context: { someCustomSqlClient: {} } }], ['logMigration', { name: 'm1', context: { someCustomSqlClient: {} } }], ]); spy.mockClear(); spy.mockReturnValueOnce(['m1']); await umzug.down(); expect(spy.mock.calls).toEqual([ ['executed', { context: { someCustomSqlClient: {} } }], ['unlogMigration', { name: 'm1', context: { someCustomSqlClient: {} } }], ]); }); test('with migrations array', async () => { const spy = jest.fn(); const umzug = new Umzug({ migrations: [ { name: 'migration1', up: async () => spy('migration1-up'), }, { name: 'migration2', up: async () => spy('migration2-up'), }, ], logger: undefined, }); await umzug.up(); expect(names(await umzug.executed())).toEqual(['migration1', 'migration2']); expect(spy).toHaveBeenCalledTimes(2); expect(spy).toHaveBeenNthCalledWith(1, 'migration1-up'); }); test('with function returning migrations array', async () => { const spy = jest.fn(); const umzug = new Umzug({ migrations: context => { expect(context).toEqual({ someCustomSqlClient: {} }); return [ { name: 'migration1', up: async () => spy('migration1-up'), }, { name: 'migration2', up: async () => spy('migration2-up'), }, ]; }, context: { someCustomSqlClient: {} }, logger: undefined, }); await umzug.up(); expect(names(await umzug.executed())).toEqual(['migration1', 'migration2']); expect(spy).toHaveBeenCalledTimes(2); expect(spy).toHaveBeenNthCalledWith(1, 'migration1-up'); }); test('errors are wrapped helpfully', async () => { // Raw errors usually won't tell you which migration threw. This test ensures umzug adds that information. const umzug = new Umzug({ migrations: [ { name: 'm1', up: async () => {}, down: async () => Promise.reject(new Error('Some cryptic failure')), }, { name: 'm2', up: async () => Promise.reject(new Error('Some cryptic failure')), down: async () => {}, }, ], logger: undefined, }); await expect(umzug.up()).rejects.toThrowErrorMatchingInlineSnapshot( `"Migration m2 (up) failed: Original error: Some cryptic failure"` ); await expect(umzug.down()).rejects.toThrowErrorMatchingInlineSnapshot( `"Migration m1 (down) failed: Original error: Some cryptic failure"` ); }); test('Error causes are propagated properly', async () => { const umzug = new Umzug({ migrations: [ { name: 'm1', up: async () => {}, down: async () => Promise.reject(new VError({ info: { extra: 'detail' } }, 'Some cryptic failure')), }, { name: 'm2', up: async () => Promise.reject(new VError({ info: { extra: 'detail' } }, 'Some cryptic failure')), down: async () => {}, }, ], logger: undefined, }); await expect(umzug.up()).rejects.toThrowErrorMatchingInlineSnapshot( `"Migration m2 (up) failed: Some cryptic failure"` ); // slightly weird format verror uses, not worth validating much more than that the `cause` is captured await expect(umzug.up()).rejects.toMatchObject({ jse_cause: { jse_info: { extra: 'detail' }, }, }); await expect(umzug.down()).rejects.toThrowErrorMatchingInlineSnapshot( `"Migration m1 (down) failed: Some cryptic failure"` ); await expect(umzug.down()).rejects.toMatchObject({ jse_cause: { jse_info: { extra: 'detail' }, }, }); }); test('non-error throwables are wrapped helpfully', async () => { // Migration errors usually won't tell you which migration threw. This test ensures umzug adds that information. const umzug = new Umzug({ migrations: [ { name: 'm1', up: async () => {}, // eslint-disable-next-line prefer-promise-reject-errors down: async () => Promise.reject('Some cryptic failure'), }, { name: 'm2', // eslint-disable-next-line prefer-promise-reject-errors up: async () => Promise.reject('Some cryptic failure'), down: async () => {}, }, ], logger: undefined, }); await expect(umzug.up()).rejects.toThrowErrorMatchingInlineSnapshot( `"Migration m2 (up) failed: Non-error value thrown. See info for full props: Some cryptic failure"` ); await expect(umzug.down()).rejects.toThrowErrorMatchingInlineSnapshot( `"Migration m1 (down) failed: Non-error value thrown. See info for full props: Some cryptic failure"` ); }); test('typescript migration files', async () => { const syncer = fsSyncer(path.join(__dirname, 'generated/umzug/typescript'), { 'm1.ts': `export const up = () => {}; export const down = () => {}`, 'm2.ts': `throw SyntaxError('Fake syntax error to simulate typescript modules not being registered')`, }); syncer.sync(); const umzug = new Umzug({ migrations: { glob: ['*.ts', { cwd: syncer.baseDir }], }, logger: undefined, }); expect([names(await umzug.pending()), names(await umzug.executed())]).toEqual([['m1.ts', 'm2.ts'], []]); await umzug.up({ to: 'm1.ts' }); expect([names(await umzug.pending()), names(await umzug.executed())]).toEqual([['m2.ts'], ['m1.ts']]); await expect(umzug.up()).rejects.toThrowErrorMatchingInlineSnapshot(` "Migration m2.ts (up) failed: Original error: Fake syntax error to simulate typescript modules not being registered TypeScript files can be required by adding \`ts-node\` as a dependency and calling \`require('ts-node/register')\` at the program entrypoint before running migrations." `); }); test('with custom file globbing options', async () => { const spy = jest.fn(); const syncer = fsSyncer(path.join(__dirname, 'generated/umzug/glob'), { 'migration1.sql': 'select true', 'migration2.sql': 'select true', 'should-be-ignored.txt': 'abc', 'migration3.sql': 'select true', 'ignoreme1.sql': 'select false', 'ignoreme2.sql': 'select false', }); syncer.sync(); const umzug = new Umzug({ migrations: { glob: ['*.sql', { cwd: syncer.baseDir, ignore: ['ignoreme*.sql'] }], resolve: params => ({ ...params, up: async () => spy(params), }), }, context: { someCustomSqlClient: {} }, logger: undefined, }); await umzug.up(); expect(names(await umzug.executed())).toEqual(['migration1.sql', 'migration2.sql', 'migration3.sql']); expect(spy).toHaveBeenCalledTimes(3); expect(spy).toHaveBeenNthCalledWith(1, { context: { someCustomSqlClient: {} }, name: 'migration1.sql', path: path.join(syncer.baseDir, 'migration1.sql'), }); }); test('allows customization via parent instance', async () => { const spy = jest.fn(); const syncer = fsSyncer(path.join(__dirname, 'generated/umzug/customOrdering'), { 'migration1.sql': 'select true', 'migration2.sql': 'select true', 'should-be-ignored.txt': 'abc', 'migration3.sql': 'select true', }); syncer.sync(); const parent = new Umzug({ migrations: { glob: ['*.sql', { cwd: syncer.baseDir }], resolve: ({ context, ...params }) => ({ ...params, up: async () => context.spy(params), }), }, context: { spy }, logger: undefined, }); const umzug = new Umzug({ ...parent.options, migrations: async context => (await parent.migrations(context)).slice().reverse(), }); await umzug.up(); expect(names(await umzug.executed())).toEqual(['migration3.sql', 'migration2.sql', 'migration1.sql']); expect(spy).toHaveBeenCalledTimes(3); expect(spy).toHaveBeenNthCalledWith(1, { name: 'migration3.sql', path: path.join(syncer.baseDir, 'migration3.sql'), }); }); test('supports nested directories via getMigrations', async () => { const spy = jest.fn(); // folder structure splitting migrations into separate directories, with the filename determining the order: const syncer = fsSyncer(path.join(__dirname, 'generated/umzug/customOrdering'), { directory1: { 'm1.sql': 'select true', 'm1.down.sql': 'select false', 'm4.sql': 'select true', }, deeply: { nested: { directory2: { 'm2.sql': 'select true', 'm3.sql': 'select true', }, }, }, }); syncer.sync(); const withDefaultOrdering = new Umzug({ migrations: { glob: ['**/*.sql', { cwd: syncer.baseDir, ignore: '**/*.down.sql' }], resolve: params => ({ ...params, up: async () => spy(params), }), }, logger: undefined, }); const umzug = new Umzug({ ...withDefaultOrdering.options, migrations: async ctx => (await withDefaultOrdering.migrations(ctx)).slice().sort((a, b) => a.name.localeCompare(b.name)), }); await umzug.up(); expect(names(await umzug.executed())).toEqual(['m1.sql', 'm2.sql', 'm3.sql', 'm4.sql']); expect(spy).toHaveBeenCalledTimes(4); expect(spy).toHaveBeenNthCalledWith(1, { name: 'm1.sql', path: path.join(syncer.baseDir, 'directory1/m1.sql'), context: {}, }); expect(spy).toHaveBeenNthCalledWith(2, { name: 'm2.sql', path: path.join(syncer.baseDir, 'deeply/nested/directory2/m2.sql'), context: {}, }); }); }); describe('types', () => { test('constructor function', () => { expectTypeOf(Umzug).constructorParameters.toMatchTypeOf<{ length: 1 }>(); expectTypeOf(Umzug).toBeConstructibleWith({ migrations: { glob: '*/*.js' }, storage: memoryStorage(), logger: undefined, }); expectTypeOf(Umzug).toBeConstructibleWith({ migrations: { glob: ['*/*.js', { cwd: 'x/y/z' }] }, logger: undefined, }); expectTypeOf(Umzug).toBeConstructibleWith({ migrations: { glob: ['*/*.js', { ignore: ['**/*ignoreme*.js'] }] }, logger: undefined, }); expectTypeOf(Umzug).toBeConstructibleWith({ migrations: [ { name: 'm1', up: async () => {} }, { name: 'm2', up: async () => {}, down: async () => {} }, ], logger: undefined, }); expectTypeOf(Umzug).toBeConstructibleWith({ migrations: [], storage: memoryStorage(), context: { foo: 123 }, logger: console, }); expectTypeOf(Umzug) .constructorParameters.toHaveProperty('0') .toHaveProperty('logger') .toMatchTypeOf<undefined | Pick<Console, 'info' | 'warn' | 'error'>>(); expectTypeOf(Umzug).toBeConstructibleWith({ migrations: [], storage: memoryStorage(), context: { foo: 123 }, logger: { ...console, info: (...args) => expectTypeOf(args).toEqualTypeOf<[Record<string, unknown>]>(), }, }); }); test('rerun behavior is a map of its keys to themselves', () => { expectTypeOf(RerunBehavior).toEqualTypeOf<{ readonly [K in RerunBehavior]: K }>(); }); test('up and down', () => { const up = expectTypeOf(Umzug).instance.toHaveProperty('up'); const down = expectTypeOf(Umzug).instance.toHaveProperty('down'); up.toBeCallableWith({ to: 'migration123' }); up.toBeCallableWith({ migrations: ['m1'], rerun: RerunBehavior.ALLOW }); up.toBeCallableWith({ migrations: ['m1'], rerun: RerunBehavior.SKIP }); up.toBeCallableWith({ migrations: ['m1'], rerun: RerunBehavior.THROW }); up.toBeCallableWith({ migrations: ['m1'], rerun: 'ALLOW' }); up.toBeCallableWith({ migrations: ['m1'], rerun: 'SKIP' }); up.toBeCallableWith({ migrations: ['m1'], rerun: 'THROW' }); // @ts-expect-error (don't allow general strings for rerun behavior) up.toBeCallableWith({ migrations: ['m1'], rerun: 'xyztypo' }); // @ts-expect-error (rerun must be specified with `migrations`) up.toBeCallableWith({ rerun: 'ALLOW' }); // @ts-expect-error (can't go up "to" 0) up.toBeCallableWith({ to: 0 }); down.toBeCallableWith({ to: 'migration123' }); down.toBeCallableWith({ migrations: ['m1'], rerun: RerunBehavior.ALLOW }); down.toBeCallableWith({ migrations: ['m1'], rerun: RerunBehavior.SKIP }); down.toBeCallableWith({ migrations: ['m1'], rerun: RerunBehavior.THROW }); down.toBeCallableWith({ migrations: ['m1'], rerun: 'ALLOW' }); down.toBeCallableWith({ migrations: ['m1'], rerun: 'SKIP' }); down.toBeCallableWith({ migrations: ['m1'], rerun: 'THROW' }); // @ts-expect-error (don't allow general strings for rerun behavior) down.toBeCallableWith({ migrations: ['m1'], rerun: 'xyztypo' }); // @ts-expect-error (rerun can only be specified with `migrations`) down.toBeCallableWith({ rerun: 'ALLOW' }); down.toBeCallableWith({ to: 0 }); // @ts-expect-error (`{ to: 0 }` is a special case. `{ to: 1 }` shouldn't be allowed) down.toBeCallableWith({ to: 1 }); // @ts-expect-error (`{ to: 0 }` is a special case. `{ to: 1 }` shouldn't be allowed) up.toBeCallableWith({ to: 1 }); up.returns.toEqualTypeOf<Promise<Array<{ name: string; path?: string }>>>(); down.returns.toEqualTypeOf<Promise<Array<{ name: string; path?: string }>>>(); }); test('pending', () => { expectTypeOf(Umzug).instance.toHaveProperty('pending').returns.resolves.items.toEqualTypeOf<{ name: string; path?: string; }>(); }); test('executed', () => { expectTypeOf(Umzug).instance.toHaveProperty('executed').returns.resolves.items.toEqualTypeOf<{ name: string; path?: string; }>(); }); test('migration type', () => { const umzug = new Umzug({ migrations: { glob: '*/*.ts' }, context: { someCustomSqlClient: {} }, logger: undefined, }); type Migration = typeof umzug._types.migration; expectTypeOf<Migration>() .parameter(0) .toMatchTypeOf<{ name: string; path?: string; context: { someCustomSqlClient: {} } }>(); expectTypeOf<Migration>().returns.toEqualTypeOf<Promise<unknown>>(); }); test('context type', () => { const umzug = new Umzug({ migrations: { glob: '*/*.ts' }, context: { someCustomSqlClient: {} }, logger: undefined, }); type Context = typeof umzug._types.context; expectTypeOf<Context>().toMatchTypeOf<{ someCustomSqlClient: {} }>(); }); test('custom resolver type', () => { // eslint-disable-next-line no-new new Umzug({ migrations: { glob: '*/*.ts', resolve: params => { expectTypeOf(params).toEqualTypeOf<{ name: string; path?: string; context: { someCustomSqlClient: {} } }>(); return { name: '', up: async () => {} }; }, }, context: { someCustomSqlClient: {} }, logger: undefined, }); }); test('event types', () => { const umzug = new Umzug({ migrations: [], context: { someCustomSqlClient: {} }, logger: undefined, }); umzug.on('migrating', params => { expectTypeOf(params.name).toBeString(); expectTypeOf(params.path).toEqualTypeOf<string | undefined>(); expectTypeOf(params.context).toEqualTypeOf({ someCustomSqlClient: {} }); }); umzug.on('migrated', params => { expectTypeOf(params.name).toBeString(); expectTypeOf(params.path).toEqualTypeOf<string | undefined>(); expectTypeOf(params.context).toEqualTypeOf({ someCustomSqlClient: {} }); }); umzug.on('reverting', params => { expectTypeOf(params.name).toBeString(); expectTypeOf(params.path).toEqualTypeOf<string | undefined>(); expectTypeOf(params.context).toEqualTypeOf({ someCustomSqlClient: {} }); }); umzug.on('reverted', params => { expectTypeOf(params.name).toBeString(); expectTypeOf(params.path).toEqualTypeOf<string | undefined>(); expectTypeOf(params.context).toEqualTypeOf({ someCustomSqlClient: {} }); }); }); }); describe('error cases', () => { test('invalid storage', () => { expect( () => new Umzug({ migrations: [], storage: {} as any, logger: undefined, }) ).toThrowError(/Invalid umzug storage/); }); test('unresolvable file', async () => { const syncer = fsSyncer(path.join(__dirname, 'generated/umzug/errors/unresolvable'), { 'migration1.txt': 'create table somehow', }); syncer.sync(); const umzug = new Umzug({ migrations: { glob: ['*.txt', { cwd: syncer.baseDir }], }, logger: undefined, }); await expect(umzug.up()).rejects.toThrowError( /No resolver specified for file .*migration1.txt. See docs for guidance on how to write a custom resolver./ ); }); test('typo in "to"', async () => { const syncer = fsSyncer(path.join(__dirname, 'generated/umzug/errors/typo'), { 'migration1.js': 'exports.up = () => {}', }); syncer.sync(); const umzug = new Umzug({ migrations: { glob: ['*.txt', { cwd: syncer.baseDir }], }, logger: undefined, }); await expect(umzug.up({ to: 'typo' })).rejects.toThrowError(/Couldn't find migration to apply with name "typo"/); }); }); describe('events', () => { test('events', async () => { const mock = jest.fn(); const spy = (label: string) => (...args: unknown[]) => mock(label, ...args); const umzug = new Umzug({ migrations: [ { name: 'm1', up: spy('up-m1'), down: spy('down-m1') }, { name: 'm2', up: spy('up-m2'), down: spy('down-m2') }, ], logger: undefined, }); umzug.on('migrating', spy('migrating')); umzug.on('migrated', spy('migrated')); const revertingSpy = spy('reverting'); umzug.on('reverting', revertingSpy); umzug.on('reverted', spy('reverted')); await umzug.up(); expect(mock.mock.calls).toMatchObject([ ['migrating', { name: 'm1' }], ['up-m1', { name: 'm1' }], ['migrated', { name: 'm1' }], ['migrating', { name: 'm2' }], ['up-m2', { name: 'm2' }], ['migrated', { name: 'm2' }], ]); mock.mockClear(); await umzug.down(); expect(mock.mock.calls).toMatchObject([ ['reverting', { name: 'm2' }], ['down-m2', { name: 'm2' }], ['reverted', { name: 'm2' }], ]); mock.mockClear(); umzug.off('reverting', revertingSpy); await umzug.down(); expect(mock.mock.calls).toMatchObject([ // `reverting` shouldn't be here because the listener was removed ['down-m1', { name: 'm1' }], ['reverted', { name: 'm1' }], ]); }); }); describe('custom logger', () => { test('uses custom logger', async () => { const spy = jest.fn(); const umzug = new Umzug({ migrations: [{ name: 'm1', up: async () => {} }], logger: { info: spy, warn: spy, error: spy, debug: spy, }, }); await umzug.up(); expect(spy).toHaveBeenCalledTimes(2); expect( spy.mock.calls.map(([c]) => ({ ...c, durationSeconds: c.durationSeconds && Math.floor(c.durationSeconds) })) ).toEqual([ { event: 'migrating', name: 'm1' }, { event: 'migrated', name: 'm1', durationSeconds: 0 }, ]); }); });
the_stack
import * as React from 'react'; import { Form, Table, Input, Popover, InputNumber } from 'antd'; import { localize } from '../../LocaleWrapper/LocaleWrapper'; import en_US from '../../../locale/en_US'; import { ColorMap, ColorMapType, ColorMapEntry } from 'geostyler-style'; import ExtendedField from '../Field/ExtendedField/ExtendedField'; import ColorMapTypeField from '../Field/ColorMapTypeField/ColorMapTypeField'; import ColorField from '../Field/ColorField/ColorField'; import OffsetField from '../Field/OffsetField/OffsetField'; import OpacityField from '../Field/OpacityField/OpacityField'; import RasterUtil from '../../../Util/RasterUtil'; import ColorRampCombo from '../../RuleGenerator/ColorRampCombo/ColorRampCombo'; import RuleGeneratorUtil from '../../../Util/RuleGeneratorUtil'; import { brewer } from 'chroma-js'; import './ColorMapEditor.less'; import _get from 'lodash/get'; import _cloneDeep from 'lodash/cloneDeep'; // i18n export interface ColorMapEditorLocale { typeLabel: string; extendedLabel: string; colorMapEntriesLabel: string; titleLabel: string; nrOfClassesLabel: string; colorRampLabel: string; colorLabel: string; quantityLabel: string; labelLabel: string; opacityLabel: string; } export interface ColorMapEntryRecord extends ColorMapEntry { key: number; } interface ColorMapEditorDefaultProps { locale: ColorMapEditorLocale; colorRamps: { [name: string]: string[]; }; } // non default props export interface ColorMapEditorProps extends Partial<ColorMapEditorDefaultProps> { colorMap?: ColorMap; onChange?: (colorMap: ColorMap) => void; } export interface ColorMapEditorState { colorRamp: string; } export class ColorMapEditor extends React.Component<ColorMapEditorProps, ColorMapEditorState> { static componentName: string = 'ColorMapEditor'; public static defaultProps: ColorMapEditorDefaultProps = { locale: en_US.GsColorMapEditor, colorRamps: { GeoStyler: ['#E7000E', '#F48E00', '#FFED00', '#00943D', '#272C82', '#611E82'], GreenRed: ['#00FF00', '#FF0000'], ...brewer } }; constructor(props: ColorMapEditorProps) { super(props); this.state = { colorRamp: Object.keys(props.colorRamps)[0] }; } updateColorMap = (prop: string, value: any) => { const { colorMap, onChange } = this.props; let newColorMap: ColorMap; if (colorMap) { newColorMap = _cloneDeep(colorMap); } else { newColorMap = { type: 'ramp' }; } newColorMap[prop] = value; if (onChange) { onChange(newColorMap); } }; onExtendedChange = (extended: boolean) => { this.updateColorMap('extended', extended); }; onTypeChange = (type: ColorMapType) => { this.updateColorMap('type', type); }; /** * Creates the number of default ColorMapEntries according to specified * number of classes. Table will be updated accordingly. * */ onNrOfClassesChange = (value: number) => { const { colorRamp } = this.state; const cmEntries = _get(this.props, 'colorMap.colorMapEntries'); const newCmEntries: ColorMapEntry[] = cmEntries ? _cloneDeep(cmEntries) : []; if (value > newCmEntries.length) { while (newCmEntries.length < value) { newCmEntries.push(RasterUtil.generateColorMapEntry()); } } else { while (newCmEntries.length > value) { newCmEntries.pop(); } } this.applyColors(colorRamp, newCmEntries); this.updateColorMap('colorMapEntries', newCmEntries); }; onColorRampChange = (colorRamp: string) => { const cmEntries = _get(this.props, 'colorMap.colorMapEntries'); const newCmEntries = this.applyColors(colorRamp, _cloneDeep(cmEntries)); this.updateColorMap('colorMapEntries', newCmEntries); this.setState({ colorRamp }); }; /** * Applies the colors of the selected colorRamp to the colorMapEntries. * Important: This method modifies the array of colorMapEntries 'cmEntries'. * * @return {ColorMapEntry[]} cmEntries, the modified array of colorMapEntries. */ applyColors = (colorRamp: string, cmEntries: ColorMapEntry[] = []): ColorMapEntry[] => { const { colorRamps } = this.props; const ramp = colorRamps[colorRamp] ? colorRamps[colorRamp] : colorRamps[Object.keys(colorRamps)[0]]; const colors = RuleGeneratorUtil.generateColors(ramp, cmEntries.length); cmEntries.forEach((entry: ColorMapEntry, idx: number) => { entry.color = colors[idx]; }); return cmEntries; }; /** * Updates property 'key' with 'value' of colorMapEntry at position 'index'. * Creates a new colorMapEntry if it did not exist yet. */ setValueForColorMapEntry = (idx: number, key: string, value: any) => { const cmEntries = _get(this.props, 'colorMap.colorMapEntries'); let newCmEntries: ColorMapEntry[]; if (cmEntries) { newCmEntries = _cloneDeep(cmEntries); newCmEntries[idx][key] = value; } else { newCmEntries = [{}] as ColorMapEntry[]; newCmEntries[0][key] = value; } this.updateColorMap('colorMapEntries', newCmEntries); }; getColorMapRecords = () => { let cmEntries = _get(this.props, 'colorMap.colorMapEntries'); if (!cmEntries) { return []; } else { return cmEntries.map((entry: ColorMapEntry, index: number): ColorMapEntryRecord => { return { key: index, ...entry }; }); } }; /** * Renderer method for the label column. */ labelRenderer = (text: string, record: ColorMapEntryRecord) => { const { locale } = this.props; const input = ( <Input className="gs-colormap-label-input" value={record.label} onChange={(event: React.ChangeEvent<HTMLInputElement>) => { const target = event.target; this.setValueForColorMapEntry(record.key, 'label', target.value); }} />); return ( <Popover content={record.label} title={locale.labelLabel} > {input} </Popover> ); }; /** * Renderer method for the color column. */ colorRenderer = (text: string, record: ColorMapEntryRecord) => { const input = ( <ColorField color={record.color} onChange={(color: string) => { this.setValueForColorMapEntry(record.key, 'color', color); }} /> ); return input; }; /** * Renderer method for the quantity column. */ quantityRenderer = (text: string, record: ColorMapEntryRecord) => { const input = ( <OffsetField className="gs-colormap-quantity-input" offset={record.quantity} onChange={(value: number) => { this.setValueForColorMapEntry(record.key, 'quantity', value); }} /> ); return input; }; /** * Renderer method for the opacity column. */ opacityRenderer = (text: string, record: ColorMapEntryRecord) => { const input = ( <OpacityField className="gs-colormap-opacity-input" opacity={record.opacity} onChange={(opacity: number) => { this.setValueForColorMapEntry(record.key, 'opacity', opacity); }} /> ); return input; }; /** * Creates the columns for the table. */ getColumns = () => { const { locale } = this.props; const columns: any = [{ title: locale.colorLabel, dataIndex: 'color', render: this.colorRenderer }, { title: locale.quantityLabel, dataIndex: 'quantity', render: this.quantityRenderer }, { title: locale.labelLabel, dataIndex: 'label', render: this.labelRenderer }, { title: locale.opacityLabel, dataIndex: 'opacity', render: this.opacityRenderer }]; return columns; }; render() { const { colorMap, colorRamps, locale } = this.props; const { colorRamp } = this.state; const formItemLayout = { labelCol: { span: 8 }, wrapperCol: { span: 16 } }; // make sure colorMapEntries does exist let colorMapEntries: ColorMapEntry[] = _get(colorMap, 'colorMapEntries'); if (!colorMapEntries) { colorMapEntries = []; } const nrOfClasses = colorMapEntries.length; return ( <div className="gs-colormap-symbolizer-editor" > <div className="gs-colormap-header-row"> <Form.Item {...formItemLayout} > <span>{locale.titleLabel}</span> </Form.Item> <Form.Item label={locale.typeLabel} {...formItemLayout} > <ColorMapTypeField colorMapType={_get(colorMap, 'type')} onChange={this.onTypeChange} /> </Form.Item> <Form.Item label={locale.nrOfClassesLabel} {...formItemLayout} > <InputNumber className="number-of-classes-field" min={0} max={255} value={nrOfClasses} onChange={this.onNrOfClassesChange} /> </Form.Item> <Form.Item label={locale.colorRampLabel} {...formItemLayout} > <ColorRampCombo onChange={this.onColorRampChange} colorRamp={colorRamp} colorRamps={colorRamps} /> </Form.Item> <Form.Item label={locale.extendedLabel} {...formItemLayout} > <ExtendedField extended={_get(colorMap, 'extended')} onChange={this.onExtendedChange} /> </Form.Item> </div> <Table className="gs-colormap-table" columns={this.getColumns()} dataSource={this.getColorMapRecords()} pagination={{ position: ['bottomCenter'] }} size="small" /> </div> ); } } export default localize(ColorMapEditor, ColorMapEditor.componentName);
the_stack
import * as nls from 'vscode-nls'; import * as vscode from 'vscode'; import fetch, { Response } from 'node-fetch'; import { v4 as uuid } from 'uuid'; import { PromiseAdapter, promiseFromEvent } from './common/utils'; import { ExperimentationTelemetry } from './experimentationService'; import { AuthProviderType } from './github'; import { Log } from './common/logger'; import { isSupportedEnvironment } from './common/env'; import { LoopbackAuthServer } from './authServer'; import path = require('path'); const localize = nls.loadMessageBundle(); const CLIENT_ID = '01ab8ac9400c4e429b23'; const GITHUB_AUTHORIZE_URL = 'https://github.com/login/oauth/authorize'; // TODO: change to stable when that happens const GITHUB_TOKEN_URL = 'https://vscode.dev/codeExchangeProxyEndpoints/github/login/oauth/access_token'; const NETWORK_ERROR = 'network error'; const REDIRECT_URL_STABLE = 'https://vscode.dev/redirect'; const REDIRECT_URL_INSIDERS = 'https://insiders.vscode.dev/redirect'; class UriEventHandler extends vscode.EventEmitter<vscode.Uri> implements vscode.UriHandler { constructor(private readonly Logger: Log) { super(); } public handleUri(uri: vscode.Uri) { this.Logger.trace('Handling Uri...'); this.fire(uri); } } export interface IGitHubServer extends vscode.Disposable { login(scopes: string): Promise<string>; getUserInfo(token: string): Promise<{ id: string; accountName: string }>; sendAdditionalTelemetryInfo(token: string): Promise<void>; friendlyName: string; type: AuthProviderType; } interface IGitHubDeviceCodeResponse { device_code: string; user_code: string; verification_uri: string; interval: number; } async function getScopes(token: string, serverUri: vscode.Uri, logger: Log): Promise<string[]> { try { logger.info('Getting token scopes...'); const result = await fetch(serverUri.toString(), { headers: { Authorization: `token ${token}`, 'User-Agent': 'Visual-Studio-Code' } }); if (result.ok) { const scopes = result.headers.get('X-OAuth-Scopes'); return scopes ? scopes.split(',').map(scope => scope.trim()) : []; } else { logger.error(`Getting scopes failed: ${result.statusText}`); throw new Error(result.statusText); } } catch (ex) { logger.error(ex.message); throw new Error(NETWORK_ERROR); } } async function getUserInfo(token: string, serverUri: vscode.Uri, logger: Log): Promise<{ id: string; accountName: string }> { let result: Response; try { logger.info('Getting user info...'); result = await fetch(serverUri.toString(), { headers: { Authorization: `token ${token}`, 'User-Agent': 'Visual-Studio-Code' } }); } catch (ex) { logger.error(ex.message); throw new Error(NETWORK_ERROR); } if (result.ok) { try { const json = await result.json(); logger.info('Got account info!'); return { id: json.id, accountName: json.login }; } catch (e) { logger.error(`Unexpected error parsing response from GitHub: ${e.message ?? e}`); throw e; } } else { // either display the response message or the http status text let errorMessage = result.statusText; try { const json = await result.json(); if (json.message) { errorMessage = json.message; } } catch (err) { // noop } logger.error(`Getting account info failed: ${errorMessage}`); throw new Error(errorMessage); } } export class GitHubServer implements IGitHubServer { friendlyName = 'GitHub'; type = AuthProviderType.github; private _pendingNonces = new Map<string, string[]>(); private _codeExchangePromises = new Map<string, { promise: Promise<string>; cancel: vscode.EventEmitter<void> }>(); private _disposable: vscode.Disposable; private _uriHandler = new UriEventHandler(this._logger); private readonly getRedirectEndpoint: Thenable<string>; constructor(private readonly _supportDeviceCodeFlow: boolean, private readonly _logger: Log, private readonly _telemetryReporter: ExperimentationTelemetry) { this._disposable = vscode.window.registerUriHandler(this._uriHandler); this.getRedirectEndpoint = vscode.commands.executeCommand<{ [providerId: string]: string } | undefined>('workbench.getCodeExchangeProxyEndpoints').then((proxyEndpoints) => { // If we are running in insiders vscode.dev, then ensure we use the redirect route on that. let redirectUri = REDIRECT_URL_STABLE; if (proxyEndpoints?.github && new URL(proxyEndpoints.github).hostname === 'insiders.vscode.dev') { redirectUri = REDIRECT_URL_INSIDERS; } return redirectUri; }); } dispose() { this._disposable.dispose(); } // TODO@joaomoreno TODO@TylerLeonhardt private async isNoCorsEnvironment(): Promise<boolean> { const uri = await vscode.env.asExternalUri(vscode.Uri.parse(`${vscode.env.uriScheme}://vscode.github-authentication/dummy`)); return (uri.scheme === 'https' && /^((insiders\.)?vscode|github)\./.test(uri.authority)) || (uri.scheme === 'http' && /^localhost/.test(uri.authority)); } public async login(scopes: string): Promise<string> { this._logger.info(`Logging in for the following scopes: ${scopes}`); // Used for showing a friendlier message to the user when the explicitly cancel a flow. let userCancelled: boolean | undefined; const yes = localize('yes', "Yes"); const no = localize('no', "No"); const promptToContinue = async () => { if (userCancelled === undefined) { // We haven't had a failure yet so wait to prompt return; } const message = userCancelled ? localize('userCancelledMessage', "Having trouble logging in? Would you like to try a different way?") : localize('otherReasonMessage', "You have not yet finished authorizing this extension to use GitHub. Would you like to keep trying?"); const result = await vscode.window.showWarningMessage(message, yes, no); if (result !== yes) { throw new Error('Cancelled'); } }; const nonce = uuid(); const callbackUri = await vscode.env.asExternalUri(vscode.Uri.parse(`${vscode.env.uriScheme}://vscode.github-authentication/did-authenticate?nonce=${encodeURIComponent(nonce)}`)); const supported = isSupportedEnvironment(callbackUri); if (supported) { try { return await this.doLoginWithoutLocalServer(scopes, nonce, callbackUri); } catch (e) { this._logger.error(e); userCancelled = e.message ?? e === 'User Cancelled'; } } // Starting a local server isn't supported in web if (vscode.env.uiKind === vscode.UIKind.Desktop) { try { await promptToContinue(); return await this.doLoginWithLocalServer(scopes); } catch (e) { this._logger.error(e); userCancelled = e.message ?? e === 'User Cancelled'; } } if (this._supportDeviceCodeFlow) { try { await promptToContinue(); return await this.doLoginDeviceCodeFlow(scopes); } catch (e) { this._logger.error(e); userCancelled = e.message ?? e === 'User Cancelled'; } } else if (!supported) { try { await promptToContinue(); return await this.doLoginWithPat(scopes); } catch (e) { this._logger.error(e); userCancelled = e.message ?? e === 'User Cancelled'; } } throw new Error(userCancelled ? 'Cancelled' : 'No auth flow succeeded.'); } private async doLoginWithoutLocalServer(scopes: string, nonce: string, callbackUri: vscode.Uri): Promise<string> { this._logger.info(`Trying without local server... (${scopes})`); return await vscode.window.withProgress<string>({ location: vscode.ProgressLocation.Notification, title: localize('signingIn', "Signing in to github.com..."), cancellable: true }, async (_, token) => { const existingNonces = this._pendingNonces.get(scopes) || []; this._pendingNonces.set(scopes, [...existingNonces, nonce]); const redirectUri = await this.getRedirectEndpoint; const searchParams = new URLSearchParams([ ['client_id', CLIENT_ID], ['redirect_uri', redirectUri], ['scope', scopes], ['state', encodeURIComponent(callbackUri.toString(true))] ]); const uri = vscode.Uri.parse(`${GITHUB_AUTHORIZE_URL}?${searchParams.toString()}`); await vscode.env.openExternal(uri); // Register a single listener for the URI callback, in case the user starts the login process multiple times // before completing it. let codeExchangePromise = this._codeExchangePromises.get(scopes); if (!codeExchangePromise) { codeExchangePromise = promiseFromEvent(this._uriHandler.event, this.handleUri(scopes)); this._codeExchangePromises.set(scopes, codeExchangePromise); } try { return await Promise.race([ codeExchangePromise.promise, new Promise<string>((_, reject) => setTimeout(() => reject('Cancelled'), 60000)), promiseFromEvent<any, any>(token.onCancellationRequested, (_, __, reject) => { reject('User Cancelled'); }).promise ]); } finally { this._pendingNonces.delete(scopes); codeExchangePromise?.cancel.fire(); this._codeExchangePromises.delete(scopes); } }); } private async doLoginWithLocalServer(scopes: string): Promise<string> { this._logger.info(`Trying with local server... (${scopes})`); return await vscode.window.withProgress<string>({ location: vscode.ProgressLocation.Notification, title: localize('signingInAnotherWay', "Signing in to github.com..."), cancellable: true }, async (_, token) => { const redirectUri = await this.getRedirectEndpoint; const searchParams = new URLSearchParams([ ['client_id', CLIENT_ID], ['redirect_uri', redirectUri], ['scope', scopes], ]); const loginUrl = `${GITHUB_AUTHORIZE_URL}?${searchParams.toString()}`; const server = new LoopbackAuthServer(path.join(__dirname, '../media'), loginUrl); const port = await server.start(); let codeToExchange; try { vscode.env.openExternal(vscode.Uri.parse(`http://127.0.0.1:${port}/signin?nonce=${encodeURIComponent(server.nonce)}`)); const { code } = await Promise.race([ server.waitForOAuthResponse(), new Promise<any>((_, reject) => setTimeout(() => reject('Cancelled'), 60000)), promiseFromEvent<any, any>(token.onCancellationRequested, (_, __, reject) => { reject('User Cancelled'); }).promise ]); codeToExchange = code; } finally { setTimeout(() => { void server.stop(); }, 5000); } const accessToken = await this.exchangeCodeForToken(codeToExchange); return accessToken; }); } private async doLoginDeviceCodeFlow(scopes: string): Promise<string> { this._logger.info(`Trying device code flow... (${scopes})`); // Get initial device code const uri = `https://github.com/login/device/code?client_id=${CLIENT_ID}&scope=${scopes}`; const result = await fetch(uri, { method: 'POST', headers: { Accept: 'application/json' } }); if (!result.ok) { throw new Error(`Failed to get one-time code: ${await result.text()}`); } const json = await result.json() as IGitHubDeviceCodeResponse; const modalResult = await vscode.window.showInformationMessage( localize('code.title', "Your Code: {0}", json.user_code), { modal: true, detail: localize('code.detail', "To finish authenticating, navigate to GitHub and paste in the above one-time code.") }, 'Copy & Continue to GitHub'); if (modalResult !== 'Copy & Continue to GitHub') { throw new Error('User Cancelled'); } await vscode.env.clipboard.writeText(json.user_code); const uriToOpen = await vscode.env.asExternalUri(vscode.Uri.parse(json.verification_uri)); await vscode.env.openExternal(uriToOpen); return await this.waitForDeviceCodeAccessToken(json); } private async doLoginWithPat(scopes: string): Promise<string> { this._logger.info(`Trying to retrieve PAT... (${scopes})`); const token = await vscode.window.showInputBox({ prompt: 'GitHub Personal Access Token', ignoreFocusOut: true }); if (!token) { throw new Error('User Cancelled'); } const tokenScopes = await getScopes(token, this.getServerUri('/'), this._logger); // Example: ['repo', 'user'] const scopesList = scopes.split(' '); // Example: 'read:user repo user:email' if (!scopesList.every(scope => { const included = tokenScopes.includes(scope); if (included || !scope.includes(':')) { return included; } return scope.split(':').some(splitScopes => { return tokenScopes.includes(splitScopes); }); })) { throw new Error(`The provided token does not match the requested scopes: ${scopes}`); } return token; } private async waitForDeviceCodeAccessToken( json: IGitHubDeviceCodeResponse, ): Promise<string> { return await vscode.window.withProgress<string>({ location: vscode.ProgressLocation.Notification, cancellable: true, title: localize( 'progress', "Open [{0}]({0}) in a new tab and paste your one-time code: {1}", json.verification_uri, json.user_code) }, async (_, token) => { const refreshTokenUri = `https://github.com/login/oauth/access_token?client_id=${CLIENT_ID}&device_code=${json.device_code}&grant_type=urn:ietf:params:oauth:grant-type:device_code`; // Try for 2 minutes const attempts = 120 / json.interval; for (let i = 0; i < attempts; i++) { await new Promise(resolve => setTimeout(resolve, json.interval * 1000)); if (token.isCancellationRequested) { throw new Error('User Cancelled'); } let accessTokenResult; try { accessTokenResult = await fetch(refreshTokenUri, { method: 'POST', headers: { Accept: 'application/json' } }); } catch { continue; } if (!accessTokenResult.ok) { continue; } const accessTokenJson = await accessTokenResult.json(); if (accessTokenJson.error === 'authorization_pending') { continue; } if (accessTokenJson.error) { throw new Error(accessTokenJson.error_description); } return accessTokenJson.access_token; } throw new Error('Cancelled'); }); } private handleUri: (scopes: string) => PromiseAdapter<vscode.Uri, string> = (scopes) => (uri, resolve, reject) => { const query = new URLSearchParams(uri.query); const code = query.get('code'); const nonce = query.get('nonce'); if (!code) { reject(new Error('No code')); return; } if (!nonce) { reject(new Error('No nonce')); return; } const acceptedNonces = this._pendingNonces.get(scopes) || []; if (!acceptedNonces.includes(nonce)) { // A common scenario of this happening is if you: // 1. Trigger a sign in with one set of scopes // 2. Before finishing 1, you trigger a sign in with a different set of scopes // In this scenario we should just return and wait for the next UriHandler event // to run as we are probably still waiting on the user to hit 'Continue' this._logger.info('Nonce not found in accepted nonces. Skipping this execution...'); return; } resolve(this.exchangeCodeForToken(code)); }; private async exchangeCodeForToken(code: string): Promise<string> { this._logger.info('Exchanging code for token...'); const proxyEndpoints: { [providerId: string]: string } | undefined = await vscode.commands.executeCommand('workbench.getCodeExchangeProxyEndpoints'); const endpointUrl = proxyEndpoints?.github ? `${proxyEndpoints.github}login/oauth/access_token` : GITHUB_TOKEN_URL; const body = `code=${code}`; const result = await fetch(endpointUrl, { method: 'POST', headers: { Accept: 'application/json', 'Content-Type': 'application/x-www-form-urlencoded', 'Content-Length': body.toString() }, body }); if (result.ok) { const json = await result.json(); this._logger.info('Token exchange success!'); return json.access_token; } else { const text = await result.text(); const error = new Error(text); error.name = 'GitHubTokenExchangeError'; throw error; } } private getServerUri(path: string = '') { const apiUri = vscode.Uri.parse('https://api.github.com'); return vscode.Uri.parse(`${apiUri.scheme}://${apiUri.authority}${path}`); } public getUserInfo(token: string): Promise<{ id: string; accountName: string }> { return getUserInfo(token, this.getServerUri('/user'), this._logger); } public async sendAdditionalTelemetryInfo(token: string): Promise<void> { if (!vscode.env.isTelemetryEnabled) { return; } const nocors = await this.isNoCorsEnvironment(); if (nocors) { return; } try { const result = await fetch('https://education.github.com/api/user', { headers: { Authorization: `token ${token}`, 'faculty-check-preview': 'true', 'User-Agent': 'Visual-Studio-Code' } }); if (result.ok) { const json: { student: boolean; faculty: boolean } = await result.json(); /* __GDPR__ "session" : { "owner": "TylerLeonhardt", "isEdu": { "classification": "NonIdentifiableDemographicInfo", "purpose": "FeatureInsight" } } */ this._telemetryReporter.sendTelemetryEvent('session', { isEdu: json.student ? 'student' : json.faculty ? 'faculty' : 'none' }); } } catch (e) { // No-op } } public async checkEnterpriseVersion(token: string): Promise<void> { try { const result = await fetch(this.getServerUri('/meta').toString(), { headers: { Authorization: `token ${token}`, 'User-Agent': 'Visual-Studio-Code' } }); if (!result.ok) { return; } const json: { verifiable_password_authentication: boolean; installed_version: string } = await result.json(); /* __GDPR__ "ghe-session" : { "owner": "TylerLeonhardt", "version": { "classification": "SystemMetaData", "purpose": "FeatureInsight" } } */ this._telemetryReporter.sendTelemetryEvent('ghe-session', { version: json.installed_version }); } catch { // No-op } } } export class GitHubEnterpriseServer implements IGitHubServer { friendlyName = 'GitHub Enterprise'; type = AuthProviderType.githubEnterprise; constructor(private readonly _logger: Log, private readonly telemetryReporter: ExperimentationTelemetry) { } dispose() { } public async login(scopes: string): Promise<string> { this._logger.info(`Logging in for the following scopes: ${scopes}`); const token = await vscode.window.showInputBox({ prompt: 'GitHub Personal Access Token', ignoreFocusOut: true }); if (!token) { throw new Error('Sign in failed: No token provided'); } const tokenScopes = await getScopes(token, this.getServerUri('/'), this._logger); // Example: ['repo', 'user'] const scopesList = scopes.split(' '); // Example: 'read:user repo user:email' if (!scopesList.every(scope => { const included = tokenScopes.includes(scope); if (included || !scope.includes(':')) { return included; } return scope.split(':').some(splitScopes => { return tokenScopes.includes(splitScopes); }); })) { throw new Error(`The provided token does not match the requested scopes: ${scopes}`); } return token; } private getServerUri(path: string = '') { const apiUri = vscode.Uri.parse(vscode.workspace.getConfiguration('github-enterprise').get<string>('uri') || '', true); return vscode.Uri.parse(`${apiUri.scheme}://${apiUri.authority}/api/v3${path}`); } public async getUserInfo(token: string): Promise<{ id: string; accountName: string }> { return getUserInfo(token, this.getServerUri('/user'), this._logger); } public async sendAdditionalTelemetryInfo(token: string): Promise<void> { try { const result = await fetch(this.getServerUri('/meta').toString(), { headers: { Authorization: `token ${token}`, 'User-Agent': 'Visual-Studio-Code' } }); if (!result.ok) { return; } const json: { verifiable_password_authentication: boolean; installed_version: string } = await result.json(); /* __GDPR__ "ghe-session" : { "owner": "TylerLeonhardt", "version": { "classification": "SystemMetaData", "purpose": "FeatureInsight" } } */ this.telemetryReporter.sendTelemetryEvent('ghe-session', { version: json.installed_version }); } catch { // No-op } } }
the_stack
import CaretDownFilled from '@ant-design/icons/lib/icons/CaretDownFilled' import SearchOutlined from '@ant-design/icons/lib/icons/SearchOutlined' import WarningFilled from '@ant-design/icons/lib/icons/WarningFilled' import { Checkbox, Input } from 'antd' import { usePersonProperies } from 'lib/api/person-properties' import React from 'react' import { PersonProperty } from '~/types' import './styles.scss' export const PropertyNamesSelect = ({ onChange, }: { onChange?: (selectedProperties: string[]) => void }): JSX.Element => { /* Provides a super simple multiselect box for selecting property names. */ const { properties, error } = usePersonProperies() return error ? ( <div className="property-names-select"> <WarningFilled style={{ color: 'var(--warning)' }} /> Error loading properties! </div> ) : properties ? ( <SelectPropertiesProvider properties={properties}> <PropertyNamesSelectBox onChange={onChange} /> </SelectPropertiesProvider> ) : ( <div className="property-names-select">Loading properties...</div> ) } const PropertyNamesSelectBox = ({ onChange }: { onChange?: (selectedProperties: string[]) => void }): JSX.Element => { const { properties, selectedProperties, selectAll, clearAll, selectState } = useSelectedProperties() const { isOpen: isSearchOpen, popoverProps, triggerProps, } = usePopover({ onHide: () => { if (onChange) { onChange(Array.from(selectedProperties)) } }, }) return ( <div className="property-names-select-container" {...triggerProps}> <div className="property-names-select" role="combobox"> {properties ? ( <> {selectState === 'all' ? ( <Checkbox checked={true} aria-label="Select all" onClick={(evt) => { clearAll() if (onChange) { onChange([]) } evt.stopPropagation() }} /> ) : selectState === 'none' ? ( <Checkbox checked={false} aria-label="Select all" onClick={(evt) => { selectAll() if (onChange) { onChange(properties.map((property) => property.name)) } evt.stopPropagation() }} /> ) : ( <Checkbox aria-label="Select all" indeterminate={true} onClick={(evt) => { selectAll() if (onChange) { onChange(properties.map((property) => property.name)) } evt.stopPropagation() }} /> )} <div className="selection-status-text"> {selectedProperties.size} of {properties.length} selected </div> <CaretDownFilled /> </> ) : ( 'Loading properties' )} </div> {isSearchOpen ? ( <div className="popover" {...popoverProps}> <PropertyNamesSearch /> </div> ) : null} </div> ) } const PropertyNamesSearch = (): JSX.Element => { const { properties, toggleProperty, isSelected } = useSelectedProperties() const { filteredProperties, query, setQuery } = usePropertySearch(properties) return ( <> <Input onChange={({ target: { value } }) => setQuery(value)} allowClear className="search-box" placeholder="Search for properties" prefix={<SearchOutlined />} /> <div className="search-results"> {filteredProperties.length ? ( filteredProperties.map((property) => ( <Checkbox key={property.name} className={'checkbox' + (isSelected(property.name) ? ' checked' : '')} checked={isSelected(property.name)} onChange={() => toggleProperty(property.name)} > {property.highlightedName} </Checkbox> )) ) : ( <p className="no-results-message"> No properties match <b>“{query}”</b>. Refine your search to try again. </p> )} </div> </> ) } // eslint-disable-next-line @typescript-eslint/explicit-function-return-type const usePopover = ({ onHide }: { onHide: () => void }) => { /* Logic for handling arbitrary popover state */ const [isOpen, setIsOpen] = React.useState<boolean>(false) const hide = (): void => { setIsOpen(false) onHide() } const open = (): void => setIsOpen(true) const toggle = (): void => { if (isOpen) { hide() } else { open() } } // I use a ref to ensure we are able to close the popover when the user clicks outside of it. const triggerRef = React.useRef<HTMLDivElement>(null) React.useEffect(() => { const checkIfClickedOutside = (event: MouseEvent): void => { if ( isOpen && triggerRef.current && event.target instanceof Node && !triggerRef.current.contains(event.target) ) { hide() } } document.addEventListener('mousedown', checkIfClickedOutside) return () => { // Cleanup the event listener document.removeEventListener('mousedown', checkIfClickedOutside) } }, [isOpen, hide]) return { isOpen, open, hide, toggle, // Return props that should be on the actual popover. This is so we can // position things correctly popoverProps: { onClick(event: React.MouseEvent): void { // Avoid the click propogating to the trigger element. We need // to do this in order to prevent popover clicks also triggering // anything on containing elements event.stopPropagation() }, }, // Return propse that should be on the trigger. This is so we can attach // any show, hide handlers etc. triggerProps: { ref: triggerRef, onClick: toggle }, } } // eslint-disable-next-line @typescript-eslint/explicit-function-return-type const usePropertySearch = (properties: PersonProperty[]) => { /* Basic case insensitive substring search functionality for person property selection. It's pretty much this stackoverflow answer: https://stackoverflow.com/a/43235785 */ const [query, setQuery] = React.useState<string>('') const filteredProperties = React.useMemo(() => { return query === '' ? properties.map((property) => ({ ...property, highlightedName: property.name })) : properties // First we split on query term, case insensitive, and globally, // not just the first // NOTE: it's important to use a capture group here, otherwise // the query string match will not be included as a part. See // https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/String/split#splitting_with_a_regexp_to_include_parts_of_the_separator_in_the_result // for details .map((property) => ({ ...property, nameParts: property.name.split(new RegExp(`(${query})`, 'gi')), })) // Then filter where we have a match .filter((property) => property.nameParts.length > 1) // Then create a JSX.Element that can be rendered .map((property) => ({ ...property, highlightedName: ( <span> {property.nameParts.map((part, index) => part.toLowerCase() === query.toLowerCase() ? ( <b key={index}>{part}</b> ) : ( <React.Fragment key={index}>{part}</React.Fragment> ) )} </span> ), })) }, [query, properties]) return { filteredProperties, setQuery, query } } // eslint-disable-next-line @typescript-eslint/explicit-function-return-type const useSelectedProperties = () => { /* Provides functions for handling selected properties state */ const context = React.useContext(propertiesSelectionContext) // make typing happy, i.e. rule out the undefined case so we don't have to // check this everywhere if (context === undefined) { throw Error('No select React.Context found') } return context } /* A propertiesSelectionContext provides: - selectedProperties: a set of selected property names - state manipulation functions for modifying the set of selected properties */ const propertiesSelectionContext = React.createContext< | { properties: PersonProperty[] selectState: 'all' | 'none' | 'some' selectedProperties: Set<string> toggleProperty: (propertyName: string) => void clearAll: () => void selectAll: () => void isSelected: (propertyName: string) => boolean } | undefined >(undefined) const SelectPropertiesProvider = ({ properties, children, }: { properties: PersonProperty[] children: React.ReactNode }): JSX.Element => { const [selectedProperties, setSelectedProperties] = React.useState<Set<string>>( new Set(properties.map((property) => property.name)) ) const setAndNotify = (newSelectedProperties: Set<string>): void => { setSelectedProperties(newSelectedProperties) } const toggleProperty = (property: string): void => { setAndNotify( selectedProperties.has(property) ? new Set(Array.from(selectedProperties).filter((p) => p !== property)) : new Set([...Array.from(selectedProperties), property]) ) } const clearAll = (): void => { setAndNotify(new Set()) } const selectAll = (): void => { setAndNotify(new Set(properties.map((property) => property.name))) } const isSelected = (property: string): boolean => selectedProperties.has(property) const selectState: 'all' | 'none' | 'some' = selectedProperties.size === properties.length ? 'all' : selectedProperties.size === 0 ? 'none' : 'some' return ( <propertiesSelectionContext.Provider value={{ properties, selectedProperties, toggleProperty, clearAll, selectAll, selectState, isSelected }} > {children} </propertiesSelectionContext.Provider> ) }
the_stack
import * as _ from 'lodash'; import {isUndefined} from 'util'; import { Component, ElementRef, EventEmitter, Injector, Input, OnChanges, OnDestroy, OnInit, Output, SimpleChange, SimpleChanges, ViewChild, ViewChildren } from '@angular/core'; import {StringUtil} from '@common/util/string.util'; import { ConnectionType, Datasource, Field, FieldFormat, FieldFormatType, FieldRole, LogicalType } from '@domain/datasource/datasource'; import {Stats} from '@domain/datasource/stats'; import {Covariance} from '@domain/datasource/covariance'; import {Metadata} from '@domain/meta-data-management/metadata'; import {MetadataColumn} from '@domain/meta-data-management/metadata-column'; import {AbstractComponent} from '@common/component/abstract.component'; import {DatasourceService} from '../../../../datasource/service/datasource.service'; import {DataSourceCreateService, TypeFilterObject} from '../../../service/data-source-create.service'; import {TimezoneService} from '../../../service/timezone.service'; import {EditFilterDataSourceComponent} from '../edit-filter-data-source.component'; import {EditConfigSchemaComponent} from './edit-config-schema.component'; declare let echarts: any; /** * Datasource detail - column detail tab */ @Component({ selector: 'column-detail-datasource', templateUrl: './column-detail-data-source.component.html' }) export class ColumnDetailDataSourceComponent extends AbstractComponent implements OnInit, OnChanges, OnDestroy { @ViewChild('histogram') private _histogram: ElementRef; @ViewChildren('covariance') private _covariance: ElementRef; @ViewChild(EditFilterDataSourceComponent) private _editFilterComponent: EditFilterDataSourceComponent; @ViewChild(EditConfigSchemaComponent) private _editConfigSchemaComp: EditConfigSchemaComponent; // chart option private _barOption: any; private _scatterOption: any; // datasource information @Input() public datasource: Datasource; // metadata information @Input() public metaData: Metadata; // enum public readonly FIELD_ROLE: any = FieldRole; public readonly LOGICAL_TYPE: any = LogicalType; // filtered column list public filteredColumnList: any[]; // role type filter list public roleTypeFilterList: TypeFilterObject[] = this.datasourceCreateService.getRoleTypeFilterList(); // selected role type filter public selectedRoleTypeFilter: TypeFilterObject; // logical type filter list public logicalTypeFilterList: TypeFilterObject[] = this.datasourceCreateService.getLogicalTypeFilterList().filter(type => type.value !== LogicalType.USER_DEFINED); // selected logical type filter public selectedLogicalTypeFilter: TypeFilterObject; // selected field public selectedField: any; // covariance data result public covarianceData: any = {}; // stats data result public statsData: any = {}; // search text keyword public searchTextKeyword: string; @Output() public changeDatasource: EventEmitter<any> = new EventEmitter(); // constructor constructor(private datasourceService: DatasourceService, private datasourceCreateService: DataSourceCreateService, private _timezoneService: TimezoneService, protected element: ElementRef, protected injector: Injector) { super(element, injector); } /** * ngOnInit */ public ngOnInit() { super.ngOnInit(); } /** * ngOnDestroy */ public ngOnDestroy() { super.ngOnDestroy(); } /** * ngOnChanges * @param {SimpleChanges} changes */ public ngOnChanges(changes: SimpleChanges) { const dsChanges: SimpleChange = changes.datasource; if (dsChanges) { // if this is the first access if (!dsChanges.previousValue) { // ui init this._initView(); // set filtered column list this.filteredColumnList = this.datasource.fields; // if exist metadata, merge to field this.isExistMetaData() && this.filteredColumnList.forEach(field => this._setMetaDataField(field)); // change selected field this.onSelectedField(this.filteredColumnList[0], this.datasource); } // if change to the field else if (dsChanges.previousValue.fields !== dsChanges.currentValue.fields) { // update filtered column list this._updateFilteredColumnList(); // if exist metadata, merge to field this.isExistMetaData() && this.filteredColumnList.forEach(field => this._setMetaDataField(field)); // change selected field this.onSelectedField(this.selectedField ? this.datasource.fields.filter(field => field.id === this.selectedField.id)[0] : this.filteredColumnList[0], this.datasource); } } } /** * Change search text keyword and update filtered column list * @param {string} text */ public searchText(text: string): void { // change search text keyword this.searchTextKeyword = text; // update filtered column list this._updateFilteredColumnList(); } /** * Complete update schema */ public completeUpdatedSchema(): void { this.changeDatasource.emit('columns'); } /** * Is exist metadata * @returns {boolean} */ public isExistMetaData(): boolean { return !isUndefined(this.metaData); } /** * Is linked type datasource * @param {Datasource} source * @returns {boolean} */ public isLinkedTypeSource(source: Datasource): boolean { return source.connType === ConnectionType.LINK; } /** * Is enable filtering in column * @param column * @returns {boolean} */ public isEnableFiltering(column: any): boolean { return column.filtering; } /** * Is GEO type column * @param column * @returns {boolean} */ public isGeoType(column: any): boolean { return column.logicalType.indexOf('GEO_') !== -1; } /** * Is time type field * @param {Field} field * @return {boolean} */ public isEnableTimezone(field: Field): boolean { return field.format && (field.format.type === FieldFormatType.UNIX_TIME || this._timezoneService.isEnableTimezoneInDateFormat(field.format)); } /** * Get timezone label * @param {FieldFormat} format * @return {string} */ public getTimezoneLabel(format: FieldFormat): string { if (format.type === FieldFormatType.UNIX_TIME) { return 'Unix time'; } else { return this._timezoneService.getTimezoneObject(format).label; } } /** * Get column type label * @param {string} type * @returns {string} */ public getColumnTypeLabel(type: string): string { return this.logicalTypeFilterList.find(filter => filter.value === type).label; } /** * value list * @returns {any[]} */ public getValueList(): any { // frequentItems let list = this._getStats().frequentItems; // if list 10 over if (list && list.length > 10) { list = list.sort((a, b) => { return a.count > b.count ? -1 : a.count < b.count ? 1 : 0; }).slice(0, 9); list.push({value: this.translateService.instant('msg.storage.ui.dsource.detail.column.etc')}); } return list; } /** * Get covariance data list * @returns {Covariance[]} */ public getCovarianceList(): Covariance[] { if (this.selectedField && this.covarianceData.hasOwnProperty(this.selectedField.name)) { return this.covarianceData[this.selectedField.name]; } return new Array<Covariance>(); } /** * Get label * @param {string} labelName * @returns {any} */ public getLabel(labelName: string): any { // stats const stats = this._getStats(); switch (labelName) { case 'count': return this._getRowCount(); case 'valid': const valid = this._getRowCount() - (stats.missing === undefined ? 0 : stats.missing); return valid + ` (${this._getPercentage(valid)}%)`; case 'unique': const cardinality = stats.cardinality || stats['cardinality(estimated)']; const unique = cardinality === undefined ? 0 : cardinality; return unique + ` (${this._getPercentage(unique)}%)`; case 'outliers': const outliers = stats.outliers === undefined ? 0 : stats.outliers; return outliers + ` (${this._getPercentage(outliers)}%)`; case 'missing': const missing = stats.missing === undefined ? 0 : stats.missing; return missing + ` (${this._getPercentage(missing)}%)`; case 'min': const min = this._getStatsMaxAndMin('MIN'); return min === undefined ? 0 : min; case 'lower': const lower = this._getQuartile('LOWER'); return lower === undefined ? 0 : lower; case 'median': return stats.median === undefined ? 0 : stats.median; case 'upper': const upper = this._getQuartile('UPPER'); return upper === undefined ? 0 : upper; case 'max': const max = this._getStatsMaxAndMin('MAX'); return max === undefined ? 0 : max; case 'average': return stats.mean === undefined ? 0 : stats.mean; case 'standard': return stats.stddev === undefined ? 0 : stats.stddev; case 'skewness': return stats.skewness === undefined ? 0 : stats.skewness; } } /** * Role type filter change event * @param filter */ public onChangeRoleTypeFilter(filter: TypeFilterObject): void { if (this.selectedRoleTypeFilter.value !== filter.value) { // 롤 타입 필터링 변경 this.selectedRoleTypeFilter = filter; // 컬럼 목록 갱신 this._updateFilteredColumnList(); } } /** * Type filter change event * @param filter */ public onChangeLogicalTypeFilter(filter: TypeFilterObject): void { if (this.selectedLogicalTypeFilter.value !== filter.value) { // 타입 필털이 변경 this.selectedLogicalTypeFilter = filter; // 컬럼 목록 갱신 this._updateFilteredColumnList(); } } /** * Filter reset click event */ public onClickResetFilter(): void { // init search text keyword this.searchTextKeyword = undefined; // init selected role type filter this.selectedRoleTypeFilter = this.roleTypeFilterList[0]; // init selected type fliter this.selectedLogicalTypeFilter = this.logicalTypeFilterList[0]; // update filtered column list this._updateFilteredColumnList(); } /** * Selected field change event * @param field * @param {Datasource} source */ public onSelectedField(field: any, source: Datasource): void { // set selected field this.selectedField = field; // detect changes this.changeDetect.detectChanges(); // set engineName const engineName = source.engineName; // if only engine type source, get statistics and covariance // #728 except GEO types, not get statistics and covariance if (!this.isLinkedTypeSource(source) && !this.isGeoType(field)) { // if role is TIMESTAMP and __time variable not exist in statsData, // else if role is not TIMESTAMP and field name not existed in statsData if ((this.selectedField.role === FieldRole.TIMESTAMP && !this.statsData.hasOwnProperty('__time')) || (this.selectedField.role !== FieldRole.TIMESTAMP && !this.statsData.hasOwnProperty(field.name))) { // loading show this.loadingShow(); // get stats data this._getFieldStats(field, engineName) .then(() => { // loading hide this.loadingHide(); // update histogram chart this._updateHistogramChart(this.selectedField.role); }) .catch(error => this.commonExceptionHandler(error)); } else { // update histogram chart this._updateHistogramChart(this.selectedField.role); } // if role is MEASURE and field name not existed in covarianceData if (field.role === FieldRole.MEASURE && field.type !== 'ARRAY' && field.type !== 'HASHED_MAP' && !this.covarianceData.hasOwnProperty(field.name)) { // loading show this.loadingShow(); // get covariance data this._getFieldCovariance(field, engineName) .then((covariance) => { // set convariance data this.covarianceData[field.name] = covariance; // loading hide this.loadingHide(); // update covariance chart this._updateCovarianceChart(engineName); }) .catch(error => this.commonExceptionHandler(error)); } else if (field.role === FieldRole.MEASURE && this.covarianceData.hasOwnProperty(field.name)) { // update covariance chart this._updateCovarianceChart(engineName); } } } /** * Edit filter click event */ public onClickEditFilters(): void { this._editFilterComponent.init(this.datasource.id, this.datasource.fields, this.isLinkedTypeSource(this.datasource)); // change markup position $('#edit-filter-comp').appendTo($('#layout-contents')); } /** * Configure schema click event */ public onClickConfigureSchema(): void { this._editConfigSchemaComp.init(this.datasource.id, this.datasource.fields, this.datasource); // change markup position $('#edit-config-schema').appendTo($('#layout-contents')); } /** * ui init * @private */ private _initView(): void { this.selectedLogicalTypeFilter = this.logicalTypeFilterList[0]; this.selectedRoleTypeFilter = this.roleTypeFilterList[0]; // init data this.statsData = {}; this.covarianceData = {}; // bar option this._barOption = { backgroundColor: '#ffffff', color: ['#c1cef1'], tooltip: { trigger: 'axis', axisPointer: { type: 'line' } }, grid: { left: 0, top: 5, right: 5, bottom: 0, containLabel: true }, xAxis: [ { type: 'category', data: [], axisTick: { alignWithLabel: true } } ], yAxis: [ { type: 'value', splitNumber: 3, splitLine: {show: false}, } ], series: [ { type: 'bar', barWidth: '70%', itemStyle: {normal: {color: '#c1cef1'}, emphasis: {color: '#666eb2'}}, data: [] } ] }; // scatter option this._scatterOption = { backgroundColor: '#ffffff', grid: { left: 8, right: 8, top: 8, bottom: 8, containLabel: true }, title: { x: 'center', text: '' }, tooltip: { trigger: 'item', axisPointer: { show: true, type: 'cross' } }, xAxis: { name: '', type: 'value', nameLocation: 'middle', axisLabel: { show: false } }, yAxis: { type: 'value', scale: true, axisLabel: { show: false } }, series: [] }; } /** * Set metadata in field * @param {Field} field * @private */ private _setMetaDataField(field: Field): void { const fieldMetaData: MetadataColumn = _.find(this.metaData.columns, {physicalName: field.name}); // code table field['codeTable'] = fieldMetaData.codeTable; // dictionary field['dictionary'] = fieldMetaData.dictionary; } /** * Update filtered column list * @private */ private _updateFilteredColumnList(): void { this.filteredColumnList = this.datasource.fields.filter(field => (this.selectedRoleTypeFilter.value === 'ALL' ? true : (FieldRole.DIMENSION === this.selectedRoleTypeFilter.value && FieldRole.TIMESTAMP === field.role ? field : this.selectedRoleTypeFilter.value === field.role)) && (this.selectedLogicalTypeFilter.value === 'ALL' ? true : (this.selectedLogicalTypeFilter.value === LogicalType.USER_DEFINED && field.logicalType === LogicalType.STRING ? true : this.selectedLogicalTypeFilter.value === field.logicalType)) && (StringUtil.isEmpty(this.searchTextKeyword) ? true : field.name.toUpperCase().includes(this.searchTextKeyword.toUpperCase().trim()))); } /** * Get stats in filed * @param selectedField * @param engineName * @returns {Promise<any>} * @private */ private _getFieldStats(selectedField, engineName): Promise<any> { return new Promise<any>((resolve, reject) => { const params = { dataSource: { name: engineName, type: 'default' }, fields: [selectedField], userFields: [] // TODO datasource에 커스텀필드 걸려있을 경우만 집어넣음 }; // modify field to leave only name and type properties params.fields = params.fields.map((field) => { return { name: field.name, type: field.role.toLowerCase() }; }); // get stats data this.datasourceService.getFieldStats(params) .then((result) => { if (!_.isNil(result[0])) { // for loop for (const property in result[0]) { // if not exist property in statsData, push property in statsData if (!this.statsData.hasOwnProperty(property)) { this.statsData[property] = result[0][property]; } } } resolve(result); }) .catch((error) => { reject(error); }); }); } /** * Get covariance in field * @param selectedField * @param engineName * @returns {Promise<any>} * @private */ private _getFieldCovariance(selectedField, engineName): Promise<any> { return new Promise<any>((resolve, reject) => { const params = { dataSource: { type: 'default', name: engineName }, fieldName: selectedField.name, userFields: [] // TODO datasource에 커스텀필드 걸려있을 경우만 집어넣음 }; // get covarinace data this.datasourceService.getFieldCovariance(params) .then((result) => { resolve(result); }) .catch((error) => { reject(error); }); }); } /** * Get stats data * @returns {Stats} * @private */ private _getStats(): Stats { // if the seleted field is not a TIMESTAMP if (this.selectedField.role !== 'TIMESTAMP' && this.statsData.hasOwnProperty(this.selectedField.name)) { return this.statsData[this.selectedField.name]; } else if (this.selectedField.role === 'TIMESTAMP' && this.statsData.hasOwnProperty('__time')) { // If the selected field is a TIMESTAMP return this.statsData['__time']; } else { return new Stats(); } } /** * Get quartile * @param {string} type * @returns {any} * @private */ private _getQuartile(type: string) { let result; // stats const stats = this._getStats(); if (stats.hasOwnProperty('iqr')) { const length = stats.iqr.length; switch (type) { case 'LOWER': result = stats.iqr[0]; break; case 'UPPER': result = stats.iqr[length - 1]; break; } } return result; } /** * Get max and min in stats * @param {string} type * @returns {any} * @private */ private _getStatsMaxAndMin(type: string) { let result; // stats const stats = this._getStats(); // if role is a TIMESTAMP if (this.selectedField.role === 'TIMESTAMP' && stats.hasOwnProperty('segments')) { // segments length const length = stats.segments.length; switch (type) { case 'MIN': result = this._getArrayUsedSeparator(stats.segments[0].interval, /\//)[0]; break; case 'MAX': result = this._getArrayUsedSeparator(stats.segments[length - 1].interval, /\//)[1]; break; } } else if (this.selectedField.role !== 'TIMESTAMP') { // if role is not a TIMESTAMP switch (type) { case 'MIN': result = stats.min; break; case 'MAX': result = stats.max; break; } } return result; } /** * Get separator * @param {string} value * @param separator * @returns {string[]} * @private */ private _getArrayUsedSeparator(value: string, separator: any) { return value.split(separator); } /** * Get parcentage * @param {number} value * @returns {number} * @private */ private _getPercentage(value: number) { const total = this._getRowCount(); const result = Math.floor(value / total * 10000) / 100; return isNaN(result) ? 0 : result; } /** * Get row count * @returns {number} * @private */ private _getRowCount(): number { // stats const stats = this._getStats(); if (this.selectedField.role === 'TIMESTAMP' && stats.hasOwnProperty('segments')) { return stats.segments.map((item) => { return item.rows === undefined ? 0 : item.rows; }).reduce((previousValue, currentValue) => { return previousValue + currentValue; }); } else { return stats.count === undefined ? 0 : stats.count; } } // /** // * Get min max value // * @param {any[]} array // * @returns {{minValue: any; maxValue: any}} // * @private // */ // private _getMinMaxValue(array: any[]) { // const min = Math.min.apply(null, array.map((item) => { // return item.value; // })); // const max = Math.max.apply(null, array.map((item) => { // return item.value; // })); // // return {minValue: min, maxValue: max}; // } /** * Update covariance chart * @param {string} engineName * @private */ private _updateCovarianceChart(engineName: string) { this._getScatterSeries(engineName) .then((series) => { // canvas list const canvasList = this._covariance['_results']; // create chart for (let i = 0, nMax = canvasList.length; i < nMax; i++) { const canvas = canvasList[i].nativeElement; const scatterChart = echarts.init(canvas); scatterChart.setOption(this._getScatterOption(series[i])); scatterChart.resize(); } }) .catch(error => this.commonExceptionHandler(error)); } /** * Update histogram chart * @param {string} roleType * @private */ private _updateHistogramChart(roleType: string) { // init chart const barChart = echarts.init(this._histogram.nativeElement); // chart barChart.setOption(this._getBarOption(roleType)); barChart.resize(); } /** * Get series data to draw scatter chart * @param {string} engineName * @returns {Promise<any>} * @private */ private _getScatterSeries(engineName: string) { return new Promise((resolve, reject) => { // loading show this.loadingShow(); // covariance List const covarianceList = this.getCovarianceList(); // params const params = { dataSource: { name: engineName, type: 'default' }, pivot: { columns: covarianceList ? covarianceList.map((item) => { return { type: 'measure', aggregationType: 'NONE', name: item.with }; }) : [] }, // TODO 필드 확인 userFields: [] }; // selected field params.pivot.columns.push({ type: 'measure', aggregationType: 'NONE', name: this.selectedField.name }); // Get data to MEASURE value this.datasourceService.getDatasourceQuery(params) .then((result) => { // covariance names const covarianceNames = covarianceList.map((data) => { return data.with; }); // set series data const series = covarianceList.map((data) => { return { name: data.with, type: 'scatter', symbolSize: 5, data: [] }; }); result.forEach((data) => { for (let i = 0, nMax = covarianceNames.length; i < nMax; i++) { // 2 decimal places const x = data[covarianceNames[i]]; const y = data[this.selectedField.name]; series[i].data.push([ x.toFixed(2) * 1, y.toFixed(2) * 1 ]); } }); // loading hide this.loadingHide(); resolve(series); }) .catch((error) => { // loading hide this.loadingHide(); reject(error); }) }); } /** * Get options to use in Bar charts * @param {string} roleType * @returns {{} & any} * @private */ private _getBarOption(roleType: string) { // bar option const barOption = _.cloneDeep(this._barOption); // get stats const stats = this._getStats(); // data if (roleType === 'DIMENSION' && !_.isNil(stats.frequentItems)) { barOption.xAxis[0].data = stats.frequentItems.map((item) => { return item.value; }); barOption.series[0].data = stats.frequentItems.map((item) => { return item.count; }); } else if (roleType === 'TIMESTAMP' && !_.isNil(stats.segments)) { barOption.xAxis[0].data = stats.segments.map((item) => { return item.interval.split('/')[0]; }); barOption.series[0].data = stats.segments.map((item) => { return item.rows; }); } else { // MEASURE // Measure Field Histogram : It discards the first and the last in the pmf value, multiplies the count value from the second const count = stats.count; // pmf let pmf = stats.pmf; if (!_.isNil(pmf)) { pmf = this._getPmfList(pmf); // data barOption.series[0].data = pmf.map((item, _index) => { return item * count; }); // xAxis barOption.xAxis[0].data = pmf.map((_item, index) => { return index + 1; }); } } return barOption; } /** * Get options to use in Scatter charts * @param series * @returns {{} & any} * @private */ private _getScatterOption(series: any) { const scatterOption = _.cloneDeep(this._scatterOption); scatterOption.series = series; return scatterOption; } /** * Get pmf list * @param {any[]} pmf * @returns {any[]} * @private */ private _getPmfList(pmf: any[]) { // length const pmfLength = pmf.length; // Outputs when length is less than 10 if (pmfLength <= 10) { return pmf; } else if (pmfLength === 11) { // If length is 11, remove only 0th pmf.shift(); return pmf; } else { // If length is 12, remove 0th and 12th pmf.shift(); pmf.pop(); return pmf; } } }
the_stack
import { Build, Component, Prop, State, h } from '@stencil/core'; import BrowserTab from '../BrowserTab'; import { ResizeEvent } from '../rp-resizable/rp-resizable'; import slugify from '../../utils/slugify'; import unslugify from '../../utils/unslugify'; import ResizeObserver from './ResizeObserver'; import Orientation from '../Orientation'; import { PATTERNS } from '../Patterns'; import { ScreenSize } from '../ScreenSize'; const PATTERN_URL_PREFIX = 'https://github.com/phuoc-ng/responsive-page/blob/main'; @Component({ tag: 'rp-demo-viewer', styleUrl: 'rp-demo-viewer.css' }) export class RpDemoViewer { @Prop() pattern?: string; @State() isScreenListOpen: boolean = false; @State() orientation: Orientation = Orientation.Portrait; @State() scale: number = 1; @State() demoHeight: number = 0; @State() demoWidth: number = 0; @State() currentTab: BrowserTab = BrowserTab.Demo; private resizableEle!: HTMLRpResizableElement; private frameDemoEle?: HTMLElement; private viewerBodyEle!: HTMLElement; private browserFrameEle!: HTMLElement; private frameContainer!: HTMLElement; private frameContainerWidth: number = 0; private frameContainerHeight: number = 0; private resizeObserver?: ResizeObserver; private setInitialSize: boolean = false; handleChangeScreenSize = (e: CustomEvent<ScreenSize>) => { const { height, width } = e.detail; this.switchTo(width, height); } handleResize = (e: CustomEvent<ResizeEvent>) => { const { height, width } = e.detail; this.scale = 1; this.demoHeight = height; this.demoWidth = width; this.viewerBodyEle.style.width = `${width}px`; this.viewerBodyEle.style.height = `${height}px`; this.resizableEle.style.width = `${width}px`; this.resizableEle.style.height = `${height}px`; this.orientation == Orientation.Landscape ? (this.browserFrameEle.style.width = `${height}px`) : this.browserFrameEle.style.removeProperty('width'); this.frameDemoEle?.style.removeProperty('height'); this.frameDemoEle?.style.removeProperty('width'); this.frameDemoEle?.style.removeProperty('transform'); } handleDidResize = (e: CustomEvent<ResizeEvent>) => { const { height, width } = e.detail; this.switchTo(width, height); } handleRotate = () => { this.orientation = this.orientation === Orientation.Portrait ? Orientation.Landscape : Orientation.Portrait; this.switchTo(this.demoHeight, this.demoWidth); } handleActivateTab = (e: CustomEvent<number>) => { this.currentTab = e.detail; } componentDidLoad() { if (!Build.isBrowser) { // Because `ResizeObserver` isn't available in prerendering mode return; } // Automatically update the size of container this.resizeObserver = new ResizeObserver(entries => { entries.forEach(entry => { const { height, width } = entry.contentRect; this.frameContainerHeight = height; this.frameContainerWidth = width; if (!this.setInitialSize) { this.setInitialSize = true; this.switchTo(width, height); } }); }); this.resizeObserver.observe(this.frameContainer); } disconnectedCallback() { this.resizeObserver?.disconnect(); } switchTo(width: number, height: number) { const scale = this.calculateScale(width, height); this.scale = scale; this.demoHeight = height; this.demoWidth = width; // Set the size for resizable element const newHeight = height * scale; const newWidth = width * scale; this.viewerBodyEle.style.height = `${newHeight}px`; this.viewerBodyEle.style.width = `${newWidth}px`; this.resizableEle.style.height = `${newHeight}px`; this.resizableEle.style.width = `${newWidth}px`; // Update the size of the browser frame this.orientation == Orientation.Landscape ? (this.browserFrameEle.style.width = `${newHeight}px`) : this.browserFrameEle.style.removeProperty('width'); // Set the frame size this.frameDemoEle?.style.setProperty('width', `${width}px`); this.frameDemoEle?.style.setProperty('height', `${height}px`); this.frameDemoEle?.style.setProperty('transform', scale === 1 ? 'scale(1)' : `translate(${width * (scale - 1) / 2}px, ${height * (scale - 1) / 2}px) scale(${scale})` ); } // Calculate the scale to make sure the frame fit best in the container calculateScale = (w: number, h: number) => { const minScale = Math.min(this.frameContainerWidth / w, this.frameContainerHeight / h); return Math.min(minScale, 1); }; toggleScreenList = () => { this.frameContainer.style.removeProperty('height'); this.frameContainer.style.removeProperty('width'); this.isScreenListOpen = !this.isScreenListOpen; } isSelectedSize = (height: number, width: number) => (this.demoHeight === height && this.demoWidth === width) || (this.demoHeight === width && this.demoWidth === height) render() { const url = `/patterns/${this.pattern!}.html`; const title = unslugify(this.pattern!); const currentIndex = PATTERNS.findIndex(p => slugify(p.name) === this.pattern); const previousPattern = currentIndex === 0 ? '' : `/${slugify(PATTERNS[currentIndex - 1].name)}`; const nextPattern = currentIndex >= PATTERNS.length - 1 ? '' : `/${slugify(PATTERNS[currentIndex + 1].name)}`; return ( <div class={`rp-demo-viewer ${this.isScreenListOpen ? 'rp-demo-viewer--withsidebar' : ''}`}> <div class="rp-demo-viewer__toolbar"> <div class="rp-demo-viewer__toolbar-left"> <rp-tooltip tip="Mobile screen (375x667)" position="bottom"> <button class={`rp-demo-viewer__button ${this.isSelectedSize(375, 667) ? 'rp-demo-viewer__button--selected' : ''}`} onClick={() => this.switchTo(375, 667)} > <rp-icon-mobile /> </button> </rp-tooltip> <rp-tooltip tip="Tablet screen (1024x768)" position="bottom"> <button class={`rp-demo-viewer__button ${this.isSelectedSize(1024, 768) ? 'rp-demo-viewer__button--selected' : ''}`} onClick={() => this.switchTo(1024, 768)} > <rp-icon-tablet /> </button> </rp-tooltip> <rp-tooltip tip="Laptop screen (1366x768)" position="bottom"> <button class={`rp-demo-viewer__button ${this.isSelectedSize(1366, 768) ? 'rp-demo-viewer__button--selected' : ''}`} onClick={() => this.switchTo(1366, 768)} > <rp-icon-laptop /> </button> </rp-tooltip> <rp-tooltip tip="Desktop screen (1920x1080)" position="bottom"> <button class={`rp-demo-viewer__button ${this.isSelectedSize(1920, 1080) ? 'rp-demo-viewer__button--selected' : ''}`} onClick={() => this.switchTo(1920, 1080)} > <rp-icon-desktop /> </button> </rp-tooltip> <div class="rp-demo-viewer__divider" /> <rp-tooltip tip="Other screen sizes" position="bottom"> <button class="rp-demo-viewer__button" onClick={this.toggleScreenList}> <rp-icon-screens /> </button> </rp-tooltip> </div> <a class="rp-demo-viewer__button rp-demo-viewer__button--selected" href="https://github.com/phuoc-ng/responsive-page" target="_blank"> <rp-icon-github /> </a> </div> <div class="rp-demo-viewer__main" ref={ele => this.frameContainer = ele as HTMLElement} > <rp-resizable ref={ele => this.resizableEle = ele as HTMLRpResizableElement} onResizeEvent={this.handleResize} onDidResizeEvent={this.handleDidResize} > <div class="rp-demo-viewer__body" ref={ele => this.viewerBodyEle = ele as HTMLElement} > <div class={`rp-demo-viewer__browser ${this.orientation === Orientation.Portrait ? 'rp-demo-viewer__browser--portrait' : 'rp-demo-viewer__browser--landscape'}`} ref={ele => this.browserFrameEle = ele as HTMLElement} > <rp-browser-frame browserTitle={title} backUrl={previousPattern} currentTab={this.currentTab} forwardUrl={nextPattern} url={this.currentTab === BrowserTab.Demo ? '' : `${PATTERN_URL_PREFIX}${url}`} onRotateEvent={this.handleRotate} onActivateTabEvent={this.handleActivateTab} /> </div> { this.currentTab === BrowserTab.Demo && [ this.scale !== 1 && <div class="demo_viewer__zoom">Zoom: {Math.floor(this.scale * 100)}%</div>, <iframe class="rp-demo-viewer__frame" ref={ele => this.frameDemoEle = ele as HTMLElement} src={url} /> ] } { this.currentTab === BrowserTab.Source && ( <div class="rp-demo-viewer__code"> <rp-pattern-source pattern={this.pattern} /> </div> ) } </div> </rp-resizable> </div> {this.isScreenListOpen && ( <div class="rp-demo-viewer__screens"> <rp-screens onChooseScreenSizeEvent={this.handleChangeScreenSize} /> </div> )} </div> ); } }
the_stack
import React, { createRef } from 'react' import { fromJS } from 'immutable' import { connect } from 'react-redux' import moment from 'moment' import { IGlobalControlRelatedItem, InteractionType, IControlRelatedField, ILocalControl } from 'app/components/Filters/types' import { getDefaultLocalControl, deserializeDefaultValue, serializeDefaultValue, getRelatedFieldsInfo } from 'app/components/Filters/util' import { FilterTypes, IS_RANGE_TYPE} from 'app/components/Filters/filterTypes' import { localControlMigrationRecorder } from 'app/utils/migrationRecorders' import FilterList from 'app/components/Filters/config/FilterList' import FilterFormWithRedux, { FilterForm } from 'app/components/Filters/config/FilterForm' import OptionSettingFormWithModal, { OptionSettingForm } from 'app/components/Filters/config/OptionSettingForm' import { Form, Row, Col, Button, Modal, Radio, Select, Checkbox } from 'antd' import { RadioChangeEvent } from 'antd/lib/radio' import { setControlFormValues } from 'app/containers/Dashboard/actions' import { IViewVariable, IFormedView, IViewModelProps } from 'app/containers/View/types' import { CheckboxChangeEvent } from 'antd/lib/checkbox' const FormItem = Form.Item const RadioGroup = Radio.Group const Option = Select.Option const styles = require('app/components/Filters/filter.less') export interface IRelatedItemSource extends IGlobalControlRelatedItem { id: number name: string } export interface IRelatedSource { model: IViewModelProps[] variables: IViewVariable[] fields: IControlRelatedField | IControlRelatedField[] } interface ILocalControlConfigProps { currentControls: ILocalControl[] view: IFormedView visible: boolean onCancel: () => void onSave: (filterItems: any[]) => void onSetControlFormValues: (values) => void } interface ILocalControlConfigStates { controls: ILocalControl[] selected: ILocalControl relatedFields: IRelatedSource optionModalVisible: boolean, optionValues: string } export class LocalControlConfig extends React.Component<ILocalControlConfigProps, ILocalControlConfigStates> { constructor (props) { super(props) this.state = { controls: [], selected: null, relatedFields: null, optionModalVisible: false, optionValues: '' } } private filterForm = createRef<FilterForm>() private optionSettingForm = createRef<OptionSettingForm>() public componentWillReceiveProps (nextProps: ILocalControlConfigProps) { const { view, currentControls, visible } = nextProps if (currentControls !== this.props.currentControls || visible && !this.props.visible) { let selected const controls = fromJS(currentControls).toJS().map((control) => { control = localControlMigrationRecorder(control) if (!selected && !control.parent) { selected = control } return control }) this.setState({ controls, selected, relatedFields: this.getRelatedFields(selected, view) }) this.setFormData(selected) } } private getRelatedFields = (selected: ILocalControl, view?: IFormedView): IRelatedSource => { if (!view) { view = this.props.view } if (selected) { const { type, interactionType, fields } = selected return getRelatedFieldsInfo(view, type, interactionType, fields) } return null } private setFormData = (control: ILocalControl) => { if (control) { const { type, interactionType, defaultValue, ...rest } = control const fieldsValue = { type, defaultValue: deserializeDefaultValue(control), ...rest } this.props.onSetControlFormValues(fieldsValue) } else { this.props.onSetControlFormValues(null) } } private selectFilter = (key: string) => { this.getCachedFormValues((err, controls) => { if (err) { return } const selected = controls.find((c) => c.key === key) this.setState({ selected, controls, relatedFields: this.getRelatedFields(selected) }) this.setFormData(selected) }) } private addFilter = () => { const { view } = this.props const { controls, selected } = this.state const newFilter: ILocalControl = getDefaultLocalControl(view) if (selected) { this.getCachedFormValues((err, cachedControls) => { if (err) { return } this.setState({ controls: [...cachedControls, newFilter], selected: newFilter, relatedFields: this.getRelatedFields(newFilter) }) this.setFormData(newFilter) }) } else { this.setState({ controls: [...controls, newFilter], selected: newFilter, relatedFields: this.getRelatedFields(newFilter) }) this.setFormData(newFilter) } } private deleteFilter = (keys: string[], reselectedKey: string) => { const { controls } = this.state const reselected = reselectedKey ? controls.find((c) => c.key === reselectedKey) : null this.setState({ controls: controls.filter((c) => !keys.includes(c.key)), selected: reselected, relatedFields: this.getRelatedFields(reselected) }) this.setFormData(reselected) } private changeParent = (key: string, parentKey: string, type: string , dropNextKey?: string) => { let dragged let changedControls = this.state.controls.reduce((ctrls, ctrl) => { if (ctrl.key === key) { dragged = ctrl return ctrls } return ctrls.concat(ctrl) }, []) let parent = null let parentIndex let dropNextIndex for (let i = 0, l = changedControls.length; i < l; i += 1) { const control = changedControls[i] if (control.key === parentKey) { parent = control parentIndex = i } if (dropNextKey && control.key === dropNextKey) { dropNextIndex = i } } dragged.parent = parent && parent.key if (dropNextKey) { changedControls = type === 'append' ? [ ...changedControls.slice(0, dropNextIndex + 1), dragged, ...changedControls.slice(dropNextIndex + 1) ] : [ ...changedControls.slice(0, dropNextIndex), dragged, ...changedControls.slice(dropNextIndex) ] } else { changedControls = parent ? [ ...changedControls.slice(0, parentIndex + 1), dragged, ...changedControls.slice(parentIndex + 1) ] : type === 'append' ? [...changedControls, dragged] : [dragged, ...changedControls] } this.setState({ controls: changedControls }) } private changeName = (key) => (name) => { this.setState({ controls: this.state.controls.map((c) => { return c.key === key ? { ...c, name } : c }) }) } private getCachedFormValues = ( resolve?: (err, cachedControls?) => void ) => { const { controls, selected, relatedFields } = this.state this.filterForm.current.props.form.validateFieldsAndScroll((err, values) => { if (err) { if (resolve) { resolve(err) } return } const { key, defaultValue } = values const cachedControls = controls.map((c) => { if (c.key === key) { return { ...c, ...values, interactionType: selected.interactionType, defaultValue: serializeDefaultValue(values, defaultValue), fields: relatedFields.fields } } else { return c } }) if (resolve) { resolve(null, cachedControls) } }) } private save = () => { const { onSave } = this.props if (this.state.controls.length > 0) { this.getCachedFormValues((err, cachedControls) => { if (err) { return } onSave(cachedControls) }) } else { onSave([]) } } private resetForm = () => { this.setState({ selected: null }) } private modelOrVariableSelect = (value: string | string[]) => { const { selected, relatedFields } = this.state const { model, variables } = relatedFields let fields let detail if (selected.interactionType === 'column') { detail = model.find((m) => m.name === value) fields = { name: detail.name, type: detail.sqlType } } else { if (IS_RANGE_TYPE[selected.type]) { fields = (value as string[]).map((str) => { detail = variables.find((m) => m.name === str) return { name: detail.name, type: detail.valueType } }) } else { detail = variables.find((m) => m.name === value) fields = { ...selected.type === FilterTypes.Select && relatedFields.fields, name: detail.name, type: detail.valueType } } } this.setState({ relatedFields: { ...relatedFields, fields } }) } private optionsFromColumnChecked = (e: CheckboxChangeEvent) => { const { relatedFields } = this.state this.setState({ relatedFields: { ...relatedFields, fields: { ...relatedFields.fields, optionsFromColumn: e.target.checked } } }) } private optionsFromColumnSelect = (value: string) => { const { relatedFields } = this.state this.setState({ relatedFields: { ...relatedFields, fields: { ...relatedFields.fields, column: value } } }) } private interactionTypeChange = (e: RadioChangeEvent) => { const currentSelected = this.state.selected const selected = { ...currentSelected, interactionType: e.target.value, fields: void 0 } this.setState({ selected, relatedFields: this.getRelatedFields({ ...selected, fields: void 0 }) }) } private controlTypeChange = (value) => { const { selected } = this.state const { interactionType, fields } = selected const changedSelected = { ...selected, type: value, fields: this.getValidaFields(interactionType, value, fields) } this.setState({ selected: changedSelected, relatedFields: this.getRelatedFields(changedSelected) }) } private getValidaFields = ( interactionType: InteractionType, type: FilterTypes, fields: IControlRelatedField | IControlRelatedField[] ): IControlRelatedField | IControlRelatedField[] => { if (fields) { if (interactionType === 'variable') { if (IS_RANGE_TYPE[type]) { return fields } else { return Array.isArray(fields) ? fields[0] : fields } } else { return fields } } return fields } private openOptionModal = () => { const { options } = this.state.selected this.setState({ optionModalVisible: true, optionValues: options && options.map((o) => `${o.text} ${o.value}`).join('\n') }) } private closeOptionModal = () => { this.setState({ optionModalVisible: false }) } private saveOptions = () => { this.optionSettingForm.current.props.form.validateFieldsAndScroll((err, values) => { if (err) { return } const options = values.options ? [...new Set(values.options.split(/\n/))] .filter((tnv: string) => !!tnv.trim()) .map((tnv: string) => { const tnvArr = tnv.split(/\s+/) return tnvArr.length === 1 ? { text: tnvArr[0], value: tnvArr[0] } : { text: tnvArr[0], value: tnvArr[1] } }) : [] this.filterForm.current.props.form.setFieldsValue({options}) this.closeOptionModal() }) } public render () { const { visible, onCancel } = this.props const { controls, selected, relatedFields, optionModalVisible, optionValues } = this.state let interactionType let interactionTypeContent let variableSelect let model = [] let variables = [] let fieldsValue let isMultiple let optionsFromColumn let column if (selected) { const { type: t, interactionType: it } = selected const { model: o, variables: v, fields } = relatedFields interactionType = it interactionTypeContent = interactionType === 'column' ? '字段' : '变量' variableSelect = it === 'variable' && t === FilterTypes.Select model = o variables = v if (Array.isArray(fields)) { isMultiple = true fieldsValue = fields.map((f) => f.name) } else { isMultiple = false if (fields) { fieldsValue = fields.name optionsFromColumn = fields.optionsFromColumn column = fields.column } } } const modalButtons = [( <Button key="cancel" size="large" onClick={onCancel} > 取 消 </Button> ), ( <Button key="submit" size="large" type="primary" onClick={this.save} > 保 存 </Button> )] return ( <Modal wrapClassName="ant-modal-large ant-modal-center" title="本地控制器配置" maskClosable={false} visible={visible} footer={modalButtons} onCancel={onCancel} afterClose={this.resetForm} > <div className={styles.filterConfig}> <div className={styles.left}> <FilterList list={controls} selectedFilter={selected} onSelectFilter={this.selectFilter} onAddFilter={this.addFilter} onDeleteFilter={this.deleteFilter} onNameChange={this.changeName} onParentChange={this.changeParent} /> </div> <div className={styles.center}> { selected && ( <div className={styles.filterFormContainer}> <div className={styles.baseForm}> <div className={styles.title}> <h2>基础配置</h2> </div> <Row gutter={8} className={styles.formBody}> <Col span={8}> <FormItem label="类型"> <RadioGroup value={interactionType} onChange={this.interactionTypeChange} > <Radio value="column">字段</Radio> <Radio value="variable">变量</Radio> </RadioGroup> </FormItem> </Col> { variableSelect && ( <Col span={8}> <FormItem label=" " colon={false}> <Checkbox checked={optionsFromColumn} onChange={this.optionsFromColumnChecked} > 从字段取值 </Checkbox> </FormItem> </Col> ) } </Row> <Row gutter={8} className={styles.formBody}> <Col span={8}> <FormItem label={`关联${interactionTypeContent}`}> <Select size="small" placeholder="请选择" className={styles.selector} value={fieldsValue} onChange={this.modelOrVariableSelect} dropdownMatchSelectWidth={false} {...isMultiple && {mode: 'multiple'}} > { interactionType === 'column' ? model.map((m: IViewModelProps) => ( <Option key={m.name} value={m.name}>{m.name}</Option> )) : variables.map((v) => ( <Option key={v.name} value={v.name} disabled={ isMultiple && fieldsValue.length === 2 && !fieldsValue.includes(v.name) } > {v.name} </Option> )) } </Select> </FormItem> </Col> { optionsFromColumn && ( <Col span={8}> <FormItem label="取值字段"> <Select size="small" placeholder="请选择" className={styles.selector} value={column} onChange={this.optionsFromColumnSelect} dropdownMatchSelectWidth={false} {...isMultiple && {mode: 'multiple'}} > { model.map((m: IViewModelProps) => ( <Option key={m.name} value={m.name}>{m.name}</Option> )) } </Select> </FormItem> </Col> ) } </Row> </div> <FilterFormWithRedux interactionType={selected.interactionType} onControlTypeChange={this.controlTypeChange} onOpenOptionModal={this.openOptionModal} wrappedComponentRef={this.filterForm} /> </div> ) } </div> <OptionSettingFormWithModal visible={optionModalVisible} options={optionValues} onSave={this.saveOptions} onCancel={this.closeOptionModal} wrappedComponentRef={this.optionSettingForm} /> </div> </Modal> ) } } function mapDispatchToProps (dispatch) { return { onSetControlFormValues: (values) => dispatch(setControlFormValues(values)) } } export default connect(null, mapDispatchToProps)(LocalControlConfig)
the_stack
import { GenericMeasure, LiftMeasure } from "../measure/genericMeasure"; import { Measure } from "../measure/numberMeasure"; import * as Base from "./base"; // Dimensionless /** A measure without any unit */ export type Dimensionless<N = number> = LiftMeasure<typeof Dimensionless, N>; export const Dimensionless: GenericMeasure<number, {}> = Measure.dimensionless(1); // Base units /** meters */ export type Length<N = number> = LiftMeasure<typeof Base.meters, N>; export const Length: Length = Base.meters; /** kilograms */ export type Mass<N = number> = LiftMeasure<typeof Base.kilograms, N>; export const Mass: Mass = Base.kilograms; /** seconds */ export type Time<N = number> = LiftMeasure<typeof Base.seconds, N>; export const Time: Time = Base.seconds; /** Amperes */ export type ElectricCurrent<N = number> = LiftMeasure<typeof Base.amperes, N>; export const ElectricCurrent: ElectricCurrent = Base.amperes; /** Kelvin */ export type Temperature<N = number> = LiftMeasure<typeof Base.kelvin, N>; export const Temperature: Temperature = Base.kelvin; /** moles */ export type AmountOfSubstance<N = number> = LiftMeasure<typeof Base.moles, N>; export const AmountOfSubstance: AmountOfSubstance = Base.moles; /** candelas */ export type LuminousIntensity<N = number> = LiftMeasure<typeof Base.candelas, N>; export const LuminousIntensity: LuminousIntensity = Base.candelas; /** bits */ export type Memory<N = number> = LiftMeasure<typeof Base.bits, N>; export const Memory: Memory = Base.bits; // Angular base units /** radians */ export type PlaneAngle<N = number> = LiftMeasure<typeof Base.radians, N>; export const PlaneAngle: PlaneAngle = Base.radians; /** steradians */ export type SolidAngle<N = number> = LiftMeasure<typeof Base.steradians, N>; export const SolidAngle: SolidAngle = Base.steradians; // Derived units /** 1 / s */ export type Frequency<N = number> = LiftMeasure<typeof Frequency, N>; export const Frequency = Time.inverse(); /** 1 / s² */ export type FrequencyDrift<N = number> = LiftMeasure<typeof FrequencyDrift, N>; export const FrequencyDrift = Time.toThe("-2"); /** 1 / m² */ export type FuelEfficiency<N = number> = LiftMeasure<typeof FuelEfficiency, N>; export const FuelEfficiency = Length.toThe("-2"); /** 1 / m */ export type Wavenumber<N = number> = LiftMeasure<typeof Wavenumber, N>; export const Wavenumber = Length.inverse(); /** m² */ export type Area<N = number> = LiftMeasure<typeof Area, N>; export const Area = Length.squared(); /** m³ */ export type Volume<N = number> = LiftMeasure<typeof Volume, N>; export const Volume = Length.cubed(); /** m ⋅ s */ export type Absement<N = number> = LiftMeasure<typeof Absement, N>; export const Absement = Length.times(Time); /** m / s */ export type Velocity<N = number> = LiftMeasure<typeof Velocity, N>; export const Velocity = Length.over(Time); /** m / s² */ export type Acceleration<N = number> = LiftMeasure<typeof Acceleration, N>; export const Acceleration = Velocity.over(Time); /** m / s³ */ export type Jerk<N = number> = LiftMeasure<typeof Jerk, N>; export const Jerk = Acceleration.over(Time); /** m / s⁴ */ export type Jounce<N = number> = LiftMeasure<typeof Jounce, N>; export const Jounce = Jerk.over(Time); /** m / s⁵ */ export type Crackle<N = number> = LiftMeasure<typeof Crackle, N>; export const Crackle = Jounce.over(Time); /** m³ / s */ export type VolumetricFlow<N = number> = LiftMeasure<typeof VolumetricFlow, N>; export const VolumetricFlow = Volume.over(Time); /** kg / s */ export type MassFlowRate<N = number> = LiftMeasure<typeof MassFlowRate, N>; export const MassFlowRate = Mass.over(Time); /** kg / m */ export type LinearDensity<N = number> = LiftMeasure<typeof LinearDensity, N>; export const LinearDensity = Mass.over(Length); /** kg / m² */ export type AreaDensity<N = number> = LiftMeasure<typeof AreaDensity, N>; export const AreaDensity = Mass.over(Area); /** kg / m³ */ export type VolumeDensity<N = number> = LiftMeasure<typeof VolumeDensity, N>; export const VolumeDensity = Mass.over(Volume); /** kg ⋅ m / s² */ export type Force<N = number> = LiftMeasure<typeof Force, N>; export const Force = Mass.times(Acceleration); /** km ⋅ m / s³ */ export type Yank<N = number> = LiftMeasure<typeof Yank, N>; export const Yank = Force.over(Time); /** kg / (m ⋅ s²) */ export type Pressure<N = number> = LiftMeasure<typeof Pressure, N>; export const Pressure = Force.over(Area); /** m ⋅ s² / kg */ export type Compressibility<N = number> = LiftMeasure<typeof Compressibility, N>; export const Compressibility = Pressure.inverse(); /** kg / (m ⋅ s) */ export type DynamicViscosity<N = number> = LiftMeasure<typeof DynamicViscosity, N>; export const DynamicViscosity = Pressure.times(Time); /** kg / s² */ export type SurfaceTension<N = number> = LiftMeasure<typeof SurfaceTension, N>; export const SurfaceTension = Force.over(Length); /** kg ⋅ m / s */ export type Momentum<N = number> = LiftMeasure<typeof Momentum, N>; export const Momentum = Force.times(Time); /** kg ⋅ m² */ export type MomentOfInertia<N = number> = LiftMeasure<typeof MomentOfInertia, N>; export const MomentOfInertia = Mass.times(Area); /** kg ⋅ m² / s² */ export type Energy<N = number> = LiftMeasure<typeof Energy, N>; export const Energy = Force.times(Length); /** kg ⋅ m² / s³ */ export type Power<N = number> = LiftMeasure<typeof Power, N>; export const Power = Energy.over(Time); /** kg / (m ⋅ s³) */ export type PowerDensity<N = number> = LiftMeasure<typeof PowerDensity, N>; export const PowerDensity = Power.over(Volume); /** kg ⋅ m² / (s³ ⋅ A) */ export type Voltage<N = number> = LiftMeasure<typeof Voltage, N>; export const Voltage = Power.over(ElectricCurrent); /** s ⋅ A */ export type ElectricCharge<N = number> = LiftMeasure<typeof ElectricCharge, N>; export const ElectricCharge = ElectricCurrent.times(Time); /** s ⋅ A / m³ */ export type ElectricChargeDensity<N = number> = LiftMeasure<typeof ElectricChargeDensity, N>; export const ElectricChargeDensity = ElectricCharge.over(Volume); /** A / m² */ export type ElectricCurrentDensity<N = number> = LiftMeasure<typeof ElectricCurrentDensity, N>; export const ElectricCurrentDensity = ElectricCurrent.over(Area); /** s ⋅ A / m² */ export type ElectricDisplacement<N = number> = LiftMeasure<typeof ElectricDisplacement, N>; export const ElectricDisplacement = ElectricCharge.over(Area); /** kg ⋅ m / (s³ ⋅ A) */ export type EletricFieldStrength<N = number> = LiftMeasure<typeof EletricFieldStrength, N>; export const EletricFieldStrength = Voltage.over(Length); /** s⁴ ⋅ A² / (kg ⋅ m²) */ export type ElectricalCapacitance<N = number> = LiftMeasure<typeof ElectricalCapacitance, N>; export const ElectricalCapacitance = ElectricCharge.over(Voltage); /** s³ ⋅ A / (kg ⋅ m²) */ export type ElectricalConductance<N = number> = LiftMeasure<typeof ElectricalConductance, N>; export const ElectricalConductance = ElectricCurrent.over(Voltage); /** s³ ⋅ A² / (kg ⋅ m³) */ export type ElectricalConductivity<N = number> = LiftMeasure<typeof ElectricalConductivity, N>; export const ElectricalConductivity = ElectricalConductance.over(Length); /** kg ⋅ m² / (s³ ⋅ A²) */ export type ElectricalResistance<N = number> = LiftMeasure<typeof ElectricalResistance, N>; export const ElectricalResistance = Voltage.over(ElectricCurrent); /** kg ⋅ m³ / (s³ ⋅ A²) */ export type ElectricalResistivity<N = number> = LiftMeasure<typeof ElectricalResistivity, N>; export const ElectricalResistivity = ElectricalResistance.times(Length); /** kg ⋅ m² / (s² ⋅ A²) */ export type ElectricalInductance<N = number> = LiftMeasure<typeof ElectricalInductance, N>; export const ElectricalInductance = ElectricalResistance.times(Time); /** s ⋅ A / m */ export type LinearChargeDensity<N = number> = LiftMeasure<typeof LinearChargeDensity, N>; export const LinearChargeDensity = ElectricCharge.over(Length); /** s⁴ ⋅ A² / (kg ⋅ m³) */ export type Permittivity<N = number> = LiftMeasure<typeof Permittivity, N>; export const Permittivity = ElectricalCapacitance.over(Length); /** kg ⋅ m² / (s² ⋅ A) */ export type MagneticFlux<N = number> = LiftMeasure<typeof MagneticFlux, N>; export const MagneticFlux = Energy.over(ElectricCurrent); /** kg / (s² ⋅ A) */ export type MagneticFluxDensity<N = number> = LiftMeasure<typeof MagneticFluxDensity, N>; export const MagneticFluxDensity = Voltage.times(Time).over(Area); /** kg ⋅ m / (s² ⋅ A²) */ export type MagneticPermeability<N = number> = LiftMeasure<typeof MagneticPermeability, N>; export const MagneticPermeability = ElectricalInductance.over(Length); /** A / m */ export type Magnetization<N = number> = LiftMeasure<typeof Magnetization, N>; export const Magnetization = ElectricCurrent.over(Length); /** s² ⋅ A² / (kg ⋅ m²) */ export type MagneticReluctance<N = number> = LiftMeasure<typeof MagneticReluctance, N>; export const MagneticReluctance = ElectricalInductance.inverse(); /** kg ⋅ m³ / (s² ⋅ A) */ export type MagneticMoment<N = number> = LiftMeasure<typeof MagneticMoment, N>; export const MagneticMoment = MagneticFlux.times(Length); /** kg ⋅ m / (s² ⋅ A) */ export type MagneticRigidity<N = number> = LiftMeasure<typeof MagneticRigidity, N>; export const MagneticRigidity = MagneticFluxDensity.times(Length); /** m² ⋅ A */ export type MagneticDipoleMoment<N = number> = LiftMeasure<typeof MagneticDipoleMoment, N>; export const MagneticDipoleMoment = Energy.over(MagneticFluxDensity); /** s² ⋅ A² / (kg ⋅ m) */ export type MagneticSusceptibility<N = number> = LiftMeasure<typeof MagneticSusceptibility, N>; export const MagneticSusceptibility = Length.over(ElectricalInductance); /** kg / s³ */ export type Irradiance<N = number> = LiftMeasure<typeof Irradiance, N>; export const Irradiance = Power.over(Area); /** kg ⋅ m / (s² ⋅ K) */ export type Entropy<N = number> = LiftMeasure<typeof Entropy, N>; export const Entropy = Energy.over(Temperature); /** m² / (s² ⋅ K) */ export type SpecificHeat<N = number> = LiftMeasure<typeof SpecificHeat, N>; export const SpecificHeat = Energy.over(Mass.times(Temperature)); /** m³ / kg */ export type SpecificVolume<N = number> = LiftMeasure<typeof SpecificVolume, N>; export const SpecificVolume = Volume.over(Mass); /** kg ⋅ m / (s³ ⋅ K) */ export type ThermalConductivity<N = number> = LiftMeasure<typeof ThermalConductivity, N>; export const ThermalConductivity = Power.over(Length.times(Temperature)); /** s³ ⋅ K / (kg ⋅ m²) */ export type ThermalResistance<N = number> = LiftMeasure<typeof ThermalResistance, N>; export const ThermalResistance = Temperature.over(Power); /** 1 / K */ export type ThermalExpansionCoefficient<N = number> = LiftMeasure<typeof ThermalExpansionCoefficient, N>; export const ThermalExpansionCoefficient = Temperature.inverse(); /** K / m */ export type ThermalGradient<N = number> = LiftMeasure<typeof ThermalGradient, N>; export const ThermalGradient = Temperature.over(Length); /** kg ⋅ m² / (s² ⋅ K ⋅ mol) */ export type MolarEntropy<N = number> = LiftMeasure<typeof MolarEntropy, N>; export const MolarEntropy = Entropy.over(AmountOfSubstance); /** kg ⋅ m² / (s² ⋅ mol) */ export type MolarEnergy<N = number> = LiftMeasure<typeof MolarEnergy, N>; export const MolarEnergy = Energy.over(AmountOfSubstance); /** mol / m³ */ export type Molarity<N = number> = LiftMeasure<typeof Molarity, N>; export const Molarity = AmountOfSubstance.over(Volume); /** m³ / mol */ export type MolarVolume<N = number> = LiftMeasure<typeof MolarVolume, N>; export const MolarVolume = Volume.over(AmountOfSubstance); /** mol / kg */ export type Molality<N = number> = LiftMeasure<typeof Molality, N>; export const Molality = AmountOfSubstance.over(Mass); /** kg / mol */ export type MolarMass<N = number> = LiftMeasure<typeof MolarMass, N>; export const MolarMass = Mass.over(AmountOfSubstance); /** s³ ⋅ A² / (kg ⋅ mol) */ export type MolarConductivity<N = number> = LiftMeasure<typeof MolarConductivity, N>; export const MolarConductivity = ElectricalConductance.times(Area).over(AmountOfSubstance); /** mol / s */ export type CatalyticActivity<N = number> = LiftMeasure<typeof CatalyticActivity, N>; export const CatalyticActivity = AmountOfSubstance.over(Time); /** m³ / (s ⋅ mol) */ export type CatalyticEfficiency<N = number> = LiftMeasure<typeof CatalyticEfficiency, N>; export const CatalyticEfficiency = Volume.over(AmountOfSubstance.times(Time)); /** mol / (m³ ⋅ s) */ export type ReactionRate<N = number> = LiftMeasure<typeof ReactionRate, N>; export const ReactionRate = CatalyticActivity.over(Volume); /** m² / s² */ export type RadiationDose<N = number> = LiftMeasure<typeof RadiationDose, N>; export const RadiationDose = Energy.over(Mass); /** m² / s³ */ export type RadiationDoseRate<N = number> = LiftMeasure<typeof RadiationDoseRate, N>; export const RadiationDoseRate = RadiationDose.over(Time); /** s² ⋅ A / kg */ export type ElectronMobility<N = number> = LiftMeasure<typeof ElectronMobility, N>; export const ElectronMobility = Area.over(Voltage.times(Time)); /** kg ⋅ m² / s */ export type AngularMomentum<N = number> = LiftMeasure<typeof AngularMomentum, N>; export const AngularMomentum = Force.times(Length).times(Time); /** m² /s */ export type SpecificAngularMomentum<N = number> = LiftMeasure<typeof SpecificAngularMomentum, N>; export const SpecificAngularMomentum = AngularMomentum.over(Mass); /** cd / m² */ export type Luminance<N = number> = LiftMeasure<typeof Luminance, N>; export const Luminance = LuminousIntensity.over(Area); // Angular derived units /** cd ⋅ sr */ export type LuminousFlux<N = number> = LiftMeasure<typeof LuminousFlux, N>; export const LuminousFlux = LuminousIntensity.times(SolidAngle); /** cd ⋅ sr / m² */ export type Illuminance<N = number> = LiftMeasure<typeof Illuminance, N>; export const Illuminance = LuminousFlux.over(Area); /** s ⋅ cd ⋅ sr */ export type LuminousEnergy<N = number> = LiftMeasure<typeof LuminousEnergy, N>; export const LuminousEnergy = LuminousFlux.times(Time); /** s ⋅ cd ⋅ sr / m² */ export type LuminousExposure<N = number> = LiftMeasure<typeof LuminousExposure, N>; export const LuminousExposure = Illuminance.times(Time); /** s³ ⋅ cd ⋅ sr / (kg ⋅ m²) */ export type LuminousEfficiency<N = number> = LiftMeasure<typeof LuminousEfficiency, N>; export const LuminousEfficiency = LuminousFlux.over(Power); /** kg ⋅ m² / (s³ ⋅ sr) */ export type RadiantIntensity<N = number> = LiftMeasure<typeof RadiantIntensity, N>; export const RadiantIntensity = Power.over(SolidAngle); /** kg ⋅ m / (s³ ⋅ sr) */ export type SpectralIntensity<N = number> = LiftMeasure<typeof SpectralIntensity, N>; export const SpectralIntensity = RadiantIntensity.over(Length); /** kg / (s³ ⋅ sr) */ export type Radiance<N = number> = LiftMeasure<typeof Radiance, N>; export const Radiance = RadiantIntensity.over(Area); /** kg / (m ⋅ s³ ⋅ sr) */ export type SpectralRadiance<N = number> = LiftMeasure<typeof SpectralRadiance, N>; export const SpectralRadiance = RadiantIntensity.over(Volume); /** rad / s */ export type AngularVelocity<N = number> = LiftMeasure<typeof AngularVelocity, N>; export const AngularVelocity = PlaneAngle.over(Time); /** rad / s² */ export type AngularAcceleration<N = number> = LiftMeasure<typeof AngularAcceleration, N>; export const AngularAcceleration = AngularVelocity.over(Time);
the_stack
import * as urlUtil from '../../src/internal/url-util' interface PartialUrl { readonly scheme?: string | null readonly host?: string readonly port?: number readonly hostAndPort?: string readonly query?: Object readonly ipv6?: boolean } describe('#unit url-util', () => { it('should parse URL with just host name', () => { verifyUrl('localhost', { host: 'localhost' }) verifyUrl('neo4j.com', { host: 'neo4j.com' }) verifyUrl('some-neo4j-server.com', { host: 'some-neo4j-server.com' }) verifyUrl('ec2-34-242-76-91.eu-west-1.compute.aws.com', { host: 'ec2-34-242-76-91.eu-west-1.compute.aws.com' }) }) it('should parse URL with just IPv4 address', () => { verifyUrl('127.0.0.1', { host: '127.0.0.1' }) verifyUrl('10.10.192.0', { host: '10.10.192.0' }) verifyUrl('172.10.5.1', { host: '172.10.5.1' }) verifyUrl('34.242.76.91', { host: '34.242.76.91' }) }) it('should parse URL with just IPv6 address', () => { verifyUrl('[::1]', { host: '::1', ipv6: true }) verifyUrl('[ff02::2:ff00:0]', { host: 'ff02::2:ff00:0', ipv6: true }) verifyUrl('[1afc:0:a33:85a3::ff2f]', { host: '1afc:0:a33:85a3::ff2f', ipv6: true }) verifyUrl('[ff0a::101]', { host: 'ff0a::101', ipv6: true }) verifyUrl('[2a05:d018:270:f400:6d8c:d425:c5f:97f3]', { host: '2a05:d018:270:f400:6d8c:d425:c5f:97f3', ipv6: true }) verifyUrl('[fe80::1%lo0]', { host: 'fe80::1%lo0', ipv6: true }) }) it('should parse URL with host name and query', () => { verifyUrl('localhost?key1=value1&key2=value2', { host: 'localhost', query: { key1: 'value1', key2: 'value2' } }) verifyUrl('neo4j.com/?key1=1&key2=2', { host: 'neo4j.com', query: { key1: '1', key2: '2' } }) verifyUrl('some-neo4j-server.com?a=value1&b=value2&c=value3', { host: 'some-neo4j-server.com', query: { a: 'value1', b: 'value2', c: 'value3' } }) verifyUrl( 'ec2-34-242-76-91.eu-west-1.compute.aws.com/?foo=1&bar=2&baz=3&qux=4', { host: 'ec2-34-242-76-91.eu-west-1.compute.aws.com', query: { foo: '1', bar: '2', baz: '3', qux: '4' } } ) }) it('should parse URL with IPv4 address and query', () => { verifyUrl('127.0.0.1?key1=value1&key2=value2', { host: '127.0.0.1', query: { key1: 'value1', key2: 'value2' } }) verifyUrl('10.10.192.0?key1=1&key2=2', { host: '10.10.192.0', query: { key1: '1', key2: '2' } }) verifyUrl('172.10.5.1?a=value1&b=value2&c=value3', { host: '172.10.5.1', query: { a: 'value1', b: 'value2', c: 'value3' } }) verifyUrl('34.242.76.91/?foo=1&bar=2&baz=3&qux=4', { host: '34.242.76.91', query: { foo: '1', bar: '2', baz: '3', qux: '4' } }) }) it('should parse URL with IPv6 address and query', () => { verifyUrl('[::1]?key1=value1&key2=value2', { host: '::1', query: { key1: 'value1', key2: 'value2' }, ipv6: true }) verifyUrl('[ff02::2:ff00:0]?key1=1&key2=2', { host: 'ff02::2:ff00:0', query: { key1: '1', key2: '2' }, ipv6: true }) verifyUrl('[1afc:0:a33:85a3::ff2f]/?a=value1&b=value2&c=value3', { host: '1afc:0:a33:85a3::ff2f', query: { a: 'value1', b: 'value2', c: 'value3' }, ipv6: true }) verifyUrl('[ff0a::101]/?foo=1&bar=2&baz=3&qux=4', { host: 'ff0a::101', query: { foo: '1', bar: '2', baz: '3', qux: '4' }, ipv6: true }) verifyUrl('[2a05:d018:270:f400:6d8c:d425:c5f:97f3]?animal=apa', { host: '2a05:d018:270:f400:6d8c:d425:c5f:97f3', query: { animal: 'apa' }, ipv6: true }) verifyUrl('[fe80::1%lo0]?animal=apa', { host: 'fe80::1%lo0', query: { animal: 'apa' }, ipv6: true }) }) it('should parse URL with scheme, host name and query', () => { verifyUrl('http://localhost?key1=value1&key2=value2', { scheme: 'http', host: 'localhost', query: { key1: 'value1', key2: 'value2' } }) verifyUrl('https://neo4j.com/?key1=1&key2=2', { scheme: 'https', host: 'neo4j.com', query: { key1: '1', key2: '2' } }) verifyUrl('bolt://some-neo4j-server.com/?a=value1&b=value2&c=value3', { scheme: 'bolt', host: 'some-neo4j-server.com', query: { a: 'value1', b: 'value2', c: 'value3' } }) verifyUrl( 'neo4j://ec2-34-242-76-91.eu-west-1.compute.aws.com?foo=1&bar=2&baz=3&qux=4', { scheme: 'neo4j', host: 'ec2-34-242-76-91.eu-west-1.compute.aws.com', query: { foo: '1', bar: '2', baz: '3', qux: '4' } } ) }) it('should parse URL with scheme, IPv4 address and query', () => { verifyUrl('ftp://127.0.0.1/?key1=value1&key2=value2', { scheme: 'ftp', host: '127.0.0.1', query: { key1: 'value1', key2: 'value2' } }) verifyUrl('neo4j://10.10.192.0?key1=1&key2=2', { scheme: 'neo4j', host: '10.10.192.0', query: { key1: '1', key2: '2' } }) verifyUrl('bolt://172.10.5.1?a=value1&b=value2&c=value3', { scheme: 'bolt', host: '172.10.5.1', query: { a: 'value1', b: 'value2', c: 'value3' } }) verifyUrl('https://34.242.76.91/?foo=1&bar=2&baz=3&qux=4', { scheme: 'https', host: '34.242.76.91', query: { foo: '1', bar: '2', baz: '3', qux: '4' } }) }) it('should parse URL with scheme, IPv6 address and query', () => { verifyUrl('neo4j://[::1]?key1=value1&key2=value2', { scheme: 'neo4j', host: '::1', query: { key1: 'value1', key2: 'value2' }, ipv6: true }) verifyUrl('http://[ff02::2:ff00:0]?key1=1&key2=2', { scheme: 'http', host: 'ff02::2:ff00:0', query: { key1: '1', key2: '2' }, ipv6: true }) verifyUrl('https://[1afc:0:a33:85a3::ff2f]/?a=value1&b=value2&c=value3', { scheme: 'https', host: '1afc:0:a33:85a3::ff2f', query: { a: 'value1', b: 'value2', c: 'value3' }, ipv6: true }) verifyUrl('bolt://[ff0a::101]/?foo=1&bar=2&baz=3&qux=4', { scheme: 'bolt', host: 'ff0a::101', query: { foo: '1', bar: '2', baz: '3', qux: '4' }, ipv6: true }) verifyUrl('neo4j://[2a05:d018:270:f400:6d8c:d425:c5f:97f3]?animal=apa', { scheme: 'neo4j', host: '2a05:d018:270:f400:6d8c:d425:c5f:97f3', query: { animal: 'apa' }, ipv6: true }) verifyUrl('neo4j://[fe80::1%lo0]?animal=apa', { scheme: 'neo4j', host: 'fe80::1%lo0', query: { animal: 'apa' }, ipv6: true }) }) it('should parse URL with host name and port', () => { verifyUrl('localhost:1212', { host: 'localhost', port: 1212 }) verifyUrl('neo4j.com:8888', { host: 'neo4j.com', port: 8888 }) verifyUrl('some-neo4j-server.com:42', { host: 'some-neo4j-server.com', port: 42 }) verifyUrl('ec2-34-242-76-91.eu-west-1.compute.aws.com:62220', { host: 'ec2-34-242-76-91.eu-west-1.compute.aws.com', port: 62220 }) }) it('should parse URL with IPv4 address and port', () => { verifyUrl('127.0.0.1:9090', { host: '127.0.0.1', port: 9090 }) verifyUrl('10.10.192.0:22000', { host: '10.10.192.0', port: 22000 }) verifyUrl('172.10.5.1:42', { host: '172.10.5.1', port: 42 }) verifyUrl('34.242.76.91:7687', { host: '34.242.76.91', port: 7687 }) }) it('should parse URL with IPv6 address and port', () => { verifyUrl('[::1]:36000', { host: '::1', port: 36000, ipv6: true }) verifyUrl('[ff02::2:ff00:0]:8080', { host: 'ff02::2:ff00:0', port: 8080, ipv6: true }) verifyUrl('[1afc:0:a33:85a3::ff2f]:7474', { host: '1afc:0:a33:85a3::ff2f', port: 7474, ipv6: true }) verifyUrl('[ff0a::101]:1000', { host: 'ff0a::101', port: 1000, ipv6: true }) verifyUrl('[2a05:d018:270:f400:6d8c:d425:c5f:97f3]:7475', { host: '2a05:d018:270:f400:6d8c:d425:c5f:97f3', port: 7475, ipv6: true }) verifyUrl('[fe80::1%lo0]:7475', { host: 'fe80::1%lo0', port: 7475, ipv6: true }) }) it('should parse URL with scheme and host name', () => { verifyUrl('ftp://localhost', { scheme: 'ftp', host: 'localhost' }) verifyUrl('https://neo4j.com', { scheme: 'https', host: 'neo4j.com' }) verifyUrl('wss://some-neo4j-server.com', { scheme: 'wss', host: 'some-neo4j-server.com' }) verifyUrl('bolt://ec2-34-242-76-91.eu-west-1.compute.aws.com', { scheme: 'bolt', host: 'ec2-34-242-76-91.eu-west-1.compute.aws.com' }) }) it('should parse URL with scheme and IPv4 address', () => { verifyUrl('neo4j://127.0.0.1', { scheme: 'neo4j', host: '127.0.0.1' }) verifyUrl('http://10.10.192.0', { scheme: 'http', host: '10.10.192.0' }) verifyUrl('ws://172.10.5.1', { scheme: 'ws', host: '172.10.5.1' }) verifyUrl('bolt://34.242.76.91', { scheme: 'bolt', host: '34.242.76.91' }) }) it('should parse URL with scheme and IPv6 address', () => { verifyUrl('https://[::1]', { scheme: 'https', host: '::1', ipv6: true }) verifyUrl('http://[ff02::2:ff00:0]', { scheme: 'http', host: 'ff02::2:ff00:0', ipv6: true }) verifyUrl('neo4j://[1afc:0:a33:85a3::ff2f]', { scheme: 'neo4j', host: '1afc:0:a33:85a3::ff2f', ipv6: true }) verifyUrl('bolt://[ff0a::101]', { scheme: 'bolt', host: 'ff0a::101', ipv6: true }) verifyUrl('neo4j://[2a05:d018:270:f400:6d8c:d425:c5f:97f3]', { scheme: 'neo4j', host: '2a05:d018:270:f400:6d8c:d425:c5f:97f3', ipv6: true }) verifyUrl('neo4j://[fe80::1%lo0]', { scheme: 'neo4j', host: 'fe80::1%lo0', ipv6: true }) }) it('should parse URL with scheme, host name and port', () => { verifyUrl('http://localhost:8080', { scheme: 'http', host: 'localhost', port: 8080 }) verifyUrl('bolt://neo4j.com:42', { scheme: 'bolt', host: 'neo4j.com', port: 42 }) verifyUrl('neo4j://some-neo4j-server.com:12000', { scheme: 'neo4j', host: 'some-neo4j-server.com', port: 12000 }) verifyUrl('wss://ec2-34-242-76-91.eu-west-1.compute.aws.com:2626', { scheme: 'wss', host: 'ec2-34-242-76-91.eu-west-1.compute.aws.com', port: 2626 }) }) it('should parse URL with scheme, IPv4 address and port', () => { verifyUrl('bolt://127.0.0.1:9091', { scheme: 'bolt', host: '127.0.0.1', port: 9091 }) verifyUrl('bolt://10.10.192.0:7447', { scheme: 'bolt', host: '10.10.192.0', port: 7447 }) verifyUrl('neo4j://172.10.5.1:8888', { scheme: 'neo4j', host: '172.10.5.1', port: 8888 }) verifyUrl('https://34.242.76.91:42', { scheme: 'https', host: '34.242.76.91', port: 42 }) }) it('should parse URL with scheme, IPv6 address and port', () => { verifyUrl('http://[::1]:9123', { scheme: 'http', host: '::1', port: 9123, ipv6: true }) verifyUrl('bolt://[ff02::2:ff00:0]:3831', { scheme: 'bolt', host: 'ff02::2:ff00:0', port: 3831, ipv6: true }) verifyUrl('neo4j://[1afc:0:a33:85a3::ff2f]:50505', { scheme: 'neo4j', host: '1afc:0:a33:85a3::ff2f', port: 50505, ipv6: true }) verifyUrl('ftp://[ff0a::101]:4242', { scheme: 'ftp', host: 'ff0a::101', port: 4242, ipv6: true }) verifyUrl('wss://[2a05:d018:270:f400:6d8c:d425:c5f:97f3]:22', { scheme: 'wss', host: '2a05:d018:270:f400:6d8c:d425:c5f:97f3', port: 22, ipv6: true }) verifyUrl('wss://[fe80::1%lo0]:22', { scheme: 'wss', host: 'fe80::1%lo0', port: 22, ipv6: true }) }) it('should parse URL with scheme, host name, port and query', () => { verifyUrl('http://localhost:3032/?key1=value1&key2=value2', { scheme: 'http', host: 'localhost', port: 3032, query: { key1: 'value1', key2: 'value2' } }) verifyUrl('https://neo4j.com:7575?foo=bar&baz=qux', { scheme: 'https', host: 'neo4j.com', port: 7575, query: { foo: 'bar', baz: 'qux' } }) verifyUrl('neo4j://some-neo4j-server.com:14500?key=value', { scheme: 'neo4j', host: 'some-neo4j-server.com', port: 14500, query: { key: 'value' } }) verifyUrl( 'ws://ec2-34-242-76-91.eu-west-1.compute.aws.com:30270?a=1&b=2&c=3&d=4', { scheme: 'ws', host: 'ec2-34-242-76-91.eu-west-1.compute.aws.com', port: 30270, query: { a: '1', b: '2', c: '3', d: '4' } } ) }) it('should parse URL with scheme, IPv4 address, port and query', () => { verifyUrl('bolt://127.0.0.1:30399?key1=value1&key2=value2', { scheme: 'bolt', host: '127.0.0.1', port: 30399, query: { key1: 'value1', key2: 'value2' } }) verifyUrl('neo4j://10.10.192.0:12100/?foo=bar&baz=qux', { scheme: 'neo4j', host: '10.10.192.0', port: 12100, query: { foo: 'bar', baz: 'qux' } }) verifyUrl('bolt://172.10.5.1:22?a=1&b=2&c=3&d=4', { scheme: 'bolt', host: '172.10.5.1', port: 22, query: { a: '1', b: '2', c: '3', d: '4' } }) verifyUrl('http://34.242.76.91:1829?key=value', { scheme: 'http', host: '34.242.76.91', port: 1829, query: { key: 'value' } }) }) it('should parse URL with scheme, IPv6 address, port and query', () => { verifyUrl('https://[::1]:4217?key=value', { scheme: 'https', host: '::1', port: 4217, query: { key: 'value' }, ipv6: true }) verifyUrl('neo4j://[ff02::2:ff00:0]:22/?animal1=apa&animal2=dog', { scheme: 'neo4j', host: 'ff02::2:ff00:0', port: 22, query: { animal1: 'apa', animal2: 'dog' }, ipv6: true }) verifyUrl('bolt://[1afc:0:a33:85a3::ff2f]:4242?a=1&b=2&c=3&d=4', { scheme: 'bolt', host: '1afc:0:a33:85a3::ff2f', port: 4242, query: { a: '1', b: '2', c: '3', d: '4' }, ipv6: true }) verifyUrl('wss://[ff0a::101]:24240?foo=bar&baz=qux', { scheme: 'wss', host: 'ff0a::101', port: 24240, query: { foo: 'bar', baz: 'qux' }, ipv6: true }) verifyUrl( 'https://[2a05:d018:270:f400:6d8c:d425:c5f:97f3]:42?key1=value1&key2=value2', { scheme: 'https', host: '2a05:d018:270:f400:6d8c:d425:c5f:97f3', port: 42, query: { key1: 'value1', key2: 'value2' }, ipv6: true } ) verifyUrl('https://[fe80::1%lo0]:4242?key1=value1', { scheme: 'https', host: 'fe80::1%lo0', port: 4242, query: { key1: 'value1' }, ipv6: true }) }) it('should fail to parse URL without host', () => { expect(() => parse('http://')).toThrow() expect(() => parse('bolt://')).toThrow() expect(() => parse('neo4j://')).toThrow() }) it('should fail to parse URL with duplicated query parameters', () => { expect(() => parse('bolt://localhost/?key=value1&key=value2')).toThrow() expect(() => parse('bolt://localhost:8080/?key=value1&key=value2') ).toThrow() expect(() => parse('neo4j://10.10.127.5?key=value1&key=value2')).toThrow() expect(() => parse('neo4j://10.10.127.5:8080?key=value1&key=value2') ).toThrow() expect(() => parse('https://[ff0a::101]?key=value1&key=value2')).toThrow() expect(() => parse('https://[ff0a::101]:8080?key=value1&key=value2') ).toThrow() }) it('should fail to parse URL with empty query key', () => { expect(() => parse('bolt://localhost?=value')).toThrow() expect(() => parse('bolt://localhost:8080?=value')).toThrow() expect(() => parse('neo4j://10.10.127.5?=value')).toThrow() expect(() => parse('neo4j://10.10.127.5:8080?=value')).toThrow() expect(() => parse('https://[ff0a::101]/?value=')).toThrow() expect(() => parse('https://[ff0a::101]:8080/?=value')).toThrow() }) it('should fail to parse URL with empty query value', () => { expect(() => parse('bolt://localhost?key=')).toThrow() expect(() => parse('bolt://localhost:8080?key=')).toThrow() expect(() => parse('neo4j://10.10.127.5/?key=')).toThrow() expect(() => parse('neo4j://10.10.127.5:8080/?key=')).toThrow() expect(() => parse('https://[ff0a::101]?key=')).toThrow() expect(() => parse('https://[ff0a::101]:8080?key=')).toThrow() }) it('should fail to parse URL with no query value', () => { expect(() => parse('bolt://localhost?key')).toThrow() expect(() => parse('bolt://localhost:8080?key')).toThrow() expect(() => parse('neo4j://10.10.127.5/?key')).toThrow() expect(() => parse('neo4j://10.10.127.5:8080/?key')).toThrow() expect(() => parse('https://[ff0a::101]?key')).toThrow() expect(() => parse('https://[ff0a::101]:8080?key')).toThrow() }) it('should fail to parse non-strings', () => { expect(() => parse({})).toThrowError(TypeError) expect(() => parse(['bolt://localhost:2020'])).toThrowError(TypeError) expect(() => parse(() => 'bolt://localhost:8888')).toThrowError(TypeError) }) it('should format IPv4 address', () => { expect(urlUtil.formatIPv4Address('127.0.0.1', 4242)).toEqual( '127.0.0.1:4242' ) expect(urlUtil.formatIPv4Address('192.168.10.10', 8080)).toEqual( '192.168.10.10:8080' ) expect(urlUtil.formatIPv4Address('8.8.8.8', 80)).toEqual('8.8.8.8:80') }) it('should format IPv6 address', () => { expect(urlUtil.formatIPv6Address('::1', 1200)).toEqual('[::1]:1200') expect(urlUtil.formatIPv6Address('ff0a::101', 8080)).toEqual( '[ff0a::101]:8080' ) expect(urlUtil.formatIPv6Address('[::1]', 42)).toEqual('[::1]:42') expect(urlUtil.formatIPv6Address('[1afc:0:a33:85a3::ff2f]', 20201)).toEqual( '[1afc:0:a33:85a3::ff2f]:20201' ) }) it('should fail to format partially escaped IPv6 address', () => { expect(() => urlUtil.formatIPv6Address('[::1', 1000)).toThrow() expect(() => urlUtil.formatIPv6Address('::1]', 2000)).toThrow() expect(() => urlUtil.formatIPv6Address('[1afc:0:a33:85a3::ff2f', 3000) ).toThrow() expect(() => urlUtil.formatIPv6Address('1afc:0:a33:85a3::ff2f]', 4000) ).toThrow() }) it('should use default ports when no port specified', () => { expect(parse('bolt://localhost').port).toEqual( urlUtil.defaultPortForScheme('bolt') ) expect(parse('neo4j://localhost').port).toEqual( urlUtil.defaultPortForScheme('bolt') ) expect(parse('http://localhost').port).toEqual( urlUtil.defaultPortForScheme('http') ) expect(parse('https://localhost').port).toEqual( urlUtil.defaultPortForScheme('https') ) }) it('should parse URLs with port 80', () => { ;['http', 'https', 'ws', 'wss', 'bolt', 'neo4j'].forEach(scheme => { verifyUrl(`${scheme}://localhost:80`, { scheme: scheme, host: 'localhost', port: 80 }) }) ;['localhost', '127.0.0.1', '192.168.10.29'].forEach(host => { verifyUrl(`${host}:80`, { host: host, port: 80 }) }) ;['::1', '1afc:0:a33:85a3::ff2f'].forEach(host => { verifyUrl(`[${host}]:80`, { host: host, port: 80, ipv6: true }) }) }) function verifyUrl(urlString: string, expectedUrl: PartialUrl) { const url = parse(urlString) if (expectedUrl.scheme) { expect(url.scheme).toEqual(expectedUrl.scheme) } else { expect(url.scheme).toBeNull() } expect(url.host).toBeDefined() expect(url.host).not.toBeNull() expect(url.host).toEqual(expectedUrl.host) if (expectedUrl.port) { expect(url.port).toEqual(expectedUrl.port) } else { expect(url.port).toEqual( urlUtil.defaultPortForScheme(expectedUrl.scheme!!) ) } verifyHostAndPort(url, expectedUrl) if (expectedUrl.query) { expect(url.query).toEqual(expectedUrl.query) } else { expect(url.query).toEqual({}) } } function verifyHostAndPort(url: urlUtil.Url, expectedUrl: PartialUrl) { const port = expectedUrl.port === 0 || expectedUrl.port ? expectedUrl.port : urlUtil.defaultPortForScheme(expectedUrl.scheme!!) if (expectedUrl.ipv6) { expect(url.hostAndPort).toEqual(`[${expectedUrl.host}]:${port}`) } else { expect(url.hostAndPort).toEqual(`${expectedUrl.host}:${port}`) } } function parse(url: any): urlUtil.Url { return urlUtil.parseDatabaseUrl(url) } })
the_stack
import { Subject } from 'rxjs'; import { Router } from '@angular/router'; import { TestBed, fakeAsync, tick, flush } from '@angular/core/testing'; import { HttpClientTestingModule } from '@angular/common/http/testing'; import { PlanetApplicationLoader, ApplicationStatus } from './planet-application-loader'; import { AssetsLoader, AssetsLoadResult } from '../assets-loader'; import { SwitchModes, PlanetApplication } from '../planet.class'; import { PlanetApplicationService } from './planet-application.service'; import { NgZone, Injector, ApplicationRef } from '@angular/core'; import { BootstrapOptions, PlanetApplicationRef } from './planet-application-ref'; import { app1, app2 } from '../testing/applications'; import { Planet } from 'ngx-planet/planet'; import { getApplicationLoader, getApplicationService, clearGlobalPlanet } from 'ngx-planet/global-planet'; import { RouterTestingModule } from '@angular/router/testing'; import { sample } from '../testing/utils'; class PlanetApplicationRefFaker { planetAppRef: PlanetApplicationRef; destroySpy: jasmine.Spy; bootstrapSpy: jasmine.Spy; navigateByUrlSpy: jasmine.Spy; getCurrentRouterStateUrlSpy: jasmine.Spy; bootstrap$: Subject<PlanetApplicationRef>; constructor(appName: string, options?: BootstrapOptions) { this.planetAppRef = new PlanetApplicationRef(appName, options); this.bootstrapSpy = spyOn(this.planetAppRef, 'bootstrap'); this.bootstrap$ = new Subject<PlanetApplicationRef>(); this.bootstrapSpy.and.returnValues(this.bootstrap$, this.bootstrap$); this.destroySpy = spyOn(this.planetAppRef, 'destroy'); this.navigateByUrlSpy = spyOn(this.planetAppRef, 'navigateByUrl'); this.getCurrentRouterStateUrlSpy = spyOn(this.planetAppRef, 'getCurrentRouterStateUrl'); (window as any).planet.apps[appName] = this.planetAppRef; } static create(appName: string, options?: BootstrapOptions) { return new PlanetApplicationRefFaker(appName, options); } bootstrap() { this.bootstrap$.next(); this.bootstrap$.complete(); } haveBeenBootstrap() { expect(this.bootstrapSpy).toHaveBeenCalled(); } haveNotBeenBootstrap() { expect(this.bootstrapSpy).not.toHaveBeenCalled(); } } class AppStatusChangeFaker { spy: jasmine.Spy; planetApplicationLoader: PlanetApplicationLoader; status = new Map<string, ApplicationStatus>(); constructor(planetApplicationLoader: PlanetApplicationLoader) { this.planetApplicationLoader = planetApplicationLoader; this.spy = jasmine.createSpy('app status change spy'); planetApplicationLoader.appStatusChange.subscribe(data => { this.spy(data); this.status.set(data.app.name, data.status); }); expect(this.spy).not.toHaveBeenCalled(); } static create(planetApplicationLoader: PlanetApplicationLoader) { return new AppStatusChangeFaker(planetApplicationLoader); } expectHaveBeenCalledWith(...params: any[]) { expect(this.spy).toHaveBeenCalled(); expect(this.spy).toHaveBeenCalledWith(...params); } // 封装从资源加载完毕到应用的启动和激活过程,简化每个测试用例重复写很多逻辑 expectFromAssetsLoadedToActive( fromCalledTimes: number, appRefFaker: PlanetApplicationRefFaker, expectedApp: PlanetApplication ) { appRefFaker.haveNotBeenBootstrap(); flush(); appRefFaker.haveBeenBootstrap(); expect(this.spy).toHaveBeenCalledTimes(fromCalledTimes + 1); expect(this.spy).toHaveBeenCalledWith({ app: expectedApp, status: ApplicationStatus.bootstrapping }); expect(this.planetApplicationLoader.loadingDone).toBe(false); appRefFaker.bootstrap(); expect(this.planetApplicationLoader.loadingDone).toBe(true); expect(this.spy).toHaveBeenCalledTimes(fromCalledTimes + 3); expect(this.spy).toHaveBeenCalledWith({ app: expectedApp, status: ApplicationStatus.bootstrapped }); expect(this.spy).toHaveBeenCalledWith({ app: expectedApp, status: ApplicationStatus.active }); } expectAppStatus(appName: string, expectedStatus: ApplicationStatus) { const status = this.status.get(appName); expect(status).toEqual(expectedStatus, `${appName} status is ${status}`); } } describe('PlanetApplicationLoader', () => { let planetApplicationLoader: PlanetApplicationLoader; let planetApplicationService: PlanetApplicationService; let assetsLoader: AssetsLoader; let ngZone: NgZone; let planet: Planet; function expectApp1Element(classesStr = 'app1-host app1-prefix') { const app1Host = document.querySelector(app1.selector); expect(app1Host).toBeTruthy(); expect(app1Host.outerHTML).toEqual(`<app1-root class="${classesStr}"></app1-root>`); } function expectApp2Element() { const app2Host = document.querySelector(app2.selector); expect(app2Host).toBeTruthy(); expect(app2Host.outerHTML).toEqual(`<app2-root class="app2-host"></app2-root>`); } beforeEach(() => { TestBed.configureTestingModule({ imports: [HttpClientTestingModule, RouterTestingModule.withRoutes([])] }); planet = TestBed.inject(Planet); planetApplicationLoader = getApplicationLoader(); planetApplicationService = getApplicationService(); assetsLoader = TestBed.inject(AssetsLoader); ngZone = TestBed.inject(NgZone); planetApplicationService.register(app1); planetApplicationService.register(app2); // 创建宿主容器 const hostContainer = document.createElement('DIV'); hostContainer.classList.add('host-selector'); document.body.appendChild(hostContainer); }); afterEach(() => { clearGlobalPlanet(); planetApplicationLoader['destroyApp'](app1); planetApplicationLoader['destroyApp'](app2); }); it(`should throw error for PlanetApplicationLoader guard when has multiple instances`, () => { expect(() => { return new PlanetApplicationLoader( TestBed.inject(AssetsLoader), TestBed.inject(PlanetApplicationService), TestBed.inject(NgZone), TestBed.inject(Router), TestBed.inject(Injector), TestBed.inject(ApplicationRef) ); }).toThrowError('PlanetApplicationLoader has been injected in the portal, repeated injection is not allowed'); }); it(`should load (load assets and bootstrap) app1 success for legacy selector`, fakeAsync(() => { const loadAppAssets$ = new Subject<[AssetsLoadResult[], AssetsLoadResult[]]>(); const assetsLoaderSpy = spyOn(assetsLoader, 'loadAppAssets'); assetsLoaderSpy.and.returnValue(loadAppAssets$); const app1RefFaker = PlanetApplicationRefFaker.create(app1.name); // App state change const appStatusChangeFaker = AppStatusChangeFaker.create(planetApplicationLoader); // Apps loading start const appsLoadingStartSpy = jasmine.createSpy('apps loading start spy'); planetApplicationLoader.appsLoadingStart.subscribe(appsLoadingStartSpy); expect(appsLoadingStartSpy).not.toHaveBeenCalled(); planetApplicationLoader.reroute({ url: '/app1/dashboard' }); appStatusChangeFaker.expectHaveBeenCalledWith({ app: app1, status: ApplicationStatus.assetsLoading }); expect(appsLoadingStartSpy).toHaveBeenCalled(); expect(appsLoadingStartSpy).toHaveBeenCalledWith({ shouldLoadApps: [app1], shouldUnloadApps: [] }); loadAppAssets$.next(); loadAppAssets$.complete(); expect(appStatusChangeFaker.spy).toHaveBeenCalledTimes(2); expect(appStatusChangeFaker.spy).toHaveBeenCalledWith({ app: app1, status: ApplicationStatus.assetsLoaded }); appStatusChangeFaker.expectFromAssetsLoadedToActive(2, app1RefFaker, app1); // 判断是否在宿主元素中创建了应用根节点 expectApp1Element(); tick(); })); it(`should load (load assets and bootstrap) app1 success use template`, fakeAsync(() => { const loadAppAssets$ = new Subject<[AssetsLoadResult[], AssetsLoadResult[]]>(); const assetsLoaderSpy = spyOn(assetsLoader, 'loadAppAssets'); assetsLoaderSpy.and.returnValue(loadAppAssets$); const app1RefFaker = PlanetApplicationRefFaker.create(app1.name, { template: `<app1-root class="app1-root"></app1-root>`, bootstrap: null }); // App state change const appStatusChangeFaker = AppStatusChangeFaker.create(planetApplicationLoader); // Apps loading start const appsLoadingStartSpy = jasmine.createSpy('apps loading start spy'); planetApplicationLoader.appsLoadingStart.subscribe(appsLoadingStartSpy); planetApplicationLoader.reroute({ url: '/app1/dashboard' }); loadAppAssets$.next(); loadAppAssets$.complete(); appStatusChangeFaker.expectFromAssetsLoadedToActive(2, app1RefFaker, app1); // 判断是否在宿主元素中创建了应用根节点 expectApp1Element(`app1-root app1-host app1-prefix`); tick(); })); it(`should load empty apps when route navigate to '/app-not-found/dashboard'`, fakeAsync(() => { const loadAppAssets$ = new Subject<[AssetsLoadResult[], AssetsLoadResult[]]>(); const assetsLoaderSpy = spyOn(assetsLoader, 'loadAppAssets'); assetsLoaderSpy.and.returnValue(loadAppAssets$); // Apps loading start const appsLoadingStartSpy = jasmine.createSpy('apps loading start spy'); planetApplicationLoader.appsLoadingStart.subscribe(appsLoadingStartSpy); planetApplicationLoader.reroute({ url: '/app-not-found/dashboard' }); expect(appsLoadingStartSpy).toHaveBeenCalledTimes(1); expect(appsLoadingStartSpy).toHaveBeenCalledWith({ shouldLoadApps: [], shouldUnloadApps: [] }); expect(planetApplicationLoader.loadingDone).toEqual(true); loadAppAssets$.next(); loadAppAssets$.complete(); expect(planetApplicationLoader.loadingDone).toEqual(true); expect(appsLoadingStartSpy).toHaveBeenCalledTimes(1); flush(); })); it(`should not update loadingDone to false when app1 url navigate and app1 has been active`, fakeAsync(() => { const loadAppAssets$ = new Subject<[AssetsLoadResult[], AssetsLoadResult[]]>(); const assetsLoaderSpy = spyOn(assetsLoader, 'loadAppAssets'); assetsLoaderSpy.and.returnValue(loadAppAssets$); const appStatusChangeFaker = AppStatusChangeFaker.create(planetApplicationLoader); const app1RefFaker = PlanetApplicationRefFaker.create(app1.name); planetApplicationLoader.reroute({ url: '/app1/dashboard' }); loadAppAssets$.next(); loadAppAssets$.complete(); flush(); app1RefFaker.haveBeenBootstrap(); app1RefFaker.bootstrap(); expect(appStatusChangeFaker.spy).toHaveBeenCalledTimes(5); expect(app1RefFaker.navigateByUrlSpy).not.toHaveBeenCalled(); planetApplicationLoader.reroute({ url: '/app1/dashboard2' }); // app1 has been loaded expect(planetApplicationLoader.loadingDone).toEqual(true); flush(); // app2 has been not loaded planetApplicationLoader.reroute({ url: '/app2/dashboard1' }); expect(planetApplicationLoader.loadingDone).toEqual(false); flush(); })); it(`should not bootstrap app1 when app1 is active`, fakeAsync(() => { const loadAppAssets$ = new Subject<[AssetsLoadResult[], AssetsLoadResult[]]>(); const assetsLoaderSpy = spyOn(assetsLoader, 'loadAppAssets'); assetsLoaderSpy.and.returnValue(loadAppAssets$); const appStatusChangeFaker = AppStatusChangeFaker.create(planetApplicationLoader); const app1RefFaker = PlanetApplicationRefFaker.create(app1.name); planetApplicationLoader.reroute({ url: '/app1/dashboard' }); loadAppAssets$.next(); loadAppAssets$.complete(); flush(); app1RefFaker.haveBeenBootstrap(); app1RefFaker.bootstrap(); // 判断是否在宿主元素中创建了应用根节点 expectApp1Element(); expect(appStatusChangeFaker.spy).toHaveBeenCalledTimes(5); planetApplicationLoader.reroute({ url: '/app1/dashboard2' }); flush(); expect(app1RefFaker.bootstrapSpy).toHaveBeenCalledTimes(1); expect(appStatusChangeFaker.spy).toHaveBeenCalledTimes(5); tick(); expect(app1RefFaker.bootstrapSpy).toHaveBeenCalledTimes(1); expect(appStatusChangeFaker.spy).toHaveBeenCalledTimes(5); })); it(`should call app1 navigateByUrl when app1 is active`, fakeAsync(() => { const loadAppAssets$ = new Subject<[AssetsLoadResult[], AssetsLoadResult[]]>(); const assetsLoaderSpy = spyOn(assetsLoader, 'loadAppAssets'); assetsLoaderSpy.and.returnValue(loadAppAssets$); const appStatusChangeFaker = AppStatusChangeFaker.create(planetApplicationLoader); const app1RefFaker = PlanetApplicationRefFaker.create(app1.name); planetApplicationLoader.reroute({ url: '/app1/dashboard' }); loadAppAssets$.next(); loadAppAssets$.complete(); flush(); app1RefFaker.haveBeenBootstrap(); app1RefFaker.bootstrap(); expect(appStatusChangeFaker.spy).toHaveBeenCalledTimes(5); expect(app1RefFaker.navigateByUrlSpy).not.toHaveBeenCalled(); planetApplicationLoader.reroute({ url: '/app1/dashboard2' }); flush(); expect(app1RefFaker.navigateByUrlSpy).toHaveBeenCalledTimes(1); expect(app1RefFaker.navigateByUrlSpy).toHaveBeenCalledWith('/app1/dashboard2'); })); it(`should hide app1 success when app1 is not match and switch mode is default`, fakeAsync(() => { const loadAppAssets$ = new Subject<[AssetsLoadResult[], AssetsLoadResult[]]>(); const assetsLoaderSpy = spyOn(assetsLoader, 'loadAppAssets'); assetsLoaderSpy.and.returnValue(loadAppAssets$); const app1RefFaker = PlanetApplicationRefFaker.create(app1.name); // App state change const appStatusChangeFaker = AppStatusChangeFaker.create(planetApplicationLoader); // Apps loading start const appsLoadingStartSpy = jasmine.createSpy('apps loading start spy'); planetApplicationLoader.appsLoadingStart.subscribe(appsLoadingStartSpy); expect(appsLoadingStartSpy).not.toHaveBeenCalled(); planetApplicationLoader.reroute({ url: '/app1/dashboard' }); loadAppAssets$.next(); loadAppAssets$.complete(); expect(appStatusChangeFaker.spy).toHaveBeenCalledTimes(2); expect(appStatusChangeFaker.spy).toHaveBeenCalledWith({ app: app1, status: ApplicationStatus.assetsLoaded }); appStatusChangeFaker.expectFromAssetsLoadedToActive(2, app1RefFaker, app1); tick(); const app1Host = document.querySelector(app1.selector); planetApplicationLoader.reroute({ url: '/app2/dashboard' }); expect(app1Host.getAttribute('style')).toContain('display:none;'); expect(appStatusChangeFaker.spy).toHaveBeenCalledTimes(7); tick(); // restore status to assetsLoaded when switch mode is default appStatusChangeFaker.expectAppStatus(app1.name, ApplicationStatus.assetsLoaded); expect(document.querySelector(app1.selector)).toBeFalsy(); })); it(`should destroy app1 success when app1 is not match and switch mode is coexist`, fakeAsync(() => { const loadAppAssets$ = new Subject<[AssetsLoadResult[], AssetsLoadResult[]]>(); const assetsLoaderSpy = spyOn(assetsLoader, 'loadAppAssets'); assetsLoaderSpy.and.returnValue(loadAppAssets$); app1.switchMode = SwitchModes.coexist; const app1RefFaker = PlanetApplicationRefFaker.create(app1.name); // App state change const appStatusChangeFaker = AppStatusChangeFaker.create(planetApplicationLoader); // Apps loading start const appsLoadingStartSpy = jasmine.createSpy('apps loading start spy'); planetApplicationLoader.appsLoadingStart.subscribe(appsLoadingStartSpy); expect(appsLoadingStartSpy).not.toHaveBeenCalled(); planetApplicationLoader.reroute({ url: '/app1/dashboard' }); loadAppAssets$.next(); loadAppAssets$.complete(); appStatusChangeFaker.expectFromAssetsLoadedToActive(2, app1RefFaker, app1); tick(); const app1Host = document.querySelector(app1.selector); planetApplicationLoader.reroute({ url: '/app2/dashboard' }); expect(app1Host.getAttribute('style')).toContain('display:none;'); expect(appStatusChangeFaker.spy).toHaveBeenCalledTimes(7); tick(); // restore status to bootstrapped when switch mode is coexist appStatusChangeFaker.expectAppStatus(app1.name, ApplicationStatus.bootstrapped); app1.switchMode = SwitchModes.default; expect(document.querySelector(app1.selector)).toBeTruthy(); })); it(`should not call app1 navigateByUrl when app1 is active and url is same`, fakeAsync(() => { const loadAppAssets$ = new Subject<[AssetsLoadResult[], AssetsLoadResult[]]>(); const assetsLoaderSpy = spyOn(assetsLoader, 'loadAppAssets'); assetsLoaderSpy.and.returnValue(loadAppAssets$); const appStatusChangeFaker = AppStatusChangeFaker.create(planetApplicationLoader); const app1RefFaker = PlanetApplicationRefFaker.create(app1.name); planetApplicationLoader.reroute({ url: '/app1/dashboard' }); loadAppAssets$.next(); loadAppAssets$.complete(); flush(); app1RefFaker.haveBeenBootstrap(); app1RefFaker.bootstrap(); expect(appStatusChangeFaker.spy).toHaveBeenCalledTimes(5); expect(app1RefFaker.navigateByUrlSpy).not.toHaveBeenCalled(); app1RefFaker.getCurrentRouterStateUrlSpy.and.returnValue('/app1/dashboard2'); planetApplicationLoader.reroute({ url: '/app1/dashboard2' }); flush(); expect(app1RefFaker.navigateByUrlSpy).not.toHaveBeenCalled(); tick(); })); it(`should start load app1 once when reroute same url: /app1/dashboard`, fakeAsync(() => { const loadAppAssets$ = new Subject<[AssetsLoadResult[], AssetsLoadResult[]]>(); const assetsLoaderSpy = spyOn(assetsLoader, 'loadAppAssets'); assetsLoaderSpy.and.returnValue(loadAppAssets$); // Apps loading start const appsLoadingStartSpy = jasmine.createSpy('apps loading start spy'); planetApplicationLoader.appsLoadingStart.subscribe(appsLoadingStartSpy); expect(appsLoadingStartSpy).not.toHaveBeenCalled(); planetApplicationLoader.reroute({ url: '/app1/dashboard' }); expect(appsLoadingStartSpy).toHaveBeenCalledTimes(1); expect(appsLoadingStartSpy).toHaveBeenCalled(); expect(appsLoadingStartSpy).toHaveBeenCalledWith({ shouldLoadApps: [app1], shouldUnloadApps: [] }); planetApplicationLoader.reroute({ url: '/app1/dashboard' }); expect(appsLoadingStartSpy).toHaveBeenCalledTimes(1); tick(); })); it(`should cancel load app1 which assets has not loaded when next route (app2) change`, fakeAsync(() => { const loadApp1Assets$ = new Subject<[AssetsLoadResult[], AssetsLoadResult[]]>(); const loadApp2Assets$ = new Subject<[AssetsLoadResult[], AssetsLoadResult[]]>(); const app1RefFaker = PlanetApplicationRefFaker.create(app1.name); const app2RefFaker = PlanetApplicationRefFaker.create(app2.name); const assetsLoaderSpy = spyOn(assetsLoader, 'loadAppAssets'); assetsLoaderSpy.and.returnValues(loadApp1Assets$, loadApp2Assets$); const appStatusChangeFaker = AppStatusChangeFaker.create(planetApplicationLoader); expect(appStatusChangeFaker.spy).not.toHaveBeenCalled(); planetApplicationLoader.reroute({ url: '/app1' }); expect(appStatusChangeFaker.spy).toHaveBeenCalled(); expect(appStatusChangeFaker.spy).toHaveBeenCalledWith({ app: app1, status: ApplicationStatus.assetsLoading }); planetApplicationLoader.reroute({ url: '/app2' }); expect(appStatusChangeFaker.spy).toHaveBeenCalledTimes(2); expect(appStatusChangeFaker.spy).toHaveBeenCalledWith({ app: app2, status: ApplicationStatus.assetsLoading }); loadApp1Assets$.next(); loadApp1Assets$.complete(); expect(appStatusChangeFaker.spy).toHaveBeenCalledTimes(2); loadApp2Assets$.next(); loadApp2Assets$.complete(); expect(appStatusChangeFaker.spy).toHaveBeenCalledTimes(3); expect(appStatusChangeFaker.spy).toHaveBeenCalledWith({ app: app2, status: ApplicationStatus.assetsLoaded }); appStatusChangeFaker.expectFromAssetsLoadedToActive(3, app2RefFaker, app2); app1RefFaker.haveNotBeenBootstrap(); app2RefFaker.haveBeenBootstrap(); tick(); })); it(`should cancel load app1 which has not bootstrapped when next route (app2) change`, fakeAsync(() => { const loadApp1Assets$ = new Subject<[AssetsLoadResult[], AssetsLoadResult[]]>(); const loadApp2Assets$ = new Subject<[AssetsLoadResult[], AssetsLoadResult[]]>(); const app1RefFaker = PlanetApplicationRefFaker.create(app1.name); const app2RefFaker = PlanetApplicationRefFaker.create(app2.name); const assetsLoaderSpy = spyOn(assetsLoader, 'loadAppAssets'); assetsLoaderSpy.and.returnValues(loadApp1Assets$, loadApp2Assets$); const appStatusChangeFaker = AppStatusChangeFaker.create(planetApplicationLoader); expect(appStatusChangeFaker.spy).not.toHaveBeenCalled(); planetApplicationLoader.reroute({ url: '/app1' }); expect(appStatusChangeFaker.spy).toHaveBeenCalled(); expect(appStatusChangeFaker.spy).toHaveBeenCalledWith({ app: app1, status: ApplicationStatus.assetsLoading }); loadApp1Assets$.next(); loadApp1Assets$.complete(); expect(appStatusChangeFaker.spy).toHaveBeenCalledTimes(2); expect(appStatusChangeFaker.spy).toHaveBeenCalledWith({ app: app1, status: ApplicationStatus.assetsLoaded }); planetApplicationLoader.reroute({ url: '/app2' }); expect(appStatusChangeFaker.spy).toHaveBeenCalledTimes(3); expect(appStatusChangeFaker.spy).toHaveBeenCalledWith({ app: app2, status: ApplicationStatus.assetsLoading }); loadApp2Assets$.next(); loadApp2Assets$.complete(); expect(appStatusChangeFaker.spy).toHaveBeenCalledTimes(4); expect(appStatusChangeFaker.spy).toHaveBeenCalledWith({ app: app2, status: ApplicationStatus.assetsLoaded }); appStatusChangeFaker.expectFromAssetsLoadedToActive(4, app2RefFaker, app2); app1RefFaker.haveNotBeenBootstrap(); app2RefFaker.haveBeenBootstrap(); tick(); })); it(`should reload sub app when sub app is bootstrapped`, fakeAsync(() => { const loadAppAssets$ = new Subject<[AssetsLoadResult[], AssetsLoadResult[]]>(); const appRefFaker = PlanetApplicationRefFaker.create(app2.name); const assetsLoaderSpy = spyOn(assetsLoader, 'loadAppAssets'); assetsLoaderSpy.and.returnValues(loadAppAssets$); const appStatusChangeFaker = AppStatusChangeFaker.create(planetApplicationLoader); planetApplicationLoader.reroute({ url: '/app2' }); loadAppAssets$.next(); loadAppAssets$.complete(); appStatusChangeFaker.expectFromAssetsLoadedToActive(2, appRefFaker, app2); tick(); appStatusChangeFaker.expectAppStatus(app2.name, ApplicationStatus.active); planetApplicationLoader.reroute({ url: '/dashboard' }); tick(); appStatusChangeFaker.expectAppStatus(app2.name, ApplicationStatus.bootstrapped); planetApplicationLoader.reroute({ url: '/app2' }); tick(); appStatusChangeFaker.expectAppStatus(app2.name, ApplicationStatus.active); })); it(`should load next app(app2) when last app(app1) load error`, fakeAsync(() => { const loadApp1Assets$ = new Subject<[AssetsLoadResult[], AssetsLoadResult[]]>(); const loadApp2Assets$ = new Subject<[AssetsLoadResult[], AssetsLoadResult[]]>(); const errorHandlerSpy = jasmine.createSpy(`error handler spy`); planetApplicationLoader.setOptions({ errorHandler: errorHandlerSpy }); const app1RefFaker = PlanetApplicationRefFaker.create(app1.name); const app2RefFaker = PlanetApplicationRefFaker.create(app2.name); const assetsLoaderSpy = spyOn(assetsLoader, 'loadAppAssets'); assetsLoaderSpy.and.returnValues(loadApp1Assets$, loadApp2Assets$); const appStatusChangeSpy = jasmine.createSpy('app status change spy'); planetApplicationLoader.appStatusChange.subscribe(appStatusChangeSpy); expect(appStatusChangeSpy).not.toHaveBeenCalled(); planetApplicationLoader.reroute({ url: '/app1' }); expect(appStatusChangeSpy).toHaveBeenCalled(); expect(appStatusChangeSpy).toHaveBeenCalledWith({ app: app1, status: ApplicationStatus.assetsLoading }); expect(errorHandlerSpy).not.toHaveBeenCalled(); // Load Error loadApp1Assets$.error(new Error(`load app1 assets error`)); loadApp1Assets$.complete(); expect(errorHandlerSpy).toHaveBeenCalled(); expect(errorHandlerSpy).toHaveBeenCalledWith(new Error(`load app1 assets error`)); planetApplicationLoader.reroute({ url: '/app2' }); expect(appStatusChangeSpy).toHaveBeenCalledTimes(3); expect(appStatusChangeSpy).toHaveBeenCalledWith({ app: app2, status: ApplicationStatus.assetsLoading }); loadApp2Assets$.next(); loadApp2Assets$.complete(); expect(appStatusChangeSpy).toHaveBeenCalledTimes(4); expect(appStatusChangeSpy).toHaveBeenCalledWith({ app: app2, status: ApplicationStatus.assetsLoaded }); flush(); app2RefFaker.bootstrap(); expect(appStatusChangeSpy).toHaveBeenCalledTimes(7); expect(appStatusChangeSpy).toHaveBeenCalledWith({ app: app2, status: ApplicationStatus.bootstrapping }); expect(appStatusChangeSpy).toHaveBeenCalledWith({ app: app2, status: ApplicationStatus.bootstrapped }); expect(appStatusChangeSpy).toHaveBeenCalledWith({ app: app2, status: ApplicationStatus.active }); app1RefFaker.haveNotBeenBootstrap(); app2RefFaker.haveBeenBootstrap(); // 判断是否在宿主元素中创建了应用根节点 expectApp2Element(); tick(); })); it(`should reload app(app1) when before app(app1) load error`, fakeAsync(() => { const loadApp1Assets$ = new Subject<[AssetsLoadResult[], AssetsLoadResult[]]>(); const loadApp1AginAssets$ = new Subject<[AssetsLoadResult[], AssetsLoadResult[]]>(); const errorHandlerSpy = jasmine.createSpy(`error handler spy`); planetApplicationLoader.setOptions({ errorHandler: errorHandlerSpy }); const app1RefFaker = PlanetApplicationRefFaker.create(app1.name); const assetsLoaderSpy = spyOn(assetsLoader, 'loadAppAssets'); assetsLoaderSpy.and.returnValues(loadApp1Assets$, loadApp1AginAssets$); const appStatusChangeFaker = AppStatusChangeFaker.create(planetApplicationLoader); expect(appStatusChangeFaker.spy).not.toHaveBeenCalled(); planetApplicationLoader.reroute({ url: '/app1' }); expect(appStatusChangeFaker.spy).toHaveBeenCalled(); expect(appStatusChangeFaker.spy).toHaveBeenCalledWith({ app: app1, status: ApplicationStatus.assetsLoading }); expect(errorHandlerSpy).not.toHaveBeenCalled(); // Load Error loadApp1Assets$.error(new Error(`load app1 assets error`)); loadApp1Assets$.complete(); expect(errorHandlerSpy).toHaveBeenCalled(); expect(errorHandlerSpy).toHaveBeenCalledWith(new Error(`load app1 assets error`)); expect(appStatusChangeFaker.spy).toHaveBeenCalledTimes(2); expect(appStatusChangeFaker.spy).toHaveBeenCalledWith({ app: app1, status: ApplicationStatus.loadError }); planetApplicationLoader.reroute({ url: '/app1/hello' }); expect(appStatusChangeFaker.spy).toHaveBeenCalledTimes(3); expect(appStatusChangeFaker.spy).toHaveBeenCalledWith({ app: app1, status: ApplicationStatus.assetsLoading }); loadApp1AginAssets$.next(); loadApp1AginAssets$.complete(); expect(appStatusChangeFaker.spy).toHaveBeenCalledTimes(4); expect(appStatusChangeFaker.spy).toHaveBeenCalledWith({ app: app1, status: ApplicationStatus.assetsLoaded }); appStatusChangeFaker.expectFromAssetsLoadedToActive(4, app1RefFaker, app1); app1RefFaker.haveBeenBootstrap(); // 判断是否在宿主元素中创建了应用根节点 expectApp1Element(); tick(); })); it(`should throw specify error when sub app not found in bootstrapApp`, () => { const appNotFound = 'app100'; expect(() => { planetApplicationLoader['bootstrapApp']({ name: appNotFound, routerPathPrefix: 'app100', hostParent: '' }); }).toThrowError( `[${appNotFound}] not found, make sure that the app has the correct name defined use defineApplication(${appNotFound}) and runtimeChunk and vendorChunk are set to true, details see https://github.com/worktile/ngx-planet#throw-error-cannot-read-property-call-of-undefined-at-__webpack_require__-bootstrap79` ); }); describe('error handler', () => { it(`default error handler`, () => { const loadAppAssets$ = new Subject<[AssetsLoadResult[], AssetsLoadResult[]]>(); const assetsLoaderSpy = spyOn(assetsLoader, 'loadAppAssets'); assetsLoaderSpy.and.returnValue(loadAppAssets$); planetApplicationLoader.reroute({ url: '/app1/dashboard' }); loadAppAssets$.error('load app assets error'); }); it(`custom error handler`, () => { const loadAppAssets$ = new Subject<[AssetsLoadResult[], AssetsLoadResult[]]>(); const assetsLoaderSpy = spyOn(assetsLoader, 'loadAppAssets'); assetsLoaderSpy.and.returnValue(loadAppAssets$); planetApplicationLoader.reroute({ url: '/app1/dashboard' }); const errorHandlerSpy = jasmine.createSpy(`error handler spy`); planetApplicationLoader.setOptions({ errorHandler: errorHandlerSpy }); const error = new Error(`load app assets error`); loadAppAssets$.error(error); loadAppAssets$.complete(); expect(errorHandlerSpy).toHaveBeenCalled(); expect(errorHandlerSpy).toHaveBeenCalledWith(error); }); }); describe('switchModeIsCoexist', () => { it('default switchModeIsCoexist = false', () => { const result = planetApplicationLoader['switchModeIsCoexist'](undefined); expect(result).toEqual(false); }); it('default switchModeIsCoexist = true', () => { const result = planetApplicationLoader['switchModeIsCoexist']({ name: 'app100', switchMode: SwitchModes.coexist, routerPathPrefix: '', hostParent: undefined }); expect(result).toEqual(true); }); it('default switchModeIsCoexist = true', () => { planetApplicationLoader.setOptions({ switchMode: SwitchModes.coexist }); const result = planetApplicationLoader['switchModeIsCoexist'](undefined); expect(result).toEqual(true); }); }); describe('preload', () => { it(`should auto preload load app2 when after loaded app1`, fakeAsync(() => { const newApp2 = { ...app2, preload: true }; planetApplicationService.unregister(app2.name); planetApplicationService.register(newApp2); const loadApp1Assets$ = new Subject<[AssetsLoadResult[], AssetsLoadResult[]]>(); const loadApp2Assets$ = new Subject<[AssetsLoadResult[], AssetsLoadResult[]]>(); const app1RefFaker = PlanetApplicationRefFaker.create(app1.name); const app2RefFaker = PlanetApplicationRefFaker.create(newApp2.name); const assetsLoaderSpy = spyOn(assetsLoader, 'loadAppAssets'); assetsLoaderSpy.and.returnValues(loadApp1Assets$, loadApp2Assets$); const appStatusChangeFaker = AppStatusChangeFaker.create(planetApplicationLoader); expect(appStatusChangeFaker.spy).not.toHaveBeenCalled(); planetApplicationLoader.reroute({ url: '/app1' }); // Start load app1 assets expect(appStatusChangeFaker.spy).toHaveBeenCalledTimes(1); expect(appStatusChangeFaker.spy).toHaveBeenCalledWith({ app: app1, status: ApplicationStatus.assetsLoading }); loadApp1Assets$.next(); loadApp1Assets$.complete(); // App1 assets loaded expect(appStatusChangeFaker.spy).toHaveBeenCalledTimes(2); expect(appStatusChangeFaker.spy).toHaveBeenCalledWith({ app: app1, status: ApplicationStatus.assetsLoaded }); // bootstrap app1 in setTimeout flush(); // Start bootstrap app1 expect(appStatusChangeFaker.spy).toHaveBeenCalledTimes(3); expect(appStatusChangeFaker.spy).toHaveBeenCalledWith({ app: app1, status: ApplicationStatus.bootstrapping }); expect(planetApplicationLoader.loadingDone).toBe(false); // App1 Ref Faker spy bootstrap app1RefFaker.bootstrap(); // App1 bootstrapped expect(planetApplicationLoader.loadingDone).toBe(true); expect(appStatusChangeFaker.spy).toHaveBeenCalledTimes(5); expect(appStatusChangeFaker.spy).toHaveBeenCalledWith({ app: app1, status: ApplicationStatus.bootstrapped }); expect(appStatusChangeFaker.spy).toHaveBeenCalledWith({ app: app1, status: ApplicationStatus.active }); app2RefFaker.haveNotBeenBootstrap(); // Preload app2 in setTimeout tick(); // 已经开始加载 App2 静态资源 expect(appStatusChangeFaker.spy).toHaveBeenCalledTimes(6); expect(appStatusChangeFaker.spy).toHaveBeenCalledWith({ app: newApp2, status: ApplicationStatus.assetsLoading }); // App2 静态资源加载完毕 loadApp2Assets$.next(); loadApp2Assets$.complete(); // App2 's assets loaded and bootstrapped expect(appStatusChangeFaker.spy).toHaveBeenCalledTimes(8); expect(appStatusChangeFaker.spy).toHaveBeenCalledWith({ app: newApp2, status: ApplicationStatus.assetsLoaded }); expect(appStatusChangeFaker.spy).toHaveBeenCalledWith({ app: newApp2, status: ApplicationStatus.bootstrapping }); // App2 bootstrapped app2RefFaker.bootstrap(); expect(appStatusChangeFaker.spy).toHaveBeenCalledTimes(9); expect(appStatusChangeFaker.spy).toHaveBeenCalledWith({ app: newApp2, status: ApplicationStatus.bootstrapped }); tick(); })); it(`should active app1 success when app1 is bootstrapping by preload`, fakeAsync(() => { const newApp1 = { ...app1, preload: true }; planetApplicationService.unregister(app1.name); planetApplicationService.register(newApp1); const loadApp1Assets$ = new Subject<[AssetsLoadResult[], AssetsLoadResult[]]>(); const loadApp2Assets$ = new Subject<[AssetsLoadResult[], AssetsLoadResult[]]>(); const app1RefFaker = PlanetApplicationRefFaker.create(app1.name); const assetsLoaderSpy = spyOn(assetsLoader, 'loadAppAssets'); assetsLoaderSpy.and.returnValues(loadApp1Assets$, loadApp2Assets$); const appStatusChangeFaker = AppStatusChangeFaker.create(planetApplicationLoader); expect(appStatusChangeFaker.spy).not.toHaveBeenCalled(); planetApplicationLoader.reroute({ url: '/dashboard' }); flush(); loadApp1Assets$.next(); loadApp1Assets$.complete(); planetApplicationLoader.reroute({ url: '/app1' }); flush(); // 测试在 app1 被预加载处于 bootstrapping 状态,然后路由跳转加载 app1 订阅 bootstrapped 事件后激活应用 app1RefFaker.bootstrap(); appStatusChangeFaker.expectAppStatus('app1', ApplicationStatus.active); })); it(`should active app1 success when app1 is bootstrapping by preload and bootstrapped in setTimeout`, fakeAsync(() => { const newApp1 = { ...app1, preload: true }; planetApplicationService.unregister(app1.name); planetApplicationService.register(newApp1); const loadApp1Assets$ = new Subject<[AssetsLoadResult[], AssetsLoadResult[]]>(); const loadApp2Assets$ = new Subject<[AssetsLoadResult[], AssetsLoadResult[]]>(); const app1RefFaker = PlanetApplicationRefFaker.create(app1.name); const assetsLoaderSpy = spyOn(assetsLoader, 'loadAppAssets'); assetsLoaderSpy.and.returnValues(loadApp1Assets$, loadApp2Assets$); const appStatusChangeFaker = AppStatusChangeFaker.create(planetApplicationLoader); expect(appStatusChangeFaker.spy).not.toHaveBeenCalled(); planetApplicationLoader.reroute({ url: '/dashboard' }); flush(); loadApp1Assets$.next(); loadApp1Assets$.complete(); planetApplicationLoader.reroute({ url: '/app1' }); // It must be bootstrap first and then flush (setTimeout) // Because app1 may be bootstrapping before setTimeout // But app1 is bootstrapped after setTimeout, expect to load success in this case // 先启用,后 flush,测试在 flush 之前应用是 bootstrapping 状态,但是 flush 之后是 bootstrapped 状态的场景 app1RefFaker.bootstrap(); // start forkJoin(apps$) in setTimeout flush(); appStatusChangeFaker.expectAppStatus('app1', ApplicationStatus.active); })); it('should preload app when status is in assetsLoading, assetsLoaded or bootstrapping', fakeAsync(() => { [ApplicationStatus.assetsLoading, ApplicationStatus.assetsLoaded, ApplicationStatus.bootstrapping].forEach( status => { const preloadAppSpy = jasmine.createSpy('preload app spy'); planetApplicationLoader['setAppStatus'](app1, status); const appRefFaker = PlanetApplicationRefFaker.create(app1.name); planetApplicationLoader.preload(app1).subscribe(data => { // expect(NgZone.isInAngularZone()).toEqual(true); preloadAppSpy(data); }); expect(preloadAppSpy).not.toHaveBeenCalled(); planetApplicationLoader['setAppStatus'](app1, ApplicationStatus.bootstrapped); expect(preloadAppSpy).toHaveBeenCalled(); expect(preloadAppSpy).toHaveBeenCalledWith(appRefFaker.planetAppRef); expect(NgZone.isInAngularZone()).toEqual(false); } ); })); it('should preload app when status is empty or error', fakeAsync(() => { const status = sample([ApplicationStatus.loadError, undefined]); const loadAppAssets$ = new Subject<[AssetsLoadResult[], AssetsLoadResult[]]>(); const assetsLoaderSpy = spyOn(assetsLoader, 'loadAppAssets'); assetsLoaderSpy.and.returnValues(loadAppAssets$); const appRefFaker = PlanetApplicationRefFaker.create(app1.name); const preloadAppSpy = jasmine.createSpy('preload app spy'); planetApplicationLoader['setAppStatus'](app1, status); planetApplicationLoader.preload(app1, true).subscribe(data => { // expect(NgZone.isInAngularZone()).toEqual(true); preloadAppSpy(data); }); expect(preloadAppSpy).not.toHaveBeenCalled(); loadAppAssets$.next(); loadAppAssets$.complete(); ngZone.run(() => { appRefFaker.bootstrap(); }); expect(preloadAppSpy).toHaveBeenCalled(); expect(preloadAppSpy).toHaveBeenCalledWith(appRefFaker.planetAppRef); expect(NgZone.isInAngularZone()).toEqual(false); })); it(`should throw error when preload load app2 error`, fakeAsync(() => { const newApp2 = { ...app2, preload: true }; planetApplicationService.unregister(app2.name); planetApplicationService.register(newApp2); const loadApp1Assets$ = new Subject<[AssetsLoadResult[], AssetsLoadResult[]]>(); const loadApp2Assets$ = new Subject<[AssetsLoadResult[], AssetsLoadResult[]]>(); const errorHandlerSpy = jasmine.createSpy(`error handler spy`); planetApplicationLoader.setOptions({ errorHandler: errorHandlerSpy }); const app1RefFaker = PlanetApplicationRefFaker.create(app1.name); const app2RefFaker = PlanetApplicationRefFaker.create(newApp2.name); const assetsLoaderSpy = spyOn(assetsLoader, 'loadAppAssets'); assetsLoaderSpy.and.returnValues(loadApp1Assets$, loadApp2Assets$); const appStatusChangeSpy = jasmine.createSpy('app status change spy'); planetApplicationLoader.appStatusChange.subscribe(appStatusChangeSpy); expect(appStatusChangeSpy).not.toHaveBeenCalled(); planetApplicationLoader.reroute({ url: '/app1' }); expect(appStatusChangeSpy).toHaveBeenCalledTimes(1); expect(appStatusChangeSpy).toHaveBeenCalledWith({ app: app1, status: ApplicationStatus.assetsLoading }); loadApp1Assets$.next(); loadApp1Assets$.complete(); expect(appStatusChangeSpy).toHaveBeenCalledTimes(2); expect(appStatusChangeSpy).toHaveBeenCalledWith({ app: app1, status: ApplicationStatus.assetsLoaded }); app1RefFaker.haveNotBeenBootstrap(); flush(); expect(appStatusChangeSpy).toHaveBeenCalledTimes(3); expect(appStatusChangeSpy).toHaveBeenCalledWith({ app: app1, status: ApplicationStatus.bootstrapping }); app1RefFaker.bootstrap(); app1RefFaker.haveBeenBootstrap(); expect(appStatusChangeSpy).toHaveBeenCalledTimes(5); expect(appStatusChangeSpy).toHaveBeenCalledWith({ app: app1, status: ApplicationStatus.bootstrapped }); expect(appStatusChangeSpy).toHaveBeenCalledWith({ app: app1, status: ApplicationStatus.active }); flush(); loadApp2Assets$.error(new Error(`load newApp2 assets error`)); loadApp2Assets$.complete(); expect(errorHandlerSpy).toHaveBeenCalled(); expect(errorHandlerSpy).toHaveBeenCalledWith(new Error(`load newApp2 assets error`)); })); }); });
the_stack
import { createTxInput, execute, executeWithTxInput } from "../script/adapter"; import {BigNumber} from "bignumber.js"; import { ADD, ADDMOD, ADDRESS, AND, BALANCE, BIN_OUTPUT_PATH, BLOCKHASH, BYTE, CALLDATACOPY, CALLDATALOAD, CALLDATASIZE, CALLER, CALLVALUE, CODECOPY, CODESIZE, COINBASE, CONTRACT_TEST_SIG, CREATE, DEFAULT_CALLER, DEFAULT_CONTRACT_ADDRESS, DIFFICULTY, DIV, DUP1, DUP16, DUP3, EQ, ERROR_INVALID_JUMP_DESTINATION, ERROR_INVALID_OPCODE, ERROR_STACK_UNDERFLOW, ERROR_STATE_REVERTED, EVM_EXECUTE_SIG, EXP, GAS, GASLIMIT, GASPRICE, GT, ISZERO, JUMP, JUMPDEST, JUMPI, LT, MLOAD, MOD, MSIZE, MSTORE, MSTORE8, MUL, MULMOD, NO_ERROR, NOT, NUMBER, OR, PC, POP, PUSH1, PUSH2, PUSH20, PUSH29, PUSH32, PUSH4, PUSH5, RETURN, REVERT, ROOT_PATH, SDIV, SGT, SHA3, SLOAD, SLT, SMOD, SOL_ETH_SRC, SRC_PATH, SSTORE, STATICCALL, STOP, SUB, SWAP1, SWAP10, SWAP11, SWAP12, SWAP13, SWAP14, SWAP15, SWAP16, SWAP2, SWAP3, SWAP4, SWAP5, SWAP6, SWAP7, SWAP8, SWAP9, TIMESTAMP, XOR } from "../script/constants"; import {compile} from "../script/solc"; import path = require("path"); import {readText} from "../script/io"; beforeAll(async () => { console.log("Compiling contracts."); await compile(SOL_ETH_SRC, BIN_OUTPUT_PATH, true); await compile(path.join(SRC_PATH, 'testcontracts.sol'), BIN_OUTPUT_PATH, true); await compile(path.join(SRC_PATH, 'testcontracts_advanced.sol'), BIN_OUTPUT_PATH, true); console.log("Compiling done."); }, 100000); const runTest = async (code, data, resExpected) => { const result = await execute(code, data); expect(result.errno).toEqual(resExpected.errno); expect(result.errpc).toEqual(resExpected.errpc); expect(result.returnData).toEqual(resExpected.returnData); expect(result.mem.length).toEqual(resExpected.mem.length); expect(result.mem).toEqual(resExpected.mem); expect(result.stack.length).toEqual(resExpected.stack.length); for (let i = 0; i < result.stack.length; i++) { expect(result.stack[i].eq(resExpected.stack[i])).toBeTruthy(); } return result; }; const runTestWithInput = async (input, resExpected) => { const result = await executeWithTxInput(input); expect(result.errno).toEqual(resExpected.errno); expect(result.errpc).toEqual(resExpected.errpc); expect(result.returnData).toEqual(resExpected.returnData); expect(result.mem.length).toEqual(resExpected.mem.length); expect(result.mem).toEqual(resExpected.mem); expect(result.stack.length).toEqual(resExpected.stack.length); for (let i = 0; i < result.stack.length; i++) { expect(result.stack[i].eq(resExpected.stack[i])).toBeTruthy(); } return result; }; describe('single instructions', async () => { describe('stop and arithmetic ops', () => { it('should STOP successfully', async () => { const code = STOP; const data = ""; const resExpected = { errno: 0, errpc: 0, returnData: "", memSize: 0, mem: "", stack: [], }; await runTest(code, data, resExpected); }); it('should ADD two numbers successfully', async () => { const stack_0 = '0000000000000000000000000000000000000000000000000000000000000003'; const stack_1 = '0000000000000000000000000000000000000000000000000000000000000004'; const code = PUSH32 + stack_0 + PUSH32 + stack_1 + ADD; const data = ""; const resExpected = { errno: 0, errpc: code.length / 2, returnData: "", memSize: 0, mem: "", stack: [ new BigNumber(7) ], }; await runTest(code, data, resExpected); }); it('should ADD with too few params, resulting in a stack underflow', async () => { const code = PUSH1 + '00' + ADD; const data = ""; const resExpected = { errno: ERROR_STACK_UNDERFLOW, errpc: 2, returnData: "", memSize: 0, mem: "", stack: [new BigNumber(0)], }; await runTest(code, data, resExpected); }); it('should MUL two numbers successfully', async () => { const stack_0 = '0000000000000000000000000000000000000000000000000000000000000003'; const stack_1 = '0000000000000000000000000000000000000000000000000000000000000004'; const code = PUSH32 + stack_0 + PUSH32 + stack_1 + MUL; const data = ""; const resExpected = { errno: 0, errpc: code.length / 2, returnData: "", memSize: 0, mem: "", stack: [ new BigNumber(12) ], }; await runTest(code, data, resExpected); }); it('should MUL with too few params, resulting in a stack underflow', async () => { const code = PUSH1 + '00' + MUL; const data = ""; const resExpected = { errno: ERROR_STACK_UNDERFLOW, errpc: 2, returnData: "", memSize: 0, mem: "", stack: [new BigNumber(0)], }; await runTest(code, data, resExpected); }); it('should SUB two numbers successfully', async () => { const stack_0 = '0000000000000000000000000000000000000000000000000000000000000004'; const stack_1 = '0000000000000000000000000000000000000000000000000000000000000009'; const code = PUSH32 + stack_0 + PUSH32 + stack_1 + SUB; const data = ""; const resExpected = { errno: 0, errpc: code.length / 2, returnData: "", memSize: 0, mem: "", stack: [ new BigNumber(5) ], }; await runTest(code, data, resExpected); }); it('should SUB with too few params, resulting in a stack underflow', async () => { const code = PUSH1 + '00' + SUB; const data = ""; const resExpected = { errno: ERROR_STACK_UNDERFLOW, errpc: 2, returnData: "", memSize: 0, mem: "", stack: [new BigNumber(0)], }; await runTest(code, data, resExpected); }); it('should DIV two numbers successfully', async () => { const stack_0 = '0000000000000000000000000000000000000000000000000000000000000004'; const stack_1 = '0000000000000000000000000000000000000000000000000000000000000008'; const code = PUSH32 + stack_0 + PUSH32 + stack_1 + DIV; const data = ""; const resExpected = { errno: 0, errpc: code.length / 2, returnData: "", memSize: 0, mem: "", stack: [ new BigNumber(2) ], }; await runTest(code, data, resExpected); }); it('should DIV with too few params, resulting in a stack underflow', async () => { const code = PUSH1 + '00' + DIV; const data = ""; const resExpected = { errno: ERROR_STACK_UNDERFLOW, errpc: 2, returnData: "", memSize: 0, mem: "", stack: [new BigNumber(0)], }; await runTest(code, data, resExpected); }); it('should DIV with zero successfully', async () => { const stack_0 = '0000000000000000000000000000000000000000000000000000000000000000'; const stack_1 = '0000000000000000000000000000000000000000000000000000000000000008'; const code = PUSH32 + stack_0 + PUSH32 + stack_1 + DIV; const data = ""; const resExpected = { errno: 0, errpc: code.length / 2, returnData: "", memSize: 0, mem: "", stack: [ new BigNumber(0) ], }; await runTest(code, data, resExpected); }); it('should SDIV two numbers successfully', async () => { const stack_0 = 'fffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffe'; // -6 const stack_1 = 'fffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffa'; const code = PUSH32 + stack_0 + PUSH32 + stack_1 + SDIV; const data = ""; const resExpected = { errno: 0, errpc: code.length / 2, returnData: "", memSize: 0, mem: "", stack: [ new BigNumber(3) ], }; await runTest(code, data, resExpected); }); it('should SDIV with too few params, resulting in a stack underflow', async () => { const code = PUSH1 + '00' + SDIV; const data = ""; const resExpected = { errno: ERROR_STACK_UNDERFLOW, errpc: 2, returnData: "", memSize: 0, mem: "", stack: [new BigNumber(0)], }; await runTest(code, data, resExpected); }); it('should SDIV with zero successfully', async () => { const stack_0 = '0000000000000000000000000000000000000000000000000000000000000000'; const stack_1 = '0000000000000000000000000000000000000000000000000000000000000008'; const code = PUSH32 + stack_0 + PUSH32 + stack_1 + SDIV; const data = ""; const resExpected = { errno: 0, errpc: code.length / 2, returnData: "", memSize: 0, mem: "", stack: [ new BigNumber(0) ], }; await runTest(code, data, resExpected); }); it('should MOD a number successfully', async () => { const stack_0 = '0000000000000000000000000000000000000000000000000000000000000004'; const stack_1 = '0000000000000000000000000000000000000000000000000000000000000009'; const code = PUSH32 + stack_0 + PUSH32 + stack_1 + MOD; const data = ""; const resExpected = { errno: 0, errpc: code.length / 2, returnData: "", memSize: 0, mem: "", stack: [ new BigNumber(1) ], }; await runTest(code, data, resExpected); }); it('should MOD a number with zero successfully', async () => { const stack_0 = '0000000000000000000000000000000000000000000000000000000000000000'; const stack_1 = '0000000000000000000000000000000000000000000000000000000000000009'; const code = PUSH32 + stack_0 + PUSH32 + stack_1 + MOD; const data = ""; const resExpected = { errno: 0, errpc: code.length / 2, returnData: "", memSize: 0, mem: "", stack: [ new BigNumber(0) ], }; await runTest(code, data, resExpected); }); it('should MOD with too few params, resulting in a stack underflow', async () => { const code = PUSH1 + '00' + MOD; const data = ""; const resExpected = { errno: ERROR_STACK_UNDERFLOW, errpc: 2, returnData: "", memSize: 0, mem: "", stack: [new BigNumber(0)], }; await runTest(code, data, resExpected); }); it('should SMOD a signed number successfully', async () => { const stack_0 = 'fffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffc'; const stack_1 = '0000000000000000000000000000000000000000000000000000000000000009'; const code = PUSH32 + stack_0 + PUSH32 + stack_1 + SMOD; const data = ""; const resExpected = { errno: 0, errpc: code.length / 2, returnData: "", memSize: 0, mem: "", stack: [ new BigNumber(1) ], }; await runTest(code, data, resExpected); }); it('should SMOD number with zero successfully', async () => { const stack_0 = '0000000000000000000000000000000000000000000000000000000000000000'; const stack_1 = '0000000000000000000000000000000000000000000000000000000000000009'; const code = PUSH32 + stack_0 + PUSH32 + stack_1 + SMOD; const data = ""; const resExpected = { errno: 0, errpc: code.length / 2, returnData: "", memSize: 0, mem: "", stack: [ new BigNumber(0) ], }; await runTest(code, data, resExpected); }); it('should SMOD with too few params, resulting in a stack underflow', async () => { const code = PUSH1 + '00' + SMOD; const data = ""; const resExpected = { errno: ERROR_STACK_UNDERFLOW, errpc: 2, returnData: "", memSize: 0, mem: "", stack: [new BigNumber(0)], }; await runTest(code, data, resExpected); }); it('should ADDMOD successfully', async () => { const stack_0 = '0000000000000000000000000000000000000000000000000000000000000005'; const stack_1 = '0000000000000000000000000000000000000000000000000000000000000004'; const stack_2 = '0000000000000000000000000000000000000000000000000000000000000009'; const code = PUSH32 + stack_0 + PUSH32 + stack_1 + PUSH32 + stack_2 + ADDMOD; const data = ""; const resExpected = { errno: 0, errpc: code.length / 2, returnData: "", memSize: 0, mem: "", stack: [ new BigNumber(3) ], }; await runTest(code, data, resExpected); }); it('should ADDMOD with too few params, resulting in a stack underflow', async () => { const code = PUSH1 + '00' + PUSH1 + '00' + ADDMOD; const data = ""; const resExpected = { errno: ERROR_STACK_UNDERFLOW, errpc: 4, returnData: "", memSize: 0, mem: "", stack: [new BigNumber(0), new BigNumber(0)], }; await runTest(code, data, resExpected); }); it('should MULMOD successfully', async () => { const stack_0 = '0000000000000000000000000000000000000000000000000000000000000005'; const stack_1 = '0000000000000000000000000000000000000000000000000000000000000004'; const stack_2 = '0000000000000000000000000000000000000000000000000000000000000009'; const code = PUSH32 + stack_0 + PUSH32 + stack_1 + PUSH32 + stack_2 + MULMOD; const data = ""; const resExpected = { errno: 0, errpc: code.length / 2, returnData: "", memSize: 0, mem: "", stack: [ new BigNumber(1) ], }; await runTest(code, data, resExpected); }); it('should MULMOD with too few params, resulting in a stack underflow', async () => { const code = PUSH1 + '00' + PUSH1 + '00' + MULMOD; const data = ""; const resExpected = { errno: ERROR_STACK_UNDERFLOW, errpc: 4, returnData: "", memSize: 0, mem: "", stack: [new BigNumber(0), new BigNumber(0)], }; await runTest(code, data, resExpected); }); it('should EXP successfully', async () => { const stack_0 = '0000000000000000000000000000000000000000000000000000000000000004'; const stack_1 = '0000000000000000000000000000000000000000000000000000000000000003'; const code = PUSH32 + stack_0 + PUSH32 + stack_1 + EXP; const data = ""; const resExpected = { errno: 0, errpc: code.length / 2, returnData: "", memSize: 0, mem: "", stack: [ new BigNumber(81) ], }; await runTest(code, data, resExpected); }); it('should EXP with too few params, resulting in a stack underflow', async () => { const code = PUSH1 + '00' + EXP; const data = ""; const resExpected = { errno: ERROR_STACK_UNDERFLOW, errpc: 2, returnData: "", memSize: 0, mem: "", stack: [new BigNumber(0)], }; await runTest(code, data, resExpected); }); }); describe('comparison and bitwise ops', () => { it('should compute LT of two numbers successfully when true', async () => { const stack_0 = '0000000000000000000000000000000000000000000000000000000000000003'; const stack_1 = '0000000000000000000000000000000000000000000000000000000000000002'; const code = PUSH32 + stack_0 + PUSH32 + stack_1 + LT; const data = ""; const resExpected = { errno: 0, errpc: code.length / 2, returnData: "", memSize: 0, mem: "", stack: [ new BigNumber(1) ], }; await runTest(code, data, resExpected); }); it('should compute LT of two numbers successfully when false', async () => { const stack_0 = '0000000000000000000000000000000000000000000000000000000000000003'; const stack_1 = '0000000000000000000000000000000000000000000000000000000000000003'; const code = PUSH32 + stack_0 + PUSH32 + stack_1 + LT; const data = ""; const resExpected = { errno: 0, errpc: code.length / 2, returnData: "", memSize: 0, mem: "", stack: [ new BigNumber(0) ], }; await runTest(code, data, resExpected); }); it('should LT with too few params, resulting in a stack underflow', async () => { const code = PUSH1 + '00' + LT; const data = ""; const resExpected = { errno: ERROR_STACK_UNDERFLOW, errpc: 2, returnData: "", memSize: 0, mem: "", stack: [new BigNumber(0)], }; await runTest(code, data, resExpected); }); it('should compute GT of two numbers successfully when true', async () => { const stack_0 = '0000000000000000000000000000000000000000000000000000000000000002'; const stack_1 = '0000000000000000000000000000000000000000000000000000000000000003'; const code = PUSH32 + stack_0 + PUSH32 + stack_1 + GT; const data = ""; const resExpected = { errno: 0, errpc: code.length / 2, returnData: "", memSize: 0, mem: "", stack: [ new BigNumber(1) ], }; await runTest(code, data, resExpected); }); it('should compute GT of two numbers successfully when false', async () => { const stack_0 = '0000000000000000000000000000000000000000000000000000000000000003'; const stack_1 = '0000000000000000000000000000000000000000000000000000000000000003'; const code = PUSH32 + stack_0 + PUSH32 + stack_1 + GT; const data = ""; const resExpected = { errno: 0, errpc: code.length / 2, returnData: "", memSize: 0, mem: "", stack: [ new BigNumber(0) ], }; await runTest(code, data, resExpected); }); it('should GT with too few params, resulting in a stack underflow', async () => { const code = PUSH1 + '00' + GT; const data = ""; const resExpected = { errno: ERROR_STACK_UNDERFLOW, errpc: 2, returnData: "", memSize: 0, mem: "", stack: [new BigNumber(0)], }; await runTest(code, data, resExpected); }); it('should compute SLT of two numbers successfully when true', async () => { const stack_0 = 'fffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffe'; const stack_1 = 'fffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffc'; const code = PUSH32 + stack_0 + PUSH32 + stack_1 + SLT; const data = ""; const resExpected = { errno: 0, errpc: code.length / 2, returnData: "", memSize: 0, mem: "", stack: [ new BigNumber(1) ], }; await runTest(code, data, resExpected); }); it('should compute SLT of two numbers successfully when false', async () => { const stack_0 = 'fffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffc'; const stack_1 = 'fffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffc'; const code = PUSH32 + stack_0 + PUSH32 + stack_1 + SLT; const data = ""; const resExpected = { errno: 0, errpc: code.length / 2, returnData: "", memSize: 0, mem: "", stack: [ new BigNumber(0) ], }; await runTest(code, data, resExpected); }); it('should SLT with too few params, resulting in a stack underflow', async () => { const code = PUSH1 + '00' + SLT; const data = ""; const resExpected = { errno: ERROR_STACK_UNDERFLOW, errpc: 2, returnData: "", memSize: 0, mem: "", stack: [new BigNumber(0)], }; await runTest(code, data, resExpected); }); it('should compute SGT of two numbers successfully when true', async () => { const stack_0 = 'fffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffc'; const stack_1 = '0000000000000000000000000000000000000000000000000000000000000003'; const code = PUSH32 + stack_0 + PUSH32 + stack_1 + SGT; const data = ""; const resExpected = { errno: 0, errpc: code.length / 2, returnData: "", memSize: 0, mem: "", stack: [ new BigNumber(1) ], }; await runTest(code, data, resExpected); }); it('should compute SGT of two numbers successfully when false', async () => { const stack_0 = '0000000000000000000000000000000000000000000000000000000000000003'; const stack_1 = '0000000000000000000000000000000000000000000000000000000000000003'; const code = PUSH32 + stack_0 + PUSH32 + stack_1 + SGT; const data = ""; const resExpected = { errno: 0, errpc: code.length / 2, returnData: "", memSize: 0, mem: "", stack: [ new BigNumber(0) ], }; await runTest(code, data, resExpected); }); it('should SGT with too few params, resulting in a stack underflow', async () => { const code = PUSH1 + '00' + SGT; const data = ""; const resExpected = { errno: ERROR_STACK_UNDERFLOW, errpc: 2, returnData: "", memSize: 0, mem: "", stack: [new BigNumber(0)], }; await runTest(code, data, resExpected); }); it('should compute EQ of two numbers successfully when true', async () => { const stack_0 = '0000000000000000000000000000000000000000000000000000000000000003'; const stack_1 = '0000000000000000000000000000000000000000000000000000000000000003'; const code = PUSH32 + stack_0 + PUSH32 + stack_1 + EQ; const data = ""; const resExpected = { errno: 0, errpc: code.length / 2, returnData: "", memSize: 0, mem: "", stack: [ new BigNumber(1) ], }; await runTest(code, data, resExpected); }); it('should compute EQ of two numbers successfully when false', async () => { const stack_0 = '0000000000000000000000000000000000000000000000000000000000000003'; const stack_1 = '0000000000000000000000000000000000000000000000000000000000000001'; const code = PUSH32 + stack_0 + PUSH32 + stack_1 + EQ; const data = ""; const resExpected = { errno: 0, errpc: code.length / 2, returnData: "", memSize: 0, mem: "", stack: [ new BigNumber(0) ], }; await runTest(code, data, resExpected); }); it('should EQ with too few params, resulting in a stack underflow', async () => { const code = PUSH1 + '00' + EQ; const data = ""; const resExpected = { errno: ERROR_STACK_UNDERFLOW, errpc: 2, returnData: "", memSize: 0, mem: "", stack: [new BigNumber(0)], }; await runTest(code, data, resExpected); }); it('should compute ISZERO of a number successfully when true', async () => { const stack_0 = '0000000000000000000000000000000000000000000000000000000000000000'; const code = PUSH32 + stack_0 + ISZERO; const data = ""; const resExpected = { errno: 0, errpc: code.length / 2, returnData: "", memSize: 0, mem: "", stack: [ new BigNumber(1) ], }; await runTest(code, data, resExpected); }); it('should compute ISZERO of a number successfully when false', async () => { const stack_0 = '0000000000000000000000000000000000000000000000000000000000000004'; const code = PUSH32 + stack_0 + ISZERO; const data = ""; const resExpected = { errno: 0, errpc: code.length / 2, returnData: "", memSize: 0, mem: "", stack: [ new BigNumber(0) ], }; await runTest(code, data, resExpected); }); it('should EQ with too few params, resulting in a stack underflow', async () => { const code = EQ; const data = ""; const resExpected = { errno: ERROR_STACK_UNDERFLOW, errpc: 0, returnData: "", memSize: 0, mem: "", stack: [], }; await runTest(code, data, resExpected); }); it('should compute AND of two numbers successfully', async () => { const stack_0 = '0000000000000000000000000000000000000000000000000000000000000003'; const stack_1 = '0000000000000000000000000000000000000000000000000000000000000001'; const code = PUSH32 + stack_0 + PUSH32 + stack_1 + AND; const data = ""; const resExpected = { errno: 0, errpc: code.length / 2, returnData: "", memSize: 0, mem: "", stack: [ new BigNumber(1) ], }; await runTest(code, data, resExpected); }); it('should AND with too few params, resulting in a stack underflow', async () => { const code = PUSH1 + '00' + AND; const data = ""; const resExpected = { errno: ERROR_STACK_UNDERFLOW, errpc: 2, returnData: "", memSize: 0, mem: "", stack: [new BigNumber(0)], }; await runTest(code, data, resExpected); }); it('should compute OR of two numbers successfully', async () => { const stack_0 = '0000000000000000000000000000000000000000000000000000000000000003'; const stack_1 = '0000000000000000000000000000000000000000000000000000000000000001'; const code = PUSH32 + stack_0 + PUSH32 + stack_1 + OR; const data = ""; const resExpected = { errno: 0, errpc: code.length / 2, returnData: "", memSize: 0, mem: "", stack: [ new BigNumber(3) ], }; await runTest(code, data, resExpected); }); it('should OR with too few params, resulting in a stack underflow', async () => { const code = PUSH1 + '00' + OR; const data = ""; const resExpected = { errno: ERROR_STACK_UNDERFLOW, errpc: 2, returnData: "", memSize: 0, mem: "", stack: [new BigNumber(0)], }; await runTest(code, data, resExpected); }); it('should compute XOR of two numbers successfully', async () => { const stack_0 = '0000000000000000000000000000000000000000000000000000000000000003'; const stack_1 = '0000000000000000000000000000000000000000000000000000000000000001'; const code = PUSH32 + stack_0 + PUSH32 + stack_1 + XOR; const data = ""; const resExpected = { errno: 0, errpc: code.length / 2, returnData: "", memSize: 0, mem: "", stack: [ new BigNumber(2) ], }; await runTest(code, data, resExpected); }); it('should XOR with too few params, resulting in a stack underflow', async () => { const code = PUSH1 + '00' + XOR; const data = ""; const resExpected = { errno: ERROR_STACK_UNDERFLOW, errpc: 2, returnData: "", memSize: 0, mem: "", stack: [new BigNumber(0)], }; await runTest(code, data, resExpected); }); it('should compute NOT of a number successfully', async () => { const stack_0 = 'ffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffff'; const code = PUSH32 + stack_0 + NOT; const data = ""; const resExpected = { errno: 0, errpc: code.length / 2, returnData: "", memSize: 0, mem: "", stack: [ new BigNumber(0) ], }; await runTest(code, data, resExpected); }); it('should NOT with too few params, resulting in a stack underflow', async () => { const code = NOT; const data = ""; const resExpected = { errno: ERROR_STACK_UNDERFLOW, errpc: 0, returnData: "", memSize: 0, mem: "", stack: [], }; await runTest(code, data, resExpected); }); it('should get the 0:th BYTE from a number successfully', async () => { const stack_0 = '0102030405060708010203040506070801020304050607080102030405060708'; const stack_1 = '0000000000000000000000000000000000000000000000000000000000000000'; const code = PUSH32 + stack_0 + PUSH32 + stack_1 + BYTE; const data = ""; const resExpected = { errno: 0, errpc: code.length / 2, returnData: "", memSize: 0, mem: "", stack: [ new BigNumber(1) ], }; await runTest(code, data, resExpected); }); it('should get the 10:th BYTE from a number successfully', async () => { const stack_0 = '0102030405060708010203040506070801020304050607080102030405060708'; const stack_1 = '0000000000000000000000000000000000000000000000000000000000000009'; const code = PUSH32 + stack_0 + PUSH32 + stack_1 + BYTE; const data = ""; const resExpected = { errno: 0, errpc: code.length / 2, returnData: "", memSize: 0, mem: "", stack: [ new BigNumber(2) ], }; await runTest(code, data, resExpected); }); it('should return 0 when getting a BYTE out of range', async () => { const stack_0 = '0102030405060708010203040506070801020304050607080102030405060708'; const stack_1 = '0000000000000000000000000000000000000000000000000000000000000100'; const code = PUSH32 + stack_0 + PUSH32 + stack_1 + BYTE; const data = ""; const resExpected = { errno: 0, errpc: code.length / 2, returnData: "", memSize: 0, mem: "", stack: [ new BigNumber(0) ], }; await runTest(code, data, resExpected); }); it('should BYTE with too few params, resulting in a stack underflow', async () => { const code = PUSH1 + '00' + BYTE; const data = ""; const resExpected = { errno: ERROR_STACK_UNDERFLOW, errpc: 2, returnData: "", memSize: 0, mem: "", stack: [new BigNumber(0)], }; await runTest(code, data, resExpected); }); }); describe('sha3', () => { it('should use SHA3 successfully with 0-size input', async () => { const code = PUSH1 + '00' + PUSH1 + '00' + SHA3; const data = ""; const resExpected = { errno: 0, errpc: code.length / 2, returnData: "", memSize: 0, mem: "", stack: [ new BigNumber("c5d2460186f7233c927e7db2dcc703c0e500b653ca82273b7bfad8045d85a470", 16) ], }; await runTest(code, data, resExpected); }); it('should use SHA3 successfully with non-zero length input', async () => { const code = PUSH1 + '20' + PUSH1 + '00' + SHA3; const data = ""; const resExpected = { errno: 0, errpc: code.length / 2, returnData: "", memSize: 0, mem: "", stack: [ new BigNumber("290decd9548b62a8d60345a988386fc84ba6bc95484008f6362f93160ef3e563", 16) ], }; await runTest(code, data, resExpected); }); it('should use SHA3 successfully with large input', async () => { const code = PUSH2 + '0500' + PUSH1 + '00' + SHA3; const data = ""; const resExpected = { errno: 0, errpc: code.length / 2, returnData: "", memSize: 0, mem: "", stack: [ new BigNumber("e36384b33d42c0941ec56a16413312b35766b36e5e75c673c1862ae08e6d02ba", 16) ], }; await runTest(code, data, resExpected); }); it('should SHA3 with too few params, resulting in a stack underflow', async () => { const code = PUSH1 + '00' + SHA3; const data = ""; const resExpected = { errno: ERROR_STACK_UNDERFLOW, errpc: 2, returnData: "", memSize: 0, mem: "", stack: [new BigNumber(0)], }; await runTest(code, data, resExpected); }); }); describe('environmental information', () => { it('should use ADDRESS successfully', async () => { const code = ADDRESS; const data = ""; const resExpected = { errno: 0, errpc: code.length / 2, returnData: "", memSize: 0, mem: "", stack: [ new BigNumber(DEFAULT_CONTRACT_ADDRESS, 16) ], }; await runTest(code, data, resExpected); }); it('should use BALANCE successfully', async () => { const code = PUSH20 + DEFAULT_CALLER + BALANCE; const data = ""; const input = createTxInput(code, data, 500); input.value = new BigNumber(0); // just use createTxInput to not have to set everything. const resExpected = { errno: 0, errpc: code.length / 2, returnData: "", memSize: 0, mem: "", stack: [ new BigNumber(500) ], }; await runTestWithInput(input, resExpected); }); it('should use BALANCE with too few params, resulting in a stack underflow', async () => { const code = BALANCE; const data = ""; const resExpected = { errno: ERROR_STACK_UNDERFLOW, errpc: 0, returnData: "", memSize: 0, mem: "", stack: [], }; await runTest(code, data, resExpected); }); it('should use CALLER successfully', async () => { const code = CALLER; const data = ""; const resExpected = { errno: 0, errpc: code.length / 2, returnData: "", memSize: 0, mem: "", stack: [ new BigNumber(DEFAULT_CALLER, 16) ], }; await runTest(code, data, resExpected); }); it('should use CALLVALUE successfully', async () => { const code = CALLVALUE; const data = ""; const input = createTxInput(code, data, 55, false); const resExpected = { errno: 0, errpc: code.length / 2, returnData: "", memSize: 0, mem: "", stack: [ new BigNumber(55) ], }; await runTestWithInput(input, resExpected); // prettyPrintResults(result); }); it('should use CALLDATALOAD successfully within the calldata boundary, with no offset', async () => { const stack_0 = '0000000000000000000000000000000000000000000000000000000000000000'; const code = PUSH32 + stack_0 + CALLDATALOAD; const data = "0000000000000000000000000000000000000000000000000000000000000001"; const resExpected = { errno: 0, errpc: code.length / 2, returnData: "", memSize: 0, mem: "", stack: [ new BigNumber(1) ], }; await runTest(code, data, resExpected); }); it('should use CALLDATALOAD successfully outside the calldata boundary, with no offset', async () => { const stack_0 = '0000000000000000000000000000000000000000000000000000000000000000'; const code = PUSH32 + stack_0 + CALLDATALOAD; const data = ""; const resExpected = { errno: 0, errpc: code.length / 2, returnData: "", memSize: 0, mem: "", stack: [ new BigNumber(0) ], }; await runTest(code, data, resExpected); }); it('should use CALLDATALOAD successfully partially inside the calldata boundary, with no offset', async () => { const stack_0 = '0000000000000000000000000000000000000000000000000000000000000000'; const code = PUSH32 + stack_0 + CALLDATALOAD; const data = "01"; const resExpected = { errno: 0, errpc: code.length / 2, returnData: "", memSize: 0, mem: "", stack: [ new BigNumber('0100000000000000000000000000000000000000000000000000000000000000', 16) ], }; await runTest(code, data, resExpected); }); it('should use CALLDATALOAD successfully within the calldata boundary, with offset', async () => { const stack_0 = '0000000000000000000000000000000000000000000000000000000000000020'; const code = PUSH32 + stack_0 + CALLDATALOAD; const data = "00000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000001"; const resExpected = { errno: 0, errpc: code.length / 2, returnData: "", memSize: 0, mem: "", stack: [ new BigNumber(1) ], }; await runTest(code, data, resExpected); }); it('should use CALLDATALOAD successfully outside the calldata boundary, with offset', async () => { const stack_0 = '0000000000000000000000000000000000000000000000000000000000000020'; const code = PUSH32 + stack_0 + CALLDATALOAD; const data = ""; const resExpected = { errno: 0, errpc: code.length / 2, returnData: "", memSize: 0, mem: "", stack: [ new BigNumber(0) ], }; await runTest(code, data, resExpected); }); it('should use CALLDATALOAD successfully partially inside the calldata boundary, with offset', async () => { const stack_0 = '0000000000000000000000000000000000000000000000000000000000000020'; const code = PUSH32 + stack_0 + CALLDATALOAD; const data = "000000000000000000000000000000000000000000000000000000000000000001"; const resExpected = { errno: 0, errpc: code.length / 2, returnData: "", memSize: 0, mem: "", stack: [ new BigNumber('0100000000000000000000000000000000000000000000000000000000000000', 16) ], }; await runTest(code, data, resExpected); }); it('should use CALLDATALOAD with too few params, resulting in a stack underflow', async () => { const code = CALLDATALOAD; const data = ""; const resExpected = { errno: ERROR_STACK_UNDERFLOW, errpc: 0, returnData: "", memSize: 0, mem: "", stack: [], }; await runTest(code, data, resExpected); }); it('should use CALLDATASIZE successfully when zero', async () => { const code = CALLDATASIZE; const data = ""; const resExpected = { errno: 0, errpc: code.length / 2, returnData: "", memSize: 0, mem: "", stack: [ new BigNumber(0) ], }; await runTest(code, data, resExpected); }); it('should use CALLDATASIZE successfully when non-zero', async () => { const code = CALLDATASIZE; const data = "01010101010101"; const resExpected = { errno: 0, errpc: code.length / 2, returnData: "", memSize: 0, mem: "", stack: [ new BigNumber(7) ], }; await runTest(code, data, resExpected); }); it('should use CALLDATACOPY successfully with zero bytes copied', async () => { const code = PUSH1 + '00' + PUSH1 + '00' + PUSH1 + '00' + CALLDATACOPY; const data = ""; const resExpected = { errno: 0, errpc: code.length / 2, returnData: "", memSize: 32, mem: "", stack: [], }; await runTest(code, data, resExpected); }); it('should use CALLDATACOPY successfully', async () => { const code = PUSH1 + '10' + PUSH1 + '08' + PUSH1 + '08' + CALLDATACOPY; const data = "0101010101010101020202020202020203030303030303030404040404040404"; const resExpected = { errno: 0, errpc: code.length / 2, returnData: "", memSize: 32, mem: "0000000000000000020202020202020203030303030303030000000000000000", stack: [], }; await runTest(code, data, resExpected); }); it('should use CALLDATACOPY with too few params, resulting in a stack underflow', async () => { const code = PUSH1 + '00' + PUSH1 + '00' + CALLDATACOPY; const data = ""; const resExpected = { errno: ERROR_STACK_UNDERFLOW, errpc: 4, returnData: "", memSize: 0, mem: "", stack: [ new BigNumber(0), new BigNumber(0) ], }; await runTest(code, data, resExpected); }); it('should use CODESIZE successfully', async () => { const code = CODESIZE; const data = ""; const resExpected = { errno: 0, errpc: code.length / 2, returnData: "", memSize: 0, mem: "", stack: [ new BigNumber(1) ], }; await runTest(code, data, resExpected); }); it('should use CODECOPY successfully with zero size', async () => { const code = PUSH1 + '00' + PUSH1 + '00' + PUSH1 + '00' + CODECOPY; const data = ""; const resExpected = { errno: 0, errpc: code.length / 2, returnData: "", memSize: 0, mem: "", stack: [], }; await runTest(code, data, resExpected); }); it('should use CODECOPY successfully', async () => { const code = PUSH1 + '07' + PUSH1 + '00' + PUSH1 + '00' + CODECOPY; const data = ""; const resExpected = { errno: 0, errpc: code.length / 2, returnData: "", memSize: 32, mem: code + "00000000000000000000000000000000000000000000000000", stack: [], }; await runTest(code, data, resExpected); }); it('should use CODECOPY with too few params, resulting in a stack underflow', async () => { const code = PUSH1 + '00' + PUSH1 + '00' + CODECOPY; const data = ""; const resExpected = { errno: ERROR_STACK_UNDERFLOW, errpc: 4, returnData: "", memSize: 0, mem: "", stack: [ new BigNumber(0), new BigNumber(0) ], }; await runTest(code, data, resExpected); }); it('should use GASPRICE successfully', async () => { const code = GASPRICE; const data = ""; const resExpected = { errno: 0, errpc: code.length / 2, returnData: "", memSize: 0, mem: "", stack: [ new BigNumber(0) ], }; await runTest(code, data, resExpected); }); // TODO EXTCODESIZE, EXTCODECOPY, RETURNDATASIZE, RETURNDATACOPY // These should maybe be done directly in solidity // There are tests for returndata in solidity contract tests. }); describe('block information', () => { it('should use BLOCKHASH successfully', async () => { const code = PUSH1 + '00' + BLOCKHASH; const data = ""; const resExpected = { errno: 0, errpc: code.length / 2, returnData: "", memSize: 0, mem: "", stack: [ new BigNumber(0) ], }; await runTest(code, data, resExpected); }); it('should use BLOCKHASH with too few params, resulting in a stack underflow', async () => { const code = BLOCKHASH; const data = ""; const resExpected = { errno: ERROR_STACK_UNDERFLOW, errpc: 0, returnData: "", memSize: 0, mem: "", stack: [], }; await runTest(code, data, resExpected); }); it('should use COINBASE successfully', async () => { const code = COINBASE; const data = ""; const resExpected = { errno: 0, errpc: code.length / 2, returnData: "", memSize: 0, mem: "", stack: [ new BigNumber(0) ], }; await runTest(code, data, resExpected); }); it('should use TIMESTAMP successfully', async () => { const code = TIMESTAMP; const data = ""; const resExpected = { errno: 0, errpc: code.length / 2, returnData: "", memSize: 0, mem: "", stack: [ new BigNumber(0) ], }; await runTest(code, data, resExpected); }); it('should use NUMBER successfully', async () => { const code = NUMBER; const data = ""; const resExpected = { errno: 0, errpc: code.length / 2, returnData: "", memSize: 0, mem: "", stack: [ new BigNumber(0) ], }; await runTest(code, data, resExpected); }); it('should use DIFFICULTY successfully', async () => { const code = DIFFICULTY; const data = ""; const resExpected = { errno: 0, errpc: code.length / 2, returnData: "", memSize: 0, mem: "", stack: [ new BigNumber(0) ], }; await runTest(code, data, resExpected); }); it('should use GASLIMIT successfully', async () => { const code = GASLIMIT; const data = ""; const resExpected = { errno: 0, errpc: code.length / 2, returnData: "", memSize: 0, mem: "", stack: [ new BigNumber(0) ], }; await runTest(code, data, resExpected); }); }); describe('stack, memory, storage and flow ops', () => { it('should run PUSH32 three times in a row then pop all three successfully', async () => { const stack_0 = '0101010101010101010101010101010101010101010101010101010101010101'; const stack_1 = '0101010101010101010101010101010101010101010101010101010101010102'; const stack_2 = '0101010101010101010101010101010101010101010101010101010101010103'; const code = PUSH32 + stack_0 + PUSH32 + stack_1 + PUSH32 + stack_2 + POP + POP + POP; const data = ""; const resExpected = { errno: 0, errpc: code.length / 2, returnData: "", memSize: 0, mem: "", stack: [], }; await runTest(code, data, resExpected); }); it('should POP empty stack and result in a stack underflow', async () => { const code = POP; const data = ""; const resExpected = { errno: ERROR_STACK_UNDERFLOW, errpc: 0, returnData: "", memSize: 0, mem: "", stack: [], }; await runTest(code, data, resExpected); }); it('should use MLOAD successfully', async () => { const code = PUSH32 + '0000000000000000000000000000000000000000000000000000000000000001' + PUSH1 + '00' + MSTORE + PUSH1 + '00' + MLOAD; const data = ""; const resExpected = { errno: 0, errpc: code.length / 2, returnData: "", memSize: 0, mem: "0000000000000000000000000000000000000000000000000000000000000001", stack: [ new BigNumber(1) ], }; await runTest(code, data, resExpected); }); it('should use MSTORE successfully', async () => { const code = PUSH32 + '0000000000000000000000000000000000000000000000000000000000000001' + PUSH1 + '00' + MSTORE; const data = ""; const resExpected = { errno: 0, errpc: code.length / 2, returnData: "", memSize: 0, mem: "0000000000000000000000000000000000000000000000000000000000000001", stack: [], }; await runTest(code, data, resExpected); }); it('should use MSTORE8 successfully', async () => { const code = PUSH32 + '8877665544332211887766554433221188776655443322118877665544332211' + PUSH1 + '00' + MSTORE8; const data = ""; const resExpected = { errno: 0, errpc: code.length / 2, returnData: "", memSize: 0, mem: "1100000000000000000000000000000000000000000000000000000000000000", stack: [], }; await runTest(code, data, resExpected); }); it('should use SLOAD successfully', async () => { const code = PUSH1 + '02' + PUSH1 + '01' + SSTORE + PUSH1 + '01' + SLOAD; const data = ""; const resExpected = { errno: 0, errpc: code.length / 2, returnData: "", memSize: 0, mem: "", stack: [new BigNumber(2)], }; await runTest(code, data, resExpected); }); it('should use SSTORE successfully', async () => { const code = PUSH1 + '02' + PUSH1 + '01' + SSTORE; const data = ""; const resExpected = { errno: 0, errpc: code.length / 2, returnData: "", memSize: 0, mem: "", stack: [], }; const result = await runTest(code, data, resExpected); expect(result.errno).toBe(0); const storage = result.accounts[1].storage; expect(storage[0].address.toNumber()).toBe(1); expect(storage[0].value.toNumber()).toBe(2); }); it('should use JUMP successfully', async () => { const code = PUSH1 + '05' + JUMP + PUSH1 + '05' + JUMPDEST + STOP; const data = ""; const resExpected = { errno: 0, errpc: 6, returnData: "", memSize: 0, mem: "", stack: [], }; await runTest(code, data, resExpected); }); it('should fail JUMP when the jump destination is invalid', async () => { const code = PUSH1 + '05' + JUMP + PUSH1 + '05' + STOP; const data = ""; const resExpected = { errno: ERROR_INVALID_JUMP_DESTINATION, errpc: 2, returnData: "", memSize: 0, mem: "", stack: [], }; await runTest(code, data, resExpected); }); it('should use JUMP with too few params, resulting in a stack underflow', async () => { const code = JUMP; const data = ""; const resExpected = { errno: ERROR_STACK_UNDERFLOW, errpc: 0, returnData: "", memSize: 0, mem: "", stack: [], }; await runTest(code, data, resExpected); }); it('should use JUMPI successfully when condition is true', async () => { const code = PUSH1 + '01' + PUSH1 + '07' + JUMPI + PUSH1 + '05' + JUMPDEST + STOP; const data = ""; const resExpected = { errno: 0, errpc: 8, returnData: "", memSize: 0, mem: "", stack: [], }; await runTest(code, data, resExpected); }); it('should use JUMPI successfully when condition is false', async () => { const code = PUSH1 + '00' + PUSH1 + '07' + JUMPI + PUSH1 + '05' + JUMPDEST + STOP; const data = ""; const resExpected = { errno: 0, errpc: 8, returnData: "", memSize: 0, mem: "", stack: [new BigNumber(5)], }; await runTest(code, data, resExpected); }); it('should fail JUMPI when the jump destination is invalid', async () => { const code = PUSH1 + '01' + PUSH1 + '07' + JUMPI + PUSH1 + '05' + STOP; const data = ""; const resExpected = { errno: ERROR_INVALID_JUMP_DESTINATION, errpc: 4, returnData: "", memSize: 0, mem: "", stack: [], }; await runTest(code, data, resExpected); }); it('should use JUMPI with too few params, resulting in a stack underflow', async () => { const code = PUSH1 + '00' + JUMPI; const data = ""; const resExpected = { errno: ERROR_STACK_UNDERFLOW, errpc: 2, returnData: "", memSize: 0, mem: "", stack: [ new BigNumber(0) ], }; await runTest(code, data, resExpected); }); it('should use PC successfully', async () => { const code = PC + PC + PC; const data = ""; const resExpected = { errno: 0, errpc: code.length / 2, returnData: "", memSize: 0, mem: "", stack: [ new BigNumber(0), new BigNumber(1), new BigNumber(2) ], }; await runTest(code, data, resExpected); }); it('should use MSIZE successfully when memory is empty', async () => { const code = MSIZE; const data = ""; const resExpected = { errno: 0, errpc: code.length / 2, returnData: "", memSize: 0, mem: "", stack: [ new BigNumber(0) ], }; await runTest(code, data, resExpected); }); it('should use MSIZE successfully when memory is non-empty', async () => { const code = PUSH1 + '01' + PUSH1 + '00' + MSTORE + MSIZE; const data = ""; const resExpected = { errno: 0, errpc: code.length / 2, returnData: "", memSize: 32, mem: "0000000000000000000000000000000000000000000000000000000000000001", stack: [ new BigNumber(32) ], }; await runTest(code, data, resExpected); }); it('should use GAS successfully', async () => { const code = GAS; const data = ""; const resExpected = { errno: 0, errpc: code.length / 2, returnData: "", memSize: 0, mem: "", stack: [ new BigNumber(0) ], }; await runTest(code, data, resExpected); }); it('should use JUMPDEST successfully', async () => { const code = JUMPDEST; const data = ""; const resExpected = { errno: 0, errpc: code.length / 2, returnData: "", memSize: 0, mem: "", stack: [], }; await runTest(code, data, resExpected); }); }); describe('push ops', () => { it('should run PUSH32 successfully', async () => { const stack_0 = '0101010101010101010101010101010101010101010101010101010101010101'; const code = PUSH32 + stack_0; const data = ""; const resExpected = { errno: 0, errpc: code.length / 2, returnData: "", memSize: 0, mem: "", stack: [ new BigNumber(stack_0, 16) ], }; await runTest(code, data, resExpected); }); it('should run PUSH32 three times in a row successfully', async () => { const stack_0 = '0101010101010101010101010101010101010101010101010101010101010101'; const stack_1 = '0101010101010101010101010101010101010101010101010101010101010102'; const stack_2 = '0101010101010101010101010101010101010101010101010101010101010103'; const code = PUSH32 + stack_0 + PUSH32 + stack_1 + PUSH32 + stack_2; const data = ""; const resExpected = { errno: 0, errpc: code.length / 2, returnData: "", memSize: 0, mem: "", stack: [ new BigNumber(stack_0, 16), new BigNumber(stack_1, 16), new BigNumber(stack_2, 16) ], }; await runTest(code, data, resExpected); }); it('should run PUSH1 successfully', async () => { const stack_0 = '01'; const code = PUSH1 + stack_0; const data = ""; const resExpected = { errno: 0, errpc: code.length / 2, returnData: "", memSize: 0, mem: "", stack: [ new BigNumber(stack_0, 16) ], }; await runTest(code, data, resExpected); }); }); describe('dup ops', () => { it('should run DUP1 successfully', async () => { const stack_0 = '0101010101010101010101010101010101010101010101010101010101010101'; const code = PUSH32 + stack_0 + DUP1; const data = ""; const resExpected = { errno: 0, errpc: code.length / 2, returnData: "", memSize: 0, mem: "", stack: [ new BigNumber(stack_0, 16), new BigNumber(stack_0, 16) ], }; await runTest(code, data, resExpected); }); it('should run DUP16 sixteen times in a row successfully', async () => { const stack_0 = '0101010101010101010101010101010101010101010101010101010101010101'; const stack_1 = '0101010101010101010101010101010101010101010101010101010101010102'; const stack_2 = '0101010101010101010101010101010101010101010101010101010101010103'; const stack_3 = '0101010101010101010101010101010101010101010101010101010101010104'; const stack_4 = '0101010101010101010101010101010101010101010101010101010101010105'; const stack_5 = '0101010101010101010101010101010101010101010101010101010101010106'; const stack_6 = '0101010101010101010101010101010101010101010101010101010101010107'; const stack_7 = '0101010101010101010101010101010101010101010101010101010101010108'; const stack_8 = '0101010101010101010101010101010101010101010101010101010101010109'; const stack_9 = '010101010101010101010101010101010101010101010101010101010101010a'; const stack_10 = '010101010101010101010101010101010101010101010101010101010101010b'; const stack_11 = '010101010101010101010101010101010101010101010101010101010101010c'; const stack_12 = '010101010101010101010101010101010101010101010101010101010101010d'; const stack_13 = '010101010101010101010101010101010101010101010101010101010101010e'; const stack_14 = '010101010101010101010101010101010101010101010101010101010101010f'; const stack_15 = '0101010101010101010101010101010101010101010101010101010101010110'; const code = PUSH32 + stack_0 + PUSH32 + stack_1 + PUSH32 + stack_2 + PUSH32 + stack_3 + PUSH32 + stack_4 + PUSH32 + stack_5 + PUSH32 + stack_6 + PUSH32 + stack_7 + PUSH32 + stack_8 + PUSH32 + stack_9 + PUSH32 + stack_10 + PUSH32 + stack_11 + PUSH32 + stack_12 + PUSH32 + stack_13 + PUSH32 + stack_14 + PUSH32 + stack_15 + DUP16 + DUP16 + DUP16 + DUP16 + DUP16 + DUP16 + DUP16 + DUP16 + DUP16 + DUP16 + DUP16 + DUP16 + DUP16 + DUP16 + DUP16 + DUP16; const data = ""; const resExpected = { errno: 0, errpc: code.length / 2, returnData: "", memSize: 0, mem: "", stack: [ new BigNumber(stack_0, 16), new BigNumber(stack_1, 16), new BigNumber(stack_2, 16), new BigNumber(stack_3, 16), new BigNumber(stack_4, 16), new BigNumber(stack_5, 16), new BigNumber(stack_6, 16), new BigNumber(stack_7, 16), new BigNumber(stack_8, 16), new BigNumber(stack_9, 16), new BigNumber(stack_10, 16), new BigNumber(stack_11, 16), new BigNumber(stack_12, 16), new BigNumber(stack_13, 16), new BigNumber(stack_14, 16), new BigNumber(stack_15, 16), new BigNumber(stack_0, 16), new BigNumber(stack_1, 16), new BigNumber(stack_2, 16), new BigNumber(stack_3, 16), new BigNumber(stack_4, 16), new BigNumber(stack_5, 16), new BigNumber(stack_6, 16), new BigNumber(stack_7, 16), new BigNumber(stack_8, 16), new BigNumber(stack_9, 16), new BigNumber(stack_10, 16), new BigNumber(stack_11, 16), new BigNumber(stack_12, 16), new BigNumber(stack_13, 16), new BigNumber(stack_14, 16), new BigNumber(stack_15, 16) ], }; await runTest(code, data, resExpected); }); }); describe('swap ops', () => { it('should run SWAP1 successfully', async () => { const stack_0 = '0101010101010101010101010101010101010101010101010101010101010101'; const stack_1 = '0101010101010101010101010101010101010101010101010101010101010102'; const code = PUSH32 + stack_0 + PUSH32 + stack_1 + SWAP1; const data = ""; const resExpected = { errno: 0, errpc: code.length / 2, returnData: "", memSize: 0, mem: "", stack: [ new BigNumber(stack_1, 16), new BigNumber(stack_0, 16) ], }; await runTest(code, data, resExpected); }); it('should run SWAP1 to swap16 successfully', async () => { const stack_0 = '0101010101010101010101010101010101010101010101010101010101010101'; const stack_1 = '0101010101010101010101010101010101010101010101010101010101010102'; const stack_2 = '0101010101010101010101010101010101010101010101010101010101010103'; const stack_3 = '0101010101010101010101010101010101010101010101010101010101010104'; const stack_4 = '0101010101010101010101010101010101010101010101010101010101010105'; const stack_5 = '0101010101010101010101010101010101010101010101010101010101010106'; const stack_6 = '0101010101010101010101010101010101010101010101010101010101010107'; const stack_7 = '0101010101010101010101010101010101010101010101010101010101010108'; const stack_8 = '0101010101010101010101010101010101010101010101010101010101010109'; const stack_9 = '010101010101010101010101010101010101010101010101010101010101010a'; const stack_10 = '010101010101010101010101010101010101010101010101010101010101010b'; const stack_11 = '010101010101010101010101010101010101010101010101010101010101010c'; const stack_12 = '010101010101010101010101010101010101010101010101010101010101010d'; const stack_13 = '010101010101010101010101010101010101010101010101010101010101010e'; const stack_14 = '010101010101010101010101010101010101010101010101010101010101010f'; const stack_15 = '0101010101010101010101010101010101010101010101010101010101010110'; const stack_16 = '0101010101010101010101010101010101010101010101010101010101010111'; const code = PUSH32 + stack_0 + PUSH32 + stack_1 + PUSH32 + stack_2 + PUSH32 + stack_3 + PUSH32 + stack_4 + PUSH32 + stack_5 + PUSH32 + stack_6 + PUSH32 + stack_7 + PUSH32 + stack_8 + PUSH32 + stack_9 + PUSH32 + stack_10 + PUSH32 + stack_11 + PUSH32 + stack_12 + PUSH32 + stack_13 + PUSH32 + stack_14 + PUSH32 + stack_15 + PUSH32 + stack_16 + SWAP1 + SWAP2 + SWAP3 + SWAP4 + SWAP5 + SWAP6 + SWAP7 + SWAP8 + SWAP9 + SWAP10 + SWAP11 + SWAP12 + SWAP13 + SWAP14 + SWAP15 + SWAP16; const data = ""; const resExpected = { errno: 0, errpc: code.length / 2, returnData: "", memSize: 0, mem: "", stack: [ new BigNumber(stack_1, 16), new BigNumber(stack_2, 16), new BigNumber(stack_3, 16), new BigNumber(stack_4, 16), new BigNumber(stack_5, 16), new BigNumber(stack_6, 16), new BigNumber(stack_7, 16), new BigNumber(stack_8, 16), new BigNumber(stack_9, 16), new BigNumber(stack_10, 16), new BigNumber(stack_11, 16), new BigNumber(stack_12, 16), new BigNumber(stack_13, 16), new BigNumber(stack_14, 16), new BigNumber(stack_15, 16), new BigNumber(stack_16, 16), new BigNumber(stack_0, 16) ], }; await runTest(code, data, resExpected); }); }); describe('swap ops', () => { it('should run SWAP1 successfully', async () => { const stack_0 = '0101010101010101010101010101010101010101010101010101010101010101'; const stack_1 = '0101010101010101010101010101010101010101010101010101010101010102'; const code = PUSH32 + stack_0 + PUSH32 + stack_1 + SWAP1; const data = ""; const resExpected = { errno: 0, errpc: code.length / 2, returnData: "", memSize: 0, mem: "", stack: [ new BigNumber(stack_1, 16), new BigNumber(stack_0, 16) ], }; await runTest(code, data, resExpected); }); }); describe('system ops', () => { it('should run CREATE successfully', async () => { // CREATE with code that returns '00'. Third account should have '00' as code. const code = PUSH32 + '60016000f3000000000000000000000000000000000000000000000000000000' + PUSH1 + '00' + MSTORE + PUSH1 + '05' + PUSH1 + '00' + PUSH1 + '00' + CREATE; const data = ''; const resExpected = { errno: 0, errpc: code.length / 2, returnData: "", memSize: 32, mem: "60016000f3000000000000000000000000000000000000000000000000000000", stack: [ new BigNumber("5ecfbe86fcd903321c505cb5c8a5de6331e2e7b1", 16) ], }; const result = await runTest(code, data, resExpected); expect(result.accounts[2].code === "00"); }); it('should run CREATE twice, first failed, and only one account should be created', async () => { // CREATE failed contract, then a successful one. const code = PUSH32 + 'fe00000000000000000000000000000000000000000000000000000000000000' + PUSH1 + '00' + MSTORE + PUSH1 + '05' + PUSH1 + '00' + PUSH1 + '00' + CREATE + PUSH32 + '60016000f3000000000000000000000000000000000000000000000000000000' + PUSH1 + '00' + MSTORE + PUSH1 + '05' + PUSH1 + '00' + PUSH1 + '00' + CREATE; const data = ''; const resExpected = { errno: 0, errpc: code.length / 2, returnData: "", memSize: 32, mem: "60016000f3000000000000000000000000000000000000000000000000000000", stack: [ new BigNumber(0), new BigNumber("5ecfbe86fcd903321c505cb5c8a5de6331e2e7b1", 16) ], }; const result = await runTest(code, data, resExpected); expect(result.accounts[2].code === "00"); }); }); }); /* TODO describe('precompiles', () => { it('ecrecover', async () => { const code = PUSH1 + '20' + PUSH1 + '20' + PUSH1 + '80' + PUSH1 + '00' + PUSH1 + '01' + PUSH1 + '00' + STATICCALL; const data = ""; const result = await execute(code, data); prettyPrintResults(result); }); it('sha256', async () => { const code = PUSH1 + '20' + PUSH1 + '20' + PUSH1 + '20' + PUSH1 + '00' + PUSH1 + '02' + PUSH1 + '00' + STATICCALL; const data = ""; const result = await execute(code, data); prettyPrintResults(result); }); it('ripemd160', async () => { const code = PUSH1 + '20' + PUSH1 + '20' + PUSH1 + '20' + PUSH1 + '00' + PUSH1 + '03' + PUSH1 + '00' + STATICCALL; const data = ""; const result = await execute(code, data); prettyPrintResults(result); }); it('identity', async () => { const code = PUSH1 + '20' + PUSH1 + '20' + PUSH1 + '20' + PUSH1 + '00' + PUSH1 + '04' + PUSH1 + '00' + STATICCALL; const data = ""; const result = await execute(code, data); prettyPrintResults(result); }); }); */ describe('solidity contracts', () => { it('should call test function on TestContractNoop', async () => { const code = readText(path.join(BIN_OUTPUT_PATH, 'TestContractNoop.bin-runtime')); const result = await execute(code, CONTRACT_TEST_SIG); expect(result.errno).toBe(NO_ERROR); }); it('should call test function on TestContractRetUint', async () => { const code = readText(path.join(BIN_OUTPUT_PATH, 'TestContractRetUint.bin-runtime')); const result = await execute(code, CONTRACT_TEST_SIG); expect(result.errno).toBe(NO_ERROR); expect(result.returnData).toBe('0000000000000000000000000000000000000000000000000000000000000005'); }); it('should call test function on TestContractReverts', async () => { const code = readText(path.join(BIN_OUTPUT_PATH, 'TestContractReverts.bin-runtime')); const result = await execute(code, CONTRACT_TEST_SIG); expect(result.errno).toBe(ERROR_STATE_REVERTED); expect(result.returnData).toBe(''); }); it('should call test function on TestContractRevertsWithArgument', async () => { const code = readText(path.join(BIN_OUTPUT_PATH, 'TestContractRevertsWithArgument.bin-runtime')); const result = await execute(code, CONTRACT_TEST_SIG); expect(result.errno).toBe(ERROR_STATE_REVERTED); expect(result.returnData).toBe('08c379a0000000000000000000000000000000000000000000000000000000000000002000000000000000000000000000000000000000000000000000000000000000036162630000000000000000000000000000000000000000000000000000000000'); }); it('should call test function on TestContractCallsItself', async () => { const code = readText(path.join(BIN_OUTPUT_PATH, 'TestContractCallsItself.bin-runtime')); const result = await execute(code, CONTRACT_TEST_SIG); expect(result.errno).toBe(NO_ERROR); expect(result.returnData).toBe('0000000000000000000000000000000000000000000000000000000000000003'); }); it('should call test function on TestContractStorageWrite', async () => { const code = readText(path.join(BIN_OUTPUT_PATH, 'TestContractStorageWrite.bin-runtime')); const result = await execute(code, CONTRACT_TEST_SIG); expect(result.errno).toBe(NO_ERROR); const storage = result.accounts[1].storage; expect(storage.length).toBe(4); expect(storage[0].address.eq(new BigNumber(0))).toBeTruthy(); expect(storage[0].value.eq(new BigNumber(3))).toBeTruthy(); expect(storage[1].address.eq(new BigNumber('290decd9548b62a8d60345a988386fc84ba6bc95484008f6362f93160ef3e563', 16))).toBeTruthy(); expect(storage[1].value.eq(new BigNumber(0x11))).toBeTruthy(); expect(storage[2].address.eq(new BigNumber('290decd9548b62a8d60345a988386fc84ba6bc95484008f6362f93160ef3e564', 16))).toBeTruthy(); expect(storage[2].value.eq(new BigNumber(0x22))).toBeTruthy(); expect(storage[3].address.eq(new BigNumber('290decd9548b62a8d60345a988386fc84ba6bc95484008f6362f93160ef3e565', 16))).toBeTruthy(); expect(storage[3].value.eq(new BigNumber(0x33))).toBeTruthy(); expect(result.returnData).toBe(''); }); it('should call test function on TestContractStorageAndInternal', async () => { const code = readText(path.join(BIN_OUTPUT_PATH, 'TestContractStorageAndInternal.bin-runtime')); const result = await execute(code, CONTRACT_TEST_SIG); expect(result.errno).toBe(NO_ERROR); const storage = result.accounts[1].storage; expect(result.returnData).toBe('0000000000000000000000000000000000000000000000000000000000000009'); expect(storage[0].address.eq(new BigNumber(0))).toBeTruthy(); expect(storage[0].value.eq(new BigNumber(9))).toBeTruthy(); }); it('should create DeployedContractEmpty', async () => { const code = readText(path.join(BIN_OUTPUT_PATH, 'DeployedContractEmpty.bin')); const runtimeCode = readText(path.join(BIN_OUTPUT_PATH, 'DeployedContractEmpty.bin-runtime')); const result = await execute(code, CONTRACT_TEST_SIG); expect(result.returnData).toEqual(runtimeCode); expect(result.errno).toBe(NO_ERROR); }); it('should call test function on TestContractCreate', async () => { const code = readText(path.join(BIN_OUTPUT_PATH, 'TestContractCreate.bin-runtime')); const result = await execute(code, CONTRACT_TEST_SIG); expect(result.errno).toBe(NO_ERROR); expect(result.returnData).toBe('0000000000000000000000005ecfbe86fcd903321c505cb5c8a5de6331e2e7b1'); }); it('should call test function on TestContractCreateAndCall', async () => { const code = readText(path.join(BIN_OUTPUT_PATH, 'TestContractCreateAndCall.bin-runtime')); const result = await execute(code, CONTRACT_TEST_SIG); expect(result.errno).toBe(NO_ERROR); expect(result.returnData).toBe('0000000000000000000000000000000000000000000000000000000000000003'); }); it('should call test function on TestContractCreateAndStaticCall', async () => { const code = readText(path.join(BIN_OUTPUT_PATH, 'TestContractCreateAndStaticCall.bin-runtime')); const result = await execute(code, CONTRACT_TEST_SIG); expect(result.errno).toBe(NO_ERROR); expect(result.returnData).toBe('0000000000000000000000000000000000000000000000000000000000000003'); }); it('should call test function on TestContractCallchainSameContract', async () => { const code = readText(path.join(BIN_OUTPUT_PATH, 'TestContractCallchainSameContract.bin-runtime')); const result = await execute(code, CONTRACT_TEST_SIG); expect(result.errno).toBe(NO_ERROR); expect(result.returnData).toBe('0000000000000000000000000000000000000000000000000000000000000002'); }); it('should call test function on TestContractFailedAssertion', async () => { const code = readText(path.join(BIN_OUTPUT_PATH, 'TestContractFailedAssertion.bin-runtime')); const result = await execute(code, CONTRACT_TEST_SIG); expect(result.errno).toBe(ERROR_INVALID_OPCODE); }); it('should call test function on TestContractNoTopicEvent', async () => { const code = readText(path.join(BIN_OUTPUT_PATH, 'TestContractNoTopicEvent.bin-runtime')); const result = await execute(code, CONTRACT_TEST_SIG); expect(result.errno).toBe(NO_ERROR); expect(result.logs.length).toBe(1); const log = result.logs[0]; expect(log.account).toBe("0f572e5295c57f15886f9b263e2f6d2d6c7b5ec6"); expect(log.topics.length).toBe(4); expect(log.topics[0].eq(new BigNumber("1732d0c17008d342618e7f03069177d8d39391d79811bb4e706d7c6c84108c0f", 16))).toBeTruthy(); expect(log.topics[1].eq(new BigNumber(0))).toBeTruthy(); expect(log.topics[2].eq(new BigNumber(0))).toBeTruthy(); expect(log.topics[3].eq(new BigNumber(0))).toBeTruthy(); expect(log.data).toBe(""); }); it('should call test function on TestContractOneTopicEvent', async () => { const code = readText(path.join(BIN_OUTPUT_PATH, 'TestContractOneTopicEvent.bin-runtime')); const result = await execute(code, CONTRACT_TEST_SIG); expect(result.errno).toBe(NO_ERROR); expect(result.logs.length).toBe(1); const log = result.logs[0]; expect(log.account).toBe("0f572e5295c57f15886f9b263e2f6d2d6c7b5ec6"); expect(log.topics.length).toBe(4); expect(log.topics[0].eq(new BigNumber("624fb00c2ce79f34cb543884c3af64816dce0f4cec3d32661959e49d488a7a93", 16))).toBeTruthy(); expect(log.topics[1].eq(new BigNumber(5))).toBeTruthy(); expect(log.topics[2].eq(new BigNumber(0))).toBeTruthy(); expect(log.topics[3].eq(new BigNumber(0))).toBeTruthy(); expect(log.data).toBe(""); }); it('should call test function on TestContractTwoTopicsEvent', async () => { const code = readText(path.join(BIN_OUTPUT_PATH, 'TestContractTwoTopicsEvent.bin-runtime')); const result = await execute(code, CONTRACT_TEST_SIG); expect(result.errno).toBe(NO_ERROR); expect(result.logs.length).toBe(1); const log = result.logs[0]; expect(log.account).toBe("0f572e5295c57f15886f9b263e2f6d2d6c7b5ec6"); expect(log.topics.length).toBe(4); expect(log.topics[0].eq(new BigNumber("ebe57242c74e694c7ec0f2fe9302812f324576f94a505b0de3f0ecb473d149bb", 16))).toBeTruthy(); expect(log.topics[1].eq(new BigNumber(5))).toBeTruthy(); expect(log.topics[2].eq(new BigNumber(6))).toBeTruthy(); expect(log.topics[3].eq(new BigNumber(0))).toBeTruthy(); expect(log.data).toBe(""); }); it('should call test function on TestContractThreeTopicsEvent', async () => { const code = readText(path.join(BIN_OUTPUT_PATH, 'TestContractThreeTopicsEvent.bin-runtime')); const result = await execute(code, CONTRACT_TEST_SIG); expect(result.errno).toBe(NO_ERROR); expect(result.logs.length).toBe(1); const log = result.logs[0]; expect(log.account).toBe("0f572e5295c57f15886f9b263e2f6d2d6c7b5ec6"); expect(log.topics.length).toBe(4); expect(log.topics[0].eq(new BigNumber("8540fe9d62711b26f5d55a228125ce553737daafbb466fb5c89ffef0b5907d14", 16))).toBeTruthy(); expect(log.topics[1].eq(new BigNumber(5))).toBeTruthy(); expect(log.topics[2].eq(new BigNumber(6))).toBeTruthy(); expect(log.topics[3].eq(new BigNumber(7))).toBeTruthy(); expect(log.data).toBe(""); }); it('should call test function on TestContractDataEvent', async () => { const code = readText(path.join(BIN_OUTPUT_PATH, 'TestContractDataEvent.bin-runtime')); const result = await execute(code, CONTRACT_TEST_SIG); expect(result.errno).toBe(NO_ERROR); expect(result.logs.length).toBe(1); const log = result.logs[0]; expect(log.account).toBe("0f572e5295c57f15886f9b263e2f6d2d6c7b5ec6"); expect(log.topics.length).toBe(4); expect(log.topics[0].eq(new BigNumber("7e1e31b207b8694ac24cb269143e8ba879cc2fbc6def5fae514c8783140c48dc", 16))).toBeTruthy(); expect(log.topics[1].eq(new BigNumber(0))).toBeTruthy(); expect(log.topics[2].eq(new BigNumber(0))).toBeTruthy(); expect(log.topics[3].eq(new BigNumber(0))).toBeTruthy(); expect(log.data).toBe("00000000000000000000000000000000000000000000000000000000000000040000000000000000000000000000000000000000000000000000000000000005"); }); it('should call test function on TestContractThreeTopicsAndDataEvent', async () => { const code = readText(path.join(BIN_OUTPUT_PATH, 'TestContractThreeTopicsAndDataEvent.bin-runtime')); const result = await execute(code, CONTRACT_TEST_SIG); expect(result.errno).toBe(NO_ERROR); expect(result.logs.length).toBe(1); const log = result.logs[0]; expect(log.account).toBe("0f572e5295c57f15886f9b263e2f6d2d6c7b5ec6"); expect(log.topics.length).toBe(4); expect(log.topics[0].eq(new BigNumber("e9759a9398e9a2cc19ff163f90583422455643acd0b40fb4561be7d1df63b160", 16))).toBeTruthy(); expect(log.topics[1].eq(new BigNumber(5))).toBeTruthy(); expect(log.topics[2].eq(new BigNumber(6))).toBeTruthy(); expect(log.topics[3].eq(new BigNumber(7))).toBeTruthy(); expect(log.data).toBe("0000000000000000000000000f572e5295c57f15886f9b263e2f6d2d6c7b5ec6"); }); it('should call test function on TestContractMultipleThreeTopicsAndDataEvents', async () => { const code = readText(path.join(BIN_OUTPUT_PATH, 'TestContractMultipleThreeTopicsAndDataEvents.bin-runtime')); const result = await execute(code, CONTRACT_TEST_SIG); expect(result.errno).toBe(NO_ERROR); expect(result.logs.length).toBe(2); const log = result.logs[0]; expect(log.account).toBe("0f572e5295c57f15886f9b263e2f6d2d6c7b5ec6"); expect(log.topics.length).toBe(4); expect(log.topics[0].eq(new BigNumber("e9759a9398e9a2cc19ff163f90583422455643acd0b40fb4561be7d1df63b160", 16))).toBeTruthy(); expect(log.topics[1].eq(new BigNumber(5))).toBeTruthy(); expect(log.topics[2].eq(new BigNumber(6))).toBeTruthy(); expect(log.topics[3].eq(new BigNumber(7))).toBeTruthy(); expect(log.data).toBe("0000000000000000000000000f572e5295c57f15886f9b263e2f6d2d6c7b5ec6"); const log2 = result.logs[1]; expect(log2.account).toBe("0f572e5295c57f15886f9b263e2f6d2d6c7b5ec6"); expect(log2.topics.length).toBe(4); expect(log2.topics[0].eq(new BigNumber("aa2ecc4039583791812ce14fb62fff084d7d4ac354b47128d283d12b9ded2275", 16))).toBeTruthy(); expect(log2.topics[1].eq(new BigNumber(7))).toBeTruthy(); expect(log2.topics[2].eq(new BigNumber(8))).toBeTruthy(); expect(log2.topics[3].eq(new BigNumber(9))).toBeTruthy(); expect(log2.data).toBe("0000000000000000000000000f572e5295c57f15886f9b263e2f6d2d6c7b5ec6"); }); it('should call test function on TestContractPrecompileSha256', async () => { const code = readText(path.join(BIN_OUTPUT_PATH, 'TestContractPrecompileSha256.bin-runtime')); const result = await execute(code, CONTRACT_TEST_SIG); expect(result.errno).toBe(NO_ERROR); expect(result.returnData).toBe('66840dda154e8a113c31dd0ad32f7f3a366a80e8136979d8f5a101d3d29d6f72'); }); it('should call test function on TestContractPrecompileRipemd160', async () => { const code = readText(path.join(BIN_OUTPUT_PATH, 'TestContractPrecompileRipemd160.bin-runtime')); const result = await execute(code, CONTRACT_TEST_SIG); expect(result.errno).toBe(NO_ERROR); expect(result.returnData).toBe('c9883eece7dca619b830dc9d87e82c38478111c0000000000000000000000000'); }); it('should call test function on TestContractMultipleCreate', async () => { const code = readText(path.join(BIN_OUTPUT_PATH, 'TestContractMultipleCreate.bin-runtime')); const result = await execute(code, CONTRACT_TEST_SIG); // prettyPrintResults(result); expect(result.errno).toBe(NO_ERROR); expect(result.returnData).toBe('0000000000000000000000000000000000000000000000000000000000000005'); }); it('should call test function on TestContractCreateWithConstructorParams', async () => { const code = readText(path.join(BIN_OUTPUT_PATH, 'TestContractCreateWithConstructorParams.bin-runtime')); const result = await execute(code, CONTRACT_TEST_SIG); // prettyPrintResults(result); expect(result.errno).toBe(NO_ERROR); expect(result.returnData).toBe('00000000000000000000000000000000000000000000000000000000000000040000000000000000000000000000000000000000000000000000000000000005'); }); it('should call test function on TestContractCreatesPayable', async () => { const code = readText(path.join(BIN_OUTPUT_PATH, 'TestContractCreatesPayable.bin-runtime')); const input = createTxInput(code, CONTRACT_TEST_SIG, 3); input.value = new BigNumber(2); const result = await executeWithTxInput(input); // prettyPrintResults(result); expect(result.errno).toBe(NO_ERROR); expect(result.accounts.length).toBe(3); // should spread the 3 wei, 1 to each account. for (const acc of result.accounts) { expect(acc.balance.eq(1)).toBeTruthy(); } }); it('should call test function on TestContractSelfDestructs', async () => { const code = readText(path.join(BIN_OUTPUT_PATH, 'TestContractSelfDestructs.bin-runtime')); const input = createTxInput(code, CONTRACT_TEST_SIG, 55); const result = await executeWithTxInput(input); expect(result.errno).toBe(NO_ERROR); expect(result.accounts[1].balance.eq(0)).toBeTruthy(); expect(result.accounts[1].destroyed).toBeTruthy(); }); it('should call test function on TestContractCallsB', async () => { // Call should set the storage in contract 'TestContractCallsE' const code = readText(path.join(BIN_OUTPUT_PATH, 'TestContractCallsB.bin-runtime')); const input = createTxInput(code, CONTRACT_TEST_SIG); const result = await executeWithTxInput(input); expect(result.errno).toBe(NO_ERROR); const storage = result.accounts[3].storage; expect(storage[0].address.eq(0)).toBeTruthy(); expect(storage[0].value.eq(5)).toBeTruthy(); expect(storage[1].address.eq(1)).toBeTruthy(); expect(storage[1].value.eq("5ecfbe86fcd903321c505cb5c8a5de6331e2e7b1", 16)).toBeTruthy(); }); it('should call test function on TestContractCallsC', async () => { // Delegatecall should set the storage in contract 'TestContractCallsD' const code = readText(path.join(BIN_OUTPUT_PATH, 'TestContractCallsC.bin-runtime')); const input = createTxInput(code, CONTRACT_TEST_SIG); const result = await executeWithTxInput(input); expect(result.errno).toBe(NO_ERROR); const storage = result.accounts[2].storage; expect(storage[0].address.eq(0)).toBeTruthy(); expect(storage[0].value.eq(5)).toBeTruthy(); expect(storage[1].address.eq(1)).toBeTruthy(); expect(storage[1].value.eq("0f572e5295c57f15886f9b263e2f6d2d6c7b5ec6", 16)).toBeTruthy(); }); }); describe('solidity contracts - advanced', () => { it('should call test function on TestContractEVMStack', async () => { const code = readText(path.join(BIN_OUTPUT_PATH, 'TestContractEVMStack.bin-runtime')); const result = await execute(code, CONTRACT_TEST_SIG); expect(result.errno).toBe(NO_ERROR); }); });
the_stack
import { RequestUtil } from "mesosphere-shared-reactjs"; import * as repositoriesStream from "#PLUGINS/catalog/src/js/repositories/data/PackageRepositoryClient"; import { REQUEST_COSMOS_PACKAGES_LIST_SUCCESS, REQUEST_COSMOS_PACKAGES_SEARCH_ERROR, REQUEST_COSMOS_PACKAGES_SEARCH_SUCCESS, REQUEST_COSMOS_PACKAGES_LIST_ERROR, REQUEST_COSMOS_PACKAGE_DESCRIBE_ERROR, REQUEST_COSMOS_PACKAGE_DESCRIBE_SUCCESS, REQUEST_COSMOS_PACKAGE_INSTALL_ERROR, REQUEST_COSMOS_PACKAGE_INSTALL_SUCCESS, REQUEST_COSMOS_PACKAGE_UNINSTALL_ERROR, REQUEST_COSMOS_PACKAGE_UNINSTALL_SUCCESS, REQUEST_COSMOS_REPOSITORIES_LIST_SUCCESS, REQUEST_COSMOS_REPOSITORIES_LIST_ERROR, REQUEST_COSMOS_REPOSITORY_ADD_SUCCESS, REQUEST_COSMOS_REPOSITORY_ADD_ERROR, REQUEST_COSMOS_REPOSITORY_DELETE_SUCCESS, REQUEST_COSMOS_REPOSITORY_DELETE_ERROR, REQUEST_COSMOS_PACKAGE_LIST_VERSIONS_SUCCESS, REQUEST_COSMOS_PACKAGE_LIST_VERSIONS_ERROR, REQUEST_COSMOS_SERVICE_DESCRIBE_SUCCESS, REQUEST_COSMOS_SERVICE_DESCRIBE_ERROR, REQUEST_COSMOS_SERVICE_UPDATE_SUCCESS, REQUEST_COSMOS_SERVICE_UPDATE_ERROR, } from "../constants/ActionTypes"; import AppDispatcher from "./AppDispatcher"; import Config from "../config/Config"; import Util from "../utils/Util"; import getFixtureResponses from "../utils/getFixtureResponses"; function getContentType({ action, actionType, entity, version }) { return `application/vnd.dcos.${entity}.${action}-${actionType}+json;charset=utf-8;version=${version}`; } function getErrorMessage(response = {}) { if (typeof response === "string") { return response; } return response.description || response.message || "An error has occurred."; } const CosmosPackagesActions = { fetchAvailablePackages(query) { RequestUtil.json({ contentType: getContentType({ action: "search", actionType: "request", entity: "package", version: "v1", }), headers: { Accept: getContentType({ action: "search", actionType: "response", entity: "package", version: "v1", }), }, method: "POST", url: `${Config.rootUrl}${Config.cosmosAPIPrefix}/search`, data: JSON.stringify({ query }), success(response) { const packages = response.packages || []; const packageImages = {}; const data = packages.map((cosmosPackage) => { if (!cosmosPackage.resource) { cosmosPackage.resource = {}; } if (cosmosPackage.images) { cosmosPackage.resource.images = cosmosPackage.images; delete cosmosPackage.images; } packageImages[cosmosPackage.name] = cosmosPackage.resource.images; return cosmosPackage; }); AppDispatcher.handleServerAction({ type: REQUEST_COSMOS_PACKAGES_SEARCH_SUCCESS, data: { packages: data, images: packageImages }, query, }); }, error(xhr) { AppDispatcher.handleServerAction({ type: REQUEST_COSMOS_PACKAGES_SEARCH_ERROR, data: RequestUtil.parseResponseBody(xhr), query, xhr, }); }, }); }, fetchInstalledPackages(packageName, appId) { RequestUtil.json({ contentType: getContentType({ action: "list", actionType: "request", entity: "package", version: "v1", }), headers: { Accept: getContentType({ action: "list", actionType: "response", entity: "package", version: "v1", }), }, method: "POST", url: `${Config.rootUrl}${Config.cosmosAPIPrefix}/list`, data: JSON.stringify({ packageName, appId }), success(response) { const packages = response.packages || []; // Map list data to match other endpoint structures const data = packages.map((item) => { const cosmosPackage = Util.findNestedPropertyInObject( item, "packageInformation.packageDefinition" ) || {}; cosmosPackage.appId = item.appId; cosmosPackage.resource = Util.findNestedPropertyInObject( item, "packageInformation.resourceDefinition" ) || {}; if (cosmosPackage.images) { cosmosPackage.resource.images = cosmosPackage.images; delete cosmosPackage.images; } if (!cosmosPackage.currentVersion && cosmosPackage.version) { cosmosPackage.currentVersion = cosmosPackage.version; delete cosmosPackage.version; } return cosmosPackage; }); AppDispatcher.handleServerAction({ type: REQUEST_COSMOS_PACKAGES_LIST_SUCCESS, data, packageName, appId, }); }, error(xhr) { AppDispatcher.handleServerAction({ type: REQUEST_COSMOS_PACKAGES_LIST_ERROR, data: RequestUtil.getErrorFromXHR(xhr), packageName, appId, xhr, }); }, }); }, fetchPackageDescription(packageName, packageVersion) { RequestUtil.json({ contentType: getContentType({ action: "describe", actionType: "request", entity: "package", version: "v1", }), headers: { Accept: getContentType({ action: "describe", actionType: "response", entity: "package", version: "v3", }), }, method: "POST", url: `${Config.rootUrl}${Config.cosmosAPIPrefix}/describe`, data: JSON.stringify({ packageName, ...(packageVersion && { packageVersion }), }), success(response) { const cosmosPackage = response.package; AppDispatcher.handleServerAction({ type: REQUEST_COSMOS_PACKAGE_DESCRIBE_SUCCESS, data: cosmosPackage, packageName, packageVersion, }); }, error(xhr) { AppDispatcher.handleServerAction({ type: REQUEST_COSMOS_PACKAGE_DESCRIBE_ERROR, data: RequestUtil.getErrorFromXHR(xhr), packageName, packageVersion, xhr, }); }, }); }, fetchServiceDescription(serviceId) { RequestUtil.json({ contentType: getContentType({ action: "describe", actionType: "request", entity: "service", version: "v1", }), headers: { Accept: getContentType({ action: "describe", actionType: "response", entity: "service", version: "v1", }), }, method: "POST", url: `${Config.rootUrl}/cosmos/service/describe`, data: JSON.stringify({ appId: serviceId }), success(response) { AppDispatcher.handleServerAction({ type: REQUEST_COSMOS_SERVICE_DESCRIBE_SUCCESS, data: response, serviceId, }); }, error(xhr) { AppDispatcher.handleServerAction({ type: REQUEST_COSMOS_SERVICE_DESCRIBE_ERROR, data: RequestUtil.getErrorFromXHR(xhr), serviceId, xhr, }); }, }); }, updateService(serviceId, options) { RequestUtil.json({ contentType: getContentType({ action: "update", actionType: "request", entity: "service", version: "v1", }), headers: { Accept: getContentType({ action: "update", actionType: "response", entity: "service", version: "v1", }), }, method: "POST", url: `${Config.rootUrl}/cosmos/service/update`, data: JSON.stringify({ appId: serviceId, options, replace: true }), success() { AppDispatcher.handleServerAction({ type: REQUEST_COSMOS_SERVICE_UPDATE_SUCCESS, }); }, error(xhr) { AppDispatcher.handleServerAction({ type: REQUEST_COSMOS_SERVICE_UPDATE_ERROR, data: RequestUtil.parseResponseBody(xhr), xhr, }); }, }); }, fetchPackageVersions(packageName) { // necessary for the backend // even though it's not in use const includePackageVersions = false; RequestUtil.json({ contentType: getContentType({ action: "list-versions", actionType: "request", entity: "package", version: "v1", }), headers: { Accept: getContentType({ action: "list-versions", actionType: "response", entity: "package", version: "v1", }), }, method: "POST", url: `${Config.rootUrl}${Config.cosmosAPIPrefix}/list-versions`, data: JSON.stringify({ packageName, includePackageVersions }), success(response) { const packageVersions = response.results; AppDispatcher.handleServerAction({ type: REQUEST_COSMOS_PACKAGE_LIST_VERSIONS_SUCCESS, data: packageVersions, packageName, }); }, error(xhr) { AppDispatcher.handleServerAction({ type: REQUEST_COSMOS_PACKAGE_LIST_VERSIONS_ERROR, data: RequestUtil.getErrorFromXHR(xhr), packageName, xhr, }); }, }); }, installPackage(packageName, packageVersion, options = {}) { RequestUtil.json({ contentType: getContentType({ action: "install", actionType: "request", entity: "package", version: "v1", }), headers: { Accept: getContentType({ action: "install", actionType: "response", entity: "package", version: "v2", }), }, method: "POST", url: `${Config.rootUrl}${Config.cosmosAPIPrefix}/install`, data: JSON.stringify({ packageName, packageVersion, options }), success(response) { AppDispatcher.handleServerAction({ type: REQUEST_COSMOS_PACKAGE_INSTALL_SUCCESS, data: response, packageName, packageVersion, }); }, error(xhr) { AppDispatcher.handleServerAction({ type: REQUEST_COSMOS_PACKAGE_INSTALL_ERROR, data: RequestUtil.parseResponseBody(xhr), packageName, packageVersion, xhr, }); }, }); }, uninstallPackage(packageName, appId, all = false) { RequestUtil.json({ contentType: getContentType({ action: "uninstall", actionType: "request", entity: "package", version: "v1", }), headers: { Accept: getContentType({ action: "uninstall", actionType: "response", entity: "package", version: "v1", }), }, method: "POST", url: `${Config.rootUrl}${Config.cosmosAPIPrefix}/uninstall`, data: JSON.stringify({ packageName, appId, all }), success(response) { AppDispatcher.handleServerAction({ type: REQUEST_COSMOS_PACKAGE_UNINSTALL_SUCCESS, data: response, packageName, appId, }); }, error(xhr) { AppDispatcher.handleServerAction({ type: REQUEST_COSMOS_PACKAGE_UNINSTALL_ERROR, data: RequestUtil.parseResponseBody(xhr), packageName, appId, xhr, }); }, }); }, fetchRepositories(type) { repositoriesStream.fetchRepositories(type).subscribe( function success(response) { AppDispatcher.handleServerAction({ type: REQUEST_COSMOS_REPOSITORIES_LIST_SUCCESS, data: response.repositories, }); }, function error({ response }) { AppDispatcher.handleServerAction({ type: REQUEST_COSMOS_REPOSITORIES_LIST_ERROR, data: getErrorMessage(response), }); } ); }, addRepository(name, uri, index) { console.warn("DEPRECATED", "use the new data-layer approach"); repositoriesStream.addRepository(name, uri, index).subscribe( function success(response) { AppDispatcher.handleServerAction({ type: REQUEST_COSMOS_REPOSITORY_ADD_SUCCESS, data: response, name, uri, }); }, function error({ response }) { AppDispatcher.handleServerAction({ type: REQUEST_COSMOS_REPOSITORY_ADD_ERROR, data: getErrorMessage(response), name, uri, }); } ); }, deleteRepository(name, uri) { console.warn("DEPRECATED", "use the new data-layer approach"); repositoriesStream.deleteRepository(name, uri).subscribe( function success(response) { AppDispatcher.handleServerAction({ type: REQUEST_COSMOS_REPOSITORY_DELETE_SUCCESS, data: response, name, uri, }); }, function error({ response }) { AppDispatcher.handleServerAction({ type: REQUEST_COSMOS_REPOSITORY_DELETE_ERROR, data: getErrorMessage(response), name, uri, }); } ); }, }; if (Config.useFixtures) { const methodFixtureMapping = { fetchPackageDescription: import( /* webpackChunkName: "packageDescribeFixture" */ "../../../tests/_fixtures/cosmos/package-describe.json" ), fetchPackageVersions: import( /* webpackChunkName: "packageListVersionsFixture" */ "../../../tests/_fixtures/cosmos/package-list-versions.json" ), fetchServiceDescription: import( /* webpackChunkName: "serviceDescribeFixture" */ "../../../tests/_fixtures/cosmos/service-describe.json" ), fetchInstalledPackages: import( /* webpackChunkName: "packagesListFixture" */ "../../../tests/_fixtures/cosmos/packages-list.json" ), fetchAvailablePackages: import( /* webpackChunkName: "packagesSearchFixture" */ "../../../tests/_fixtures/cosmos/packages-search.json" ), fetchRepositories: import( /* webpackChunkName: "packagesRepositoriesFixture" */ "../../../tests/_fixtures/cosmos/packages-repositories.json" ), }; if (!window.actionTypes) { window.actionTypes = {}; } Promise.all( Object.keys(methodFixtureMapping).map( (method) => methodFixtureMapping[method] ) ).then((responses) => { window.actionTypes.CosmosPackagesActions = Object.assign( getFixtureResponses(methodFixtureMapping, responses), { updateService: { event: "success" }, installPackage: { event: "success" }, uninstallPackage: { event: "success" }, addRepository: { event: "success" }, deleteRepository: { event: "success" }, } ); Object.keys(window.actionTypes.CosmosPackagesActions).forEach((method) => { CosmosPackagesActions[method] = RequestUtil.stubRequest( CosmosPackagesActions, "CosmosPackagesActions", method ); }); }); } export default CosmosPackagesActions;
the_stack
import { Component, EventEmitter, Input, OnInit, Output, ViewChild, ElementRef, Renderer2 } from '@angular/core'; import { clamp } from 'lodash'; import { Subject, Observable, of as observableOf } from 'rxjs'; import { debounceTime, switchMap, distinctUntilChanged } from 'rxjs/operators'; import { FilterC } from '../types'; import * as moment from 'moment/moment'; import { Chicklet } from 'app/types/types'; import { ReportQueryService, SuggestionsService } from 'app/pages/+compliance/shared/reporting'; import { DateTime } from 'app/helpers/datetime/datetime'; @Component({ selector: 'app-reporting-searchbar', templateUrl: './reporting-searchbar.component.html', styleUrls: ['./reporting-searchbar.component.scss'] }) export class ReportingSearchbarComponent implements OnInit { @Input() date = moment().utc(); @Input() last24h = true; @Input() filters: FilterC[] = []; @Input() filterTypes = []; @Input() filterValues = []; @Output() suggestValues = new EventEmitter(); @Output() filtersCleared = new EventEmitter(); @Output() filterRemoved = new EventEmitter(); @Output() filterAdded = new EventEmitter(); @Output() dateChanged = new EventEmitter(); @Output() last24Selected = new EventEmitter(); @ViewChild('keyInput', { static: true }) keyInput: ElementRef; @ViewChild('valInput', { static: true }) valInput: ElementRef; private suggestionsVisibleStream = new Subject<boolean>(); private suggestionSearchTermDebounce = new Subject<any>(); public CHEF_SHORT_DATE = DateTime.CHEF_SHORT_DATE; filterTypesCategories = []; calendarMenuVisible = false; calendarVisible = false; keyInputVisible = true; valInputVisible = false; filtersVisible = true; suggestionsVisible = false; isLoadingSuggestions = false; visibleDate: moment.Moment; selectedType; highlightedIndex = -1; inputText = ''; delayForNoSuggestions = false; constructor( public reportQuery: ReportQueryService, public sugg: SuggestionsService, private renderer: Renderer2 ) { // This is needed because focus is lost when clicking items. this.suggestionsVisibleStream.pipe( // wait 0.2 seconds after each lost and gain focus debounceTime(300), // switch to the latest focus change switchMap((active: boolean): Observable<boolean> => { return observableOf(active); }) ).subscribe((active: boolean) => { this.delayForNoSuggestions = false; this.suggestionsVisible = active; }); this.suggestionSearchTermDebounce.pipe( // wait 1/3 second after each keystroke before considering the term debounceTime(300), // ignore new term if same as previous term distinctUntilChanged() ).subscribe((c: any) => { this.suggestValues.emit({ detail: c}); this.isLoadingSuggestions = true; setTimeout(() => { this.isLoadingSuggestions = false; }, 500); setTimeout(() => { this.delayForNoSuggestions = true; }, 800); }); } ngOnInit() { this.isLoadingSuggestions = false; this.visibleDate = moment.utc(this.date); this.filterTypesCategories = JSON.parse(JSON.stringify(this.filterTypes)); } ngOnChange() { } toggleFilters() { this.filtersVisible = !this.filtersVisible; } hideFilters() { this.filtersVisible = false; } showFilters() { this.filtersVisible = true; } toggleCalendarMenu() { this.calendarMenuVisible = !this.calendarMenuVisible; } hideCalendarMenu() { this.calendarMenuVisible = false; } showCalendarMenu() { this.calendarMenuVisible = true; } toggleCalendar() { this.calendarVisible = !this.calendarVisible; } hideCalendar() { this.calendarVisible = false; } showCalendar() { this.calendarVisible = true; } handleSelectLast24() { this.last24Selected.emit(); } handleFocus(event: Event): void { event.stopPropagation(); this.suggestionsVisibleStream.next(true); } handleSuggestionItemOnMouseOver(index: number): void { this.highlightedIndex = index; } handleInput(key, currentText): void { switch (key.toLowerCase()) { case 'arrowdown': this.pressArrowDown(); break; case 'arrowup': this.pressArrowUp(); break; case 'arrowleft': this.suggestionsVisible = true; break; case 'arrowright': this.suggestionsVisible = true; break; case 'enter': this.pressEnter(currentText); break; case 'backspace': this.pressBackspace(currentText); break; case 'escape': this.suggestionsVisible = false; break; default: this.pressDefaultText(currentText); break; } } pressArrowDown(): void { const downList = (this.selectedType) ? this.filterValues : this.filterTypes; this.highlightedIndex = clamp( this.highlightedIndex + 1, -1, downList.length - 1 ); this.suggestionsVisible = true; } pressArrowUp(): void { const upList = (this.selectedType) ? this.filterValues : this.filterTypes; this.highlightedIndex = clamp( this.highlightedIndex + -1, -1, upList.length - 1 ); this.suggestionsVisible = true; } pressEnter(currentText: string): void { if (this.selectedType) { this.pressEnterCategorySelected(currentText); } else { if (this.filterTypes.length > 0) { if (this.highlightedIndex >= 0) { const type = this.filterTypes[this.highlightedIndex]; this.categorySelected(type); } else if (this.filterTypes.length === 1) { const type = this.filterTypes[0]; this.categorySelected(type); } this.suggestionsVisible = true; this.showValInput(); } } } pressEnterCategorySelected(currentText: string): void { if (this.highlightedIndex >= 0) { const search = this.filterValues[this.highlightedIndex]; const type = this.selectedType; if (type.name === 'control_tag_key') { this.onControlTagKeyValueClick(search); } else { this.ClearAll(); this.suggestionsVisible = false; this.filterAdded.emit({ detail: { value: search, type: type } }); } } else { if (currentText.indexOf('?') >= 0 || currentText.indexOf('*') >= 0) { const type = this.selectedType; this.ClearAll(); this.filterAdded.emit({ detail: { value: currentText, type: type } }); } else if (this.filterValues.length > 0) { const foundSuggestion = this.filterValues.find((suggestion: string, _key: number, _iter: any) => suggestion === currentText); if (foundSuggestion) { const type = this.selectedType; this.ClearAll(); this.filterAdded.emit({ detail: { value: foundSuggestion, type: type } }); } } } this.showKeyInput(); setTimeout(() => { this.renderer.selectRootElement('#keyInput').focus(); }, 10); } pressDefaultText(currentText: string): void { if (this.selectedType) { const type = this.selectedType.name; this.clearSuggestions(); this.requestForSuggestions({ text: currentText, type: type, type_key: this.sugg.selectedControlTagKey }); this.inputText = currentText; } else { this.updateVisibleCategories(currentText); } this.suggestionsVisible = true; } pressBackspace(currentText: string): void { if (this.selectedType) { if (this.inputText === '') { this.clearFilterCategories(); this.showKeyInput(); setTimeout(() => { this.keyInput.nativeElement.value = currentText; this.keyInput.nativeElement.focus(); }, 10); } else { const type = this.selectedType.name; this.clearSuggestions(); this.requestForSuggestions({ text: currentText, type: type, type_key: this.sugg.selectedControlTagKey }); this.showValInput(); this.inputText = currentText; } } else { if (this.keyInput.nativeElement.value === '') { this.clearFilterCategories(); } else { this.updateVisibleCategories(currentText); } this.showKeyInput(); this.keyInput.nativeElement.value = currentText; } } updateVisibleCategories(currentText: string): void { this.highlightedIndex = -1; this.filterTypes = JSON.parse(JSON.stringify(this.filterTypesCategories)); this.filterTypes = this.filterTypes.filter(cat => { return cat.title.toLowerCase().indexOf(currentText.toLowerCase()) !== -1; }); } categorySelected(type: any): void { this.selectedType = type; this.highlightedIndex = -1; this.inputText = ''; setTimeout(() => { this.keyInput.nativeElement.value = ''; this.valInput.nativeElement.focus(); }, 10); } filterClick(type, event: Event) { if (!this.selectedType) { this.categorySelected(type); } event.stopPropagation(); this.showValInput(); this.suggestionsVisible = false; setTimeout(() => this.renderer.selectRootElement('#valInput').focus(), 10); } valueClick(value: any, event: Event) { const type = this.selectedType; event.stopPropagation(); this.suggestionsVisible = false; if (type.name === 'control_tag_key') { this.onControlTagKeyValueClick(value); } else { this.ClearAll(); this.filterAdded.emit({ detail: { type: type, value: value } }); this.showKeyInput(); this.inputText = ''; this.keyInput.nativeElement.value = ''; setTimeout(() => { this.renderer.selectRootElement('#keyInput').focus(); }, 10); this.suggestionsVisibleStream.next(false); } } onKeyChange(e) { const type = this.filterTypes.filter(t => t.title === e.target.value)[0]; const text = ''; if (type) { this.selectedType = type; this.suggestValues.emit({ detail: { type: type.name, text } }); this.showValInput(); setTimeout(() => { this.valInput.nativeElement.focus(); }, 10); } } onValKeydown(e) { const text = e.target.value; if (e.keyCode === 8 && text.length === 0) { this.selectedType = undefined; this.showKeyInput(); setTimeout(() => { this.keyInput.nativeElement.value = ''; this.keyInput.nativeElement.focus(); }, 10); } } onValInputAndFocus(e) { this.delayForNoSuggestions = false; const type = this.selectedType.name; const text = e.target.value; this.clearSuggestions(); this.requestForSuggestions({ text: text, type: type, type_key: this.sugg.selectedControlTagKey }); this.suggestionsVisibleStream.next(true); } onValChange(e) { const type = this.selectedType; const text: string = e.target.value; const suggestionValue = this.filterValues.filter(v => v.title === text)[0]; if (this.containsWildcardChar(text)) { const wildcardValue = { text, title: text }; this.addNewFilter(type, wildcardValue); } else if (suggestionValue && suggestionValue === undefined) { this.addNewFilter(type, suggestionValue); } } private containsWildcardChar(text: string): boolean { return (text.indexOf('?') >= 0 || text.indexOf('*') >= 0); } private addNewFilter(type, value) { this.filterAdded.emit({ detail: { type, value } }); this.selectedType = undefined; this.showKeyInput(); this.inputText = ''; setTimeout(() => { this.keyInput.nativeElement.value = ''; this.valInput.nativeElement.focus(); }, 10); } onClearClick() { this.filtersCleared.emit(); } onRemoveFilterClick(filter) { this.filterRemoved.emit({ detail: filter }); } // month - month with January 0 and December 11 // year - 4 digit year (2019) onMonthSelect([month, year]) { this.visibleDate.month(month); this.visibleDate.year(year); } onDaySelect(date: string) { const m = moment.utc(date); this.visibleDate.date(m.date()); this.visibleDate.month(m.month()); this.visibleDate.year(m.year()); this.dateChanged.emit({ detail: date }); } handleFocusOut() { this.suggestionsVisibleStream.next(false); } clearSuggestions(): void { this.filterValues = []; this.highlightedIndex = -1; } clearFilterCategories(): void { this.selectedType = undefined; this.filterTypes = JSON.parse(JSON.stringify(this.filterTypesCategories)); this.highlightedIndex = -1; } ClearAll() { this.clearFilterCategories(); this.clearSuggestions(); this.highlightedIndex = -1; } requestForSuggestions(c: Chicklet): void { if (c.type) { c.type = this.formatType(c.type); this.suggestionSearchTermDebounce.next(c); } } // hide value input and show key input showKeyInput() { this.valInputVisible = false; this.keyInputVisible = true; } // hide key input and show value input showValInput() { this.keyInputVisible = false; this.valInputVisible = true; } formatType(type: any) { // format the type value when control tag key is selected. return type.search('control_tag:') === 0 ? 'control_tag_value' : type; } public displayText(text: string): string { return text === '' ? 'no value' : text; } // When value is clicked for the control tag key onControlTagKeyValueClick(value: any) { const type = this.selectedType; type.name = `control_tag:${value.text}`; type.title = `Control Tag | ${value.text}`; type.placeholder = 'Enter Control Tag Values...'; this.clearSuggestions(); this.sugg.selectedControlTagKey = type.name; this.requestForSuggestions({ type: 'control_tag_value', text: '', // for control tag key filters, we want to send that info as a diff field on the api type_key: type.name }); this.suggestionsVisibleStream.next(true); } }
the_stack
import type { Faker } from '../..'; import { FakerError } from '../../errors/faker-error'; import { deprecated } from '../../internal/deprecated'; import type { LiteralUnion } from '../../utils/types'; export type Casing = 'upper' | 'lower' | 'mixed'; const UPPER_CHARS: readonly string[] = 'ABCDEFGHIJKLMNOPQRSTUVWXYZ'.split(''); const LOWER_CHARS: readonly string[] = 'abcdefghijklmnopqrstuvwxyz'.split(''); const DIGIT_CHARS: readonly string[] = '0123456789'.split(''); export type LowerAlphaChar = | 'a' | 'b' | 'c' | 'd' | 'e' | 'f' | 'g' | 'h' | 'i' | 'j' | 'k' | 'l' | 'm' | 'n' | 'o' | 'p' | 'q' | 'r' | 's' | 't' | 'u' | 'v' | 'w' | 'x' | 'y' | 'z'; export type UpperAlphaChar = | 'A' | 'B' | 'C' | 'D' | 'E' | 'F' | 'G' | 'H' | 'I' | 'J' | 'K' | 'L' | 'M' | 'N' | 'O' | 'P' | 'Q' | 'R' | 'S' | 'T' | 'U' | 'V' | 'W' | 'X' | 'Y' | 'Z'; export type NumericChar = | '0' | '1' | '2' | '3' | '4' | '5' | '6' | '7' | '8' | '9'; export type AlphaChar = LowerAlphaChar | UpperAlphaChar; export type AlphaNumericChar = AlphaChar | NumericChar; /** * Method to reduce array of characters. * * @param arr existing array of characters * @param values array of characters which should be removed * @returns new array without banned characters */ function arrayRemove<T>(arr: T[], values: readonly T[]): T[] { values.forEach((value) => { arr = arr.filter((ele) => ele !== value); }); return arr; } /** * Generates random values of different kinds. */ export class Random { constructor(private readonly faker: Faker) { // Bind `this` so namespaced is working correctly for (const name of Object.getOwnPropertyNames(Random.prototype)) { if (name === 'constructor' || typeof this[name] !== 'function') { continue; } this[name] = this[name].bind(this); } } /** * Returns random word. * * @example * faker.random.word() // 'Seamless' */ word(): string { const wordMethods = [ this.faker.commerce.department, this.faker.commerce.productName, this.faker.commerce.productAdjective, this.faker.commerce.productMaterial, this.faker.commerce.product, this.faker.color.human, this.faker.company.catchPhraseAdjective, this.faker.company.catchPhraseDescriptor, this.faker.company.catchPhraseNoun, this.faker.company.bsAdjective, this.faker.company.bsBuzz, this.faker.company.bsNoun, this.faker.address.streetSuffix, this.faker.address.county, this.faker.address.country, this.faker.address.state, this.faker.finance.accountName, this.faker.finance.transactionType, this.faker.finance.currencyName, this.faker.hacker.noun, this.faker.hacker.verb, this.faker.hacker.adjective, this.faker.hacker.ingverb, this.faker.hacker.abbreviation, this.faker.name.jobDescriptor, this.faker.name.jobArea, this.faker.name.jobType, ]; const bannedChars = [ '!', '#', '%', '&', '*', ')', '(', '+', '=', '.', '<', '>', '{', '}', '[', ']', ':', ';', "'", '"', '_', '-', ]; let result: string; do { // randomly pick from the many faker methods that can generate words const randomWordMethod = this.faker.helpers.arrayElement(wordMethods); result = randomWordMethod(); } while (!result || bannedChars.some((char) => result.includes(char))); return this.faker.helpers.arrayElement(result.split(' ')); } /** * Returns string with set of random words. * * @param count Number of words. Defaults to a random value between `1` and `3`. * * @example * faker.random.words() // 'neural' * faker.random.words(5) // 'copy Handcrafted bus client-server Point' */ words(count?: number): string { const words: string[] = []; if (count == null) { count = this.faker.datatype.number({ min: 1, max: 3 }); } for (let i = 0; i < count; i++) { words.push(this.word()); } return words.join(' '); } /** * Returns a random locale, that is available in this faker instance. * You can use the returned locale with `faker.setLocale(result)`. * * @example * faker.random.locale() // 'el' */ locale(): string { return this.faker.helpers.arrayElement(Object.keys(this.faker.locales)); } /** * Generating a string consisting of letters in the English alphabet. * * @param options Either the number of characters or an options instance. Defaults to `{ count: 1, casing: 'lower', bannedChars: [] }`. * @param options.count The number of characters to generate. Defaults to `1`. * @param options.casing The casing of the characters. Defaults to `'lower'`. * @param options.upcase Deprecated, use `casing: 'upper'` instead. * @param options.bannedChars An array with characters to exclude. Defaults to `[]`. * * @example * faker.random.alpha() // 'b' * faker.random.alpha(10) // 'qccrabobaf' * faker.random.alpha({ count: 5, casing: 'upper', bannedChars: ['A'] }) // 'DTCIC' */ // TODO @Shinigami92 2022-02-14: Tests covered `(count, options)`, but they were never typed like that alpha( options: | number | { count?: number; /** * @deprecated Use `casing` instead. */ upcase?: boolean; casing?: Casing; bannedChars?: readonly LiteralUnion<AlphaChar>[] | string; } = {} ): string { if (typeof options === 'number') { options = { count: options, }; } const { count = 1, upcase } = options; let { bannedChars = [] } = options; if (typeof bannedChars === 'string') { bannedChars = bannedChars.split(''); } if (count <= 0) { return ''; } const { // Switch to 'mixed' with v8.0 casing = upcase ? 'upper' : 'lower', } = options; if (upcase != null) { deprecated({ deprecated: 'faker.random.alpha({ upcase: true })', proposed: "faker.random.alpha({ casing: 'upper' })", since: 'v7.0', until: 'v8.0', }); } let charsArray: string[]; switch (casing) { case 'upper': charsArray = [...UPPER_CHARS]; break; case 'lower': charsArray = [...LOWER_CHARS]; break; case 'mixed': default: charsArray = [...LOWER_CHARS, ...UPPER_CHARS]; break; } charsArray = arrayRemove(charsArray, bannedChars); if (charsArray.length === 0) { throw new FakerError( 'Unable to generate string, because all possible characters are banned.' ); } return Array.from({ length: count }, () => this.faker.helpers.arrayElement(charsArray) ).join(''); } /** * Generating a string consisting of alpha characters and digits. * * @param count The number of characters and digits to generate. Defaults to `1`. * @param options The options to use. Defaults to `{ bannedChars: [] }`. * @param options.casing The casing of the characters. Defaults to `'lower'`. * @param options.bannedChars An array of characters and digits which should be banned in the generated string. Defaults to `[]`. * * @example * faker.random.alphaNumeric() // '2' * faker.random.alphaNumeric(5) // '3e5v7' * faker.random.alphaNumeric(5, { bannedChars: ["a"] }) // 'xszlm' */ alphaNumeric( count: number = 1, options: { casing?: Casing; bannedChars?: readonly LiteralUnion<AlphaNumericChar>[] | string; } = {} ): string { if (count <= 0) { return ''; } const { // Switch to 'mixed' with v8.0 casing = 'lower', } = options; let { bannedChars = [] } = options; if (typeof bannedChars === 'string') { bannedChars = bannedChars.split(''); } let charsArray = [...DIGIT_CHARS]; switch (casing) { case 'upper': charsArray.push(...UPPER_CHARS); break; case 'lower': charsArray.push(...LOWER_CHARS); break; case 'mixed': default: charsArray.push(...LOWER_CHARS, ...UPPER_CHARS); break; } charsArray = arrayRemove(charsArray, bannedChars); if (charsArray.length === 0) { throw new FakerError( 'Unable to generate string, because all possible characters are banned.' ); } return Array.from({ length: count }, () => this.faker.helpers.arrayElement(charsArray) ).join(''); } /** * Generates a given length string of digits. * * @param length The number of digits to generate. Defaults to `1`. * @param options The options to use. Defaults to `{}`. * @param options.allowLeadingZeros If true, leading zeros will be allowed. Defaults to `false`. * @param options.bannedDigits An array of digits which should be banned in the generated string. Defaults to `[]`. * * @example * faker.random.numeric() // '2' * faker.random.numeric(5) // '31507' * faker.random.numeric(42) // '56434563150765416546479875435481513188548' * faker.random.numeric(42, { allowLeadingZeros: true }) // '00564846278453876543517840713421451546115' * faker.random.numeric(6, { bannedDigits: ['0'] }) // '943228' */ numeric( length: number = 1, options: { allowLeadingZeros?: boolean; bannedDigits?: readonly LiteralUnion<NumericChar>[] | string; } = {} ): string { if (length <= 0) { return ''; } const { allowLeadingZeros = false } = options; let { bannedDigits = [] } = options; if (typeof bannedDigits === 'string') { bannedDigits = bannedDigits.split(''); } const allowedDigits = DIGIT_CHARS.filter( (digit) => !bannedDigits.includes(digit) ); if ( allowedDigits.length === 0 || (allowedDigits.length === 1 && !allowLeadingZeros && allowedDigits[0] === '0') ) { throw new FakerError( 'Unable to generate numeric string, because all possible digits are banned.' ); } let result = ''; if (!allowLeadingZeros && !bannedDigits.includes('0')) { result += this.faker.helpers.arrayElement( allowedDigits.filter((digit) => digit !== '0') ); } while (result.length < length) { result += this.faker.helpers.arrayElement(allowedDigits); } return result; } }
the_stack
import {xliffDigest, xliffLoadToI18n, xliffLoadToXml, xliffWrite} from "../../lib/src/serializers/xliff"; import {MessageBundle} from "../../lib/extractor/src/message-bundle"; const XLIFF = `<?xml version="1.0" encoding="UTF-8" ?> <xliff version="1.2" xmlns="urn:oasis:names:tc:xliff:document:1.2"> <file source-language="en" target-language="fr" datatype="plaintext" original="ng2.template"> <body> <trans-unit id="983775b9a51ce14b036be72d4cfd65d68d64e231" datatype="html"> <source>translatable attribute</source> <target>etubirtta elbatalsnart</target> <context-group purpose="location"> <context context-type="sourcefile">file.ts</context> <context context-type="linenumber">1</context> </context-group> </trans-unit> <trans-unit id="ec1d033f2436133c14ab038286c4f5df4697484a" datatype="html"> <source>translatable element <x id="START_BOLD_TEXT" ctype="b"/>with placeholders<x id="CLOSE_BOLD_TEXT" ctype="b"/> <x id="INTERPOLATION"/></source> <target><x id="INTERPOLATION"/> footnemele elbatalsnart <x id="START_BOLD_TEXT" ctype="x-b"/>sredlohecalp htiw<x id="CLOSE_BOLD_TEXT" ctype="x-b"/></target> </trans-unit> <trans-unit id="e2ccf3d131b15f54aa1fcf1314b1ca77c14bfcc2" datatype="html"> <source>{VAR_PLURAL, plural, =0 {<x id="START_PARAGRAPH" ctype="x-p"/>test<x id="CLOSE_PARAGRAPH" ctype="x-p"/>} }</source> <target>{VAR_PLURAL, plural, =0 {<x id="START_PARAGRAPH" ctype="x-p"/>TEST<x id="CLOSE_PARAGRAPH" ctype="x-p"/>} }</target> </trans-unit> <trans-unit id="db3e0a6a5a96481f60aec61d98c3eecddef5ac23" datatype="html"> <source>foo</source> <target>oof</target> </trans-unit> <trans-unit id="i" datatype="html"> <source>foo</source> <target>toto</target> </trans-unit> <trans-unit id="bar" datatype="html"> <source>foo</source> <target>tata</target> </trans-unit> <trans-unit id="d7fa2d59aaedcaa5309f13028c59af8c85b8c49d" datatype="html"> <source><x id="LINE_BREAK" ctype="lb"/><x id="TAG_IMG" ctype="image"/><x id="START_TAG_DIV" ctype="x-div"/><x id="CLOSE_TAG_DIV" ctype="x-div"/></source> <target><x id="START_TAG_DIV" ctype="x-div"/><x id="CLOSE_TAG_DIV" ctype="x-div"/><x id="TAG_IMG" ctype="image"/><x id="LINE_BREAK" ctype="lb"/></target> </trans-unit> <trans-unit id="empty target" datatype="html"> <source><x id="LINE_BREAK" ctype="lb"/><x id="TAG_IMG" ctype="image"/><x id="START_TAG_DIV" ctype="x-div"/><x id="CLOSE_TAG_DIV" ctype="x-div"/></source> <target/> </trans-unit> <trans-unit id="baz" datatype="html"> <source>{VAR_PLURAL, plural, =0 {{VAR_SELECT, select, other {<x id="START_PARAGRAPH" ctype="x-p"/>deeply nested<x id="CLOSE_PARAGRAPH" ctype="x-p"/>} } } }</source> <target>{VAR_PLURAL, plural, =0 {{VAR_SELECT, select, other {<x id="START_PARAGRAPH" ctype="x-p"/>profondément imbriqué<x id="CLOSE_PARAGRAPH" ctype="x-p"/>} } } }</target> </trans-unit> <trans-unit id="52ffa620dcd76247a56d5331f34e73f340a43cdb" datatype="html"> <source>Test: <x id="ICU" equiv-text="{ count, plural, =0 {...} =other {...}}"/></source> <target>Test: <x id="ICU" equiv-text="{ count, plural, =0 {...} =other {...}}"/></target> </trans-unit> <trans-unit id="1503afd0ccc20ff01d5e2266a9157b7b342ba494" datatype="html"> <source>{VAR_PLURAL, plural, =0 {{VAR_SELECT, select, other {<x id="START_PARAGRAPH" ctype="x-p"/>deeply nested<x id="CLOSE_PARAGRAPH" ctype="x-p"/>} } } =other {a lot} }</source> <target>{VAR_PLURAL, plural, =0 {{VAR_SELECT, select, other {<x id="START_PARAGRAPH" ctype="x-p"/>profondément imbriqué<x id="CLOSE_PARAGRAPH" ctype="x-p"/>} } } =other {beaucoup} }</target> </trans-unit> <trans-unit id="fcfa109b0e152d4c217dbc02530be0bcb8123ad1" datatype="html"> <source>multi lines</source> <target>multi lignes</target> </trans-unit> </body> </file> </xliff> `; describe("Xliff serializer", () => { it("should decode xliff", () => { const loaded = xliffLoadToI18n(XLIFF); expect(loaded["1503afd0ccc20ff01d5e2266a9157b7b342ba494"]).toBeDefined(); }); it("should write xliff", () => { const messageBundle = new MessageBundle("en"); messageBundle.updateFromTemplate("This is a test message {sex, select, other {deeply nested}}", "file.ts"); expect(messageBundle.write(xliffWrite, xliffDigest)).toEqual(`<?xml version="1.0" encoding="UTF-8" ?> <xliff version="1.2" xmlns="urn:oasis:names:tc:xliff:document:1.2"> <file source-language="en" datatype="plaintext" original="ng2.template"> <body> <trans-unit id="9161da7236814a71c5fec94eb42161651f6b4967" datatype="html"> <source>This is a test message <x id="ICU" equiv-text="{sex, select, other {...}}"/></source> <context-group purpose="location"> <context context-type="sourcefile">file.ts</context> <context context-type="linenumber">1</context> </context-group> </trans-unit> <trans-unit id="f4661fab0bda1dae3620088f290a8f086a6ca26e" datatype="html"> <source>{VAR_SELECT, select, other {deeply nested} }</source> <context-group purpose="location"> <context context-type="sourcefile">file.ts</context> <context context-type="linenumber">1</context> </context-group> </trans-unit> </body> </file> </xliff> `); }); it("should write xliff with i18nDef", () => { const messageBundle = new MessageBundle("en"); messageBundle.updateFromTemplate( { value: "This is a test message {sex, select, other {deeply nested}}", id: "customId", meaning: "Custom meaning", description: "Custom desc" }, "file.ts" ); expect(messageBundle.write(xliffWrite, xliffDigest)).toEqual(`<?xml version="1.0" encoding="UTF-8" ?> <xliff version="1.2" xmlns="urn:oasis:names:tc:xliff:document:1.2"> <file source-language="en" datatype="plaintext" original="ng2.template"> <body> <trans-unit id="customId" datatype="html"> <source>This is a test message <x id="ICU" equiv-text="{sex, select, other {...}}"/></source> <context-group purpose="location"> <context context-type="sourcefile">file.ts</context> <context context-type="linenumber">1</context> </context-group> <note priority="1" from="description">Custom desc</note> <note priority="1" from="meaning">Custom meaning</note> </trans-unit> <trans-unit id="f4661fab0bda1dae3620088f290a8f086a6ca26e" datatype="html"> <source>{VAR_SELECT, select, other {deeply nested} }</source> <context-group purpose="location"> <context context-type="sourcefile">file.ts</context> <context context-type="linenumber">1</context> </context-group> </trans-unit> </body> </file> </xliff> `); }); it("should write xliff with merged content", () => { const messageBundle = new MessageBundle("en"); messageBundle.updateFromTemplate("This is a test message {sex, select, other {deeply nested}}", "file.ts"); expect(messageBundle.write(xliffWrite, xliffDigest, xliffLoadToXml(XLIFF))) .toEqual(`<?xml version="1.0" encoding="UTF-8" ?> <xliff version="1.2" xmlns="urn:oasis:names:tc:xliff:document:1.2"> <file source-language="en" datatype="plaintext" original="ng2.template"> <body> <trans-unit id="983775b9a51ce14b036be72d4cfd65d68d64e231" datatype="html"> <source>translatable attribute</source> <target>etubirtta elbatalsnart</target> <context-group purpose="location"> <context context-type="sourcefile">file.ts</context> <context context-type="linenumber">1</context> </context-group> </trans-unit><trans-unit id="ec1d033f2436133c14ab038286c4f5df4697484a" datatype="html"> <source>translatable element <x id="START_BOLD_TEXT" ctype="b"/>with placeholders<x id="CLOSE_BOLD_TEXT" ctype="b"/> <x id="INTERPOLATION"/></source> <target><x id="INTERPOLATION"/> footnemele elbatalsnart <x id="START_BOLD_TEXT" ctype="x-b"/>sredlohecalp htiw<x id="CLOSE_BOLD_TEXT" ctype="x-b"/></target> </trans-unit><trans-unit id="e2ccf3d131b15f54aa1fcf1314b1ca77c14bfcc2" datatype="html"> <source>{VAR_PLURAL, plural, =0 {<x id="START_PARAGRAPH" ctype="x-p"/>test<x id="CLOSE_PARAGRAPH" ctype="x-p"/>} }</source> <target>{VAR_PLURAL, plural, =0 {<x id="START_PARAGRAPH" ctype="x-p"/>TEST<x id="CLOSE_PARAGRAPH" ctype="x-p"/>} }</target> </trans-unit><trans-unit id="db3e0a6a5a96481f60aec61d98c3eecddef5ac23" datatype="html"> <source>foo</source> <target>oof</target> </trans-unit><trans-unit id="i" datatype="html"> <source>foo</source> <target>toto</target> </trans-unit><trans-unit id="bar" datatype="html"> <source>foo</source> <target>tata</target> </trans-unit><trans-unit id="d7fa2d59aaedcaa5309f13028c59af8c85b8c49d" datatype="html"> <source><x id="LINE_BREAK" ctype="lb"/><x id="TAG_IMG" ctype="image"/><x id="START_TAG_DIV" ctype="x-div"/><x id="CLOSE_TAG_DIV" ctype="x-div"/></source> <target><x id="START_TAG_DIV" ctype="x-div"/><x id="CLOSE_TAG_DIV" ctype="x-div"/><x id="TAG_IMG" ctype="image"/><x id="LINE_BREAK" ctype="lb"/></target> </trans-unit><trans-unit id="empty target" datatype="html"> <source><x id="LINE_BREAK" ctype="lb"/><x id="TAG_IMG" ctype="image"/><x id="START_TAG_DIV" ctype="x-div"/><x id="CLOSE_TAG_DIV" ctype="x-div"/></source> <target/> </trans-unit><trans-unit id="baz" datatype="html"> <source>{VAR_PLURAL, plural, =0 {{VAR_SELECT, select, other {<x id="START_PARAGRAPH" ctype="x-p"/>deeply nested<x id="CLOSE_PARAGRAPH" ctype="x-p"/>} } } }</source> <target>{VAR_PLURAL, plural, =0 {{VAR_SELECT, select, other {<x id="START_PARAGRAPH" ctype="x-p"/>profondément imbriqué<x id="CLOSE_PARAGRAPH" ctype="x-p"/>} } } }</target> </trans-unit><trans-unit id="52ffa620dcd76247a56d5331f34e73f340a43cdb" datatype="html"> <source>Test: <x id="ICU" equiv-text="{ count, plural, =0 {...} =other {...}}"/></source> <target>Test: <x id="ICU" equiv-text="{ count, plural, =0 {...} =other {...}}"/></target> </trans-unit><trans-unit id="1503afd0ccc20ff01d5e2266a9157b7b342ba494" datatype="html"> <source>{VAR_PLURAL, plural, =0 {{VAR_SELECT, select, other {<x id="START_PARAGRAPH" ctype="x-p"/>deeply nested<x id="CLOSE_PARAGRAPH" ctype="x-p"/>} } } =other {a lot} }</source> <target>{VAR_PLURAL, plural, =0 {{VAR_SELECT, select, other {<x id="START_PARAGRAPH" ctype="x-p"/>profondément imbriqué<x id="CLOSE_PARAGRAPH" ctype="x-p"/>} } } =other {beaucoup} }</target> </trans-unit><trans-unit id="fcfa109b0e152d4c217dbc02530be0bcb8123ad1" datatype="html"> <source>multi lines</source> <target>multi lignes</target> </trans-unit> <trans-unit id="9161da7236814a71c5fec94eb42161651f6b4967" datatype="html"> <source>This is a test message <x id="ICU" equiv-text="{sex, select, other {...}}"/></source> <context-group purpose="location"> <context context-type="sourcefile">file.ts</context> <context context-type="linenumber">1</context> </context-group> </trans-unit> <trans-unit id="f4661fab0bda1dae3620088f290a8f086a6ca26e" datatype="html"> <source>{VAR_SELECT, select, other {deeply nested} }</source> <context-group purpose="location"> <context context-type="sourcefile">file.ts</context> <context context-type="linenumber">1</context> </context-group> </trans-unit> </body> </file> </xliff> `); }); });
the_stack
import utils from './util'; import { StyleSheet } from './css'; import event, { Notification, EventNoticer, Listen, Event } from './event'; import { TextNode, View, DOM } from './_view'; const TEXT_NODE_VALUE_TYPE = new Set(['function', 'string', 'number', 'boolean']); const G_removeSet = new WeakSet<ViewController>(); const G_renderQueueSet = new Set<ViewController>(); var G_renderQueueWorking = false; const G_warnRecord = new Set(); const G_warnDefine = { UndefinedDOMKey: 'DOM key no defined in DOM Collection', } as Dict<string>; function warn(id: string, msg = '') { var def = G_warnDefine[id]; if (def) { if (!G_warnRecord.has(id)) { G_warnRecord.add(id); console.warn(def, msg); } } } // mark controller rerender function markRerender(ctr: ViewController) { var size = G_renderQueueSet.size; G_renderQueueSet.add(ctr); if (size == G_renderQueueSet.size) return; if (G_renderQueueWorking) return; G_renderQueueWorking = true; utils.nextTick(function() { try { for( var item of G_renderQueueSet ) { rerender(item); } } finally { G_renderQueueWorking = false; } }); } export interface DOMConstructor { new(...args: any[]): DOM; readonly isViewController: boolean; } /** * @class VirtualDOM */ export class VirtualDOM { readonly propsHash: number; readonly props: Dict<[any/*value*/,number/*hash*/]>; readonly domConstructor: DOMConstructor; readonly children: (VirtualDOM | null)[]; dom: DOM; hash: number; constructor(domConstructor: DOMConstructor, props: Dict | null, children: (VirtualDOM | null)[]) { var _propsHash = 0; var _props: Dict<[any,number]> = {}; for (var prop in props) { var hashCode = 0; var value = props[prop]; hashCode += (hashCode << 5) + prop.hashCode(); hashCode += (hashCode << 5) + Object.hashCode(value); _props[prop] = [value,hashCode]; _propsHash += (_propsHash << 5) + hashCode; } var _hash = (domConstructor.hashCode() << 5) + _propsHash; for (var vdom of children) { if (vdom) { _hash += (_hash << 5) + vdom.hash; } } this.domConstructor = domConstructor; this.props = _props; this.hash = _hash; this.propsHash = _propsHash; this.children = children; } getProp(name: string) { var prop = this.props[name]; return prop ? prop[0]: null; } hasProp(name: string) { return name in this.props; } assignProps() { var props = this.props; for (var key in props) { (this.dom as any)[key] = props[key][0]; // assignProp } } diffProps(vdom: VirtualDOM) { if (this.propsHash != vdom.propsHash) { var props0 = this.props; var props1 = vdom.props; for (var key in props1) { var prop0 = props0[key], prop1 = props1[key]; if (!prop0 || prop0[1] != prop1[1]) { (this.dom as any)[key] = prop1[0]; // assignProp } } } } newInstance(ctr: ViewController | null): DOM { utils.assert(this.dom === defaultDOM); var dom = new this.domConstructor(); this.dom = dom; (dom as any).m_owner = ctr; // private props visit if (this.domConstructor.isViewController) { // ctrl var newCtr = dom as ViewController; (newCtr as any).m_vchildren = this.children; // private props visit this.assignProps(); // before set props var r = (newCtr as any).triggerLoad(); // trigger event Load, private props visit if (r instanceof Promise) { r.then(()=>{ (newCtr as any).m_loaded = true; markRerender(newCtr); }); // private props visit } else { (newCtr as any).m_loaded = true; // private props visit } rerender(newCtr); // rerender } else { for (var vdom of this.children) { if (vdom) vdom.newInstance(ctr).appendTo(dom as View); } this.assignProps(); // after set props } return dom; } hashCode() { return this.hash; } } const defaultDOM = { id: '', get __meta__(): View { throw Error.new('implemented') }, get owner(): ViewController { throw Error.new('implemented') }, remove() { throw Error.new('implemented') }, appendTo(){ throw Error.new('implemented') }, afterTo(){ throw Error.new('implemented') }, style: {}, } as DOM; VirtualDOM.prototype.dom = defaultDOM; /** * @class VirtualDOMCollection */ class VirtualDOMCollection extends VirtualDOM { vdoms: VirtualDOM[]; keys: Dict<VirtualDOM> = {}; placeholder: View | null = null; // view placeholder constructor(vdoms: (VirtualDOM | null)[]) { super(DOMCollection, {}, []); this.vdoms = vdoms.filter(e=>e) as VirtualDOM[]; this.vdoms.forEach(e=>(this.hash += (this.hash << 5) + e.hash)); } diffProps(vdom: VirtualDOM) { var { vdoms, hash } = vdom as VirtualDOMCollection; var dom = this.dom as DOMCollection; var keys: Dict<VirtualDOM> = {}; var keys_c = this.keys; // private props visit var ctr = dom.owner; var prev: View = this.vdoms.length ? this.vdoms[0].dom.__meta__: this.placeholder as View; // DOMCollection placeholder or doms[0] utils.assert(prev); for (var i = 0; i < vdoms.length; i++) { var vdom = vdoms[i], key; if (vdom.hasProp('key')) { key = vdom.getProp('key'); } else { warn('UndefinedDOMKey'); key = '_$auto' + i; // auto key } if (keys[key]) { throw new Error('DOM Key definition duplication in DOM Collection, = ' + key); } else { keys[key] = vdom; } var vdom_c = keys_c[key]; if (vdom_c) { if (vdom_c.hash != vdom.hash) { prev = diff(ctr, vdom_c, vdom, prev); // diff } else { // use old dom keys[key] = vdom_c; vdoms[i] = vdom_c; prev = vdom_c.dom.afterTo(prev); } delete keys_c[key]; } else { // no key var cell = vdom.newInstance(ctr); prev = cell.afterTo(prev); } } if (vdoms.length) { if (this.placeholder) { this.placeholder.remove(); this.placeholder = null; } } else if (!this.placeholder) { this.placeholder = new View(); this.placeholder.afterTo(prev); } this.hash = hash; this.keys = keys; this.vdoms = vdoms; for (let key in keys_c) { removeDOM(ctr, keys_c[key]); } } newInstance(ctr: ViewController | null): DOM { utils.assert(this.dom === defaultDOM); var vdoms = this.vdoms; var keys = this.keys; this.dom = new DOMCollection(ctr, this); for (var i = 0; i < vdoms.length; i++) { var vdom = vdoms[i], key; vdom.newInstance(ctr); if (vdom.hasProp('key')) { key = vdom.getProp('key'); } else { warn('UndefinedDOMKey'); key = '_$auto' + i; // auto key } if (keys[key]) { throw new Error('DOM Key definition duplication in DOM Collection, = ' + key); } else { keys[key] = vdom; } } return this.dom; } } /** * @class DOMCollection DOM */ class DOMCollection implements DOM { private m_owner: ViewController | null; private m_vdoms: VirtualDOMCollection; private _callDOMsFunc(active: 'afterTo' | 'appendTo', view: View): View { var self = this; if (self.m_vdoms.placeholder) { return self.m_vdoms.placeholder[active](view); } else { for (var cellView of self.m_vdoms.vdoms) { cellView.dom[active](view); } return self.m_vdoms.vdoms.indexReverse(0).dom.__meta__; } } get __meta__() { return this.m_vdoms.placeholder ? this.m_vdoms.placeholder: this.m_vdoms.vdoms.indexReverse(0).dom.__meta__; } id = ''; get owner() { return this.m_owner; } get collection() { return this.m_vdoms.vdoms.map(e=>e.dom as DOM); } key(key: string) { var vdom = this.m_vdoms.keys[key]; return vdom ? vdom.dom: null; } constructor(owner: ViewController | null, vdoms: VirtualDOMCollection) { this.m_owner = owner; this.m_vdoms = vdoms; } get style() { return {} } set style(value: StyleSheet) { } remove() { if (this.m_vdoms.placeholder) { this.m_vdoms.placeholder.remove(); this.m_vdoms.placeholder = null; } else if (this.m_vdoms.vdoms.length) { this.m_vdoms.vdoms.forEach(vdom=>{ removeDOM(this.m_owner, vdom); }); this.m_vdoms.vdoms = []; this.m_vdoms.keys = {}; } } appendTo(parentView: View) { return this._callDOMsFunc('appendTo', parentView); } afterTo(prevView: View) { return this._callDOMsFunc('afterTo', prevView); } static get isViewController() { return false; } } function removeSubctr(ctr: ViewController | null, vdom: VirtualDOM) { for (var e of vdom.children) { if (e) { if (e.domConstructor.isViewController) { e.dom.remove(); // remove ctrl } else { removeSubctr(ctr, e); } } } var id = vdom.dom.id; if (id && ctr) { if ((ctr as any).m_IDs[id] === vdom.dom) { delete (ctr as any).m_IDs[id]; } } } function removeDOM(ctr: ViewController | null, vdom: VirtualDOM) { removeSubctr(ctr, vdom); vdom.dom.remove(); } function diff(ctr: ViewController | null, vdom_c: VirtualDOM, vdom: VirtualDOM, prevView: View) { utils.assert(prevView); // diff type if (vdom_c.domConstructor !== vdom.domConstructor) { var r = vdom.newInstance(ctr).afterTo(prevView); // add new removeDOM(ctr, vdom_c); // del dom return r; } var dom = vdom_c.dom as DOM; vdom.dom = dom; // diff props vdom_c.diffProps(vdom); var view = dom.__meta__; // diff children var children_c = vdom_c.children; var children = vdom.children; if ( vdom.domConstructor.isViewController ) { if ( children_c.length || children.length ) { (dom as any).m_vchildren = children; // private props visit rerender(dom as ViewController); // mark ctrl render } } else { var childrenCount = Math.max(children_c.length, children.length); for (var i = 0, prev = null; i < childrenCount; i++) { let vdom_c = children_c[i]; let vdom = children[i]; if (vdom_c) { if (vdom) { if (vdom_c.hash != vdom.hash) { prev = diff(ctr, vdom_c, vdom, prev || vdom_c.dom.__meta__); // diff } else { children[i] = vdom_c; prev = vdom_c.dom.__meta__; } } else { removeDOM(ctr, vdom_c); // remove DOM } } else { if (vdom) { var dom = vdom.newInstance(ctr); if (prev) prev = dom.afterTo(prev); // add else { var tmp = new View(); view.prepend(tmp); prev = dom.afterTo(tmp); // add tmp.remove(); } } } } } // if (vdom.type.isViewController) end return view; } function domInCtr(self: ViewController): DOM { return (self as any).m_vdom ? (self as any).m_vdom.dom: (self as any).m_placeholder; } /** * @func prop() * <pre> * class MyViewController extends ViewController { * @prop width: number = 100; * @prop height: number = 100; * render() { * return ( * <Div width=this.width height=this.height>Hello</Div> * ); * } * } * </pre> */ function defineProp<T extends any/*typeof ViewController.prototype*/>(target: T, name: string, defaultValue?: any) { var _target = target as any; utils.assert(utils.equalsClass(ViewController, _target.constructor), 'Type error'); var m_name = 'm_' + name; var m_hash_name = 'm_prop_' + name; Object.defineProperty(_target, name, { get: arguments.length < 3 ? function(this: any) { return this[m_name]; }: typeof defaultValue == 'function' ? defaultValue: ((_target[m_name] = defaultValue), function(this: any) { return this[m_name]; }), set(this: any, value: any) { var hashCode = Object.hashCode(value); var hash = this.m_dataHash; if (hash[m_hash_name] != hashCode) { hash[m_hash_name] = hashCode; this[m_name] = value; this.markRerender(); // mark render } }, configurable: false, enumerable: true, }); } // export declare function prop<T extends typeof ViewController.prototype>(target: T, name: string): void; // export declare function prop(defaultValue: (()=>any) | any): <T extends typeof ViewController.prototype>(target: T, name: string)=>void; export declare function prop<T extends object>(target: T, name: string): void; export declare function prop(defaultValue: (()=>any) | any): <T extends object>(target: T, name: string)=>void; exports.prop = function(defaultValueOrTarget: any, name?: string) { if (arguments.length < 2) { return function(target: any, name: any) { defineProp(target, name, defaultValueOrTarget/*default value*/); }; } else { defineProp(defaultValueOrTarget/*target*/, name as string); } }; const _prop = exports.prop; function rerender(ctr: ViewController) { ViewController.rerender(ctr); } export enum TypeOf { NONE = 0, DOM = 1, VDOM = 2, } /** * @class ViewController DOM */ export class ViewController<State extends Dict = Dict> extends Notification<Event<any, ViewController>> implements DOM { private m_IDs: Dict<ViewController | View> = {}; private m_state: State = {} as State; // state private m_dataHash: Dict<number> = {}; // modle and props hash private m_id: string; // = null; // id private m_owner: ViewController | null; // = null; // owner controller private m_placeholder: View | null; // = null; // view placeholder private m_vdom: VirtualDOM | null; // = null; // children vdom private m_vchildren: VirtualDOM[]; // = []; // outer vdom children private m_loaded: boolean; // = false; private m_mounted: boolean; // = false; private m_style: StyleSheet | null; // = null; static rerender(self: ViewController) { G_renderQueueSet.delete(self); // delete mark var vdom_c = self.m_vdom; var vdom = _CVDD(self.render(...self.m_vchildren)); var update = false; if (vdom_c) { if (vdom) { if (vdom_c.hash != vdom.hash) { var prev = vdom_c.dom.__meta__; utils.assert(prev); self.m_vdom = vdom; diff(self, vdom_c, vdom, prev); // diff update = true; } } else { var prev = vdom_c.dom.__meta__; utils.assert(prev); utils.assert(!self.m_placeholder); self.m_placeholder = new View(); self.m_placeholder.afterTo(prev); self.m_vdom = null; removeDOM(self, vdom_c); // del dom update = true; } } else { if (vdom) { self.m_vdom = vdom; vdom.newInstance(self); if (self.m_placeholder) { vdom.dom.afterTo(self.m_placeholder); self.m_placeholder.remove(); self.m_placeholder = null; } update = true; } else { if (!self.m_placeholder) { self.m_placeholder = new View(); } } } if (!self.m_mounted) { self.m_mounted = true; self.triggerMounted(); } if (update) { self.triggerUpdate(); } } get __meta__(): View { return this.m_vdom ? this.m_vdom.dom.__meta__: this.m_placeholder as View; } @event readonly onLoad: EventNoticer<Event<void, ViewController>>; // @event onLoad @event readonly onMounted: EventNoticer<Event<void, ViewController>>; // @event onMounted @event readonly onUpdate: EventNoticer<Event<void, ViewController>>; // @event onUpdate @event readonly onRemove: EventNoticer<Event<void, ViewController>>; // @event onRemove @event readonly onRemoved: EventNoticer<Event<void, ViewController>>; // @event onRemoved protected triggerLoad(): any { return this.trigger('Load'); } protected triggerMounted(): any { return this.trigger('Mounted'); } protected triggerUpdate(): any { return this.trigger('Update'); } protected triggerRemove(): any { return this.trigger('Remove'); } protected triggerRemoved(): any { return this.trigger('Removed'); } get id() { return this.m_id; } set id(value: string) { ViewController._setID(this, value); } get IDs() { return this.m_IDs; } find<T extends View | ViewController = View>(id: string) { var r = this.m_IDs[id]; utils.assert(r, 'ViewController.find<T>(id) = null'); return r as T; } static _setID(dom: DOM, id: string) { var _id = (dom as any).m_id; // private props visit if (_id != id) { if ((dom as any).m_owner) { // private props visit var ids = (dom as any).m_owner.m_IDs; // private props visit if (ids[_id] === dom) { delete ids[_id]; } if (id) { if (id in ids) { throw new Error('Identifier reference duplication in controller, = ' + id); } ids[id] = dom; } } (dom as any).m_id = id; // private props visit } } get owner() { return this.m_owner; } get dom(): DOM | null { return this.m_vdom ? this.m_vdom.dom: null; } /** * Insecure access */ ownerAs<T extends ViewController = ViewController>() { utils.assert(this.m_owner, 'ViewController.ownerAs<T>() = null'); return this.m_owner as T; } /** * Insecure access */ domAs<T extends DOM = View>() { utils.assert(this.m_vdom, 'ViewController.domAs<T>() = null'); return (this.m_vdom as VirtualDOM).dom as T; } get isLoaded() { return this.m_loaded; } get isMounted() { return this.m_mounted; } /** * @get state view model */ get state() { return this.m_state; } /** * @set state view model */ set state(state: State) { this.setState(state); } /** * @func setState() */ setState(state: State) { var update = false; var value = this.m_state; var hash = this.m_dataHash; for (var key in state) { var item = state[key]; var hashCode = Object.hashCode(item); if (hashCode != hash[key]) { value[key] = item; hash[key] = hashCode; update = true; } } if (update) { this.markRerender(); // mark render } } /* * @func markRerender() */ markRerender() { markRerender(this); } hashCode() { return Function.prototype.hashCode.call(this); } appendTo(parentView: View): View { return domInCtr(this).appendTo(parentView); } afterTo(prevView: View): View { return domInCtr(this).afterTo(prevView); } /** * @func render(...vdoms) */ protected render(...vdoms: any[]): any { return vdoms; } remove() { var vdom = this.m_vdom; var placeholder = this.m_placeholder; if (vdom || placeholder) { var owner = this.m_owner; if (owner) { utils.assert(owner.dom !== this, 'Illegal call'); } if (G_removeSet.has(this)) return; G_removeSet.add(this); try { this.triggerRemove(); // trigger Remove event } finally { G_removeSet.delete(this); } this.m_placeholder = null; this.m_vdom = null; if (vdom) { removeDOM(this, vdom); } else { (placeholder as View).remove(); } this.triggerRemoved(); // trigger Removed } } /** * @prop style */ @_prop(function(this: ViewController) { return this.m_style || {}; }) style: StyleSheet; /** * @get isViewController * @static */ static get isViewController() { return true; } /** * @func typeOf(obj, [Type=class ViewController]) * @arg obj {VirtualDOM|View|ViewController|class} * @static */ static typeOf(obj: DOM | VirtualDOM, Type?: DOMConstructor/* = ViewController*/): TypeOf { Type = Type || ViewController; if (utils.equalsClass(ViewController, Type) || utils.equalsClass(View, Type)) { if (obj instanceof Type) return TypeOf.DOM; // dom instance if (obj instanceof VirtualDOM) { if (utils.equalsClass(Type, obj.domConstructor)) return TypeOf.VDOM; // vdom instance } } return 0; } /** * @func render(obj, [parentView]) * @arg obj {DOM | DOMConstructor} * @ret {DOM} return dom instance */ static render<T extends DOM = DOM>(obj: DOM | VirtualDOM, parentView?: View) { var dom: DOM; var owner = parentView ? parentView.owner: null; if (obj instanceof ViewController || obj instanceof View) { dom = obj; // dom instance } else { let vd = _CVDD(obj) as VirtualDOM; // format vdom utils.assert(vd instanceof VirtualDOM, 'Bad argument'); dom = vd.newInstance(owner); } if (parentView) { dom.appendTo(parentView); // (dom as any).m_owner = owner; // private props visit } return dom as T; } static hashCode() { return Function.prototype.hashCode.call(this); } static readonly CVD = _CVD; } (ViewController as any).prototype.m_id = ''; (ViewController as any).prototype.m_owner = null; (ViewController as any).prototype.m_placeholder = null; (ViewController as any).prototype.m_vdom = null; (ViewController as any).prototype.m_vchildren = []; (ViewController as any).prototype.m_loaded = false; (ViewController as any).prototype.m_mounted = false; (ViewController as any).prototype.m_style = null; export default ViewController; // create virtual dom TextNode function _CVDT(value: string) { return new VirtualDOM(TextNode, {value}, []); } // create virtual dom dynamic export function _CVDD(value: any): VirtualDOM | null { if (value instanceof VirtualDOM) { return value } else if (TEXT_NODE_VALUE_TYPE.has(typeof value)) { return _CVDT(value); } else if (Array.isArray(value)) { if (value.length) { return value.length == 1 ? _CVDD(value[0]): new VirtualDOMCollection(value.map(_CVDD)); } else { return null; } } return value ? _CVDT(String(value)): null; // null or TextNode } // create virtual dom export function _CVD(Type: DOMConstructor, props: Dict | null, ...children: any[]) { return new VirtualDOM(Type, props, children.map(_CVDD)); }
the_stack
import {BytecodeNode, IHaikuComponent} from './api'; import {visitManaTree} from './HaikuNode'; import compareSemver from './helpers/compareSemver'; import migrateAutoSizing from './helpers/migrateAutoSizing'; import {SVG_SIZEABLES} from './layout/applyCssLayout'; import functionToRFO from './reflection/functionToRFO'; import reifyRFO from './reflection/reifyRFO'; const enum UpgradeVersionRequirement { OriginSupport = '3.2.0', TimelineDefaultFrames = '3.2.23', CamelAutoSizingOffset3DOmnibus = '3.5.2', } const HAIKU_ID_ATTRIBUTE = 'haiku-id'; const HAIKU_SOURCE_ATTRIBUTE = 'haiku-source'; const HAIKU_VAR_ATTRIBUTE = 'haiku-var'; const HAIKU_ROOT_DEFAULT_REGEX = /^web\+haikuroot:\/\//; const HAIKU_ROOT_DEFAULT = 'web+haikuroot://'; const SRC_ATTRIBUTE = 'src'; const HREF_ATTRIBUTE = 'href'; const XLINKHREF_ATTRIBUTE = 'xlink:href'; const requiresUpgrade = (coreVersion: string, requiredVersion: UpgradeVersionRequirement) => !coreVersion || compareSemver( coreVersion, requiredVersion, ) < 0; const areKeyframesDefined = (keyframeGroup) => { return ( keyframeGroup && Object.keys(keyframeGroup).length > 0 ); }; export interface MigrationOptions { attrsHyphToCamel: { [key in string]: string; }; mutations?: { referenceUniqueness: string; haikuRoot: string; }; } const ensure3dPreserved = (node: BytecodeNode) => { if (!node || !node.attributes || !node.attributes.style) { return; } let changed = false; // Only preserve 3D behavior if the node hasn't been *explicitly* defined yet if (!node.attributes.style.transformStyle) { node.attributes.style.transformStyle = 'preserve-3d'; changed = true; if (!node.attributes.style.perspective) { node.attributes.style.perspective = 'inherit'; } } return changed; }; /** * Migrations are a mechanism to modify our bytecode from legacy format to the current format. * This always runs against production components' bytecode to ensure their data is a format * that the current version of the engine knows how to handle. There are two phases to migration: * the pre-phase, which runs before an initial .render call, and a post-phase, which runs after. */ export const runMigrationsPrePhase = (component: IHaikuComponent, options: MigrationOptions) => { const bytecode = component.bytecode; if (!bytecode.states) { bytecode.states = {}; } if (!bytecode.metadata) { bytecode.metadata = {}; } const coreVersion = bytecode.metadata.core || bytecode.metadata.player; // Convert the properties array to the states dictionary if (bytecode.properties) { const properties = bytecode.properties; delete bytecode.properties; for (let i = 0; i < properties.length; i++) { const propertySpec = properties[i]; const updatedSpec = {} as any; if (propertySpec.value !== undefined) { updatedSpec.value = propertySpec.value; } if (propertySpec.type !== undefined) { updatedSpec.type = propertySpec.type; } if (propertySpec.setter !== undefined) { updatedSpec.set = propertySpec.setter; } if (propertySpec.getter !== undefined) { updatedSpec.get = propertySpec.getter; } if (propertySpec.set !== undefined) { updatedSpec.set = propertySpec.set; } if (propertySpec.get !== undefined) { updatedSpec.get = propertySpec.get; } bytecode.states[propertySpec.name] = updatedSpec; } } // Convert the eventHandlers array into a dictionary // [{selector:'foo',name:'onclick',handler:function}] => {'foo':{'onclick':{handler:function}}} if (Array.isArray(bytecode.eventHandlers)) { const eventHandlers = bytecode.eventHandlers; delete bytecode.eventHandlers; bytecode.eventHandlers = {}; for (let j = 0; j < eventHandlers.length; j++) { const eventHandlerSpec = eventHandlers[j]; if (!bytecode.eventHandlers[eventHandlerSpec.selector]) { bytecode.eventHandlers[eventHandlerSpec.selector] = {}; } bytecode.eventHandlers[eventHandlerSpec.selector][eventHandlerSpec.name] = { handler: eventHandlerSpec.handler, }; } } if (bytecode.timelines) { // Expand all bytecode properties represented as shorthand. for (const timelineName in bytecode.timelines) { for (const selector in bytecode.timelines[timelineName]) { for (const property in bytecode.timelines[timelineName][selector]) { if (bytecode.timelines[timelineName][selector][property] === null) { delete bytecode.timelines[timelineName][selector][property]; } else if (typeof bytecode.timelines[timelineName][selector][property] !== 'object') { bytecode.timelines[timelineName][selector][property] = { 0: { value: bytecode.timelines[timelineName][selector][property], }, }; } } } } } const needsOmnibusUpgrade = requiresUpgrade( coreVersion, UpgradeVersionRequirement.CamelAutoSizingOffset3DOmnibus, ); const referencesToUpdate = {}; if (bytecode.template) { // y-overflow + preserve-3d leads to various rendering bugs, so for now, disable when overflow is available. // #FIXME const autoPreserve3d = component.config.preserve3d === 'auto' && component.config.overflowY !== 'visible'; visitManaTree( '0', bytecode.template, (_, attributes) => { if (typeof attributes !== 'object') { return; } if (options.mutations) { if (attributes.id) { const prev = attributes.id; const next = prev + '-' + options.mutations.referenceUniqueness; attributes.id = next; referencesToUpdate[`#${prev}`] = `#${next}`; referencesToUpdate['url(#' + prev + ')'] = 'url(#' + next + ')'; } } }, null, 0, ); visitManaTree( '0', bytecode.template, (elementName, attributes) => { if (typeof attributes !== 'object') { return; } const timelineProperties = bytecode.timelines.Default[`haiku:${attributes[HAIKU_ID_ATTRIBUTE]}`] || {}; // Hoist xlink:href up to the timeline if not already done. Older versions of Haiku installed xlink:href in the // attributes dictionary. if (attributes[XLINKHREF_ATTRIBUTE]) { timelineProperties[XLINKHREF_ATTRIBUTE] = {0: {value: attributes[XLINKHREF_ATTRIBUTE]}}; delete attributes[XLINKHREF_ATTRIBUTE]; } if (options.mutations) { for (const property in timelineProperties) { if (property !== SRC_ATTRIBUTE && property !== XLINKHREF_ATTRIBUTE && property !== HREF_ATTRIBUTE) { continue; } for (const keyframe in timelineProperties[property]) { const value = timelineProperties[property][keyframe].value as string; if (HAIKU_ROOT_DEFAULT_REGEX.test(value)) { timelineProperties[property][keyframe].value = value.replace( HAIKU_ROOT_DEFAULT, options.mutations.haikuRoot, ); } else if (referencesToUpdate[value]) { timelineProperties[property][keyframe].value = referencesToUpdate[value]; } } } } // Switch the legacy 'source' attribute to the new 'haiku-source' if (attributes.source) { attributes[HAIKU_SOURCE_ATTRIBUTE] = attributes.source; delete attributes.source; } if (attributes.identifier) { attributes[HAIKU_VAR_ATTRIBUTE] = attributes.identifier; delete attributes.identifier; } // Legacy backgroundColor was a root prop; in newer versions it's style.backgroundColor. // We only want to update this if the user *hasn't* explicitly set style.backroundColor. if (timelineProperties.backgroundColor && !timelineProperties['style.backgroundColor']) { timelineProperties['style.backgroundColor'] = timelineProperties.backgroundColor; delete timelineProperties.backgroundColor; } if (needsOmnibusUpgrade) { const transformStyleGroup = timelineProperties['style.transformStyle']; if (transformStyleGroup && transformStyleGroup[0] && transformStyleGroup[0].value === 'flat') { delete timelineProperties['style.transformStyle']; } const perspectiveGroup = timelineProperties['style.perspective']; if (perspectiveGroup && perspectiveGroup[0] && perspectiveGroup[0].value === 'none') { delete timelineProperties['style.perspective']; } // Retire sizing layout from any SVG sizeable in favor of explicit properties. if (typeof elementName === 'string' && SVG_SIZEABLES[elementName]) { if (timelineProperties['sizeAbsolute.x']) { timelineProperties.width = {0: {value: timelineProperties['sizeAbsolute.x'][0].value}}; delete timelineProperties['sizeAbsolute.x']; delete timelineProperties['sizeMode.x']; } if (timelineProperties['sizeAbsolute.y']) { timelineProperties.height = {0: {value: timelineProperties['sizeAbsolute.y'][0].value}}; delete timelineProperties['sizeAbsolute.y']; delete timelineProperties['sizeMode.y']; } if (timelineProperties['sizeProportional.x']) { timelineProperties.width = { 0: {value: `${Number(timelineProperties['sizeProportional.x'][0].value) * 100}%`}, }; delete timelineProperties['sizeProportional.x']; delete timelineProperties['sizeMode.x']; } if (timelineProperties['sizeProportional.y']) { timelineProperties.height = { 0: {value: `${Number(timelineProperties['sizeProportional.y'][0].value) * 100}%`}, }; delete timelineProperties['sizeProportional.y']; delete timelineProperties['sizeMode.y']; } } } // If we see that any 3D transformations are applied, automatically override flat perspective // if it hasn't been automatically set, so that 3D perspective "just works" if ( !component.doPreserve3d && autoPreserve3d && ( areKeyframesDefined(timelineProperties['rotation.x']) || areKeyframesDefined(timelineProperties['rotation.y']) || areKeyframesDefined(timelineProperties['translation.z']) || areKeyframesDefined(timelineProperties['scale.z']) ) ) { component.doPreserve3d = true; } if ( !bytecode.timelines.Default[`haiku:${attributes[HAIKU_ID_ATTRIBUTE]}`] && Object.keys(timelineProperties).length > 0 ) { // Update with our hot object if we inadvertently created this object during migration. bytecode.timelines.Default[`haiku:${attributes[HAIKU_ID_ATTRIBUTE]}`] = timelineProperties; } }, null, 0, ); } if (bytecode.timelines) { // Although not ideal, it's likely beneficial to do another pass through the timelines to fill in // reference uniqueness. This may allow us to avoid a rerender below. for (const timelineName in bytecode.timelines) { for (let selector in bytecode.timelines[timelineName]) { if (needsOmnibusUpgrade) { // Migrate auto-sizing. migrateAutoSizing(bytecode.timelines[timelineName][selector]); } // Ensure ID-based selectors like #box work. if (referencesToUpdate[selector]) { bytecode.timelines[timelineName][referencesToUpdate[selector]] = bytecode.timelines[timelineName][selector]; delete bytecode.timelines[timelineName][selector]; selector = referencesToUpdate[selector]; } for (const propertyName in bytecode.timelines[timelineName][selector]) { if (needsOmnibusUpgrade) { // Migrate camel-case property names. const camelVariant = options.attrsHyphToCamel[propertyName]; if (camelVariant) { bytecode.timelines[timelineName][selector][camelVariant] = bytecode.timelines[timelineName][selector][propertyName]; delete bytecode.timelines[timelineName][selector][propertyName]; } } for (const keyframeMs in bytecode.timelines[timelineName][selector][propertyName]) { const keyframeDesc = bytecode.timelines[timelineName][selector][propertyName][keyframeMs]; if (keyframeDesc && referencesToUpdate[keyframeDesc.value as string]) { keyframeDesc.value = referencesToUpdate[keyframeDesc.value as string]; } } } } } } }; export const runMigrationsPostPhase = (component: IHaikuComponent, options: MigrationOptions, version: string) => { const bytecode = component.bytecode; const coreVersion = bytecode.metadata.core || bytecode.metadata.player; let needsRerender = false; if (component.doPreserve3d) { const node = component.node; if (node) { const didNodePreserve3dChange = ensure3dPreserved(node); if (didNodePreserve3dChange) { component.patches.push(node); } } // The wrapper also needs preserve-3d set for 3d-preservation to work const parent = component.parentNode; // This should be the "wrapper div" node if (parent) { const didParentPreserve3dChange = ensure3dPreserved(parent); if (didParentPreserve3dChange) { component.patches.push(parent); } } } const needsCamelAutoSizingOffsetOmnibus = requiresUpgrade( coreVersion, UpgradeVersionRequirement.CamelAutoSizingOffset3DOmnibus); if (needsCamelAutoSizingOffsetOmnibus) { const alsoMigrateOrigin = requiresUpgrade(coreVersion, UpgradeVersionRequirement.OriginSupport); component.visit((element) => { let offsetX = 0; let offsetY = 0; const timelineProperties = bytecode.timelines.Default[`haiku:${element.getComponentId()}`]; if (!timelineProperties) { return; } // Note: the migrations below are incorrect if align properties were ever defined on an element with explicit // size. Since in practice this never happened, this is fine. if (timelineProperties['align.x']) { const alignX = timelineProperties['align.x'][0] && timelineProperties['align.x'][0].value; if (typeof alignX === 'number') { offsetX += alignX * element.getNearestDefinedNonZeroAncestorSizeX(); } } if (timelineProperties['align.y']) { const alignY = timelineProperties['align.y'][0] && timelineProperties['align.y'][0].value; if (typeof alignY === 'number') { offsetY += alignY * element.getNearestDefinedNonZeroAncestorSizeY(); } } if (timelineProperties['mount.x']) { const mountX = timelineProperties['mount.x'][0] && timelineProperties['mount.x'][0].value; if (typeof mountX === 'number') { offsetX -= mountX * element.getNearestDefinedNonZeroAncestorSizeX(); } } if (timelineProperties['mount.y']) { const mountY = timelineProperties['mount.y'][0] && timelineProperties['mount.y'][0].value; if (typeof mountY === 'number') { offsetY -= mountY * element.getNearestDefinedNonZeroAncestorSizeY(); } } if (alsoMigrateOrigin) { // Prior to explicit origin support, we were applying a default origin of (0, 0, 0) for all objects, then // allowing the browser default for SVG elements (50%, 50%, 0px) be the effective transform-origin. This led to // inaccuracies in the layout system, specifically related to addressing translation on SVG elements and // addressing origin in general. Since as of the introduction of explicit origin support we had not made layout // offset addressable in Haiku, we can "backport" to the old coordinate system by simply offsetting layout // by its "origin error". if (element.tagName === 'svg') { offsetX += 0.5 * element.getNearestDefinedNonZeroAncestorSizeX(); offsetY += 0.5 * element.getNearestDefinedNonZeroAncestorSizeY(); } else { offsetX += element.originX * element.getNearestDefinedNonZeroAncestorSizeX(); offsetY += element.originY * element.getNearestDefinedNonZeroAncestorSizeY(); } } if (offsetX !== 0) { timelineProperties['offset.x'] = {0: {value: offsetX}}; needsRerender = true; } if (offsetY !== 0) { timelineProperties['offset.y'] = {0: {value: offsetY}}; needsRerender = true; } delete timelineProperties['align.x']; delete timelineProperties['align.y']; delete timelineProperties['align.z']; delete timelineProperties['mount.x']; delete timelineProperties['mount.y']; delete timelineProperties['mount.z']; }); } component.eachEventHandler((eventSelector, eventName, {handler}) => { if (!handler) { console.warn(`Unable to migrate event handler for ${eventSelector} ${eventName} in ${component.$id}`); return; } const rfo = handler.__rfo || functionToRFO(handler).__function; let params = rfo.params; let body: string = rfo.body; let changed = false; if (requiresUpgrade(coreVersion, UpgradeVersionRequirement.TimelineDefaultFrames)) { (['.seek(', '.gotoAndPlay(', '.gotoAndStop(']).forEach((methodSignature) => { for (let cursor = 0; cursor < body.length; ++cursor) { if (body.substring(cursor, cursor + methodSignature.length) !== methodSignature) { continue; } changed = true; // We have matched e.g. this.getDefaultTimeline().seek( at the string index of ".seek(". // Using the assumption that the method arguments do not contain string arguments with parentheses inside, // we can apply a simple parenthesis-balancing algorithm here. cursor += methodSignature.length; let openParens = 1; while (openParens > 0 && cursor < body.length) { if (body[cursor] === '(') { openParens++; } else if (body[cursor] === ')') { openParens--; } ++cursor; } // Essentially, replace .seek(foo) with .seek(foo, 'ms'). body = `${body.slice(0, cursor - 1)}, 'ms')${body.slice(cursor)}`; } }); } if (params.length < 4) { params = ['component', 'element', 'target', 'event']; changed = true; } if (changed) { bytecode.eventHandlers[eventSelector][eventName].handler = reifyRFO({ ...rfo, params, body, }); } }); if (needsRerender) { component.clearCaches(); component.markForFullFlush(); } // Ensure the bytecode metadata core version is recent. bytecode.metadata.core = version; };
the_stack
import { literal, Op } from 'sequelize' import each from 'jest-each' import { CaseAppealDecision, CaseDecision, CaseState, CaseType, InstitutionType, restrictionCases, UserRole, } from '@island.is/judicial-system/types' import type { User } from '@island.is/judicial-system/types' import { getCasesQueryFilter, isCaseBlockedFromUser } from './case.filters' import { Case } from '../models' describe('isCaseBlockedFromUser', () => { each` state | role | institutionType ${CaseState.DELETED} | ${UserRole.PROSECUTOR} | ${InstitutionType.PROSECUTORS_OFFICE} ${CaseState.DELETED} | ${UserRole.REGISTRAR} | ${InstitutionType.COURT} ${CaseState.DELETED} | ${UserRole.JUDGE} | ${InstitutionType.COURT} ${CaseState.DELETED} | ${UserRole.REGISTRAR} | ${InstitutionType.HIGH_COURT} ${CaseState.DELETED} | ${UserRole.JUDGE} | ${InstitutionType.HIGH_COURT} ${CaseState.DELETED} | ${UserRole.STAFF} | ${InstitutionType.PRISON} ${CaseState.DELETED} | ${UserRole.STAFF} | ${InstitutionType.PRISON_ADMIN} ${CaseState.NEW} | ${UserRole.REGISTRAR} | ${InstitutionType.COURT} ${CaseState.NEW} | ${UserRole.JUDGE} | ${InstitutionType.COURT} ${CaseState.NEW} | ${UserRole.REGISTRAR} | ${InstitutionType.HIGH_COURT} ${CaseState.NEW} | ${UserRole.JUDGE} | ${InstitutionType.HIGH_COURT} ${CaseState.NEW} | ${UserRole.STAFF} | ${InstitutionType.PRISON} ${CaseState.NEW} | ${UserRole.STAFF} | ${InstitutionType.PRISON_ADMIN} ${CaseState.DRAFT} | ${UserRole.REGISTRAR} | ${InstitutionType.HIGH_COURT} ${CaseState.DRAFT} | ${UserRole.JUDGE} | ${InstitutionType.HIGH_COURT} ${CaseState.DRAFT} | ${UserRole.STAFF} | ${InstitutionType.PRISON} ${CaseState.DRAFT} | ${UserRole.STAFF} | ${InstitutionType.PRISON_ADMIN} ${CaseState.SUBMITTED} | ${UserRole.REGISTRAR} | ${InstitutionType.HIGH_COURT} ${CaseState.SUBMITTED} | ${UserRole.JUDGE} | ${InstitutionType.HIGH_COURT} ${CaseState.SUBMITTED} | ${UserRole.STAFF} | ${InstitutionType.PRISON} ${CaseState.SUBMITTED} | ${UserRole.STAFF} | ${InstitutionType.PRISON_ADMIN} ${CaseState.RECEIVED} | ${UserRole.REGISTRAR} | ${InstitutionType.HIGH_COURT} ${CaseState.RECEIVED} | ${UserRole.JUDGE} | ${InstitutionType.HIGH_COURT} ${CaseState.RECEIVED} | ${UserRole.STAFF} | ${InstitutionType.PRISON} ${CaseState.RECEIVED} | ${UserRole.STAFF} | ${InstitutionType.PRISON_ADMIN} ${CaseState.REJECTED} | ${UserRole.STAFF} | ${InstitutionType.PRISON} ${CaseState.REJECTED} | ${UserRole.STAFF} | ${InstitutionType.PRISON_ADMIN} ${CaseState.DISMISSED} | ${UserRole.STAFF} | ${InstitutionType.PRISON} ${CaseState.DISMISSED} | ${UserRole.STAFF} | ${InstitutionType.PRISON_ADMIN} `.it( 'should block $state case from $role at $institutionType', ({ state, role, institutionType }) => { // Arrange const theCase = { state } as Case const user = { role, institution: { type: institutionType }, } as User // Act const isWriteBlocked = isCaseBlockedFromUser(theCase, user) const isReadBlocked = isCaseBlockedFromUser(theCase, user, false) // Assert expect(isWriteBlocked).toBe(true) expect(isReadBlocked).toBe(true) }, ) each` state ${CaseState.NEW} ${CaseState.DRAFT} ${CaseState.SUBMITTED} ${CaseState.RECEIVED} ${CaseState.ACCEPTED} ${CaseState.REJECTED} ${CaseState.DISMISSED} `.describe('given $state case', ({ state }) => { it('should block the case from other prosecutors offices', () => { // Arrange const theCase = { state, creatingProsecutor: { institutionId: 'Prosecutors Office' }, } as Case const user = { role: UserRole.PROSECUTOR, institution: { id: 'Another Prosecutors Office', type: InstitutionType.PROSECUTORS_OFFICE, }, } as User // Act const isWriteBlocked = isCaseBlockedFromUser(theCase, user) const isReadBlocked = isCaseBlockedFromUser(theCase, user, false) // Assert expect(isWriteBlocked).toBe(true) expect(isReadBlocked).toBe(true) }) it('should not block the case from own prosecutors office', () => { // Arrange const theCase = { state, creatingProsecutor: { institutionId: 'Prosecutors Office' }, } as Case const user = { role: UserRole.PROSECUTOR, institution: { id: 'Prosecutors Office', type: InstitutionType.PROSECUTORS_OFFICE, }, } as User // Act const isWriteBlocked = isCaseBlockedFromUser(theCase, user) const isReadBlocked = isCaseBlockedFromUser(theCase, user, false) // Assert expect(isWriteBlocked).toBe(false) expect(isReadBlocked).toBe(false) }) it('should not read block the case from shared prosecutors office', () => { // Arrange const theCase = { state, creatingProsecutor: { institutionId: 'Prosecutors Office' }, sharedWithProsecutorsOfficeId: 'Another Prosecutors Office', } as Case const user = { role: UserRole.PROSECUTOR, institution: { id: 'Another Prosecutors Office', type: InstitutionType.PROSECUTORS_OFFICE, }, } as User // Act const isWriteBlocked = isCaseBlockedFromUser(theCase, user) const isReadBlocked = isCaseBlockedFromUser(theCase, user, false) // Assert expect(isWriteBlocked).toBe(true) expect(isReadBlocked).toBe(false) }) it('should block a hightened security case from other prosecutors', () => { // Arrange const theCase = { state, isHeightenedSecurityLevel: true, creatingProsecutor: { id: 'Creating Prosecutor', institution: { id: 'Prosecutors Office' }, }, prosecutor: { id: 'Assigned Prosecutor' }, } as Case const user = { id: 'Other Prosecutor', role: UserRole.PROSECUTOR, institution: { id: 'Prosecutors Office', type: InstitutionType.PROSECUTORS_OFFICE, }, } as User // Act const isWriteBlocked = isCaseBlockedFromUser(theCase, user) const isReadBlocked = isCaseBlockedFromUser(theCase, user, false) // Assert expect(isWriteBlocked).toBe(true) expect(isReadBlocked).toBe(true) }) it('should not block a hightened security case from creating prosecutor', () => { // Arrange const theCase = { state, isHeightenedSecurityLevel: true, creatingProsecutor: { id: 'Creating Prosecutor', institution: { id: 'Prosecutors Office' }, }, prosecutor: { id: 'Assigned Prosecutor' }, } as Case const user = { id: 'Creating Prosecutor', role: UserRole.PROSECUTOR, institution: { id: 'Prosecutors Office', type: InstitutionType.PROSECUTORS_OFFICE, }, } as User // Act const isWriteBlocked = isCaseBlockedFromUser(theCase, user) const isReadBlocked = isCaseBlockedFromUser(theCase, user, false) // Assert expect(isWriteBlocked).toBe(false) expect(isReadBlocked).toBe(false) }) it('should not block a hightened security case from assigned prosecutor', () => { // Arrange const theCase = { state, isHeightenedSecurityLevel: true, creatingProsecutor: { id: 'Creating Prosecutor', institution: { id: 'Prosecutors Office' }, }, prosecutor: { id: 'Assigned Prosecutor' }, } as Case const user = { id: 'Assigned Prosecutor', role: UserRole.PROSECUTOR, institution: { id: 'Prosecutors Office', type: InstitutionType.PROSECUTORS_OFFICE, }, } as User // Act const isWriteBlocked = isCaseBlockedFromUser(theCase, user) const isReadBlocked = isCaseBlockedFromUser(theCase, user, false) // Assert expect(isWriteBlocked).toBe(false) expect(isReadBlocked).toBe(false) }) }) each` state | role ${CaseState.DRAFT} | ${UserRole.REGISTRAR} ${CaseState.DRAFT} | ${UserRole.JUDGE} ${CaseState.SUBMITTED} | ${UserRole.REGISTRAR} ${CaseState.SUBMITTED} | ${UserRole.JUDGE} ${CaseState.RECEIVED} | ${UserRole.REGISTRAR} ${CaseState.RECEIVED} | ${UserRole.JUDGE} ${CaseState.ACCEPTED} | ${UserRole.REGISTRAR} ${CaseState.ACCEPTED} | ${UserRole.JUDGE} ${CaseState.REJECTED} | ${UserRole.REGISTRAR} ${CaseState.REJECTED} | ${UserRole.JUDGE} ${CaseState.DISMISSED} | ${UserRole.REGISTRAR} ${CaseState.DISMISSED} | ${UserRole.JUDGE} `.describe('given $state case and $role role', ({ state, role }) => { it('should block the case from the role at other courts', () => { // Arrange const theCase = { state, courtId: 'Court', } as Case const user = { role, institution: { id: 'Another Court', type: InstitutionType.COURT }, } as User // Act const isWriteBlocked = isCaseBlockedFromUser(theCase, user) const isReadBlocked = isCaseBlockedFromUser(theCase, user, false) // Assert expect(isWriteBlocked).toBe(true) expect(isReadBlocked).toBe(true) }) it('should not block the case from the role at own court', () => { // Arrange const theCase = { state, courtId: 'Court', } as Case const user = { role, institution: { id: 'Court', type: InstitutionType.COURT }, } as User // Act const isWriteBlocked = isCaseBlockedFromUser(theCase, user) const isReadBlocked = isCaseBlockedFromUser(theCase, user, false) // Assert expect(isWriteBlocked).toBe(false) expect(isReadBlocked).toBe(false) }) it('should not block a hightened security case from own court', () => { // Arrange const theCase = { state, isHeightenedSecurityLevel: true, courtId: 'Court', creatingProsecutor: { id: 'Creating Prosecutor', institution: { id: 'Prosecutors Office' }, }, prosecutor: { id: 'Assigned Prosecutor' }, } as Case const user = { id: 'Court User', role, institution: { id: 'Court', type: InstitutionType.COURT }, } as User // Act const isWriteBlocked = isCaseBlockedFromUser(theCase, user) const isReadBlocked = isCaseBlockedFromUser(theCase, user, false) // Assert expect(isWriteBlocked).toBe(false) expect(isReadBlocked).toBe(false) }) }) each` state | role ${CaseState.ACCEPTED} | ${UserRole.REGISTRAR} ${CaseState.ACCEPTED} | ${UserRole.JUDGE} ${CaseState.REJECTED} | ${UserRole.REGISTRAR} ${CaseState.REJECTED} | ${UserRole.JUDGE} ${CaseState.DISMISSED} | ${UserRole.REGISTRAR} ${CaseState.DISMISSED} | ${UserRole.JUDGE} `.describe( 'given a $state case and $role at high court', ({ state, role }) => { it('should not read block the case if the accused appealed in court', () => { // Arrange const theCase = { state, courtId: 'Court', accusedAppealDecision: CaseAppealDecision.APPEAL, } as Case const user = { role, institution: { id: 'High Court', type: InstitutionType.HIGH_COURT }, } as User // Act const isWriteBlocked = isCaseBlockedFromUser(theCase, user) const isReadBlocked = isCaseBlockedFromUser(theCase, user, false) // Assert expect(isWriteBlocked).toBe(true) expect(isReadBlocked).toBe(false) }) it('should not read block the case if the prosecutor appealed in court', () => { // Arrange const theCase = { state, courtId: 'Court', prosecutorAppealDecision: CaseAppealDecision.APPEAL, } as Case const user = { role, institution: { id: 'High Court', type: InstitutionType.HIGH_COURT }, } as User // Act const isWriteBlocked = isCaseBlockedFromUser(theCase, user) const isReadBlocked = isCaseBlockedFromUser(theCase, user, false) // Assert expect(isWriteBlocked).toBe(true) expect(isReadBlocked).toBe(false) }) it('should not read block the case if the accused appealed out of court', () => { // Arrange const theCase = { state, courtId: 'Court', accusedAppealDecision: CaseAppealDecision.POSTPONE, accusedPostponedAppealDate: new Date(), } as Case const user = { role, institution: { id: 'High Court', type: InstitutionType.HIGH_COURT }, } as User // Act const isWriteBlocked = isCaseBlockedFromUser(theCase, user) const isReadBlocked = isCaseBlockedFromUser(theCase, user, false) // Assert expect(isWriteBlocked).toBe(true) expect(isReadBlocked).toBe(false) }) it('should not read block the case if the prosecutor appealed out of court', () => { // Arrange const theCase = { state, courtId: 'Court', prosecutorAppealDecision: CaseAppealDecision.POSTPONE, prosecutorPostponedAppealDate: new Date(), } as Case const user = { role, institution: { id: 'High Court', type: InstitutionType.HIGH_COURT }, } as User // Act const isWriteBlocked = isCaseBlockedFromUser(theCase, user) const isReadBlocked = isCaseBlockedFromUser(theCase, user, false) // Assert expect(isWriteBlocked).toBe(true) expect(isReadBlocked).toBe(false) }) each` accusedAppealDecision | prosecutorAppealDecision ${CaseAppealDecision.ACCEPT} | ${CaseAppealDecision.ACCEPT} ${CaseAppealDecision.ACCEPT} | ${CaseAppealDecision.NOT_APPLICABLE} ${CaseAppealDecision.ACCEPT} | ${CaseAppealDecision.POSTPONE} ${CaseAppealDecision.NOT_APPLICABLE} | ${CaseAppealDecision.ACCEPT} ${CaseAppealDecision.NOT_APPLICABLE} | ${CaseAppealDecision.NOT_APPLICABLE} ${CaseAppealDecision.NOT_APPLICABLE} | ${CaseAppealDecision.POSTPONE} ${CaseAppealDecision.POSTPONE} | ${CaseAppealDecision.ACCEPT} ${CaseAppealDecision.POSTPONE} | ${CaseAppealDecision.NOT_APPLICABLE} ${CaseAppealDecision.POSTPONE} | ${CaseAppealDecision.POSTPONE} `.it( 'should block the case if it has not been appealed', ({ accusedAppealDecision, prosecutorAppealDecision }) => { // Arrange const theCase = { state, courtId: 'Court', accusedAppealDecision, prosecutorAppealDecision, } as Case const user = { role, institution: { id: 'High Court', type: InstitutionType.HIGH_COURT }, } as User // Act const isWriteBlocked = isCaseBlockedFromUser(theCase, user) const isReadBlocked = isCaseBlockedFromUser(theCase, user, false) // Assert expect(isWriteBlocked).toBe(true) expect(isReadBlocked).toBe(true) }, ) }, ) each` type ${CaseType.SEARCH_WARRANT} ${CaseType.BANKING_SECRECY_WAIVER} ${CaseType.PHONE_TAPPING} ${CaseType.TELECOMMUNICATIONS} ${CaseType.TRACKING_EQUIPMENT} ${CaseType.PSYCHIATRIC_EXAMINATION} ${CaseType.SOUND_RECORDING_EQUIPMENT} ${CaseType.AUTOPSY} ${CaseType.BODY_SEARCH} ${CaseType.INTERNET_USAGE} ${CaseType.OTHER} `.describe('given an accepted $type case', ({ type }) => { each` institutionType ${InstitutionType.PRISON} ${InstitutionType.PRISON_ADMIN} `.it( 'it should block the case from staff at $institution', ({ institutionType }) => { // Arrange const theCase = { type, state: CaseState.ACCEPTED, } as Case const user = { role: UserRole.STAFF, institution: { type: institutionType }, } as User // Act const isWriteBlocked = isCaseBlockedFromUser(theCase, user) const isReadBlocked = isCaseBlockedFromUser(theCase, user, false) // Assert expect(isWriteBlocked).toBe(true) expect(isReadBlocked).toBe(true) }, ) }) it('it should block an accepted travel ban case from prison staff', () => { // Arrange const theCase = { type: CaseType.TRAVEL_BAN, state: CaseState.ACCEPTED, } as Case const user = { role: UserRole.STAFF, institution: { type: InstitutionType.PRISON }, } as User // Act const isWriteBlocked = isCaseBlockedFromUser(theCase, user) const isReadBlocked = isCaseBlockedFromUser(theCase, user, false) // Assert expect(isWriteBlocked).toBe(true) expect(isReadBlocked).toBe(true) }) it('it should not read block an accepted travel ban case from prison admin staff', () => { // Arrange const theCase = { type: CaseType.TRAVEL_BAN, state: CaseState.ACCEPTED, } as Case const user = { role: UserRole.STAFF, institution: { type: InstitutionType.PRISON_ADMIN }, } as User // Act const isWriteBlocked = isCaseBlockedFromUser(theCase, user) const isReadBlocked = isCaseBlockedFromUser(theCase, user, false) // Assert expect(isWriteBlocked).toBe(true) expect(isReadBlocked).toBe(false) }) it('should block an accepted custody case with travel ban ruling from prison staff', () => { // Arrange const theCase = { type: CaseType.CUSTODY, state: CaseState.ACCEPTED, decision: CaseDecision.ACCEPTING_ALTERNATIVE_TRAVEL_BAN, } as Case const user = { role: UserRole.STAFF, institution: { type: InstitutionType.PRISON }, } as User // Act const isWriteBlocked = isCaseBlockedFromUser(theCase, user) const isReadBlocked = isCaseBlockedFromUser(theCase, user, false) // Assert expect(isWriteBlocked).toBe(true) expect(isReadBlocked).toBe(true) }) it('should not read block an accepted custody case from prison staff', () => { // Arrange const theCase = { type: CaseType.CUSTODY, state: CaseState.ACCEPTED, decision: CaseDecision.ACCEPTING, } as Case const user = { role: UserRole.STAFF, institution: { type: InstitutionType.PRISON }, } as User // Act const isWriteBlocked = isCaseBlockedFromUser(theCase, user) const isReadBlocked = isCaseBlockedFromUser(theCase, user, false) // Assert expect(isWriteBlocked).toBe(true) expect(isReadBlocked).toBe(false) }) it('should not read block an accepted custody case from prison admin staff', () => { // Arrange const theCase = { type: CaseType.CUSTODY, state: CaseState.ACCEPTED, } as Case const user = { role: UserRole.STAFF, institution: { type: InstitutionType.PRISON_ADMIN }, } as User // Act const isWriteBlocked = isCaseBlockedFromUser(theCase, user) const isReadBlocked = isCaseBlockedFromUser(theCase, user, false) // Assert expect(isWriteBlocked).toBe(true) expect(isReadBlocked).toBe(false) }) }) describe('getCasesQueryFilter', () => { it('should get prosecutor filter', () => { // Arrange const user = { id: 'Prosecutor Id', role: UserRole.PROSECUTOR, institution: { id: 'Prosecutors Office Id', type: InstitutionType.PROSECUTORS_OFFICE, }, } // Act const res = getCasesQueryFilter(user as User) // Assert expect(res).toStrictEqual({ [Op.and]: [ { [Op.not]: { state: [CaseState.DELETED] } }, { [Op.not]: { [Op.and]: [ { state: [CaseState.REJECTED, CaseState.DISMISSED] }, { ruling_date: { [Op.lt]: literal('current_date - 90') } }, ], }, }, { [Op.not]: { [Op.and]: [ { state: [ CaseState.NEW, CaseState.DRAFT, CaseState.SUBMITTED, CaseState.RECEIVED, ], }, { created: { [Op.lt]: literal('current_date - 90') } }, ], }, }, { [Op.not]: { [Op.and]: [ { type: restrictionCases }, { state: CaseState.ACCEPTED }, { valid_to_date: { [Op.lt]: literal('current_date - 90') } }, ], }, }, { [Op.not]: { [Op.and]: [ { [Op.not]: { type: restrictionCases } }, { state: CaseState.ACCEPTED }, { ruling_date: { [Op.lt]: literal('current_date - 90') } }, ], }, }, { [Op.or]: [ { creating_prosecutor_id: { [Op.is]: null } }, { '$creatingProsecutor.institution_id$': 'Prosecutors Office Id' }, { shared_with_prosecutors_office_id: 'Prosecutors Office Id' }, ], }, { [Op.or]: [ { is_heightened_security_level: { [Op.is]: null } }, { is_heightened_security_level: false }, { creating_prosecutor_id: 'Prosecutor Id' }, { prosecutor_id: 'Prosecutor Id' }, ], }, ], }) }) each` role ${UserRole.REGISTRAR} ${UserRole.JUDGE} `.describe('given $role role', ({ role }) => { it(`should get ${role} filter for`, () => { // Arrange const user = { role, institution: { id: 'Court Id', type: InstitutionType.COURT }, } // Act const res = getCasesQueryFilter(user as User) // Assert expect(res).toStrictEqual({ [Op.and]: [ { [Op.not]: { state: [CaseState.DELETED, CaseState.NEW] } }, { [Op.not]: { [Op.and]: [ { state: [CaseState.REJECTED, CaseState.DISMISSED] }, { ruling_date: { [Op.lt]: literal('current_date - 90') } }, ], }, }, { [Op.not]: { [Op.and]: [ { state: [ CaseState.NEW, CaseState.DRAFT, CaseState.SUBMITTED, CaseState.RECEIVED, ], }, { created: { [Op.lt]: literal('current_date - 90') } }, ], }, }, { [Op.not]: { [Op.and]: [ { type: restrictionCases }, { state: CaseState.ACCEPTED }, { valid_to_date: { [Op.lt]: literal('current_date - 90') } }, ], }, }, { [Op.not]: { [Op.and]: [ { [Op.not]: { type: restrictionCases } }, { state: CaseState.ACCEPTED }, { ruling_date: { [Op.lt]: literal('current_date - 90') } }, ], }, }, { [Op.or]: [ { court_id: { [Op.is]: null } }, { court_id: 'Court Id' }, ], }, ], }) }) it('should get high court filter', () => { // Arrange const user = { role, institution: { id: 'High Court Id', type: InstitutionType.HIGH_COURT }, } // Act const res = getCasesQueryFilter(user as User) // Assert expect(res).toStrictEqual({ [Op.and]: [ { [Op.not]: { state: [ CaseState.DELETED, CaseState.NEW, CaseState.DRAFT, CaseState.SUBMITTED, CaseState.RECEIVED, ], }, }, { [Op.not]: { [Op.and]: [ { state: [CaseState.REJECTED, CaseState.DISMISSED] }, { ruling_date: { [Op.lt]: literal('current_date - 90') } }, ], }, }, { [Op.not]: { [Op.and]: [ { state: [ CaseState.NEW, CaseState.DRAFT, CaseState.SUBMITTED, CaseState.RECEIVED, ], }, { created: { [Op.lt]: literal('current_date - 90') } }, ], }, }, { [Op.not]: { [Op.and]: [ { type: restrictionCases }, { state: CaseState.ACCEPTED }, { valid_to_date: { [Op.lt]: literal('current_date - 90') } }, ], }, }, { [Op.not]: { [Op.and]: [ { [Op.not]: { type: restrictionCases } }, { state: CaseState.ACCEPTED }, { ruling_date: { [Op.lt]: literal('current_date - 90') } }, ], }, }, { [Op.or]: { accused_appeal_decision: CaseAppealDecision.APPEAL, prosecutor_appeal_decision: CaseAppealDecision.APPEAL, accused_postponed_appeal_date: { [Op.not]: null }, prosecutor_postponed_appeal_date: { [Op.not]: null }, }, }, ], }) }) }) it('should get prison staff filter', () => { // Arrange const user = { id: 'Staff Id', role: UserRole.STAFF, institution: { id: 'Prison Id', type: InstitutionType.PRISON, }, } // Act const res = getCasesQueryFilter(user as User) // Assert expect(res).toStrictEqual({ [Op.and]: [ { state: CaseState.ACCEPTED }, { type: CaseType.CUSTODY }, { decision: CaseDecision.ACCEPTING }, { valid_to_date: { [Op.gt]: literal('current_date - 90') } }, ], }) }) it('should get prison admin staff filter', () => { // Arrange const user = { id: 'Staff Id', role: UserRole.STAFF, institution: { id: 'Prison Id', type: InstitutionType.PRISON_ADMIN, }, } // Act const res = getCasesQueryFilter(user as User) // Assert expect(res).toStrictEqual({ [Op.and]: [ { state: CaseState.ACCEPTED }, { type: [CaseType.CUSTODY, CaseType.TRAVEL_BAN] }, { valid_to_date: { [Op.gt]: literal('current_date - 90') } }, ], }) }) })
the_stack
import { Bounds, GoogleTms, Nztm2000QuadTms, Nztm2000Tms, QuadKey } from '@basemaps/geo'; import { Approx } from '@basemaps/test'; import { round } from '@basemaps/test/build/rounding.js'; import { BBox } from '@linzjs/geojson'; import o from 'ospec'; import { LatLon, Projection } from '../projection.js'; const TileSize = 256; /** * Get the raster bounds for a WebMercator zoom level * * @param extent Extent in meters in the format of [minX,minY,maxX,maxY] * @param zoom Web mercator zoom level */ function getPixelsBoundsFromMeters(extent: BBox, zoom: number): Bounds { const upperLeftMeters = GoogleTms.sourceToPixels(extent[0], extent[3], zoom); const lowerRightMeters = GoogleTms.sourceToPixels(extent[2], extent[1], zoom); return Bounds.fromUpperLeftLowerRight(upperLeftMeters, lowerRightMeters); } /** Convert a XYZ tile into a screen bounding box */ function getPixelsFromTile(x: number, y: number): Bounds { return new Bounds(x * TileSize, y * TileSize, TileSize, TileSize); } function isValidLatLong(x: LatLon): void { o(x.lat <= 90).equals(true)(`lat: ${x.lat} <= 90`); o(x.lat >= -90).equals(true)(`lat: ${x.lat} >= -90`); o(x.lon <= 180).equals(true)(`lon: ${x.lon} <= 180`); o(x.lon >= -180).equals(true)(`lon: ${x.lon} >= -180`); } o.spec('ProjectionTileMatrixSet', () => { o('getTiffResZoom', () => { o(Projection.getTiffResZoom(GoogleTms, 10)).equals(14); o(Projection.getTiffResZoom(GoogleTms, 10, 2)).equals(13); o(Projection.getTiffResZoom(GoogleTms, 0.075)).equals(21); o(Projection.getTiffResZoom(Nztm2000Tms, 10)).equals(10); o(Projection.getTiffResZoom(Nztm2000Tms, 10, 2)).equals(9); o(Projection.getTiffResZoom(Nztm2000Tms, 0.075)).equals(16); }); o('getTileSize', async () => { o(Projection.getImagePixelWidth(GoogleTms, { x: 0, y: 0, z: 5 }, 10)).equals(16384); o(Projection.getImagePixelWidth(GoogleTms, { x: 0, y: 0, z: 13 }, 20)).equals(65536); o(Projection.getImagePixelWidth(Nztm2000Tms, { x: 0, y: 0, z: 5 }, 10)).equals(20480); o(Projection.getImagePixelWidth(Nztm2000Tms, { x: 0, y: 0, z: 13 }, 16)).equals(5120); }); o('findAlignmentLevels', () => { o(Projection.findAlignmentLevels(GoogleTms, { x: 2, y: 0, z: 5 }, 0.075)).equals(15); o(Projection.findAlignmentLevels(GoogleTms, { x: 2, y: 0, z: 5 }, 0.5)).equals(13); o(Projection.findAlignmentLevels(GoogleTms, { x: 2, y: 0, z: 3 }, 1)).equals(14); o(Projection.findAlignmentLevels(GoogleTms, { x: 2, y: 0, z: 8 }, 10)).equals(5); o(Projection.findAlignmentLevels(GoogleTms, { x: 2, y: 0, z: 14 }, 10)).equals(0); o(Projection.findAlignmentLevels(Nztm2000Tms, { x: 2, y: 0, z: 1 }, 0.075)).equals(14); o(Projection.findAlignmentLevels(Nztm2000Tms, { x: 2, y: 0, z: 5 }, 0.5)).equals(8); o(Projection.findAlignmentLevels(Nztm2000Tms, { x: 2, y: 0, z: 3 }, 7)).equals(6); o(Projection.findAlignmentLevels(Nztm2000Tms, { x: 2, y: 0, z: 8 }, 14)).equals(0); }); o.spec('tileCenterToLatLon', () => { o('should create centers for web mercator', () => { const center = Projection.tileCenterToLatLon(GoogleTms, QuadKey.toTile('3120123')); isValidLatLong(center); o(round(center, 8)).deepEquals({ lat: -47.98992167, lon: 105.46875, }); }); o('should create centers for NZTM', () => { const center = Projection.tileCenterToLatLon(Nztm2000Tms, { x: 2295, y: 5119, z: 10 }); isValidLatLong(center); const centerB = Projection.tileCenterToLatLon(Nztm2000Tms, { x: 20, y: 20, z: 10 }); isValidLatLong(centerB); }); o('should create centers for NZTMQuad', () => { const center = Projection.tileCenterToLatLon(Nztm2000QuadTms, { x: 200, y: 500, z: 10 }); isValidLatLong(center); o(round(center, 8)).deepEquals({ lat: -35.79628765, lon: 141.39377624 }); const centerB = Projection.tileCenterToLatLon(Nztm2000QuadTms, { x: 1000, y: 1000, z: 10 }); isValidLatLong(centerB); }); }); o.spec('wrapLatLon', () => { o('should wrap longitude', () => { o(Projection.wrapLatLon(0, 1)).deepEquals({ lat: 0, lon: 1 }); o(Projection.wrapLatLon(0, 181)).deepEquals({ lat: 0, lon: -179 }); o(Projection.wrapLatLon(0, 271)).deepEquals({ lat: 0, lon: -89 }); o(Projection.wrapLatLon(0, 361)).deepEquals({ lat: 0, lon: 1 }); o(Projection.wrapLatLon(0, 631)).deepEquals({ lat: 0, lon: -89 }); o(Projection.wrapLatLon(0, 721)).deepEquals({ lat: 0, lon: 1 }); o(Projection.wrapLatLon(0, -1)).deepEquals({ lat: 0, lon: -1 }); o(Projection.wrapLatLon(0, -181)).deepEquals({ lat: 0, lon: 179 }); o(Projection.wrapLatLon(0, -271)).deepEquals({ lat: 0, lon: 89 }); o(Projection.wrapLatLon(0, -361)).deepEquals({ lat: 0, lon: -1 }); o(Projection.wrapLatLon(0, -631)).deepEquals({ lat: 0, lon: 89 }); o(Projection.wrapLatLon(0, -721)).deepEquals({ lat: 0, lon: -1 }); }); o('should wrap latitude', () => { o(Projection.wrapLatLon(1, 0)).deepEquals({ lat: 1, lon: 0 }); o(Projection.wrapLatLon(91, 0)).deepEquals({ lat: 89, lon: 180 }); o(Projection.wrapLatLon(181, 0)).deepEquals({ lat: -1, lon: 180 }); o(Projection.wrapLatLon(271, 0)).deepEquals({ lat: -89, lon: 0 }); o(Projection.wrapLatLon(361, 0)).deepEquals({ lat: 1, lon: 0 }); o(Projection.wrapLatLon(631, 0)).deepEquals({ lat: -89, lon: 0 }); o(Projection.wrapLatLon(721, 0)).deepEquals({ lat: 1, lon: 0 }); o(Projection.wrapLatLon(-1, 0)).deepEquals({ lat: -1, lon: 0 }); o(Projection.wrapLatLon(-91, 0)).deepEquals({ lat: -89, lon: 180 }); o(Projection.wrapLatLon(-181, 0)).deepEquals({ lat: 1, lon: 180 }); o(Projection.wrapLatLon(-271, 0)).deepEquals({ lat: 89, lon: 0 }); o(Projection.wrapLatLon(-361, 0)).deepEquals({ lat: -1, lon: 0 }); o(Projection.wrapLatLon(-631, 0)).deepEquals({ lat: 89, lon: 0 }); o(Projection.wrapLatLon(-721, 0)).deepEquals({ lat: -1, lon: 0 }); }); }); o.spec('tileToWgs84Bbox', () => { o('should handle antimeridian', () => { const pt = Projection.tileToWgs84Bbox(Nztm2000Tms, { x: 2, y: 1, z: 1 }); o(round(pt)).deepEquals([170.05982382, -20.71836222, -179.34441046, -10.28396555]); }); o('should convert base tiles', () => { const pt = Projection.tileToWgs84Bbox(GoogleTms, { x: 0, y: 0, z: 0 }); o(round(pt)).deepEquals([-180, -85.05112878, 180, 85.05112878]); }); }); o.spec('TilingBounds', () => { // Approximate bounding box of new zealand const tifBoundingBox: BBox = [18494091.86765497, -6051366.655280836, 19986142.659781612, -4016307.214216303]; const expectedBaseSize = Bounds.fromJson({ width: 9.53125, height: 13, y: 153.65625, x: 246.14062500000006 }); o('should tile 0,0,0', () => { const bounds = getPixelsBoundsFromMeters(tifBoundingBox, 0); Approx.bounds(bounds, expectedBaseSize); const screenBounds = getPixelsFromTile(0, 0); const intersection = bounds.intersection(screenBounds); Approx.bounds(intersection, expectedBaseSize); }); o('should tile 1,1,1', () => { const [x, y, z] = [1, 1, 1]; const bounds = getPixelsBoundsFromMeters(tifBoundingBox, z); const expectedBaseSizeScaled = expectedBaseSize.scale(2, 2); Approx.bounds(bounds, expectedBaseSizeScaled); const screenBounds = getPixelsFromTile(x, y); const intersection = bounds.intersection(screenBounds); Approx.bounds(intersection, expectedBaseSizeScaled); }); /** * XYZ tiles 15,9,4 & 15,10,4 provide a top/bottom tiles for this bounding box * * 15 * |-------| * | XXX | 9 * |-------| * | XXX | 10 * |-------| */ o('should tile [15, 9, 4] & [15, 10, 4]', () => { const [x, z] = [15, 4]; const bounds = getPixelsBoundsFromMeters(tifBoundingBox, z); const expectedBaseSizeScaled = expectedBaseSize.scale(2 ** z, 2 ** z); Approx.bounds(bounds, expectedBaseSizeScaled); const screenBounds9 = getPixelsFromTile(x, 9); const screenBounds10 = getPixelsFromTile(x, 10); o(screenBounds9.toJson()).deepEquals({ width: 256, height: 256, y: 2304, x: 3840 }); o(screenBounds10.toJson()).deepEquals({ width: 256, height: 256, y: 2560, x: 3840 }); const intersection9 = bounds.intersection(screenBounds9); const intersection10 = bounds.intersection(screenBounds10); if (intersection9 == null || intersection10 == null) { throw new Error('Intersections are null'); } // the image is split in two so the intersection should combine into the total height of the image const totalIntersectionHeight = intersection9.height + intersection10.height; o(totalIntersectionHeight).equals(bounds.height); // The image is not split horizontally so the width should be the same for both intersections o(intersection9.width).equals(bounds.width); o(intersection10.width).equals(bounds.width); Approx.equal(intersection9.height, 101.5, 'height'); Approx.equal(intersection10.height, 106.5, 'height'); }); /** * XYZ tiles [30, 19, 5], [31, 19, 5], [30, 20, 5], [31, 20, 5] * provide a top, bottom, left & right tiles for this bounding box * * 30 31 * |-------|-------| * | XXXXX|XXXX | 19 * |-------|-------| * | XXXXX|XXXX | 20 * |-------|-------| */ o('should tile [30, 19, 5], [31, 19, 5], [30, 20, 5], [31, 20, 5]', () => { const z = 5; const tileBounds = new Bounds(30, 19, 1, 1); const bounds = getPixelsBoundsFromMeters(tifBoundingBox, z); const expectedBaseSizeScaled = expectedBaseSize.scale(2 ** z, 2 ** z); Approx.bounds(bounds, expectedBaseSizeScaled); const screenTopLeft = getPixelsFromTile(tileBounds.x, tileBounds.y); const screenTopRight = getPixelsFromTile(tileBounds.right, tileBounds.y); o(screenTopLeft.toJson()).deepEquals({ width: 256, height: 256, y: 4864, x: 7680 }); o(screenTopRight.toJson()).deepEquals({ width: 256, height: 256, y: 4864, x: 7936 }); const intersectionTopLeft = bounds.intersection(screenTopLeft); const intersectionTopRight = bounds.intersection(screenTopRight); if (intersectionTopLeft == null || intersectionTopRight == null) { throw new Error('Intersections are null'); } // the image is split in two so the intersection should combine into the total width of the image const totalTopIntersectionWidth = intersectionTopLeft.width + intersectionTopRight.width; o(totalTopIntersectionWidth).equals(bounds.width); o(intersectionTopLeft.height).equals(203); o(intersectionTopRight.height).equals(203); const screenBottomLeft = getPixelsFromTile(tileBounds.x, tileBounds.bottom); const screenBottomRight = getPixelsFromTile(tileBounds.right, tileBounds.bottom); o(screenBottomLeft.toJson()).deepEquals({ width: 256, height: 256, y: 5120, x: 7680 }); o(screenBottomRight.toJson()).deepEquals({ width: 256, height: 256, y: 5120, x: 7936 }); const intersectionBottomLeft = bounds.intersection(screenBottomLeft); const intersectionBottomRight = bounds.intersection(screenBottomRight); if (intersectionBottomLeft == null || intersectionBottomRight == null) { throw new Error('Bottom intersections are null'); } // the image is split in two so the intersection should combine into the total width of the image const totalBottomIntersectionWidth = intersectionBottomLeft.width + intersectionBottomRight.width; o(totalBottomIntersectionWidth).equals(bounds.width); Approx.equal(intersectionBottomLeft.height, 213, 'height'); Approx.equal(intersectionBottomRight.height, 213, 'height'); const totalLeftIntersectionHeight = intersectionTopLeft.height + intersectionBottomLeft.height; const totalRightIntersectionHeight = intersectionTopRight.height + intersectionBottomRight.height; o(totalLeftIntersectionHeight).equals(bounds.height); o(totalRightIntersectionHeight).equals(bounds.height); }); }); });
the_stack
import Log from '../utils/log'; import PluginSystem from './plugins'; import NextPlugin from './plugins/next'; import {TY_GLOBAL_VALUES} from './globals'; import {isWindowFunction} from '../utils/proxys/fn'; import WebpackPlugin from './plugins/webpack'; import CommonPlugin from './plugins/common'; import IceStarkPlugin from './plugins/icestark'; import ZoePlugin from './plugins/zoe'; import {listenNativeEvents, listenRoutes} from './listener'; import {ILifecycle, validateExportLifecycle} from '../plugins/ali/qiankun'; import {topWindow, TY_SUB_APP_ID, TY_SUB_BASE_NAME, TY_SUB_MOUNT_CALLBACK, TY_SUB_PUBLIC_PATH, TY_SUB_UNMOUNT_CALLBACK} from '../common'; declare global { interface Window { __tyParentWindow?: any _currentSandbox?: any next?: { router?: { push: (url: string, as?: string) => void, replace: (url: string, as?: string) => void asPath: string pathname: string }, changeState: ( method: 'pushState' | 'replaceState', url: string, as: string, ) => void } } } // based on icestark-sandbox export default class Sandbox { private _pluginSystem: PluginSystem private _toGlobals:Array<string> = [] private eventListeners:{[key:string]: any} = {} private timeoutIds: number[] = [] private intervalIds: number[] = [] private propertyAdded:any = {}; private originalValues:any = {}; private _needToClear:Record<any, any> = {}; private _appId?: string private _basename?: string private _path: string | undefined private _isNext = false private _unlisten: Function | undefined | null = null private _frameWorkUnmount: Function | undefined private _container: HTMLElement | string | undefined private _assetPublicPath: string | undefined public lifecycle: ILifecycle | string | undefined public sandbox: Window | undefined; constructor(options?: { globals?: Array<string>, appId?: string, basename?: string, path: string container: HTMLElement | string framework?: 'icestark' | 'qiankun' | 'zoe' | 'next' | 'ty-next' assetPublicPath?: string nextVersion?: number, }) { if (!window.Proxy) { throw new Error('Sorry, window.Proxy is not defined !! '); } if (options?.globals) { this._toGlobals = options.globals; } this._path = options?.path; this._appId = options?.appId; this._basename = options?.basename; this._container = options?.container; this._assetPublicPath = options?.assetPublicPath; this._pluginSystem = new PluginSystem; this._pluginSystem.plugins.push(new WebpackPlugin(this._appId)); if (options?.framework === 'next' || options?.framework === 'ty-next') { this._pluginSystem.plugins.push(new NextPlugin( this._appId, this._container as HTMLElement, options.basename, options.nextVersion )); this._isNext = true; } else if (options?.framework === 'icestark' || options?.framework === 'qiankun') { this._pluginSystem.plugins.push(new IceStarkPlugin( options.framework, this._assetPublicPath, this._container, this._basename )); } else if (options?.framework === 'zoe') { this._pluginSystem.plugins.push(new ZoePlugin( this._appId!, this._container as HTMLElement, this._assetPublicPath, this._basename )); } else { this._pluginSystem.plugins.push(new CommonPlugin); } } listen() { this._unlisten = listenRoutes(this._path, this._basename, this._isNext, this.sandbox); } unlisten() { this._unlisten?.(); this._unlisten = null; } init() { const {propertyAdded, originalValues} = this; const proxyWindow = Object.create(null) as Window; const originalWindow = window.__tyParentWindow || window; listenNativeEvents(proxyWindow, this.eventListeners, this.timeoutIds, this.intervalIds); const _globals = this._toGlobals; const _needToClear = this._needToClear; if (this._appId) { proxyWindow[TY_SUB_APP_ID] = this._appId; } if (this._basename) { proxyWindow[TY_SUB_BASE_NAME] = this._basename; } if (this._assetPublicPath) { proxyWindow[TY_SUB_PUBLIC_PATH] = this._assetPublicPath; } this._pluginSystem.init(proxyWindow); const sandbox = new Proxy(proxyWindow, { set: (target: any, p: PropertyKey, value: any): boolean => { if (TY_GLOBAL_VALUES.includes(p as string)) { if (originalWindow.hasOwnProperty(p) && !originalValues.hasOwnProperty(p)) { originalValues[p] = originalWindow[p]; Log.warn('微前端全局变量已存在,正在重复设置中,请检查是否存在BUG ===>', p, value); } originalWindow[p] = value; _needToClear[p as string] = 1; Log.info('正在设置微前端全局变量 ===>', p, value); return true; } if (_globals.includes(p as string)) { if (originalWindow.hasOwnProperty(p) && !originalValues.hasOwnProperty(p)) { originalValues[p] = originalWindow[p]; Log.info('正在覆盖全局变量', p, value); } originalWindow[p] = value; _needToClear[p as string] = 1; Log.info('注册全局变量 ===>', p, value); return true; } if (this._pluginSystem.proxySet(target, p, value, sandbox, originalWindow)) { return true; } if (originalWindow.hasOwnProperty(p)) { // Log.info('存在变量名和全局变量一致,正在隔离', p, value); } else { propertyAdded[p] = value; } // if (!originalWindow.hasOwnProperty(p)) { // // recorde value added in sandbox // propertyAdded[p] = value; // // eslint-disable-next-line no-prototype-builtins // } else if (!originalValues.hasOwnProperty(p)) { // // if it is already been setted in orignal window, record it's original value // originalValues[p] = originalWindow[p]; // } target[p] = value; return true; }, get: (target: any, p: PropertyKey): any => { if (p === 'isProxy') { return true; } if (p === Symbol.unscopables) { return undefined; } if (['top', 'window', 'self', 'globalThis'].includes(p as string)) { return sandbox; } if (p === '__tyParentWindow') { return originalWindow[p] || originalWindow; } if (p === 'eval') { return eval; } if (_globals.includes(p as string) || TY_GLOBAL_VALUES.includes(p as string)) { return originalWindow[p]; } // proxy hasOwnProperty, in case of proxy.hasOwnProperty value represented as originalWindow.hasOwnProperty if (p === 'hasOwnProperty') { // eslint-disable-next-line no-prototype-builtins return (key: PropertyKey) => !!target[key] || originalWindow.hasOwnProperty(key); } const pluginValue = this._pluginSystem.proxyGet(target, p, sandbox, originalWindow); if (pluginValue !== undefined) { return pluginValue.value; } const targetValue = target[p]; if (targetValue) { // case of addEventListener, removeEventListener, setTimeout, setInterval setted in sandbox return targetValue; } const value = originalWindow[p]; if (isWindowFunction(value)) { // fix Illegal invocation return value.bind(originalWindow); } else { // case of window.clientWidth、new window.Object() return value; } }, has: (target: any, key: PropertyKey): boolean => { return key in target || key in topWindow; }, }); Reflect.set(proxyWindow, 'self', sandbox); window._currentSandbox = sandbox; this.sandbox = sandbox; this.listen(); } getSandbox() { return this.sandbox; } execScriptInSandbox(script: string, src?: string): void { // create sandbox before exec script if (!this.sandbox) { this.init(); } try { let execScript = `with (window) {;${script}\n}`; if (src) { execScript = `${execScript}\n//# sourceURL=${src}\n`; } // eslint-disable-next-line no-new-func const code = new Function('window', execScript).bind(this.sandbox); // run code with sandbox code(this.sandbox); } catch (error) { console.error(`error occurs when execute script in sandbox: ${error}`); throw error; } } runFinal() { if (this.sandbox) { this._pluginSystem.runFinal(this.sandbox, this.lifecycle); } if (!this._container) { return; } const {[TY_SUB_UNMOUNT_CALLBACK]: unmount, [TY_SUB_MOUNT_CALLBACK]: mount} = (this.sandbox as any) || {}; if (mount && unmount) { mount?.({container: this._container}); this._frameWorkUnmount = () => { unmount({container: this._container}); }; } } clear() { this._pluginSystem.clear(); if (this._frameWorkUnmount) { this._frameWorkUnmount?.({container: this._container}); } // remove event listeners Object.keys(this.eventListeners).forEach((eventName) => { (this.eventListeners[eventName] || []).forEach((listener: any) => { window.removeEventListener(eventName, listener); }); }); // clear timeout this.timeoutIds.forEach((id) => window.clearTimeout(id)); this.intervalIds.forEach((id) => window.clearInterval(id)); const list = Object.keys(this._needToClear); Log.info('清除全局污染数据 ===>', list); list.forEach((key) => { if (this.originalValues.hasOwnProperty(key)) { window[key] = this.originalValues[key]; } else { Reflect.deleteProperty(window, key); } }); this.unlisten(); Log.info('退出沙箱'); } dispatchPathChange(pathname: string) { const {TY_SUB_PATH_CHANGE_CALLBACK: onPathChange} = (this.sandbox as any) || {}; if (onPathChange) { onPathChange(pathname); } } }
the_stack
import axios from 'axios'; import * as Cms from './cms'; import {actions, ModelAction} from 'react-redux-form'; import {Field, FieldType, Model, Node, NodeType, normalizeModel, Path, TreeModel} from './model'; import {ActionCreator, Dispatch} from "react-redux"; import {Action} from "redux"; import AppState, {JsonFile, ViewMode} from "./state"; import {migrateSchema, schemaToModel} from "./cms"; import {RootSchemaElement} from "./schema"; import * as JSZip from 'jszip'; export const enum ActionTypes { ADD_CHILD, ADD_ITEM, DELETE_ITEM, MOVE_ITEM, INPUT_VALUE, ADD_VALUE, LOAD_START, LOAD_END, LOAD_ERROR, SAVE_START, SAVE_END, SAVE_ERROR, LOG_INFO, LOG_ERROR, CLEAR_FIELD_ERRORS, ON_NAVIGATE, SUBMIT_FIELD, CANCEL_EDIT_FIELD, EDIT_FIELD, EDIT_NODE, SUBMIT_NODE, CANCEL_EDIT_NODE, DELETE_FIELD, SHOW_CONFIRM, CANCEL_CONFIRM, DELETE_NODE, RESET_NAVIGATE_TO, SET_VIEW_MODE, SET_JSON_FILE, DEFAULT_ACTION = "__any_other_action_type__" } export interface DefaultAction extends Action { type: ActionTypes.DEFAULT_ACTION } export interface LogErrorAction extends Action { type: ActionTypes.LOG_ERROR; message: string; } export const logError: ActionCreator<LogErrorAction> = (message: string): LogErrorAction => ({ type: ActionTypes.LOG_ERROR, message }); export interface LogInfoAction extends Action { type: ActionTypes.LOG_INFO; message: string; } export const logInfo: ActionCreator<LogInfoAction> = (message: string): LogInfoAction => ({ type: ActionTypes.LOG_INFO, message }); export interface AddChildAction extends Action { type: ActionTypes.ADD_CHILD, node: Node<TreeModel>, childType: NodeType } export const addChild: ActionCreator<AddChildAction> = (node: Node<TreeModel>, childType: NodeType): AddChildAction => ({ type: ActionTypes.ADD_CHILD, node: node, childType: childType }); export interface AddItemAction extends Action { type: ActionTypes.ADD_ITEM, node: Node<Model> } export const addItem: ActionCreator<AddItemAction> = (node: Node<Model>) : AddItemAction => ({ type: ActionTypes.ADD_ITEM, node: node }); export interface DeleteItemAction extends Action { type: ActionTypes.DELETE_ITEM, node: Node<Model>, dataIndex: number | string } export const deleteItem : ActionCreator<DeleteItemAction> = (node: Node<Model>, dataIndex: number | string) : DeleteItemAction => ({ type: ActionTypes.DELETE_ITEM, node, dataIndex }); export interface MoveItemAction extends Action { type: ActionTypes.MOVE_ITEM, node: Node<Model>, source: number, target: number } export const moveItem: ActionCreator<MoveItemAction> = (node: Node<Model>, source : number, target : number) : MoveItemAction => ({ type: ActionTypes.MOVE_ITEM, node, source, target }); export interface ClearFieldErrorsAction extends Action { type: ActionTypes.CLEAR_FIELD_ERRORS } export const clearFieldErrors : ActionCreator<ClearFieldErrorsAction> = () : ClearFieldErrorsAction => ({ type: ActionTypes.CLEAR_FIELD_ERRORS }); export interface NavigateAction extends Action { type: ActionTypes.ON_NAVIGATE, previous: string, current: string } export const onNavigate: ActionCreator<NavigateAction> = (previousRouterPath: string, newRouterPath: string) => ({ type: ActionTypes.ON_NAVIGATE, previous: previousRouterPath, current: newRouterPath }); export const load = () => { return (dispatch: Dispatch<ActionCreator<Action>>) => { dispatch(loadStart()); dispatch(logInfo('Loading model and data files')); Promise.all([axios.get(`/schema.json`), axios.get(`/data.json`)]).then(values => { const model = migrateSchema(values[0].data); const data = values[1].data; dispatch(loadEnd(model, data)); dispatch(logInfo('Model and data files loaded from server')); }).catch(err => { dispatch(loadError()); dispatch(logError('Error while loading JSON files: ' + err)); }); } }; export interface LoadStartAction extends Action { type: ActionTypes.LOAD_START } const loadStart: ActionCreator<LoadStartAction> = () : LoadStartAction => ({ type: ActionTypes.LOAD_START }); export interface LoadEndAction extends Action { type: ActionTypes.LOAD_END, model: RootSchemaElement, data: object } export const loadEnd : ActionCreator<LoadEndAction> = (model, data) : LoadEndAction => ({ type: ActionTypes.LOAD_END, model, data }); export interface LoadErrorAction extends Action { type: ActionTypes.LOAD_ERROR } export const loadError: ActionCreator<LoadErrorAction> = () : LoadErrorAction => ({ type: ActionTypes.LOAD_ERROR }); export const save = () => { return (dispatch, getState : () => AppState) => { dispatch(saveStart()); const state = getState(); const promises = [] as Promise<any>[]; let beforeMessage; let afterMessage; if (state.main.schemaStale) { promises.push(axios.post('/schema.json', getState().main.tree.schema)); if (state.main.dataStale) { beforeMessage = 'Saving schema and data files'; afterMessage = 'Schema and data files saved on disk'; } else { beforeMessage = 'Saving schema file'; afterMessage = 'Schema file saved on disk'; } } if (state.main.dataStale) { promises.push(axios.post('/data.json', getState().main.tree.data)); if (!state.main.schemaStale) { beforeMessage = 'Saving data file'; afterMessage = 'Data file saved on disk'; } } dispatch(logInfo(beforeMessage)); Promise.all(promises).then(() => { dispatch(saveEnd()); dispatch(logInfo(afterMessage)); }).catch(err => { dispatch(saveError()); dispatch(logError('Error while saving JSON file: ' + err)); }); } }; export const download = () => { return (dispatch, getState : () => AppState) => { const schema = getState().main.tree.schema; const data = getState().main.tree.data; const zip = new JSZip(); zip.file('schema.json', JSON.stringify(schema)); zip.file('data.json', JSON.stringify(data)); zip.generateAsync({type:"blob"}) .then(function(blob) { if (window.navigator.msSaveOrOpenBlob) { // IE hack; see http://msdn.microsoft.com/en-us/library/ie/hh779016.aspx window.navigator.msSaveBlob(blob, "cms.zip"); } else { const a = window.document.createElement("a"); a.href = window.URL.createObjectURL(blob); a.download = "cms.zip"; document.body.appendChild(a); a.click(); // IE: "Access is denied"; see: https://connect.microsoft.com/IE/feedback/details/797361/ie-10-treats-blob-url-as-cross-origin-and-denies-access document.body.removeChild(a); } }); }; }; export interface SaveStartAction extends Action { type: ActionTypes.SAVE_START } const saveStart: ActionCreator<SaveStartAction> = () : SaveStartAction => ({ type: ActionTypes.SAVE_START }); export interface SaveEndAction extends Action { type: ActionTypes.SAVE_END } const saveEnd: ActionCreator<SaveEndAction> = () : SaveEndAction => ({ type: ActionTypes.SAVE_END }); export interface SaveErrorAction extends Action { type: ActionTypes.SAVE_ERROR } const saveError: ActionCreator<SaveErrorAction> = () : SaveErrorAction => ({ type: ActionTypes.SAVE_ERROR }); export interface InputValueAction extends Action { type: ActionTypes.INPUT_VALUE, node: Node<Model>, field: Field, event } export const inputValue: ActionCreator<InputValueAction> = (node: Node<Model>, field: Field, event) : InputValueAction => ({ type: ActionTypes.INPUT_VALUE, node, field, event }); export interface AddValueAction extends Action { type: ActionTypes.ADD_VALUE, node: Node<Model>, field: Field, value } export const addValue: ActionCreator<AddValueAction> = (node: Node<Model>, field, value) : AddValueAction => ({ type: ActionTypes.ADD_VALUE, node, field, value }); export const editField = (node : Node<Model>, fieldIndex: number) => { return (dispatch: (a: EditFieldAction | ModelAction) => SubmitFieldAction/*, getState: () => AppState*/) => { let field : Field; if (fieldIndex >= 0) { field = Cms.getField(node.model.fields[fieldIndex]); } else { field = { name: '', type: FieldType.String, key: false, description: '', className: '' } } dispatch(actions.change('field', field)); dispatch({ type: ActionTypes.EDIT_FIELD, node, fieldIndex }); } }; export interface EditFieldAction extends Action { type: ActionTypes.EDIT_FIELD; node: Node<Model>; fieldIndex: number; } export interface SubmitFieldAction { type: ActionTypes.SUBMIT_FIELD, field: Field, node: Node<Model>, fieldIndex: number } export const submitField = (field : Field) => { return (dispatch: (a: SubmitFieldAction) => SubmitFieldAction, getState: () => AppState) => { const state = getState(); if (state.editingField != null) { dispatch({ type: ActionTypes.SUBMIT_FIELD, field: field, node: Cms.findNode(state.main.tree, state.editingField.path), fieldIndex: state.editingField.fieldIndex }); } }; }; export interface CancelEditFieldAction extends Action { type: ActionTypes.CANCEL_EDIT_FIELD } export const cancelEditField: ActionCreator<CancelEditFieldAction> = () : CancelEditFieldAction => ({ type: ActionTypes.CANCEL_EDIT_FIELD }); export interface CancelConfirmAction extends Action { type: ActionTypes.CANCEL_CONFIRM } export const cancelConfirm: ActionCreator<CancelConfirmAction> = () : CancelConfirmAction => ({ type: ActionTypes.CANCEL_CONFIRM }); export interface ShowConfirmAction extends Action { type: ActionTypes.SHOW_CONFIRM; ok: () => void, title: string, body: string } export interface DeleteFieldAction extends Action { type: ActionTypes.DELETE_FIELD; node : Node<Model>; fieldIndex : number } export const deleteField = (node : Node<Model>, fieldIndex : number) => { return (dispatch : (action: ShowConfirmAction | DeleteFieldAction) => Action /*, getState */) => { dispatch({ type: ActionTypes.SHOW_CONFIRM, ok: () => { dispatch({ type: ActionTypes.DELETE_FIELD, node, fieldIndex }); }, title: 'Confirm delete field', body: `Are you sure you want to delete the field '${Cms.getField(node.model.fields[fieldIndex]).name}' ?` }); }; }; export interface DeleteNodeAction extends Action { type: ActionTypes.DELETE_NODE; node : Node<Model>; selection : Path; } export const deleteNode = (node : Node<Model>, selection : Path, history) => { return (dispatch: (action: DeleteNodeAction | ShowConfirmAction) => Action, getState : () => AppState) => { dispatch({ type: ActionTypes.SHOW_CONFIRM, ok: () => { dispatch({ type: ActionTypes.DELETE_NODE, node, selection }); navigate(dispatch as ((action: Action) => Action), getState, history); }, title: 'Confirm delete node', body: `Are you sure you want to delete the node '${node.model.name}' ?` }); }; }; export interface EditNodeAction extends Action { type: ActionTypes.EDIT_NODE, node: Node<Model> } export const editNode = (node : Node<Model>) => { return (dispatch : (action : EditNodeAction | ModelAction) => EditNodeAction) => { dispatch(actions.change('modelNode', node.model)); dispatch({ type: ActionTypes.EDIT_NODE, node }); } }; export interface CancelEditNodeAction extends Action { type: ActionTypes.CANCEL_EDIT_NODE } export const cancelEditNode : ActionCreator<CancelEditNodeAction> = () : CancelEditNodeAction => ({ type: ActionTypes.CANCEL_EDIT_NODE }); export interface SubmitNodeAction extends Action { type: ActionTypes.SUBMIT_NODE, model : Model, node : Node<Model> } export const submitNode: ActionCreator<SubmitNodeAction> = (node : Node<Model>, model: Model) : SubmitNodeAction => ({ type: ActionTypes.SUBMIT_NODE, model, node }); export interface ResetNavigateToAction extends Action { type: ActionTypes.RESET_NAVIGATE_TO } export const resetNavigateTo : ActionCreator<ResetNavigateToAction> = () : ResetNavigateToAction => ({ type: ActionTypes.RESET_NAVIGATE_TO }); const navigate = (dispatch: (action: Action) => void, getState: () => AppState, history) => { const navigateTo = getState().main.path; if (navigateTo !== null) { history.push(navigateTo); dispatch(resetNavigateTo()); } }; export interface SetViewModeAction extends Action { type: ActionTypes.SET_VIEW_MODE; mode: ViewMode; } export const setViewMode : ActionCreator<SetViewModeAction> = (mode: ViewMode) : SetViewModeAction => ({ type: ActionTypes.SET_VIEW_MODE, mode: mode }); export interface SetJsonFileAction extends Action { type: ActionTypes.SET_JSON_FILE; jsonFile: JsonFile; } export const setJsonFile : ActionCreator<SetJsonFileAction> = (jsonFile: JsonFile) : SetJsonFileAction => ({ type: ActionTypes.SET_JSON_FILE, jsonFile: jsonFile });
the_stack
import { ActionCreator, Dispatch } from 'redux'; import { ThunkAction } from 'redux-thunk'; import { checkIfProtected } from '../services/BrowserActionService'; import { cleanCookiesOperation } from '../services/CleanupService'; import { getContainerExpressionDefault, getSetting, getStoreId, isChrome, isFirefoxAndroid, showNotification, sleep, } from '../services/Libs'; import { ADD_ACTIVITY_LOG, ADD_EXPRESSION, CLEAR_ACTIVITY_LOG, CLEAR_EXPRESSIONS, COOKIE_CLEANUP, INCREMENT_COOKIE_DELETED_COUNTER, ReduxAction, ReduxConstants, REMOVE_ACTIVITY_LOG, REMOVE_EXPRESSION, REMOVE_LIST, RESET_ALL, RESET_COOKIE_DELETED_COUNTER, RESET_SETTINGS, UPDATE_EXPRESSION, UPDATE_SETTING, } from '../typings/ReduxConstants'; import { initialState } from './State'; export const addExpressionUI = (payload: Expression): ADD_EXPRESSION => ({ payload, type: ReduxConstants.ADD_EXPRESSION, }); export const clearExpressionsUI = ( payload: StoreIdToExpressionList, ): CLEAR_EXPRESSIONS => ({ payload, type: ReduxConstants.CLEAR_EXPRESSIONS, }); export const removeExpressionUI = (payload: Expression): REMOVE_EXPRESSION => ({ payload, type: ReduxConstants.REMOVE_EXPRESSION, }); export const updateExpressionUI = (payload: Expression): UPDATE_EXPRESSION => ({ payload, type: ReduxConstants.UPDATE_EXPRESSION, }); export const removeListUI = ( payload: keyof StoreIdToExpressionList, ): REMOVE_LIST => ({ payload, type: ReduxConstants.REMOVE_LIST, }); export const addExpression = (payload: Expression) => ( dispatch: Dispatch<ReduxAction>, getState: GetState, ): void => { // Sanitize the payload's storeId const storeId = getStoreId(getState(), payload.storeId); const defaultOptions = getContainerExpressionDefault( getState(), storeId, payload.listType as ListType, ); dispatch({ payload: { ...payload, cleanAllCookies: payload.cleanAllCookies ? payload.cleanAllCookies : defaultOptions.cleanAllCookies, cleanSiteData: payload.cleanSiteData ? payload.cleanSiteData : defaultOptions.cleanSiteData || [], storeId, }, type: ReduxConstants.ADD_EXPRESSION, }); checkIfProtected(getState()); }; export const clearExpressions = (payload: StoreIdToExpressionList) => ( dispatch: Dispatch<ReduxAction>, getState: GetState, ): void => { dispatch({ payload, type: ReduxConstants.CLEAR_EXPRESSIONS, }); checkIfProtected(getState()); }; export const removeExpression = (payload: Expression) => ( dispatch: Dispatch<ReduxAction>, getState: GetState, ): void => { dispatch({ payload: { ...payload, // Sanitize the payload's storeId storeId: getStoreId(getState(), payload.storeId), }, type: ReduxConstants.REMOVE_EXPRESSION, }); checkIfProtected(getState()); }; export const updateExpression = (payload: Expression) => ( dispatch: Dispatch<ReduxAction>, getState: GetState, ): void => { // Sanitize the payload's storeId const sanitizedStoreId = getStoreId(getState(), payload.storeId); dispatch({ payload: { ...payload, storeId: sanitizedStoreId, }, type: ReduxConstants.UPDATE_EXPRESSION, }); // Migration Downgrades between 3.5.0 and 3.4.0 // Uncheck 'Keep LocalStorage' on New ... Expressions if ( payload.expression === `_Default:${payload.listType}` && sanitizedStoreId === 'default' && payload.cleanSiteData ) { if (payload.cleanSiteData.includes(SiteDataType.LOCALSTORAGE)) { if ( !getSetting( getState(), `${payload.listType.toLowerCase()}CleanLocalstorage` as SettingID, ) ) { // Enable Deprecated Option dispatch({ payload: { name: `${payload.listType.toLowerCase()}CleanLocalstorage`, value: true, }, type: ReduxConstants.UPDATE_SETTING, }); } } else { if ( getSetting( getState(), `${payload.listType.toLowerCase()}CleanLocalstorage` as SettingID, ) ) { // Disable Deprecated Option dispatch({ payload: { name: `${payload.listType.toLowerCase()}CleanLocalstorage`, value: false, }, type: ReduxConstants.UPDATE_SETTING, }); } } } checkIfProtected(getState()); }; export const removeList = (payload: keyof StoreIdToExpressionList) => ( dispatch: Dispatch<ReduxAction>, getState: GetState, ): void => { dispatch({ payload, type: ReduxConstants.REMOVE_LIST, }); checkIfProtected(getState()); }; export const addActivity = (payload: ActivityLog): ADD_ACTIVITY_LOG => ({ payload, type: ReduxConstants.ADD_ACTIVITY_LOG, }); export const clearActivities = (): CLEAR_ACTIVITY_LOG => ({ type: ReduxConstants.CLEAR_ACTIVITY_LOG, }); export const removeActivity = (payload: ActivityLog): REMOVE_ACTIVITY_LOG => ({ payload, type: ReduxConstants.REMOVE_ACTIVITY_LOG, }); export const incrementCookieDeletedCounter = ( payload: number, ): INCREMENT_COOKIE_DELETED_COUNTER => ({ payload, type: ReduxConstants.INCREMENT_COOKIE_DELETED_COUNTER, }); export const resetCookieDeletedCounter = (): RESET_COOKIE_DELETED_COUNTER => ({ type: ReduxConstants.RESET_COOKIE_DELETED_COUNTER, }); export const updateSetting = (payload: Setting): UPDATE_SETTING => ({ payload, type: ReduxConstants.UPDATE_SETTING, }); export const resetSettings = (): RESET_SETTINGS => ({ type: ReduxConstants.RESET_SETTINGS, }); export const resetAll = (): RESET_ALL => ({ type: ReduxConstants.RESET_ALL, }); // Validates the setting object and adds missing settings if it doesn't already exist in the initialState export const validateSettings: ActionCreator<ThunkAction< void, State, null, ReduxAction >> = () => (dispatch, getState) => { const { cache, settings } = getState(); const initialSettings = initialState.settings; const settingKeys = Object.keys(settings); const initialSettingKeys = Object.keys(initialSettings); settingKeys.forEach((k) => { // Properties in a individual setting do not match up. Repopulate from the default one and reuse existing value if ( initialSettings[k] !== undefined && Object.keys(settings[k]).length !== Object.keys(initialSettings[k]).length ) { dispatch({ payload: { ...initialSettings[k], value: settings[k].value, }, type: ReduxConstants.UPDATE_SETTING, }); } }); // Missing a setting if (settingKeys.length !== initialSettingKeys.length) { initialSettingKeys.forEach((k) => { if (settings[k] === undefined) { dispatch({ payload: initialSettings[k], type: ReduxConstants.UPDATE_SETTING, }); } }); } function disableSettingIfTrue(s: Setting) { if (s && s.value) { dispatch({ payload: { ...s, value: false, }, type: ReduxConstants.UPDATE_SETTING, }); } } // Disable unusable setting in Chrome if (isChrome(cache)) { disableSettingIfTrue(settings[SettingID.CONTEXTUAL_IDENTITIES]); } // Disable unusable setting in Firefox Android if (isFirefoxAndroid(cache)) { disableSettingIfTrue(settings[SettingID.NUM_COOKIES_ICON]); disableSettingIfTrue(settings[SettingID.CLEANUP_LOCALSTORAGE_OLD]); disableSettingIfTrue(settings[SettingID.CLEANUP_LOCALSTORAGE]); disableSettingIfTrue(settings[SettingID.CONTEXTUAL_IDENTITIES]); disableSettingIfTrue(settings[SettingID.CONTEXT_MENUS]); } // Minimum 1 second autoclean delay. if (settings[SettingID.CLEAN_DELAY].value < 1) { dispatch({ payload: { name: SettingID.CLEAN_DELAY, value: 1, }, type: ReduxConstants.UPDATE_SETTING, }); } // Maximum 2147483 seconds due to signed 32-bit Integer (ms x 1000) if (settings[SettingID.CLEAN_DELAY].value > 2147483) { dispatch({ payload: { name: SettingID.CLEAN_DELAY, value: 2147483, }, type: ReduxConstants.UPDATE_SETTING, }); } // If show cookie count in badge is disabled, force change icon color instead if ( !settings[SettingID.NUM_COOKIES_ICON].value && settings[SettingID.KEEP_DEFAULT_ICON].value ) { disableSettingIfTrue(settings[SettingID.KEEP_DEFAULT_ICON]); } }; export const cookieCleanupUI = ( payload: CleanupProperties, ): COOKIE_CLEANUP => ({ payload, type: ReduxConstants.COOKIE_CLEANUP, }); // Cookie Cleanup operation that is to be called from the React UI export const cookieCleanup: ActionCreator<ThunkAction< void, State, null, ReduxAction >> = ( options: CleanupProperties = { greyCleanup: false, ignoreOpenTabs: false }, ) => async (dispatch, getState) => { const cleanupDoneObject = await cleanCookiesOperation(getState(), options); if (!cleanupDoneObject) return; const { setOfDeletedDomainCookies, cachedResults } = cleanupDoneObject; const { browsingDataCleanup, recentlyCleaned, siteDataCleaned, } = cachedResults as ActivityLog; // Increment the count if (recentlyCleaned !== 0 && getSetting(getState(), SettingID.STAT_LOGGING)) { dispatch(incrementCookieDeletedCounter(recentlyCleaned)); } if ( (recentlyCleaned !== 0 || siteDataCleaned) && getSetting(getState(), SettingID.STAT_LOGGING) ) { dispatch(addActivity(cachedResults)); } // Show notifications after cleanup if (getSetting(getState(), SettingID.NOTIFY_AUTO)) { const domainsAll = new Set<string>(); Object.values((cachedResults as ActivityLog).storeIds).forEach((v) => { v.forEach((d) => domainsAll.add(d.cookie.hostname)); }); const bDomains = new Set<string>(); // Count for Summary Notification if (browsingDataCleanup) { for (const domains of Object.values(browsingDataCleanup)) { if (!domains || domains.length === 0) continue; domains.forEach((d) => bDomains.add(d)); } bDomains.forEach((d) => domainsAll.add(d)); } if (setOfDeletedDomainCookies.length > 0) { // Cookie Notification const notifyMessage = browser.i18n.getMessage('notificationContent', [ recentlyCleaned.toString(), domainsAll.size.toString(), (setOfDeletedDomainCookies as string[]).slice(0, 5).join(', '), ]); showNotification({ duration: getSetting(getState(), SettingID.NOTIFY_DURATION) as number, msg: `${notifyMessage} ...`, title: browser.i18n.getMessage('notificationTitle'), }); await sleep(750); } // Here we just show a generic 'Site Data' cleaned instead of the specifics, with all domains. if (siteDataCleaned && browsingDataCleanup && bDomains.size > 0) { await showNotification({ duration: getSetting(getState(), SettingID.NOTIFY_DURATION) as number, msg: browser.i18n.getMessage('activityLogSiteDataDomainsText', [ browser.i18n.getMessage('siteDataText'), Array.from(bDomains).join(', '), ]), title: browser.i18n.getMessage('notificationTitleSiteData'), }); } } };
the_stack
import { Vector2, Vector4 } from '../math/index' import { VertexProgram } from './shader' import { FragmentProgram } from './shader' import { DepthBuffer } from './depth' import { Vertex } from './vertex' import { RenderTarget } from './target' export class Raster { // triangle: registers private static position_0 = Vector4.zero() private static position_1 = Vector4.zero() private static position_2 = Vector4.zero() private static clippos_0 = Vector2.zero() private static clippos_1 = Vector2.zero() private static clippos_2 = Vector2.zero() private static varying_0 = Vertex.create() private static varying_1 = Vertex.create() private static varying_2 = Vertex.create() private static corrected_varying_0 = Vertex.create() private static corrected_varying_1 = Vertex.create() private static corrected_varying_2 = Vertex.create() /** Renders a triangle with the given arguments */ public static triangle<TUniform>( vertexProgram: VertexProgram<TUniform>, fragmentProgram: FragmentProgram<TUniform>, depth: DepthBuffer, target: RenderTarget, uniform: TUniform, vertex_0: Vertex, vertex_1: Vertex, vertex_2: Vertex ): void { // Compute half width and height const width = target.width const height = target.height const half_width = width * 0.5 const half_height = height * 0.5 // Execute vertex shader. vertexProgram.main(uniform, vertex_0, Raster.varying_0, Raster.position_0) vertexProgram.main(uniform, vertex_1, Raster.varying_1, Raster.position_1) vertexProgram.main(uniform, vertex_2, Raster.varying_2, Raster.position_2) // Prevent z less than 0.0 errors, discard the triangle. if (Raster.position_0.v[2] < 0.0 || Raster.position_1.v[2] < 0.0 || Raster.position_2.v[2] < 0.0) { // todo: we should consider clipping the triangle here. return } // Calculate positions in clip space. Raster.clippos_0.v[0] = (( Raster.position_0.v[0] / Raster.position_0.v[3]) * width) + half_width Raster.clippos_0.v[1] = ((-Raster.position_0.v[1] / Raster.position_0.v[3]) * height) + half_height Raster.clippos_1.v[0] = (( Raster.position_1.v[0] / Raster.position_1.v[3]) * width) + half_width Raster.clippos_1.v[1] = ((-Raster.position_1.v[1] / Raster.position_1.v[3]) * height) + half_height Raster.clippos_2.v[0] = (( Raster.position_2.v[0] / Raster.position_2.v[3]) * width) + half_width Raster.clippos_2.v[1] = ((-Raster.position_2.v[1] / Raster.position_2.v[3]) * height) + half_height // Correct varying with respect to w Vertex.correct(Raster.varying_0, Raster.position_0.v[3], Raster.corrected_varying_0) Vertex.correct(Raster.varying_1, Raster.position_1.v[3], Raster.corrected_varying_1) Vertex.correct(Raster.varying_2, Raster.position_2.v[3], Raster.corrected_varying_2) // Backface cull and render fragments if (Raster.edge(Raster.clippos_0, Raster.clippos_1, Raster.clippos_2) >= 0.0) { Raster.draw_triangle<TUniform>( fragmentProgram, depth, target, uniform, Raster.corrected_varying_0, Raster.corrected_varying_1, Raster.corrected_varying_2, Raster.clippos_0, Raster.clippos_1, Raster.clippos_2, (1.0 / Raster.position_0.v[3]), (1.0 / Raster.position_1.v[3]), (1.0 / Raster.position_2.v[3]), ) } } private static calculate_x_scan_range(y: number, ordered_0: Vector2, ordered_1: Vector2, ordered_2: Vector2, ordered_3: Vector2): [number, number] { const gradient_0 = (ordered_0.v[1] !== ordered_1.v[1]) ? (y - ordered_0.v[1]) / (ordered_1.v[1] - ordered_0.v[1]) : 1.0 const gradient_1 = (ordered_2.v[1] !== ordered_3.v[1]) ? (y - ordered_2.v[1]) / (ordered_3.v[1] - ordered_2.v[1]) : 1.0 const min_x = ordered_0.v[0] + (ordered_1.v[0] - ordered_0.v[0]) * Raster.clamp(gradient_0, 0.0, 1.0) const max_x = ordered_2.v[0] + (ordered_3.v[0] - ordered_2.v[0]) * Raster.clamp(gradient_1, 0.0, 1.0) return [min_x | 0, max_x | 0] } // draw_triangle: registers private static ordered_0 = Vector2.zero() private static ordered_1 = Vector2.zero() private static ordered_2 = Vector2.zero() private static draw_triangle<TUniform>( fragment: FragmentProgram<TUniform>, depth: DepthBuffer, target: RenderTarget, uniform: TUniform, varying_0: Vertex, varying_1: Vertex, varying_2: Vertex, clippos_0: Vector2, clippos_1: Vector2, clippos_2: Vector2, corrected_z_0: number, corrected_z_1: number, corrected_z_2: number, ) { // Clone clippos for sorting. Raster.ordered_0.v[0] = clippos_0.v[0] Raster.ordered_0.v[1] = clippos_0.v[1] Raster.ordered_1.v[0] = clippos_1.v[0] Raster.ordered_1.v[1] = clippos_1.v[1] Raster.ordered_2.v[0] = clippos_2.v[0] Raster.ordered_2.v[1] = clippos_2.v[1] // Sort ordered y-descending. if (Raster.ordered_0.v[1] > Raster.ordered_1.v[1]) { Raster.swap(Raster.ordered_0, Raster.ordered_1); } if (Raster.ordered_1.v[1] > Raster.ordered_2.v[1]) { Raster.swap(Raster.ordered_1, Raster.ordered_2); } if (Raster.ordered_0.v[1] > Raster.ordered_1.v[1]) { Raster.swap(Raster.ordered_0, Raster.ordered_1); } // Draw scanlines (may need further optimization) for (let y = (Raster.ordered_0.v[1] | 0); y <= (Raster.ordered_2.v[1] | 0); y++) { if (y < Raster.ordered_1.v[1]) { const [min_x, max_x] = Raster.calculate_x_scan_range( y, Raster.ordered_0, Raster.ordered_2, Raster.ordered_0, Raster.ordered_1, ); Raster.draw_line( fragment, depth, target, uniform, clippos_0, clippos_1, clippos_2, varying_0, varying_1, varying_2, corrected_z_0, corrected_z_1, corrected_z_2, min_x, max_x, y, ) } else { const [min_x, max_x] = Raster.calculate_x_scan_range( y, Raster.ordered_0, Raster.ordered_2, Raster.ordered_1, Raster.ordered_2, ); Raster.draw_line( fragment, depth, target, uniform, clippos_0, clippos_1, clippos_2, varying_0, varying_1, varying_2, corrected_z_0, corrected_z_1, corrected_z_2, min_x, max_x, y, ) } } for (let y = (Raster.ordered_0.v[1] | 0); y <= (Raster.ordered_2.v[1] | 0); y++) { if (y < Raster.ordered_1.v[1]) { const [min_x, max_x] = Raster.calculate_x_scan_range( y, Raster.ordered_0, Raster.ordered_1, Raster.ordered_0, Raster.ordered_2, ); Raster.draw_line( fragment, depth, target, uniform, clippos_0, clippos_1, clippos_2, varying_0, varying_1, varying_2, corrected_z_0, corrected_z_1, corrected_z_2, min_x, max_x, y, ) } else { const [min_x, max_x] = Raster.calculate_x_scan_range( y, Raster.ordered_1, Raster.ordered_2, Raster.ordered_0, Raster.ordered_2, ); Raster.draw_line( fragment, depth, target, uniform, clippos_0, clippos_1, clippos_2, varying_0, varying_1, varying_2, corrected_z_0, corrected_z_1, corrected_z_2, min_x, max_x, y, ) } } } // draw_line: registers private static fragment_varying = Vertex.create() private static fragment_coord = Vector2.zero() private static fragment_color = Vector4.zero() public static draw_line<TUniform>( fragment: FragmentProgram<TUniform>, depth: DepthBuffer, target: RenderTarget, uniform: TUniform, clippos_0: Vector2, clippos_1: Vector2, clippos_2: Vector2, varying_0: Vertex, varying_1: Vertex, varying_2: Vertex, corrected_z_0: number, corrected_z_1: number, corrected_z_2: number, min_x: number, max_x: number, y: number, ) { // Exit if outside viewport height. if (y < 0 || y >= target.height) { return; } // min | max within viewport width. min_x = Math.max(min_x, 0); max_x = Math.min(max_x, target.width); // Calculate edge value const edge = Raster.edge(clippos_0, clippos_1, clippos_2); for (let x = min_x; x < max_x; x++) { // Store X, Y in fragment coord. Raster.fragment_coord.v[0] = x Raster.fragment_coord.v[1] = y // Calulate weights across triangle clippos. const weight_0 = Raster.edge(clippos_2, clippos_1, Raster.fragment_coord) / edge const weight_1 = Raster.edge(clippos_0, clippos_2, Raster.fragment_coord) / edge const weight_2 = Raster.edge(clippos_1, clippos_0, Raster.fragment_coord) / edge // Calculate depth of fragment. const calculated_depth = (weight_0 * corrected_z_0) + (weight_1 * corrected_z_1) + (weight_2 * corrected_z_2); // Check depth and discard. Otherwise interpolate and render. if (calculated_depth <= depth.get(x | 0, y | 0)) { // Set the depth component depth.set(x, y, calculated_depth) // Interpolate the varying Vertex.interpolate( varying_0, varying_1, varying_2, weight_0, weight_1, weight_2, calculated_depth, Raster.fragment_varying ) // Execute fragment shader. fragment.main( uniform, Raster.fragment_varying, Raster.fragment_color ) // Set color. target.set(x, y, Raster.fragment_color) } } } private static edge(v0: Vector2, v1: Vector2, v2: Vector2): number { return (v2.v[0] - v0.v[0]) * (v1.v[1] - v0.v[1]) - (v2.v[1] - v0.v[1]) * (v1.v[0] - v0.v[0]) } public static clamp(f: number, min: number, max: number): number { if (f < min) return min if (f > max) return max return f } private static swap(v0: Vector2, v1: Vector2) { const tx = v0.v[0] const ty = v0.v[1] v0.v[0] = v1.v[0] v0.v[1] = v1.v[1] v1.v[0] = tx v1.v[1] = ty } }
the_stack
interface PlayerInfo { score: number; team: string; status: string; color: string; }; interface WormDirection { NONE : number; UP : number; DOWN : number; RIGHT : number; LEFT : number; }; // // Worm: Worm class // class Worm { // Enums for worm direction direction : WormDirection; upVector : number[]; downVector : number[]; rightVector : number[]; leftVector : number[]; zeroVector : number[]; boardSpacing : number; boardWidth : number; boardHeight : number; maxPlayers : number; directionVector : number[]; partsPositionX : any; // number[]; partsPositionY : any; // number[]; previousTailX : number; previousTailY : number; killedBy : number; updated : boolean; playerInfo : PlayerInfo; hasLooped : boolean; // Changes the worm's direction changeDirection(newDirection) { var direction = this.direction; var directionVector = this.directionVector; var newDirectionVector; switch (newDirection) { case direction.UP: if (directionVector !== this.downVector) { newDirectionVector = this.upVector; } break; case direction.DOWN: if (directionVector !== this.upVector) { newDirectionVector = this.downVector; } break; case direction.RIGHT: if (directionVector !== this.leftVector) { newDirectionVector = this.rightVector; } break; case direction.LEFT: if (directionVector !== this.rightVector) { newDirectionVector = this.leftVector; } break; default: newDirectionVector = this.zeroVector; break; } if (newDirectionVector !== undefined) { if (directionVector !== newDirectionVector) { this.directionVector = newDirectionVector; this.updated = true; } } } // Update called every frame update() { if (this.directionVector !== this.zeroVector) { if (this.partsPositionX.length === 1) { this.playerInfo.status = "is looking for food."; } this.moveBody(); this.moveHead(); this.updated = true; } else { this.playerInfo.status = "is thinking about getting some lunch."; } this.killedBy = null; } // Collided with something die(killedBy) { this.directionVector = this.zeroVector; this.killedBy = killedBy; this.updated = true; this.playerInfo.status = "is bird-food."; } // Serialize worm information serialize() { var directionVector = this.directionVector; var direction = this.direction; var dir; if (directionVector === this.downVector) { dir = direction.DOWN; } else if (directionVector === this.upVector) { dir = direction.UP; } else if (directionVector === this.leftVector) { dir = direction.LEFT; } else if (directionVector === this.rightVector) { dir = direction.RIGHT; } else //if (directionVector === this.zeroVector) { dir = direction.NONE; } var data = { dir: dir, x: this.partsPositionX.slice(), y: this.partsPositionY.slice(), score: this.playerInfo.score, color: this.playerInfo.color, team: this.playerInfo.team, status: this.playerInfo.status, killedBy: <number>undefined }; var killedBy = this.killedBy; if (killedBy !== null) { data.killedBy = killedBy; } return data; } // Deserialize from external data deserialize(isHost, data) { var partsPositionX = this.partsPositionX; var partsPositionY = this.partsPositionY; var numParts = partsPositionX.length; if (!isHost) { var killedBy = data.killedBy; if (killedBy !== undefined) { this.killedBy = killedBy; } else { this.killedBy = null; } } var direction = this.direction; switch (data.dir) { case direction.UP: this.directionVector = this.upVector; break; case direction.DOWN: this.directionVector = this.downVector; break; case direction.RIGHT: this.directionVector = this.rightVector; break; case direction.LEFT: this.directionVector = this.leftVector; break; default: this.directionVector = this.zeroVector; break; } var newPartsPositionX = data.x; var newPartsPositionY = data.y; var newNumParts = newPartsPositionX.length; if (numParts !== newNumParts) { partsPositionX.length = newNumParts; partsPositionY.length = newNumParts; } for (var n = 0; n < newNumParts; n += 1) { partsPositionX[n] = newPartsPositionX[n]; partsPositionY[n] = newPartsPositionY[n]; } this.playerInfo.score = data.score; this.playerInfo.team = data.team; this.playerInfo.status = data.status; this.playerInfo.color = data.color; } // Moves all of worm parts as required moveBody() { var partsPositionX = this.partsPositionX; var partsPositionY = this.partsPositionY; var length = partsPositionX.length; var tailIndex = (length - 1); var i; // Update the previous tail position this.previousTailX = partsPositionX[tailIndex]; this.previousTailY = partsPositionY[tailIndex]; // Copy positions from back to front for (i = tailIndex; i > 0; i -= 1) { partsPositionX[i] = partsPositionX[i - 1]; partsPositionY[i] = partsPositionY[i - 1]; } } // Moves head and loops over board edge if necessary moveHead() { var boardWidth = this.boardWidth; var boardHeight = this.boardHeight; var partsPositionX = this.partsPositionX; var partsPositionY = this.partsPositionY; var directionVector = this.directionVector; var headPositionX = partsPositionX[0]; var headPositionY = partsPositionY[0]; // Update head of snake headPositionX += directionVector[0]; headPositionY += directionVector[1]; this.hasLooped = true; // Adjust if it has gone off edge if (headPositionX === boardWidth) { headPositionX = 0; } else if (headPositionX === -1) { headPositionX = boardWidth - 1; } else if (headPositionY === boardHeight) { headPositionY = 0; } else if (headPositionY === -1) { headPositionY = boardHeight - 1; } else { this.hasLooped = false; } partsPositionX[0] = headPositionX; partsPositionY[0] = headPositionY; } // Increases worm length by 1 addToTail() { var partsPositionX = this.partsPositionX; var partsPositionY = this.partsPositionY; var length = partsPositionX.length; partsPositionX[length] = this.previousTailX; partsPositionY[length] = this.previousTailY; this.updated = true; if (length > 2) { this.playerInfo.status = "is still hungry."; } if (length > 4) { this.playerInfo.status = "is getting full."; } if (length > 8) { this.playerInfo.status = "is eating too much."; } if (length > 10) { this.playerInfo.status = "is putting on a bit of weight."; } if (length > 12) { this.playerInfo.status = "is feeling bloated."; } } // Tests for self intersection isIntersectingSelf() { var partsPositionX = this.partsPositionX; var partsPositionY = this.partsPositionY; var length = partsPositionX.length; var headX = partsPositionX[0]; var headY = partsPositionY[0]; var i; for (i = 1; i < length; i += 1) { if (partsPositionX[i] === headX && partsPositionY[i] === headY) { return true; } } return false; } // Tests for intersection with other worms isIntersecting(otherWorm) { var otherPartsPositionX = otherWorm.partsPositionX; var otherPartsPositionY = otherWorm.partsPositionY; var otherLength = otherPartsPositionX.length; var headX = this.partsPositionX[0]; var headY = this.partsPositionY[0]; var i; for (i = 0; i < otherLength; i += 1) { if (otherPartsPositionX[i] === headX && otherPartsPositionY[i] === headY) { return true; } } return false; } // Tests if position x,y is covered by worm containsPosition(x, y) { var partsPositionX = this.partsPositionX; var partsPositionY = this.partsPositionY; var length = partsPositionX.length; var i; for (i = 0; i < length; i += 1) { if (partsPositionX[i] === x && partsPositionY[i] === y) { return true; } } return false; } // Test if position x,y is covered by worm head isOnHead(x, y) { if (this.partsPositionX[0] === x && this.partsPositionY[0] === y) { return true; } return false; } // Resets worm to original state reset(x, y) { this.hasLooped = false; var partsPositionX = this.partsPositionX; var partsPositionY = this.partsPositionY; this.directionVector = this.zeroVector; partsPositionX.length = 1; partsPositionY.length = 1; partsPositionX[0] = x; partsPositionY[0] = y; this.previousTailX = x; this.previousTailY = y; this.playerInfo.color = Math.random() > 0.5 ? "green" : "yellow"; this.playerInfo.score = 0; this.updated = true; } static create(gameSettings): Worm { var worm = new Worm(); worm.boardSpacing = gameSettings.boardSpacing; worm.boardWidth = gameSettings.width; worm.boardHeight = gameSettings.height; worm.maxPlayers = gameSettings.maxPlayers; worm.directionVector = worm.zeroVector; worm.partsPositionX = []; worm.partsPositionY = []; worm.previousTailX = 0; worm.previousTailY = 0; worm.killedBy = null; worm.updated = false; worm.playerInfo = { score: 0, team: "Worms", status: "is thinking about getting some lunch.", color: Math.random() > 0.5 ? "green" : "yellow" }; return worm; } } Worm.prototype.direction = { NONE : -1, UP : 0, DOWN : 1, RIGHT : 2, LEFT : 3 }; Worm.prototype.upVector = [ 0, 1]; Worm.prototype.downVector = [ 0, -1]; Worm.prototype.rightVector = [ 1, 0]; Worm.prototype.leftVector = [-1, 0]; Worm.prototype.zeroVector = [ 0, 0];
the_stack
import * as React from 'react'; import styles from './ImageGallery.module.scss'; import { ImageGalleryProps } from './ImageGalleryProps'; import { ImageGalleryState } from './ImageGalleryState'; import { escape } from '@microsoft/sp-lodash-subset'; import spservices from '../../../../services/spservices'; import Gallery from 'react-grid-gallery'; import { WebPartTitle } from "@pnp/spfx-controls-react/lib/WebPartTitle"; import RenderImage from '../RenderImage/RenderImage'; import { Spinner, SpinnerSize, MessageBar, MessageBarType, Label, Icon, DocumentCard, DefaultButton, PrimaryButton, ImageFit, Image, Dialog, DialogType, DialogFooter, ActionButton, IButtonProps, IconButton, CommandBarButton, ImageLoadState, Panel, PanelType } from 'office-ui-fabric-react'; import { Placeholder } from "@pnp/spfx-controls-react/lib/Placeholder"; import { DisplayMode } from '@microsoft/sp-core-library'; import { FontSizes, } from '@uifabric/fluent-theme/lib/fluent/FluentType'; import { CommunicationColors } from '@uifabric/fluent-theme/lib/fluent/FluentColors'; import * as strings from 'ImageGalleryWebPartStrings'; import * as microsoftTeams from '@microsoft/teams-js'; import "react-responsive-carousel/lib/styles/carousel.min.css"; import { Carousel } from 'react-responsive-carousel'; import 'video-react/dist/video-react.css'; // import css import { Player, BigPlayButton } from 'video-react'; import './carousel.scss'; import { IGalleryImages } from './IGalleryImages'; import Slider from "react-slick"; import "slick-carousel/slick/slick.css"; import "slick-carousel/slick/slick-theme.css"; import * as $ from 'jquery'; /** * * * @export * @class ImageGallery * @extends {React.Component<ImageGalleryProps, ImageGalleryState>} */ export default class ImageGallery extends React.Component<ImageGalleryProps, ImageGalleryState> { private spService: spservices = null; private images: any; private galleryImages: IGalleryImages[] = []; private _teamsContext: microsoftTeams.Context; private _teamsTheme: string = ''; private _carouselImages: any; private _slider: any = null; constructor(props: ImageGalleryProps) { super(props); this.spService = new spservices(this.props.context); if (this.props.context.microsoftTeams) { this.props.context.microsoftTeams.getContext(context => { this._teamsContext = context; console.log('ctt', this._teamsContext.theme); this.setState({ teamsTheme: this._teamsContext.theme }); }); } this.state = { images: [], isLoading: false, errorMessage: '', hasError: false, teamsTheme: 'default', isPlaying: true, showLithbox: false, photoIndex: 0, isloadingCarousel: false, carouselImages: [], autoplay: true, }; this.onPlayResume = this.onPlayResume.bind(this); } /** * * * @protected * @returns {Promise<any>} * @memberof ImageGallery */ /** * * * @private * @memberof ImageGallery */ private async loadPictures() { this.setState({ isLoading: true, hasError: false }); const tenantUrl = `https://${location.host}`; try { this.images = await this.spService.getImages(this.props.siteUrl, this.props.list, this.props.numberImages); for (const image of this.images) { const pURL = `${tenantUrl}/_api/v2.0/sharePoint:${image.File.ServerRelativeUrl}:/driveItem/thumbnails/0/large/content?preferNoRedirect=true `; const thumbnailUrl = `${tenantUrl}/_api/v2.0/sharePoint:${image.File.ServerRelativeUrl}:/driveItem/thumbnails/0/c240x240/content?preferNoRedirect=true `; let mediaType: string = ''; switch (image.File_x0020_Type) { case ('jpg'): case ('jpeg'): case ('png'): case ('tiff'): case ('gif'): mediaType = 'image'; break; case ('mp4'): mediaType = 'video'; break; default: continue; break; } this.galleryImages.push( { imageUrl: pURL, mediaType: mediaType, ServerRelativeUrl: image.File.ServerRelativeUrl, thumbnail: thumbnailUrl, thumbnailWidth: 240, thumbnailHeight: 180, caption: image.Title ? image.Title : image.File.Name, // thumbnailCaption: image.File.Name, customOverlay: <Label style={{ fontSize: FontSizes.size18, bottom: 0, transition: '.5s ease', textAlign: 'center', width: '100%', position: 'absolute', background: 'rgba(0, 0, 0, 0.5)', color: '#f1f1f1', padding: '10px' }}> {image.Title ? image.Title : image.File.Name} </Label> }, ); // Create Carousel Slides from Images this._carouselImages = this.galleryImages.map((GalleryImage, i) => { return ( <div className='slideLoading'> <div style={{}} > <Label style={{ fontSize: FontSizes.size18, textAlign: 'center', width: '100%', padding: '5px' }}> <ActionButton data-automation-id="test" iconProps={{ iconName: 'Download', styles: { root: { fontSize: FontSizes.size18, } } }} allowDisabledFocus={true} style={{ padding: '10px', fontSize: FontSizes.size18 }} checked={true} href={`${this.props.context.pageContext.legacyPageContext.siteAbsoluteUrl}/_layouts/download.aspx?SourceUrl=${GalleryImage.ServerRelativeUrl}`} > {GalleryImage.caption} </ActionButton> </Label> </div> {GalleryImage.mediaType == 'video' ? <div > <Player poster={GalleryImage.imageUrl} style={{ width: '100%', height: '640px' }} > <BigPlayButton position="center" /> <source src={GalleryImage.ServerRelativeUrl} /> </Player> </div> : <div style={{ maxWidth: '100%' }}> <Image src={GalleryImage.imageUrl} style={{ height: 'auto', overflow: 'hidden', maxHeight: '100%' }} onLoadingStateChange={async (loadState: ImageLoadState) => { console.log('imageload Status ' + i, loadState, GalleryImage.imageUrl); if (loadState == ImageLoadState.loaded) { this.setState({ isloadingCarousel: false }); } }} height={'400px'} imageFit={ImageFit.contain} /> </div> } </div> ); } ); } } catch (error) { this.setState({ hasError: true, errorMessage: decodeURIComponent(error.message) }); } } public async componentDidMount() { await this.loadPictures(); this.setState({ images: this.galleryImages, carouselImages: this._carouselImages, isLoading: false, isloadingCarousel: false }); } /** * * * @param {ImageGalleryProps} prevProps * @returns * @memberof ImageGallery */ public async componentDidUpdate(prevProps: ImageGalleryProps) { if (!this.props.list || !this.props.siteUrl) return; // Get Properties change if (prevProps.list !== this.props.list || prevProps.numberImages !== this.props.numberImages) { this.galleryImages = []; this._carouselImages = []; await this.loadPictures(); this.setState({ images: this.galleryImages, carouselImages: this._carouselImages, isLoading: false }); } } /** * * * @private * @memberof ImageGallery */ private onConfigure() { // Context of the web part this.props.context.propertyPane.open(); } private handleclick = event => { const value = event.currentTarget.attributes.getNamedItem("data-i").value; this.setState({ showLithbox: true, photoIndex: Number(value), isloadingCarousel: true }); } private onNext = () => { this._slider.slickNext(); } private onPrev = () => { this._slider.slickPrev(); } private async onPlayResume() { const { isPlaying } = this.state; if (isPlaying) { this._slider.slickPause(); } else { this._slider.slickPlay(); } this.setState({ isPlaying: !isPlaying }); } private onDialogClose = (ev: React.MouseEvent<HTMLButtonElement>) => { this.setState({ showLithbox: false }); } /** * * * @returns {React.ReactElement<ImageGalleryProps>} * @memberof ImageGallery */ public render(): React.ReactElement<ImageGalleryProps> { console.log('theme', this.state.teamsTheme); const sliderSettings = { dots: false, infinite: true, speed: 500, slidesToShow: 1, slidesToScroll: 1, lazyLoad: 'progressive', autoplaySpeed: 3000, initialSlide: this.state.photoIndex, arrows: false, draggable: false, adaptiveHeight: true, useCSS: true, useTransform: true, }; return ( <div className={styles.container}> <div> { this.state.teamsTheme == 'dark' ? <Label style={{color:'white', fontSize: FontSizes.size24}}>{this.props.title}</Label> : <WebPartTitle displayMode={this.props.displayMode} title={this.props.title} updateProperty={this.props.updateProperty} /> } </div> { (!this.props.list) ? <Placeholder iconName='Edit' iconText={strings.WebpartConfigIconText} description={strings.WebpartConfigDescription} buttonLabel={strings.WebPartConfigButtonLabel} hideButton={this.props.displayMode === DisplayMode.Read} onConfigure={this.onConfigure.bind(this)} /> : this.state.hasError ? <MessageBar messageBarType={MessageBarType.error}> {this.state.errorMessage} </MessageBar> : this.state.isLoading ? <Spinner size={SpinnerSize.large} label='loading images...' /> : this.state.images.length == 0 ? <div style={{ width: '300px', margin: 'auto' }}> <Icon iconName="PhotoCollection" style={{ fontSize: '250px', color: '#d9d9d9' }} /> <Label style={{ width: '250px', margin: 'auto', fontSize: FontSizes.size20 }}>No images in the library</Label> </div> : <div style={{ width: '100%', height: '100%', overflow: 'hidden' }}> { this.state.images.map((item, i) => { let v: boolean = true; return ( <div onClick={this.handleclick} data-i={i} id={i.toString()} style={{ width: '230px', display: 'inline-block', verticalAlign: 'top', margin: '2px' }}> <DocumentCard> <RenderImage displayCaption={v} image={item} context={this.props.context} /> </DocumentCard> </div> ); }) } <Panel isOpen={this.state.showLithbox} onDismiss={this.onDialogClose} headerText="Images - slides" type={PanelType.custom} customWidth="700px" onRenderFooterContent={() => { return ( <div style={{ float: 'right', paddingBottom: '20px' }}> <PrimaryButton text="Close" onClick={this.onDialogClose} /> </div> ); }} > <div style={{ marginBottom: 25, verticalAlign: 'Top', width: '100%' }}> <Slider ref={c => (this._slider = c)} {...sliderSettings} autoplay={this.state.autoplay} onReInit={() => { if (!this.state.isloadingCarousel) $(".slideLoading").removeClass("slideLoading"); }} > { this.state.carouselImages } </Slider> </div> { !this.state.isloadingCarousel ? <div style={{ textAlign: 'center', width: '100%' }}> <CommandBarButton iconProps={{ iconName: 'TriangleSolidLeft12', styles: { root: { fontSize: FontSizes.size16, padding: '10px', color: CommunicationColors.primary } } }} allowDisabledFocus={true} style={{ fontSize: FontSizes.size16, marginRight: '10px' }} title='Prev' onClick={this.onPrev}> </CommandBarButton> <CommandBarButton iconProps={{ iconName: this.state.isPlaying ? 'Pause' : 'PlayResume', styles: { root: { fontSize: FontSizes.size18, padding: '10px', color: CommunicationColors.primary } } }} allowDisabledFocus={true} style={{ fontSize: FontSizes.size18, marginRight: '10px' }} title={this.state.isPlaying ? 'Pause' : 'Play'} onClick={this.onPlayResume}> </CommandBarButton> <CommandBarButton iconProps={{ iconName: 'TriangleSolidRight12', styles: { root: { fontSize: FontSizes.size16, padding: '10px', color: CommunicationColors.primary } } }} allowDisabledFocus={true} style={{ fontSize: FontSizes.size16 }} title='Next' onClick={this.onNext}> </CommandBarButton> </div> : <Spinner size={SpinnerSize.large} label={'Loading...'} style={{ fontSize: FontSizes.size18, color: CommunicationColors.primary }}></Spinner> } </Panel> </div> } </div> ); } }
the_stack
/*global TurbulenzBridge: false*/ /*exported TurbulenzUI*/ // requires jQuery /** * The DynamicUI manager sends events to the DynamicUI server to create instances of UI elements on the host website. It * then manages updates to the UI either responding to requests for the value for a specific UI element, or pushing * values to elements referenced by id. */ class DynamicUIManager { _objects : any; // TODO _setters : any; // TODO _getters : any; // TODO _watchGroup : number; /** * Generates a new id for use in the dynamicUI system * * @return A new unique id to use */ _newId: { (): number; }; /** * Helper function to add a new UI element. Sends an event to the dynamicUI server and sets up listeners to * handle requests to get and set the value that come form the UI. * * @param {String} type The type of the UI element used * @param {String} title The title to use for the UI element * @param {Function} getValue A callback that gets the value for the UI element * @param {Function} setValue A callback that is called when the value in the UI is changed * @param [groupId] The group id of the parent group. If not defined then the default group is used * @param [options] An object containing UI specific options. The details of this will depend on the implementation * of the DynamicUI server * @returns The id of the new element to use to push values to this UI element */ _addUI(type, title, getValue, setValue, groupId, options) { var id = this._newId(); TurbulenzBridge.emit('dynamicui.add-item', JSON.stringify({ id: id, type: type, title: title, groupId: groupId || null, options: options || {} })); this._setters[id] = setValue; this._getters[id] = getValue; return id; } /** * Utility function to handle "watch stashed object" events. * * @param paramstring The JSONified request */ _watchStashedObject(paramstring) { var params = JSON.parse(paramstring); var id = params.id; var property = params.property; var title = params.title || id; var ui = params.ui; var options = params.options || {}; var groupId = params.groupId || this._watchGroup; this.watchVariable(title, this._objects[id], property, ui, groupId, options); } /** * Adds a slider to the specified group. * * @param {String} title The title to use for the UI element * @param {Function} getValue A callback that gets the value for the UI element * @param {Function} setValue A callback that is called when the value in the UI is changed * @param [groupId] The group id of the parent group. If not defined then the default group is used * @param [options] An object containing UI specific options. The details of this will depend on the implementation * of the DynamicUI server * @returns The id of the new element to use to push values to this UI element */ addSlider(title, getValue, setValue, groupId, options) { return this._addUI('slider', title, getValue, setValue, groupId, options); } /** * Adds a checkbox to the specified group. * * @param {String} title The title to use for the UI element * @param {Function} getValue A callback that gets the value for the UI element * @param {Function} setValue A callback that is called when the value in the UI is changed * @param [groupId] The group id of the parent group. If not defined then the default group is used * @param [options] An object containing UI specific options. The details of this will depend on the implementation * of the DynamicUI server * @returns The id of the new element to use to push values to this UI element */ addCheckbox(title, getValue, setValue, groupId, options) { return this._addUI('checkbox', title, getValue, setValue, groupId, options); } /** * Adds a drop-down selector to the specified group. * * @param {String} title The title to use for the UI element * @param {Function} getValue A callback that gets the value for the UI element * @param {Function} setValue A callback that is called when the value in the UI is changed * @param [groupId] The group id of the parent group. If not defined then the default group is used * @param [options] An object containing UI specific options. The details of this will depend on the implementation * of the DynamicUI server * @returns The id of the new element to use to push values to this UI element */ addSelect(title, getValue, setValue, groupId, options) { return this._addUI('select', title, getValue, setValue, groupId, options); } /** * Adds an updatable label to the specified group. * * @param {String} title The title to use for the UI element * @param {Function} getValue A callback that gets the value for the UI element * @param {Function} setValue A callback that is called when the value in the UI is changed * @param [groupId] The group id of the parent group. If not defined then the default group is used * @param [options] An object containing UI specific options. The details of this will depend on the implementation * of the DynamicUI server * @returns The id of the new element to use to push values to this UI element */ addWatch(title, getValue, setValue, groupId, options) { return this._addUI('watch', title, getValue, setValue, groupId, options); } /** * Adds a set of radio buttons to the specified group. * * @param {String} title The title to use for the UI element * @param {Function} getValue A callback that gets the value for the UI element * @param {Function} setValue A callback that is called when the value in the UI is changed * @param [groupId] The group id of the parent group. If not defined then the default group is used * @param [options] An object containing UI specific options. The details of this will depend on the implementation * of the DynamicUI server * @returns The id of the new element to use to push values to this UI element */ addRadioButton(title, getValue, setValue, groupId, options) { return this._addUI('radio', title, getValue, setValue, groupId, options); } /** * Destroys the specified UI element. * * @param id The Id of the element to destroy. If the element is a group, the group and all its children are * destroyed */ destroy(id) { TurbulenzBridge.emit('dynamicui.destroy', JSON.stringify({ id: id })); } /** * Updates the specified UI element with a new value. * * @param id The Id of the element to update * @param value The value to send to the UI */ pushValue(id, value) { TurbulenzBridge.emit('dynamicui.pushvalue', JSON.stringify({ id: id, value: value })); } /** * Adds a group to the dynamid UI. * * @param {String} title The title of the group * @param groupId The parent group to add this new group to * @returns The id of the newly created group. */ addGroup(title, groupId?) { var id = this._newId(); TurbulenzBridge.emit('dynamicui.group-create', JSON.stringify({ id: id, title: title, groupId: groupId || null })); return id; } /** * Adds a UI element to an existing group. The element is moved, so if it is already a member of a group it * will be removed from that group and added to the group specified in the function call. * * @param id The id of the element to move * @param groupId The parent group to add this new group to */ addToGroup(id, groupId) { TurbulenzBridge.emit('dynamicui.group-add', JSON.stringify({ id: id, groupId: groupId })); } /** * Removes a UI element from a group. This does not destroy the UI element so it can be used to temporarily hide * a UI element which can then be re-shown by calling addToGroup * * @param id The id of the UI element to remove * @param groupId The id of the group to remove it from */ removeFromGroup(id, groupId) { TurbulenzBridge.emit('dynamicui.group-remove', JSON.stringify({ id: id, groupId: groupId })); } /** * Helper function to watch the specified property of an object. This automatically sets up the getter and setter * callbacks on the property to tie it to the state of the UI. * * @param {String} title The title of the UI element to create * @param {Object} object The object whose property will be watched * @param {String} property The name of the property to watch * @param {String} [ui = "watch"] The UI to use to show the variable * @param [group] The group to add this watch element to * @param [options] The UI creation options to use * @returns The id of the newly created element */ watchVariable(title: string, object, property, ui?: string, group?: number, options?): number { var uiType = ui || 'watch'; var groupId = group || null; var id = -1; var getVal = function getValFn() { if (property) { return object[property]; } else { return object; } }; var setVal = function setValFn(value) { object[property] = value; }; switch (uiType) { case 'slider' : id = this.addSlider(title, getVal, setVal, groupId, options); break; case 'checkbox' : id = this.addCheckbox(title, getVal, setVal, groupId, options); break; case 'radio' : id = this.addRadioButton(title, getVal, setVal, groupId, options); break; case 'select' : id = this.addSelect(title, getVal, setVal, groupId, options); break; case 'watch' : id = this.addWatch(title, getVal, setVal, groupId, options); break; } return id; } showObject(title, object, editable, group) { var objectGroup = this.addGroup(title, group); var propertyName, property; for (propertyName in object) { if (object.hasOwnProperty(propertyName)) { property = object[propertyName]; if (typeof property === "object") { this.showObject(propertyName, property, editable, objectGroup); } else { if (editable) { // TODO: parse type and provide appropriate UI this.watchVariable(propertyName, object, propertyName, 'watch', objectGroup); } else { this.watchVariable(propertyName, object, propertyName, 'watch', objectGroup); } } } } return objectGroup; } /** * Registers a named path to an object so that the object can be referenced from another context for the creation of * watch UI * * @param {Object} object The object to stash * @param {String} path The path to use to access the object in the form "folder/folder/folder/item", for example * "actors/npcs/enemies/bots/ed209" * @returns The id of the stashed object - currently for internal use only */ stashObject(object, path) { var id = this._newId(); this._objects[id] = object; TurbulenzBridge.emit('dynamicui.stash-add', id + ':' + path); return id; } /** * Creates a DynamicUI manager and initialises it, registering against events. * * @param title * @returns {DynamicUIManager} The UI Manager */ static create(/* title */): DynamicUIManager { var uiMan = new DynamicUIManager(); uiMan._objects = {}; uiMan._setters = {}; uiMan._getters = {}; uiMan._watchGroup = uiMan.addGroup('watches'); // Watch for calls from the console to watch stashed objects TurbulenzBridge.setListener('dynamicui.stash-watch', function (paramstring) { uiMan._watchStashedObject(paramstring); }); TurbulenzBridge.setListener('dynamicui.changevalue', function (jsonstring) { var options = JSON.parse(jsonstring); var setter = uiMan._setters[options.id]; if (setter) { setter(options.value); } }); TurbulenzBridge.setListener('dynamicui.requestvalue', function (jsonstring) { var options = JSON.parse(jsonstring); var getter = uiMan._getters[options.id]; if (getter) { TurbulenzBridge.emit('dynamicui.pushvalue', JSON.stringify({ id: options.id, value: getter() })); } }); return uiMan; } } DynamicUIManager.prototype._newId = (function () { var id = 0; return function getId() { id += 1; return id; }; }()); /** * The instance of the DynamicUI manager */ /* tslint:disable:no-unused-variable */ var TurbulenzUI = DynamicUIManager.create();
the_stack
declare interface Console { log (msg: any, ...params: any[]): void; info (msg: any, ...params: any[]): void; warn (msg: any, ...params: any[]): void; error (msg: any, ...params: any[]): void; } declare var console: Console; /* @internal */ namespace ts { export interface Node { $declarationLink?: ClassDeclaration; } export interface Type { $info?: reflection.ReflectionInfo; } export interface CompilerOptions { reflectionEnabled?: boolean; } export interface Program { $reflectionEmitted?: boolean; } export interface SourceFile { $typePackage?: reflection.TypePackage; $packageNameLiteral?: StringLiteral; compilerOptions: CompilerOptions; } export type StatementsBlock = Block | SourceFile | ModuleBlock; export type TypeDeclaration = DeclarationStatement; } /* @internal */ namespace ts.reflection { export const reflectionModuleName = 'Reflection'; export const reflectionLocalVariableName = '$reflection'; export const registerPackageFunctionName = 'registerPackage'; export const interfaceForNameFunctionName = 'interfaceForName'; export const registerClassFunctionName = 'registerClass'; export const registerClassDecoratorName = 'RegisterClass'; export const classTypeName = 'Class'; export const interfaceTypeName = 'Interface'; export const libsField = '$libs'; // Reflection.$libs will contain all data for each loaded module. export const localTypeVar = '_l'; export const tempTypeVar = '_t'; export interface TypePackage { name: string; fullName: string; node: Node; parent: TypePackage; types?: { [index: string]: TypeDeclaration; }; children?: { [index: string]: TypePackage; }; } export interface ReflectionInfo { localIndex?: number; path?: string; name?: string; // may be null. See anonymous types, for example. } let invalidIdentifierCharsRegex = /^[\d]|[^a-zA-Z\d\_\$\xA0-\uFFFF]+?/; export function getSafeIdentifierName(name: string): string { return name.replace(invalidIdentifierCharsRegex, "_"); } export interface IntrinsicTypeDescriptor { varName: string, definition: string, }; function buildIntrinsicType(name: string): IntrinsicTypeDescriptor { let varName = `_type_${name}`; return { definition: `var ${varName} = {kind: '${name}'};`, varName: varName }; } export const IntrinsicTypes: { [index: string]: IntrinsicTypeDescriptor } = {}; IntrinsicTypes[TypeFlags.Any] = buildIntrinsicType('any'); IntrinsicTypes[TypeFlags.String] = buildIntrinsicType('string'); IntrinsicTypes[TypeFlags.Number] = buildIntrinsicType('number'); IntrinsicTypes[TypeFlags.Boolean] = buildIntrinsicType('boolean'); IntrinsicTypes[TypeFlags.Void] = buildIntrinsicType('void'); IntrinsicTypes[TypeFlags.ESSymbol] = buildIntrinsicType('symbol'); IntrinsicTypes[TypeFlags.Undefined] = buildIntrinsicType('undefined'); IntrinsicTypes[TypeFlags.Null] = buildIntrinsicType('null'); IntrinsicTypes[TypeFlags.Never] = buildIntrinsicType('never'); export const intrinsicTypeFlagsMask = TypeFlags.Any | TypeFlags.String | TypeFlags.Number | TypeFlags.Boolean | TypeFlags.Enum | TypeFlags.StringLiteral | TypeFlags.NumberLiteral | TypeFlags.BooleanLiteral | TypeFlags.EnumLiteral | TypeFlags.ESSymbol | TypeFlags.Void | TypeFlags.Undefined | TypeFlags.Null | TypeFlags.Never; export const allTypeFlagsMask = intrinsicTypeFlagsMask | TypeFlags.TypeParameter | TypeFlags.Union | TypeFlags.Intersection | TypeFlags.Object; // | TypeFlags.Class | TypeFlags.Interface // | TypeFlags.Reference | TypeFlags.Tuple // | TypeFlags.Anonymous; export function getIntrinsicType(typeFlags: TypeFlags) { let filtered = typeFlags & intrinsicTypeFlagsMask; //from Any to Never (bit 13) return IntrinsicTypes[filtered]; } export const SerializedTypeKind = { //:{[index: string]: string } ???? Interface: 'interface', Class: 'class', Function: 'function', Array: 'array', Parameter: 'parameter', Reference: 'reference', Alias: 'alias', ClassExpression: 'expression', Union: 'union', Intersection: 'intersection', }; export function getTypeName(type: Type, statement?: Statement | Declaration): string { let name: string; if (statement && (statement.kind === SyntaxKind.TypeAliasDeclaration || statement.kind === SyntaxKind.ClassDeclaration || statement.kind === SyntaxKind.InterfaceDeclaration)) { let declaration = (<TypeDeclaration>statement); name = getDeclarationName(declaration); name = name ? name : type.symbol.name; } else { name = type.symbol ? type.symbol.name : null; // for anonymous types name is null. } return name; } /** * Adds some tracking information to Type objects, useful for building relationships among them. */ export function addReflectionInfo(type: Type, typeCounter: Counter, typeDeclaration?: Statement) { type.$info = { name: getTypeName(type, typeDeclaration), localIndex: typeCounter.increment() } } export interface Counter { getValue(): number; increment(): number; } export function createCounter(initValue?: number): Counter { let value = initValue >= 0 ? initValue : 0; return { getValue: () => value, increment: () => value++ } } /** * Mimics the EmitTextWriter, but with fluent API. */ export class Writer { private output = ""; private indent = 0; private lineStart = true; private lineCount = 0; private linePos = 0; constructor(private newLine: string) { } write(s: string) { if (s && s.length) { if (this.lineStart) { this.output += getIndentString(this.indent); this.lineStart = false; } this.output += s; } return this; } writeAtBeginning(s: string) { if (s && s.length) { this.output = s + this.output; } return this; } writeLine() { if (!this.lineStart) { this.output += this.newLine; this.lineCount++; this.linePos = this.output.length; this.lineStart = true; } return this; } getText() { return this.output; }; increaseIndent() { this.indent++; return this; } decreaseIndent() { this.indent > 0 ? this.indent-- : null; return this; } writeObjectStart(skipNewLine?: boolean) { return this.writeDelimiterStart(`{`, skipNewLine); } writeObjectEnd(skipNewLine?: boolean) { return this.writeDelimiterEnd(`}`, skipNewLine); } writeArrayStart(skipNewLine?: boolean) { return this.writeDelimiterStart(`[`, skipNewLine); } writeArrayEnd(skipNewLine?: boolean) { return this.writeDelimiterEnd(`]`, skipNewLine); } writeDelimiterStart(delimiterStart: string, skipNewLine?: boolean) { this.write(delimiterStart).increaseIndent(); if (!skipNewLine) { this.writeLine(); } return this; } writeDelimiterEnd(delimiterEnd: string, skipNewLine?: boolean) { this.decreaseIndent(); if (!skipNewLine) { this.writeLine(); } return this.write(delimiterEnd); } writeObjectPropertyStart(propertyName: string, skipNewLine?: boolean) { return this.write(`${propertyName} : `).writeObjectStart(skipNewLine); } writeArrayPropertyStart(propertyName: string, skipNewLine?: boolean) { return this.write(`${propertyName} : `).writeArrayStart(skipNewLine); } } export function valuesOf<T>(dataObject: Map<T>) { let dataArray: T[] = <T[]>[]; if (dataObject) { dataObject.forEach(value => dataArray.push(value)); } return dataArray; } export module debug { export function info(message: any, ...strArray: any[]) { //todo: if debug enabled if (strArray) { console.info(message, ...strArray); } } export function warn(message: any, ...strArray: any[]) { //todo: if warn enabled if (strArray) { console.warn(message, ...strArray); } } } export const contentHeader = `;(function(globalObj, undefined) { var freeExports = typeof exports == 'object' && exports; var freeModule = typeof module == 'object' && module && module.exports == freeExports && module; /** Detect free variable 'global' and use it as 'globalObj' */ var freeGlobal = typeof global == 'object' && global; if (freeGlobal) { globalObj = freeGlobal; } var metadataField = (typeof Symbol === 'function') ? Symbol('metadata') : '__reflectionData__'; function O_o(){return Object.create(null);} //lol var ${reflectionModuleName} = globalObj.${reflectionModuleName} || { ${libsField}: O_o() }; `; export const contentFooter = ` Reflection.registerPackage = function(name) { //console.log('Registering package: ' + name); var pkg = Reflection.$libs['default'][name]; pkg.registerClass = function(ctor, metadata) { //console.log('Registering constructor: ' + ctor.name); ctor.prototype[metadataField] = metadata; metadata.getConstructor = function(){ return ctor; }; }; //decorator: pkg.RegisterClass = function(metadata) { return function(ctor) { //console.log('Invoking RegisterClass decorator for: ' + ctor.name); pkg.registerClass(ctor, metadata); return ctor; }; }; return pkg; }; Reflection.interfaceForName = function(pkg, name) { var fqn = name ? [pkg, name] : pkg.split('#'); var type = Reflection.$libs['default'][fqn[0]][fqn[1]]; if(!type || type.kind !== 'interface') { throw new Error('Interface not found: '+ name); } return type; }; Reflection.registerClass = function(ctor, name) { var metadata = Reflection.classForName(name); ctor.prototype[metadataField] = metadata; metadata.getConstructor = function(){ return ctor; }; }; Reflection.RegisterClass = function(name) { return function(ctor) { //console.log('Invoking RegisterClass decorator for: ' + ctor.name); Reflection.registerClass(ctor, name); return ctor; }; }; Reflection.classForName = function(pkg, name) { var fqn = name ? [pkg, name] : pkg.split('#'); var type = Reflection.$libs['default'][fqn[0]][fqn[1]]; if(!type || type.kind !== 'class') { throw new Error('Class not found: '+ name); } return type; }; Reflection.classForConstructor = function(ctor) { return ctor.prototype[metadataField]; }; Function.prototype.getClass = function() { return Reflection.classForConstructor(this); }; globalObj.${reflectionModuleName} = ${reflectionModuleName}; \n}(this));\n\n`; }
the_stack
import * as d3ScaleChromatic from 'd3-scale-chromatic'; // ----------------------------------------------------------------------- // Preparatory Steps // ----------------------------------------------------------------------- let colorInterpolator: ((t: number) => string); let simpleScheme: ReadonlyArray<string>; let nestedScheme: ReadonlyArray<ReadonlyArray<string>>; // ----------------------------------------------------------------------- // Categorical // ----------------------------------------------------------------------- simpleScheme = d3ScaleChromatic.schemeCategory10; simpleScheme = d3ScaleChromatic.schemeAccent; simpleScheme = d3ScaleChromatic.schemeDark2; simpleScheme = d3ScaleChromatic.schemePaired; simpleScheme = d3ScaleChromatic.schemePastel1; simpleScheme = d3ScaleChromatic.schemePastel2; simpleScheme = d3ScaleChromatic.schemeSet1; simpleScheme = d3ScaleChromatic.schemeSet2; simpleScheme = d3ScaleChromatic.schemeSet3; const category10: string = d3ScaleChromatic.schemeCategory10[0]; // #1f77b4 const accent: string = d3ScaleChromatic.schemeAccent[0]; // #7fc97f const dark: string = d3ScaleChromatic.schemeDark2[0]; // #1b9e77 const paired: string = d3ScaleChromatic.schemePaired[0]; // #a6cee3 const pastel1: string = d3ScaleChromatic.schemePastel1[0]; // #fbb4ae const pastel2: string = d3ScaleChromatic.schemePastel2[0]; // #b3e2cd const set1: string = d3ScaleChromatic.schemeSet1[0]; // #e41a1c const set2: string = d3ScaleChromatic.schemeSet2[0]; // #66c2a5 const set3: string = d3ScaleChromatic.schemeSet3[0]; // #8dd3c7 // ----------------------------------------------------------------------- // Diverging // ----------------------------------------------------------------------- colorInterpolator = d3ScaleChromatic.interpolateBrBG; colorInterpolator = d3ScaleChromatic.interpolatePRGn; colorInterpolator = d3ScaleChromatic.interpolatePiYG; colorInterpolator = d3ScaleChromatic.interpolatePuOr; colorInterpolator = d3ScaleChromatic.interpolateRdBu; colorInterpolator = d3ScaleChromatic.interpolateRdGy; colorInterpolator = d3ScaleChromatic.interpolateRdYlBu; colorInterpolator = d3ScaleChromatic.interpolateRdYlGn; colorInterpolator = d3ScaleChromatic.interpolateSpectral; const BrBG: string = d3ScaleChromatic.interpolateBrBG(0); // rgb(84, 48, 5) const PRGn: string = d3ScaleChromatic.interpolatePRGn(0); // rgb(64, 0, 75) const PiYG: string = d3ScaleChromatic.interpolatePiYG(0); // rgb(142, 1, 82) const PuOr: string = d3ScaleChromatic.interpolatePuOr(0); // rgb(127, 59, 8) const RdBu: string = d3ScaleChromatic.interpolateRdBu(0); // rgb(103, 0, 31) const RdGy: string = d3ScaleChromatic.interpolateRdGy(0); // rgb(103, 0, 31) const RdYlBu: string = d3ScaleChromatic.interpolateRdYlBu(0); // rgb(103, 0, 31) const RdYlGn: string = d3ScaleChromatic.interpolateRdYlGn(0); // rgb(103, 0, 31) const Spectral: string = d3ScaleChromatic.interpolateSpectral(0); // rgb(158, 1, 66) nestedScheme = d3ScaleChromatic.schemeBrBG; nestedScheme = d3ScaleChromatic.schemePRGn; nestedScheme = d3ScaleChromatic.schemePiYG; nestedScheme = d3ScaleChromatic.schemePuOr; nestedScheme = d3ScaleChromatic.schemeRdBu; nestedScheme = d3ScaleChromatic.schemeRdGy; nestedScheme = d3ScaleChromatic.schemeRdYlBu; nestedScheme = d3ScaleChromatic.schemeRdYlGn; nestedScheme = d3ScaleChromatic.schemeSpectral; const schemeBrBG: string = d3ScaleChromatic.schemeBrBG[3][0]; // #d8b365 const schemePRGn: string = d3ScaleChromatic.schemePRGn[3][0]; // #af8dc3 const schemePiYG: string = d3ScaleChromatic.schemePiYG[3][0]; // #e9a3c9 const schemePuOr: string = d3ScaleChromatic.schemePuOr[3][0]; // #998ec3 const schemeRdBu: string = d3ScaleChromatic.schemeRdBu[3][0]; // #ef8a62 const schemeRdGy: string = d3ScaleChromatic.schemeRdGy[3][0]; // #ef8a62 const schemeRdYlBu: string = d3ScaleChromatic.schemeRdYlBu[3][0]; // #fc8d59 const schemeRdYlGn: string = d3ScaleChromatic.schemeRdYlGn[3][0]; // #fc8d59 const schemeSpectral: string = d3ScaleChromatic.schemeSpectral[3][0]; // #fc8d59 // ----------------------------------------------------------------------- // Sequential // ----------------------------------------------------------------------- colorInterpolator = d3ScaleChromatic.interpolateBlues; colorInterpolator = d3ScaleChromatic.interpolateGreens; colorInterpolator = d3ScaleChromatic.interpolateGreys; colorInterpolator = d3ScaleChromatic.interpolateOranges; colorInterpolator = d3ScaleChromatic.interpolatePurples; colorInterpolator = d3ScaleChromatic.interpolateReds; const Blue: string = d3ScaleChromatic.interpolateBlues(1); // rgb(8, 48, 107) const Green: string = d3ScaleChromatic.interpolateGreens(1); // rgb(0, 68, 27) const Grey: string = d3ScaleChromatic.interpolateGreys(1); // rgb(0, 0, 0) const Orange: string = d3ScaleChromatic.interpolateOranges(1); // rgb(127, 39, 4) const Purple: string = d3ScaleChromatic.interpolatePurples(1); // rgb(63, 0, 125) const Red: string = d3ScaleChromatic.interpolateReds(1); // rgb(103, 0, 13) nestedScheme = d3ScaleChromatic.schemeBlues; nestedScheme = d3ScaleChromatic.schemeGreens; nestedScheme = d3ScaleChromatic.schemeGreys; nestedScheme = d3ScaleChromatic.schemeOranges; nestedScheme = d3ScaleChromatic.schemePurples; nestedScheme = d3ScaleChromatic.schemeReds; const schemeBlues: string = d3ScaleChromatic.schemeBlues[3][0]; // #deebf7 const schemeGreens: string = d3ScaleChromatic.schemeGreens[3][0]; // #e5f5e0 const schemeGreys: string = d3ScaleChromatic.schemeGreys[3][0]; // #f0f0f0 const schemeOranges: string = d3ScaleChromatic.schemeOranges[3][0]; // #fee6ce const schemePurples: string = d3ScaleChromatic.schemePurples[3][0]; // #efedf5 const schemeReds: string = d3ScaleChromatic.schemeReds[3][0]; // #fee0d2 // ----------------------------------------------------------------------- // Sequential(Multi-Hue) // ----------------------------------------------------------------------- colorInterpolator = d3ScaleChromatic.interpolateViridis; colorInterpolator = d3ScaleChromatic.interpolateMagma; colorInterpolator = d3ScaleChromatic.interpolateInferno; colorInterpolator = d3ScaleChromatic.interpolatePlasma; colorInterpolator = d3ScaleChromatic.interpolateRainbow; colorInterpolator = d3ScaleChromatic.interpolateSinebow; colorInterpolator = d3ScaleChromatic.interpolateWarm; colorInterpolator = d3ScaleChromatic.interpolateCool; colorInterpolator = d3ScaleChromatic.interpolateCubehelixDefault; const Viridis: string = d3ScaleChromatic.interpolateViridis(0.7); const Magma: string = d3ScaleChromatic.interpolateMagma(0.7); const Inferno: string = d3ScaleChromatic.interpolateInferno(0.7); const Plasma: string = d3ScaleChromatic.interpolatePlasma(0.7); const Rainbow: string = d3ScaleChromatic.interpolateRainbow(0.7); const Sinebow: string = d3ScaleChromatic.interpolateSinebow(0.7); const Warm: string = d3ScaleChromatic.interpolateWarm(0.7); const Cool: string = d3ScaleChromatic.interpolateCool(0.7); const CubehelixDefault: string = d3ScaleChromatic.interpolateCubehelixDefault(0.7); colorInterpolator = d3ScaleChromatic.interpolateBuGn; colorInterpolator = d3ScaleChromatic.interpolateBuPu; colorInterpolator = d3ScaleChromatic.interpolateGnBu; colorInterpolator = d3ScaleChromatic.interpolateOrRd; colorInterpolator = d3ScaleChromatic.interpolatePuBuGn; colorInterpolator = d3ScaleChromatic.interpolatePuBu; colorInterpolator = d3ScaleChromatic.interpolatePuRd; colorInterpolator = d3ScaleChromatic.interpolateRdPu; colorInterpolator = d3ScaleChromatic.interpolateYlGnBu; colorInterpolator = d3ScaleChromatic.interpolateYlGn; colorInterpolator = d3ScaleChromatic.interpolateYlOrBr; colorInterpolator = d3ScaleChromatic.interpolateYlOrRd; const BuGn: string = d3ScaleChromatic.interpolateBuGn(1); // rgb(0, 68, 27) const BuPu: string = d3ScaleChromatic.interpolateBuPu(1); // rgb(77, 0, 75) const GnBu: string = d3ScaleChromatic.interpolateGnBu(1); // rgb(8, 64, 129) const OrRd: string = d3ScaleChromatic.interpolateOrRd(1); // rgb(127, 0, 0) const PuBuGn: string = d3ScaleChromatic.interpolatePuBuGn(1); // rgb(1, 70, 54) const PuBu: string = d3ScaleChromatic.interpolatePuBu(1); // rgb(2, 56, 88) const PuRd: string = d3ScaleChromatic.interpolatePuRd(1); // rgb(103, 0, 31) const RdPu: string = d3ScaleChromatic.interpolateRdPu(1); // rgb(73, 0, 106) const YlGnBu: string = d3ScaleChromatic.interpolateYlGnBu(1); // rgb(8, 29, 88) const YlGn: string = d3ScaleChromatic.interpolateYlGn(1); // rgb(0, 69, 41) const YlOrBr: string = d3ScaleChromatic.interpolateYlOrBr(1); // rgb(102, 37, 6) const YlOrRd: string = d3ScaleChromatic.interpolateYlOrRd(1); // rgb(128, 0, 38) nestedScheme = d3ScaleChromatic.schemeBuGn; nestedScheme = d3ScaleChromatic.schemeBuPu; nestedScheme = d3ScaleChromatic.schemeGnBu; nestedScheme = d3ScaleChromatic.schemeOrRd; nestedScheme = d3ScaleChromatic.schemePuBuGn; nestedScheme = d3ScaleChromatic.schemePuBu; nestedScheme = d3ScaleChromatic.schemePuRd; nestedScheme = d3ScaleChromatic.schemeRdPu; nestedScheme = d3ScaleChromatic.schemeYlGnBu; nestedScheme = d3ScaleChromatic.schemeYlGn; nestedScheme = d3ScaleChromatic.schemeYlOrBr; nestedScheme = d3ScaleChromatic.schemeYlOrRd; const schemeBuGn: string = d3ScaleChromatic.schemeBuGn[3][0]; // #e5f5f9 const schemeBuPu: string = d3ScaleChromatic.schemeBuPu[3][0]; // #e0ecf4 const schemeGnBu: string = d3ScaleChromatic.schemeGnBu[3][0]; // #e0f3db const schemeOrRd: string = d3ScaleChromatic.schemeOrRd[3][0]; // #fee8c8 const schemePuBuGn: string = d3ScaleChromatic.schemePuBuGn[3][0]; // #ece2f0 const schemePuBu: string = d3ScaleChromatic.schemePuBu[3][0]; // #ece7f2 const schemePuRd: string = d3ScaleChromatic.schemePuRd[3][0]; // #e7e1ef const schemeRdPu: string = d3ScaleChromatic.schemeRdPu[3][0]; // #fde0dd const schemeYlGnBu: string = d3ScaleChromatic.schemeYlGnBu[3][0]; // #edf8b1 const schemeYlGn: string = d3ScaleChromatic.schemeYlGn[3][0]; // #f7fcb9 const schemeYlOrBr: string = d3ScaleChromatic.schemeYlOrBr[3][0]; // #fff7bc const schemeYlOrRd: string = d3ScaleChromatic.schemeYlOrRd[3][0]; // #ffeda0
the_stack
import BN from 'bn.js'; import BigNumber from 'bignumber.js'; import { PromiEvent, TransactionReceipt, EventResponse, EventData, Web3ContractContext, } from 'ethereum-abi-types-generator'; export interface CallOptions { from?: string; gasPrice?: string; gas?: number; } export interface SendOptions { from: string; value?: number | string | BN | BigNumber; gasPrice?: string; gas?: number; } export interface EstimateGasOptions { from?: string; value?: number | string | BN | BigNumber; gas?: number; } export interface MethodPayableReturnContext { send(options: SendOptions): PromiEvent<TransactionReceipt>; send( options: SendOptions, callback: (error: Error, result: any) => void ): PromiEvent<TransactionReceipt>; estimateGas(options: EstimateGasOptions): Promise<number>; estimateGas( options: EstimateGasOptions, callback: (error: Error, result: any) => void ): Promise<number>; encodeABI(): string; } export interface MethodConstantReturnContext<TCallReturn> { call(): Promise<TCallReturn>; call(options: CallOptions): Promise<TCallReturn>; call( options: CallOptions, callback: (error: Error, result: TCallReturn) => void ): Promise<TCallReturn>; encodeABI(): string; } export interface MethodReturnContext extends MethodPayableReturnContext {} export type ContractContext = Web3ContractContext< StakingRewards, StakingRewardsMethodNames, StakingRewardsEventsContext, StakingRewardsEvents >; export type StakingRewardsEvents = | 'OwnerChanged' | 'OwnerNominated' | 'PauseChanged' | 'Recovered' | 'RewardAdded' | 'RewardPaid' | 'RewardsDurationUpdated' | 'Staked' | 'Withdrawn'; export interface StakingRewardsEventsContext { OwnerChanged( parameters: { filter?: {}; fromBlock?: number; toBlock?: 'latest' | number; topics?: string[]; }, callback?: (error: Error, event: EventData) => void ): EventResponse; OwnerNominated( parameters: { filter?: {}; fromBlock?: number; toBlock?: 'latest' | number; topics?: string[]; }, callback?: (error: Error, event: EventData) => void ): EventResponse; PauseChanged( parameters: { filter?: {}; fromBlock?: number; toBlock?: 'latest' | number; topics?: string[]; }, callback?: (error: Error, event: EventData) => void ): EventResponse; Recovered( parameters: { filter?: {}; fromBlock?: number; toBlock?: 'latest' | number; topics?: string[]; }, callback?: (error: Error, event: EventData) => void ): EventResponse; RewardAdded( parameters: { filter?: {}; fromBlock?: number; toBlock?: 'latest' | number; topics?: string[]; }, callback?: (error: Error, event: EventData) => void ): EventResponse; RewardPaid( parameters: { filter?: { user?: string | string[] }; fromBlock?: number; toBlock?: 'latest' | number; topics?: string[]; }, callback?: (error: Error, event: EventData) => void ): EventResponse; RewardsDurationUpdated( parameters: { filter?: {}; fromBlock?: number; toBlock?: 'latest' | number; topics?: string[]; }, callback?: (error: Error, event: EventData) => void ): EventResponse; Staked( parameters: { filter?: { user?: string | string[] }; fromBlock?: number; toBlock?: 'latest' | number; topics?: string[]; }, callback?: (error: Error, event: EventData) => void ): EventResponse; Withdrawn( parameters: { filter?: { user?: string | string[] }; fromBlock?: number; toBlock?: 'latest' | number; topics?: string[]; }, callback?: (error: Error, event: EventData) => void ): EventResponse; } export type StakingRewardsMethodNames = | 'new' | 'acceptOwnership' | 'balanceOf' | 'earned' | 'exit' | 'getReward' | 'getRewardForDuration' | 'lastPauseTime' | 'lastTimeRewardApplicable' | 'lastUpdateTime' | 'nominateNewOwner' | 'nominatedOwner' | 'notifyRewardAmount' | 'owner' | 'paused' | 'periodFinish' | 'recoverERC20' | 'rewardPerToken' | 'rewardPerTokenStored' | 'rewardRate' | 'rewards' | 'rewardsDistribution' | 'rewardsDuration' | 'rewardsToken' | 'setPaused' | 'setRewardsDistribution' | 'setRewardsDuration' | 'stake' | 'stakingToken' | 'totalSupply' | 'userRewardPerTokenPaid' | 'withdraw'; export interface StakingRewards { /** * Payable: false * Constant: false * StateMutability: nonpayable * Type: constructor * @param _owner Type: address, Indexed: false * @param _rewardsDistribution Type: address, Indexed: false * @param _rewardsToken Type: address, Indexed: false * @param _stakingToken Type: address, Indexed: false */ 'new'( _owner: string, _rewardsDistribution: string, _rewardsToken: string, _stakingToken: string ): MethodReturnContext; /** * Payable: false * Constant: false * StateMutability: nonpayable * Type: function */ acceptOwnership(): MethodReturnContext; /** * Payable: false * Constant: true * StateMutability: view * Type: function * @param account Type: address, Indexed: false */ balanceOf(account: string): MethodConstantReturnContext<string>; /** * Payable: false * Constant: true * StateMutability: view * Type: function * @param account Type: address, Indexed: false */ earned(account: string): MethodConstantReturnContext<string>; /** * Payable: false * Constant: false * StateMutability: nonpayable * Type: function */ exit(): MethodReturnContext; /** * Payable: false * Constant: false * StateMutability: nonpayable * Type: function */ getReward(): MethodReturnContext; /** * Payable: false * Constant: true * StateMutability: view * Type: function */ getRewardForDuration(): MethodConstantReturnContext<string>; /** * Payable: false * Constant: true * StateMutability: view * Type: function */ lastPauseTime(): MethodConstantReturnContext<string>; /** * Payable: false * Constant: true * StateMutability: view * Type: function */ lastTimeRewardApplicable(): MethodConstantReturnContext<string>; /** * Payable: false * Constant: true * StateMutability: view * Type: function */ lastUpdateTime(): MethodConstantReturnContext<string>; /** * Payable: false * Constant: false * StateMutability: nonpayable * Type: function * @param _owner Type: address, Indexed: false */ nominateNewOwner(_owner: string): MethodReturnContext; /** * Payable: false * Constant: true * StateMutability: view * Type: function */ nominatedOwner(): MethodConstantReturnContext<string>; /** * Payable: false * Constant: false * StateMutability: nonpayable * Type: function * @param reward Type: uint256, Indexed: false */ notifyRewardAmount(reward: string): MethodReturnContext; /** * Payable: false * Constant: true * StateMutability: view * Type: function */ owner(): MethodConstantReturnContext<string>; /** * Payable: false * Constant: true * StateMutability: view * Type: function */ paused(): MethodConstantReturnContext<boolean>; /** * Payable: false * Constant: true * StateMutability: view * Type: function */ periodFinish(): MethodConstantReturnContext<string>; /** * Payable: false * Constant: false * StateMutability: nonpayable * Type: function * @param tokenAddress Type: address, Indexed: false * @param tokenAmount Type: uint256, Indexed: false */ recoverERC20(tokenAddress: string, tokenAmount: string): MethodReturnContext; /** * Payable: false * Constant: true * StateMutability: view * Type: function */ rewardPerToken(): MethodConstantReturnContext<string>; /** * Payable: false * Constant: true * StateMutability: view * Type: function */ rewardPerTokenStored(): MethodConstantReturnContext<string>; /** * Payable: false * Constant: true * StateMutability: view * Type: function */ rewardRate(): MethodConstantReturnContext<string>; /** * Payable: false * Constant: true * StateMutability: view * Type: function * @param parameter0 Type: address, Indexed: false */ rewards(parameter0: string): MethodConstantReturnContext<string>; /** * Payable: false * Constant: true * StateMutability: view * Type: function */ rewardsDistribution(): MethodConstantReturnContext<string>; /** * Payable: false * Constant: true * StateMutability: view * Type: function */ rewardsDuration(): MethodConstantReturnContext<string>; /** * Payable: false * Constant: true * StateMutability: view * Type: function */ rewardsToken(): MethodConstantReturnContext<string>; /** * Payable: false * Constant: false * StateMutability: nonpayable * Type: function * @param _paused Type: bool, Indexed: false */ setPaused(_paused: boolean): MethodReturnContext; /** * Payable: false * Constant: false * StateMutability: nonpayable * Type: function * @param _rewardsDistribution Type: address, Indexed: false */ setRewardsDistribution(_rewardsDistribution: string): MethodReturnContext; /** * Payable: false * Constant: false * StateMutability: nonpayable * Type: function * @param _rewardsDuration Type: uint256, Indexed: false */ setRewardsDuration(_rewardsDuration: string): MethodReturnContext; /** * Payable: false * Constant: false * StateMutability: nonpayable * Type: function * @param amount Type: uint256, Indexed: false */ stake(amount: string): MethodReturnContext; /** * Payable: false * Constant: true * StateMutability: view * Type: function */ stakingToken(): MethodConstantReturnContext<string>; /** * Payable: false * Constant: true * StateMutability: view * Type: function */ totalSupply(): MethodConstantReturnContext<string>; /** * Payable: false * Constant: true * StateMutability: view * Type: function * @param parameter0 Type: address, Indexed: false */ userRewardPerTokenPaid(parameter0: string): MethodConstantReturnContext<string>; /** * Payable: false * Constant: false * StateMutability: nonpayable * Type: function * @param amount Type: uint256, Indexed: false */ withdraw(amount: string): MethodReturnContext; }
the_stack
import Scene from "../../src/Scene"; import { hasClass } from "@daybrush/utils"; import { START_ANIMATION, PAUSE_ANIMATION } from "../../src/consts"; import SceneItem from "../../src/SceneItem"; import * as sinon from "sinon"; /* eslint-disable */ describe("Scene Test", () => { describe("test Scene initialize", () => { it("should check default Scene", () => { const scene = new Scene({ item: { 0: { a: 1, }, 1: { display: "block", a: 2, }, }, }); // Then expect(scene.getItem<SceneItem>("item").get(0, "a")).to.be.equals(1); expect(scene.getDuration()).to.be.equals(1); }); }); describe("test Scene method", () => { it("should check 'newItem' method", () => { const scene = new Scene({ item: {}, }); // When const item = scene.newItem("item2"); const duplicateItem2 = scene.newItem("item2"); expect(duplicateItem2).to.be.equals(item); }); it("should check 'removeItem' method", () => { const scene = new Scene({ item: {}, }); // When const item = scene.newItem("item2"); scene.removeItem("item2"); expect(item).to.be.ok; expect(scene.getItem("item2")).to.be.undefined; }); it("should check 'getDuration' method", () => { const scene = new Scene({ item: {}, }); const noItemDuration = scene.getDuration(); // When scene.getItem("item").set(0, "opacity", 0); const duration = scene.getDuration(); scene.getItem("item").set(1, "opacity", 1); const duration2 = scene.getDuration(); scene.newItem("item2").set(3, "opacity", 2); const duration3 = scene.getDuration(); // Then expect(noItemDuration).to.be.equals(0); expect(duration).to.be.equals(0); expect(duration2).to.be.equals(1); expect(duration3).to.be.equals(3); }); it("should check 'setDuration' method", () => { const scene = new Scene({ item: { 0: { a: 1, }, 1: { display: "block", a: 2, }, 2: { display: "none", a: 4, }, }, }); const duration = scene.getDuration(); // When scene.setDuration(4); // Then expect(duration).to.be.equals(2); expect(scene.getDuration()).to.be.equals(4); }); it("should check 'setDuration' method(item's duration is infinite)", () => { const scene = new Scene({ item: { 0: { a: 1, }, 1: { display: "block", a: 2, }, 2: { display: "none", a: 4, }, options: { iterationCount: "infinite", }, }, }); // When scene.setDuration(4); // Then expect(isFinite(scene.getDuration())).to.be.not.ok; }); it(`should check 'append' method`, () => { const scene = new Scene({ item: { 0: { a: 1, }, 1: { display: "block", a: 2, }, 2: { display: "none", a: 4, }, options: { iterationCount: 2, }, }, }); // When scene.append(new SceneItem({ 0: { display: "none", }, 1: { diplay: "block", }, }, { id: "item2", })); // Then expect(scene.getDuration()).to.be.equals(5); expect(scene.getItem("item2").getDuration()).to.be.equals(1); }); }); describe("test Scene events", () => { beforeEach(() => { this.scene = new Scene({ item: { 0: { a: 1, }, 1: { display: "block", a: 2, }, 2: { display: "none", a: 4, }, }, item2: { 0: { a: 1, }, 1: { display: "block", a: 2, }, }, }); }); afterEach(() => { this.scene = null; }); it(`should check forEach method`, () => { const scene = new Scene({ ".test": { 0: { width: "100px", height: "100px", }, 1: { width: "200px", height: "200px", }, }, ".test2": { 0: { width: "200px", height: "200px", }, 1: { width: "100px", height: "100px", }, }, }); const test = {}; let test2 = {}; scene.forEach((item, name, index, items) => { test[name] = item; test2 = items; }); expect(test[".test"]).to.be.ok; expect(test[".test2"]).to.be.ok; expect(test[".test"].get(0, "width")).to.be.equals("100px"); expect(test[".test2"].get(0, "width")).to.be.equals("200px"); expect(test).to.be.deep.equals(test2); }); it(`should check 'animate' event`, done => { // Given const scene = new Scene({ ".test": { 0: { width: "100px", height: "100px", }, 1: { width: "200px", height: "200px", }, }, ".test2": { 0: { width: "200px", height: "200px", }, 1: { width: "100px", height: "100px", }, }, }); scene.on("animate", e => { // Then expect(e.time).to.be.equals(0.25); expect(e.currentTime).to.be.equals(0.25); expect(e.frames[".test"].get("width")).to.be.equals("125px"); expect(e.frames[".test2"].get("width")).to.be.equals("175px"); done(); }); // When scene.setTime(0.25); }); }); describe(`test body's element`, () => { beforeEach(() => { document.body.innerHTML = `<div class="test test1"></div><div class="test test2"></div> <div class="testf testf1"></div><div class="testf testf2"></div>`; }); afterEach(() => { document.body.innerHTML = ""; }); it(`should check setSelector method`, () => { const scene = new Scene(); scene.newItem(".test"); scene.setSelector(true); expect(scene.getItem<SceneItem>(".test").elements.length).to.be.equals(2); }); it(`should check Scene load`, () => { const scene = new Scene(); scene.set({ ".test": { 0: { width: "100px", height: "100px", }, 1: { width: "200px", height: "200px", }, }, "options": { selector: true, }, }); expect(scene.getItem<SceneItem>(".test").elements.length).to.be.equals(2); }); it(`should check Scene load with function`, () => { // Given, When const scene = new Scene({ ".test": i => ({ 0: { width: `${i * 100}px`, height: "100px", }, 1: { width: "200px", height: "200px", }, }), }, { selector: true, }).playCSS(); const item0 = scene.getItem<Scene>(".test").getItem<SceneItem>(0); const item1 = scene.getItem<Scene>(".test").getItem<SceneItem>(1); // Then expect(scene.getItem(".test") instanceof Scene).to.be.true; expect(item0.state.selector).to.be.equals(`[data-scene-id="${item0.state.id}"]`); expect(item1.state.selector).to.be.equals(`[data-scene-id="${item1.state.id}"]`); expect(item0.elements.length).to.be.equals(1); expect(item1.elements.length).to.be.equals(1); expect(item0.elements[0].getAttribute("data-scene-id")).to.be.equals(item0.state.id); expect(item1.elements[0].getAttribute("data-scene-id")).to.be.equals(item1.state.id); expect(item0.get(0, "width")).to.be.equals("0px"); expect(item1.get(0, "width")).to.be.equals("100px"); }); it(`should check load options`, () => { const scene = new Scene({ ".test": { 0: { width: "100px", height: "100px", }, 1: { width: "200px", height: "200px", }, }, "options": { selector: true, }, }); expect(scene.getItem<SceneItem>(".test").elements.length).to.be.equals(2); }); it(`should check playCSS method`, done => { const scene = new Scene({ ".test": { 0: { width: "100px", height: "100px", }, 0.1: { width: "200px", height: "200px", }, }, "options": { selector: true, }, }); scene.playCSS(); expect(hasClass(document.querySelector(".test1"), START_ANIMATION)).to.be.true; expect(hasClass(document.querySelector(".test2"), START_ANIMATION)).to.be.true; expect(scene.getPlayState()).to.be.equals("running"); scene.on("ended", e => { expect(scene.getPlayState()).to.be.equals("paused"); expect(scene.state.playCSS).to.be.false; done(); }); }); it(`should check playCSS method with function`, done => { // Given const scene = new Scene({ ".test": i => ({ 0: { width: `${i * 100}px`, height: "100px", }, 0.1: { width: "200px", height: "200px", }, options: { iterationCount: "infinite", }, }), ".testf": { 0: { width: "0px", }, 0.1: { height: "1px", }, options: { // iterationCount: "infinite", }, }, }, { selector: true, }); // When scene.playCSS(); setTimeout(() => { // Then expect(scene.isEnded()).to.be.false; scene.finish(); done(); }, 300); // Then }); it(`should check playCSS & pauseCSS method`, () => { const scene = new Scene({ ".test": { 0: { width: "100px", height: "100px", }, 0.1: { width: "200px", height: "200px", }, }, "options": { selector: true, }, }); // when scene.playCSS(); scene.pause(); // then expect(hasClass(document.querySelector(".test1"), START_ANIMATION)).to.be.true; expect(hasClass(document.querySelector(".test1"), PAUSE_ANIMATION)).to.be.true; expect(hasClass(document.querySelector(".test2"), START_ANIMATION)).to.be.true; expect(hasClass(document.querySelector(".test2"), PAUSE_ANIMATION)).to.be.true; expect(scene.getPlayState()).to.be.equals("paused"); expect(scene.state.playCSS).to.be.true; scene.finish(); }); it(`should check toCSS method with no element`, () => { const scene = new Scene({ ".noelement": { 0: { width: "100px", height: "100px", }, 0.1: { width: "200px", height: "200px", }, }, }, { selector: true, }); // when const css = scene.toCSS(); // then expect(css).to.be.have.string(".noelement.startAnimation"); expect(css).to.be.have.string(".noelement.pauseAnimation"); expect(css).to.be.have.string("width:200px;"); }); it(`should check playCSS & finish method`, () => { const scene = new Scene({ ".test": { 0: { width: "100px", height: "100px", }, 0.1: { width: "200px", height: "200px", }, }, "options": { selector: true, }, }); // when scene.playCSS(); scene.finish(); // then expect(hasClass(document.querySelector(".test1"), START_ANIMATION)).to.be.false; expect(hasClass(document.querySelector(".test1"), PAUSE_ANIMATION)).to.be.false; expect(hasClass(document.querySelector(".test2"), START_ANIMATION)).to.be.false; expect(hasClass(document.querySelector(".test2"), PAUSE_ANIMATION)).to.be.false; expect(scene.getPlayState()).to.be.equals("paused"); expect(scene.state.playCSS).to.be.false; }); it(`should check playCSS method with iteration count = 2`, done => { const scene = new Scene({ ".test": { 0: { width: "100px", height: "100px", }, 0.1: { width: "200px", height: "200px", }, }, "options": { iterationCount: 2, selector: true, }, }); scene.playCSS(); expect(hasClass(document.querySelector(".test1"), START_ANIMATION)).to.be.true; expect(hasClass(document.querySelector(".test2"), START_ANIMATION)).to.be.true; expect(scene.getPlayState()).to.be.equals("running"); expect(scene.state.playCSS).to.be.true; const spy = sinon.spy(); scene.on("iteration", spy); scene.on("ended", e => { expect(spy.calledOnce).to.be.true; expect(scene.getPlayState()).to.be.equals("paused"); expect(scene.state.playCSS).to.be.false; done(); }); }); }); });
the_stack
import Adapt, { ChangeType, Group, isMountedElement, PluginOptions } from "@adpt/core"; import should from "should"; import { createMockLogger, k8sutils, MockLogger } from "@adpt/testutils"; import { sleep } from "@adpt/utils"; import { ActionPlugin, createActionPlugin } from "../../src/action"; import { ClusterInfo, Kubeconfig, Resource, resourceElementToName, } from "../../src/k8s"; import { kubectlOpManifest } from "../../src/k8s/kubectl"; import { deployIDToLabel, labelKey, Manifest } from "../../src/k8s/manifest_support"; import { mkInstance } from "../run_minikube"; import { act, checkNoActions, doBuild, randomName } from "../testlib"; import { forceK8sObserverSchemaLoad, K8sTestStatusType } from "./testlib"; const { deleteAll, getAll } = k8sutils; // tslint:disable-next-line: no-object-literal-type-assertion const dummyConfig = {} as ClusterInfo; describe("k8s Resource Component Tests", () => { it("Should Instantiate Resource", () => { const resElem = <Resource key="test" kind="Pod" config={dummyConfig} spec={{ containers: [{ name: "test", image: "dummy-image", }] }} />; should(resElem).not.Undefined(); }); }); describe("k8s Resource Tests (Resource, Pod)", function () { this.timeout(60 * 1000); let plugin: ActionPlugin; let logger: MockLogger; let options: PluginOptions; let clusterInfo: ClusterInfo; let client: k8sutils.KubeClient; let deployID: string | undefined; const testNamespace = "utility-function-test"; const testNamespaceManifest: Manifest = { apiVersion: "v1", kind: "Namespace", metadata: { name: testNamespace, } }; before(async function () { this.timeout(mkInstance.setupTimeoutMs); this.slow(20 * 1000); clusterInfo = { kubeconfig: await mkInstance.kubeconfig as Kubeconfig }; client = await mkInstance.client; forceK8sObserverSchemaLoad(); await kubectlOpManifest("create", { kubeconfig: clusterInfo.kubeconfig, manifest: testNamespaceManifest, }); }); beforeEach(async () => { plugin = createActionPlugin(); logger = createMockLogger(); deployID = randomName("cloud-k8s-plugin"); options = { dataDir: "/fake/datadir", deployID, logger, log: logger.info, }; }); afterEach(async function () { this.timeout(40 * 1000); if (client) { await deleteAll("pods", { client, deployID }); await deleteAll("services", { client, deployID }); } }); after(async () => { await kubectlOpManifest("delete", { kubeconfig: clusterInfo.kubeconfig, manifest: testNamespaceManifest, }); }); function createPodDom(name: string, namespace?: string) { return ( <Resource key={name} config={clusterInfo} kind="Pod" metadata={{ namespace, }} spec={{ containers: [{ name: "container", image: "alpine:3.8", command: ["sleep", "3s"], }], terminationGracePeriodSeconds: 0 }} /> ); } async function createPod(name: string, namespace?: string) { if (!deployID) throw new Error(`Missing deployID?`); const resElem = createPodDom(name, namespace); const { mountedOrig, dom } = await doBuild(resElem, { deployID }); if (!isMountedElement(dom)) { throw should(isMountedElement(dom)).True(); } await plugin.start(options); const obs = await plugin.observe(null, dom); const actions = plugin.analyze(null, dom, obs); should(actions).length(1); should(actions[0].type).equal(ChangeType.create); should(actions[0].detail).startWith("Creating Pod"); should(actions[0].changes).have.length(1); should(actions[0].changes[0].type).equal(ChangeType.create); should(actions[0].changes[0].detail).startWith("Creating Pod"); should(actions[0].changes[0].element.componentName).equal("Resource"); should(actions[0].changes[0].element.props.key).equal(name); await act(actions); const pods = await getAll("pods", { client, deployID, namespaces: ["default", testNamespace] }); should(pods).length(1); should(pods[0].metadata.name) .equal(resourceElementToName(dom, options.deployID)); should(pods[0].metadata.annotations).containEql({ [labelKey("name")]: dom.id }); if (mountedOrig === null) throw should(mountedOrig).not.Null(); const status = await mountedOrig.status<K8sTestStatusType>(); should(status.kind).equal("Pod"); should(status.metadata.name).equal(resourceElementToName(dom, options.deployID)); should(status.metadata.annotations).containEql({ [labelKey("name")]: dom.id }); should(status.metadata.labels).eql({ [labelKey("deployID")]: deployIDToLabel(options.deployID), [labelKey("name")]: resourceElementToName(dom, options.deployID) }); await plugin.finish(); return dom; } it("Should create pod", async () => { await createPod("test"); }); it("Should modify pod", async () => { if (!deployID) throw new Error(`Missing deployID?`); const oldDom = await createPod("test"); //5s sleep diff to cause modify vs. 3s sleep in createPod const command = ["sleep", "5s"]; const resElem = <Resource key="test" config={clusterInfo} kind="Pod" spec={{ containers: [{ name: "container", image: "alpine:3.8", command, }], terminationGracePeriodSeconds: 0 }} />; const { dom } = await doBuild(resElem, { deployID }); await plugin.start(options); const obs = await plugin.observe(oldDom, dom); const actions = plugin.analyze(oldDom, dom, obs); should(actions).length(1); should(actions[0].type).equal(ChangeType.modify); should(actions[0].detail).startWith("Replacing Pod"); should(actions[0].changes).have.length(1); should(actions[0].changes[0].type).equal(ChangeType.modify); should(actions[0].changes[0].detail).startWith("Replacing Pod"); should(actions[0].changes[0].element.componentName).equal("Resource"); should(actions[0].changes[0].element.props.key).equal("test"); await act(actions); const pods = await getAll("pods", { client, deployID }); should(pods).length(1); should(pods[0].metadata.name) .equal(resourceElementToName(dom, options.deployID)); should(pods[0].spec.containers).length(1); should(pods[0].spec.containers[0].command).eql(command); await plugin.finish(); }); it("Should leave pod alone", async () => { const oldDom = await createPod("test"); //No diff const command = ["sleep", "3s"]; const resElem = <Resource key="test" config={clusterInfo} kind="Pod" spec={{ containers: [{ name: "container", image: "alpine:3.8", imagePullPolicy: "IfNotPresent", command, }], terminationGracePeriodSeconds: 0 }} />; const { dom } = await doBuild(resElem, { deployID }); await plugin.start(options); const obs = await plugin.observe(oldDom, dom); const actions = plugin.analyze(oldDom, dom, obs); checkNoActions(actions, dom); await plugin.finish(); }); it("Should delete pod", async () => { if (!deployID) throw new Error(`Missing deployID?`); const oldDom = await createPod("test"); const { dom } = await doBuild(<Group />, { deployID }); await plugin.start(options); const obs = await plugin.observe(oldDom, dom); const actions = plugin.analyze(oldDom, dom, obs); should(actions.length).equal(1); should(actions[0].type).equal(ChangeType.delete); should(actions[0].detail).startWith("Deleting Pod"); should(actions[0].changes).have.length(1); should(actions[0].changes[0].type).equal(ChangeType.delete); should(actions[0].changes[0].detail).startWith("Deleting Pod"); should(actions[0].changes[0].element.componentName).equal("Resource"); should(actions[0].changes[0].element.props.key).equal("test"); await act(actions); await sleep(6); // Sleep longer than termination grace period const pods = await getAll("pods", { client, deployID }); if (pods.length !== 0) { should(pods.length).equal(1); should(pods[0].metadata.deletionGracePeriod).not.Undefined(); } await plugin.finish(); }); it("Should delete pod in alternate namespace", async () => { if (!deployID) throw new Error(`Missing deployID?`); const oldDom = await createPod("test", testNamespace); const { dom } = await doBuild(<Group />, { deployID }); await plugin.start(options); const obs = await plugin.observe(oldDom, dom); const actions = plugin.analyze(oldDom, dom, obs); should(actions.length).equal(1); should(actions[0].type).equal(ChangeType.delete); should(actions[0].detail).startWith("Deleting Pod"); should(actions[0].changes).have.length(1); should(actions[0].changes[0].type).equal(ChangeType.delete); should(actions[0].changes[0].detail).startWith("Deleting Pod"); should(actions[0].changes[0].element.componentName).equal("Resource"); should(actions[0].changes[0].element.props.key).equal("test"); await act(actions); await sleep(6); // Sleep longer than termination grace period const pods = await getAll("pods", { client, deployID }); if (pods.length !== 0) { should(pods.length).equal(1); should(pods[0].metadata.deletionGracePeriod).not.Undefined(); } await plugin.finish(); }); it("Should not delete unmanaged pod", async () => { const manifest = { apiVersion: "v1", kind: "Pod", metadata: { name: randomName("unmanaged-pod") }, spec: { containers: [{ name: "sleep", image: "alpine:latest", command: ["sleep", "5s"] }], terminationGracePeriodSeconds: 0 } }; const result = await client.api.v1.namespaces("default").pods.post({ body: manifest }); should(result.statusCode).equal(201); const { dom } = await doBuild(<Group />, { deployID }); await plugin.start(options); const obs = await plugin.observe(null, dom); const actions = plugin.analyze(null, dom, obs); should(actions.length).equal(0); await plugin.finish(); await client.api.v1.namespaces("default").pods(manifest.metadata.name).delete(); }); it("Should handle deleted pod", async () => { if (!deployID) throw new Error(`Missing deployID?`); const oldDom = await createPod("test"); // Check that the pod was created const podName = resourceElementToName(oldDom, options.deployID); let pods = await getAll("pods", { client, deployID }); should(pods).length(1); should(pods[0].metadata.name).equal(podName); const result = await client.api.v1.namespaces("default").pods(podName).delete(); should(result.statusCode).equal(200); // No change in DOM const updateDom = createPodDom("test"); const { dom } = await doBuild(updateDom, { deployID }); await plugin.start(options); const obs = await plugin.observe(oldDom, dom); const actions = plugin.analyze(oldDom, dom, obs); should(actions).length(1); should(actions[0].type).equal(ChangeType.modify); should(actions[0].detail).startWith("Creating Pod"); should(actions[0].changes).have.length(1); should(actions[0].changes[0].type).equal(ChangeType.modify); should(actions[0].changes[0].detail).startWith("Creating Pod"); should(actions[0].changes[0].element.componentName).equal("Resource"); should(actions[0].changes[0].element.props.key).equal("test"); await act(actions); pods = await getAll("pods", { client, deployID }); should(pods).length(1); should(pods[0].metadata.name).equal(podName); await plugin.finish(); }); });
the_stack
import { GraphQLObjectType, GraphQLInt, GraphQLInputObjectType, GraphQLID, GraphQLFieldConfigMap, GraphQLFieldConfig, GraphQLInputFieldConfigMap, GraphQLFieldResolver, } from 'graphql'; import * as _ from 'lodash'; import * as camelcase from 'camelcase'; import { mutationWithClientMutationId } from "graphql-relay"; import { defaultArgs, defaultListArgs, attributeFields, resolver, SequelizeConnection, Cache, } from "graphql-sequelize-teselagen"; import { convertFieldsFromGlobalId, mutationName, getTableName, convertFieldsToGlobalId, queryName, globalIdInputField, createNonNullList, createNonNullListResolver, } from "./utils"; import { Model, ModelsHashInterface as Models, ModelTypes, } from "./types"; export class OperationFactory { private models: Models; private modelTypes: ModelTypes; private associationsToModel: AssociationToModels; private associationsFromModel: AssociationFromModels; private cache: Cache; constructor(config: OperationFactoryConfig) { this.models = config.models; this.modelTypes = config.modelTypes; this.associationsToModel = config.associationsToModel; this.associationsFromModel = config.associationsFromModel; this.cache = config.cache; } public createRecord({ mutations, model, modelType, }: { mutations: Mutations, model: Model, modelType: GraphQLObjectType, }) { const { models, modelTypes, associationsToModel, associationsFromModel, cache, } = this; const createMutationName = mutationName(model, 'create'); mutations[createMutationName] = mutationWithClientMutationId({ name: createMutationName, description: `Create ${getTableName(model)} record.`, inputFields: () => { const exclude = model.excludeFields ? model.excludeFields : []; const fields = attributeFields(model, { exclude, commentToDescription: true, cache }) as GraphQLInputFieldConfigMap; convertFieldsToGlobalId(model, fields); // FIXME: Handle timestamps // console.log('_timestampAttributes', Model._timestampAttributes); delete fields.createdAt; delete fields.updatedAt; return fields; }, outputFields: () => { const output: GraphQLFieldConfigMap<any, any> = {}; // New Record output[camelcase(`new_${getTableName(model)}`)] = { type: modelType, description: `The new ${getTableName(model)}, if successfully created.`, // tslint:disable-next-line:max-func-args resolve: (args: any, arg2: any, context: any, info: any) => { return resolver(model, { })({}, { [model.primaryKeyAttribute]: args[model.primaryKeyAttribute] }, context, info); } }; // New Edges _.each(associationsToModel[getTableName(model)], (association) => { const { from, type: atype, key: field } = association; // console.log("Edge To", getTableName(Model), "From", from, field, atype); if (atype !== "BelongsTo") { // HasMany Association const { connection } = associationsFromModel[from][`${getTableName(model)}_${field}`]; const fromType = modelTypes[from] as GraphQLObjectType; // let nodeType = conn.nodeType; // let association = Model.associations[field]; // let targetType = association // console.log("Connection", getTableName(Model), field, nodeType, conn, association); output[camelcase(`new_${fromType.name}_${field}_Edge`)] = { type: connection.edgeType, resolve: (payload: any) => connection.resolveEdge(payload) }; } }); _.each(associationsFromModel[getTableName(model)], (association) => { const { to, type: atype, foreignKey, key: field } = association; // console.log("Edge From", getTableName(Model), "To", to, field, as, atype, foreignKey); if (atype === "BelongsTo") { // BelongsTo association const toType = modelTypes[to] as GraphQLObjectType; output[field] = { type: toType, // tslint:disable-next-line:max-func-args resolve: (args: any, arg2: any, context: any, info: any) => { // console.log('Models', Models, Models[toType.name]); return resolver(models[toType.name], {})({}, { id: args[foreignKey] }, context, info); } }; } }); // console.log(`${getTableName(Model)} mutation output`, output); return output; }, mutateAndGetPayload: (data) => { convertFieldsFromGlobalId(model, data); return model.create(data); } }); } public findRecord({ queries, model, modelType }: { queries: Queries; model: Model; modelType: GraphQLObjectType; }) { const findByIdQueryName = queryName(model, 'findById'); const queryArgs = defaultArgs(model); convertFieldsToGlobalId(model, queryArgs); const baseResolve = resolver(model, {}); // tslint:disable-next-line:max-func-args const resolve: GraphQLFieldResolver<any, any> = (source, args, context, info) => { convertFieldsFromGlobalId(model, args); if (args.where) { convertFieldsFromGlobalId(model, args.where); } return baseResolve(source, args, context, info); }; queries[findByIdQueryName] = { type: modelType, args: queryArgs, resolve }; } public findAll({ queries, model, modelType }: { model: Model; modelType: GraphQLObjectType; queries: Queries; }) { const findAllQueryName = queryName(model, 'findAll'); const queryArgs = defaultListArgs(model); const baseResolve = createNonNullListResolver(resolver(model, { list: true })); // tslint:disable-next-line:max-func-args const resolve: GraphQLFieldResolver<any, any> = (source, args, context, info) => { if (args.where) { convertFieldsFromGlobalId(model, args.where); } if (args.include) { convertFieldsFromGlobalId(model, args.include); } return baseResolve(source, args, context, info); }; queries[findAllQueryName] = { type: createNonNullList(modelType), args: queryArgs, resolve, }; } public updateRecords({ mutations, model, modelType, }: { mutations: Mutations, model: Model, modelType: GraphQLObjectType, }) { const { models, modelTypes, associationsToModel, associationsFromModel, cache, } = this; const updateMutationName = mutationName(model, 'update'); mutations[updateMutationName] = mutationWithClientMutationId({ name: updateMutationName, description: `Update multiple ${getTableName(model)} records.`, inputFields: () => { const fields = attributeFields(model, { exclude: model.excludeFields ? model.excludeFields : [], commentToDescription: true, allowNull: true, cache }) as GraphQLInputFieldConfigMap; convertFieldsToGlobalId(model, fields); const updateModelTypeName = `Update${getTableName(model)}ValuesInput`; const updateModelValuesType: GraphQLInputObjectType = ( (cache[updateModelTypeName] as GraphQLInputObjectType) || new GraphQLInputObjectType({ name: updateModelTypeName, description: "Values to update", fields })); cache[updateModelTypeName] = updateModelValuesType; const updateModelWhereType: GraphQLInputObjectType = new GraphQLInputObjectType({ name: `Update${getTableName(model)}WhereInput`, description: "Options to describe the scope of the search.", fields }); return { values: { type: updateModelValuesType }, where: { type: updateModelWhereType, } }; }, outputFields: () => { const output: GraphQLFieldConfigMap<any, any> = {}; // New Record output[camelcase(`new_${getTableName(model)}`)] = { type: modelType, description: `The new ${getTableName(model)}, if successfully created.`, // tslint:disable-next-line max-func-args resolve: (args: any, arg2: any, context: any, info: any) => { return resolver(model, { })({}, { [model.primaryKeyAttribute]: args[model.primaryKeyAttribute] }, context, info); } }; // New Edges _.each(associationsToModel[getTableName(model)], (association) => { const { from, type: atype, key: field } = association; // console.log("Edge To", getTableName(Model), "From", from, field, atype); if (atype !== "BelongsTo") { // HasMany Association const { connection } = associationsFromModel[from][`${getTableName(model)}_${field}`]; const fromType = modelTypes[from] as GraphQLObjectType; // console.log("Connection", getTableName(Model), field, nodeType, conn, association); output[camelcase(`new_${fromType.name}_${field}_Edge`)] = { type: connection.edgeType, resolve: (payload) => connection.resolveEdge(payload) }; } }); _.each(associationsFromModel[getTableName(model)], (association) => { const { to, type: atype, foreignKey, key: field } = association; // console.log("Edge From", getTableName(Model), "To", to, field, as, atype, foreignKey); if (atype === "BelongsTo") { // BelongsTo association const toType = modelTypes[to] as GraphQLObjectType; output[field] = { type: toType, // tslint:disable-next-line max-func-args resolve: (args: any, arg2: any, context: any, info: any) => { // console.log('Models', models, models[toType.name]); return resolver(models[toType.name], {})({}, { id: args[foreignKey] }, context, info); } }; } }); // console.log(`${getTableName(Model)} mutation output`, output); const updateModelOutputTypeName = `Update${getTableName(model)}Output`; const outputType: GraphQLObjectType = ( cache[updateModelOutputTypeName] as GraphQLObjectType || new GraphQLObjectType({ name: updateModelOutputTypeName, fields: output })); cache[updateModelOutputTypeName] = outputType; return { nodes: { type: createNonNullList(outputType), // tslint:disable-next-line max-func-args resolve: createNonNullListResolver((source: any, args: any, context: any, info: any) => { // console.log('update', source, args); return model.findAll({ where: source.where }); }) }, affectedCount: { type: GraphQLInt } }; }, mutateAndGetPayload: (data) => { // console.log('mutate', data); const { values, where } = data; convertFieldsFromGlobalId(model, values); convertFieldsFromGlobalId(model, where); return model.update(values, { where }) .then((result) => { return { where, affectedCount: result[0] }; }); } }); } public updateRecord({ mutations, model, modelType, }: { mutations: Mutations, model: Model, modelType: GraphQLObjectType, }) { const { models, modelTypes, associationsToModel, associationsFromModel, cache, } = this; const updateMutationName = mutationName(model, 'updateOne'); mutations[updateMutationName] = mutationWithClientMutationId({ name: updateMutationName, description: `Update a single ${getTableName(model)} record.`, inputFields: () => { const fields = attributeFields(model, { exclude: model.excludeFields ? model.excludeFields : [], commentToDescription: true, allowNull: true, cache }) as GraphQLInputFieldConfigMap; convertFieldsToGlobalId(model, fields); const updateModelInputTypeName = `Update${getTableName(model)}ValuesInput`; const updateModelValuesType = cache[updateModelInputTypeName] || new GraphQLInputObjectType({ name: updateModelInputTypeName, description: "Values to update", fields }); cache[updateModelInputTypeName] = updateModelValuesType; return { [model.primaryKeyAttribute]: globalIdInputField(getTableName(model)), values: { type: updateModelValuesType } } as any; }, outputFields: () => { const output: GraphQLFieldConfigMap<any, any> = {}; // New Record output[camelcase(`new_${getTableName(model)}`)] = { type: modelType, description: `The new ${getTableName(model)}, if successfully created.`, // tslint:disable-next-line max-func-args resolve: (args: any, arg2: any, context: any, info: any) => { return resolver(model, { })({}, { [model.primaryKeyAttribute]: args[model.primaryKeyAttribute] }, context, info); } }; // New Edges _.each(associationsToModel[getTableName(model)], (association) => { const { from, type: atype, key: field } = association; // console.log("Edge To", getTableName(Model), "From", from, field, atype); if (atype !== "BelongsTo") { // HasMany Association const { connection } = associationsFromModel[from][`${getTableName(model)}_${field}`]; const fromType = modelTypes[from] as GraphQLObjectType; // console.log("Connection", getTableName(Model), field, nodeType, conn, association); output[camelcase(`new_${fromType.name}_${field}_Edge`)] = { type: connection.edgeType, resolve: (payload) => connection.resolveEdge(payload) }; } }); _.each(associationsFromModel[getTableName(model)], (association) => { const { to, type: atype, foreignKey, key: field } = association; // console.log("Edge From", getTableName(Model), "To", to, field, as, atype, foreignKey); if (atype === "BelongsTo") { // BelongsTo association const toType = modelTypes[to] as GraphQLObjectType; output[field] = { type: toType, // tslint:disable-next-line:max-func-args resolve: (args: any, arg2: any, context: any, info: any) => { // console.log('Models', Models, Models[toType.name]); return resolver(models[toType.name], {})({}, { id: args[foreignKey] }, context, info); } }; } }); // console.log(`${getTableName(Model)} mutation output`, output); const updateModelOutputTypeName = `Update${getTableName(model)}Output`; const outputType = cache[updateModelOutputTypeName] || new GraphQLObjectType({ name: updateModelOutputTypeName, fields: output }); cache[updateModelOutputTypeName] = outputType; return output; }, mutateAndGetPayload: (data) => { // console.log('mutate', data); const { values } = data; const where = { [model.primaryKeyAttribute]: data[model.primaryKeyAttribute] }; convertFieldsFromGlobalId(model, values); convertFieldsFromGlobalId(model, where); return model.update(values, { where }) .then((result) => { return where; }); } }); } public deleteRecords({ mutations, model, modelType, }: { mutations: Mutations, model: Model, modelType: GraphQLObjectType, }) { const { cache, } = this; const deleteMutationName = mutationName(model, 'delete'); mutations[deleteMutationName] = mutationWithClientMutationId({ name: deleteMutationName, description: `Delete ${getTableName(model)} records.`, inputFields: () => { const fields = attributeFields(model, { exclude: model.excludeFields ? model.excludeFields : [], commentToDescription: true, allowNull: true, cache }) as GraphQLInputFieldConfigMap; convertFieldsToGlobalId(model, fields); const deleteModelWhereType = new GraphQLInputObjectType({ name: `Delete${getTableName(model)}WhereInput`, description: "Options to describe the scope of the search.", fields }); return { where: { type: deleteModelWhereType, } }; }, outputFields: () => { return { affectedCount: { type: GraphQLInt } }; }, mutateAndGetPayload: (data) => { const { where } = data; convertFieldsFromGlobalId(model, where); return model.destroy({ where }) .then((affectedCount) => { return { where, affectedCount }; }); } }); } public deleteRecord({ mutations, model, modelType, }: { mutations: Mutations, model: Model, modelType: GraphQLObjectType, }) { const deleteMutationName = mutationName(model, 'deleteOne'); mutations[deleteMutationName] = mutationWithClientMutationId({ name: deleteMutationName, description: `Delete single ${getTableName(model)} record.`, inputFields: () => { return { [model.primaryKeyAttribute]: globalIdInputField(getTableName(model)), } as any; }, outputFields: () => { const idField = camelcase(`deleted_${getTableName(model)}_id`); return { [idField]: { type: GraphQLID, resolve: (source) => { return source[model.primaryKeyAttribute]; } } }; }, mutateAndGetPayload: (data) => { const where = { [model.primaryKeyAttribute]: data[model.primaryKeyAttribute] }; convertFieldsFromGlobalId(model, where); return model.destroy({ where }) .then((affectedCount) => { return data; }); } }); } } export interface AssociationToModel { from: string; type: string; key: string; connection: SequelizeConnection; as: any; } export interface AssociationToModels { [tableName: string]: { [fieldName: string]: AssociationToModel; }; } export interface AssociationFromModel { to: string; type: string; foreignKey: string; key: string; connection: SequelizeConnection; as: any; } export interface AssociationFromModels { [tableName: string]: { [fieldName: string]: AssociationFromModel; }; } export interface Queries extends GraphQLFieldConfigMap<any, any> { [queryName: string]: GraphQLFieldConfig<any, any>; } export interface Mutations extends GraphQLFieldConfigMap<any, any> { [mutationName: string]: GraphQLFieldConfig<any, any>; } export interface OperationFactoryConfig { models: Models; modelTypes: ModelTypes; associationsToModel: AssociationToModels; associationsFromModel: AssociationFromModels; cache: Cache; }
the_stack
import type { RuleConfig } from '../rule-config'; /** * Option. */ export type NamingConventionOption = ( | { format: | ( | 'camelCase' | 'strictCamelCase' | 'PascalCase' | 'StrictPascalCase' | 'snake_case' | 'UPPER_CASE' )[] | null; custom?: { match: boolean; regex: string; [k: string]: any; }; leadingUnderscore?: | 'forbid' | 'allow' | 'require' | 'requireDouble' | 'allowDouble' | 'allowSingleOrDouble'; trailingUnderscore?: | 'forbid' | 'allow' | 'require' | 'requireDouble' | 'allowDouble' | 'allowSingleOrDouble'; prefix?: string[]; suffix?: string[]; failureMessage?: string; filter?: | string | { match: boolean; regex: string; [k: string]: any; }; selector: ( | 'default' | 'variableLike' | 'memberLike' | 'typeLike' | 'method' | 'property' | 'variable' | 'function' | 'parameter' | 'parameterProperty' | 'accessor' | 'enumMember' | 'classMethod' | 'objectLiteralMethod' | 'typeMethod' | 'classProperty' | 'objectLiteralProperty' | 'typeProperty' | 'class' | 'interface' | 'typeAlias' | 'enum' | 'typeParameter' )[]; modifiers?: ( | 'const' | 'readonly' | 'static' | 'public' | 'protected' | 'private' | 'abstract' | 'destructured' | 'global' | 'exported' | 'unused' | 'requiresQuotes' )[]; types?: ('boolean' | 'string' | 'number' | 'function' | 'array')[]; } | { format: | ( | 'camelCase' | 'strictCamelCase' | 'PascalCase' | 'StrictPascalCase' | 'snake_case' | 'UPPER_CASE' )[] | null; custom?: { match: boolean; regex: string; [k: string]: any; }; leadingUnderscore?: | 'forbid' | 'allow' | 'require' | 'requireDouble' | 'allowDouble' | 'allowSingleOrDouble'; trailingUnderscore?: | 'forbid' | 'allow' | 'require' | 'requireDouble' | 'allowDouble' | 'allowSingleOrDouble'; prefix?: string[]; suffix?: string[]; failureMessage?: string; filter?: | string | { match: boolean; regex: string; [k: string]: any; }; selector: 'default'; modifiers?: ( | 'const' | 'readonly' | 'static' | 'public' | 'protected' | 'private' | 'abstract' | 'destructured' | 'global' | 'exported' | 'unused' | 'requiresQuotes' )[]; } | { format: | ( | 'camelCase' | 'strictCamelCase' | 'PascalCase' | 'StrictPascalCase' | 'snake_case' | 'UPPER_CASE' )[] | null; custom?: { match: boolean; regex: string; [k: string]: any; }; leadingUnderscore?: | 'forbid' | 'allow' | 'require' | 'requireDouble' | 'allowDouble' | 'allowSingleOrDouble'; trailingUnderscore?: | 'forbid' | 'allow' | 'require' | 'requireDouble' | 'allowDouble' | 'allowSingleOrDouble'; prefix?: string[]; suffix?: string[]; failureMessage?: string; filter?: | string | { match: boolean; regex: string; [k: string]: any; }; selector: 'variableLike'; modifiers?: 'unused'[]; } | { format: | ( | 'camelCase' | 'strictCamelCase' | 'PascalCase' | 'StrictPascalCase' | 'snake_case' | 'UPPER_CASE' )[] | null; custom?: { match: boolean; regex: string; [k: string]: any; }; leadingUnderscore?: | 'forbid' | 'allow' | 'require' | 'requireDouble' | 'allowDouble' | 'allowSingleOrDouble'; trailingUnderscore?: | 'forbid' | 'allow' | 'require' | 'requireDouble' | 'allowDouble' | 'allowSingleOrDouble'; prefix?: string[]; suffix?: string[]; failureMessage?: string; filter?: | string | { match: boolean; regex: string; [k: string]: any; }; selector: 'variable'; modifiers?: ( | 'const' | 'destructured' | 'exported' | 'global' | 'unused' )[]; types?: ('boolean' | 'string' | 'number' | 'function' | 'array')[]; } | { format: | ( | 'camelCase' | 'strictCamelCase' | 'PascalCase' | 'StrictPascalCase' | 'snake_case' | 'UPPER_CASE' )[] | null; custom?: { match: boolean; regex: string; [k: string]: any; }; leadingUnderscore?: | 'forbid' | 'allow' | 'require' | 'requireDouble' | 'allowDouble' | 'allowSingleOrDouble'; trailingUnderscore?: | 'forbid' | 'allow' | 'require' | 'requireDouble' | 'allowDouble' | 'allowSingleOrDouble'; prefix?: string[]; suffix?: string[]; failureMessage?: string; filter?: | string | { match: boolean; regex: string; [k: string]: any; }; selector: 'function'; modifiers?: ('exported' | 'global' | 'unused')[]; } | { format: | ( | 'camelCase' | 'strictCamelCase' | 'PascalCase' | 'StrictPascalCase' | 'snake_case' | 'UPPER_CASE' )[] | null; custom?: { match: boolean; regex: string; [k: string]: any; }; leadingUnderscore?: | 'forbid' | 'allow' | 'require' | 'requireDouble' | 'allowDouble' | 'allowSingleOrDouble'; trailingUnderscore?: | 'forbid' | 'allow' | 'require' | 'requireDouble' | 'allowDouble' | 'allowSingleOrDouble'; prefix?: string[]; suffix?: string[]; failureMessage?: string; filter?: | string | { match: boolean; regex: string; [k: string]: any; }; selector: 'parameter'; modifiers?: ('destructured' | 'unused')[]; types?: ('boolean' | 'string' | 'number' | 'function' | 'array')[]; } | { format: | ( | 'camelCase' | 'strictCamelCase' | 'PascalCase' | 'StrictPascalCase' | 'snake_case' | 'UPPER_CASE' )[] | null; custom?: { match: boolean; regex: string; [k: string]: any; }; leadingUnderscore?: | 'forbid' | 'allow' | 'require' | 'requireDouble' | 'allowDouble' | 'allowSingleOrDouble'; trailingUnderscore?: | 'forbid' | 'allow' | 'require' | 'requireDouble' | 'allowDouble' | 'allowSingleOrDouble'; prefix?: string[]; suffix?: string[]; failureMessage?: string; filter?: | string | { match: boolean; regex: string; [k: string]: any; }; selector: 'memberLike'; modifiers?: ( | 'abstract' | 'private' | 'protected' | 'public' | 'readonly' | 'requiresQuotes' | 'static' )[]; } | { format: | ( | 'camelCase' | 'strictCamelCase' | 'PascalCase' | 'StrictPascalCase' | 'snake_case' | 'UPPER_CASE' )[] | null; custom?: { match: boolean; regex: string; [k: string]: any; }; leadingUnderscore?: | 'forbid' | 'allow' | 'require' | 'requireDouble' | 'allowDouble' | 'allowSingleOrDouble'; trailingUnderscore?: | 'forbid' | 'allow' | 'require' | 'requireDouble' | 'allowDouble' | 'allowSingleOrDouble'; prefix?: string[]; suffix?: string[]; failureMessage?: string; filter?: | string | { match: boolean; regex: string; [k: string]: any; }; selector: 'classProperty'; modifiers?: ( | 'abstract' | 'private' | 'protected' | 'public' | 'readonly' | 'requiresQuotes' | 'static' )[]; types?: ('boolean' | 'string' | 'number' | 'function' | 'array')[]; } | { format: | ( | 'camelCase' | 'strictCamelCase' | 'PascalCase' | 'StrictPascalCase' | 'snake_case' | 'UPPER_CASE' )[] | null; custom?: { match: boolean; regex: string; [k: string]: any; }; leadingUnderscore?: | 'forbid' | 'allow' | 'require' | 'requireDouble' | 'allowDouble' | 'allowSingleOrDouble'; trailingUnderscore?: | 'forbid' | 'allow' | 'require' | 'requireDouble' | 'allowDouble' | 'allowSingleOrDouble'; prefix?: string[]; suffix?: string[]; failureMessage?: string; filter?: | string | { match: boolean; regex: string; [k: string]: any; }; selector: 'objectLiteralProperty'; modifiers?: ('public' | 'requiresQuotes')[]; types?: ('boolean' | 'string' | 'number' | 'function' | 'array')[]; } | { format: | ( | 'camelCase' | 'strictCamelCase' | 'PascalCase' | 'StrictPascalCase' | 'snake_case' | 'UPPER_CASE' )[] | null; custom?: { match: boolean; regex: string; [k: string]: any; }; leadingUnderscore?: | 'forbid' | 'allow' | 'require' | 'requireDouble' | 'allowDouble' | 'allowSingleOrDouble'; trailingUnderscore?: | 'forbid' | 'allow' | 'require' | 'requireDouble' | 'allowDouble' | 'allowSingleOrDouble'; prefix?: string[]; suffix?: string[]; failureMessage?: string; filter?: | string | { match: boolean; regex: string; [k: string]: any; }; selector: 'typeProperty'; modifiers?: ('public' | 'readonly' | 'requiresQuotes')[]; types?: ('boolean' | 'string' | 'number' | 'function' | 'array')[]; } | { format: | ( | 'camelCase' | 'strictCamelCase' | 'PascalCase' | 'StrictPascalCase' | 'snake_case' | 'UPPER_CASE' )[] | null; custom?: { match: boolean; regex: string; [k: string]: any; }; leadingUnderscore?: | 'forbid' | 'allow' | 'require' | 'requireDouble' | 'allowDouble' | 'allowSingleOrDouble'; trailingUnderscore?: | 'forbid' | 'allow' | 'require' | 'requireDouble' | 'allowDouble' | 'allowSingleOrDouble'; prefix?: string[]; suffix?: string[]; failureMessage?: string; filter?: | string | { match: boolean; regex: string; [k: string]: any; }; selector: 'parameterProperty'; modifiers?: ('private' | 'protected' | 'public' | 'readonly')[]; types?: ('boolean' | 'string' | 'number' | 'function' | 'array')[]; } | { format: | ( | 'camelCase' | 'strictCamelCase' | 'PascalCase' | 'StrictPascalCase' | 'snake_case' | 'UPPER_CASE' )[] | null; custom?: { match: boolean; regex: string; [k: string]: any; }; leadingUnderscore?: | 'forbid' | 'allow' | 'require' | 'requireDouble' | 'allowDouble' | 'allowSingleOrDouble'; trailingUnderscore?: | 'forbid' | 'allow' | 'require' | 'requireDouble' | 'allowDouble' | 'allowSingleOrDouble'; prefix?: string[]; suffix?: string[]; failureMessage?: string; filter?: | string | { match: boolean; regex: string; [k: string]: any; }; selector: 'property'; modifiers?: ( | 'abstract' | 'private' | 'protected' | 'public' | 'readonly' | 'requiresQuotes' | 'static' )[]; types?: ('boolean' | 'string' | 'number' | 'function' | 'array')[]; } | { format: | ( | 'camelCase' | 'strictCamelCase' | 'PascalCase' | 'StrictPascalCase' | 'snake_case' | 'UPPER_CASE' )[] | null; custom?: { match: boolean; regex: string; [k: string]: any; }; leadingUnderscore?: | 'forbid' | 'allow' | 'require' | 'requireDouble' | 'allowDouble' | 'allowSingleOrDouble'; trailingUnderscore?: | 'forbid' | 'allow' | 'require' | 'requireDouble' | 'allowDouble' | 'allowSingleOrDouble'; prefix?: string[]; suffix?: string[]; failureMessage?: string; filter?: | string | { match: boolean; regex: string; [k: string]: any; }; selector: 'classMethod'; modifiers?: ( | 'abstract' | 'private' | 'protected' | 'public' | 'requiresQuotes' | 'static' )[]; } | { format: | ( | 'camelCase' | 'strictCamelCase' | 'PascalCase' | 'StrictPascalCase' | 'snake_case' | 'UPPER_CASE' )[] | null; custom?: { match: boolean; regex: string; [k: string]: any; }; leadingUnderscore?: | 'forbid' | 'allow' | 'require' | 'requireDouble' | 'allowDouble' | 'allowSingleOrDouble'; trailingUnderscore?: | 'forbid' | 'allow' | 'require' | 'requireDouble' | 'allowDouble' | 'allowSingleOrDouble'; prefix?: string[]; suffix?: string[]; failureMessage?: string; filter?: | string | { match: boolean; regex: string; [k: string]: any; }; selector: 'objectLiteralMethod'; modifiers?: ('public' | 'requiresQuotes')[]; } | { format: | ( | 'camelCase' | 'strictCamelCase' | 'PascalCase' | 'StrictPascalCase' | 'snake_case' | 'UPPER_CASE' )[] | null; custom?: { match: boolean; regex: string; [k: string]: any; }; leadingUnderscore?: | 'forbid' | 'allow' | 'require' | 'requireDouble' | 'allowDouble' | 'allowSingleOrDouble'; trailingUnderscore?: | 'forbid' | 'allow' | 'require' | 'requireDouble' | 'allowDouble' | 'allowSingleOrDouble'; prefix?: string[]; suffix?: string[]; failureMessage?: string; filter?: | string | { match: boolean; regex: string; [k: string]: any; }; selector: 'typeMethod'; modifiers?: ('public' | 'requiresQuotes')[]; } | { format: | ( | 'camelCase' | 'strictCamelCase' | 'PascalCase' | 'StrictPascalCase' | 'snake_case' | 'UPPER_CASE' )[] | null; custom?: { match: boolean; regex: string; [k: string]: any; }; leadingUnderscore?: | 'forbid' | 'allow' | 'require' | 'requireDouble' | 'allowDouble' | 'allowSingleOrDouble'; trailingUnderscore?: | 'forbid' | 'allow' | 'require' | 'requireDouble' | 'allowDouble' | 'allowSingleOrDouble'; prefix?: string[]; suffix?: string[]; failureMessage?: string; filter?: | string | { match: boolean; regex: string; [k: string]: any; }; selector: 'method'; modifiers?: ( | 'abstract' | 'private' | 'protected' | 'public' | 'requiresQuotes' | 'static' )[]; } | { format: | ( | 'camelCase' | 'strictCamelCase' | 'PascalCase' | 'StrictPascalCase' | 'snake_case' | 'UPPER_CASE' )[] | null; custom?: { match: boolean; regex: string; [k: string]: any; }; leadingUnderscore?: | 'forbid' | 'allow' | 'require' | 'requireDouble' | 'allowDouble' | 'allowSingleOrDouble'; trailingUnderscore?: | 'forbid' | 'allow' | 'require' | 'requireDouble' | 'allowDouble' | 'allowSingleOrDouble'; prefix?: string[]; suffix?: string[]; failureMessage?: string; filter?: | string | { match: boolean; regex: string; [k: string]: any; }; selector: 'accessor'; modifiers?: ( | 'abstract' | 'private' | 'protected' | 'public' | 'requiresQuotes' | 'static' )[]; types?: ('boolean' | 'string' | 'number' | 'function' | 'array')[]; } | { format: | ( | 'camelCase' | 'strictCamelCase' | 'PascalCase' | 'StrictPascalCase' | 'snake_case' | 'UPPER_CASE' )[] | null; custom?: { match: boolean; regex: string; [k: string]: any; }; leadingUnderscore?: | 'forbid' | 'allow' | 'require' | 'requireDouble' | 'allowDouble' | 'allowSingleOrDouble'; trailingUnderscore?: | 'forbid' | 'allow' | 'require' | 'requireDouble' | 'allowDouble' | 'allowSingleOrDouble'; prefix?: string[]; suffix?: string[]; failureMessage?: string; filter?: | string | { match: boolean; regex: string; [k: string]: any; }; selector: 'enumMember'; modifiers?: 'requiresQuotes'[]; } | { format: | ( | 'camelCase' | 'strictCamelCase' | 'PascalCase' | 'StrictPascalCase' | 'snake_case' | 'UPPER_CASE' )[] | null; custom?: { match: boolean; regex: string; [k: string]: any; }; leadingUnderscore?: | 'forbid' | 'allow' | 'require' | 'requireDouble' | 'allowDouble' | 'allowSingleOrDouble'; trailingUnderscore?: | 'forbid' | 'allow' | 'require' | 'requireDouble' | 'allowDouble' | 'allowSingleOrDouble'; prefix?: string[]; suffix?: string[]; failureMessage?: string; filter?: | string | { match: boolean; regex: string; [k: string]: any; }; selector: 'typeLike'; modifiers?: ('abstract' | 'exported' | 'unused')[]; } | { format: | ( | 'camelCase' | 'strictCamelCase' | 'PascalCase' | 'StrictPascalCase' | 'snake_case' | 'UPPER_CASE' )[] | null; custom?: { match: boolean; regex: string; [k: string]: any; }; leadingUnderscore?: | 'forbid' | 'allow' | 'require' | 'requireDouble' | 'allowDouble' | 'allowSingleOrDouble'; trailingUnderscore?: | 'forbid' | 'allow' | 'require' | 'requireDouble' | 'allowDouble' | 'allowSingleOrDouble'; prefix?: string[]; suffix?: string[]; failureMessage?: string; filter?: | string | { match: boolean; regex: string; [k: string]: any; }; selector: 'class'; modifiers?: ('abstract' | 'exported' | 'unused')[]; } | { format: | ( | 'camelCase' | 'strictCamelCase' | 'PascalCase' | 'StrictPascalCase' | 'snake_case' | 'UPPER_CASE' )[] | null; custom?: { match: boolean; regex: string; [k: string]: any; }; leadingUnderscore?: | 'forbid' | 'allow' | 'require' | 'requireDouble' | 'allowDouble' | 'allowSingleOrDouble'; trailingUnderscore?: | 'forbid' | 'allow' | 'require' | 'requireDouble' | 'allowDouble' | 'allowSingleOrDouble'; prefix?: string[]; suffix?: string[]; failureMessage?: string; filter?: | string | { match: boolean; regex: string; [k: string]: any; }; selector: 'interface'; modifiers?: ('exported' | 'unused')[]; } | { format: | ( | 'camelCase' | 'strictCamelCase' | 'PascalCase' | 'StrictPascalCase' | 'snake_case' | 'UPPER_CASE' )[] | null; custom?: { match: boolean; regex: string; [k: string]: any; }; leadingUnderscore?: | 'forbid' | 'allow' | 'require' | 'requireDouble' | 'allowDouble' | 'allowSingleOrDouble'; trailingUnderscore?: | 'forbid' | 'allow' | 'require' | 'requireDouble' | 'allowDouble' | 'allowSingleOrDouble'; prefix?: string[]; suffix?: string[]; failureMessage?: string; filter?: | string | { match: boolean; regex: string; [k: string]: any; }; selector: 'typeAlias'; modifiers?: ('exported' | 'unused')[]; } | { format: | ( | 'camelCase' | 'strictCamelCase' | 'PascalCase' | 'StrictPascalCase' | 'snake_case' | 'UPPER_CASE' )[] | null; custom?: { match: boolean; regex: string; [k: string]: any; }; leadingUnderscore?: | 'forbid' | 'allow' | 'require' | 'requireDouble' | 'allowDouble' | 'allowSingleOrDouble'; trailingUnderscore?: | 'forbid' | 'allow' | 'require' | 'requireDouble' | 'allowDouble' | 'allowSingleOrDouble'; prefix?: string[]; suffix?: string[]; failureMessage?: string; filter?: | string | { match: boolean; regex: string; [k: string]: any; }; selector: 'enum'; modifiers?: ('exported' | 'unused')[]; } | { format: | ( | 'camelCase' | 'strictCamelCase' | 'PascalCase' | 'StrictPascalCase' | 'snake_case' | 'UPPER_CASE' )[] | null; custom?: { match: boolean; regex: string; [k: string]: any; }; leadingUnderscore?: | 'forbid' | 'allow' | 'require' | 'requireDouble' | 'allowDouble' | 'allowSingleOrDouble'; trailingUnderscore?: | 'forbid' | 'allow' | 'require' | 'requireDouble' | 'allowDouble' | 'allowSingleOrDouble'; prefix?: string[]; suffix?: string[]; failureMessage?: string; filter?: | string | { match: boolean; regex: string; [k: string]: any; }; selector: 'typeParameter'; modifiers?: 'unused'[]; } )[]; /** * Options. */ export type NamingConventionOptions = NamingConventionOption; /** * Enforces naming conventions for everything across a codebase. * * @see [naming-convention](https://typescript-eslint.io/rules/naming-convention) */ export type NamingConventionRuleConfig = RuleConfig<NamingConventionOptions>; /** * Enforces naming conventions for everything across a codebase. * * @see [naming-convention](https://typescript-eslint.io/rules/naming-convention) */ export interface NamingConventionRule { /** * Enforces naming conventions for everything across a codebase. * * @see [naming-convention](https://typescript-eslint.io/rules/naming-convention) */ '@typescript-eslint/naming-convention': NamingConventionRuleConfig; }
the_stack
import { PdfDocument, PdfPage, PdfStandardFont, PdfTrueTypeFont, PdfGraphics } from './../../../src/index'; import { PdfSolidBrush, PdfColor, PdfFont,PointF, PdfFontFamily, PdfStringFormat } from './../../../src/index'; import { RectangleF, PdfPen, PdfGraphicsState, PdfFontStyle, PdfTextAlignment, PdfBrush, Dictionary} from './../../../src/index'; import { Utils } from './../utils.spec'; import { PdfBrushes} from './../../../src/implementation/graphics/brushes/pdf-brushes'; import { KnownColor} from './../../../src/implementation/graphics/brushes/enum'; describe('UTC-01: Working with PdfBrushes', () => { it('-EJ2-38410 Drawing PdfBrushes1', (done) => { // create a new PDF document let document : PdfDocument = new PdfDocument(); // add pages to the document. let page1 : PdfPage = document.pages.add(); let page2 : PdfPage = document.pages.add(); let page3 : PdfPage = document.pages.add(); let page4 : PdfPage = document.pages.add(); let page5 : PdfPage = document.pages.add(); //Draw rectangle page1 page1.graphics.drawRectangle(PdfBrushes.AliceBlue, 0, 0, 200, 50); page1.graphics.drawRectangle(PdfBrushes.AntiqueWhite, 0, 150, 200, 50); page1.graphics.drawRectangle(PdfBrushes.Aqua, 0, 300, 200, 50); page1.graphics.drawRectangle(PdfBrushes.Aquamarine, 0, 450, 200 , 50); //Draw rectangele page2 page2.graphics.drawRectangle(PdfBrushes.Azure, 0, 0, 200, 50); page2.graphics.drawRectangle(PdfBrushes.Beige, 0, 150, 200, 50); page2.graphics.drawRectangle(PdfBrushes.Bisque, 0, 300, 200, 50); page2.graphics.drawRectangle(PdfBrushes.Black, 0, 450, 200 , 50); //Draw rectangele page3 page3.graphics.drawRectangle(PdfBrushes.BlanchedAlmond, 0, 0, 200, 50); page3.graphics.drawRectangle(PdfBrushes.Blue, 0, 150, 200, 50); page3.graphics.drawRectangle(PdfBrushes.BlueViolet, 0, 300, 200, 50); page3.graphics.drawRectangle(PdfBrushes.Brown, 0, 450, 200 , 50); //Draw rectangele page4 page4.graphics.drawRectangle(PdfBrushes.BurlyWood, 0, 0, 200, 50); page4.graphics.drawRectangle(PdfBrushes.CadetBlue, 0, 150, 200, 50); page4.graphics.drawRectangle(PdfBrushes.Chartreuse, 0, 300, 200, 50); page4.graphics.drawRectangle(PdfBrushes.Chocolate, 0, 450, 200 , 50); //Draw rectangele page5 page5.graphics.drawRectangle(PdfBrushes.Coral, 0, 0, 200, 50); page5.graphics.drawRectangle(PdfBrushes.CornflowerBlue, 0, 150, 200, 50); page5.graphics.drawRectangle(PdfBrushes.Cornsilk, 0, 300, 200, 50); page5.graphics.drawRectangle(PdfBrushes.Crimson, 0, 450, 200 , 50); //Save the document. //document.save('EJ2_38410_Drawing_with_brushes_1.pdf'); document.save().then((xlBlob: { blobData: Blob }) => { if (Utils.isDownloadEnabled) { Utils.download(xlBlob.blobData, 'EJ2_38410_Drawing_with_brushes_1.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(); }) }); describe('UTC-02: Working with PdfBrushes', () => { it('-EJ2-38410 Drawing PdfBrushes2', (done) => { // create a new PDF document let document : PdfDocument = new PdfDocument(); // add pages to the document. let page1 : PdfPage = document.pages.add(); let page2 : PdfPage = document.pages.add(); let page3 : PdfPage = document.pages.add(); let page4 : PdfPage = document.pages.add(); let page5 : PdfPage = document.pages.add(); //Draw rectangle page1 page1.graphics.drawRectangle(PdfBrushes.Cyan, 0, 0, 200, 50); page1.graphics.drawRectangle(PdfBrushes.DarkBlue, 0, 150, 200, 50); page1.graphics.drawRectangle(PdfBrushes.DarkCyan, 0, 300, 200, 50); page1.graphics.drawRectangle(PdfBrushes.DarkGoldenrod, 0, 450, 200 , 50); //Draw rectangele page2 page2.graphics.drawRectangle(PdfBrushes.DarkGray, 0, 0, 200, 50); page2.graphics.drawRectangle(PdfBrushes.DarkGreen, 0, 150, 200, 50); page2.graphics.drawRectangle(PdfBrushes.DarkKhaki, 0, 300, 200, 50); page2.graphics.drawRectangle(PdfBrushes.DarkMagenta, 0, 450, 200 , 50); //Draw rectangele page3 page3.graphics.drawRectangle(PdfBrushes.DarkOliveGreen, 0, 0, 200, 50); page3.graphics.drawRectangle(PdfBrushes.DarkOrange, 0, 150, 200, 50); page3.graphics.drawRectangle(PdfBrushes.DarkOrchid, 0, 300, 200, 50); page3.graphics.drawRectangle(PdfBrushes.DarkRed, 0, 450, 200 , 50); //Draw rectangele page4 page4.graphics.drawRectangle(PdfBrushes.DarkSalmon, 0, 0, 200, 50); page4.graphics.drawRectangle(PdfBrushes.DarkSeaGreen, 0, 150, 200, 50); page4.graphics.drawRectangle(PdfBrushes.DarkSlateBlue, 0, 300, 200, 50); page4.graphics.drawRectangle(PdfBrushes.DarkSlateGray, 0, 450, 200 , 50); //Draw rectangele page5 page5.graphics.drawRectangle(PdfBrushes.DarkTurquoise, 0, 0, 200, 50); page5.graphics.drawRectangle(PdfBrushes.DarkViolet, 0, 150, 200, 50); page5.graphics.drawRectangle(PdfBrushes.DeepPink, 0, 300, 200, 50); page5.graphics.drawRectangle(PdfBrushes.DeepSkyBlue, 0, 450, 200 , 50); //Save the document. //document.save('EJ2_38410_Drawing_with_brushes_2.pdf'); document.save().then((xlBlob: { blobData: Blob }) => { if (Utils.isDownloadEnabled) { Utils.download(xlBlob.blobData, 'EJ2_38410_Drawing_with_brushes_2.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(); }) }); describe('UTC-03: Working with PdfBrushes', () => { it('-EJ2-38410 Drawing PdfBrushes3', (done) => { // create a new PDF document let document : PdfDocument = new PdfDocument(); // add pages to the document. let page1 : PdfPage = document.pages.add(); let page2 : PdfPage = document.pages.add(); let page3 : PdfPage = document.pages.add(); let page4 : PdfPage = document.pages.add(); let page5 : PdfPage = document.pages.add(); //Draw rectangle page1 page1.graphics.drawRectangle(PdfBrushes.DimGray, 0, 0, 200, 50); page1.graphics.drawRectangle(PdfBrushes.DodgerBlue, 0, 150, 200, 50); page1.graphics.drawRectangle(PdfBrushes.Firebrick, 0, 300, 200, 50); page1.graphics.drawRectangle(PdfBrushes.FloralWhite, 0, 450, 200 , 50); //Draw rectangele page2 page2.graphics.drawRectangle(PdfBrushes.ForestGreen, 0, 0, 200, 50); page2.graphics.drawRectangle(PdfBrushes.Fuchsia, 0, 150, 200, 50); page2.graphics.drawRectangle(PdfBrushes.Gainsboro, 0, 300, 200, 50); page2.graphics.drawRectangle(PdfBrushes.GhostWhite, 0, 450, 200 , 50); //Draw rectangele page3 page3.graphics.drawRectangle(PdfBrushes.Gold, 0, 0, 200, 50); page3.graphics.drawRectangle(PdfBrushes.Goldenrod, 0, 150, 200, 50); page3.graphics.drawRectangle(PdfBrushes.Gray, 0, 300, 200, 50); page3.graphics.drawRectangle(PdfBrushes.Green, 0, 450, 200 , 50); //Draw rectangele page4 page4.graphics.drawRectangle(PdfBrushes.GreenYellow, 0, 0, 200, 50); page4.graphics.drawRectangle(PdfBrushes.Honeydew, 0, 150, 200, 50); page4.graphics.drawRectangle(PdfBrushes.HotPink, 0, 300, 200, 50); page4.graphics.drawRectangle(PdfBrushes.IndianRed, 0, 450, 200 , 50); //Draw rectangele page5 page5.graphics.drawRectangle(PdfBrushes.Indigo, 0, 0, 200, 50); page5.graphics.drawRectangle(PdfBrushes.Ivory, 0, 150, 200, 50); page5.graphics.drawRectangle(PdfBrushes.Khaki, 0, 300, 200, 50); page5.graphics.drawRectangle(PdfBrushes.Lavender, 0, 450, 200 , 50); //Save the document. //document.save('EJ2_38410_Drawing_with_brushes_3.pdf'); document.save().then((xlBlob: { blobData: Blob }) => { if (Utils.isDownloadEnabled) { Utils.download(xlBlob.blobData, 'EJ2_38410_Drawing_with_brushes_3.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(); }) }); describe('UTC-04: Working with PdfBrushes', () => { it('-EJ2-38410 Drawing PdfBrushes4', (done) => { // create a new PDF document let document : PdfDocument = new PdfDocument(); // add pages to the document. let page1 : PdfPage = document.pages.add(); let page2 : PdfPage = document.pages.add(); let page3 : PdfPage = document.pages.add(); let page4 : PdfPage = document.pages.add(); let page5 : PdfPage = document.pages.add(); //Draw rectangle page1 page1.graphics.drawRectangle(PdfBrushes.LavenderBlush, 0, 0, 200, 50); page1.graphics.drawRectangle(PdfBrushes.LawnGreen, 0, 150, 200, 50); page1.graphics.drawRectangle(PdfBrushes.LemonChiffon, 0, 300, 200, 50); page1.graphics.drawRectangle(PdfBrushes.LightBlue, 0, 450, 200 , 50); //Draw rectangele page2 page2.graphics.drawRectangle(PdfBrushes.LightCoral, 0, 0, 200, 50); page2.graphics.drawRectangle(PdfBrushes.LightCyan, 0, 150, 200, 50); page2.graphics.drawRectangle(PdfBrushes.LightGoldenrodYellow, 0, 300, 200, 50); page2.graphics.drawRectangle(PdfBrushes.LightGray, 0, 450, 200 , 50); //Draw rectangele page3 page3.graphics.drawRectangle(PdfBrushes.LightGreen, 0, 0, 200, 50); page3.graphics.drawRectangle(PdfBrushes.LightPink, 0, 150, 200, 50); page3.graphics.drawRectangle(PdfBrushes.LightSalmon, 0, 300, 200, 50); page3.graphics.drawRectangle(PdfBrushes.LightSeaGreen, 0, 450, 200 , 50); //Draw rectangele page4 page4.graphics.drawRectangle(PdfBrushes.LightSkyBlue, 0, 0, 200, 50); page4.graphics.drawRectangle(PdfBrushes.LightSlateGray, 0, 150, 200, 50); page4.graphics.drawRectangle(PdfBrushes.LightSteelBlue, 0, 300, 200, 50); page4.graphics.drawRectangle(PdfBrushes.LightYellow, 0, 450, 200 , 50); //Draw rectangele page5 page5.graphics.drawRectangle(PdfBrushes.Lime, 0, 0, 200, 50); page5.graphics.drawRectangle(PdfBrushes.LimeGreen, 0, 150, 200, 50); page5.graphics.drawRectangle(PdfBrushes.Linen, 0, 300, 200, 50); page5.graphics.drawRectangle(PdfBrushes.Magenta, 0, 450, 200 , 50); //Save the document. //document.save('EJ2_38410_Drawing_with_brushes_4.pdf'); document.save().then((xlBlob: { blobData: Blob }) => { if (Utils.isDownloadEnabled) { Utils.download(xlBlob.blobData, 'EJ2_38410_Drawing_with_brushes_4.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(); }) }); describe('UTC-05: Working with PdfBrushes', () => { it('-EJ2-38410 Drawing PdfBrushes5', (done) => { // create a new PDF document let document : PdfDocument = new PdfDocument(); // add pages to the document. let page1 : PdfPage = document.pages.add(); let page2 : PdfPage = document.pages.add(); let page3 : PdfPage = document.pages.add(); let page4 : PdfPage = document.pages.add(); let page5 : PdfPage = document.pages.add(); //Draw rectangle page1 page1.graphics.drawRectangle(PdfBrushes.Maroon, 0, 0, 200, 50); page1.graphics.drawRectangle(PdfBrushes.MediumAquamarine, 0, 150, 200, 50); page1.graphics.drawRectangle(PdfBrushes.MediumBlue, 0, 300, 200, 50); page1.graphics.drawRectangle(PdfBrushes.MediumOrchid, 0, 450, 200 , 50); //Draw rectangele page2 page2.graphics.drawRectangle(PdfBrushes.MediumPurple, 0, 0, 200, 50); page2.graphics.drawRectangle(PdfBrushes.MediumSeaGreen, 0, 150, 200, 50); page2.graphics.drawRectangle(PdfBrushes.MediumSlateBlue, 0, 300, 200, 50); page2.graphics.drawRectangle(PdfBrushes.MediumSpringGreen, 0, 450, 200 , 50); //Draw rectangele page3 page3.graphics.drawRectangle(PdfBrushes.MediumTurquoise, 0, 0, 200, 50); page3.graphics.drawRectangle(PdfBrushes.MediumVioletRed, 0, 150, 200, 50); page3.graphics.drawRectangle(PdfBrushes.MidnightBlue, 0, 300, 200, 50); page3.graphics.drawRectangle(PdfBrushes.MintCream, 0, 450, 200 , 50); //Draw rectangele page4 page4.graphics.drawRectangle(PdfBrushes.MistyRose, 0, 0, 200, 50); page4.graphics.drawRectangle(PdfBrushes.Moccasin, 0, 150, 200, 50); page4.graphics.drawRectangle(PdfBrushes.NavajoWhite, 0, 300, 200, 50); page4.graphics.drawRectangle(PdfBrushes.Navy, 0, 450, 200 , 50); //Draw rectangele page5 page5.graphics.drawRectangle(PdfBrushes.OldLace, 0, 0, 200, 50); page5.graphics.drawRectangle(PdfBrushes.Olive, 0, 150, 200, 50); page5.graphics.drawRectangle(PdfBrushes.OliveDrab, 0, 300, 200, 50); page5.graphics.drawRectangle(PdfBrushes.Orange, 0, 450, 200 , 50); //Save the document. //document.save('EJ2_38410_Drawing_with_brushes_5.pdf'); document.save().then((xlBlob: { blobData: Blob }) => { if (Utils.isDownloadEnabled) { Utils.download(xlBlob.blobData, 'EJ2_38410_Drawing_with_brushes_5.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(); }) }); describe('UTC-06: Working with PdfBrushes', () => { it('-EJ2-38410 Drawing PdfBrushes6', (done) => { // create a new PDF document let document : PdfDocument = new PdfDocument(); // add pages to the document. let page1 : PdfPage = document.pages.add(); let page2 : PdfPage = document.pages.add(); let page3 : PdfPage = document.pages.add(); let page4 : PdfPage = document.pages.add(); let page5 : PdfPage = document.pages.add(); //Draw rectangle page1 page1.graphics.drawRectangle(PdfBrushes.OrangeRed, 0, 0, 200, 50); page1.graphics.drawRectangle(PdfBrushes.Orchid, 0, 150, 200, 50); page1.graphics.drawRectangle(PdfBrushes.PaleGoldenrod, 0, 300, 200, 50); page1.graphics.drawRectangle(PdfBrushes.PaleGreen, 0, 450, 200 , 50); //Draw rectangele page2 page2.graphics.drawRectangle(PdfBrushes.PaleTurquoise, 0, 0, 200, 50); page2.graphics.drawRectangle(PdfBrushes.PaleVioletRed, 0, 150, 200, 50); page2.graphics.drawRectangle(PdfBrushes.PapayaWhip, 0, 300, 200, 50); page2.graphics.drawRectangle(PdfBrushes.PeachPuff, 0, 450, 200 , 50); //Draw rectangele page3 page3.graphics.drawRectangle(PdfBrushes.Peru, 0, 0, 200, 50); page3.graphics.drawRectangle(PdfBrushes.Pink, 0, 150, 200, 50); page3.graphics.drawRectangle(PdfBrushes.Plum, 0, 300, 200, 50); page3.graphics.drawRectangle(PdfBrushes.PowderBlue, 0, 450, 200 , 50); //Draw rectangele page4 page4.graphics.drawRectangle(PdfBrushes.Purple, 0, 0, 200, 50); page4.graphics.drawRectangle(PdfBrushes.Red, 0, 150, 200, 50); page4.graphics.drawRectangle(PdfBrushes.RosyBrown, 0, 300, 200, 50); page4.graphics.drawRectangle(PdfBrushes.RoyalBlue, 0, 450, 200 , 50); //Draw rectangele page5 page5.graphics.drawRectangle(PdfBrushes.SaddleBrown, 0, 0, 200, 50); page5.graphics.drawRectangle(PdfBrushes.Salmon, 0, 150, 200, 50); page5.graphics.drawRectangle(PdfBrushes.SandyBrown, 0, 300, 200, 50); page5.graphics.drawRectangle(PdfBrushes.SeaGreen, 0, 450, 200 , 50); //Save the document. //document.save('EJ2_38410_Drawing_with_brushes_6.pdf'); document.save().then((xlBlob: { blobData: Blob }) => { if (Utils.isDownloadEnabled) { Utils.download(xlBlob.blobData, 'EJ2_38410_Drawing_with_brushes_6.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(); }) }); describe('UTC-07: Working with PdfBrushes', () => { it('-EJ2-38410 Drawing PdfBrushes7', (done) => { // create a new PDF document let document : PdfDocument = new PdfDocument(); // add pages to the document. let page1 : PdfPage = document.pages.add(); let page2 : PdfPage = document.pages.add(); let page3 : PdfPage = document.pages.add(); let page4 : PdfPage = document.pages.add(); let page5 : PdfPage = document.pages.add(); //Draw rectangle page1 page1.graphics.drawRectangle(PdfBrushes.SeaShell, 0, 0, 200, 50); page1.graphics.drawRectangle(PdfBrushes.Sienna, 0, 150, 200, 50); page1.graphics.drawRectangle(PdfBrushes.Silver, 0, 300, 200, 50); page1.graphics.drawRectangle(PdfBrushes.SkyBlue, 0, 450, 200 , 50); //Draw rectangele page2 page2.graphics.drawRectangle(PdfBrushes.SlateBlue, 0, 0, 200, 50); page2.graphics.drawRectangle(PdfBrushes.SlateGray, 0, 150, 200, 50); page2.graphics.drawRectangle(PdfBrushes.Snow, 0, 300, 200, 50); page2.graphics.drawRectangle(PdfBrushes.SpringGreen, 0, 450, 200 , 50); //Draw rectangele page3 page3.graphics.drawRectangle(PdfBrushes.SteelBlue, 0, 0, 200, 50); page3.graphics.drawRectangle(PdfBrushes.Tan, 0, 150, 200, 50); page3.graphics.drawRectangle(PdfBrushes.Teal, 0, 300, 200, 50); page3.graphics.drawRectangle(PdfBrushes.Thistle, 0, 450, 200 , 50); //Draw rectangele page4 page4.graphics.drawRectangle(PdfBrushes.Tomato, 0, 0, 200, 50); page4.graphics.drawRectangle(PdfBrushes.Transparent, 0, 150, 200, 50); page4.graphics.drawRectangle(PdfBrushes.Turquoise, 0, 300, 200, 50); page4.graphics.drawRectangle(PdfBrushes.Violet, 0, 450, 200 , 50); //Draw rectangele page5 page5.graphics.drawRectangle(PdfBrushes.Wheat, 0, 0, 200, 50); page5.graphics.drawRectangle(PdfBrushes.White, 0, 150, 200, 50); page5.graphics.drawRectangle(PdfBrushes.WhiteSmoke, 0, 300, 200, 50); page5.graphics.drawRectangle(PdfBrushes.Yellow, 0, 450, 200 , 50); page5.graphics.drawRectangle(PdfBrushes.YellowGreen, 0, 550, 200 , 50); //Save the document. //document.save('EJ2_38410_Drawing_with_brushes_7.pdf'); document.save().then((xlBlob: { blobData: Blob }) => { if (Utils.isDownloadEnabled) { Utils.download(xlBlob.blobData, 'EJ2_38410_Drawing_with_brushes_7.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(); }) }); describe('UTC-08: Working with PdfBrushes', () => { it('-EJ2-38410 Drawing PdfBrushes8', (done) => { // create a new PDF document let document : PdfDocument = new PdfDocument(); // add pages to the document. let page1 : PdfPage = document.pages.add(); let pen : PdfPen = new PdfPen(new PdfColor(255, 0, 0)); //Draw rectangle page1 page1.graphics.drawRectangle(pen,PdfBrushes.Transparent, 0, 0, 200, 50); //Save the document. //document.save('EJ2_38410_Drawing_with_brushes_8.pdf'); document.save().then((xlBlob: { blobData: Blob }) => { if (Utils.isDownloadEnabled) { Utils.download(xlBlob.blobData, 'EJ2_38410_Drawing_with_brushes_8.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(); }) }); describe('PdfBrushes.ts', () => { describe('Constructor initializing',()=> { let brushes : PdfBrushes = new PdfBrushes(); let brush : PdfBrush = PdfBrushes.AliceBlue; brush = PdfBrushes.AntiqueWhite; brush = PdfBrushes.Aqua; brush = PdfBrushes.Aquamarine; brush = PdfBrushes.Azure; brush = PdfBrushes.Beige; brush = PdfBrushes.Bisque; brush = PdfBrushes.Black; brush = PdfBrushes.BlanchedAlmond; brush = PdfBrushes.Blue; brush = PdfBrushes.BlueViolet; brush = PdfBrushes.Brown; brush = PdfBrushes.BurlyWood; brush = PdfBrushes.CadetBlue; brush = PdfBrushes.Chartreuse; brush = PdfBrushes.Chocolate; brush = PdfBrushes.Coral; brush = PdfBrushes.CornflowerBlue; brush = PdfBrushes.Cornsilk; brush = PdfBrushes.Crimson; brush = PdfBrushes.Cyan; brush = PdfBrushes.DarkBlue; brush = PdfBrushes.DarkCyan; brush = PdfBrushes.DarkGoldenrod; brush = PdfBrushes.DarkGray; brush = PdfBrushes.DarkGreen; brush = PdfBrushes.DarkKhaki; brush = PdfBrushes.DarkMagenta; brush = PdfBrushes.DarkOliveGreen; brush = PdfBrushes.DarkOrange; brush = PdfBrushes.DarkOrchid; brush = PdfBrushes.DarkRed; brush = PdfBrushes.DarkSalmon; brush = PdfBrushes.DarkSeaGreen; brush = PdfBrushes.DarkSlateBlue; brush = PdfBrushes.DarkSlateGray; brush = PdfBrushes.DarkTurquoise brush = PdfBrushes.DarkViolet brush = PdfBrushes.DeepPink; brush = PdfBrushes.DeepSkyBlue; brush = PdfBrushes.DimGray; brush = PdfBrushes.DodgerBlue; brush = PdfBrushes.Firebrick; brush = PdfBrushes.FloralWhite; brush = PdfBrushes.ForestGreen; brush = PdfBrushes.Fuchsia; brush = PdfBrushes.Gainsboro; brush = PdfBrushes.GhostWhite; brush = PdfBrushes.Gold; brush = PdfBrushes.Goldenrod; brush = PdfBrushes.Gray; brush = PdfBrushes.Green; brush = PdfBrushes.GreenYellow; brush = PdfBrushes.Honeydew; brush = PdfBrushes.HotPink; brush = PdfBrushes.IndianRed; brush = PdfBrushes.Indigo; brush = PdfBrushes.Ivory; brush = PdfBrushes.Khaki; brush = PdfBrushes.Lavender; brush = PdfBrushes.LavenderBlush; brush = PdfBrushes.LawnGreen; brush = PdfBrushes.LemonChiffon; brush = PdfBrushes.LightBlue; brush = PdfBrushes.LightCoral; brush = PdfBrushes.LightCyan; brush = PdfBrushes.LightGoldenrodYellow; brush = PdfBrushes.LightGray; brush = PdfBrushes.LightGreen; brush = PdfBrushes.LightPink; brush = PdfBrushes.LightSalmon; brush = PdfBrushes.LightSeaGreen; brush = PdfBrushes.LightSkyBlue; brush = PdfBrushes.LightSlateGray; brush = PdfBrushes.LightSteelBlue; brush = PdfBrushes.LightYellow; brush = PdfBrushes.Lime; brush = PdfBrushes.LimeGreen; brush = PdfBrushes.Linen; brush = PdfBrushes.Magenta; brush = PdfBrushes.Maroon; brush = PdfBrushes.MediumAquamarine; brush = PdfBrushes.MediumBlue; brush = PdfBrushes.MediumOrchid; brush = PdfBrushes.MediumPurple; brush = PdfBrushes.MediumSeaGreen; brush = PdfBrushes.MediumSlateBlue; brush = PdfBrushes.MediumSpringGreen; brush = PdfBrushes.MediumTurquoise; brush = PdfBrushes.MediumVioletRed; brush = PdfBrushes.MidnightBlue; brush = PdfBrushes.MintCream; brush = PdfBrushes.MistyRose; brush = PdfBrushes.Moccasin; brush = PdfBrushes.NavajoWhite; brush = PdfBrushes.Navy; brush = PdfBrushes.OldLace; brush = PdfBrushes.Olive; brush = PdfBrushes.OliveDrab; brush = PdfBrushes.Orange; brush = PdfBrushes.OrangeRed; brush = PdfBrushes.Orchid; brush = PdfBrushes.PaleGoldenrod; brush = PdfBrushes.PaleGreen; brush = PdfBrushes.PaleTurquoise; brush = PdfBrushes.PaleVioletRed; brush = PdfBrushes.PapayaWhip; brush = PdfBrushes.PeachPuff; brush = PdfBrushes.Peru; brush = PdfBrushes.Pink; brush = PdfBrushes.Plum; brush = PdfBrushes.PowderBlue; brush = PdfBrushes.Purple; brush = PdfBrushes.Red; brush = PdfBrushes.RosyBrown; brush = PdfBrushes.RoyalBlue; brush = PdfBrushes.SaddleBrown; brush = PdfBrushes.Salmon; brush = PdfBrushes.SandyBrown; brush = PdfBrushes.SeaGreen; brush = PdfBrushes.SeaShell; brush = PdfBrushes.Sienna; brush = PdfBrushes.Silver; brush = PdfBrushes.SkyBlue; brush = PdfBrushes.SlateBlue; brush = PdfBrushes.SlateGray; brush = PdfBrushes.Snow; brush = PdfBrushes.SpringGreen; brush = PdfBrushes.SteelBlue; brush = PdfBrushes.Tan; brush = PdfBrushes.Teal; brush = PdfBrushes.Thistle; brush = PdfBrushes.Tomato; brush = PdfBrushes.Transparent; brush = PdfBrushes.Turquoise; brush = PdfBrushes.Violet; brush = PdfBrushes.Wheat; brush = PdfBrushes.White; brush = PdfBrushes.WhiteSmoke; brush = PdfBrushes.Yellow; brush = PdfBrushes.YellowGreen; }) })
the_stack
import * as angular from 'angular'; /** * @ngdoc directive * @name uifCommandBar * @module officeuifabric.components.commandbar * * @restrict E * * @description * `<uif-command-bar>` is the commandbar directive. * * @see {link http://dev.office.com/fabric/components/commandbar} * * @usage * * <uif-command-bar> * <uif-command-bar-search></uif-command-bar-search> * <uif-command-bar-side> * <uif-command-bar-item> * <uif-icon uif-type="save" /> * <span>Right</span> * </uif-command-bar-item> * </uif-command-bar-side> * <uif-command-bar-main uif-show-overflow='true'> * <uif-command-bar-item ng-click="goToLink('First Item')"> * <uif-icon uif-type="save"></uif-icon> * <span>First Item</span> * </uif-command-bar-item> * </uif-command-main> * </uif-command-bar> */ export class CommandBarDirective implements angular.IDirective { public restrict: string = 'E'; public template: string = '<div class="ms-CommandBar" ng-transclude></div>'; public transclude: boolean = true; public replace: boolean = true; public scope: {} = { placeholder: '@', uifSearchTerm: '=' }; public static factory(): angular.IDirectiveFactory { const directive: angular.IDirectiveFactory = () => new CommandBarDirective(); return directive; } public link(scope: ICommandBarScope, elem: angular.IAugmentedJQuery, attrs: angular.IAttributes): void { { // focuses the cursor on the input box scope.focusSearchInput = () => { scope.isSearchActive = true; angular.element(elem[0].querySelector('.ms-CommandBarSearch-input'))[0].focus(); }; // clears the search term scope.clearSearchTerm = () => { scope.uifSearchTerm = null; scope.isSearchActive = false; }; }} } /** * @ngdoc interface * @name ICommandBarScope * @module officeuifabric.components.commandbar * * @description * This is the scope used by the <uif-command-bar> directive. * * @property {string} uifSearchTerm - The string value in the uifCommandBarSearch input * @property {string} placeholder - The placeholder for the search input * @property {boolean} isSearchActive - Indicates whether search bar is active - defines the style and behaviour of the element * @property {function} focusSearchInput() - Brings the cursor to the search input in mobile mode and when clicking on the search hourglass * @property {function} clearSearchTerm() - Clears the search term */ interface ICommandBarScope extends angular.IScope { uifSearchTerm: string; placeholder: string; isSearchActive: boolean; focusSearchInput: () => void; clearSearchTerm: () => void; } /** * @ngdoc directive * @name uifCommandBarSearch * @module officeuifabric.components.commandbar * @restrict E * * @description * `<uif-command-bar-search>` implements the fabric commandbar search box behaviour, optional * * @usage * * <uif-command-bar-search placeholder='Search'></uif-command-bar-search> */ export class CommandBarSearchDirective implements angular.IDirective { public restrict: string = 'E'; public replace: boolean = true; public transclude: boolean = true; public template: string = `<div class="ms-CommandBarSearch" ng-class="$parent.isSearchActive == true ? \'is-active\' : \'\';"> <input class="ms-CommandBarSearch-input" type="text" placeholder="{{$parent.placeholder}}" tabindex="1" ng-focus="$parent.isSearchActive = true;" ng-blur="$parent.isSearchActive = false;" ng-model="$parent.uifSearchTerm"> <div class="ms-CommandBarSearch-iconWrapper ms-CommandBarSearch-iconSearchWrapper" ng-click="$parent.focusSearchInput()"> <uif-icon uif-type="search" /> </div> <div class="ms-CommandBarSearch-iconWrapper ms-CommandBarSearch-iconClearWrapper ms-font-s" ng-mousedown="$parent.clearSearchTerm()"> <uif-icon uif-type="x"/> </div> </div>`; public static factory(): angular.IDirectiveFactory { const directive: angular.IDirectiveFactory = () => new CommandBarSearchDirective(); return directive; } } /** * @ngdoc directive * @name uifCommandBarSide * @module officeuifabric.components.commandbar * @restrict E * * @description * `<uif-command-bar-side>` is the side command, show on the right-hand side of the uifCommandBar. * * @usage * * <uif-command-bar-side></uif-command-bar-side> */ export class CommandBarSideDirective implements angular.IDirective { public restrict: string = 'E'; public template: string = '<div class="ms-CommandBar-sideCommands" ng-transclude></div>'; public replace: boolean = true; public transclude: boolean = true; public static factory(): angular.IDirectiveFactory { const directive: angular.IDirectiveFactory = () => new CommandBarSideDirective(); return directive; } } /** * @ngdoc directive * @name uifCommandBarMain * @module officeuifabric.components.commandbar * @restrict E * * @description * `<uif-command-bar-main>` is the uifCommandBarMain directive. Holds all uifCommandBarItems rendered on the left-hand side * * @usage * * <uif-command-bar-main></uif-command-bar-main> */ export class CommandBarMainDirective implements angular.IDirective { public restrict: string = 'E'; public template: string = `<div class="ms-CommandBar-mainArea"> <ng-transclude></ng-transclude> <div ng-if="uifShowOverflow" class="ms-CommandBarItem ms-CommandBarItem--iconOnly ms-CommandBarItem-overflow" ng-class="overflowVisible == true ? \'is-visible\' : \'\';"> <div class="ms-CommandBarItem-linkWrapper" ng-click="openOverflowMenu()"> <a class="ms-CommandBarItem-link" tabindex="2"> <uif-icon uif-type="ellipsis" /> </a> </div> </div> </div>`; public replace: boolean = true; public transclude: boolean = true; public controller: any = CommandBarMainController; public scope: {} = { uifShowOverflow: '=' }; public static factory(): angular.IDirectiveFactory { const directive: angular.IDirectiveFactory = ($timeout: angular.ITimeoutService) => new CommandBarMainDirective($timeout); directive.$inject = ['$timeout']; return directive; } public compile(element: angular.IAugmentedJQuery, attrs: angular.IAttributes, transclude: angular.ITranscludeFunction): angular.IDirectivePrePost { return { post: this.postLink }; } constructor(private $timeout: angular.ITimeoutService) { } private postLink( scope: ICommandBarMainScope, elem: angular.IAugmentedJQuery, attrs: angular.IAttributes, ctrl: CommandBarMainController): void { // opens the overflow menu scope.openOverflowMenu = function(): void { scope.overflowMenuOpen = !scope.overflowMenuOpen; // buid dropdown let contextualMenu: string; contextualMenu = ` <uif-contextual-menu class="ms-CommandBar-overflowMenu" uif-is-open="overflowMenuOpen" uif-close-on-click="false">`; angular.element(elem[0].querySelector('.ms-CommandBarItem-overflow .ms-CommandBarItem-linkWrapper ul')).remove(); angular.forEach(scope.hiddenItems, function(menuitem: any): void { if (menuitem.submenu) { contextualMenu += `<uif-contextual-menu-item ng-model="hiddenItems[` + menuitem.i + `]" ng-click='openOverflowItem(hiddenItems[` + menuitem.i + `])' uif-text='hiddenItems[` + menuitem.i + `].text' ng-show='hiddenItems[` + menuitem.i + `].visible' uif-type="subMenu"> <uif-contextual-menu> <uif-contextual-menu-item ng-click='openOverflowItem(subitem)' uif-text='subitem.text' uif-type="link" ng-repeat="subitem in hiddenItems[` + menuitem.i + `].submenuitems track by $index"/> </uif-contextual-menu> </uif-contextual-menu-item>`; } else { contextualMenu += `<uif-contextual-menu-item ng-model="hiddenItems[` + menuitem.i + `]" ng-click='openOverflowItem(hiddenItems[` + menuitem.i + `])' uif-text='hiddenItems[` + menuitem.i + `].text' ng-show='hiddenItems[` + menuitem.i + `].visible' uif-type="link"> </uif-contextual-menu-item>`; } }); contextualMenu += '</<uif-contextual-menu>'; let menu: any; menu = elem[0].querySelector('.ms-CommandBarItem-overflow .ms-CommandBarItem-linkWrapper'); angular.element(menu).append(ctrl.$compile(contextualMenu)(scope)); }; // calculate total width of items, fired on resize and called on load scope.loadMenuItems = function(commandItems: any): void { let commandItemWidth: number = 0; let commandItemIndex: number = 0; scope.commandItems = []; angular.forEach(commandItems, function(element: any): void { if (angular.element(element).hasClass('ms-CommandBarItem-overflow') !== true) { commandItemWidth += element.offsetWidth; scope.commandItems.push({index: commandItemIndex, offset: commandItemWidth}); commandItemIndex++; } }); }; // opens the overflow item by calling the click of the related uifCommandBarItem scope.openOverflowItem = function(item: any): void { // open any submenu which was defined in the uifCommandBarItem if (item.submenu) { item.submenuitems = []; angular.forEach(item.submenu.children, function(element: any): void { let submenuitem: any; submenuitem = {}; submenuitem.text = element.innerText; submenuitem.menuType = 'item'; submenuitem.childitem = true; submenuitem.i = item.submenuitems.length; submenuitem.parent = item.i; item.submenuitems.push(submenuitem); }); } else { ctrl.$timeout( () => { if (item.childitem === true) { let m: any; m = elem[0].querySelectorAll('.ms-CommandBarItem')[item.parent].querySelectorAll('.ms-ContextualMenu-item')[item.i]; angular.element(m).triggerHandler('click'); } else { angular.element(elem[0].querySelectorAll('.ms-CommandBarItem')[item.i]).triggerHandler('click'); } }, 1); } }; // calculated which items should be hidden and places them into overflow scope.toggleItemVisibility = function(): void { let commandBarItems: any; commandBarItems = angular.element(elem[0].querySelectorAll('.ms-CommandBar-mainArea .ms-CommandBarItem')); // check for toggle to/from mobile if (window.innerWidth < 640 && scope.mobileSwitch === false) { scope.loadMenuItems(commandBarItems); scope.mobileSwitch = true; } else if (window.innerWidth >= 640 && scope.mobileSwitch === true) { scope.loadMenuItems(commandBarItems); scope.mobileSwitch = false; } // check for any existing items which need to be hidden angular.forEach(scope.commandItems, function(element: any): void { if (element.offset >= elem.prop('offsetWidth') - 200) { angular.element(elem[0].querySelectorAll('.ms-CommandBarItem')[element.index]).addClass('is-hidden'); scope.hiddenItems[element.index].visible = true; scope.overflowVisible = true; } else { angular.element(elem[0].querySelectorAll('.ms-CommandBarItem')[element.index]).removeClass('is-hidden'); scope.hiddenItems[element.index].visible = false; scope.overflowVisible = false; } }); ctrl.$timeout( () => { scope.$apply(); }, 1); }; scope.$on('uif-command-bar-resize', () => { scope.overflowMenuOpen = false; scope.toggleItemVisibility(); }); // bind window resize to trigger overflow event angular.element(window).bind('resize', function(): void { scope.$broadcast('uif-command-bar-resize'); }); // fire on load to render overflow correctly angular.element(document).ready(function (): void { scope.loadMenuItems(angular.element(elem[0].querySelectorAll('.ms-CommandBarItem'))); scope.toggleItemVisibility(); }); } } /** * @ngdoc interface * @name ICommandBarItemScope * @module officeuifabric.components.commandbar * * @description * This is the scope used by the directive. * * @property {boolean} uifShowOverflow - Indicates whether the overflow menu is shown * @property {boolean} overflowMenuOpen - Indicates whether the overflow menu is open * @property {boolean} overflowVisible - Indicates whether the overflow icon should be displayed * @property {boolean} mobileSwitch - Indicates whether the device is in the mobile viewport (below 640px) * @property {collection} commandItems - contains all hidden items * @property {collection} hiddenitems - contains all hidden items * @property {function} openOverflowItem - calls the click of the overflowed item * @property {function} loadMenuItems - loads all of the menu items from <uif-command-bar-main> and records offset for overflow calc * @property {function} toggleItemVisibility - Hides and overflows items which break the bounds of the control * @property {function} openOverflowMenu - Opens the overflow menu * @property {function} openOverflowItem - Adds an item to hiddenItems */ interface ICommandBarMainScope extends angular.IScope { uifShowOverflow: boolean; overflowMenuOpen: boolean; overflowVisible: boolean; mobileSwitch: boolean; commandItems: any[]; hiddenItems: any[]; openOverflowItem: (item: any) => void; loadMenuItems: (commandItems: any) => void; toggleItemVisibility: () => void; openOverflowMenu: () => void; addOverflowItem: (item: any) => void; } /** * @ngdoc controller * @name CommandBarMainController * @module officeuifabric.components.commandbar * * @description * Controller used for the `<uif-command-bar-side-main>` directive. */ export class CommandBarMainController { public static $inject: string[] = ['$scope', '$element', '$compile', '$timeout']; constructor(private $scope: ICommandBarMainScope, private $element: angular.IAugmentedJQuery, public $compile: angular.ICompileService, public $timeout: angular.ITimeoutService) { } public addOverflowItem(item: any): void { if (this.$scope.hiddenItems == null) { this.$scope.hiddenItems = []; } item.i = this.$scope.hiddenItems.length; this.$scope.hiddenItems.push(item); } } /** * @ngdoc directive * @name uifCommandBarItem * @module officeuifabric.components.commandbar * * @restrict E * * @description * `<uif-command-bar-item>` is the commandbar directive. * * @usage * * <uif-command-baritem><span>Item</span></uif-command-bar-item> */ export class CommandBarItemDirective implements angular.IDirective { public restrict: string = 'E'; public template: string = '<div class="ms-CommandBarItem">' + '<div class="ms-CommandBarItem-linkWrapper">' + ' <a class="ms-CommandBarItem-link">' + ' </a>' + '</div>' + '</div>'; public transclude: boolean = true; public replace: boolean = true; public controller: any = CommandBarMainController; public require: string = '^?uifCommandBarMain'; public static factory(): angular.IDirectiveFactory { const directive: angular.IDirectiveFactory = () => new CommandBarItemDirective(); return directive; } public compile(element: angular.IAugmentedJQuery, attrs: angular.IAttributes, transclude: angular.ITranscludeFunction): angular.IDirectivePrePost { return { post: this.postLink }; } private postLink( scope: ICommandBarMainScope, elem: angular.IAugmentedJQuery, attrs: angular.IAttributes, ctrl: CommandBarMainController, transclude: angular.ITranscludeFunction): void { transclude((clone: angular.IAugmentedJQuery) => { let hiddenItem: any; hiddenItem = {}; for (let i: number = 0; i < clone.length; i++) { if (clone[i].tagName === 'UIF-ICON') { angular.element(elem[0].querySelector('a.ms-CommandBarItem-link')).append(clone[i]); } if (clone[i].tagName === 'SPAN') { // validate whether user has added fabric class, include if required if (!clone[i].classList.contains('ms-CommandBarItem-commandText')) { clone[i].classList.add('ms-CommandBarItem-commandText'); } // validate whether user has added any fabric text class, include if required if (clone[i].className.indexOf('ms-font-') === -1) { clone[i].classList.add('ms-font-m'); } angular.element(elem[0].querySelector('a.ms-CommandBarItem-link')).append(clone[i]); hiddenItem.text = clone[i].innerText; } // add the contextual menu to the appropriate place if (clone[i].tagName === 'UL' && clone[i].classList.contains('ms-ContextualMenu')) { angular.element(elem).append(clone[i]); // go through each item hiddenItem.submenu = clone[i]; } } if (ctrl !== null) { if (hiddenItem.submenu == null) { hiddenItem.menuType = 'link'; } else { hiddenItem.menuType = 'subMenu'; } ctrl.addOverflowItem(hiddenItem); } }); // check whether there is a uifIcon, set as textonly otherwise if (angular.element(elem[0].querySelector('.ms-CommandBarItem-link > uif-icon')).length === 0) { angular.element(elem[0].querySelector('.ms-CommandBarItem')).addClass('ms-CommandBarItem-hasTextOnly'); } } } /** * @ngdoc module * @name officeuifabric.components.commandbar * * @description * CommandBar * */ export let module: angular.IModule = angular.module('officeuifabric.components.commandbar', [ 'officeuifabric.components' ]) .directive('uifCommandBar', CommandBarDirective.factory()) .directive('uifCommandBarSearch', CommandBarSearchDirective.factory()) .directive('uifCommandBarItem', CommandBarItemDirective.factory()) .directive('uifCommandBarMain', CommandBarMainDirective.factory()) .directive('uifCommandBarSide', CommandBarSideDirective.factory());
the_stack
const testLogLevel: LogLevelDesc = "debug"; const sutLogLevel: LogLevelDesc = "info"; // Contants: Test ledger const ledgerImageName = "ghcr.io/hyperledger/cactus-corda-4-8-all-in-one-obligation"; const ledgerImageVersion = "2022-03-31-28f0cbf--1956"; const partyARpcUsername = "user1"; const partyARpcPassword = "password"; const partyBRpcUsername = partyARpcUsername; const partyBRpcPassword = partyARpcPassword; const stateToMonitor = "net.corda.samples.example.states.IOUState"; const flowToInvoke = "net.corda.samples.example.flows.ExampleFlow$Initiator"; const testAppId = "monitor-transactions-test-app"; // Contants: Kotlin connector server const kotlinServerImageName = "ghcr.io/hyperledger/cactus-connector-corda-server"; const kotlinServerImageVersion = "2022-05-26-0ff7407--pr-2021"; import "jest-extended"; import { v4 as internalIpV4 } from "internal-ip"; import { CordaTestLedger, SampleCordappEnum, CordaConnectorContainer, pruneDockerAllIfGithubAction, } from "@hyperledger/cactus-test-tooling"; import { Logger, LoggerProvider, LogLevelDesc, } from "@hyperledger/cactus-common"; import { CordappDeploymentConfig, FlowInvocationType, InvokeContractV1Request, JvmTypeKind, PublicKey, } from "../../../main/typescript/generated/openapi/typescript-axios/index"; import { CordaApiClient } from "../../../main/typescript/api-client/corda-api-client"; import { Configuration } from "@hyperledger/cactus-core-api"; import { Subscription } from "rxjs"; // Unit Test logger setup const log: Logger = LoggerProvider.getOrCreate({ label: "kotlin-server-monitor-transactions-v4.8.test", level: testLogLevel, }); ////////////////////////////////// // Helper Functions ////////////////////////////////// async function deployContract( apiClient: CordaApiClient, ledger: CordaTestLedger, rpcPort: number, internalIp: string, ) { log.info("deployContract() called..."); const sshConfig = await ledger.getSshConfig(); const corDappsDirPartyA = await ledger.getCorDappsDirPartyA(); const cdcA: CordappDeploymentConfig = { cordappDir: corDappsDirPartyA, cordaNodeStartCmd: "supervisorctl start corda-a", cordaJarPath: "/samples-kotlin/Advanced/obligation-cordapp/build/nodes/ParticipantA/corda.jar", nodeBaseDirPath: "/samples-kotlin/Advanced/obligation-cordapp/build/nodes/ParticipantA/", rpcCredentials: { hostname: internalIp, port: rpcPort, username: partyARpcUsername, password: partyARpcPassword, }, sshCredentials: { hostKeyEntry: "foo", hostname: internalIp, password: "root", port: sshConfig.port as number, username: sshConfig.username as string, }, }; const partyBRpcPort = await ledger.getRpcBPublicPort(); const corDappsDirPartyB = await ledger.getCorDappsDirPartyB(); const cdcB: CordappDeploymentConfig = { cordappDir: corDappsDirPartyB, cordaNodeStartCmd: "supervisorctl start corda-b", cordaJarPath: "/samples-kotlin/Advanced/obligation-cordapp/build/nodes/ParticipantB/corda.jar", nodeBaseDirPath: "/samples-kotlin/Advanced/obligation-cordapp/build/nodes/ParticipantB/", rpcCredentials: { hostname: internalIp, port: partyBRpcPort, username: partyBRpcUsername, password: partyBRpcPassword, }, sshCredentials: { hostKeyEntry: "foo", hostname: internalIp, password: "root", port: sshConfig.port as number, username: sshConfig.username as string, }, }; const cordappDeploymentConfigs: CordappDeploymentConfig[] = [cdcA, cdcB]; log.debug("cordappDeploymentConfigs:", cordappDeploymentConfigs); const jarFiles = await ledger.pullCordappJars( SampleCordappEnum.BASIC_CORDAPP, ); expect(jarFiles).toBeTruthy(); const deployRes = await apiClient.deployContractJarsV1({ jarFiles, cordappDeploymentConfigs, }); expect(deployRes.data.deployedJarFiles.length).toBeGreaterThan(0); const flowsRes = await apiClient.listFlowsV1(); expect(flowsRes.data.flowNames).toContain(flowToInvoke); } async function invokeContract(apiClient: CordaApiClient, publicKey: PublicKey) { const req: InvokeContractV1Request = ({ timeoutMs: 60000, flowFullClassName: flowToInvoke, flowInvocationType: FlowInvocationType.FlowDynamic, params: [ { jvmTypeKind: JvmTypeKind.Primitive, jvmType: { fqClassName: "java.lang.Integer", }, primitiveValue: 42, }, { jvmTypeKind: JvmTypeKind.Reference, jvmType: { fqClassName: "net.corda.core.identity.Party", }, jvmCtorArgs: [ { jvmTypeKind: JvmTypeKind.Reference, jvmType: { fqClassName: "net.corda.core.identity.CordaX500Name", }, jvmCtorArgs: [ { jvmTypeKind: JvmTypeKind.Primitive, jvmType: { fqClassName: "java.lang.String", }, primitiveValue: "ParticipantB", }, { jvmTypeKind: JvmTypeKind.Primitive, jvmType: { fqClassName: "java.lang.String", }, primitiveValue: "New York", }, { jvmTypeKind: JvmTypeKind.Primitive, jvmType: { fqClassName: "java.lang.String", }, primitiveValue: "US", }, ], }, { jvmTypeKind: JvmTypeKind.Reference, jvmType: { fqClassName: "org.hyperledger.cactus.plugin.ledger.connector.corda.server.impl.PublicKeyImpl", }, jvmCtorArgs: [ { jvmTypeKind: JvmTypeKind.Primitive, jvmType: { fqClassName: "java.lang.String", }, primitiveValue: publicKey?.algorithm, }, { jvmTypeKind: JvmTypeKind.Primitive, jvmType: { fqClassName: "java.lang.String", }, primitiveValue: publicKey?.format, }, { jvmTypeKind: JvmTypeKind.Primitive, jvmType: { fqClassName: "java.lang.String", }, primitiveValue: publicKey?.encoded, }, ], }, ], }, ], } as unknown) as InvokeContractV1Request; const res = await apiClient.invokeContractV1(req); expect(res).toBeTruthy(); expect(res.status).toBe(200); expect(res.data.success).toBeTrue(); } ////////////////////////////////// // Monitor Tests ////////////////////////////////// describe("Monitor Tests", () => { let ledger: CordaTestLedger; let connector: CordaConnectorContainer; let apiClient: CordaApiClient; let partyBPublicKey: PublicKey; beforeAll(async () => { log.info("Prune Docker..."); await pruneDockerAllIfGithubAction({ logLevel: testLogLevel }); ledger = new CordaTestLedger({ imageName: ledgerImageName, imageVersion: ledgerImageVersion, logLevel: testLogLevel, }); const ledgerContainer = await ledger.start(); expect(ledgerContainer).toBeTruthy(); log.debug("Corda ledger started..."); await ledger.logDebugPorts(); const partyARpcPort = await ledger.getRpcAPublicPort(); const internalIp = (await internalIpV4()) as string; expect(internalIp).toBeTruthy(); log.info("Internal IP (based on default gateway):", internalIp); const springAppConfig = { logging: { level: { root: "info", "net.corda": "info", "org.hyperledger.cactus": sutLogLevel, }, }, cactus: { threadCount: 2, sessionExpireMinutes: 10, corda: { node: { host: internalIp }, rpc: { port: partyARpcPort, username: partyARpcUsername, password: partyARpcPassword, }, }, }, }; const springApplicationJson = JSON.stringify(springAppConfig); const envVarSpringAppJson = `SPRING_APPLICATION_JSON=${springApplicationJson}`; log.debug(envVarSpringAppJson); connector = new CordaConnectorContainer({ logLevel: sutLogLevel, imageName: kotlinServerImageName, imageVersion: kotlinServerImageVersion, envVars: [envVarSpringAppJson], }); expect(connector).toBeTruthy(); await connector.start(); await connector.logDebugPorts(); const apiUrl = await connector.getApiLocalhostUrl(); const config = new Configuration({ basePath: apiUrl }); apiClient = new CordaApiClient(config); expect(apiClient).toBeTruthy(); await deployContract(apiClient, ledger, partyARpcPort, internalIp); log.info("Fetching network map for Corda network..."); const networkMapRes = await apiClient.networkMapV1(); expect(networkMapRes.data).toBeTruthy(); const partyB = networkMapRes.data.find((it) => it.legalIdentities.some((li) => li.name.organisation === "ParticipantB"), ); partyBPublicKey = partyB?.legalIdentities[0].owningKey as PublicKey; expect(partyBPublicKey).toBeTruthy(); }); afterAll(async () => { if (ledger) { await ledger.stop(); await ledger.destroy(); } if (connector) { await connector.stop(); await connector.destroy(); } }); describe("Low-level StartMonitor and StopMonitor tests", () => { afterEach(async () => { // Stop monitor await apiClient.stopMonitorV1({ clientAppId: testAppId, stateFullClassName: stateToMonitor, }); }); test("Transactions can be read repeatedly until cleared or monitoring stop", async () => { // Start monitor const resMonitor = await apiClient.startMonitorV1({ clientAppId: testAppId, stateFullClassName: stateToMonitor, }); expect(resMonitor.status).toBe(200); expect(resMonitor.data.success).toBeTrue(); // Get transactions before invoke - should be 0 const resGetTxPre = await apiClient.getMonitorTransactionsV1({ clientAppId: testAppId, stateFullClassName: stateToMonitor, }); expect(resGetTxPre.status).toBe(200); expect(resGetTxPre.data.stateFullClassName).toEqual(stateToMonitor); expect(resGetTxPre.data.tx?.length).toBe(0); // Invoke transactions const transactionCount = 3; for (let i = 0; i < transactionCount; i++) { await invokeContract(apiClient, partyBPublicKey); } // Get transactions after invoke const resGetTxPost = await apiClient.getMonitorTransactionsV1({ clientAppId: testAppId, stateFullClassName: stateToMonitor, }); expect(resGetTxPost.status).toBe(200); expect(resGetTxPost.data.stateFullClassName).toEqual(stateToMonitor); expect(resGetTxPost.data.tx?.length).toBe(transactionCount); const seenIndexes = new Set<string>(); resGetTxPost.data.tx?.forEach((tx) => { expect(tx.index).toBeTruthy(); // Expect indexes to be unique expect(seenIndexes).not.toContain(tx.index); seenIndexes.add(tx.index as string); expect(tx.data).toBeTruthy(); }); // Get transactions after already reading all current ones - should be the same as before const resGetTxPostRead = await apiClient.getMonitorTransactionsV1({ clientAppId: testAppId, stateFullClassName: stateToMonitor, }); expect(resGetTxPostRead.status).toBe(200); expect(resGetTxPostRead.data.stateFullClassName).toEqual(stateToMonitor); expect(resGetTxPostRead.data.tx).toEqual(resGetTxPost.data.tx); }); test("Received transactions can be cleared so they can't be read anymore", async () => { // Start monitor const resMonitor = await apiClient.startMonitorV1({ clientAppId: testAppId, stateFullClassName: stateToMonitor, }); expect(resMonitor.status).toBe(200); expect(resMonitor.data.success).toBeTrue(); // Invoke transactions const transactionCount = 3; for (let i = 0; i < transactionCount; i++) { await invokeContract(apiClient, partyBPublicKey); } // Get transactions after invoke const resGetTx = await apiClient.getMonitorTransactionsV1({ clientAppId: testAppId, stateFullClassName: stateToMonitor, }); expect(resGetTx.status).toBe(200); expect(resGetTx.data.stateFullClassName).toEqual(stateToMonitor); expect(resGetTx.data.tx?.length).toBe(transactionCount); // Clear seen transactions const readTxIdx = resGetTx.data.tx?.map((tx) => tx.index); const resClearTx = await apiClient.clearMonitorTransactionsV1({ clientAppId: testAppId, stateFullClassName: stateToMonitor, txIndexes: readTxIdx as string[], }); expect(resClearTx.status).toBe(200); expect(resClearTx.data.success).toBeTrue(); // Get transactions after clear - should be 0 const resGetTxPostClear = await apiClient.getMonitorTransactionsV1({ clientAppId: testAppId, stateFullClassName: stateToMonitor, }); expect(resGetTxPostClear.status).toBe(200); expect(resGetTxPostClear.data.stateFullClassName).toEqual(stateToMonitor); expect(resGetTxPostClear.data.tx?.length).toBe(0); }); test("Sending startMonitor repeatedly doesn't affect monitor results", async () => { // Start monitor const resMonitor = await apiClient.startMonitorV1({ clientAppId: testAppId, stateFullClassName: stateToMonitor, }); expect(resMonitor.status).toBe(200); expect(resMonitor.data.success).toBeTrue(); // Invoke first transactions const firstTransactionCount = 3; for (let i = 0; i < firstTransactionCount; i++) { await invokeContract(apiClient, partyBPublicKey); } // Start monitor once again const resMonitorAgain = await apiClient.startMonitorV1({ clientAppId: testAppId, stateFullClassName: stateToMonitor, }); expect(resMonitorAgain.status).toBe(200); expect(resMonitorAgain.data.success).toBeTrue(); // Invoke second transactions const secondTransactionCount = 3; for (let i = 0; i < secondTransactionCount; i++) { await invokeContract(apiClient, partyBPublicKey); } // Get final transactions const resGetTx = await apiClient.getMonitorTransactionsV1({ clientAppId: testAppId, stateFullClassName: stateToMonitor, }); expect(resGetTx.status).toBe(200); expect(resGetTx.data.stateFullClassName).toEqual(stateToMonitor); expect(resGetTx.data.tx?.length).toEqual( firstTransactionCount + secondTransactionCount, ); }); test("Monitoring restart after previous stop works", async () => { // Start monitor const resMonitor = await apiClient.startMonitorV1({ clientAppId: testAppId, stateFullClassName: stateToMonitor, }); expect(resMonitor.status).toBe(200); expect(resMonitor.data.success).toBeTrue(); // Invoke transactions const transactionCount = 3; for (let i = 0; i < transactionCount; i++) { await invokeContract(apiClient, partyBPublicKey); } // Stop Monitor const resStopMonitor = await apiClient.stopMonitorV1({ clientAppId: testAppId, stateFullClassName: stateToMonitor, }); expect(resStopMonitor.status).toBe(200); expect(resStopMonitor.data.success).toBeTrue(); // Restart Monitor const resMonitorRestart = await apiClient.startMonitorV1({ clientAppId: testAppId, stateFullClassName: stateToMonitor, }); expect(resMonitorRestart.status).toBe(200); expect(resMonitorRestart.data.success).toBeTrue(); // Invoke transactions after restart const transactionCountAfterRestart = 2; for (let i = 0; i < transactionCountAfterRestart; i++) { await invokeContract(apiClient, partyBPublicKey); } // Get transactions should return only new transactions const resGetTxPostRestart = await apiClient.getMonitorTransactionsV1({ clientAppId: testAppId, stateFullClassName: stateToMonitor, }); expect(resGetTxPostRestart.status).toBe(200); expect(resGetTxPostRestart.data.stateFullClassName).toEqual( stateToMonitor, ); expect(resGetTxPostRestart.data.tx?.length).toBe( transactionCountAfterRestart, ); }); test("Monitor returns only transactions after monitor was started, not previous ones", async () => { // Invoke initial transactions const transactionCountFirst = 5; for (let i = 0; i < transactionCountFirst; i++) { await invokeContract(apiClient, partyBPublicKey); } // Start monitor const resMonitor = await apiClient.startMonitorV1({ clientAppId: testAppId, stateFullClassName: stateToMonitor, }); expect(resMonitor.status).toBe(200); expect(resMonitor.data.success).toBeTrue(); // Invoke transactions after start const transactionCountAfterStart = 2; for (let i = 0; i < transactionCountAfterStart; i++) { await invokeContract(apiClient, partyBPublicKey); } // Get transactions const resGetTx = await apiClient.getMonitorTransactionsV1({ clientAppId: testAppId, stateFullClassName: stateToMonitor, }); expect(resGetTx.status).toBe(200); expect(resGetTx.data.stateFullClassName).toEqual(stateToMonitor); expect(resGetTx.data.tx?.length).toBe(transactionCountAfterStart); }); test("Start monitoring with unknown state returns error", async () => { const unknownState = "foo.bar.non.existent"; // Start monitor const resMonitor = await apiClient.startMonitorV1({ clientAppId: testAppId, stateFullClassName: unknownState, }); expect(resMonitor.status).toBe(200); expect(resMonitor.data.success).toBeFalse(); expect(resMonitor.data.msg).toContain(unknownState); }); test("Stop monitoring with unknown state does nothing and returns success", async () => { // Stop monitor const resStopMon = await apiClient.stopMonitorV1({ clientAppId: testAppId, stateFullClassName: "foo.bar.non.existent", }); expect(resStopMon.status).toBe(200); expect(resStopMon.data.success).toBeTrue(); }); test("Reading / clearing transactions without monitor running returns an error", async () => { // Get transactions before start monitor const resGet = await apiClient.getMonitorTransactionsV1({ clientAppId: testAppId, stateFullClassName: stateToMonitor, }); expect(resGet.status).toBe(200); expect(resGet.data.success).toBeFalse(); expect(resGet.data.msg).toBeTruthy(); expect(resGet.data.stateFullClassName).toBeFalsy(); expect(resGet.data.tx).toBeFalsy(); // Clear transactions before start monitor const resClear = await apiClient.clearMonitorTransactionsV1({ clientAppId: testAppId, stateFullClassName: stateToMonitor, txIndexes: ["1", "2"], }); expect(resClear.status).toBe(200); expect(resClear.data.success).toBeFalse(); expect(resClear.data.msg).toBeTruthy(); }); test("Reading / clearing unknown state returns an error", async () => { // Start monitor const resMonitor = await apiClient.startMonitorV1({ clientAppId: testAppId, stateFullClassName: stateToMonitor, }); expect(resMonitor.status).toBe(200); expect(resMonitor.data.success).toBeTrue(); // Get transactions of unknown state const resGet = await apiClient.getMonitorTransactionsV1({ clientAppId: testAppId, stateFullClassName: "foo.bar.non.existent", }); expect(resGet.status).toBe(200); expect(resGet.data.success).toBeFalse(); expect(resGet.data.msg).toBeTruthy(); expect(resGet.data.stateFullClassName).toBeFalsy(); expect(resGet.data.tx).toBeFalsy(); // Clear transactions of unknown state const resClear = await apiClient.clearMonitorTransactionsV1({ clientAppId: testAppId, stateFullClassName: "foo.bar.non.existent", txIndexes: ["1", "2"], }); expect(resClear.status).toBe(200); expect(resClear.data.msg).toBeTruthy(); expect(resClear.data.success).toBeFalse(); }); }); describe("Multiple clients tests", () => { const anotherAppId = "anotherTestApp"; afterEach(async () => { // Stop Monitors await apiClient.stopMonitorV1({ clientAppId: testAppId, stateFullClassName: stateToMonitor, }); await apiClient.stopMonitorV1({ clientAppId: anotherAppId, stateFullClassName: stateToMonitor, }); }); test("State change can be read by all listening clients separately", async () => { // Start monitor for first client const resMonitorFirst = await apiClient.startMonitorV1({ clientAppId: testAppId, stateFullClassName: stateToMonitor, }); expect(resMonitorFirst.status).toBe(200); expect(resMonitorFirst.data.success).toBeTrue(); // Start monitor for second client const resMonitorAnother = await apiClient.startMonitorV1({ clientAppId: anotherAppId, stateFullClassName: stateToMonitor, }); expect(resMonitorAnother.status).toBe(200); expect(resMonitorAnother.data.success).toBeTrue(); // Invoke transactions const transactionCountAfterStart = 3; for (let i = 0; i < transactionCountAfterStart; i++) { await invokeContract(apiClient, partyBPublicKey); } // Get transactions for first client const resGetTxFirstClient = await apiClient.getMonitorTransactionsV1({ clientAppId: testAppId, stateFullClassName: stateToMonitor, }); expect(resGetTxFirstClient.status).toBe(200); expect(resGetTxFirstClient.data.stateFullClassName).toEqual( stateToMonitor, ); expect(resGetTxFirstClient.data.tx?.length).toBe( transactionCountAfterStart, ); // Clear transactions seen by the first client const readTxIdx = resGetTxFirstClient.data.tx?.map((tx) => tx.index); const resClearTx = await apiClient.clearMonitorTransactionsV1({ clientAppId: testAppId, stateFullClassName: stateToMonitor, txIndexes: readTxIdx as string[], }); expect(resClearTx.status).toBe(200); expect(resClearTx.data.success).toBeTrue(); // Get transactions for second client - should have all transactions available const resGetTxSecondClient = await apiClient.getMonitorTransactionsV1({ clientAppId: anotherAppId, stateFullClassName: stateToMonitor, }); expect(resGetTxSecondClient.status).toBe(200); expect(resGetTxSecondClient.data.stateFullClassName).toEqual( stateToMonitor, ); expect(resGetTxSecondClient.data.tx?.length).toBe( transactionCountAfterStart, ); }); test("State change unsubscribe doesn't affect other client monitors", async () => { // Start monitor for first client const resMonitorFirst = await apiClient.startMonitorV1({ clientAppId: testAppId, stateFullClassName: stateToMonitor, }); expect(resMonitorFirst.status).toBe(200); expect(resMonitorFirst.data.success).toBeTrue(); // Start monitor for second client const resMonitorAnother = await apiClient.startMonitorV1({ clientAppId: anotherAppId, stateFullClassName: stateToMonitor, }); expect(resMonitorAnother.status).toBe(200); expect(resMonitorAnother.data.success).toBeTrue(); // Invoke transactions const transactionCountAfterStart = 3; for (let i = 0; i < transactionCountAfterStart; i++) { await invokeContract(apiClient, partyBPublicKey); } // Stop first client monitoring await apiClient.stopMonitorV1({ clientAppId: testAppId, stateFullClassName: stateToMonitor, }); // Invoke transactions for second client only const transactionCountOnlySecondClient = 4; for (let i = 0; i < transactionCountOnlySecondClient; i++) { await invokeContract(apiClient, partyBPublicKey); } // Get transactions for second client const resGetTxSecondClient = await apiClient.getMonitorTransactionsV1({ clientAppId: anotherAppId, stateFullClassName: stateToMonitor, }); expect(resGetTxSecondClient.status).toBe(200); expect(resGetTxSecondClient.data.stateFullClassName).toEqual( stateToMonitor, ); expect(resGetTxSecondClient.data.tx?.length).toBe( transactionCountAfterStart + transactionCountOnlySecondClient, ); }); }); describe("watchBlocks tests", () => { // watchBlocks tests are async, don't wait so long if something goes wrong const watchBlockTestTimeout = 5 * 60 * 1000; // 5 minutes test( "watchBlocksAsyncV1 reports all transactions", async () => { const transactionCount = 10; const observable = await apiClient.watchBlocksAsyncV1({ clientAppId: testAppId, stateFullClassName: stateToMonitor, pollRate: 1000, }); let sub: Subscription | undefined; const monitor = new Promise<void>((resolve, reject) => { let transactionsReceived = 0; sub = observable.subscribe({ next(tx) { let error: string | undefined; log.debug("Received transaction from monitor:", tx); if (tx.index === undefined || !tx.data) { error = `Wrong transaction format - idx ${tx.index} data ${tx.data}`; } transactionsReceived++; if (error) { log.error(error); reject(error); } if (transactionsReceived === transactionCount) { log.info(`Read all ${transactionCount} transactions - OK`); resolve(); } }, error(err) { log.error("watchBlocksAsyncV1 failed:", err); reject(err); }, }); }).finally(() => sub?.unsubscribe()); // Invoke transactions for (let i = 0; i < transactionCount; i++) { invokeContract(apiClient, partyBPublicKey); } await monitor; }, watchBlockTestTimeout, ); test( "Running watchBlocksAsyncV1 with unknown state report an error on rxjs subject", async () => { const observable = await apiClient.watchBlocksAsyncV1({ clientAppId: testAppId, stateFullClassName: "foo.bar.unknown", }); let sub: Subscription | undefined; await new Promise<void>((resolve, reject) => { sub = observable.subscribe({ next() { reject("Monitor reported new transaction when it should fail."); }, error(err) { log.info("watchBlocksAsyncV1 error reported as expected:", err); resolve(); }, }); }).finally(() => sub?.unsubscribe()); }, watchBlockTestTimeout, ); }); });
the_stack
import dayjs from 'dayjs'; import { getChartListColor } from '@/utils/color'; import { getRandomArray } from '@/utils/charts'; /** 首页 dashboard 折线图 */ export function constructInitDashboardDataset(type: string) { const dateArray: Array<string> = ['周一', '周二', '周三', '周四', '周五', '周六', '周日']; const datasetAxis = { xAxis: { type: 'category', show: false, data: dateArray, }, yAxis: { show: false, type: 'value', }, grid: { top: 0, left: 0, right: 0, bottom: 0, }, }; if (type === 'line') { const lineDataset = { ...datasetAxis, color: ['#fff'], series: [ { data: [150, 230, 224, 218, 135, 147, 260], type, showSymbol: true, symbol: 'circle', symbolSize: 0, markPoint: { data: [ { type: 'max', name: '最大值' }, { type: 'min', name: '最小值' }, ], }, itemStyle: { normal: { lineStyle: { width: 2, }, }, }, }, ], }; return lineDataset; } if (type === 'bar') { const barDataset = { ...datasetAxis, color: getChartListColor(), series: [ { data: [ 100, 130, 184, 218, { value: 135, itemStyle: { opacity: 0.2, }, }, { value: 118, itemStyle: { opacity: 0.2, }, }, { value: 60, itemStyle: { opacity: 0.2, }, }, ], type, barWidth: 9, }, ], }; return barDataset; } } /** 柱状图数据源 */ export function constructInitDataset({ dateTime = [], placeholderColor, borderColor, }: { dateTime: Array<string> } & Record<string, string>) { const divideNum = 10; const timeArray = []; const inArray = []; const outArray = []; for (let i = 0; i < divideNum; i++) { if (dateTime.length > 0) { const dateAbsTime: number = (new Date(dateTime[1]).getTime() - new Date(dateTime[0]).getTime()) / divideNum; const enhandTime: number = new Date(dateTime[0]).getTime() + dateAbsTime * i; timeArray.push(dayjs(enhandTime).format('MM-DD')); } else { timeArray.push( dayjs() .subtract(divideNum - i, 'day') .format('MM-DD'), ); } inArray.push(getRandomArray().toString()); outArray.push(getRandomArray().toString()); } const dataset = { color: getChartListColor(), tooltip: { trigger: 'item', }, xAxis: { type: 'category', data: timeArray, axisLabel: { color: placeholderColor, }, axisLine: { lineStyle: { color: borderColor, width: 1, }, }, }, yAxis: { type: 'value', axisLabel: { color: placeholderColor, }, splitLine: { lineStyle: { color: borderColor, }, }, }, grid: { top: '5%', left: '25px', right: 0, bottom: '60px', }, legend: { icon: 'rect', itemWidth: 12, itemHeight: 4, itemGap: 48, textStyle: { fontSize: 12, color: placeholderColor, }, left: 'center', bottom: '0', orient: 'horizontal', data: ['本月', '上月'], }, series: [ { name: '本月', data: outArray, type: 'bar', }, { name: '上月', data: inArray, type: 'bar', }, ], }; return dataset; } export function getLineChartDataSet({ dateTime = [], placeholderColor, borderColor, }: { dateTime?: Array<string> } & Record<string, string>) { const divideNum = 10; const timeArray = []; const inArray = []; const outArray = []; for (let i = 0; i < divideNum; i++) { if (dateTime.length > 0) { const dateAbsTime: number = (new Date(dateTime[1]).getTime() - new Date(dateTime[0]).getTime()) / divideNum; const enhandTime: number = new Date(dateTime[0]).getTime() + dateAbsTime * i; timeArray.push(dayjs(enhandTime).format('MM-DD')); } else { timeArray.push( dayjs() .subtract(divideNum - i, 'day') .format('MM-DD'), ); } inArray.push(getRandomArray().toString()); outArray.push(getRandomArray().toString()); } const dataSet = { color: getChartListColor(), tooltip: { trigger: 'item', }, grid: { left: '0', right: '20px', top: '5px', bottom: '36px', containLabel: true, }, legend: { left: 'center', bottom: '0', orient: 'horizontal', // legend 横向布局。 data: ['本月', '上月'], textStyle: { fontSize: 12, color: placeholderColor, }, }, xAxis: { type: 'category', data: timeArray, boundaryGap: false, axisLabel: { color: placeholderColor, }, axisLine: { lineStyle: { width: 1, }, }, }, yAxis: { type: 'value', axisLabel: { color: placeholderColor, }, splitLine: { lineStyle: { color: borderColor, }, }, }, series: [ { name: '本月', data: outArray, type: 'line', smooth: false, showSymbol: true, symbol: 'circle', symbolSize: 8, itemStyle: { normal: { borderColor, borderWidth: 1, }, }, areaStyle: { normal: { opacity: 0.1, }, }, }, { name: '上月', data: inArray, type: 'line', smooth: false, showSymbol: true, symbol: 'circle', symbolSize: 8, itemStyle: { normal: { borderColor, borderWidth: 1, }, }, }, ], }; return dataSet; } /** * 获取表行数据 * * @export * @param {string} productName * @param {number} divideNum */ export function getSelftItemList(productName: string, divideNum: number): string[] { const productArray: string[] = [productName]; for (let i = 0; i < divideNum; i++) { productArray.push(getRandomArray(100 * i).toString()); } return productArray; } /** * 散点图数据 * * @export * @returns {any[]} */ export function getScatterDataSet({ dateTime = [], placeholderColor, borderColor, }: { dateTime?: Array<string> } & Record<string, string>): any { const divideNum = 40; const timeArray = []; const inArray = []; const outArray = []; for (let i = 0; i < divideNum; i++) { // const [timeArray, inArray, outArray] = dataset; if (dateTime.length > 0) { const dateAbsTime: number = (new Date(dateTime[1]).getTime() - new Date(dateTime[0]).getTime()) / divideNum; const enhandTime: number = new Date(dateTime[0]).getTime() + dateAbsTime * i; timeArray.push(dayjs(enhandTime).format('MM-DD')); } else { timeArray.push( dayjs() .subtract(divideNum - i, 'day') .format('MM-DD'), ); } inArray.push(getRandomArray().toString()); outArray.push(getRandomArray().toString()); } return { color: getChartListColor(), xAxis: { data: timeArray, axisLabel: { color: placeholderColor, }, splitLine: { show: false }, axisLine: { lineStyle: { color: borderColor, width: 1, }, }, }, yAxis: { type: 'value', // splitLine: { show: false}, axisLabel: { color: placeholderColor, }, nameTextStyle: { padding: [0, 0, 0, 60], }, axisTick: { show: false, axisLine: { show: false, }, }, axisLine: { show: false, }, splitLine: { lineStyle: { color: borderColor, }, }, }, tooltip: { trigger: 'item', }, grid: { top: '5px', left: '25px', right: '5px', bottom: '60px', }, legend: { left: 'center', bottom: '0', orient: 'horizontal', // legend 横向布局。 data: ['按摩仪', '咖啡机'], itemHeight: 8, itemWidth: 8, textStyle: { fontSize: 12, color: placeholderColor, }, }, series: [ { name: '按摩仪', symbolSize: 10, data: outArray.reverse(), type: 'scatter', }, { name: '咖啡机', symbolSize: 10, data: inArray.concat(inArray.reverse()), type: 'scatter', }, ], }; } /** * 获域图数据结构 * * @export * @returns {any[]} */ export function getAreaChartDataSet(): any { const xAxisData = []; const data1 = []; const data2 = []; for (let i = 0; i < 50; i++) { xAxisData.push(`${i}`); data1.push((getRandomArray() * Math.sin(i / 5) * (i / 5 - 5) + i / 6) * 2); data2.push((getRandomArray() * Math.cos(i / 5) * (i / 5 - 5) + i / 6) * 2); } return { color: getChartListColor(), // title: { // text: '柱状图动画延迟', // }, legend: { left: 'center', bottom: '5%', orient: 'horizontal', data: ['测试', '上线'], }, tooltip: { trigger: 'item', }, xAxis: { data: xAxisData, splitLine: { show: false, }, }, yAxis: {}, series: [ { name: '测试', type: 'bar', data: data1, emphasis: { focus: 'series', }, animationDelay(idx: number) { return idx * 10; }, }, { name: '上线', type: 'bar', data: data2, emphasis: { focus: 'series', }, animationDelay(idx: number) { return idx * 10 + 100; }, }, ], animationEasing: 'elasticOut', animationDelayUpdate(idx: number) { return idx * 5; }, }; } /** * 柱状图数据结构 * * @export * @param {boolean} [isMonth=false] * @returns {*} */ export function getColumnChartDataSet(isMonth = false) { if (isMonth) { return { color: getChartListColor(), legend: { left: 'center', top: '10%', orient: 'horizontal', // legend 横向布局。 data: ['直接访问'], }, tooltip: { trigger: 'axis', axisPointer: { // 坐标轴指示器,坐标轴触发有效 type: 'shadow', // 默认为直线,可选为:'line' | 'shadow' }, }, grid: { left: '3%', right: '4%', bottom: '3%', containLabel: true, }, xAxis: [ { type: 'category', data: ['1', '4', '8', '12', '16', '20', '24'], axisTick: { alignWithLabel: true, }, }, ], yAxis: [ { type: 'value', }, ], series: [ { name: '直接访问', type: 'bar', barWidth: '60%', data: [ getRandomArray(Math.random() * 100), getRandomArray(Math.random() * 200), getRandomArray(Math.random() * 300), getRandomArray(Math.random() * 400), getRandomArray(Math.random() * 500), getRandomArray(Math.random() * 600), getRandomArray(Math.random() * 700), ], }, ], }; } return { color: getChartListColor(), tooltip: { trigger: 'axis', axisPointer: { // 坐标轴指示器,坐标轴触发有效 type: 'shadow', // 默认为直线,可选为:'line' | 'shadow' }, }, legend: { left: 'center', bottom: '0%', orient: 'horizontal', // legend 横向布局。 data: ['直接访问'], }, grid: { left: '3%', right: '4%', bottom: '13%', containLabel: true, }, xAxis: [ { type: 'category', data: ['周一', '周二', '周三', '周四', '周五', '周六', '周日'], axisTick: { alignWithLabel: true, }, }, ], yAxis: [ { type: 'value', }, ], series: [ { name: '直接访问', type: 'bar', barWidth: '20%', data: [ getRandomArray(Math.random() * 100), getRandomArray(Math.random() * 200), getRandomArray(Math.random() * 300), getRandomArray(Math.random() * 400), getRandomArray(Math.random() * 500), getRandomArray(Math.random() * 600), getRandomArray(Math.random() * 700), ], }, ], }; } export function getPieChartDataSet({ radius = 42, textColor, placeholderColor, containerColor, }: { radius: number } & Record<string, string>) { return { color: getChartListColor(), tooltip: { show: false, trigger: 'axis', position: null, }, grid: { top: '0', right: '0', }, legend: { selectedMode: false, itemWidth: 12, itemHeight: 4, textStyle: { fontSize: 12, color: placeholderColor, }, left: 'center', bottom: '0', orient: 'horizontal', // legend 横向布局。 }, series: [ { name: '销售渠道', type: 'pie', radius: ['48%', '60%'], avoidLabelOverlap: true, selectedMode: true, hoverAnimation: true, silent: true, itemStyle: { borderColor: containerColor, borderWidth: 1, }, label: { show: true, position: 'center', formatter: ['{value|{d}%}', '{name|{b}渠道占比}'].join('\n'), rich: { value: { color: textColor, fontSize: 28, fontWeight: 'normal', lineHeight: 46, }, name: { color: '#909399', fontSize: 12, lineHeight: 14, }, }, }, emphasis: { label: { show: true, formatter: ['{value|{d}%}', '{name|{b}渠道占比}'].join('\n'), rich: { value: { color: textColor, fontSize: 28, fontWeight: 'normal', lineHeight: 46, }, name: { color: '#909399', fontSize: 14, lineHeight: 14, }, }, }, }, labelLine: { show: false, }, data: [ { value: 1048, name: '线上', }, { value: radius * 7, name: '门店' }, ], }, ], }; }
the_stack
import hastscript from 'hastscript' import visit from 'unist-util-visit' import mdastToc from 'mdast-util-toc' import frontmatter from 'front-matter' import toHast from 'mdast-util-to-hast' import { basename, dirname } from 'path' import toString from 'hast-util-to-string' import unified, { Settings } from 'unified' import VMessage, { VFileMessage } from 'vfile-message' /** * Remark imports */ import gfm from 'remark-gfm' import slug from 'remark-slug' import markdown from 'remark-parse' import directive from 'remark-directive' import headings from 'remark-autolink-headings' import squeezeParagraphs from 'remark-squeeze-paragraphs' /** * Rehype imports */ import raw from 'rehype-raw' import remarkToRehype from 'remark-rehype' /** * Local imports */ import { Point, Position, StatsNode, hastTypes, mdastTypes, ReferenceNode, LeafDirective, TextDirective, ContainerDirective, MarkdownFileOptions, MarkdownFileJson, } from '../Contracts' import { Macros } from '../Macros' import { Compiler } from '../Compiler' import { CodeBlockParser } from '../CodeBlockParser' import { getProtocol } from '../utils' /** * Exposes the API to process markdown contents for a given file using unified, * remark and rehype. */ export class MarkdownFile { /** * Tracked assets to avoid duplicates */ private trackedAssets: Set<string> = new Set() /** * Macros manager */ private macros = new Macros(this) /** * Registered hooks */ private hooks: { test: string | ((node: mdastTypes.Content, file: MarkdownFile) => boolean) visitor: (node: mdastTypes.Content, file: MarkdownFile) => void }[] = [] /** * Collection of unified plugins */ private unifiedPlugins: { callback: unified.Plugin<any>; settings?: any }[] = [] /** * File state */ public state: 'idle' | 'processing' | 'processed' = 'idle' /** * Reference to the file path */ public filePath?: string = this.options.filePath /** * Reference to the file basename */ public basename?: string = this.filePath ? basename(this.filePath) : undefined /** * Reference to the file dirname */ public dirname?: string = this.filePath ? dirname(this.filePath) : undefined /** * Document collected stats */ public stats: StatsNode = { assets: [], } /** * Reference to the document table of content. Only available when "options.generateToc = true" */ public toc: hastTypes.Element | null /** * Find if a document has a fatal message or not */ public hasFatalMessages: boolean = false /** * Array of reported messages */ public messages: VFileMessage[] = [] /** * Reference to the file parsed front matter */ public frontmatter: { [key: string]: any } /** * Excerpt generated from the summary. */ public excerpt?: string /** * Processed markdown summary to AST. */ public summary?: hastTypes.Root /** * Parsed AST. Available after "process" call */ public ast?: hastTypes.Root /** * A factory function to create hash script node */ public hastFactory = hastscript constructor(public contents: string, public options: MarkdownFileOptions = {}) { this.boot() } /** * Boot method parses the yaml front matter right away */ private boot() { const { attributes, body, bodyBegin } = frontmatter<{ [key: string]: any }>(this.contents) this.frontmatter = attributes /** * Here we intentionally patch the public options to reflect the options * defined in front matter. This is done, so that any other part of the * codebase relying on the `file.options` property get the final set * of options and not just the initial options. * * ------------------------------------------------------------------ * ONLY FOLLOWING OPTIONS ARE ENTERTAINED * ------------------------------------------------------------------ * * generateToc?: boolean * tocDepth?: 1 | 2 | 3 | 4 | 5 | 6 */ if (this.frontmatter.generateToc !== undefined) { this.options.generateToc = this.frontmatter.generateToc } if (this.frontmatter.tocDepth !== undefined) { this.options.tocDepth = this.frontmatter.tocDepth } /** * Patch the remaining contents with empty whitespace. This will ensure * that the ast location points to the correct line + col */ this.contents = `${new Array(bodyBegin).join('\n')}${body}` } /** * Cleanup by releasing values no longer required */ private cleanup() { this.unifiedPlugins = [] this.hooks = [] this.trackedAssets.clear() this.macros.clear() } /** * Convert mdast to hast */ private useRehype(stream: unified.Processor) { /** * Configure stream to process HTML. The "rehype-raw" plugin is required to properly * re-parse HTML nodes. Mdast is not good in recognizing HTML */ if (this.options.allowHtml === true) { return stream .use(remarkToRehype, { allowDangerousHtml: this.options.allowHtml === true }) .use(raw) } else { return stream.use(remarkToRehype) } } /** * Add compiler to the unified stream */ private useCompiler(stream: unified.Processor) { return stream.use(function () { const compiler = new Compiler() this.Compiler = compiler.compile.bind(compiler) }) } /** * Returns the matching hooks for a given node */ private getNodeHooks(node: mdastTypes.Content) { return this.hooks.filter((hook) => { if (typeof hook.test === 'function') { return hook.test(node, this) } return node.type === hook.test }) } /** * Processes pre-defined hooks for the matching nodes. */ private processHooks(stream: unified.Processor) { /** * Return early if no hooks are defined */ if (this.hooks.length === 0) { return stream } return stream.use(() => { return (tree) => { visit(tree, (node: mdastTypes.Content) => { this.getNodeHooks(node).forEach((hook) => hook.visitor(node, this)) }) } }) } /** * Process the markdown contents */ private async processContents() { /** * Markdown + gfm + headings with id + auto linking headings */ const stream = unified() .use(markdown) .use(gfm) .use(slug) .use(headings) .use(() => { return (tree) => { /** * Attach meta data to codeblocks */ visit(tree, 'code', (node: mdastTypes.Code) => { const { content, ...codeBlockMeta } = new CodeBlockParser().parse(node.value) node.value = content node.meta = codeBlockMeta as any }) } }) /** * Enable directives and macros */ if (this.options.enableDirectives === true) { stream.use(directive).use(() => this.macros.transform.bind(this.macros)) } /** * Stick custom plugins */ this.unifiedPlugins.forEach((plugin) => stream.use(plugin.callback, ...plugin.settings)) /** * Generate toc when generateToc is set to true */ if (this.options.generateToc === true) { stream.use(() => { return (tree) => { /** * Generate table of contents and convert to hast tree */ const toc = mdastToc(tree, { maxDepth: this.options.tocDepth || 3 }).map if (toc) { this.toc = toHast(toc) as hastTypes.Element } } }) } /** * Collect assets */ if (this.options.collectAssets === true) { this.on('image', (node: mdastTypes.Image) => { this.addAsset(node.url, 'image') }) } /** * Final set of mdast plugins to squeeze empty paragraphs. Should be the * last mdast plugin */ stream.use(squeezeParagraphs) /** * Process hooks on the mdast tree */ this.processHooks(stream) /** * Convert to rehype */ this.useRehype(stream) /** * Stick compiler */ this.useCompiler(stream) this.ast = (await stream.process(this.contents)).result as hastTypes.Root } /** * Process the file summary as markdown */ private async processSummary() { if (!this.frontmatter.summary) { return } /** * Markdown + gfm (headings and autolinking not required here) */ const stream = unified().use(markdown).use(gfm) /** * Convert to rehype */ this.useRehype(stream) /** * Stick compiler */ this.useCompiler(stream) /** * Get summary and its plain text excerpt */ this.summary = (await stream.process(this.frontmatter.summary)).result as hastTypes.Root this.excerpt = toString(this.summary) } /** * Report error message */ public report(reason: string, position?: Position | Point, rule?: string): VFileMessage { const message = new VMessage(reason, position, rule) this.messages.push(message) return message } /** * Define inline macro */ public inlineMacro( name: string, cb: (node: TextDirective | LeafDirective, file: this, removeNode: () => void) => void ): this { this.macros.add(name, cb) return this } /** * Define container macro */ public macro( name: string, cb: (node: ContainerDirective, file: this, removeNode: () => void) => void ): this { this.macros.add(name, cb) return this } /** * Track asset */ public addAsset(url: string, type: string): this { if (this.trackedAssets.has(url)) { return this } const protocol = getProtocol(url) const asset: ReferenceNode = { originalUrl: url, url: url, type: type, isRelative: !protocol, isLocal: !protocol || protocol === 'file:', } this.trackedAssets.add(url) this.stats.assets.push(asset) return this } /** * Hook into link node */ public on( test: string | ((node: mdastTypes.Content, file: this) => boolean), cb: (node: mdastTypes.Content, file: this) => void ): this { this.hooks.push({ test, visitor: cb }) return this } /** * Define unified plugin */ public transform<S extends any[] = [Settings?]>( callback: unified.Plugin<S>, ...settings: S ): this { this.unifiedPlugins.push({ callback, settings }) return this } /** * Process the file */ public async process() { if (this.state !== 'idle') { throw new Error('Cannot re-process the same markdown file') } this.state = 'processing' await Promise.all([this.processSummary(), this.processContents()]) this.state = 'processed' this.cleanup() return this.ast } /** * JSON representation of the file */ public toJSON(): MarkdownFileJson { return { state: this.state, stats: this.stats, ast: this.ast, summary: this.summary, excerpt: this.excerpt, frontmatter: this.frontmatter, messages: this.messages, ...(this.filePath ? { filePath: this.filePath, dirname: this.dirname, basename: this.basename } : {}), ...(this.options.generateToc ? { toc: this.toc! } : {}), } } }
the_stack
import * as fs from "fs"; import * as fsPath from "path"; import * as async from "async"; import * as _ from "lodash"; import { VEvent } from "./VEvent"; import { VDefinition } from "./VDefinition"; import { HTTP, VBase, VConfig, VError, VModel, VMiddleware, VRouter, VEventReader, VWebSocket } from "./Components"; import { VFallback, VCondition, VPolicy, VValidator, VPager, VBody, VSession } from "./MiddlewareParsers"; import { VTemplate } from "./Templates/VTemplate"; import { VWSServer } from "./VWSServer"; import { promisify } from "bluebird"; import * as debug from "debug"; import * as url from "url"; const print = debug("vig:vhandler"); export class VHandler { public urls: string[] = []; public prefix = ""; public config: VConfig; public condition: VCondition; public error: VError; public body: VBody; public event: VEventReader; // Expressjs Traditional Middlewares public middleware: VMiddleware; public model: VModel; public policy: VPolicy; public session: VSession; public router: VRouter; public validator: VValidator; public fallback: VFallback; // VWebSocket public websocket: VWebSocket; // Pagination Parser public pager: VPager; public template: VTemplate; public definition: VDefinition; protected path: string; private parent: VHandler = null; private children: VHandler[] = []; private eventHandler: VEvent = VEvent.getInstance(); // Current Scope private scope: object = {}; private unmuted: any = { }; constructor(urls: string[] = null, path: string = "", prefix = "") { this.urls = urls || []; path = path || ""; this.path = path; this.prefix = prefix; if (!urls || !urls.length) { this.requireFile("urls"); } if (!prefix) { this.requireFile("prefix"); } this.config = new VConfig(path); this.pager = new VPager(path); this.event = new VEventReader(path); this.condition = new VCondition(path); this.error = new VError(path); this.body = new VBody(path); this.model = new VModel(path); this.session = new VSession(path); this.middleware = new VMiddleware(path); this.policy = new VPolicy(path); this.router = new VRouter(path); this.validator = new VValidator(path); this.fallback = new VFallback(path); this.template = new VTemplate(path); this.websocket = new VWebSocket(path); this.definition = new VDefinition(path); const data = [ "pager", "config", "condition", "error", "body", "model", "session", "event", "middleware", "policy", "event", "router", "validator", "websocket", "fallback"]; for (const key of data) { this[key].loadOn(); } this.updateFallbacks(); this.loadStaticScope(); this.initChildren(); } public requireFile(name: string) { const allowedExt = [".js", ".ts", ".json"]; for (const ext of allowedExt) { const dir = fsPath.resolve(this.path, "./" + name); const resolve = dir + ext; if (fs.existsSync(resolve)) { const data = require(resolve); if (data) { this[name] = data; break; } } } } public setUrls(urls: string[]) { this.urls = urls; } public setParent(p: VHandler) { this.parent = p; this.template.setParent(p.template); const parent = this.parent.getScope(); const clone = _.merge({}, parent); const scope = _.merge({}, this.scope); this.scope = _.merge(clone, scope); for (const child of this.children) { child.setParent(this); } } public setPrefix(prefix) { this.prefix = prefix; } public update(k: string, v) { if (this[k]) { this[k].set(v); } } public extend(method, cb) { return this.router.extend(method, cb); } public set(config) { const keys = { condition: "conditions", middleware: "middlewares", router: "routers", error: "errors", config: "configs", event: "events", body: "bodies", model: "models", session: "sessions", pager: "pagers", definition: "definitions", policy: "policies", websocket: "websockets", validator: "validations", fallback: "failures" }; if (config.urls) { this.urls = config.urls; } if (config.prefix) { this.prefix = config.prefix; } for (const key of Object.keys(keys)) { if (config[keys[key]]) { this[key].set(config[keys[key]]); } else { this[key].set({}); } } this.updateFallbacks(); this.loadStaticScope(); this.children = []; } public getScope() { return this.scope; } public updateFallbacks() { const keys = { validation: "validator" }; const fallbacks = this.fallback.get(); const items = Object.keys(fallbacks); for (const key of items) { const keyOne = this[keys[key]] || this[key]; if (keyOne) { keyOne.setFailureHandler(fallbacks[key]); } } } public attach(app) { const prefix = this.prefix || ""; let urls = []; if (this.urls instanceof Array) { urls = this.urls; } for (const item of urls) { let urlTemp = prefix + item; urlTemp = urlTemp.replace(/\/+/g, "/"); app.all(urlTemp, (req, res) => { this.run(req, res).catch((e) => print(e)); }); } for (const child of this.children) { child.attach(app); } } public loadStaticScope() { this.config.parse(this.scope); this.error.parse(this.scope); this.definition.parse(this.scope); this.eventPrepare(); this.websocketPrepare(); // Accelerate speed by ignoring unnecessary processes this.processMuted(); } public eventPrepare() { const events = this.event.get(); for (const key in events) { if (key && events[key]) { this.eventHandler.on(key, ((iK) => { return async (...args) => { args = [this.scope].concat(args); await this.event.run(iK, args); } })(key)); } } } public websocketPrepare() { const wss = VWSServer.getInstance(); const websocketHandlers = this.websocket.get(); for (const key of Object.keys(websocketHandlers)) { wss.addEventListener(key, this); } } public getFixedScope() { const scope: any = { debug, time: { start: new Date() } }; for (const key of Object.keys(this.scope)) { scope[key] = this.scope[key]; } this.model.parse(scope); scope.template = this.template; return scope; } public checkMutable(module) { return Object.keys(this[module].get()).length > 0; } public processMuted() { const mutables = ["body", "session", "condition", "policy", "middleware", "condition", "validator", "pager"]; for (const key of mutables) { this.unmuted[key] = this.checkMutable(key); } } public async run(req, res) { // Scoped Data const scope: any = this.getFixedScope(); scope.event = this.eventHandler; try { // Parsers and processors // TODO: enable server protector here, using condition instead now. // Input Data prepare if (req.method === "POST" || this.unmuted.body) { await this.body.parse(req, res); } if (this.unmuted.session) { await this.session.parse(req, res, scope); } // Utilities res.vRender = (data, template, ext = "html") => { // Add user session to current User if (req.session && req.session.user) { data.currentUser = req.session.user; } // Add configs to template defaultly data.config = scope.configs; res.send(this.template.render(data, template, ext)); }; res.errorize = res.restify = function errorize(error, data) { if (!error) { return res.json(scope.errors.UnknownError.restify()); } if (error.restify && error.restify instanceof Function) { error = error.restify(); } if (!data) { return res.json( _.extend(error) ); } return res.json( _.extend(error, { data }) ); }; // Middlewares // Exit when middleware return false if (this.unmuted.middleware && await this.middleware.process(req, res, scope) === false) { return; } if (this.unmuted.condition && !await this.condition.process(req, res, scope)) { return; } if (this.unmuted.validator && !await this.validator.process(req, res, scope)) { return; } if (this.unmuted.pager) { await this.pager.parse(req, res, scope); } if (this.unmuted.policy && !await this.policy.process(req, res, scope)) { return; } // Final request process const result = await this.router.run(req, res, scope); if (false === result) { return this.notFound("Not Found!", req, res); } } catch (e) { print(e); } } public notFound(error, req, res) { res.status(404).send("Not Found!"); } // Web sockets public async wsEvent(event, message, ws, req) { const cookies = req.headers.cookie; const store = _.get(this.scope, ["configs", "session", "store"]); if (this.unmuted.session && cookies && store) { let id = cookies.split("="); id = id[1]; id = decodeURIComponent(id); id = id.split(".")[0].split(":")[1]; const getSession = promisify(store.get); const session = await getSession.call(store, id); req.session = session; } await this.websocket.run(event, message, ws, req, this.scope); } // Deprecated public toJSON() { const json: any = {}; json.prefix = this.prefix; json.urls = this.urls; json.routers = this.router.toMethods(); json.middlewares = this.middleware.get(); json.policies = this.policy.toMethods(); json.validations = this.validator.get(); json.conditions = this.condition.get(); json.failures = this.fallback.get(); return json; } private initChildren() { const subDir = "handlers" const resolve = fsPath.resolve(this.path, subDir); if (!fs.existsSync(resolve)) { return; } const stat = fs.statSync(resolve); // ignore directories if (!stat || !stat.isDirectory()) { return false; } this.loadDirectory(resolve); } private loadDirectory(dir: string) { const files = fs.readdirSync(dir); files.forEach((file) => { const absPath = fsPath.resolve(dir, file); const stat = fs.statSync(absPath); let handler; // ignore directories if (stat && stat.isDirectory()) { handler = new VHandler(null, absPath); } else { const data = require(absPath); handler = new VHandler(); handler.set(data); } this.children.push(handler); handler.setParent(this); }); } }
the_stack
import { mxCell, mxEventObject, mxPopupMenu } from "mxgraph"; import { ActionMessage, DrawioLoadActionMessage, EventMessageEvents, } from "src/Messages"; import { FrameMessenger } from "../../FrameMessenger"; import { patch } from "../patch"; import { FontManager } from "./FontManager"; export default class Plugin { app: App; frameMessenger: FrameMessenger; fontManager: FontManager; fileFormat: string; public static plugin(app: App) { // Add the app instance to global scope for debugging Object.defineProperty(window, "drawioApp", { value: app }); // This makes debugging easier because the dev tools exposes the [[TargetFunction]] mxUtils.bind = (thisArg: any, fn: Function) => { return fn.bind(thisArg); }; // Create an instance of our plugin new Plugin(app); } private constructor(app: App) { this.app = app; this.fontManager = new FontManager(); this.frameMessenger = new FrameMessenger( () => window.parent, this.handleMessages.bind(this) ); // Update the file when the diagram changes app.editor.graph.model.addListener( "change", this.handleGraphChange.bind(this) ); // TODO: Make it easy to link the selected cell to a note app.editor.graph.addListener("click", this.handleGraphClick.bind(this)); // Change the drawio app user interface this.modifyUi(app); } handleMessages(message: ActionMessage) { if ("action" in message) { switch (message.action) { case "load": this.handleLoadActionMessage(message); break; } } } handleLoadActionMessage(message: DrawioLoadActionMessage) { // Derive the file format from file data this.fileFormat = /\<svg[\>\s]/.test(message.xml) ? "svg" : "xml"; } handleGraphClick(_sender: any, eventObj: mxEventObject) { // TODO: Make it easy to link the selected cell to a note // const cell = eventObj.getProperty("cell"); } async handleGraphChange() { const currentFile = this.app.getCurrentFile(); if (!currentFile || !this.fileFormat) { //"No current file or format yet return; } if (this.fileFormat === "svg") { // Update svg format const svg = await this.getSvg(this.app.editor); this.frameMessenger.sendMessage({ event: EventMessageEvents.Change, data: svg, }); } else { // Update drawio format const xml = await this.getXml(this.app.editor); this.frameMessenger.sendMessage({ event: EventMessageEvents.Change, data: xml, }); } } private xmlToString(xml: Node) { return new XMLSerializer().serializeToString(xml); } private modifyUi(app: App) { // TODO: Manage dark mode switching // patch( // EditorUi.prototype, // "setDarkMode", // (fn) => // function (dark: boolean) { // console.log("set dark Mode", dark); // } // ); // Hide page view app.setPageVisible(false); // Collapse the format panel app.toggleFormatPanel(false); // Stop Save and exit buttons being created when a new file is loaded this.removeMenubars(app); // Hide menu items that aren't relevant this.removeMenus(); } private removeMenubars(app: App) { patch(EditorUi.prototype, "addEmbedButtons", (fn) => function () {}); // Remove the status elements because this plugin manages saving the diagram app.statusContainer.remove(); app.statusContainer = null; if ( app.menubarContainer.parentElement.firstChild === app.menubarContainer && app.menubarContainer.parentElement.childElementCount === 1 ) { // Move the format window up const formatWindow = app.formatWindow.window; formatWindow.setLocation(formatWindow.getX(), 10); // Hide the empty menubar app.menubarContainer.parentElement.remove(); app.menubarContainer.remove(); } } private removeMenus() { const ignoredMenus: string[] = [ "print", "saveAndExit", "plugins", "exit", "about", ]; const ignoredSubMenus: string[] = ["exportAs", "importFrom", "help"]; patch( Menus.prototype, "addMenuItem", (fn) => function (menu: mxPopupMenu, name: string, ...args: any[]) { if (ignoredMenus.includes(name)) { return; } else { return fn.call(this, menu, name, ...args); } } ); patch( Menus.prototype, "addSubmenu", (fn) => function (name: string, menu: mxPopupMenu, ...args: any[]) { if (ignoredSubMenus.includes(name)) { return; } else { return fn.call(this, name, menu, ...args); } } ); } // Get XML data for saving async getXml(editor: Editor) { const graphXml = editor.getGraphXml(); return this.xmlToString(graphXml); } // Get SVG data for saving async getSvg(editor: Editor): Promise<string> { const svgNamespaceUri = "http://www.w3.org/2000/svg"; const svgDocument = document.createElementNS(svgNamespaceUri, "svg"); const graph = editor.graph; const view = graph.getView(); const { x, y, height, width } = view.graphBounds; const viewScale = view.scale; svgDocument.setAttribute("version", "1.1"); svgDocument.setAttribute("height", `${height / viewScale}px`); svgDocument.setAttribute("width", `${width / viewScale}px`); svgDocument.setAttribute( "viewBox", `0 0 ${width / viewScale} ${height / viewScale}` ); const svgCanvas = new mxSvgCanvas2D(svgDocument); svgCanvas.translate(-x / viewScale, -y / viewScale); svgCanvas.scale(1 / viewScale); const imageExport = new mxImageExport(); const graphCellState = view.getState(graph.model.root); imageExport.getLinkForCellState = function (state, canvas) { const cell = state.cell; if (cell.value != null && typeof cell.value == "object") { return cell.value.getAttribute("link"); } return null; }; imageExport.drawState(graphCellState, svgCanvas); await this.embedGraphInSvg(editor, svgDocument); await this.embedFontsInSvg(editor, svgDocument); // Add margin to SVG this.addViewBoxMarginToSvg(svgDocument); const xml = this.xmlToString(svgDocument); return xml; } private embedGraphInSvg(editor: Editor, svg: SVGElement) { const graphXml = editor.getGraphXml(); const graphXmlContent = this.xmlToString(graphXml); svg.setAttribute("content", graphXmlContent); } private async embedFontsInSvg(editor: Editor, svg: SVGElement) { const customFonts = editor.graph.getCustomFonts(); const fontCssRules: string[] = []; for (const customFont of customFonts) { try { const fontCssRule = await this.fontManager.getFontCssForUrl( customFont.name, customFont.url ); fontCssRules.push(fontCssRule); } catch (err) { console.warn("Couldn't embed font data", err); } } const svgDoc = svg.ownerDocument; const style = svgDoc.createElementNS("http://www.w3.org/2000/svg", "style"); style.setAttribute("type", "text/css"); style.appendChild(svgDoc.createTextNode(fontCssRules.join("\r\n"))); svg.insertBefore(style, svg.firstChild); } private addViewBoxMarginToSvg(svg: SVGElement) { const margin = 10; const viewBox = svg.getAttribute("viewBox"); const [a, b, c, d] = viewBox .split(" ") .map((x: string) => Number.parseFloat(x)); svg.setAttribute( "viewBox", [a - margin, b - margin, c + margin * 2, d + margin * 2].join(" ") ); } } // Draw.loadPlugin((ui) => { // sendEvent({ event: "pluginLoaded", pluginId: "linkSelectedNodeWithData" }); // let nodeSelectionEnabled = false; // const graph = ui.editor.graph; // const highlight = new mxCellHighlight(graph, "#00ff00", 8); // const model = graph.model; // let activeCell: DrawioCell | undefined = undefined; // graph.addListener(mxEvent.DOUBLE_CLICK, function (sender: any, evt: any) { // if (!nodeSelectionEnabled) { // return; // } // var cell: any | null = evt.getProperty("cell"); // if (cell != null) { // const data = getLinkedData(cell); // const label = getLabelTextOfCell(cell); // if (!data && !label.match(/#([a-zA-Z0-9_]+)/)) { // return; // } // sendEvent({ event: "nodeSelected", label, linkedData: data }); // evt.consume(); // } // }); // function getLabelTextOfCell(cell: any): string { // const labelHtml = graph.getLabel(cell); // const el = document.createElement("html"); // el.innerHTML = labelHtml; // label can be html // return el.innerText; // } // const selectionModel = graph.getSelectionModel(); // selectionModel.addListener(mxEvent.CHANGE, (sender: any, evt: any) => { // // selection has changed // const cells = selectionModel.cells; // if (cells.length >= 1) { // const selectedCell = cells[0]; // activeCell = selectedCell; // (window as any).hediet_Cell = selectedCell; // } else { // activeCell = undefined; // } // }); // const prefix = "hedietLinkedDataV1"; // const flattener = new FlattenToDictionary({ // parser: new ConservativeFlattenedEntryParser({ // prefix, // separator: "_", // }), // }); // function getLinkedData(cell: { value: unknown }) { // if (!mxUtils.isNode(cell.value)) { // return undefined; // } // const kvs = [...(cell.value.attributes as any)] // .filter((a) => a.name.startsWith(prefix)) // .map((a) => [a.name, a.value]); // if (kvs.length === 0) { // return undefined; // } // const r: Record<string, string> = {}; // for (const [k, v] of kvs) { // r[k] = v; // } // return flattener.unflatten(r); // } // function setLinkedData(cell: any, linkedData: JSONValue) { // let newNode: HTMLElement; // if (!mxUtils.isNode(cell.value)) { // const doc = mxUtils.createXmlDocument(); // const obj = doc.createElement("object"); // obj.setAttribute("label", cell.value || ""); // newNode = obj; // } else { // newNode = cell.value.cloneNode(true); // } // for (const a of [ // ...((newNode.attributes as any) as { name: string }[]), // ]) { // if (a.name.startsWith(prefix)) { // newNode.attributes.removeNamedItem(a.name); // } // } // const kvp = flattener.flatten(linkedData); // for (const [k, v] of Object.entries(kvp)) { // newNode.setAttribute(k, v); // } // // don't use cell.setValue as it does not trigger a change // model.setValue(cell, newNode); // } // window.addEventListener("message", (evt) => { // if (evt.source !== window.opener) { // return; // } // console.log(evt); // const data = JSON.parse(evt.data) as CustomDrawioAction; // switch (data.action) { // case "setNodeSelectionEnabled": { // nodeSelectionEnabled = data.enabled; // break; // } // case "linkSelectedNodeWithData": { // if (activeCell !== undefined) { // log("Set linkedData to " + data.linkedData); // graph.model.beginUpdate(); // try { // setLinkedData(activeCell, data.linkedData); // } finally { // graph.model.endUpdate(); // } // highlight.highlight(graph.view.getState(activeCell)); // setTimeout(() => { // highlight.highlight(null); // }, 500); // } // break; // } // case "getVertices": { // const vertices = Object.values(graph.model.cells) // .filter((c) => graph.model.isVertex(c)) // .map((c: any) => ({ id: c.id, label: graph.getLabel(c) })); // sendEvent({ // event: "getVertices", // message: data, // vertices: vertices, // }); // break; // } // case "updateVertices": { // const vertices = data.verticesToUpdate; // graph.model.beginUpdate(); // try { // for (const v of vertices) { // const c = graph.model.cells[v.id]; // if (!c) { // log(`Unknown cell "${v.id}"!`); // continue; // } // if (graph.getLabel(c) !== v.label) { // graph.model.setValue(c, v.label); // } // } // } finally { // graph.model.endUpdate(); // } // break; // } // case "addVertices": { // // why is this called twice? // log("add vertices is being called"); // const vertices = data.vertices; // graph.model.beginUpdate(); // try { // let i = 0; // for (const v of vertices) { // graph.insertVertex( // undefined, // null, // v.label, // i * 120, // 0, // 100, // 50, // "rectangle" // ); // i++; // } // } finally { // graph.model.endUpdate(); // } // break; // } // default: { // return; // } // } // evt.preventDefault(); // evt.stopPropagation(); // }); // });
the_stack
module android.support.v4.widget { import MotionEvent = android.view.MotionEvent; import VelocityTracker = android.view.VelocityTracker; import View = android.view.View; import ViewConfiguration = android.view.ViewConfiguration; import ViewGroup = android.view.ViewGroup; import OverScroller = android.widget.OverScroller; import Interpolator = android.view.animation.Interpolator; import System = java.lang.System; import Runnable = java.lang.Runnable; /** * ViewDragHelper is a utility class for writing custom ViewGroups. It offers a number * of useful operations and state tracking for allowing a user to drag and reposition * views within their parent ViewGroup. */ export class ViewDragHelper { private static TAG:string = "ViewDragHelper"; /** * A null/invalid pointer ID. */ static INVALID_POINTER:number = -1; /** * A view is not currently being dragged or animating as a result of a fling/snap. */ static STATE_IDLE:number = 0; /** * A view is currently being dragged. The position is currently changing as a result * of user input or simulated user input. */ static STATE_DRAGGING:number = 1; /** * A view is currently settling into place as a result of a fling or * predefined non-interactive motion. */ static STATE_SETTLING:number = 2; /** * Edge flag indicating that the left edge should be affected. */ static EDGE_LEFT:number = 1 << 0; /** * Edge flag indicating that the right edge should be affected. */ static EDGE_RIGHT:number = 1 << 1; /** * Edge flag indicating that the top edge should be affected. */ static EDGE_TOP:number = 1 << 2; /** * Edge flag indicating that the bottom edge should be affected. */ static EDGE_BOTTOM:number = 1 << 3; /** * Edge flag set indicating all edges should be affected. */ static EDGE_ALL:number = ViewDragHelper.EDGE_LEFT | ViewDragHelper.EDGE_TOP | ViewDragHelper.EDGE_RIGHT | ViewDragHelper.EDGE_BOTTOM; /** * Indicates that a check should occur along the horizontal axis */ static DIRECTION_HORIZONTAL:number = 1 << 0; /** * Indicates that a check should occur along the vertical axis */ static DIRECTION_VERTICAL:number = 1 << 1; /** * Indicates that a check should occur along all axes */ static DIRECTION_ALL:number = ViewDragHelper.DIRECTION_HORIZONTAL | ViewDragHelper.DIRECTION_VERTICAL; // dp private static EDGE_SIZE:number = 20; // ms private static BASE_SETTLE_DURATION:number = 256; // ms private static MAX_SETTLE_DURATION:number = 600; // Current drag state; idle, dragging or settling private mDragState:number = 0; // Distance to travel before a drag may begin private mTouchSlop:number = 0; // Last known position/pointer tracking private mActivePointerId:number = ViewDragHelper.INVALID_POINTER; private mInitialMotionX:number[]; private mInitialMotionY:number[]; private mLastMotionX:number[]; private mLastMotionY:number[]; private mInitialEdgesTouched:number[]; private mEdgeDragsInProgress:number[]; private mEdgeDragsLocked:number[]; private mPointersDown:number = 0; private mVelocityTracker:VelocityTracker; private mMaxVelocity:number = 0; private mMinVelocity:number = 0; private mEdgeSize:number = 0; private mTrackingEdges:number = 0; private mScroller:OverScroller; private mCallback:ViewDragHelper.Callback; private mCapturedView:View; private mReleaseInProgress:boolean; private mParentView:ViewGroup; /** * Interpolator defining the animation curve for mScroller */ private static sInterpolator:Interpolator = (()=>{ class _Inner implements Interpolator { getInterpolation(t:number):number { t -= 1.0; return t * t * t * t * t + 1.0; } } return new _Inner(); })(); private mSetIdleRunnable:Runnable = (()=>{ const inner_this=this; class _Inner implements Runnable { run():void { inner_this.setDragState(ViewDragHelper.STATE_IDLE); } } return new _Inner(); })(); /** * Factory method to create a new ViewDragHelper. * * @param forParent Parent view to monitor * @param cb Callback to provide information and receive events * @param sensitivity Multiplier for how sensitive the helper should be about detecting * the start of a drag. Larger values are more sensitive. 1.0f is normal. * @return a new ViewDragHelper instance */ static create(forParent:ViewGroup, cb:ViewDragHelper.Callback):ViewDragHelper; static create(forParent:ViewGroup, sensitivity:number, cb:ViewDragHelper.Callback):ViewDragHelper; static create(...args):ViewDragHelper { if(args.length===2) return new ViewDragHelper(args[0], args[1]); else if(args.length===3){ let [forParent, sensitivity, cb] = args; const helper:ViewDragHelper = ViewDragHelper.create(forParent, cb); helper.mTouchSlop = Math.floor((helper.mTouchSlop * (1 / sensitivity))); return helper; } } /** * Apps should use ViewDragHelper.create() to get a new instance. * This will allow VDH to use internal compatibility implementations for different * platform versions. * * @param forParent Parent view to monitor * @param cb Callback to provide information and receive events */ constructor(forParent:ViewGroup, cb:ViewDragHelper.Callback) { if (forParent == null) { throw Error(`new IllegalArgumentException("Parent view may not be null")`); } if (cb == null) { throw Error(`new IllegalArgumentException("Callback may not be null")`); } this.mParentView = forParent; this.mCallback = cb; const vc:ViewConfiguration = ViewConfiguration.get(); const density:number = android.content.res.Resources.getDisplayMetrics().density; this.mEdgeSize = Math.floor((ViewDragHelper.EDGE_SIZE * density + 0.5)); this.mTouchSlop = vc.getScaledTouchSlop(); this.mMaxVelocity = vc.getScaledMaximumFlingVelocity(); this.mMinVelocity = vc.getScaledMinimumFlingVelocity(); this.mScroller = new OverScroller(ViewDragHelper.sInterpolator); } /** * Set the minimum velocity that will be detected as having a magnitude greater than zero * in pixels per second. Callback methods accepting a velocity will be clamped appropriately. * * @param minVel Minimum velocity to detect */ setMinVelocity(minVel:number):void { this.mMinVelocity = minVel; } /** * Return the currently configured minimum velocity. Any flings with a magnitude less * than this value in pixels per second. Callback methods accepting a velocity will receive * zero as a velocity value if the real detected velocity was below this threshold. * * @return the minimum velocity that will be detected */ getMinVelocity():number { return this.mMinVelocity; } /** * Retrieve the current drag state of this helper. This will return one of * {@link #STATE_IDLE}, {@link #STATE_DRAGGING} or {@link #STATE_SETTLING}. * @return The current drag state */ getViewDragState():number { return this.mDragState; } /** * Enable edge tracking for the selected edges of the parent view. * The callback's {@link Callback#onEdgeTouched(int, int)} and * {@link Callback#onEdgeDragStarted(int, int)} methods will only be invoked * for edges for which edge tracking has been enabled. * * @param edgeFlags Combination of edge flags describing the edges to watch * @see #EDGE_LEFT * @see #EDGE_TOP * @see #EDGE_RIGHT * @see #EDGE_BOTTOM */ setEdgeTrackingEnabled(edgeFlags:number):void { this.mTrackingEdges = edgeFlags; } /** * Return the size of an edge. This is the range in pixels along the edges of this view * that will actively detect edge touches or drags if edge tracking is enabled. * * @return The size of an edge in pixels * @see #setEdgeTrackingEnabled(int) */ getEdgeSize():number { return this.mEdgeSize; } /** * Capture a specific child view for dragging within the parent. The callback will be notified * but {@link Callback#tryCaptureView(android.view.View, int)} will not be asked permission to * capture this view. * * @param childView Child view to capture * @param activePointerId ID of the pointer that is dragging the captured child view */ captureChildView(childView:View, activePointerId:number):void { if (childView.getParent() != this.mParentView) { throw Error(`new IllegalArgumentException("captureChildView: parameter must be a descendant " + "of the ViewDragHelper's tracked parent view (" + this.mParentView + ")")`); } this.mCapturedView = childView; this.mActivePointerId = activePointerId; this.mCallback.onViewCaptured(childView, activePointerId); this.setDragState(ViewDragHelper.STATE_DRAGGING); } /** * @return The currently captured view, or null if no view has been captured. */ getCapturedView():View { return this.mCapturedView; } /** * @return The ID of the pointer currently dragging the captured view, * or {@link #INVALID_POINTER}. */ getActivePointerId():number { return this.mActivePointerId; } /** * @return The minimum distance in pixels that the user must travel to initiate a drag */ getTouchSlop():number { return this.mTouchSlop; } /** * The result of a call to this method is equivalent to * {@link #processTouchEvent(android.view.MotionEvent)} receiving an ACTION_CANCEL event. */ cancel():void { this.mActivePointerId = ViewDragHelper.INVALID_POINTER; this.clearMotionHistory(); if (this.mVelocityTracker != null) { this.mVelocityTracker.recycle(); this.mVelocityTracker = null; } } /** * {@link #cancel()}, but also abort all motion in progress and snap to the end of any * animation. */ abort():void { this.cancel(); if (this.mDragState == ViewDragHelper.STATE_SETTLING) { const oldX:number = this.mScroller.getCurrX(); const oldY:number = this.mScroller.getCurrY(); this.mScroller.abortAnimation(); const newX:number = this.mScroller.getCurrX(); const newY:number = this.mScroller.getCurrY(); this.mCallback.onViewPositionChanged(this.mCapturedView, newX, newY, newX - oldX, newY - oldY); } this.setDragState(ViewDragHelper.STATE_IDLE); } /** * Animate the view <code>child</code> to the given (left, top) position. * If this method returns true, the caller should invoke {@link #continueSettling(boolean)} * on each subsequent frame to continue the motion until it returns false. If this method * returns false there is no further work to do to complete the movement. * * <p>This operation does not count as a capture event, though {@link #getCapturedView()} * will still report the sliding view while the slide is in progress.</p> * * @param child Child view to capture and animate * @param finalLeft Final left position of child * @param finalTop Final top position of child * @return true if animation should continue through {@link #continueSettling(boolean)} calls */ smoothSlideViewTo(child:View, finalLeft:number, finalTop:number):boolean { this.mCapturedView = child; this.mActivePointerId = ViewDragHelper.INVALID_POINTER; return this.forceSettleCapturedViewAt(finalLeft, finalTop, 0, 0); } /** * Settle the captured view at the given (left, top) position. * The appropriate velocity from prior motion will be taken into account. * If this method returns true, the caller should invoke {@link #continueSettling(boolean)} * on each subsequent frame to continue the motion until it returns false. If this method * returns false there is no further work to do to complete the movement. * * @param finalLeft Settled left edge position for the captured view * @param finalTop Settled top edge position for the captured view * @return true if animation should continue through {@link #continueSettling(boolean)} calls */ settleCapturedViewAt(finalLeft:number, finalTop:number):boolean { if (!this.mReleaseInProgress) { throw Error(`new IllegalStateException("Cannot settleCapturedViewAt outside of a call to " + "Callback#onViewReleased")`); } return this.forceSettleCapturedViewAt(finalLeft, finalTop, Math.floor(this.mVelocityTracker.getXVelocity(this.mActivePointerId)), Math.floor(this.mVelocityTracker.getYVelocity(this.mActivePointerId))); } /** * Settle the captured view at the given (left, top) position. * * @param finalLeft Target left position for the captured view * @param finalTop Target top position for the captured view * @param xvel Horizontal velocity * @param yvel Vertical velocity * @return true if animation should continue through {@link #continueSettling(boolean)} calls */ private forceSettleCapturedViewAt(finalLeft:number, finalTop:number, xvel:number, yvel:number):boolean { const startLeft:number = this.mCapturedView.getLeft(); const startTop:number = this.mCapturedView.getTop(); const dx:number = finalLeft - startLeft; const dy:number = finalTop - startTop; if (dx == 0 && dy == 0) { // Nothing to do. Send callbacks, be done. this.mScroller.abortAnimation(); this.setDragState(ViewDragHelper.STATE_IDLE); return false; } const duration:number = this.computeSettleDuration(this.mCapturedView, dx, dy, xvel, yvel); this.mScroller.startScroll(startLeft, startTop, dx, dy, duration); this.setDragState(ViewDragHelper.STATE_SETTLING); return true; } private computeSettleDuration(child:View, dx:number, dy:number, xvel:number, yvel:number):number { xvel = this.clampMag(xvel, Math.floor(this.mMinVelocity), Math.floor(this.mMaxVelocity)); yvel = this.clampMag(yvel, Math.floor(this.mMinVelocity), Math.floor(this.mMaxVelocity)); const absDx:number = Math.abs(dx); const absDy:number = Math.abs(dy); const absXVel:number = Math.abs(xvel); const absYVel:number = Math.abs(yvel); const addedVel:number = absXVel + absYVel; const addedDistance:number = absDx + absDy; const xweight:number = xvel != 0 ? <number> absXVel / addedVel : <number> absDx / addedDistance; const yweight:number = yvel != 0 ? <number> absYVel / addedVel : <number> absDy / addedDistance; let xduration:number = this.computeAxisDuration(dx, xvel, this.mCallback.getViewHorizontalDragRange(child)); let yduration:number = this.computeAxisDuration(dy, yvel, this.mCallback.getViewVerticalDragRange(child)); return Math.floor((xduration * xweight + yduration * yweight)); } private computeAxisDuration(delta:number, velocity:number, motionRange:number):number { if (delta == 0) { return 0; } const width:number = this.mParentView.getWidth(); const halfWidth:number = width / 2; const distanceRatio:number = Math.min(1, <number> Math.abs(delta) / width); const distance:number = halfWidth + halfWidth * this.distanceInfluenceForSnapDuration(distanceRatio); let duration:number; velocity = Math.abs(velocity); if (velocity > 0) { duration = 4 * Math.round(1000 * Math.abs(distance / velocity)); } else { const range:number = <number> Math.abs(delta) / motionRange; duration = Math.floor(((range + 1) * ViewDragHelper.BASE_SETTLE_DURATION)); } return Math.min(duration, ViewDragHelper.MAX_SETTLE_DURATION); } /** * Clamp the magnitude of value for absMin and absMax. * If the value is below the minimum, it will be clamped to zero. * If the value is above the maximum, it will be clamped to the maximum. * * @param value Value to clamp * @param absMin Absolute value of the minimum significant value to return * @param absMax Absolute value of the maximum value to return * @return The clamped value with the same sign as <code>value</code> */ private clampMag(value:number, absMin:number, absMax:number):number { const absValue:number = Math.abs(value); if (absValue < absMin) return 0; if (absValue > absMax) return value > 0 ? absMax : -absMax; return value; } private distanceInfluenceForSnapDuration(f:number):number { // center the values about 0. f -= 0.5; f *= 0.3 * Math.PI / 2.0; return <number> Math.sin(f); } /** * Settle the captured view based on standard free-moving fling behavior. * The caller should invoke {@link #continueSettling(boolean)} on each subsequent frame * to continue the motion until it returns false. * * @param minLeft Minimum X position for the view's left edge * @param minTop Minimum Y position for the view's top edge * @param maxLeft Maximum X position for the view's left edge * @param maxTop Maximum Y position for the view's top edge */ flingCapturedView(minLeft:number, minTop:number, maxLeft:number, maxTop:number):void { if (!this.mReleaseInProgress) { throw Error(`new IllegalStateException("Cannot flingCapturedView outside of a call to " + "Callback#onViewReleased")`); } this.mScroller.fling(this.mCapturedView.getLeft(), this.mCapturedView.getTop(), Math.floor(this.mVelocityTracker.getXVelocity(this.mActivePointerId)), Math.floor(this.mVelocityTracker.getYVelocity(this.mActivePointerId)), minLeft, maxLeft, minTop, maxTop); this.setDragState(ViewDragHelper.STATE_SETTLING); } /** * Move the captured settling view by the appropriate amount for the current time. * If <code>continueSettling</code> returns true, the caller should call it again * on the next frame to continue. * * @param deferCallbacks true if state callbacks should be deferred via posted message. * Set this to true if you are calling this method from * {@link android.view.View#computeScroll()} or similar methods * invoked as part of layout or drawing. * @return true if settle is still in progress */ continueSettling(deferCallbacks:boolean):boolean { if (this.mDragState == ViewDragHelper.STATE_SETTLING) { let keepGoing:boolean = this.mScroller.computeScrollOffset(); const x:number = this.mScroller.getCurrX(); const y:number = this.mScroller.getCurrY(); const dx:number = x - this.mCapturedView.getLeft(); const dy:number = y - this.mCapturedView.getTop(); if (dx != 0) { this.mCapturedView.offsetLeftAndRight(dx); } if (dy != 0) { this.mCapturedView.offsetTopAndBottom(dy); } if (dx != 0 || dy != 0) { this.mCallback.onViewPositionChanged(this.mCapturedView, x, y, dx, dy); } if (keepGoing && x == this.mScroller.getFinalX() && y == this.mScroller.getFinalY()) { // Close enough. The interpolator/scroller might think we're still moving // but the user sure doesn't. this.mScroller.abortAnimation(); keepGoing = this.mScroller.isFinished(); } if (!keepGoing) { if (deferCallbacks) { this.mParentView.post(this.mSetIdleRunnable); } else { this.setDragState(ViewDragHelper.STATE_IDLE); } } } return this.mDragState == ViewDragHelper.STATE_SETTLING; } /** * Like all callback events this must happen on the UI thread, but release * involves some extra semantics. During a release (mReleaseInProgress) * is the only time it is valid to call {@link #settleCapturedViewAt(int, int)} * or {@link #flingCapturedView(int, int, int, int)}. */ private dispatchViewReleased(xvel:number, yvel:number):void { this.mReleaseInProgress = true; this.mCallback.onViewReleased(this.mCapturedView, xvel, yvel); this.mReleaseInProgress = false; if (this.mDragState == ViewDragHelper.STATE_DRAGGING) { // onViewReleased didn't call a method that would have changed this. Go idle. this.setDragState(ViewDragHelper.STATE_IDLE); } } private clearMotionHistory(pointerId?:number):void { if (this.mInitialMotionX == null) { return; } if(pointerId==null){ this.mInitialMotionX = []; this.mInitialMotionY = []; this.mLastMotionX = []; this.mLastMotionY = []; this.mInitialEdgesTouched = []; this.mEdgeDragsInProgress = []; this.mEdgeDragsLocked = []; //for(let i=0,count=this.mInitialMotionX.length; i<count; i++) this.mInitialMotionX[i] = 0; //for(let i=0,count=this.mInitialMotionY.length; i<count; i++) this.mInitialMotionY[i] = 0; //for(let i=0,count=this.mLastMotionX.length; i<count; i++) this.mLastMotionX[i] = 0; //for(let i=0,count=this.mLastMotionY.length; i<count; i++) this.mLastMotionY[i] = 0; //for(let i=0,count=this.mInitialEdgesTouched.length; i<count; i++) this.mInitialEdgesTouched[i] = 0; //for(let i=0,count=this.mEdgeDragsInProgress.length; i<count; i++) this.mEdgeDragsInProgress[i] = 0; //for(let i=0,count=this.mEdgeDragsLocked.length; i<count; i++) this.mEdgeDragsLocked[i] = 0; this.mPointersDown = 0; }else { this.mInitialMotionX[pointerId] = 0; this.mInitialMotionY[pointerId] = 0; this.mLastMotionX[pointerId] = 0; this.mLastMotionY[pointerId] = 0; this.mInitialEdgesTouched[pointerId] = 0; this.mEdgeDragsInProgress[pointerId] = 0; this.mEdgeDragsLocked[pointerId] = 0; this.mPointersDown &= ~(1 << pointerId); } } private ensureMotionHistorySizeForId(pointerId:number):void { if (this.mInitialMotionX == null || this.mInitialMotionX.length <= pointerId) { let imx:number[] = androidui.util.ArrayCreator.newNumberArray(pointerId + 1); let imy:number[] = androidui.util.ArrayCreator.newNumberArray(pointerId + 1); let lmx:number[] = androidui.util.ArrayCreator.newNumberArray(pointerId + 1); let lmy:number[] = androidui.util.ArrayCreator.newNumberArray(pointerId + 1); let iit:number[] = androidui.util.ArrayCreator.newNumberArray(pointerId + 1); let edip:number[] = androidui.util.ArrayCreator.newNumberArray(pointerId + 1); let edl:number[] = androidui.util.ArrayCreator.newNumberArray(pointerId + 1); if (this.mInitialMotionX != null) { System.arraycopy(this.mInitialMotionX, 0, imx, 0, this.mInitialMotionX.length); System.arraycopy(this.mInitialMotionY, 0, imy, 0, this.mInitialMotionY.length); System.arraycopy(this.mLastMotionX, 0, lmx, 0, this.mLastMotionX.length); System.arraycopy(this.mLastMotionY, 0, lmy, 0, this.mLastMotionY.length); System.arraycopy(this.mInitialEdgesTouched, 0, iit, 0, this.mInitialEdgesTouched.length); System.arraycopy(this.mEdgeDragsInProgress, 0, edip, 0, this.mEdgeDragsInProgress.length); System.arraycopy(this.mEdgeDragsLocked, 0, edl, 0, this.mEdgeDragsLocked.length); } this.mInitialMotionX = imx; this.mInitialMotionY = imy; this.mLastMotionX = lmx; this.mLastMotionY = lmy; this.mInitialEdgesTouched = iit; this.mEdgeDragsInProgress = edip; this.mEdgeDragsLocked = edl; } } private saveInitialMotion(x:number, y:number, pointerId:number):void { this.ensureMotionHistorySizeForId(pointerId); this.mInitialMotionX[pointerId] = this.mLastMotionX[pointerId] = x; this.mInitialMotionY[pointerId] = this.mLastMotionY[pointerId] = y; this.mInitialEdgesTouched[pointerId] = this.getEdgesTouched(Math.floor(x), Math.floor(y)); this.mPointersDown |= 1 << pointerId; } private saveLastMotion(ev:MotionEvent):void { const pointerCount:number = ev.getPointerCount(); for (let i:number = 0; i < pointerCount; i++) { const pointerId:number = ev.getPointerId(i); const x:number = ev.getX(i); const y:number = ev.getY(i); this.mLastMotionX[pointerId] = x; this.mLastMotionY[pointerId] = y; } } /** * Check if the given pointer ID represents a pointer that is currently down (to the best * of the ViewDragHelper's knowledge). * * <p>The state used to report this information is populated by the methods * {@link #shouldInterceptTouchEvent(android.view.MotionEvent)} or * {@link #processTouchEvent(android.view.MotionEvent)}. If one of these methods has not * been called for all relevant MotionEvents to track, the information reported * by this method may be stale or incorrect.</p> * * @param pointerId pointer ID to check; corresponds to IDs provided by MotionEvent * @return true if the pointer with the given ID is still down */ isPointerDown(pointerId:number):boolean { return (this.mPointersDown & 1 << pointerId) != 0; } setDragState(state:number):void { if (this.mDragState != state) { this.mDragState = state; this.mCallback.onViewDragStateChanged(state); if (state == ViewDragHelper.STATE_IDLE) { this.mCapturedView = null; } } } /** * Attempt to capture the view with the given pointer ID. The callback will be involved. * This will put us into the "dragging" state. If we've already captured this view with * this pointer this method will immediately return true without consulting the callback. * * @param toCapture View to capture * @param pointerId Pointer to capture with * @return true if capture was successful */ tryCaptureViewForDrag(toCapture:View, pointerId:number):boolean { if (toCapture == this.mCapturedView && this.mActivePointerId == pointerId) { // Already done! return true; } if (toCapture != null && this.mCallback.tryCaptureView(toCapture, pointerId)) { this.mActivePointerId = pointerId; this.captureChildView(toCapture, pointerId); return true; } return false; } /** * Tests scrollability within child views of v given a delta of dx. * * @param v View to test for horizontal scrollability * @param checkV Whether the view v passed should itself be checked for scrollability (true), * or just its children (false). * @param dx Delta scrolled in pixels along the X axis * @param dy Delta scrolled in pixels along the Y axis * @param x X coordinate of the active touch point * @param y Y coordinate of the active touch point * @return true if child views of v can be scrolled by delta of dx. */ protected canScroll(v:View, checkV:boolean, dx:number, dy:number, x:number, y:number):boolean { if (v instanceof ViewGroup) { const group:ViewGroup = <ViewGroup> v; const scrollX:number = v.getScrollX(); const scrollY:number = v.getScrollY(); const count:number = group.getChildCount(); // Count backwards - let topmost views consume scroll distance first. for (let i:number = count - 1; i >= 0; i--) { // TODO: Add versioned support here for transformed views. // This will not work for transformed views in Honeycomb+ const child:View = group.getChildAt(i); if (x + scrollX >= child.getLeft() && x + scrollX < child.getRight() && y + scrollY >= child.getTop() && y + scrollY < child.getBottom() && this.canScroll(child, true, dx, dy, x + scrollX - child.getLeft(), y + scrollY - child.getTop())) { return true; } } } return checkV && (v.canScrollHorizontally(-dx) || v.canScrollVertically(-dy)); } /** * Check if this event as provided to the parent view's onInterceptTouchEvent should * cause the parent to intercept the touch event stream. * * @param ev MotionEvent provided to onInterceptTouchEvent * @return true if the parent view should return true from onInterceptTouchEvent */ shouldInterceptTouchEvent(ev:MotionEvent):boolean { const action:number = ev.getActionMasked(); const actionIndex:number = ev.getActionIndex(); if (action == MotionEvent.ACTION_DOWN) { // Reset things for a new event stream, just in case we didn't get // the whole previous stream. this.cancel(); } if (this.mVelocityTracker == null) { this.mVelocityTracker = VelocityTracker.obtain(); } this.mVelocityTracker.addMovement(ev); switch(action) { case MotionEvent.ACTION_DOWN: { const x:number = ev.getX(); const y:number = ev.getY(); const pointerId:number = ev.getPointerId(0); this.saveInitialMotion(x, y, pointerId); const toCapture:View = this.findTopChildUnder(Math.floor(x), Math.floor(y)); // Catch a settling view if possible. if (toCapture == this.mCapturedView && this.mDragState == ViewDragHelper.STATE_SETTLING) { this.tryCaptureViewForDrag(toCapture, pointerId); } const edgesTouched:number = this.mInitialEdgesTouched[pointerId]; if ((edgesTouched & this.mTrackingEdges) != 0) { this.mCallback.onEdgeTouched(edgesTouched & this.mTrackingEdges, pointerId); } break; } case MotionEvent.ACTION_POINTER_DOWN: { const pointerId:number = ev.getPointerId(actionIndex); const x:number = ev.getX(actionIndex); const y:number = ev.getY(actionIndex); this.saveInitialMotion(x, y, pointerId); // A ViewDragHelper can only manipulate one view at a time. if (this.mDragState == ViewDragHelper.STATE_IDLE) { const edgesTouched:number = this.mInitialEdgesTouched[pointerId]; if ((edgesTouched & this.mTrackingEdges) != 0) { this.mCallback.onEdgeTouched(edgesTouched & this.mTrackingEdges, pointerId); } } else if (this.mDragState == ViewDragHelper.STATE_SETTLING) { // Catch a settling view if possible. const toCapture:View = this.findTopChildUnder(Math.floor(x), Math.floor(y)); if (toCapture == this.mCapturedView) { this.tryCaptureViewForDrag(toCapture, pointerId); } } break; } case MotionEvent.ACTION_MOVE: { // First to cross a touch slop over a draggable view wins. Also report edge drags. const pointerCount:number = ev.getPointerCount(); for (let i:number = 0; i < pointerCount; i++) { const pointerId:number = ev.getPointerId(i); const x:number = ev.getX(i); const y:number = ev.getY(i); const dx:number = x - this.mInitialMotionX[pointerId]; const dy:number = y - this.mInitialMotionY[pointerId]; this.reportNewEdgeDrags(dx, dy, pointerId); if (this.mDragState == ViewDragHelper.STATE_DRAGGING) { // Callback might have started an edge drag break; } const toCapture:View = this.findTopChildUnder(Math.floor(x), Math.floor(y)); if (toCapture != null && this.checkTouchSlop(toCapture, dx, dy) && this.tryCaptureViewForDrag(toCapture, pointerId)) { break; } } this.saveLastMotion(ev); break; } case MotionEvent.ACTION_POINTER_UP: { const pointerId:number = ev.getPointerId(actionIndex); this.clearMotionHistory(pointerId); break; } case MotionEvent.ACTION_UP: case MotionEvent.ACTION_CANCEL: { this.cancel(); break; } } return this.mDragState == ViewDragHelper.STATE_DRAGGING; } /** * Process a touch event received by the parent view. This method will dispatch callback events * as needed before returning. The parent view's onTouchEvent implementation should call this. * * @param ev The touch event received by the parent view */ processTouchEvent(ev:MotionEvent):void { const action:number = ev.getActionMasked(); const actionIndex:number = ev.getActionIndex(); if (action == MotionEvent.ACTION_DOWN) { // Reset things for a new event stream, just in case we didn't get // the whole previous stream. this.cancel(); } if (this.mVelocityTracker == null) { this.mVelocityTracker = VelocityTracker.obtain(); } this.mVelocityTracker.addMovement(ev); switch(action) { case MotionEvent.ACTION_DOWN: { const x:number = ev.getX(); const y:number = ev.getY(); const pointerId:number = ev.getPointerId(0); const toCapture:View = this.findTopChildUnder(Math.floor(x), Math.floor(y)); this.saveInitialMotion(x, y, pointerId); // Since the parent is already directly processing this touch event, // there is no reason to delay for a slop before dragging. // Start immediately if possible. this.tryCaptureViewForDrag(toCapture, pointerId); const edgesTouched:number = this.mInitialEdgesTouched[pointerId]; if ((edgesTouched & this.mTrackingEdges) != 0) { this.mCallback.onEdgeTouched(edgesTouched & this.mTrackingEdges, pointerId); } break; } case MotionEvent.ACTION_POINTER_DOWN: { const pointerId:number = ev.getPointerId(actionIndex); const x:number = ev.getX(actionIndex); const y:number = ev.getY(actionIndex); this.saveInitialMotion(x, y, pointerId); // A ViewDragHelper can only manipulate one view at a time. if (this.mDragState == ViewDragHelper.STATE_IDLE) { // If we're idle we can do anything! Treat it like a normal down event. const toCapture:View = this.findTopChildUnder(Math.floor(x), Math.floor(y)); this.tryCaptureViewForDrag(toCapture, pointerId); const edgesTouched:number = this.mInitialEdgesTouched[pointerId]; if ((edgesTouched & this.mTrackingEdges) != 0) { this.mCallback.onEdgeTouched(edgesTouched & this.mTrackingEdges, pointerId); } } else if (this.isCapturedViewUnder(Math.floor(x), Math.floor(y))) { // We're still tracking a captured view. If the same view is under this // point, we'll swap to controlling it with this pointer instead. // (This will still work if we're "catching" a settling view.) this.tryCaptureViewForDrag(this.mCapturedView, pointerId); } break; } case MotionEvent.ACTION_MOVE: { if (this.mDragState == ViewDragHelper.STATE_DRAGGING) { const index:number = ev.findPointerIndex(this.mActivePointerId); const x:number = ev.getX(index); const y:number = ev.getY(index); const idx:number = Math.floor((x - this.mLastMotionX[this.mActivePointerId])); const idy:number = Math.floor((y - this.mLastMotionY[this.mActivePointerId])); this.dragTo(this.mCapturedView.getLeft() + idx, this.mCapturedView.getTop() + idy, idx, idy); this.saveLastMotion(ev); } else { // Check to see if any pointer is now over a draggable view. const pointerCount:number = ev.getPointerCount(); for (let i:number = 0; i < pointerCount; i++) { const pointerId:number = ev.getPointerId(i); const x:number = ev.getX(i); const y:number = ev.getY(i); const dx:number = x - this.mInitialMotionX[pointerId]; const dy:number = y - this.mInitialMotionY[pointerId]; this.reportNewEdgeDrags(dx, dy, pointerId); if (this.mDragState == ViewDragHelper.STATE_DRAGGING) { // Callback might have started an edge drag. break; } const toCapture:View = this.findTopChildUnder(Math.floor(x), Math.floor(y)); if (this.checkTouchSlop(toCapture, dx, dy) && this.tryCaptureViewForDrag(toCapture, pointerId)) { break; } } this.saveLastMotion(ev); } break; } case MotionEvent.ACTION_POINTER_UP: { const pointerId:number = ev.getPointerId(actionIndex); if (this.mDragState == ViewDragHelper.STATE_DRAGGING && pointerId == this.mActivePointerId) { // Try to find another pointer that's still holding on to the captured view. let newActivePointer:number = ViewDragHelper.INVALID_POINTER; const pointerCount:number = ev.getPointerCount(); for (let i:number = 0; i < pointerCount; i++) { const id:number = ev.getPointerId(i); if (id == this.mActivePointerId) { // This one's going away, skip. continue; } const x:number = ev.getX(i); const y:number = ev.getY(i); if (this.findTopChildUnder(Math.floor(x), Math.floor(y)) == this.mCapturedView && this.tryCaptureViewForDrag(this.mCapturedView, id)) { newActivePointer = this.mActivePointerId; break; } } if (newActivePointer == ViewDragHelper.INVALID_POINTER) { // We didn't find another pointer still touching the view, release it. this.releaseViewForPointerUp(); } } this.clearMotionHistory(pointerId); break; } case MotionEvent.ACTION_UP: { if (this.mDragState == ViewDragHelper.STATE_DRAGGING) { this.releaseViewForPointerUp(); } this.cancel(); break; } case MotionEvent.ACTION_CANCEL: { if (this.mDragState == ViewDragHelper.STATE_DRAGGING) { this.dispatchViewReleased(0, 0); } this.cancel(); break; } } } private reportNewEdgeDrags(dx:number, dy:number, pointerId:number):void { let dragsStarted:number = 0; if (this.checkNewEdgeDrag(dx, dy, pointerId, ViewDragHelper.EDGE_LEFT)) { dragsStarted |= ViewDragHelper.EDGE_LEFT; } if (this.checkNewEdgeDrag(dy, dx, pointerId, ViewDragHelper.EDGE_TOP)) { dragsStarted |= ViewDragHelper.EDGE_TOP; } if (this.checkNewEdgeDrag(dx, dy, pointerId, ViewDragHelper.EDGE_RIGHT)) { dragsStarted |= ViewDragHelper.EDGE_RIGHT; } if (this.checkNewEdgeDrag(dy, dx, pointerId, ViewDragHelper.EDGE_BOTTOM)) { dragsStarted |= ViewDragHelper.EDGE_BOTTOM; } if (dragsStarted != 0) { this.mEdgeDragsInProgress[pointerId] |= dragsStarted; this.mCallback.onEdgeDragStarted(dragsStarted, pointerId); } } private checkNewEdgeDrag(delta:number, odelta:number, pointerId:number, edge:number):boolean { const absDelta:number = Math.abs(delta); const absODelta:number = Math.abs(odelta); if ((this.mInitialEdgesTouched[pointerId] & edge) != edge || (this.mTrackingEdges & edge) == 0 || (this.mEdgeDragsLocked[pointerId] & edge) == edge || (this.mEdgeDragsInProgress[pointerId] & edge) == edge || (absDelta <= this.mTouchSlop && absODelta <= this.mTouchSlop)) { return false; } if (absDelta < absODelta * 0.5 && this.mCallback.onEdgeLock(edge)) { this.mEdgeDragsLocked[pointerId] |= edge; return false; } return (this.mEdgeDragsInProgress[pointerId] & edge) == 0 && absDelta > this.mTouchSlop; } checkTouchSlop(child:View, dx:number, dy:number):boolean; checkTouchSlop(directions:number):boolean; checkTouchSlop(directions:number, pointerId:number):boolean; checkTouchSlop(...args):boolean { if(args.length===1) return this._checkTouchSlop_1(args[0]); if(args.length===2) return this._checkTouchSlop_2(args[0], args[1]); if(args.length===3) return this._checkTouchSlop_3(args[0], args[1], args[2]); return false; } /** * Check if we've crossed a reasonable touch slop for the given child view. * If the child cannot be dragged along the horizontal or vertical axis, motion * along that axis will not count toward the slop check. * * @param child Child to check * @param dx Motion since initial position along X axis * @param dy Motion since initial position along Y axis * @return true if the touch slop has been crossed */ private _checkTouchSlop_3(child:View, dx:number, dy:number):boolean { if (child == null) { return false; } const checkHorizontal:boolean = this.mCallback.getViewHorizontalDragRange(child) > 0; const checkVertical:boolean = this.mCallback.getViewVerticalDragRange(child) > 0; if (checkHorizontal && checkVertical) { return dx * dx + dy * dy > this.mTouchSlop * this.mTouchSlop; } else if (checkHorizontal) { return Math.abs(dx) > this.mTouchSlop; } else if (checkVertical) { return Math.abs(dy) > this.mTouchSlop; } return false; } /** * Check if any pointer tracked in the current gesture has crossed * the required slop threshold. * * <p>This depends on internal state populated by * {@link #shouldInterceptTouchEvent(android.view.MotionEvent)} or * {@link #processTouchEvent(android.view.MotionEvent)}. You should only rely on * the results of this method after all currently available touch data * has been provided to one of these two methods.</p> * * @param directions Combination of direction flags, see {@link #DIRECTION_HORIZONTAL}, * {@link #DIRECTION_VERTICAL}, {@link #DIRECTION_ALL} * @return true if the slop threshold has been crossed, false otherwise */ private _checkTouchSlop_1(directions:number):boolean { const count:number = this.mInitialMotionX.length; for (let i:number = 0; i < count; i++) { if (this.checkTouchSlop(directions, i)) { return true; } } return false; } /** * Check if the specified pointer tracked in the current gesture has crossed * the required slop threshold. * * <p>This depends on internal state populated by * {@link #shouldInterceptTouchEvent(android.view.MotionEvent)} or * {@link #processTouchEvent(android.view.MotionEvent)}. You should only rely on * the results of this method after all currently available touch data * has been provided to one of these two methods.</p> * * @param directions Combination of direction flags, see {@link #DIRECTION_HORIZONTAL}, * {@link #DIRECTION_VERTICAL}, {@link #DIRECTION_ALL} * @param pointerId ID of the pointer to slop check as specified by MotionEvent * @return true if the slop threshold has been crossed, false otherwise */ private _checkTouchSlop_2(directions:number, pointerId:number):boolean { if (!this.isPointerDown(pointerId)) { return false; } const checkHorizontal:boolean = (directions & ViewDragHelper.DIRECTION_HORIZONTAL) == ViewDragHelper.DIRECTION_HORIZONTAL; const checkVertical:boolean = (directions & ViewDragHelper.DIRECTION_VERTICAL) == ViewDragHelper.DIRECTION_VERTICAL; const dx:number = this.mLastMotionX[pointerId] - this.mInitialMotionX[pointerId]; const dy:number = this.mLastMotionY[pointerId] - this.mInitialMotionY[pointerId]; if (checkHorizontal && checkVertical) { return dx * dx + dy * dy > this.mTouchSlop * this.mTouchSlop; } else if (checkHorizontal) { return Math.abs(dx) > this.mTouchSlop; } else if (checkVertical) { return Math.abs(dy) > this.mTouchSlop; } return false; } /** * Check if any of the edges specified were initially touched by the pointer with * the specified ID. If there is no currently active gesture or if there is no pointer with * the given ID currently down this method will return false. * * @param edges Edges to check for an initial edge touch. See {@link #EDGE_LEFT}, * {@link #EDGE_TOP}, {@link #EDGE_RIGHT}, {@link #EDGE_BOTTOM} and * {@link #EDGE_ALL} * @return true if any of the edges specified were initially touched in the current gesture */ isEdgeTouched(edges:number, pointerId?:number):boolean { if(pointerId==null) { const count:number = this.mInitialEdgesTouched.length; for (let i:number = 0; i < count; i++) { if (this.isEdgeTouched(edges, i)) { return true; } } } return this.isPointerDown(pointerId) && (this.mInitialEdgesTouched[pointerId] & edges) != 0; } private releaseViewForPointerUp():void { this.mVelocityTracker.computeCurrentVelocity(1000, this.mMaxVelocity); const xvel:number = this.clampMag(this.mVelocityTracker.getXVelocity(this.mActivePointerId), this.mMinVelocity, this.mMaxVelocity); const yvel:number = this.clampMag(this.mVelocityTracker.getYVelocity(this.mActivePointerId), this.mMinVelocity, this.mMaxVelocity); this.dispatchViewReleased(xvel, yvel); } private dragTo(left:number, top:number, dx:number, dy:number):void { let clampedX:number = left; let clampedY:number = top; const oldLeft:number = this.mCapturedView.getLeft(); const oldTop:number = this.mCapturedView.getTop(); if (dx != 0) { clampedX = this.mCallback.clampViewPositionHorizontal(this.mCapturedView, left, dx); this.mCapturedView.offsetLeftAndRight(clampedX - oldLeft); } if (dy != 0) { clampedY = this.mCallback.clampViewPositionVertical(this.mCapturedView, top, dy); this.mCapturedView.offsetTopAndBottom(clampedY - oldTop); } if (dx != 0 || dy != 0) { const clampedDx:number = clampedX - oldLeft; const clampedDy:number = clampedY - oldTop; this.mCallback.onViewPositionChanged(this.mCapturedView, clampedX, clampedY, clampedDx, clampedDy); } } /** * Determine if the currently captured view is under the given point in the * parent view's coordinate system. If there is no captured view this method * will return false. * * @param x X position to test in the parent's coordinate system * @param y Y position to test in the parent's coordinate system * @return true if the captured view is under the given point, false otherwise */ isCapturedViewUnder(x:number, y:number):boolean { return this.isViewUnder(this.mCapturedView, x, y); } /** * Determine if the supplied view is under the given point in the * parent view's coordinate system. * * @param view Child view of the parent to hit test * @param x X position to test in the parent's coordinate system * @param y Y position to test in the parent's coordinate system * @return true if the supplied view is under the given point, false otherwise */ isViewUnder(view:View, x:number, y:number):boolean { if (view == null) { return false; } return x >= view.getLeft() && x < view.getRight() && y >= view.getTop() && y < view.getBottom(); } /** * Find the topmost child under the given point within the parent view's coordinate system. * The child order is determined using {@link Callback#getOrderedChildIndex(int)}. * * @param x X position to test in the parent's coordinate system * @param y Y position to test in the parent's coordinate system * @return The topmost child view under (x, y) or null if none found. */ findTopChildUnder(x:number, y:number):View { const childCount:number = this.mParentView.getChildCount(); for (let i:number = childCount - 1; i >= 0; i--) { const child:View = this.mParentView.getChildAt(this.mCallback.getOrderedChildIndex(i)); if (x >= child.getLeft() && x < child.getRight() && y >= child.getTop() && y < child.getBottom()) { return child; } } return null; } private getEdgesTouched(x:number, y:number):number { let result:number = 0; if (x < this.mParentView.getLeft() + this.mEdgeSize) result |= ViewDragHelper.EDGE_LEFT; if (y < this.mParentView.getTop() + this.mEdgeSize) result |= ViewDragHelper.EDGE_TOP; if (x > this.mParentView.getRight() - this.mEdgeSize) result |= ViewDragHelper.EDGE_RIGHT; if (y > this.mParentView.getBottom() - this.mEdgeSize) result |= ViewDragHelper.EDGE_BOTTOM; return result; } } export module ViewDragHelper{ /** * A Callback is used as a communication channel with the ViewDragHelper back to the * parent view using it. <code>on*</code>methods are invoked on siginficant events and several * accessor methods are expected to provide the ViewDragHelper with more information * about the state of the parent view upon request. The callback also makes decisions * governing the range and draggability of child views. */ export abstract class Callback { /** * Called when the drag state changes. See the <code>STATE_*</code> constants * for more information. * * @param state The new drag state * * @see #STATE_IDLE * @see #STATE_DRAGGING * @see #STATE_SETTLING */ onViewDragStateChanged(state:number):void { } /** * Called when the captured view's position changes as the result of a drag or settle. * * @param changedView View whose position changed * @param left New X coordinate of the left edge of the view * @param top New Y coordinate of the top edge of the view * @param dx Change in X position from the last call * @param dy Change in Y position from the last call */ onViewPositionChanged(changedView:View, left:number, top:number, dx:number, dy:number):void { } /** * Called when a child view is captured for dragging or settling. The ID of the pointer * currently dragging the captured view is supplied. If activePointerId is * identified as {@link #INVALID_POINTER} the capture is programmatic instead of * pointer-initiated. * * @param capturedChild Child view that was captured * @param activePointerId Pointer id tracking the child capture */ onViewCaptured(capturedChild:View, activePointerId:number):void { } /** * Called when the child view is no longer being actively dragged. * The fling velocity is also supplied, if relevant. The velocity values may * be clamped to system minimums or maximums. * * <p>Calling code may decide to fling or otherwise release the view to let it * settle into place. It should do so using {@link #settleCapturedViewAt(int, int)} * or {@link #flingCapturedView(int, int, int, int)}. If the Callback invokes * one of these methods, the ViewDragHelper will enter {@link #STATE_SETTLING} * and the view capture will not fully end until it comes to a complete stop. * If neither of these methods is invoked before <code>onViewReleased</code> returns, * the view will stop in place and the ViewDragHelper will return to * {@link #STATE_IDLE}.</p> * * @param releasedChild The captured child view now being released * @param xvel X velocity of the pointer as it left the screen in pixels per second. * @param yvel Y velocity of the pointer as it left the screen in pixels per second. */ onViewReleased(releasedChild:View, xvel:number, yvel:number):void { } /** * Called when one of the subscribed edges in the parent view has been touched * by the user while no child view is currently captured. * * @param edgeFlags A combination of edge flags describing the edge(s) currently touched * @param pointerId ID of the pointer touching the described edge(s) * @see #EDGE_LEFT * @see #EDGE_TOP * @see #EDGE_RIGHT * @see #EDGE_BOTTOM */ onEdgeTouched(edgeFlags:number, pointerId:number):void { } /** * Called when the given edge may become locked. This can happen if an edge drag * was preliminarily rejected before beginning, but after {@link #onEdgeTouched(int, int)} * was called. This method should return true to lock this edge or false to leave it * unlocked. The default behavior is to leave edges unlocked. * * @param edgeFlags A combination of edge flags describing the edge(s) locked * @return true to lock the edge, false to leave it unlocked */ onEdgeLock(edgeFlags:number):boolean { return false; } /** * Called when the user has started a deliberate drag away from one * of the subscribed edges in the parent view while no child view is currently captured. * * @param edgeFlags A combination of edge flags describing the edge(s) dragged * @param pointerId ID of the pointer touching the described edge(s) * @see #EDGE_LEFT * @see #EDGE_TOP * @see #EDGE_RIGHT * @see #EDGE_BOTTOM */ onEdgeDragStarted(edgeFlags:number, pointerId:number):void { } /** * Called to determine the Z-order of child views. * * @param index the ordered position to query for * @return index of the view that should be ordered at position <code>index</code> */ getOrderedChildIndex(index:number):number { return index; } /** * Return the magnitude of a draggable child view's horizontal range of motion in pixels. * This method should return 0 for views that cannot move horizontally. * * @param child Child view to check * @return range of horizontal motion in pixels */ getViewHorizontalDragRange(child:View):number { return 0; } /** * Return the magnitude of a draggable child view's vertical range of motion in pixels. * This method should return 0 for views that cannot move vertically. * * @param child Child view to check * @return range of vertical motion in pixels */ getViewVerticalDragRange(child:View):number { return 0; } /** * Called when the user's input indicates that they want to capture the given child view * with the pointer indicated by pointerId. The callback should return true if the user * is permitted to drag the given view with the indicated pointer. * * <p>ViewDragHelper may call this method multiple times for the same view even if * the view is already captured; this indicates that a new pointer is trying to take * control of the view.</p> * * <p>If this method returns true, a call to {@link #onViewCaptured(android.view.View, int)} * will follow if the capture is successful.</p> * * @param child Child the user is attempting to capture * @param pointerId ID of the pointer attempting the capture * @return true if capture should be allowed, false otherwise */ abstract tryCaptureView(child:View, pointerId:number):boolean ; /** * Restrict the motion of the dragged child view along the horizontal axis. * The default implementation does not allow horizontal motion; the extending * class must override this method and provide the desired clamping. * * * @param child Child view being dragged * @param left Attempted motion along the X axis * @param dx Proposed change in position for left * @return The new clamped position for left */ clampViewPositionHorizontal(child:View, left:number, dx:number):number { return 0; } /** * Restrict the motion of the dragged child view along the vertical axis. * The default implementation does not allow vertical motion; the extending * class must override this method and provide the desired clamping. * * * @param child Child view being dragged * @param top Attempted motion along the Y axis * @param dy Proposed change in position for top * @return The new clamped position for top */ clampViewPositionVertical(child:View, top:number, dy:number):number { return 0; } } } }
the_stack
import Decimal from "decimal.js"; import { BasicClient, MarketMap } from "../BasicClient"; import { Candle } from "../Candle"; import { CandlePeriod } from "../CandlePeriod"; import { ClientOptions } from "../ClientOptions"; import * as https from "../Https"; import { Level2Point } from "../Level2Point"; import { Level2Snapshot } from "../Level2Snapshots"; import { Level2Update } from "../Level2Update"; import { NotImplementedFn } from "../NotImplementedFn"; import { Ticker } from "../Ticker"; import { Trade } from "../Trade"; export type KrakenClientOptions = ClientOptions & { autoloadSymbolMaps?: boolean }; /** Kraken's API documentation is availble at: https://www.kraken.com/features/websocket-api Once the socket is open you can subscribe to a channel by sending a subscribe request message. Ping is initiated by the client, not the server. This means we do not need to listen for pings events or respond appropriately. Requests take an array of pairs to subscribe to an event. This means when we subscribe or unsubscribe we need to send the COMPLETE list of active markets. BasicClient maintains the list of active markets in the various maps: _tickerSubs, _tradeSubs, _level2UpdateSubs. This client will retrieve the market keys from those maps to determine the remoteIds to send to the server on all sub/unsub requests. */ export class KrakenClient extends BasicClient { public candlePeriod: CandlePeriod; public bookDepth: number; public debounceWait: number; protected debouceTimeoutHandles: Map<string, NodeJS.Timeout>; protected subscriptionLog: Map<number, any>; protected fromRestMap: Map<string, string>; protected fromWsMap: Map<string, string>; constructor({ wssPath = "wss://ws.kraken.com", autoloadSymbolMaps = true, watcherMs, }: KrakenClientOptions = {}) { super(wssPath, "Kraken", undefined, watcherMs); this.hasTickers = true; this.hasTrades = true; this.hasCandles = true; this.hasLevel2Updates = true; this.hasLevel2Snapshots = false; this.candlePeriod = CandlePeriod._1m; this.bookDepth = 500; this.subscriptionLog = new Map(); this.debouceTimeoutHandles = new Map(); this.debounceWait = 200; this.fromRestMap = new Map(); this.fromWsMap = new Map(); if (autoloadSymbolMaps) { this.loadSymbolMaps().catch(err => this.emit("error", err)); } } /** Kraken made the websocket symbols different than the REST symbols. Because CCXT uses the REST symbols, we're going to default to receiving REST symbols and mapping them to the corresponding WS symbol. In order to do this, we'll need to retrieve the list of symbols from the REST API. The constructor executes this. */ public async loadSymbolMaps() { const uri = "https://api.kraken.com/0/public/AssetPairs"; const { result } = await https.get(uri); for (const symbol in result) { const restName = symbol; const wsName = result[symbol].wsname; if (wsName) { this.fromRestMap.set(restName, wsName); this.fromWsMap.set(wsName, restName); } } } /** Helper that retrieves the list of ws symbols from the supplied subscription map. The BasicClient manages the subscription maps when subscribe<Trade|Ticker|etc> is called and adds the records. This helper will take the values in a subscription map and convert them into the websocket symbols, ensuring that markets that are not mapped do not get included in the list. @param map subscription map such as _tickerSubs or _tradeSubs */ protected _wsSymbolsFromSubMap(map: MarketMap) { const restSymbols = Array.from(map.keys()); return restSymbols.map(p => this.fromRestMap.get(p)).filter(p => p); } /** Debounce is used to throttle a function that is repeatedly called. This is applicable when many calls to subscribe or unsubscribe are executed in quick succession by the calling application. */ protected _debounce(type: string, fn: () => void) { clearTimeout(this.debouceTimeoutHandles.get(type)); this.debouceTimeoutHandles.set(type, setTimeout(fn, this.debounceWait)); } /** This method is called by each of the _send* methods. It uses a debounce function on a given key so we can batch send the request with the active symbols. We also need to convert the rest symbols provided by the caller into websocket symbols used by the Kraken ws server. @param debounceKey unique key for the caller so each call is debounced with related calls @param subMap subscription map storing the current subs for the type, such as _tickerSubs, _tradeSubs, etc. @param subscribe true for subscribe, false for unsubscribe @param subscription the subscription name passed to the JSON-RPC call */ protected _debounceSend( debounceKey: string, subMap: MarketMap, subscribe: boolean, subscription: { name: string; [x: string]: any }, ) { this._debounce(debounceKey, () => { const wsSymbols = this._wsSymbolsFromSubMap(subMap); if (!this._wss) return; this._wss.send( JSON.stringify({ event: subscribe ? "subscribe" : "unsubscribe", pair: wsSymbols, subscription, }), ); }); } /** Constructs a request that looks like: { "event": "subscribe", "pair": ["XBT/USD","BCH/USD"] "subscription": { "name": "ticker" } } */ protected _sendSubTicker() { this._debounceSend("sub-ticker", this._tickerSubs, true, { name: "ticker" }); } /** Constructs a request that looks like: { "event": "unsubscribe", "pair": ["XBT/USD","BCH/USD"] "subscription": { "name": "ticker" } } */ protected _sendUnsubTicker() { this._debounceSend("unsub-ticker", this._tickerSubs, false, { name: "ticker" }); } /** Constructs a request that looks like: { "event": "subscribe", "pair": ["XBT/USD","BCH/USD"] "subscription": { "name": "trade" } } */ protected _sendSubTrades() { this._debounceSend("sub-trades", this._tradeSubs, true, { name: "trade" }); } /** Constructs a request that looks like: { "event": "unsubscribe", "pair": ["XBT/USD","BCH/USD"] "subscription": { "name": "trade" } } */ protected _sendUnsubTrades() { this._debounceSend("unsub-trades", this._tradeSubs, false, { name: "trade" }); } /** * Constructs a request that looks like: { "event": "unsubscribe", "pair": ["XBT/USD","BCH/USD"] "subscription": { "name": "ohlc" "interval": 1 } } */ protected _sendSubCandles() { const interval = getCandlePeriod(this.candlePeriod); this._debounceSend("sub-candles", this._candleSubs, true, { name: "ohlc", interval }); } /** * Constructs a request that looks like: { "event": "unsubscribe", "pair": ["XBT/USD","BCH/USD"] "subscription": { "name": "ohlc" "interval": 1 } } */ protected _sendUnsubCandles() { const interval = getCandlePeriod(this.candlePeriod); this._debounceSend("unsub-candles", this._candleSubs, false, { name: "ohlc", interval }); } /** Constructs a request that looks like: { "event": "subscribe", "pair": ["XBT/USD","BCH/USD"] "subscription": { "name": "book" } } */ protected _sendSubLevel2Updates() { this._debounceSend("sub-l2updates", this._level2UpdateSubs, true, { name: "book", depth: this.bookDepth, }); } /** Constructs a request that looks like: { "event": "unsubscribe", "pair": ["XBT/USD","BCH/USD"] "subscription": { "name": "trade" } } */ protected _sendUnsubLevel2Updates() { this._debounceSend("unsub-l2updates", this._level2UpdateSubs, false, { name: "book" }); } /** Handle for incoming messages @param raw */ protected _onMessage(raw: string) { const msgs = JSON.parse(raw); this._processsMessage(msgs); } protected _sendSubLevel2Snapshots = NotImplementedFn; protected _sendUnsubLevel2Snapshots = NotImplementedFn; protected _sendSubLevel3Snapshots = NotImplementedFn; protected _sendUnsubLevel3Snapshots = NotImplementedFn; protected _sendSubLevel3Updates = NotImplementedFn; protected _sendUnsubLevel3Updates = NotImplementedFn; /** When a subscription is initiated, a subscriptionStatus event is sent. This message will be cached in the subscriptionLog for look up later. When messages arrive, they only contain the subscription id. The id is used to look up the subscription details in the subscriptionLog to determine what the message means. */ protected _processsMessage(msg: any) { if (msg.event === "heartbeat") { return; } if (msg.event === "systemStatus") { return; } // Capture the subscription metadata for use later. if (msg.event === "subscriptionStatus") { /* { channelID: '15', event: 'subscriptionStatus', pair: 'XBT/EUR', status: 'subscribed', subscription: { name: 'ticker' } } */ this.subscriptionLog.set(parseInt(msg.channelID), msg); return; } // All messages from this point forward should arrive as an array if (!Array.isArray(msg)) { return; } const [subscriptionId, details] = msg; const sl = this.subscriptionLog.get(subscriptionId); // If we don't have a subscription log entry for this event then // we need to abort since we don't know what to do with it! // From the subscriptionLog entry's pair, we can convert // the ws symbol into a rest symbol const remote_id = this.fromWsMap.get(sl.pair); // tickers if (sl.subscription.name === "ticker") { const market = this._tickerSubs.get(remote_id); if (!market) return; const ticker = this._constructTicker(details, market); if (ticker) { this.emit("ticker", ticker, market); } return; } // trades if (sl.subscription.name === "trade") { if (Array.isArray(msg[1])) { const market = this._tradeSubs.get(remote_id); if (!market) return; for (const t of msg[1]) { const trade = this._constructTrade(t, market); if (trade) { this.emit("trade", trade, market); } } } return; } // candles if (sl.subscription.name === "ohlc") { const market = this._candleSubs.get(remote_id); if (!market) return; const candle = this._constructCandle(msg); this.emit("candle", candle, market); return; } //l2 updates if (sl.subscription.name === "book") { const market = this._level2UpdateSubs.get(remote_id); if (!market) return; // snapshot use as/bs // updates us a/b const isSnapshot = !!msg[1].as; if (isSnapshot) { const l2snapshot = this._constructLevel2Snapshot(msg[1], market); if (l2snapshot) { this.emit("l2snapshot", l2snapshot, market, msg); } } else { const l2update = this._constructLevel2Update(msg, market); if (l2update) { this.emit("l2update", l2update, market, msg); } } } return; } /** Refer to https://www.kraken.com/en-us/features/websocket-api#message-ticker */ protected _constructTicker(msg, market) { /* { a: [ '3343.70000', 1, '1.03031692' ], b: [ '3342.20000', 1, '1.00000000' ], c: [ '3343.70000', '0.01000000' ], v: [ '4514.26000539', '7033.48119179' ], p: [ '3357.13865', '3336.28299' ], t: [ 14731, 22693 ], l: [ '3308.40000', '3223.90000' ], h: [ '3420.00000', '3420.00000' ], o: [ '3339.40000', '3349.00000' ] } */ // calculate change and change percent based from the open/close // prices const open = parseFloat(msg.o[1]); const last = parseFloat(msg.c[0]); const change = open - last; const changePercent = ((last - open) / open) * 100; // calculate the quoteVolume by multiplying the volume // over the last 24h by the 24h vwap const quoteVolume = parseFloat(msg.v[1]) * parseFloat(msg.p[1]); return new Ticker({ exchange: this.name, base: market.base, quote: market.quote, timestamp: Date.now(), last: msg.c[0], open: msg.o[1], high: msg.h[0], low: msg.l[0], volume: msg.v[1], quoteVolume: quoteVolume.toFixed(8), change: change.toFixed(8), changePercent: changePercent.toFixed(2), bid: msg.b[0], bidVolume: msg.b[2], ask: msg.a[0], askVolume: msg.a[2], }); } /** Refer to https://www.kraken.com/en-us/features/websocket-api#message-trade Since Kraken doesn't send a trade Id we create a surrogate from the time stamp. This can result in duplicate trade Ids being generated. Additionaly mechanism will need to be put into place by the consumer to dedupe them. */ protected _constructTrade(datum, market) { /* [ '3363.20000', '0.05168143', '1551432237.079148', 'b', 'l', '' ] */ const side = datum[3] === "b" ? "buy" : "sell"; // see above const tradeId = this._createTradeId(datum[2]); // convert to ms timestamp as an int const unix = parseInt((parseFloat(datum[2]) * 1000) as any); return new Trade({ exchange: this.name, base: market.base, quote: market.quote, tradeId, side: side, unix, price: datum[0], amount: datum[1], rawUnix: datum[2], }); } /** Refer to https://www.kraken.com/en-us/features/websocket-api#message-ohlc */ protected _constructCandle(msg) { /** [ 6, [ '1571080988.157759', '1571081040.000000', '8352.00000', '8352.00000', '8352.00000', '8352.00000', '8352.00000', '0.01322211', 1 ], 'ohlc-1', 'XBT/USD' ] */ const datum = msg[1]; const ms = parseInt(datum[1]) * 1000; return new Candle(ms, datum[2], datum[3], datum[4], datum[5], datum[7]); } /** * Refer to https://www.kraken.com/en-us/features/websocket-api#message-book * Values will look like: * [ * 270, * {"b":[["11260.50000","0.00000000","1596221402.104952"],["11228.70000","2.60111463","1596221103.546084","r"]],"c":"1281654047"}, * "book-100", * "XBT/USD" * ] * * [ * 270, * {"a":[["11277.30000","1.01949833","1596221402.163693"]]}, * {"b":[["11275.30000","0.17300000","1596221402.163680"]],"c":"1036980588"}, * "book-100", * "XBT/USD" * ] */ protected _constructLevel2Update(msg, market) { const asks = []; const bids = []; let checksum; // Because some messages will send more than a single result object // we need to iterate the results blocks starting at position 1 and // look for ask, bid, and checksum data. for (let i = 1; i < msg.length; i++) { // Process ask updates if (msg[i].a) { for (const [price, size, timestamp] of msg[i].a) { asks.push(new Level2Point(price, size, undefined, undefined, timestamp)); } } // Process bid updates if (msg[i].b) { for (const [price, size, timestamp] of msg[i].b) { bids.push(new Level2Point(price, size, undefined, undefined, timestamp)); } } // Process checksum if (msg[i].c) { checksum = msg[i].c; } } // Calculates the newest timestamp value to maintain backwards // compatibility with the update timestamp const timestamp = Math.max(...asks.concat(bids).map(p => parseFloat(p.timestamp))); return new Level2Update({ exchange: this.name, base: market.base, quote: market.quote, timestampMs: parseInt((timestamp * 1000) as any), asks, bids, checksum, }); } /** * Refer to https://www.kraken.com/en-us/features/websocket-api#message-book * * { * as: [ * [ '3361.30000', '25.57512297', '1551438550.367822' ], * [ '3363.80000', '15.81228000', '1551438539.149525' ] * ], * bs: [ * [ '3361.20000', '0.07234101', '1551438547.041624' ], * [ '3357.60000', '1.75000000', '1551438516.825218' ] * ] * } */ protected _constructLevel2Snapshot(datum, market) { // Process asks const as = datum.as || []; const asks = []; for (const [price, size, timestamp] of as) { asks.push(new Level2Point(price, size, undefined, undefined, timestamp)); } // Process bids const bs = datum.bs || []; const bids = []; for (const [price, size, timestamp] of bs) { bids.push(new Level2Point(price, size, undefined, undefined, timestamp)); } // Calculates the newest timestamp value to maintain backwards // compatibility with the update timestamp const timestamp = Math.max(...asks.concat(bids).map(p => parseFloat(p.timestamp))); return new Level2Snapshot({ exchange: this.name, base: market.base, quote: market.quote, timestampMs: parseInt((timestamp * 1000) as any), asks, bids, }); } /** Since Kraken doesn't send a trade id, we need to come up with a way to generate one on our own. The REST API include the last trade id which gives us the clue that it is the second timestamp + 9 sub-second digits. The WS will provide timestamps with up to 6 decimals of precision. The REST API only has timestamps with 4 decimal of precision. To maintain consistency, we're going to use the following formula: <integer part of unix timestamp> + <first 4 digits of fractional part of unix timestamp> + 00000 We're using the ROUND_HALF_UP method. From testing, this resulted in the best rounding results. Ids are in picoseconds, the websocket is broadcast in microsecond, and the REST results are truncated to 4 decimals. This mean it is impossible to determine the rounding algorithm or the proper rounding to go from 6 to 4 decimals as the 6 decimals are being rounded from 9 which causes issues as the half point for 4 digit rounding .222950 rounds up to .2230 if the pico_ms value is > .222295000 .222950 rounds down to .2229 if the pico_ms value is < .222295000 Consumer code will need to account for collisions and id mismatch. */ protected _createTradeId(unix: string): string { const roundMode = Decimal.ROUND_HALF_UP; const [integer, frac] = unix.split("."); const fracResult = new Decimal("0." + frac) .toDecimalPlaces(4, roundMode) .toFixed(4) .split(".")[1]; return integer + fracResult + "00000"; } } /** * Maps the candle period from CCXWS to those required by the subscription mechanism * as defined in https://www.kraken.com/en-us/features/websocket-api#message-subscribe * @paramp */ function getCandlePeriod(p: CandlePeriod) { switch (p) { case CandlePeriod._1m: return 1; case CandlePeriod._5m: return 5; case CandlePeriod._15m: return 15; case CandlePeriod._30m: return 30; case CandlePeriod._1h: return 60; case CandlePeriod._4h: return 240; case CandlePeriod._1d: return 1440; case CandlePeriod._1w: return 10080; case CandlePeriod._2w: return 21600; } }
the_stack
* Please try to keep this list in alphabetical order :-) * (hopefully your editor can do it!) */ export enum ActionTypes { COLONY_CLAIM_TOKEN = 'COLONY_CLAIM_TOKEN', COLONY_CLAIM_TOKEN_ERROR = 'COLONY_CLAIM_TOKEN_ERROR', COLONY_CLAIM_TOKEN_SUCCESS = 'COLONY_CLAIM_TOKEN_SUCCESS', COLONY_CREATE = 'COLONY_CREATE', COLONY_CREATE_CANCEL = 'COLONY_CREATE_CANCEL', COLONY_CREATE_ERROR = 'COLONY_CREATE_ERROR', COLONY_CREATE_SUCCESS = 'COLONY_CREATE_SUCCESS', COLONY_DEPLOYMENT_RESTART = 'COLONY_DEPLOYMENT_RESTART', COLONY_DEPLOYMENT_RESTART_ERROR = 'COLONY_DEPLOYMENT_RESTART_ERROR', COLONY_DEPLOYMENT_RESTART_SUCCESS = 'COLONY_DEPLOYMENT_RESTART_SUCCESS', COLONY_RECOVERY_MODE_ENTER = 'COLONY_RECOVERY_MODE_ENTER', COLONY_RECOVERY_MODE_ENTER_ERROR = 'COLONY_RECOVERY_MODE_ENTER_ERROR', COLONY_RECOVERY_MODE_ENTER_SUCCESS = 'COLONY_RECOVERY_MODE_ENTER_SUCCESS', COLONY_EXTENSION_ENABLE = 'COLONY_EXTENSION_ENABLE', COLONY_EXTENSION_ENABLE_ERROR = 'COLONY_EXTENSION_ENABLE_ERROR', COLONY_EXTENSION_ENABLE_SUCCESS = 'COLONY_EXTENSION_ENABLE_SUCCESS', COLONY_EXTENSION_INSTALL = 'COLONY_EXTENSION_INSTALL', COLONY_EXTENSION_INSTALL_ERROR = 'COLONY_EXTENSION_INSTALL_ERROR', COLONY_EXTENSION_INSTALL_SUCCESS = 'COLONY_EXTENSION_INSTALL_SUCCESS', COLONY_EXTENSION_DEPRECATE= 'COLONY_EXTENSION_DEPRECATE', COLONY_EXTENSION_DEPRECATE_ERROR = 'COLONY_EXTENSION_DEPRECATE_ERROR', COLONY_EXTENSION_DEPRECATE_SUCCESS = 'COLONY_EXTENSION_DEPRECATE_SUCCESS', COLONY_EXTENSION_UNINSTALL = 'COLONY_EXTENSION_UNINSTALL', COLONY_EXTENSION_UNINSTALL_ERROR = 'COLONY_EXTENSION_UNINSTALL_ERROR', COLONY_EXTENSION_UNINSTALL_SUCCESS = 'COLONY_EXTENSION_UNINSTALL_SUCCESS', COLONY_EXTENSION_UPGRADE = 'COLONY_EXTENSION_UPGRADE', COLONY_EXTENSION_UPGRADE_ERROR = 'COLONY_EXTENSION_UPGRADE_ERROR', COLONY_EXTENSION_UPGRADE_SUCCESS = 'COLONY_EXTENSION_UPGRADE_SUCCESS', WHITELIST_UPDATE = 'WHITELIST_UPDATE', WHITELIST_UPDATE_SUCCESS = 'WHITELIST_UPDATE_SUCCESS', WHITELIST_UPDATE_ERROR = 'WHITELIST_UPDATE_ERROR', /* * Actions */ COLONY_ACTION_DOMAIN_CREATE = 'COLONY_ACTION_DOMAIN_CREATE', COLONY_ACTION_DOMAIN_CREATE_ERROR = 'COLONY_ACTION_DOMAIN_CREATE_ERROR', COLONY_ACTION_DOMAIN_CREATE_SUCCESS = 'COLONY_ACTION_DOMAIN_CREATE_SUCCESS', COLONY_ACTION_DOMAIN_EDIT = 'COLONY_ACTION_DOMAIN_EDIT', COLONY_ACTION_DOMAIN_EDIT_ERROR = 'COLONY_ACTION_DOMAIN_EDIT_ERROR', COLONY_ACTION_DOMAIN_EDIT_SUCCESS = 'COLONY_ACTION_DOMAIN_EDIT_SUCCESS', /* * @NOTE These are generic actions use for placeholders * They are not, and should not be wired to any dispatch action */ COLONY_ACTION_GENERIC = 'COLONY_ACTION_GENERIC', COLONY_ACTION_GENERIC_ERROR = 'COLONY_ACTION_GENERIC_ERROR', COLONY_ACTION_GENERIC_SUCCESS = 'COLONY_ACTION_GENERIC_SUCCESS', COLONY_ACTION_EXPENDITURE_PAYMENT = 'COLONY_ACTION_EXPENDITURE_PAYMENT', COLONY_ACTION_EXPENDITURE_PAYMENT_ERROR = 'COLONY_ACTION_EXPENDITURE_PAYMENT_ERROR', COLONY_ACTION_EXPENDITURE_PAYMENT_SUCCESS = 'COLONY_ACTION_EXPENDITURE_PAYMENT_SUCCESS', COLONY_ACTION_EDIT_COLONY = 'COLONY_ACTION_EDIT_COLONY', COLONY_ACTION_EDIT_COLONY_ERROR = 'COLONY_ACTION_EDIT_COLONY_ERROR', COLONY_ACTION_EDIT_COLONY_SUCCESS = 'COLONY_ACTION_EDIT_COLONY_SUCCESS', COLONY_ACTION_MINT_TOKENS = 'COLONY_ACTION_MINT_TOKENS', COLONY_ACTION_MINT_TOKENS_ERROR = 'COLONY_ACTION_MINT_TOKENS_ERROR', COLONY_ACTION_MINT_TOKENS_SUCCESS = 'COLONY_ACTION_MINT_TOKENS_SUCCESS', COLONY_ACTION_MOVE_FUNDS = 'COLONY_ACTION_MOVE_FUNDS', COLONY_ACTION_MOVE_FUNDS_ERROR = 'COLONY_ACTION_MOVE_FUNDS_ERROR', COLONY_ACTION_MOVE_FUNDS_SUCCESS = 'COLONY_ACTION_MOVE_FUNDS_SUCCESS', COLONY_ACTION_RECOVERY = 'COLONY_ACTION_RECOVERY', COLONY_ACTION_RECOVERY_ERROR = 'COLONY_ACTION_RECOVERY_ERROR', COLONY_ACTION_RECOVERY_SUCCESS = 'COLONY_ACTION_RECOVERY_SUCCESS', COLONY_ACTION_RECOVERY_SET_SLOT = 'COLONY_ACTION_RECOVERY_SET_SLOT', COLONY_ACTION_RECOVERY_SET_SLOT_ERROR = 'COLONY_ACTION_RECOVERY_SET_SLOT_ERROR', COLONY_ACTION_RECOVERY_SET_SLOT_SUCCESS = 'COLONY_ACTION_RECOVERY_SET_SLOT_SUCCESS', COLONY_ACTION_RECOVERY_APPROVE = 'COLONY_ACTION_RECOVERY_APPROVE', COLONY_ACTION_RECOVERY_APPROVE_ERROR = 'COLONY_ACTION_RECOVERY_APPROVE_ERROR', COLONY_ACTION_RECOVERY_APPROVE_SUCCESS = 'COLONY_ACTION_RECOVERY_APPROVE_SUCCESS', COLONY_ACTION_RECOVERY_EXIT = 'COLONY_ACTION_RECOVERY_EXIT', COLONY_ACTION_RECOVERY_EXIT_ERROR = 'COLONY_ACTION_RECOVERY_EXIT_ERROR', COLONY_ACTION_RECOVERY_EXIT_SUCCESS = 'COLONY_ACTION_RECOVERY_EXIT_SUCCESS', COLONY_ACTION_VERSION_UPGRADE = 'COLONY_ACTION_VERSION_UPGRADE', COLONY_ACTION_VERSION_UPGRADE_ERROR = 'COLONY_ACTION_VERSION_UPGRADE_ERROR', COLONY_ACTION_VERSION_UPGRADE_SUCCESS = 'COLONY_ACTION_VERSION_UPGRADE_SUCCESS', COLONY_ACTION_USER_ROLES_SET = 'COLONY_ACTION_USER_ROLES_SET', COLONY_ACTION_USER_ROLES_SET_ERROR = 'COLONY_ACTION_USER_ROLES_SET_ERROR', COLONY_ACTION_USER_ROLES_SET_SUCCESS = 'COLONY_ACTION_USER_ROLES_SET_SUCCESS', COLONY_ACTION_UNLOCK_TOKEN = 'COLONY_ACTION_UNLOCK_TOKEN', COLONY_ACTION_UNLOCK_TOKEN_ERROR = 'COLONY_ACTION_UNLOCK_TOKEN_ERROR', COLONY_ACTION_UNLOCK_TOKEN_SUCCESS = 'COLONY_ACTION_UNLOCK_TOKEN_SUCCESS', /* * Motions */ COLONY_MOTION_STAKE = 'COLONY_MOTION_STAKE', COLONY_MOTION_STAKE_ERROR = 'COLONY_MOTION_STAKE_ERROR', COLONY_MOTION_STAKE_SUCCESS = 'COLONY_MOTION_STAKE_SUCCESS', COLONY_MOTION_VOTE = 'COLONY_MOTION_VOTE', COLONY_MOTION_VOTE_ERROR = 'COLONY_MOTION_VOTE_ERROR', COLONY_MOTION_VOTE_SUCCESS = 'COLONY_MOTION_VOTE_SUCCESS', COLONY_MOTION_REVEAL_VOTE = 'COLONY_MOTION_REVEAL_VOTE', COLONY_MOTION_REVEAL_VOTE_ERROR = 'COLONY_MOTION_REVEAL_VOTE_ERROR', COLONY_MOTION_REVEAL_VOTE_SUCCESS = 'COLONY_MOTION_REVEAL_VOTE_SUCCESS', COLONY_MOTION_FINALIZE = 'COLONY_MOTION_FINALIZE', COLONY_MOTION_FINALIZE_ERROR = 'COLONY_MOTION_FINALIZE_ERROR', COLONY_MOTION_FINALIZE_SUCCESS = 'COLONY_MOTION_FINALIZE_SUCCESS', COLONY_MOTION_CLAIM = 'COLONY_MOTION_CLAIM', COLONY_MOTION_CLAIM_ERROR = 'COLONY_MOTION_CLAIM_ERROR', COLONY_MOTION_CLAIM_SUCCESS = 'COLONY_MOTION_CLAIM_SUCCESS', COLONY_MOTION_DOMAIN_CREATE_EDIT = 'COLONY_MOTION_DOMAIN_CREATE_EDIT', COLONY_MOTION_DOMAIN_CREATE_EDIT_ERROR = 'COLONY_MOTION_DOMAIN_CREATE_EDIT_ERROR', COLONY_MOTION_DOMAIN_CREATE_EDIT_SUCCESS = 'COLONY_MOTION_DOMAIN_CREATE_EDIT_SUCCESS', COLONY_MOTION_EDIT_COLONY = 'COLONY_MOTION_EDIT_COLONY', COLONY_MOTION_EDIT_COLONY_ERROR = 'COLONY_MOTION_EDIT_COLONY_ERROR', COLONY_MOTION_EDIT_COLONY_SUCCESS = 'COLONY_MOTION_EDIT_COLONY_SUCCESS', COLONY_MOTION_EXPENDITURE_PAYMENT = 'COLONY_MOTION_EXPENDITURE_PAYMENT', COLONY_MOTION_EXPENDITURE_PAYMENT_ERROR = 'COLONY_MOTION_EXPENDITURE_PAYMENT_ERROR', COLONY_MOTION_EXPENDITURE_PAYMENT_SUCCESS = 'COLONY_MOTION_EXPENDITURE_PAYMENT_SUCCESS', COLONY_MOTION_MOVE_FUNDS = 'COLONY_MOTION_MOVE_FUNDS', COLONY_MOTION_MOVE_FUNDS_ERROR = 'COLONY_MOTION_MOVE_FUNDS_ERROR', COLONY_MOTION_MOVE_FUNDS_SUCCESS = 'COLONY_MOTION_MOVE_FUNDS_SUCCESS', COLONY_MOTION_USER_ROLES_SET = 'COLONY_MOTION_USER_ROLES_SET', COLONY_MOTION_USER_ROLES_SET_ERROR = 'COLONY_MOTION_USER_ROLES_SET_ERROR', COLONY_MOTION_USER_ROLES_SET_SUCCESS = 'COLONY_MOTION_USER_ROLES_SET_SUCCESS', COLONY_ROOT_MOTION = 'COLONY_ROOT_MOTION', COLONY_ROOT_MOTION_ERROR = 'COLONY_ROOT_MOTION_ERROR', COLONY_ROOT_MOTION_SUCCESS = 'COLONY_ROOT_MOTION_SUCCESS', COLONY_MOTION_STATE_UPDATE = 'COLONY_MOTION_STATE_UPDATE', COLONY_MOTION_STATE_UPDATE_ERROR = 'COLONY_MOTION_STATE_UPDATE_ERROR', COLONY_MOTION_STATE_UPDATE_SUCCESS = 'COLONY_MOTION_STATE_UPDATE_SUCCESS', COLONY_MOTION_ESCALATE = 'COLONY_MOTION_ESCALATE', COLONY_MOTION_ESCALATE_ERROR = 'COLONY_MOTION_ESCALATE_ERROR', COLONY_MOTION_ESCALATE_SUCCESS = 'COLONY_MOTION_ESCALATE_SUCCESS', /* * Other */ CONNECTION_STATS_SUB_ERROR = 'CONNECTION_STATS_SUB_ERROR', CONNECTION_STATS_SUB_EVENT = 'CONNECTION_STATS_SUB_EVENT', CONNECTION_STATS_SUB_START = 'CONNECTION_STATS_SUB_START', CONNECTION_STATS_SUB_STOP = 'CONNECTION_STATS_SUB_STOP', GAS_PRICES_UPDATE = 'GAS_PRICES_UPDATE', IPFS_DATA_FETCH = 'IPFS_DATA_FETCH', IPFS_DATA_FETCH_ERROR = 'IPFS_DATA_FETCH_ERROR', IPFS_DATA_FETCH_SUCCESS = 'IPFS_DATA_FETCH_SUCCESS', IPFS_DATA_UPLOAD = 'IPFS_DATA_UPLOAD', IPFS_DATA_UPLOAD_ERROR = 'IPFS_DATA_UPLOAD_ERROR', IPFS_DATA_UPLOAD_SUCCESS = 'IPFS_DATA_UPLOAD_SUCCESS', MESSAGE_CANCEL = 'MESSAGE_CANCEL', MESSAGE_CREATED = 'MESSAGE_CREATED', MESSAGE_ERROR = 'MESSAGE_ERROR', MESSAGE_SIGN = 'MESSAGE_SIGN', MESSAGE_SIGNED = 'MESSAGE_SIGNED', MULTISIG_TRANSACTION_CREATED = 'MULTISIG_TRANSACTION_CREATED', MULTISIG_TRANSACTION_REFRESHED = 'MULTISIG_TRANSACTION_REFRESHED', MULTISIG_TRANSACTION_REJECT = 'MULTISIG_TRANSACTION_REJECT', MULTISIG_TRANSACTION_SIGN = 'MULTISIG_TRANSACTION_SIGN', MULTISIG_TRANSACTION_SIGNED = 'MULTISIG_TRANSACTION_SIGNED', TRANSACTION_ADD_IDENTIFIER = 'TRANSACTION_ADD_IDENTIFIER', TRANSACTION_ADD_PARAMS = 'TRANSACTION_ADD_PARAMS', TRANSACTION_CANCEL = 'TRANSACTION_CANCEL', TRANSACTION_CREATED = 'TRANSACTION_CREATED', TRANSACTION_ERROR = 'TRANSACTION_ERROR', TRANSACTION_ESTIMATE_GAS = 'TRANSACTION_ESTIMATE_GAS', TRANSACTION_GAS_UPDATE = 'TRANSACTION_GAS_UPDATE', TRANSACTION_HASH_RECEIVED = 'TRANSACTION_HASH_RECEIVED', TRANSACTION_LOAD_RELATED = 'TRANSACTION_LOAD_RELATED', TRANSACTION_READY = 'TRANSACTION_READY', TRANSACTION_PENDING = 'TRANSACTION_PENDING', TRANSACTION_RECEIPT_RECEIVED = 'TRANSACTION_RECEIPT_RECEIVED', TRANSACTION_SEND = 'TRANSACTION_SEND', TRANSACTION_SENT = 'TRANSACTION_SENT', TRANSACTION_SUCCEEDED = 'TRANSACTION_SUCCEEDED', TRANSACTION_RETRY = 'TRANSACTION_RETRY', USER_AVATAR_REMOVE = 'USER_AVATAR_REMOVE', USER_AVATAR_REMOVE_ERROR = 'USER_AVATAR_REMOVE_ERRROR', USER_AVATAR_REMOVE_SUCCESS = 'USER_AVATAR_REMOVE_SUCCESS', USER_AVATAR_UPLOAD = 'USER_AVATAR_UPLOAD', USER_AVATAR_UPLOAD_ERROR = 'USER_AVATAR_UPLOAD_ERRROR', USER_AVATAR_UPLOAD_SUCCESS = 'USER_AVATAR_UPLOAD_SUCCESS', USER_CONTEXT_SETUP_SUCCESS = 'USER_CONTEXT_SETUP_SUCCESS', USER_DEPOSIT_TOKEN = 'USER_DEPOSIT_TOKEN', USER_DEPOSIT_TOKEN_ERROR = 'USER_DEPOSIT_TOKEN_ERROR', USER_DEPOSIT_TOKEN_SUCCESS = 'USER_DEPOSIT_TOKEN_SUCCESS', USER_LOGOUT = 'USER_LOGOUT', USER_LOGOUT_ERROR = 'USER_LOGOUT_ERROR', USER_LOGOUT_SUCCESS = 'USER_LOGOUT_SUCCESS', USER_WITHDRAW_TOKEN = 'USER_WITHDRAW_TOKEN', USER_WITHDRAW_TOKEN_ERROR = 'USER_WITHDRAW_TOKEN_ERROR', USER_WITHDRAW_TOKEN_SUCCESS = 'USER_WITHDRAW_TOKEN_SUCCESS', USERNAME_CREATE = 'USERNAME_CREATE', USERNAME_CREATE_ERROR = 'USERNAME_CREATE_ERROR', USERNAME_CREATE_SUCCESS = 'USERNAME_CREATE_SUCCESS', WALLET_CREATE = 'WALLET_CREATE', WALLET_CREATE_ERROR = 'WALLET_CREATE_ERROR', WALLET_CREATE_SUCCESS = 'WALLET_CREATE_SUCCESS', }
the_stack
import React, { useCallback, useEffect, useMemo, useState } from "react"; import { Animated, Easing, NativeSyntheticEvent, StyleProp, StyleSheet, TargetedEvent, TextInput as RNTextInput, TextInputFocusEventData, TextInputProps as RNTextInputProps, View, ViewStyle, } from "react-native"; import Text from "./Text"; import { Color, usePaletteColor } from "./hooks/use-palette-color"; import { useTheme } from "./base/ThemeContext"; import { useSurfaceScale } from "./hooks/use-surface-scale"; import { useStyles } from "./hooks/use-styles"; export interface TextInputProps extends RNTextInputProps { /** * The variant to use. * * @default "filled" */ variant?: "filled" | "outlined" | "standard"; /** * The label to display. */ label?: string; /** * The element placed before the text input. */ leading?: React.ReactNode | ((props: { color: string; size: number }) => React.ReactNode | null) | null; /** * The element placed after the text input. */ trailing?: React.ReactNode | ((props: { color: string; size: number }) => React.ReactNode | null) | null; /** * The color of the text input's content (e.g. label, icons, selection). * * @default "primary" */ color?: Color; /** * The helper text to display. */ helperText?: string; /** * Callback function to call when user moves pointer over the input. */ onMouseEnter?: (event: NativeSyntheticEvent<TargetedEvent>) => void; /** * Callback function to call when user moves pointer away from the input. */ onMouseLeave?: (event: NativeSyntheticEvent<TargetedEvent>) => void; /** * The style of the container view. */ style?: StyleProp<ViewStyle>; /** * The style of the text input container view. */ inputContainerStyle?: StyleProp<ViewStyle>; /** * The style of the text input. */ inputStyle?: RNTextInputProps["style"]; /** * The style of the text input's leading element container. */ leadingContainerStyle?: StyleProp<ViewStyle>; /** * The style of the text input's trailing element container. */ trailingContainerStyle?: StyleProp<ViewStyle>; } const TextInput: React.FC<TextInputProps> = React.forwardRef(({ variant = "filled", label, leading, trailing, color = "primary", helperText, onMouseEnter, onMouseLeave, style, inputContainerStyle, inputStyle, leadingContainerStyle, trailingContainerStyle, placeholder, onFocus, onBlur, onChangeText, ...rest }, ref) => { const theme = useTheme(); const surfaceScale = useSurfaceScale(); const palette = usePaletteColor(color); const leadingNode = typeof leading === "function" ? leading({ color: surfaceScale(0.62).hex(), size: 24 }) : leading; const trailingNode = typeof trailing === "function" ? trailing({ color: surfaceScale(0.62).hex(), size: 24, }) : trailing; const [text, setText] = useState(""); const handleChangeText = useCallback( (text: string) => { onChangeText?.(text); setText(text); }, [onChangeText], ); const [hovered, setHovered] = useState(false); const handleMouseEnter = useCallback( (event: NativeSyntheticEvent<TargetedEvent>) => { onMouseEnter?.(event); setHovered(true); }, [onMouseEnter], ); const handleMouseLeave = useCallback( (event: NativeSyntheticEvent<TargetedEvent>) => { onMouseLeave?.(event); setHovered(false); }, [onMouseLeave], ); const [focused, setFocused] = useState(false); const handleFocus = useCallback( (event: NativeSyntheticEvent<TextInputFocusEventData>) => { onFocus?.(event); setFocused(true); }, [onFocus], ); const handleBlur = useCallback( (event: NativeSyntheticEvent<TextInputFocusEventData>) => { onBlur?.(event); setFocused(false); }, [onBlur], ); const focusAnimation = useMemo(() => new Animated.Value(0), []); useEffect(() => { Animated.timing(focusAnimation, { toValue: focused ? 1 : 0, duration: 200, easing: Easing.out(Easing.ease), useNativeDriver: false, }).start(); }, [focused]); const active = useMemo(() => focused || text.length > 0, [focused, text]); const activeAnimation = useMemo(() => new Animated.Value(active ? 1 : 0), []); useEffect(() => { Animated.timing(activeAnimation, { toValue: active ? 1 : 0, duration: 200, easing: Easing.out(Easing.ease), useNativeDriver: false, }).start(); }, [active]); const styles = useStyles( () => ({ inputContainer: { flexDirection: "row", backgroundColor: variant === "filled" ? focused ? surfaceScale(0.14).hex() : hovered ? surfaceScale(0.08).hex() : surfaceScale(0.04).hex() : variant === "outlined" ? surfaceScale(0).hex() : undefined, }, input: { flex: 1, minHeight: variant === "standard" ? 48 : 56, paddingStart: !!leadingNode ? 12 : variant === "standard" ? 0 : 16, paddingEnd: !!trailingNode ? 12 : variant === "standard" ? 0 : 16, color: surfaceScale(0.87).hex(), }, leading: { justifyContent: "center", alignItems: "center", width: 24, height: 24, marginStart: variant === "standard" ? 0 : 12, marginVertical: variant === "standard" ? 12 : 16, }, trailing: { justifyContent: "center", alignItems: "center", width: 24, height: 24, marginEnd: variant === "standard" ? 0 : 12, marginVertical: variant === "standard" ? 12 : 16, }, underline: { position: "absolute", start: 0, end: 0, bottom: 0, height: 1, backgroundColor: hovered ? surfaceScale(0.87).hex() : surfaceScale(0.42).hex(), }, underlineFocused: { position: "absolute", start: 0, end: 0, bottom: 0, height: 2, backgroundColor: palette.main, }, outline: { borderWidth: focused ? 2 : 1, borderColor: focused ? palette.main : hovered ? surfaceScale(0.87).hex() : surfaceScale(0.42).hex(), }, outlineLabelGap: { position: "absolute", top: 0, start: -4, end: -4, height: focused ? 2 : 1, backgroundColor: surfaceScale(0).hex(), }, labelContainer: { justifyContent: "center", position: "absolute", top: 0, start: variant === "standard" ? (!!leadingNode ? 36 : 0) : !!leadingNode ? 48 : 16, height: variant === "standard" ? 48 : 56, }, helperText: { color: surfaceScale(0.6).hex(), }, }), [palette.main, surfaceScale, !!leadingNode, !!trailingNode, variant, focused, hovered], ); return ( <View style={[style]}> <View style={[ styles.inputContainer, variant !== "standard" && theme.shapes.medium, variant === "filled" && { borderBottomStartRadius: 0, borderBottomEndRadius: 0 }, inputContainerStyle, ]} > {leadingNode && <View style={[styles.leading, leadingContainerStyle]}>{leadingNode}</View>} <RNTextInput ref={ref} style={[ styles.input, theme.typography.subtitle1, { paddingTop: variant === "filled" && label ? 18 : 0 }, inputStyle, ]} placeholder={label ? (focused ? placeholder : undefined) : placeholder} selectionColor={palette.main} placeholderTextColor={surfaceScale(0.4).hex()} onChangeText={handleChangeText} onFocus={handleFocus} onBlur={handleBlur} {...({ onMouseEnter: handleMouseEnter, onMouseLeave: handleMouseLeave, ...rest } as any)} /> {trailingNode && <View style={[styles.trailing, trailingContainerStyle]}>{trailingNode}</View>} {(variant === "filled" || variant === "standard") && ( <> <View style={[styles.underline]} pointerEvents="none" /> <Animated.View style={[styles.underlineFocused, { transform: [{ scaleX: focusAnimation }] }]} pointerEvents="none" /> </> )} {variant === "outlined" && ( <View style={[StyleSheet.absoluteFill, theme.shapes.medium, styles.outline]} pointerEvents="none" /> )} {label && ( <View style={[styles.labelContainer]} pointerEvents="none"> {variant === "outlined" && ( <Animated.View style={[styles.outlineLabelGap, { transform: [{ scaleX: activeAnimation }] }]} /> )} <Animated.Text style={[ theme.typography.subtitle1, { color: focusAnimation.interpolate({ inputRange: [0, 1], outputRange: [surfaceScale(0.87).hex(), palette.main], }), fontSize: activeAnimation.interpolate({ inputRange: [0, 1], outputRange: [theme.typography.subtitle1.fontSize ?? 16, 12], }), transform: [ { translateY: activeAnimation.interpolate({ inputRange: [0, 1], outputRange: [0, variant === "filled" ? -12 : variant === "outlined" ? -28 : -24], }), }, ], }, ]} > {label} </Animated.Text> </View> )} </View> <View style={{ marginTop: 4, marginHorizontal: 16 }}> {helperText && ( <Text variant="body2" style={[styles.helperText]}> {helperText} </Text> )} </View> </View> ); }); export default TextInput;
the_stack
import {BrowserWindow, ipcMain} from 'electron'; import ArduinoCompiler from "../compiler/compiler"; import {ArduinoSerial} from "./arduinoSerial"; import * as fs from "fs"; import * as path from "path"; import * as util from "../compiler/util"; import logger from "./logger"; import messenger, {MessageType} from "./messenger"; import {parseProps} from "../compiler/util"; export default class ArduinoCompile { private arduinoSerial: ArduinoSerial; private running: boolean = false; private window: BrowserWindow; private cancel: boolean = false; public constructor(arduinoSerial: ArduinoSerial){ this.arduinoSerial = arduinoSerial; ipcMain.on("stop", (event, args) => { if(!this.running){ this.send('runprogress', { stage: 'DONE' }); return; } this.cancel = true; logger.log("Force stopping compile/upload"); ArduinoCompiler.stopDaemon(true); this.running = false; const context = this; setTimeout(() => { ArduinoCompiler.startDaemon() .then(() => { logger.log("Daemon started"); console.log('Daemon started'); }) .catch((error) => { console.log(error); logger.log("Daemon start error", error); messenger.reportFatal(); }); context.send('runprogress', { stage: 'DONE', cancel: true }); this.cancel = false; }, 1000); }); ipcMain.on("run", (event, args) => { if(this.cancel) return; const stats = ArduinoCompiler.getDaemon(); if(!stats.connected){ this.send('runprogress', { stage: 'DONE' }); if(stats.connecting){ messenger.report(MessageType.DAEMON, [ "Arduino daemon still loading. Please wait a bit and then try again." ], [{ title: "Ok", action: "installstate" }]); }else{ messenger.reportFatal(); //this.send("runprogress", { stage: "DONE", error: "Arduino daemon couldn't load. Please restart CircuitMess.", fatal: true}); } return; } if(this.running){ this.send("runprogress", { stage: "DONE", running: true }); messenger.report(MessageType.RUN, [ "A compile operation is already running. Please wait or restart CircuitBlocks." ], [{ title: "Ok" }]); return; } this.running = true; const code = args.code; const minimal = args.minimal != undefined && args.minimal; this.send("runprogress", { stage: "COMPILE", progress: 0 }); this.compile(code, (binary) => { this.send('runprogress', { stage: 'UPLOAD', progress: 0 }); this.upload(binary, args.device,() => { this.send('runprogress', { stage: 'DONE' }); this.running = false; }); }, args.device, undefined, minimal); }); ipcMain.on("export", (event, args) => { if(this.cancel) return; const stats = ArduinoCompiler.getDaemon(); if(!stats.connected){ if(stats.connecting){ messenger.report(MessageType.DAEMON, [ "Arduino daemon still loading. Please wait a bit and then try again." ], [{ title: "Ok", action: "installstate" }]); //this.send("runprogress", { stage: "DONE", error: "Arduino daemon still loading. Please try a bit later."}); }else{ messenger.reportFatal(); //this.send("runprogress", { stage: "DONE", error: "Arduino daemon couldn't load. Please restart CircuitMess.", fatal: true}); } return; } if(this.running){ this.send("runprogress", { stage: "DONE", running: true }); messenger.report(MessageType.RUN, [ "A compile operation is already running. Please wait or restart CircuitBlocks." ], [{ title: "Ok" }]); return; } this.running = true; const { code } = args; let exportPath = args.path; const parsed = path.parse(exportPath); if(parsed.ext.toLowerCase() != ".bin"){ exportPath += ".bin"; } const minimal = args.minimal != undefined && args.minimal; this.send("runprogress", { error: null, stage: "EXPORT", progress: 0 }); this.compile(code, (binary) => { fs.copyFile(binary, exportPath, error => { if(error){ logger.log("Export copy error", error); this.send('runprogress', { stage: 'DONE', progress: 0 }); messenger.report(MessageType.EXPORT, [ "Error saving compiled binary. Make sure you have the permissions to write to the specified file." ], [{ title: "Ok" }]) }else{ this.send('runprogress', { stage: 'DONE', progress: 0 }); messenger.report(MessageType.EXPORT, [ "Export successful" ], [{ title: "Ok" }]); } this.running = false; }); }, args.device, "EXPORT", minimal); }); ipcMain.on("firmware", (event, args) => { if(this.running){ //this.send("installstate", { state: { stage: "DONE", error: "Firmware is already uploading", restoring: true } }); messenger.report(MessageType.EXPORT, [ "Firmware is already uploading" ], [{ title: "Ok" }]); return; } const stats = ArduinoCompiler.getDaemon(); if(!stats.connected && stats.connecting){ messenger.report(MessageType.DAEMON, [ "Arduino daemon still loading. Please wait a bit and then try again." ], [{ title: "Ok" }]); //this.send("installstate", { state: { stage: "0%", error: "Arduino daemon still loading. Please wait a bit and then try again.", restoring: true } }); return; } const deviceParts = args.device.split(":"); const platform = deviceParts[1]; const device = deviceParts[2]; let firmware = ""; const hardwareDir = path.join(ArduinoCompiler.getInstallInfo().local, "packages", "cm", "hardware", platform); let newest = ""; fs.readdirSync(hardwareDir).forEach((version) => { const versionDir = path.join(hardwareDir, version); if(!fs.statSync(versionDir).isDirectory()) return; if(newest == "" || util.isNewer(version, newest)){ newest = version; } }); const platformDir = path.join(hardwareDir, newest); /*if(device == "ringo"){ firmware = path.join(platformDir, "firmware", "firmware.bin"); }else{*/ const boards = parseProps(fs.readFileSync(path.join(platformDir, "boards.txt"), { encoding: "utf8" })); const firmwarePath = boards[device + ".bootloader.tool.firmware"]; firmware = path.join(platformDir, "firmwares", firmwarePath); //} console.log("Uploading", firmware); this.running = true; this.send("installstate", { state: { stage: "0%", restoring: true } }); this.upload(firmware, args.device, () => { this.send("installstate", { state: { stage: "DONE" } }); this.running = false; }, (progress => { this.send("installstate", { state: { stage: "" + progress + "%", restoring: true } }); }), (error) => { this.send("installstate", { state: { stage: "DONE", restoring: true } }); messenger.report(MessageType.RESTORE, [ error ], [{ title: "Ok" }]); this.running = false; }); }); } private send(event, args){ if(!this.window) return; this.window.webContents.send(event, args); } public setWindow(window: BrowserWindow){ this.window = window; } private compile(code: string, callback: (binary) => void, device: string, stage?: string, minimal?: boolean){ if(!stage) stage = "COMPILE"; ArduinoCompiler.compile(code, device, progress => this.send('runprogress', { stage: stage, progress }), minimal) .then((data) => { callback(data.binary); }).catch(error => { if(this.cancel){ return; } console.log(error); messenger.report(MessageType.RUN, [ "Compile error. Check your code then try again." ], [{ title: "Ok" }]); this.send('runprogress', { stage: 'DONE' }); this.running = false; } ); } private upload(binary: string, device: string, callback: () => void, pCallback?: (progress) => void, eCallback?: (error) => void){ if(this.arduinoSerial.getPort() == undefined){ logger.log("Upload error: Device disconnected"); console.log(new Error("Device disconnected")); if(eCallback){ eCallback("Upload error. Check your device then try again."); }else{ this.send('runprogress', { stage: 'DONE' }); messenger.report(MessageType.RUN, [ "Upload error. Check your device then try again." ], [{ title: "Ok" }]); } return; } ArduinoCompiler.uploadBinary(binary, this.arduinoSerial.getPort().comName, device, pCallback ? pCallback : progress => this.send("runprogress", { stage: "UPLOAD", progress })) .then(() => { callback(); }) .catch(error => { if(this.cancel){ return; } console.log(error); if(eCallback){ eCallback("Upload error. Check your device then try again.") }else{ this.send('runprogress', { stage: 'DONE' }); messenger.report(MessageType.RUN, [ "Upload error. Check your device then try again." ], [{ title: "Ok" }]); } this.running = false; }); } }
the_stack
import { Button, Checkbox, Classes, Colors, FormGroup, HTMLSelect, InputGroup, Intent, TextArea, } from '@blueprintjs/core' import copy from 'copy-to-clipboard' import _ from 'lodash' import * as React from 'react' import FlexLayout from 'components/FlexLayout' import Key from 'constants/key' import { ToggleableProps } from 'constants/toggleable' import Dialog from 'containers/Dialog' import StrawPoll, { StrawPollDuplicationStrategy } from 'libs/StrawPoll' import Toaster from 'libs/Toaster' import styled from 'styled' /** * Options component. */ const Options = styled(TextArea)` resize: none; width: 100%; &.${Classes.INPUT} { height: 200px; } ` /** * PollCheckbox component. */ const PollCheckbox = styled(Checkbox)` flex-shrink: 0; margin-right: 20px; margin-top: 6px; ` /** * Select component. */ const Select = styled(HTMLSelect)` flex-grow: 1; ` /** * Error component. */ const Error = styled.span` color: ${Colors.RED3}; font-size: 0.8rem; font-weight: bold; line-height: 16px; ` /** * Controls component. */ const Controls = styled.div` align-items: center; display: flex; justify-content: flex-end; & > button { margin-left: 10px; } ` /** * RegExp used to identify options. */ const OptionsRegExp = /\r?\n/g /** * Form state. */ enum FormState { Done, Invalid, Processing, Valid, } /** * Straw Poll duplication check strategies mapping. */ export const DuplicationStrategyMap = { 'Cookie Duplication check': StrawPollDuplicationStrategy.Cookie, 'IP duplication check': StrawPollDuplicationStrategy.Ip, 'No duplication check': StrawPollDuplicationStrategy.None, } /** * React State. */ const initialState = { captcha: false, duplication: StrawPollDuplicationStrategy.Ip as StrawPollDuplicationStrategy, formState: FormState.Invalid as FormState, multipleAnswers: false, options: '', optionsError: undefined as Optional<string>, optionsIntent: Intent.NONE as Intent, question: '', questionIntent: Intent.NONE as Intent, url: undefined as Optional<string>, } type State = Readonly<typeof initialState> /** * PollEditor Component. */ export default class PollEditor extends React.Component<Props, State> { public state: State = initialState private question: HTMLInputElement | null = null /** * Lifecycle: componentDidUpdate. * @param prevProps - The previous props. * @param prevState - The previous state. */ public componentDidUpdate(prevProps: Props) { requestAnimationFrame(() => { if (!prevProps.visible && this.props.visible && !_.isNil(this.question)) { this.question.focus() } }) } /** * Renders the component. * @return Element to render. */ public render() { const { visible } = this.props const { captcha, duplication, formState, multipleAnswers, options, optionsError, optionsIntent, question, questionIntent, } = this.state const questionLabelInfo = ( <> (required) {!_.isNil(optionsError) && ( <> {' '} - <Error>{optionsError}</Error> </> )} </> ) const isDone = formState === FormState.Done const isProcessing = formState === FormState.Processing const inputDisabled = isProcessing || isDone return ( <Dialog isOpen={visible} onClose={this.toggle} icon="horizontal-bar-chart" title="New Straw Poll"> <div className={Classes.DIALOG_BODY}> <FormGroup label="Question" labelFor="question-input" labelInfo="(required)" disabled={inputDisabled}> <InputGroup placeholder="Type your question here…" inputRef={this.setQuestionElementRef} onKeyDown={this.onKeyDownQuestion} onChange={this.onChangeQuestion} disabled={inputDisabled} intent={questionIntent} id="question-input" value={question} /> </FormGroup> <FormGroup label="Options" labelFor="options-input" labelInfo={questionLabelInfo} disabled={inputDisabled}> <Options placeholder="Type your options here with each line being an option…" onKeyDown={this.onKeyDownOptions} onChange={this.onChangeOptions} disabled={inputDisabled} intent={optionsIntent} id="options-input" value={options} /> </FormGroup> <FlexLayout> <PollCheckbox onChange={this.onChangeMultipleAnswers} checked={multipleAnswers} disabled={inputDisabled} label="Multiple answers" /> <PollCheckbox onChange={this.onChangeCaptcha} disabled={inputDisabled} checked={captcha} label="Captcha" /> <Select options={_.keys(DuplicationStrategyMap)} onChange={this.onChangeDuplication} disabled={inputDisabled} value={_.head( _.filter( _.keys(DuplicationStrategyMap) as (keyof typeof DuplicationStrategyMap)[], (key) => DuplicationStrategyMap[key] === duplication ) )} fill /> </FlexLayout> </div> <Controls className={Classes.DIALOG_FOOTER}> <Button text="Close" disabled={isProcessing} onClick={this.toggle} /> <Button text={isDone ? 'Copy URL & Close' : 'Create'} rightIcon={isDone ? 'clipboard' : 'plus'} intent={isDone ? Intent.SUCCESS : Intent.PRIMARY} onClick={this.createOrCopy} disabled={formState !== FormState.Valid && formState !== FormState.Done} loading={isProcessing} /> </Controls> </Dialog> ) } /** * Triggered when the create or copy button is pressed. */ private createOrCopy = async () => { const { formState, url } = this.state if (formState === FormState.Done && !_.isNil(url)) { copy(url) this.toggle() } else if (formState === FormState.Valid) { this.setState(() => ({ formState: FormState.Processing })) const { captcha, duplication, multipleAnswers, options, question } = this.state try { const poll = await StrawPoll.createPoll( question, this.getOptionsValues(options), multipleAnswers, duplication, captcha ) this.setState(() => ({ formState: FormState.Done, url: `https://strawpoll.me/${poll.id}` })) Toaster.show({ action: { onClick: this.createOrCopy, text: 'Copy & Close' }, icon: 'tick', intent: Intent.SUCCESS, message: 'Poll created!', }) } catch { this.setState(() => ({ formState: FormState.Valid })) Toaster.show({ icon: 'error', intent: Intent.DANGER, message: 'Something went wrong while creating the poll!', }) } } } /** * Triggered when toggling the modal. */ private toggle = () => { if (this.state.formState === FormState.Done) { this.setState(initialState) Toaster.clear() } this.props.toggle() } /** * Triggered when a key is pressed down in the question input. * @param event - The associated event. */ private onKeyDownQuestion = (event: React.KeyboardEvent<HTMLInputElement>) => { if (event.key === Key.Enter && event.altKey) { this.createOrCopy() } } /** * Triggered when a key is pressed down in the options textarea. * @param event - The associated event. */ private onKeyDownOptions = (event: React.KeyboardEvent<HTMLTextAreaElement>) => { if (event.key === Key.Enter && event.altKey) { this.createOrCopy() } } /** * Triggered when the question is modified. * @param event - The associated event. */ private onChangeQuestion = (event: React.FormEvent<HTMLInputElement>) => { const question = event.currentTarget.value this.setState(({ options }) => ({ question, ...this.getValidationState(question, options) })) } /** * Triggered when the options are modified. * @param event - The associated event. */ private onChangeOptions = (event: React.FormEvent<HTMLTextAreaElement>) => { const options = event.currentTarget.value this.setState(({ question }) => ({ options, ...this.getValidationState(question, options) })) } /** * Triggered when the multiple answers checkbox is modified. * @param event - The associated event. */ private onChangeMultipleAnswers = (event: React.FormEvent<HTMLInputElement>) => { const checked = event.currentTarget.checked this.setState(() => ({ multipleAnswers: checked })) } /** * Triggered when the captcha checkbox is modified. * @param event - The associated event. */ private onChangeCaptcha = (event: React.FormEvent<HTMLInputElement>) => { const checked = event.currentTarget.checked this.setState(() => ({ captcha: checked })) } /** * Triggered when the duplication method is modified. * @param event - The associated event. */ private onChangeDuplication = (event: React.FormEvent<HTMLSelectElement>) => { const duplication = event.currentTarget.value as keyof typeof DuplicationStrategyMap this.setState(() => ({ duplication: DuplicationStrategyMap[duplication] })) } /** * Returns the validation state. * @param question - The question to validate. * @param options - The options to validate. * @return The validation state. */ private getValidationState(question: string, options: string) { let optionsError let optionsIntent: Intent = Intent.NONE const questionIntent = question.length > 0 ? Intent.SUCCESS : Intent.NONE let formState: FormState = FormState.Invalid const values = this.getOptionsValues(options) if (options.length > 0) { if (values.length < 2) { optionsIntent = Intent.DANGER optionsError = 'You need at least 2 options.' } else if (values.length > 30) { optionsIntent = Intent.DANGER optionsError = 'You need at most 30 options.' } else { optionsIntent = Intent.SUCCESS } } if (optionsIntent === Intent.SUCCESS && question.length > 0) { formState = FormState.Valid } return { optionsError, optionsIntent, questionIntent, formState } } /** * Sets the question input ref. * @param ref - The reference to the inner input element. */ private setQuestionElementRef = (ref: HTMLInputElement | null) => { this.question = ref } /** * Returns the options values. * @param options - The options. * @return The options values. */ private getOptionsValues(options: string) { return _.filter( _.map(options.split(OptionsRegExp), (value) => value.trim()), (value) => value.length > 0 ) } } /** * React Props. */ type Props = ToggleableProps
the_stack
import { BufferGeometry, Euler, Object3D, Vector3, Color, Mesh, Group, Material, MeshPhongMaterial, Plane, DoubleSide, } from "three"; import { STLExporter } from "three/examples/jsm/exporters/STLExporter"; import { GLTFExporter } from "three/examples/jsm/exporters/GLTFExporter"; import { defaultMaterialSettings } from "./constants/materials"; import FileSaver from "./FileSaver"; import NaiveSurfaceNets from "./NaiveSurfaceNets.js"; import MarchingCubes from "./MarchingCubes"; import Volume from "./Volume"; import { Bounds } from "./types.js"; import { ThreeJsPanel } from "./ThreeJsPanel.js"; // this cutoff is chosen to have a small buffer of values before the object is treated // as transparent for gpu blending and depth testing. const ALPHA_THRESHOLD = 0.9; export default class MeshVolume { private volume: Volume; private meshRoot: Object3D; private meshPivot: Group; private meshrep: (Group | null)[]; private channelColors: [number, number, number][]; private channelOpacities: number[]; private bounds: Bounds; private scale: Vector3; constructor(volume: Volume) { // need? this.volume = volume; this.meshRoot = new Object3D(); //create an empty container this.meshRoot.name = "Mesh Surface Group"; // handle transform ordering for giving the meshroot a rotation about a pivot point this.meshPivot = new Group(); this.meshPivot.name = "MeshContainerNode"; this.meshPivot.add(this.meshRoot); this.meshrep = []; this.channelColors = []; this.channelOpacities = []; this.scale = new Vector3(1, 1, 1); this.bounds = { bmin: new Vector3(-0.5, -0.5, -0.5), bmax: new Vector3(0.5, 0.5, 0.5), }; } cleanup(): void { for (let i = 0; i < this.volume.num_channels; ++i) { this.destroyIsosurface(i); } } setVisible(isVisible: boolean): void { this.meshRoot.visible = isVisible; } doRender(_canvas: ThreeJsPanel): void { // no op } get3dObject(): Group { return this.meshPivot; } onChannelData(batch: number[]): void { for (let j = 0; j < batch.length; ++j) { const idx = batch[j]; // if an isosurface was created before the channel data arrived, we need to re-calculate it now. if (this.meshrep[idx]) { const isovalue = this.getIsovalue(idx); this.updateIsovalue(idx, isovalue === undefined ? 127 : isovalue); } } } setScale(scale: Vector3): void { this.scale = scale; this.meshRoot.scale.copy(new Vector3(0.5 * scale.x, 0.5 * scale.y, 0.5 * scale.z)); } setFlipAxes(flipX: number, flipY: number, flipZ: number): void { this.meshRoot.scale.copy( new Vector3(0.5 * this.scale.x * flipX, 0.5 * this.scale.y * flipY, 0.5 * this.scale.z * flipZ) ); } setTranslation(vec3xyz: Vector3): void { this.meshPivot.position.copy(vec3xyz); } setRotation(eulerXYZ: Euler): void { this.meshPivot.rotation.copy(eulerXYZ); this.updateClipFromBounds(); } setResolution(_x: number, _y: number): void { // no op } setOrthoThickness(_value: number): void { // no op } setAxisClip(axis: number, minval: number, maxval: number, _isOrthoAxis: boolean): void { this.bounds.bmax[axis] = maxval; this.bounds.bmin[axis] = minval; this.updateClipFromBounds(); } ////////////////////////////// updateMeshColors(channelColors: [number, number, number][]): void { // stash values here for later changes this.channelColors = channelColors; // update existing meshes for (let i = 0; i < this.volume.num_channels; ++i) { const meshrep = this.meshrep[i]; if (meshrep) { const rgb = channelColors[i]; const c = (rgb[0] << 16) | (rgb[1] << 8) | rgb[2]; meshrep.traverse(function (child) { if (child instanceof Mesh) { child.material.color = new Color(c); } }); } } } createMaterialForChannel(rgb: [number, number, number], alpha: number, _transp: boolean): Material { const col = (rgb[0] << 16) | (rgb[1] << 8) | rgb[2]; const material = new MeshPhongMaterial({ color: new Color(col), shininess: defaultMaterialSettings.shininess, specular: new Color(defaultMaterialSettings.specularColor), opacity: alpha, transparent: alpha < ALPHA_THRESHOLD, side: DoubleSide, }); return material; } createMeshForChannel( channelIndex: number, colorrgb: [number, number, number], isovalue: number, alpha: number, transp: boolean ): Group { // note that if isovalue out of range, this will return an empty array. const geometries = this.generateIsosurfaceGeometry(channelIndex, isovalue); const material = this.createMaterialForChannel(colorrgb, alpha, transp); const theObject = new Group(); theObject.name = "Channel" + channelIndex; theObject.userData = { isovalue: isovalue }; // proper scaling will be done in parent object for (let i = 0; i < geometries.length; ++i) { const mesh = new Mesh(geometries[i], material); theObject.add(mesh); } return theObject; } updateIsovalue(channel: number, value: number): void { const meshrep = this.meshrep[channel]; if (!meshrep) { return; } if (meshrep.userData.isovalue === value) { return; } // find the current isosurface opacity and color. const opacity = this.channelOpacities[channel]; const color = this.channelColors[channel]; this.destroyIsosurface(channel); const newmeshrep = this.createMeshForChannel(channel, color, value, opacity, false); this.meshrep[channel] = newmeshrep; this.meshRoot.add(newmeshrep); } getIsovalue(channel: number): number | undefined { const meshrep = this.meshrep[channel]; if (!meshrep) { return undefined; } return meshrep.userData.isovalue; } updateClipRegion(xmin: number, xmax: number, ymin: number, ymax: number, zmin: number, zmax: number): void { // incoming values expected to be between 0 and 1. // I shift them here to be between -0.5 and 0.5 this.bounds = { bmin: new Vector3(xmin - 0.5, ymin - 0.5, zmin - 0.5), bmax: new Vector3(xmax - 0.5, ymax - 0.5, zmax - 0.5), }; this.updateClipFromBounds(); } updateClipFromBounds(): void { const xmin = this.bounds.bmin.x; const ymin = this.bounds.bmin.y; const zmin = this.bounds.bmin.z; const xmax = this.bounds.bmax.x; const ymax = this.bounds.bmax.y; const zmax = this.bounds.bmax.z; const euler = this.meshPivot.rotation; for (let channel = 0; channel < this.meshrep.length; ++channel) { const meshrep = this.meshrep[channel]; if (!meshrep) { continue; } const planes: Plane[] = []; // up to 6 planes. if (xmin > -0.5) { planes.push(new Plane(new Vector3(1, 0, 0).applyEuler(euler), this.meshRoot.position.x + -xmin * this.scale.x)); } if (ymin > -0.5) { planes.push(new Plane(new Vector3(0, 1, 0).applyEuler(euler), this.meshRoot.position.y + -ymin * this.scale.y)); } if (zmin > -0.5) { planes.push(new Plane(new Vector3(0, 0, 1).applyEuler(euler), this.meshRoot.position.z + -zmin * this.scale.z)); } if (xmax < 0.5) { planes.push(new Plane(new Vector3(-1, 0, 0).applyEuler(euler), this.meshRoot.position.x + xmax * this.scale.x)); } if (ymax < 0.5) { planes.push(new Plane(new Vector3(0, -1, 0).applyEuler(euler), this.meshRoot.position.y + ymax * this.scale.y)); } if (zmax < 0.5) { planes.push(new Plane(new Vector3(0, 0, -1).applyEuler(euler), this.meshRoot.position.z + zmax * this.scale.z)); } meshrep.traverse(function (child) { if (child instanceof Mesh) { child.material.clippingPlanes = planes; } }); } } updateOpacity(channel: number, value: number): void { this.channelOpacities[channel] = value; const meshrep = this.meshrep[channel]; if (!meshrep) { return; } meshrep.traverse(function (child) { if (child instanceof Mesh) { child.material.opacity = value; child.material.transparent = value < ALPHA_THRESHOLD; //child.material.depthWrite = !child.material.transparent; } }); } hasIsosurface(channel: number): boolean { return !!this.meshrep[channel]; } createIsosurface( channel: number, color: [number, number, number], value: number, alpha: number, transp: boolean ): void { if (!this.meshrep[channel]) { if (value === undefined) { // 127 is half of the intensity range 0..255 value = 127; } if (alpha === undefined) { // 1.0 indicates full opacity, non-transparent alpha = 1.0; } if (transp === undefined) { transp = alpha < ALPHA_THRESHOLD; } const meshrep = this.createMeshForChannel(channel, color, value, alpha, transp); this.meshrep[channel] = meshrep; this.channelOpacities[channel] = alpha; this.channelColors[channel] = color; // note we are not removing any prior mesh reps for this channel this.meshRoot.add(meshrep); } } destroyIsosurface(channel: number): void { const meshrep = this.meshrep[channel]; if (meshrep) { this.meshRoot.remove(meshrep); meshrep.traverse(function (child) { if (child instanceof Mesh) { child.material.dispose(); child.geometry.dispose(); } }); this.meshrep[channel] = null; } } saveChannelIsosurface(channelIndex: number, type: string, namePrefix: string): void { const meshrep = this.meshrep[channelIndex]; if (!meshrep) { return; } if (type === "STL") { this.exportSTL(meshrep, namePrefix + "_" + this.volume.channel_names[channelIndex]); } else if (type === "GLTF") { // temporarily set other meshreps to invisible const prevviz: boolean[] = []; for (let i = 0; i < this.meshrep.length; ++i) { const meshrepi = this.meshrep[i]; if (meshrepi) { prevviz[i] = meshrepi.visible; meshrepi.visible = i === channelIndex; } } this.exportGLTF(this.meshRoot, namePrefix + "_" + this.volume.channel_names[channelIndex]); for (let i = 0; i < this.meshrep.length; ++i) { const meshrepi = this.meshrep[i]; if (meshrepi) { meshrepi.visible = prevviz[i]; } } } } exportSTL(input: Object3D, fname: string): void { const ex = new STLExporter(); const output = ex.parse(input, { binary: true }); // STLExporter's typing shows that it returns string // but this is not the case when binary=true. FileSaver.saveBinary((output as unknown as DataView).buffer, fname + ".stl"); } // takes a scene or object or array of scenes or objects or both! exportGLTF(input: Object3D, fname: string): void { const gltfExporter = new GLTFExporter(); const options = { // transforms as translate rotate scale? trs: false, onlyVisible: true, truncateDrawRange: true, binary: true, forceIndices: false, forcePowerOfTwoTextures: true, }; gltfExporter.parse( input, function (result) { if (result instanceof ArrayBuffer) { FileSaver.saveArrayBuffer(result, fname + ".glb"); } else { const output = JSON.stringify(result, null, 2); FileSaver.saveString(output, fname + ".gltf"); } }, options ); } generateIsosurfaceGeometry(channelIndex: number, isovalue: number): BufferGeometry[] { if (!this.volume) { return []; } const volumeData = this.volume.channels[channelIndex].volumeData; const marchingcubes = true; if (marchingcubes) { const effect = new MarchingCubes( [this.volume.x, this.volume.y, this.volume.z], new Material(), false, false, true, volumeData ); effect.position.copy(this.meshRoot.position); effect.scale.set(0.5 * this.scale.x, 0.5 * this.scale.y, 0.5 * this.scale.z); effect.isovalue = isovalue; const geometries = effect.generateGeometry(); // TODO: weld vertices and recompute normals if MarchingCubes results in excessive coincident verts // for (var i = 0; i < geometries.length; ++i) { // var g = new THREE.Geometry().fromBufferGeometry(geometries[i]); // g.mergeVertices(); // geometries[i] = new THREE.BufferGeometry().fromGeometry(g); // geometries[i].computeVertexNormals(); // } return geometries || []; } else { const result = NaiveSurfaceNets.surfaceNets(volumeData, [this.volume.x, this.volume.y, this.volume.z], isovalue); return NaiveSurfaceNets.constructTHREEGeometry(result); } } }
the_stack
import * as React from "react"; import * as monaco from "monaco-editor/esm/vs/editor/editor.api"; import { loadSteps, makeFEOperationLog } from "./api"; import { selectAndTraverse } from "./actions"; import TraversalStep from "./TraversalStep"; import { ErrorBoundary } from "./ErrorBoundary"; import "./CodeViewer.scss"; // monaco.languages.registerHoverProvider("javascript", { // provideHover: function(model, position) { // let ret: monaco.languages.Hover; // // if (position.lineNumber == 3) { // // ret = { // // range: new monaco.Range(1, 1, 1, 4), // // contents: [{ value: "a" }, { value: "b" }] // // }; // // } // return ret!; // the ! tells the typescript compiler to shut up // } // }); function getCodeString(loc) { const lines = window["fileContent"].split("\n"); if (loc.start.line !== loc.end.line) { return "todo"; } let line = lines[loc.start.line - 1]; if (!line) { console.log("failed to get code string"); return ""; } return line.slice(loc.start.column, loc.end.column); } export class App2 extends React.Component { state = { info: [], files: [] }; async componentDidMount() { this.setState({ files: await fetch("/xyzviewer/fileInfo").then((r) => r.json()), }); } render() { window["setLocs"] = async (locs) => { const r = await Promise.all( locs.map((loc) => { return fetch("/xyzviewer/trackingDataForLoc/" + loc.key) .then((r) => r.json()) .then((res) => { return { logs: res, loc: loc, }; }); }) ); this._random = Math.random(); if (r && r[0] && r[0].logs && r[0].logs[0]) { selectAndTraverse(r[0].logs[0].value.index, 0); } this.setState({ info: r }); }; console.log({ monaco, r: this._random }); const { App } = this.props; function selectFile(f) {} console.log(this.props); return ( <div style={{ display: "flex" }}> <div> <div style={{ height: "40vh", overflow: "auto" }}> <FileSelector files={this.state.files} fileSearch={this.props.fileSearch} selectFile={(f) => this.props.setQueryParam("selectedFile", f.fileKey) } updateFileSearch={(value) => { this.props.setQueryParam("fileSearch", value); }} ></FileSelector> </div> <FileView fileKey={this.props.selectedFile} key={this.props.selectedFile} ></FileView> </div> <div style={{ flexGrow: 1, width: "60vw", overflow: "auto", }} > <div style={{ height: "40vh", overflow: "auto" }}> {this.state.info.map((info, i) => { return ( <InfoItem info={info} key={this._random + "_" + i}></InfoItem> ); })} </div> <div style={{ height: "60vh", overflow: "auto" }}> <App></App> </div> </div> </div> ); } } class FileView extends React.Component { state = { loadingFile: true, }; componentDidMount() { fetch("/xyzviewer/fileDetails/" + this.props.fileKey) .then((r) => r.json()) .then(async (r) => { this.setState({ loadingFile: false }); if (window["editor"]) { window["editor"].dispose(); } window["editor"] = monaco.editor.create( document.getElementById("container"), { value: r["fileContent"], language: "javascript", readOnly: true, } ); window["editor"].onDidChangeCursorPosition(function ({ position }) { console.log(position.lineNumber); let matchingLocs = window["locs"].filter((l) => { return ( l.start.line <= position.lineNumber && l.end.line >= position.lineNumber && (l.start.line !== l.end.line || (l.start.column <= position.column && l.end.column >= position.column)) ); }); // debugger; window.setLocs(matchingLocs); console.log(matchingLocs); }); window["locs"] = r.locs.filter((l) => l.start && l.end); window["fileContent"] = r.fileContent; let d = []; window["locs"].forEach((loc) => { if (loc.start.line !== loc.end.line) { console.log("ignoring multiline loc for now"); d.push({ range: new monaco.Range( loc.start.line, loc.start.column, loc.start.line, loc.start.column + 2 ), options: { isWholeLine: false, inlineClassName: "myInlineDecoration-multiline-start", }, }); return; } d.push( { range: new monaco.Range( loc.start.line, loc.start.column + 1, loc.end.line, loc.end.column + 1 ), options: { isWholeLine: false, inlineClassName: loc.logCount > 0 ? loc.logCount > 5 ? "myInlineDecoration-hasMany" : "myInlineDecoration-has" : "myInlineDecoration-none", // linesDecorationsClassName: "myLineDecoration" }, } // { // range: new monaco.Range(7, 1, 7, 24), // options: { inlineClassName: "myInlineDecoration" } // } ); }); console.log(d); var decorations = window["editor"].deltaDecorations([], d); }); } render() { return ( <div> {this.state.loadingFile && <div>Loading...</div>} <div id="container" style={{ width: 800, height: "55vh", border: "1px solid grey", }} ></div> </div> ); } } class FileSelector extends React.Component { render() { return ( <div> <input type="text" onChange={(e) => this.props.updateFileSearch(e.target.value)} value={this.props.fileSearch} ></input> {this.props.files // rough filter for now .filter( (f) => f.url.includes(".js") && !f.url.includes(".json") && !f.url.includes("compileInBrowser.js") && !f.url.includes("babel-standalone.js") ) .filter((f) => { if (!this.props.fileSearch) { return true; } return (f.url + f.nodePath) .toLowerCase() .includes(this.props.fileSearch.toLowerCase()); }) .map((f) => { return ( <div onClick={() => { this.props.selectFile(f); }} > {f.nodePath || f.url}{" "} <span style={{ fontSize: 12, color: "#777" }}> {new Date(f.createdAt).toLocaleString()} </span> </div> ); })} </div> ); } } class InfoItem extends React.Component { state = { showJson: false, showUsesFor: null, }; render() { let { info } = this.props; if (getCodeString(info.loc) === "todo") { return null; } return ( <div> <h2>Values for {getCodeString(info.loc)}</h2> {info.logs.map((l) => ( <div> <code className="values-list__value" onClick={() => { selectAndTraverse(l.value.index, 0); loadSteps({ logId: l.value.index, charIndex: 0 }).then( ({ steps }) => { const lastStep = steps[steps.length - 1]; console.log({ steps }); this.setState({ showUsesFor: lastStep.operationLog.index, }); } ); }} > {JSON.stringify(l.value._result).slice(0, 2000)}{" "} </code> </div> ))} <hr /> <button onClick={() => this.setState({ showJson: !this.state.showJson })} > toggle json </button> {this.state.showJson && <pre>{JSON.stringify(info.logs, null, 2)}</pre>} {JSON.stringify(this.state)} {this.state.showUsesFor && ( <ShowUses logIndex={this.state.showUsesFor} key={this.state.showUsesFor} ></ShowUses> )} </div> ); } } class ShowUses extends React.Component { state = { uses: null, }; async componentDidMount() { this.setState({ uses: await fetch("/xyzviewer/getUses/" + this.props.logIndex).then((r) => r.json() ), }); } render() { if (!this.state.uses) { return <div></div>; } return ( <div> {this.state.uses.length === 0 && <div>No uses found.</div>} {this.state.uses .filter((u) => u.argName === "function") .map(({ use, argName }) => { return ( <div> <b>{use.operation}</b> (as {argName}) <ErrorBoundary> {" "} <TraversalStep // makeFEOoperationLog normally done in api.ts step={{ operationLog: makeFEOperationLog(use), charIndex: 0, }} ></TraversalStep> </ErrorBoundary> </div> ); })} </div> ); } }
the_stack
import {CheckContext} from "../../compiler/analyzer/type-checker"; import {StringBuilder, StringBuilder_new} from "../../utils/stringbuilder"; import {Compiler, replaceFileExtension} from "../../compiler/compiler"; import {Node, isCompactNodeKind, isUnaryPostfix, NodeKind} from "../../compiler/core/node"; import {Precedence} from "../../compiler/parser/parser"; import {Symbol, SymbolKind} from "../../compiler/core/symbol"; import {isAlpha, isNumber, isASCII} from "../../compiler/scanner/scanner"; import {Type} from "../../compiler/core/type"; import {assert} from "../../utils/assert"; export enum TypeMode { NORMAL, DECLARATION, BARE, } export enum SourceMode { HEADER, IMPLEMENTATION, } export class CResult { context: CheckContext; code: StringBuilder; codePrefix: StringBuilder; headerName: string; private indent: int32; private hasStrings: boolean; private previousNode: Node; private nextStringLiteral: int32; emitIndent(): void { var i = this.indent; while (i > 0) { this.code.append(" "); i = i - 1; } } emitNewlineBefore(node: Node): void { if (this.previousNode != null && (!isCompactNodeKind(this.previousNode.kind) || !isCompactNodeKind(node.kind))) { this.code.append('\n'); } this.previousNode = null; } emitNewlineAfter(node: Node): void { this.previousNode = node; } emitStatements(node: Node): void { while (node != null) { this.emitStatement(node); node = node.nextSibling; } } emitBlock(node: Node): void { this.previousNode = null; this.code.append("{\n"); this.indent = this.indent + 1; this.emitStatements(node.firstChild); this.indent = this.indent - 1; this.emitIndent(); this.code.append('}'); this.previousNode = null; } emitUnary(node: Node, parentPrecedence: Precedence, operator: string): void { var isPostfix = isUnaryPostfix(node.kind); var operatorPrecedence = isPostfix ? Precedence.UNARY_POSTFIX : Precedence.UNARY_PREFIX; var code = this.code; if (parentPrecedence > operatorPrecedence) { code.append('('); } if (!isPostfix) { code.append(operator); } this.emitExpression(node.unaryValue(), operatorPrecedence); if (isPostfix) { code.append(operator); } if (parentPrecedence > operatorPrecedence) { code.append(')'); } } emitBinary(node: Node, parentPrecedence: Precedence, operator: string, operatorPrecedence: Precedence): void { var kind = node.kind; var isRightAssociative = kind == NodeKind.ASSIGN; var needsParentheses = parentPrecedence > operatorPrecedence; var parentKind = node.parent.kind; var code = this.code; // Try to avoid warnings from Clang and GCC if (parentKind == NodeKind.LOGICAL_OR && kind == NodeKind.LOGICAL_AND || parentKind == NodeKind.BITWISE_OR && kind == NodeKind.BITWISE_AND || (parentKind == NodeKind.EQUAL || parentKind == NodeKind.NOT_EQUAL) && (kind == NodeKind.EQUAL || kind == NodeKind.NOT_EQUAL) || (kind == NodeKind.ADD || kind == NodeKind.SUBTRACT) && ( parentKind == NodeKind.BITWISE_AND || parentKind == NodeKind.BITWISE_OR || parentKind == NodeKind.BITWISE_XOR || parentKind == NodeKind.SHIFT_LEFT || parentKind == NodeKind.SHIFT_RIGHT)) { needsParentheses = true; } if (needsParentheses) { code.append('('); } this.emitExpression(node.binaryLeft(), isRightAssociative ? (operatorPrecedence + 1) as Precedence : operatorPrecedence); code.append(operator); this.emitExpression(node.binaryRight(), isRightAssociative ? operatorPrecedence : (operatorPrecedence + 1) as Precedence); if (needsParentheses) { code.append(')'); } } emitCommaSeparatedExpressions(start: Node, stop: Node): void { while (start != stop) { this.emitExpression(start, Precedence.LOWEST); start = start.nextSibling; if (start != stop) { this.code.append(", "); } } } emitSymbolName(symbol: Symbol): void { if (symbol.kind == SymbolKind.FUNCTION_INSTANCE) { this.code.append(symbol.parent().name).append('_'); } this.code.append(symbol.rename != null ? symbol.rename : symbol.name); } emitExpression(node: Node, parentPrecedence: Precedence): void { var code = this.code; assert(node.resolvedType != null); if (node.kind == NodeKind.NAME) { this.emitSymbolName(node.symbol); } else if (node.kind == NodeKind.NULL) { code.append("NULL"); } else if (node.kind == NodeKind.BOOLEAN) { code.append(node.intValue != 0 ? '1' : '0'); } else if (node.kind == NodeKind.INT32) { code.append(node.resolvedType.isUnsigned() ? (node.intValue).toString() : node.intValue.toString()); } else if (node.kind == NodeKind.FLOAT32) { code.append(node.floatValue.toString()); } else if (node.kind == NodeKind.STRING) { var id = this.nextStringLiteral; var builder = StringBuilder_new(); builder.append("__string_").append(id.toString()); var value = node.stringValue; var codePrefix = this.codePrefix; var length = value.length; var i = 0; if (!this.hasStrings) { codePrefix.append(` #ifdef TURBOSCRIPT_BIG_ENDIAN #define S(a, b) (((a) << 16) | (b)) #else #define S(a, b) ((a) | ((b) << 16)) #endif `); this.hasStrings = true; } var underscore = true; i = 0; while (i < length && i < 32) { var c = value[i]; if (isAlpha(c) || isNumber(c)) { if (underscore) { builder.append('_'); underscore = false; } builder.append(c); } else { underscore = true; } i = i + 1; } var name = builder.finish(); codePrefix.append("static const uint32_t ").append(name).append("[] = {").append(length.toString()); i = 0; while (i < length) { codePrefix.append(", S("); cEmitCharacter(codePrefix, value[i]); if (i + 1 < length) { codePrefix.append(i % 32 == 20 ? ",\n " : ", "); cEmitCharacter(codePrefix, value[i + 1]); codePrefix.append(')'); } else { codePrefix.append(", 0)"); } i = i + 2; } codePrefix.append("};\n"); this.nextStringLiteral = this.nextStringLiteral + 1; code.append("(const uint16_t *)").append(name); } else if (node.kind == NodeKind.CAST) { if (parentPrecedence > Precedence.UNARY_PREFIX) { code.append('('); } code.append('('); this.emitType(node.resolvedType, TypeMode.NORMAL); code.append(')'); this.emitExpression(node.castValue(), Precedence.UNARY_PREFIX); if (parentPrecedence > Precedence.UNARY_PREFIX) { code.append(')'); } } else if (node.kind == NodeKind.DOT) { var target = node.dotTarget(); this.emitExpression(target, Precedence.MEMBER); code.append(target.resolvedType.isReference() ? "->" : "."); this.emitSymbolName(node.symbol); } else if (node.kind == NodeKind.HOOK) { if (parentPrecedence > Precedence.ASSIGN) { code.append('('); } this.emitExpression(node.hookValue(), Precedence.LOGICAL_OR); code.append(" ? "); this.emitExpression(node.hookTrue(), Precedence.ASSIGN); code.append(" : "); this.emitExpression(node.hookFalse(), Precedence.ASSIGN); if (parentPrecedence > Precedence.ASSIGN) { code.append(')'); } } else if (node.kind == NodeKind.CALL) { let value = node.callValue(); this.emitSymbolName(value.symbol); code.append('('); // Make sure to emit "this" if (value.kind == NodeKind.DOT) { this.emitExpression(value.dotTarget(), Precedence.LOWEST); if (value.nextSibling != null) { code.append(", "); } } this.emitCommaSeparatedExpressions(value.nextSibling, null); code.append(')'); } // This uses "calloc" instead of "malloc" because it needs to be zero-initialized else if (node.kind == NodeKind.NEW) { code.append("calloc(1, sizeof("); this.emitType(node.resolvedType, TypeMode.BARE); code.append("))"); } else if (node.kind == NodeKind.COMPLEMENT) this.emitUnary(node, parentPrecedence, "~"); else if (node.kind == NodeKind.DEREFERENCE) this.emitUnary(node, parentPrecedence, "*"); else if (node.kind == NodeKind.NEGATIVE) this.emitUnary(node, parentPrecedence, "-"); else if (node.kind == NodeKind.NOT) this.emitUnary(node, parentPrecedence, "!"); else if (node.kind == NodeKind.POSITIVE) this.emitUnary(node, parentPrecedence, "+"); else if (node.kind == NodeKind.POSTFIX_DECREMENT) this.emitUnary(node, parentPrecedence, "--"); else if (node.kind == NodeKind.POSTFIX_INCREMENT) this.emitUnary(node, parentPrecedence, "++"); else if (node.kind == NodeKind.PREFIX_DECREMENT) this.emitUnary(node, parentPrecedence, "--"); else if (node.kind == NodeKind.PREFIX_INCREMENT) this.emitUnary(node, parentPrecedence, "++"); else if (node.kind == NodeKind.ADD) this.emitBinary(node, parentPrecedence, " + ", Precedence.ADD); else if (node.kind == NodeKind.ASSIGN) this.emitBinary(node, parentPrecedence, " = ", Precedence.ASSIGN); else if (node.kind == NodeKind.BITWISE_AND) this.emitBinary(node, parentPrecedence, " & ", Precedence.BITWISE_AND); else if (node.kind == NodeKind.BITWISE_OR) this.emitBinary(node, parentPrecedence, " | ", Precedence.BITWISE_OR); else if (node.kind == NodeKind.BITWISE_XOR) this.emitBinary(node, parentPrecedence, " ^ ", Precedence.BITWISE_XOR); else if (node.kind == NodeKind.DIVIDE) this.emitBinary(node, parentPrecedence, " / ", Precedence.MULTIPLY); else if (node.kind == NodeKind.EQUAL) this.emitBinary(node, parentPrecedence, " == ", Precedence.EQUAL); else if (node.kind == NodeKind.GREATER_THAN) this.emitBinary(node, parentPrecedence, " > ", Precedence.COMPARE); else if (node.kind == NodeKind.GREATER_THAN_EQUAL) this.emitBinary(node, parentPrecedence, " >= ", Precedence.COMPARE); else if (node.kind == NodeKind.LESS_THAN) this.emitBinary(node, parentPrecedence, " < ", Precedence.COMPARE); else if (node.kind == NodeKind.LESS_THAN_EQUAL) this.emitBinary(node, parentPrecedence, " <= ", Precedence.COMPARE); else if (node.kind == NodeKind.LOGICAL_AND) this.emitBinary(node, parentPrecedence, " && ", Precedence.LOGICAL_AND); else if (node.kind == NodeKind.LOGICAL_OR) this.emitBinary(node, parentPrecedence, " || ", Precedence.LOGICAL_OR); else if (node.kind == NodeKind.MULTIPLY) this.emitBinary(node, parentPrecedence, " * ", Precedence.MULTIPLY); else if (node.kind == NodeKind.NOT_EQUAL) this.emitBinary(node, parentPrecedence, " != ", Precedence.EQUAL); else if (node.kind == NodeKind.REMAINDER) this.emitBinary(node, parentPrecedence, " % ", Precedence.MULTIPLY); else if (node.kind == NodeKind.SHIFT_LEFT) this.emitBinary(node, parentPrecedence, " << ", Precedence.SHIFT); else if (node.kind == NodeKind.SHIFT_RIGHT) this.emitBinary(node, parentPrecedence, " >> ", Precedence.SHIFT); else if (node.kind == NodeKind.SUBTRACT) this.emitBinary(node, parentPrecedence, " - ", Precedence.ADD); else { assert(false); } } shouldEmitClass(node: Node): boolean { assert(node.kind == NodeKind.CLASS); return node.symbol.kind == SymbolKind.TYPE_CLASS && node.symbol != this.context.stringType.symbol; } emitType(originalType: Type, mode: TypeMode): void { var context = this.context; var code = this.code; var type = originalType; if (type.isEnum()) { type = type.underlyingType(this.context); } else { while (type.pointerTo != null) { type = type.pointerTo; } } if (type.isClass()) { code.append("struct "); } if (type == context.booleanType || type == context.uint8Type) code.append("uint8_t"); else if (type == context.int8Type) code.append("int8_t"); else if (type == context.int32Type) code.append("int32_t"); else if (type == context.int64Type) code.append("int64_t"); else if (type == context.int16Type) code.append("int16_t"); else if (type == context.stringType) code.append("const uint16_t"); else if (type == context.uint32Type) code.append("uint32_t"); else if (type == context.uint16Type) code.append("uint16_t"); else if (type == context.float32Type) code.append("float"); else this.emitSymbolName(type.symbol); if (originalType.pointerTo != null) { code.append(' '); while (originalType.pointerTo != null) { code.append('*'); originalType = originalType.pointerTo; } } else if (mode != TypeMode.BARE) { if (type.isReference()) code.append(" *"); else if (mode == TypeMode.DECLARATION) code.append(' '); } } emitStatement(node: Node): void { var code = this.code; if (node.kind == NodeKind.IF) { this.emitNewlineBefore(node); this.emitIndent(); while (true) { code.append("if ("); this.emitExpression(node.ifValue(), Precedence.LOWEST); code.append(") "); this.emitBlock(node.ifTrue()); var no = node.ifFalse(); if (no == null) { code.append('\n'); break; } code.append("\n\n"); this.emitIndent(); code.append("else "); if (no.firstChild == null || no.firstChild != no.lastChild || no.firstChild.kind != NodeKind.IF) { this.emitBlock(no); code.append('\n'); break; } node = no.firstChild; } this.emitNewlineAfter(node); } else if (node.kind == NodeKind.WHILE) { this.emitNewlineBefore(node); this.emitIndent(); code.append("while ("); this.emitExpression(node.whileValue(), Precedence.LOWEST); code.append(") "); this.emitBlock(node.whileBody()); code.append('\n'); this.emitNewlineAfter(node); } else if (node.kind == NodeKind.BREAK) { this.emitNewlineBefore(node); this.emitIndent(); code.append("break;\n"); this.emitNewlineAfter(node); } else if (node.kind == NodeKind.CONTINUE) { this.emitNewlineBefore(node); this.emitIndent(); code.append("continue;\n"); this.emitNewlineAfter(node); } else if (node.kind == NodeKind.EXPRESSION) { this.emitNewlineBefore(node); this.emitIndent(); this.emitExpression(node.expressionValue(), Precedence.LOWEST); code.append(";\n"); this.emitNewlineAfter(node); } else if (node.kind == NodeKind.EMPTY) { } else if (node.kind == NodeKind.RETURN) { var value = node.returnValue(); this.emitNewlineBefore(node); this.emitIndent(); if (value != null) { code.append("return "); this.emitExpression(value, Precedence.LOWEST); code.append(";\n"); } else { code.append("return;\n"); } this.emitNewlineAfter(node); } else if (node.kind == NodeKind.BLOCK) { if (node.parent.kind == NodeKind.BLOCK) { this.emitStatements(node.firstChild); } else { this.emitNewlineBefore(node); this.emitIndent(); this.emitBlock(node); code.append('\n'); this.emitNewlineAfter(node); } } else if (node.kind == NodeKind.VARIABLES) { this.emitNewlineBefore(node); var child = node.firstChild; while (child != null) { var value = child.variableValue(); this.emitIndent(); this.emitType(child.symbol.resolvedType, TypeMode.DECLARATION); this.emitSymbolName(child.symbol); assert(value != null); code.append(" = "); this.emitExpression(value, Precedence.LOWEST); code.append(";\n"); child = child.nextSibling; } this.emitNewlineAfter(node); } else if (node.kind == NodeKind.CONSTANTS || node.kind == NodeKind.ENUM) { } else { assert(false); } } emitIncludes(code: StringBuilder, mode: SourceMode): void { if (mode == SourceMode.HEADER) { code.append("#include <stdint.h>\n"); // Need "int32_t" and friends } else { code.append("#include \"").append(this.headerName).append("\"\n"); code.append("#include <stdlib.h>\n"); // Need "NULL" and "calloc" code.append("#include <string.h>\n"); // Need "memcpy" and "memcmp" } } emitTypeDeclarations(node: Node, mode: SourceMode): void { var code = this.code; while (node != null) { if (node.kind == NodeKind.CLASS) { if (this.shouldEmitClass(node) && (node.isDeclareOrExport() ? mode == SourceMode.HEADER : mode == SourceMode.IMPLEMENTATION)) { this.emitNewlineBefore(node); code.append("struct ").append(node.symbol.name).append(";\n"); } } node = node.nextSibling; } } emitTypeDefinitions(node: Node, mode: SourceMode): void { var code = this.code; while (node != null) { if (node.kind == NodeKind.CLASS) { if (this.shouldEmitClass(node) && mode != SourceMode.HEADER) { this.emitNewlineBefore(node); code.append("struct "); this.emitSymbolName(node.symbol); code.append(" {\n"); this.indent = this.indent + 1; // Emit member variables var child = node.firstChild; while (child != null) { if (child.kind == NodeKind.VARIABLE) { this.emitIndent(); this.emitType(child.symbol.resolvedType, TypeMode.DECLARATION); this.emitSymbolName(child.symbol); code.append(";\n"); } child = child.nextSibling; } this.indent = this.indent - 1; code.append("};\n"); this.emitNewlineAfter(node); } } else if (node.kind == NodeKind.ENUM) { if (mode == SourceMode.HEADER && node.isExport()) { this.emitNewlineBefore(node); code.append("enum {\n"); this.indent = this.indent + 1; // Emit enum values var child = node.firstChild; while (child != null) { assert(child.kind == NodeKind.VARIABLE); this.emitIndent(); this.emitSymbolName(node.symbol); code.append("_"); this.emitSymbolName(child.symbol); code.append(" = "); code.append(child.symbol.offset.toString()); child = child.nextSibling; code.append(child != null ? ",\n" : "\n"); } this.indent = this.indent - 1; this.emitIndent(); code.append("};\n"); this.emitNewlineAfter(node); } } node = node.nextSibling; } } shouldEmitFunction(symbol: Symbol): boolean { return symbol.kind != SymbolKind.FUNCTION_GLOBAL || symbol.name != "malloc" && symbol.name != "memcpy" && symbol.name != "memcmp"; } emitFunctionDeclarations(node: Node, mode: SourceMode): void { var code = this.code; while (node != null) { if (node.kind == NodeKind.FUNCTION && (mode != SourceMode.HEADER || node.isDeclareOrExport())) { var symbol = node.symbol; if (this.shouldEmitFunction(symbol)) { var returnType = node.functionReturnType(); var child = node.functionFirstArgument(); this.emitNewlineBefore(node); if (!node.isDeclareOrExport()) { code.append("static "); } this.emitType(returnType.resolvedType, TypeMode.DECLARATION); this.emitSymbolName(symbol); code.append('('); if (symbol.kind == SymbolKind.FUNCTION_INSTANCE) { child.symbol.rename = "__this"; } while (child != returnType) { assert(child.kind == NodeKind.VARIABLE); this.emitType(child.symbol.resolvedType, TypeMode.DECLARATION); this.emitSymbolName(child.symbol); child = child.nextSibling; if (child != returnType) { code.append(", "); } } code.append(");\n"); } } else if (node.kind == NodeKind.CLASS) { this.emitFunctionDeclarations(node.firstChild, mode); } node = node.nextSibling; } } emitGlobalVariables(node: Node, mode: SourceMode): void { var code = this.code; while (node != null) { if (node.kind == NodeKind.VARIABLE && (mode != SourceMode.HEADER || node.isExport())) { var value = node.variableValue(); this.emitNewlineBefore(node); if (!node.isDeclareOrExport()) { code.append("static "); } this.emitType(node.symbol.resolvedType, TypeMode.DECLARATION); this.emitSymbolName(node.symbol); code.append(" = "); this.emitExpression(value, Precedence.LOWEST); code.append(";\n"); } else if (node.kind == NodeKind.VARIABLES) { this.emitGlobalVariables(node.firstChild, mode); } node = node.nextSibling; } } emitFunctionDefinitions(node: Node): void { var code = this.code; while (node != null) { if (node.kind == NodeKind.FUNCTION) { var body = node.functionBody(); var symbol = node.symbol; if (body != null && this.shouldEmitFunction(symbol)) { var returnType = node.functionReturnType(); var child = node.firstChild; this.emitNewlineBefore(node); if (!node.isDeclareOrExport()) { code.append("static "); } this.emitType(returnType.resolvedType, TypeMode.DECLARATION); this.emitSymbolName(symbol); code.append('('); while (child != returnType) { assert(child.kind == NodeKind.VARIABLE); this.emitType(child.symbol.resolvedType, TypeMode.DECLARATION); this.emitSymbolName(child.symbol); child = child.nextSibling; if (child != returnType) { code.append(", "); } } code.append(") "); this.emitBlock(node.functionBody()); code.append('\n'); this.emitNewlineAfter(node); } } else if (node.kind == NodeKind.CLASS) { this.emitFunctionDefinitions(node.firstChild); } node = node.nextSibling; } } finishImplementation(): void { if (this.hasStrings) { this.codePrefix.append("\n#undef S\n"); } } } export function cEmitCharacter(builder: StringBuilder, c: string): void { if (isASCII(c.charCodeAt(0))) { builder.append('\''); if (c == '\\' || c == '\'') { builder.append('\\'); } builder.append(c); builder.append('\''); } else if (c == '\0') builder.append("\'\\0\'"); else if (c == '\r') builder.append("\'\\r\'"); else if (c == '\n') builder.append("\'\\n\'"); else if (c == '\t') builder.append("\'\\t\'"); else builder.append(c.toString()); } export function cppEmit(compiler: Compiler): void { var child = compiler.global.firstChild; var temporaryCode = StringBuilder_new(); var headerCode = StringBuilder_new(); var implementationCode = StringBuilder_new(); var result = new CResult(); result.context = compiler.context; result.code = temporaryCode; result.codePrefix = implementationCode; result.headerName = replaceFileExtension(compiler.outputName, ".h"); if (child != null) { // Emit implementation result.emitIncludes(implementationCode, SourceMode.IMPLEMENTATION); result.emitNewlineAfter(child); result.emitTypeDeclarations(child, SourceMode.IMPLEMENTATION); result.emitNewlineAfter(child); result.emitTypeDefinitions(child, SourceMode.IMPLEMENTATION); result.emitNewlineAfter(child); result.emitFunctionDeclarations(child, SourceMode.IMPLEMENTATION); result.emitNewlineAfter(child); result.emitGlobalVariables(child, SourceMode.IMPLEMENTATION); result.emitNewlineAfter(child); result.emitFunctionDefinitions(child); result.finishImplementation(); implementationCode.append(temporaryCode.finish()); // Emit header result.code = headerCode; result.emitIncludes(headerCode, SourceMode.HEADER); result.emitNewlineAfter(child); result.emitTypeDeclarations(child, SourceMode.HEADER); result.emitNewlineAfter(child); result.emitTypeDefinitions(child, SourceMode.HEADER); result.emitNewlineAfter(child); result.emitFunctionDeclarations(child, SourceMode.HEADER); result.emitNewlineAfter(child); result.emitGlobalVariables(child, SourceMode.HEADER); result.emitNewlineAfter(child); } compiler.outputCPP = implementationCode.finish(); compiler.outputH = headerCode.finish(); }
the_stack
import { dew as _readerForDewDew } from "./reader/readerFor.dew.js"; import { dew as _utilsDewDew } from "./utils.dew.js"; import { dew as _signatureDewDew } from "./signature.dew.js"; import { dew as _zipEntryDewDew } from "./zipEntry.dew.js"; import { dew as _utf8DewDew } from "./utf8.dew.js"; import { dew as _supportDewDew } from "./support.dew.js"; var exports = {}, _dewExec = false; export function dew() { if (_dewExec) return exports; _dewExec = true; var readerFor = _readerForDewDew(); var utils = _utilsDewDew(); var sig = _signatureDewDew(); var ZipEntry = _zipEntryDewDew(); var utf8 = _utf8DewDew(); var support = _supportDewDew(); // class ZipEntries {{{ /** * All the entries in the zip file. * @constructor * @param {Object} loadOptions Options for loading the stream. */ function ZipEntries(loadOptions) { this.files = []; this.loadOptions = loadOptions; } ZipEntries.prototype = { /** * Check that the reader is on the specified signature. * @param {string} expectedSignature the expected signature. * @throws {Error} if it is an other signature. */ checkSignature: function (expectedSignature) { if (!this.reader.readAndCheckSignature(expectedSignature)) { this.reader.index -= 4; var signature = this.reader.readString(4); throw new Error("Corrupted zip or bug: unexpected signature " + "(" + utils.pretty(signature) + ", expected " + utils.pretty(expectedSignature) + ")"); } }, /** * Check if the given signature is at the given index. * @param {number} askedIndex the index to check. * @param {string} expectedSignature the signature to expect. * @return {boolean} true if the signature is here, false otherwise. */ isSignature: function (askedIndex, expectedSignature) { var currentIndex = this.reader.index; this.reader.setIndex(askedIndex); var signature = this.reader.readString(4); var result = signature === expectedSignature; this.reader.setIndex(currentIndex); return result; }, /** * Read the end of the central directory. */ readBlockEndOfCentral: function () { this.diskNumber = this.reader.readInt(2); this.diskWithCentralDirStart = this.reader.readInt(2); this.centralDirRecordsOnThisDisk = this.reader.readInt(2); this.centralDirRecords = this.reader.readInt(2); this.centralDirSize = this.reader.readInt(4); this.centralDirOffset = this.reader.readInt(4); this.zipCommentLength = this.reader.readInt(2); // warning : the encoding depends of the system locale // On a linux machine with LANG=en_US.utf8, this field is utf8 encoded. // On a windows machine, this field is encoded with the localized windows code page. var zipComment = this.reader.readData(this.zipCommentLength); var decodeParamType = support.uint8array ? "uint8array" : "array"; // To get consistent behavior with the generation part, we will assume that // this is utf8 encoded unless specified otherwise. var decodeContent = utils.transformTo(decodeParamType, zipComment); this.zipComment = this.loadOptions.decodeFileName(decodeContent); }, /** * Read the end of the Zip 64 central directory. * Not merged with the method readEndOfCentral : * The end of central can coexist with its Zip64 brother, * I don't want to read the wrong number of bytes ! */ readBlockZip64EndOfCentral: function () { this.zip64EndOfCentralSize = this.reader.readInt(8); this.reader.skip(4); // this.versionMadeBy = this.reader.readString(2); // this.versionNeeded = this.reader.readInt(2); this.diskNumber = this.reader.readInt(4); this.diskWithCentralDirStart = this.reader.readInt(4); this.centralDirRecordsOnThisDisk = this.reader.readInt(8); this.centralDirRecords = this.reader.readInt(8); this.centralDirSize = this.reader.readInt(8); this.centralDirOffset = this.reader.readInt(8); this.zip64ExtensibleData = {}; var extraDataSize = this.zip64EndOfCentralSize - 44, index = 0, extraFieldId, extraFieldLength, extraFieldValue; while (index < extraDataSize) { extraFieldId = this.reader.readInt(2); extraFieldLength = this.reader.readInt(4); extraFieldValue = this.reader.readData(extraFieldLength); this.zip64ExtensibleData[extraFieldId] = { id: extraFieldId, length: extraFieldLength, value: extraFieldValue }; } }, /** * Read the end of the Zip 64 central directory locator. */ readBlockZip64EndOfCentralLocator: function () { this.diskWithZip64CentralDirStart = this.reader.readInt(4); this.relativeOffsetEndOfZip64CentralDir = this.reader.readInt(8); this.disksCount = this.reader.readInt(4); if (this.disksCount > 1) { throw new Error("Multi-volumes zip are not supported"); } }, /** * Read the local files, based on the offset read in the central part. */ readLocalFiles: function () { var i, file; for (i = 0; i < this.files.length; i++) { file = this.files[i]; this.reader.setIndex(file.localHeaderOffset); this.checkSignature(sig.LOCAL_FILE_HEADER); file.readLocalPart(this.reader); file.handleUTF8(); file.processAttributes(); } }, /** * Read the central directory. */ readCentralDir: function () { var file; this.reader.setIndex(this.centralDirOffset); while (this.reader.readAndCheckSignature(sig.CENTRAL_FILE_HEADER)) { file = new ZipEntry({ zip64: this.zip64 }, this.loadOptions); file.readCentralPart(this.reader); this.files.push(file); } if (this.centralDirRecords !== this.files.length) { if (this.centralDirRecords !== 0 && this.files.length === 0) { // We expected some records but couldn't find ANY. // This is really suspicious, as if something went wrong. throw new Error("Corrupted zip or bug: expected " + this.centralDirRecords + " records in central dir, got " + this.files.length); } else {// We found some records but not all. // Something is wrong but we got something for the user: no error here. // console.warn("expected", this.centralDirRecords, "records in central dir, got", this.files.length); } } }, /** * Read the end of central directory. */ readEndOfCentral: function () { var offset = this.reader.lastIndexOfSignature(sig.CENTRAL_DIRECTORY_END); if (offset < 0) { // Check if the content is a truncated zip or complete garbage. // A "LOCAL_FILE_HEADER" is not required at the beginning (auto // extractible zip for example) but it can give a good hint. // If an ajax request was used without responseType, we will also // get unreadable data. var isGarbage = !this.isSignature(0, sig.LOCAL_FILE_HEADER); if (isGarbage) { throw new Error("Can't find end of central directory : is this a zip file ? " + "If it is, see https://stuk.github.io/jszip/documentation/howto/read_zip.html"); } else { throw new Error("Corrupted zip: can't find end of central directory"); } } this.reader.setIndex(offset); var endOfCentralDirOffset = offset; this.checkSignature(sig.CENTRAL_DIRECTORY_END); this.readBlockEndOfCentral(); /* extract from the zip spec : 4) If one of the fields in the end of central directory record is too small to hold required data, the field should be set to -1 (0xFFFF or 0xFFFFFFFF) and the ZIP64 format record should be created. 5) The end of central directory record and the Zip64 end of central directory locator record must reside on the same disk when splitting or spanning an archive. */ if (this.diskNumber === utils.MAX_VALUE_16BITS || this.diskWithCentralDirStart === utils.MAX_VALUE_16BITS || this.centralDirRecordsOnThisDisk === utils.MAX_VALUE_16BITS || this.centralDirRecords === utils.MAX_VALUE_16BITS || this.centralDirSize === utils.MAX_VALUE_32BITS || this.centralDirOffset === utils.MAX_VALUE_32BITS) { this.zip64 = true; /* Warning : the zip64 extension is supported, but ONLY if the 64bits integer read from the zip file can fit into a 32bits integer. This cannot be solved : JavaScript represents all numbers as 64-bit double precision IEEE 754 floating point numbers. So, we have 53bits for integers and bitwise operations treat everything as 32bits. see https://developer.mozilla.org/en-US/docs/JavaScript/Reference/Operators/Bitwise_Operators and http://www.ecma-international.org/publications/files/ECMA-ST/ECMA-262.pdf section 8.5 */ // should look for a zip64 EOCD locator offset = this.reader.lastIndexOfSignature(sig.ZIP64_CENTRAL_DIRECTORY_LOCATOR); if (offset < 0) { throw new Error("Corrupted zip: can't find the ZIP64 end of central directory locator"); } this.reader.setIndex(offset); this.checkSignature(sig.ZIP64_CENTRAL_DIRECTORY_LOCATOR); this.readBlockZip64EndOfCentralLocator(); // now the zip64 EOCD record if (!this.isSignature(this.relativeOffsetEndOfZip64CentralDir, sig.ZIP64_CENTRAL_DIRECTORY_END)) { // console.warn("ZIP64 end of central directory not where expected."); this.relativeOffsetEndOfZip64CentralDir = this.reader.lastIndexOfSignature(sig.ZIP64_CENTRAL_DIRECTORY_END); if (this.relativeOffsetEndOfZip64CentralDir < 0) { throw new Error("Corrupted zip: can't find the ZIP64 end of central directory"); } } this.reader.setIndex(this.relativeOffsetEndOfZip64CentralDir); this.checkSignature(sig.ZIP64_CENTRAL_DIRECTORY_END); this.readBlockZip64EndOfCentral(); } var expectedEndOfCentralDirOffset = this.centralDirOffset + this.centralDirSize; if (this.zip64) { expectedEndOfCentralDirOffset += 20; // end of central dir 64 locator expectedEndOfCentralDirOffset += 12 /* should not include the leading 12 bytes */ + this.zip64EndOfCentralSize; } var extraBytes = endOfCentralDirOffset - expectedEndOfCentralDirOffset; if (extraBytes > 0) { // console.warn(extraBytes, "extra bytes at beginning or within zipfile"); if (this.isSignature(endOfCentralDirOffset, sig.CENTRAL_FILE_HEADER)) {// The offsets seem wrong, but we have something at the specified offset. // So… we keep it. } else { // the offset is wrong, update the "zero" of the reader // this happens if data has been prepended (crx files for example) this.reader.zero = extraBytes; } } else if (extraBytes < 0) { throw new Error("Corrupted zip: missing " + Math.abs(extraBytes) + " bytes."); } }, prepareReader: function (data) { this.reader = readerFor(data); }, /** * Read a zip file and create ZipEntries. * @param {String|ArrayBuffer|Uint8Array|Buffer} data the binary string representing a zip file. */ load: function (data) { this.prepareReader(data); this.readEndOfCentral(); this.readCentralDir(); this.readLocalFiles(); } }; // }}} end of ZipEntries exports = ZipEntries; return exports; }
the_stack
interface DropdownOption { readonly name: string; readonly value: string; readonly hint?: string; } /** * Implements the dropdown inputs used in the Git Graph View's top control bar. */ class Dropdown { private readonly showInfo: boolean; private readonly multipleAllowed: boolean; private readonly changeCallback: (values: string[]) => void; private options: ReadonlyArray<DropdownOption> = []; private optionsSelected: boolean[] = []; private lastSelected: number = 0; // Only used when multipleAllowed === false private dropdownVisible: boolean = false; private lastClicked: number = 0; private doubleClickTimeout: NodeJS.Timer | null = null; private readonly elem: HTMLElement; private readonly currentValueElem: HTMLDivElement; private readonly menuElem: HTMLDivElement; private readonly optionsElem: HTMLDivElement; private readonly noResultsElem: HTMLDivElement; private readonly filterInput: HTMLInputElement; /** * Constructs a Dropdown instance. * @param id The ID of the HTML Element that the dropdown should be rendered in. * @param showInfo Should an information icon be shown on the right of each dropdown item. * @param multipleAllowed Can multiple items be selected. * @param dropdownType The type of content the dropdown is being used for. * @param changeCallback A callback to be invoked when the selected item(s) of the dropdown changes. * @returns The Dropdown instance. */ constructor(id: string, showInfo: boolean, multipleAllowed: boolean, dropdownType: string, changeCallback: (values: string[]) => void) { this.showInfo = showInfo; this.multipleAllowed = multipleAllowed; this.changeCallback = changeCallback; this.elem = document.getElementById(id)!; this.menuElem = document.createElement('div'); this.menuElem.className = 'dropdownMenu'; let filter = this.menuElem.appendChild(document.createElement('div')); filter.className = 'dropdownFilter'; this.filterInput = filter.appendChild(document.createElement('input')); this.filterInput.className = 'dropdownFilterInput'; this.filterInput.placeholder = 'Filter ' + dropdownType + '...'; this.optionsElem = this.menuElem.appendChild(document.createElement('div')); this.optionsElem.className = 'dropdownOptions'; this.noResultsElem = this.menuElem.appendChild(document.createElement('div')); this.noResultsElem.className = 'dropdownNoResults'; this.noResultsElem.innerHTML = 'No results found.'; this.currentValueElem = this.elem.appendChild(document.createElement('div')); this.currentValueElem.className = 'dropdownCurrentValue'; alterClass(this.elem, 'multi', multipleAllowed); this.elem.appendChild(this.menuElem); document.addEventListener('click', (e) => { if (!e.target) return; if (e.target === this.currentValueElem) { this.dropdownVisible = !this.dropdownVisible; if (this.dropdownVisible) { this.filterInput.value = ''; this.filter(); } this.elem.classList.toggle('dropdownOpen'); if (this.dropdownVisible) this.filterInput.focus(); } else if (this.dropdownVisible) { if ((<HTMLElement>e.target).closest('.dropdown') !== this.elem) { this.close(); } else { const option = <HTMLElement | null>(<HTMLElement>e.target).closest('.dropdownOption'); if (option !== null && option.parentNode === this.optionsElem && typeof option.dataset.id !== 'undefined') { this.onOptionClick(parseInt(option.dataset.id!)); } } } }, true); document.addEventListener('contextmenu', () => this.close(), true); this.filterInput.addEventListener('keyup', () => this.filter()); } /** * Set the options that should be displayed in the dropdown. * @param options An array of the options to display in the dropdown. * @param optionsSelected An array of the selected options in the dropdown. */ public setOptions(options: ReadonlyArray<DropdownOption>, optionsSelected: string[]) { this.options = options; this.optionsSelected = []; let selectedOption = -1, isSelected; for (let i = 0; i < options.length; i++) { isSelected = optionsSelected.includes(options[i].value); this.optionsSelected[i] = isSelected; if (isSelected) { selectedOption = i; } } if (selectedOption === -1) { selectedOption = 0; this.optionsSelected[selectedOption] = true; } this.lastSelected = selectedOption; if (this.dropdownVisible && options.length <= 1) this.close(); this.render(); this.clearDoubleClickTimeout(); } /** * Is a value selected in the dropdown (respecting "Show All") * @param value The value to check. * @returns TRUE => The value is selected, FALSE => The value is not selected. */ public isSelected(value: string) { if (this.options.length > 0) { if (this.multipleAllowed && this.optionsSelected[0]) { // Multiple options can be selected, and "Show All" is selected. return true; } const optionIndex = this.options.findIndex((option) => option.value === value); if (optionIndex > -1 && this.optionsSelected[optionIndex]) { // The specific option is selected return true; } } return false; } /** * Select a specific value in the dropdown. * @param value The value to select. */ public selectOption(value: string) { const optionIndex = this.options.findIndex((option) => value === option.value); if (this.multipleAllowed && optionIndex > -1 && !this.optionsSelected[0] && !this.optionsSelected[optionIndex]) { // Select the option with the specified value this.optionsSelected[optionIndex] = true; // A change has occurred, re-render the dropdown options const menuScroll = this.menuElem.scrollTop; this.render(); if (this.dropdownVisible) { this.menuElem.scroll(0, menuScroll); } this.changeCallback(this.getSelectedOptions(false)); } } /** * Unselect a specific value in the dropdown. * @param value The value to unselect. */ public unselectOption(value: string) { const optionIndex = this.options.findIndex((option) => value === option.value); if (this.multipleAllowed && optionIndex > -1 && (this.optionsSelected[0] || this.optionsSelected[optionIndex])) { if (this.optionsSelected[0]) { // Show All is currently selected, so unselect it, and select all branch options this.optionsSelected[0] = false; for (let i = 1; i < this.optionsSelected.length; i++) { this.optionsSelected[i] = true; } } // Unselect the option with the specified value this.optionsSelected[optionIndex] = false; if (this.optionsSelected.every(selected => !selected)) { // All items have been unselected, select "Show All" this.optionsSelected[0] = true; } // A change has occurred, re-render the dropdown options const menuScroll = this.menuElem.scrollTop; this.render(); if (this.dropdownVisible) { this.menuElem.scroll(0, menuScroll); } this.changeCallback(this.getSelectedOptions(false)); } } /** * Refresh the rendered dropdown to apply style changes. */ public refresh() { if (this.options.length > 0) this.render(); } /** * Is the dropdown currently open (i.e. is the list of options visible). * @returns TRUE => The dropdown is open, FALSE => The dropdown is not open */ public isOpen() { return this.dropdownVisible; } /** * Close the dropdown. */ public close() { this.elem.classList.remove('dropdownOpen'); this.dropdownVisible = false; this.clearDoubleClickTimeout(); } /** * Render the dropdown. */ private render() { this.elem.classList.add('loaded'); const curValueText = formatCommaSeparatedList(this.getSelectedOptions(true)); this.currentValueElem.title = curValueText; this.currentValueElem.innerHTML = escapeHtml(curValueText); let html = ''; for (let i = 0; i < this.options.length; i++) { const escapedName = escapeHtml(this.options[i].name); html += '<div class="dropdownOption' + (this.optionsSelected[i] ? ' ' + CLASS_SELECTED : '') + '" data-id="' + i + '" title="' + escapedName + '">' + (this.multipleAllowed && this.optionsSelected[i] ? '<div class="dropdownOptionMultiSelected">' + SVG_ICONS.check + '</div>' : '') + escapedName + (typeof this.options[i].hint === 'string' && this.options[i].hint !== '' ? '<span class="dropdownOptionHint">' + escapeHtml(this.options[i].hint!) + '</span>' : '') + (this.showInfo ? '<div class="dropdownOptionInfo" title="' + escapeHtml(this.options[i].value) + '">' + SVG_ICONS.info + '</div>' : '') + '</div>'; } this.optionsElem.className = 'dropdownOptions' + (this.showInfo ? ' showInfo' : ''); this.optionsElem.innerHTML = html; this.filterInput.style.display = 'none'; this.noResultsElem.style.display = 'none'; this.menuElem.style.cssText = 'opacity:0; display:block;'; // Width must be at least 138px for the filter element. // Don't need to add 12px if showing (info icons or multi checkboxes) and the scrollbar isn't needed. The scrollbar isn't needed if: menuElem height + filter input (25px) < 297px const menuElemRect = this.menuElem.getBoundingClientRect(); this.currentValueElem.style.width = Math.max(Math.ceil(menuElemRect.width) + ((this.showInfo || this.multipleAllowed) && menuElemRect.height < 272 ? 0 : 12), 138) + 'px'; this.menuElem.style.cssText = 'right:0; overflow-y:auto; max-height:297px;'; // Max height for the dropdown is [filter (31px) + 9.5 * dropdown item (28px) = 297px] if (this.dropdownVisible) this.filter(); } /** * Filter the options displayed in the dropdown list, based on the filter criteria specified by the user. */ private filter() { let val = this.filterInput.value.toLowerCase(), match, matches = false; for (let i = 0; i < this.options.length; i++) { match = this.options[i].name.toLowerCase().indexOf(val) > -1; (<HTMLElement>this.optionsElem.children[i]).style.display = match ? 'block' : 'none'; if (match) matches = true; } this.filterInput.style.display = 'block'; this.noResultsElem.style.display = matches ? 'none' : 'block'; } /** * Get an array of the selected dropdown options. * @param names TRUE => Return the names of the selected options, FALSE => Return the values of the selected options. * @returns The array of the selected options. */ private getSelectedOptions(names: boolean) { let selected = []; if (this.multipleAllowed && this.optionsSelected[0]) { // Note: Show All is always the first option (0 index) when multiple selected items are allowed return [names ? this.options[0].name : this.options[0].value]; } for (let i = 0; i < this.options.length; i++) { if (this.optionsSelected[i]) selected.push(names ? this.options[i].name : this.options[i].value); } return selected; } /** * Select a dropdown option. * @param option The index of the option to select. */ private onOptionClick(option: number) { // Note: Show All is always the first option (0 index) when multiple selected items are allowed let change = false; let doubleClick = this.doubleClickTimeout !== null && this.lastClicked === option; if (this.doubleClickTimeout !== null) this.clearDoubleClickTimeout(); if (doubleClick) { // Double click if (this.multipleAllowed && option === 0) { for (let i = 1; i < this.optionsSelected.length; i++) { this.optionsSelected[i] = !this.optionsSelected[i]; } change = true; } } else { // Single Click if (this.multipleAllowed) { // Multiple dropdown options can be selected if (option === 0) { // Show All was selected if (!this.optionsSelected[0]) { this.optionsSelected[0] = true; for (let i = 1; i < this.optionsSelected.length; i++) { this.optionsSelected[i] = false; } change = true; } } else { if (this.optionsSelected[0]) { // Deselect "Show All" if it is enabled this.optionsSelected[0] = false; } this.optionsSelected[option] = !this.optionsSelected[option]; if (this.optionsSelected.every(selected => !selected)) { // All items have been unselected, select "Show All" this.optionsSelected[0] = true; } change = true; } } else { // Only a single dropdown option can be selected this.close(); if (this.lastSelected !== option) { this.optionsSelected[this.lastSelected] = false; this.optionsSelected[option] = true; this.lastSelected = option; change = true; } } if (change) { // If a change has occurred, trigger the callback this.changeCallback(this.getSelectedOptions(false)); } } if (change) { // If a change has occurred, re-render the dropdown elements let menuScroll = this.menuElem.scrollTop; this.render(); if (this.dropdownVisible) this.menuElem.scroll(0, menuScroll); } this.lastClicked = option; this.doubleClickTimeout = setTimeout(() => { this.clearDoubleClickTimeout(); }, 500); } /** * Clear the timeout used to detect double clicks. */ private clearDoubleClickTimeout() { if (this.doubleClickTimeout !== null) { clearTimeout(this.doubleClickTimeout); this.doubleClickTimeout = null; } } }
the_stack
import { ImgLazy } from '~/components/ui/ImgLazy'; import { Grid } from '~/components/layout/Grid'; import { FlexStack } from '~/components/layout/FlexStack'; import { TitleSection } from '~/components/lwjgl/TitleSection'; import { Dark } from '~/components/lwjgl/Dark'; import { SectionContainer } from '~/components/ui/Section'; export const GoldSponsors: React.FC = ({ children }) => ( <Dark> <SectionContainer padding> <TitleSection> Our <span style={{ color: 'gold' }}>Gold</span> Sponsors: </TitleSection> <Grid css={{ pt: '$gap', gap: '$safe', alignItems: 'center', width: '100%', img: { maxWidth: '100%', }, '@sm': { textAlign: 'center', grid: 'auto-flow / repeat(2, 1fr)', }, '@md': { grid: 'auto-flow / repeat(3, 1fr)', }, '@lg': { grid: 'auto-flow / repeat(4, 1fr)', }, }} > <a href="https://www.casinotop.com/" title="Online Casino Guide in Canada - Best Gaming Experience!" rel="sponsored noopener external" target="_blank" > <ImgLazy width={130 * 1.5} height={20 * 1.5} src="/img/sponsors/casinotop-129x20.svg" alt="CASINOTOP" /> </a> {/* <a href="https://www.parhaatnettikasinot.com/" title="Kaikki luotettavat ja parhaat nettikasinot" rel="sponsored noopener external" target="_blank" > <ImgLazy width={330.8 * 0.75} height={46.4 * 0.75} src="/img/sponsors/parhaat-nettikasinot.svg" alt="parhaat nettikasinot" /> </a> */} <a href="https://nettikasinot247.fi/" title="KÄRKITASON NETTIKASINOT" rel="sponsored noopener external" target="_blank" > <ImgLazy width={467 * 0.5} height={112 * 0.5} src="/img/sponsors/nettikasinot-logo-467x112.png" alt="NETTIKASINOT247" css={{ filter: 'invert(90%)' }} /> </a> <a href="https://nettikasinolista.com/" title="Se paras nettikasino-lista: arvostelut, bonukset ja kokemuksia" rel="sponsored noopener external" target="_blank" > <ImgLazy width={225} height={60} src="/img/sponsors/nettikasinolista.svg" alt="Nettikasino-lista" /> </a> <a href="https://www.turtlebet.com/fi/kaikki-nettikasinot.html" title="Kaikki nettikasinot - Katso Turtlebetin kaikki kasinot lista!" rel="sponsored noopener external" target="_blank" > <ImgLazy width={173} height={40} src="/img/sponsors/turtlebet-173x40.svg" alt="Turtlebet" css={{ filter: 'invert(100%) hue-rotate(180deg)' }} /> </a> <a href="https://www.vpsserver.com/" title="VPS HOSTING - GET YOUR FREE VPS TRIAL NOW!" rel="sponsored noopener external" target="_blank" > <ImgLazy width={218} height={50} src="/img/sponsors/vpsserver.com.svg" alt="VPSSERVER.com" /> </a> <a href="https://buy.fineproxy.org/eng/" rel="sponsored noopener external" target="_blank" title="BUY PROXY FROM FINEPROXY" > <ImgLazy width={250 / 1.25} height={70 / 1.25} src="/img/sponsors/fineproxy-logo-250x70.png" alt="Fineproxy" css={{ filter: 'invert(90%)' }} /> </a> <a href="https://www.bonus.net.nz/free-spins-no-deposit" title="Free Spins No Deposit" rel="sponsored noopener external" target="_blank" > <ImgLazy width={179.71} height={38} src="/img/sponsors/bonusfindernz.svg" alt="BonusFinder New Zealand" /> </a> <a href="https://www.kasinot.fi/" title="Kasinot netissä: #1 opas nettikasinoiden maailmaan" rel="sponsored noopener external" target="_blank" > <ImgLazy width={384 / 3} height={128 / 3} src="/img/sponsors/kasinot-384x128.png" alt="Kasinot.fi" /> </a> <a href="http://nettikasinot.org/" rel="sponsored noopener external" target="_blank" title="Universumin parhaat nettikasinot" > <ImgLazy width={585 / 3} height={116 / 3} src="/img/sponsors/nettikasinot-585x116.png" alt="Nettikasinot" /> </a> <a href="https://www.pelisivut.com/" title="Rahapelit netissä laadukkaasti ja luotettavasti" rel="sponsored noopener external" target="_blank" > <ImgLazy width={620 / 3} height={152 / 3} src="/img/sponsors/pelisivut-620x152.png" alt="PELISIVUT" /> </a> <a href="https://www.casinotopp.net/" title="Velkommen til CasinoTopp – Norges beste portal til online casino" rel="sponsored noopener external" target="_blank" > <ImgLazy width={144 * 1.25} height={20 * 1.25} src="/img/sponsors/casinotopp-143x20.svg" alt="CASINOTOPP" /> </a> <a href="https://www.bonusfinder.com/" title="Online Gambling at Bonusfinder USA" rel="sponsored noopener external" target="_blank" > <ImgLazy width={179.71} height={38} src="/img/sponsors/bonusfinderus.svg" alt="BonusFinder USA" /> </a> <a href="https://kajino.com/" title="オンラインカジノ リストとランキング 2021 - カジノ .com | Kajino" rel="sponsored noopener external" target="_blank" > <ImgLazy width={189} height={30} src="/img/sponsors/kajino.com-189x30.svg" alt="Kajino.com" /> </a> <a href="https://www.nettikasinot.media/" title="Nettikasinot: Mitkä ovat parhaat nettikasinot" rel="sponsored noopener external" target="_blank" > <ImgLazy width={48} height={48} src="/img/sponsors/nettikasinot.media.svg" alt="nettikasinot.media" /> </a> <a href="https://www.connessionivpn.it/" title="Connessioni VPN" rel="sponsored noopener external" target="_blank" > <FlexStack gap="0.5rem" css={{ color: '#577BFA', fontWeight: 'bold', '@md': { justifyContent: 'center', }, }} > <ImgLazy width={460 / 8} height={279 / 8} src="/img/sponsors/connessionivpn.it-460x279.svg" alt="Connessioni VPN" />{' '} <span>CONNESSIONI VPN</span> </FlexStack> </a> <a href="https://casinomartini.com/nz/new-online-casinos/" title="New Zealand New Online Casinos | Full List of New Casino Sites NZ" rel="sponsored noopener external" target="_blank" > <ImgLazy width={379 / 2} height={138 / 2} src="/img/sponsors/casino-martini.png" alt="Casino Martini" /> </a> <a href="https://goread.io/buy-instagram-followers" title="Buy Instagram Followers with Instant Delivery" rel="sponsored noopener external" target="_blank" > <ImgLazy width={1133 * 0.25} height={218 * 0.25} src="/img/sponsors/goread-1133x218.png" alt="Goread.io" /> </a> {/* <a href="https://www.boekonomi.se/" title="BoEkonomi.se | Vi hjälper dig ta hand om din ekonomi och ditt boende!" rel="sponsored noopener external" target="_blank" > <ImgLazy width={200 / 1.5} height={31 / 1.5} src="/img/sponsors/boekonomi-200x31.png" alt="BoEkonomi.se" /> </a> */} <a href="https://poprey.com/instagram_views" title="Buy Instagram Views" rel="sponsored noopener external" target="_blank" > <ImgLazy width={90} height={90} src="/img/sponsors/buy-instagram-views.png" alt="" /> </a> <a href="https://anbefaltcasino.com/" title="Beste norske nettcasinoer finner du på AnbefaltCasino.com" rel="sponsored noopener external" target="_blank" > <ImgLazy width={154.219 * 1.2} height={14.594 * 1.2} src="/img/sponsors/sanbefaltcasino.svg" alt="AnbefaltCasino.com" /> </a> <a href="https://list.casino/" title="List of All the Best Online Casinos - Ultimate Casino List!" rel="sponsored noopener external" target="_blank" > <ImgLazy width={447 / 2} height={119 / 2} src="/img/sponsors/list-casino.svg" alt="list.casino" /> </a> <a href="https://www.bonusfinder.co.uk/" title="Best Online Gambling Sites UK" rel="sponsored noopener external" target="_blank" > <ImgLazy width={318 / 1.5} height={64 / 1.5} src="/img/sponsors/bonusfinder-uk.svg" alt="BonusFinder UK" /> </a> <a href="https://casinoenlineahex.com/" title="CasinoEnLineaHEX" rel="sponsored noopener external" target="_blank" > <ImgLazy width={2565} height={734} style={{ width: 2565 / 13, height: 734 / 13 }} src="/img/sponsors/casinoenlineahex.svg" alt="CasinoEnLineaHEX" /> </a> <a href="https://nzcasinohex.com/" title="NZCasinoHex" rel="sponsored noopener external" target="_blank"> <ImgLazy width={200 / 2} height={51 / 2} src="/img/sponsors/nzcasinohex.png" alt="NZCasinoHex" /> </a> </Grid> {children} </SectionContainer> </Dark> );
the_stack
* Types generated by `yarn generate-types`. Do not edit manually. * * Version: 0.5.0 * Api Level: 7 * Api Compatible: 0 * Api Prerelease: false */ /** * UI events types emitted by `redraw` event. Do not edit manually. * More info: https://neovim.io/doc/user/ui.html */ export type UiEvents = { mode_info_set: [enabled: boolean, cursor_styles: Array<any>]; update_menu: []; busy_start: []; busy_stop: []; mouse_on: []; mouse_off: []; mode_change: [mode: string, mode_idx: number]; bell: []; visual_bell: []; flush: []; suspend: []; set_title: [title: string]; set_icon: [icon: string]; screenshot: [path: string]; option_set: [name: string, value: any]; update_fg: [fg: number]; update_bg: [bg: number]; update_sp: [sp: number]; resize: [width: number, height: number]; clear: []; eol_clear: []; cursor_goto: [row: number, col: number]; highlight_set: [attrs: Record<string, any>]; put: [str: string]; set_scroll_region: [top: number, bot: number, left: number, right: number]; scroll: [count: number]; default_colors_set: [ rgb_fg: number, rgb_bg: number, rgb_sp: number, cterm_fg: number, cterm_bg: number, ]; hl_attr_define: [ id: number, rgb_attrs: Record<string, any>, cterm_attrs: Record<string, any>, info: Array<any>, ]; hl_group_set: [name: string, id: number]; grid_resize: [grid: number, width: number, height: number]; grid_clear: [grid: number]; grid_cursor_goto: [grid: number, row: number, col: number]; grid_line: [grid: number, row: number, col_start: number, data: Array<any>]; grid_scroll: [ grid: number, top: number, bot: number, left: number, right: number, rows: number, cols: number, ]; grid_destroy: [grid: number]; win_pos: [ grid: number, win: number, startrow: number, startcol: number, width: number, height: number, ]; win_float_pos: [ grid: number, win: number, anchor: string, anchor_grid: number, anchor_row: number, anchor_col: number, focusable: boolean, zindex: number, ]; win_external_pos: [grid: number, win: number]; win_hide: [grid: number]; win_close: [grid: number]; msg_set_pos: [grid: number, row: number, scrolled: boolean, sep_char: string]; win_viewport: [ grid: number, win: number, topline: number, botline: number, curline: number, curcol: number, ]; popupmenu_show: [items: Array<any>, selected: number, row: number, col: number, grid: number]; popupmenu_hide: []; popupmenu_select: [selected: number]; tabline_update: [current: number, tabs: Array<any>, current_buffer: number, buffers: Array<any>]; cmdline_show: [ content: Array<any>, pos: number, firstc: string, prompt: string, indent: number, level: number, ]; cmdline_pos: [pos: number, level: number]; cmdline_special_char: [c: string, shift: boolean, level: number]; cmdline_hide: [level: number]; cmdline_block_show: [lines: Array<any>]; cmdline_block_append: [lines: Array<any>]; cmdline_block_hide: []; wildmenu_show: [items: Array<any>]; wildmenu_select: [selected: number]; wildmenu_hide: []; msg_show: [kind: string, content: Array<any>, replace_last: boolean]; msg_clear: []; msg_showcmd: [content: Array<any>]; msg_showmode: [content: Array<any>]; msg_ruler: [content: Array<any>]; msg_history_show: [entries: Array<any>]; }; /** * Nvim commands. * More info: https://neovim.io/doc/user/api.html */ export type NvimCommands = { nvim_buf_line_count: (buffer: number) => number; nvim_buf_attach: (buffer: number, send_buffer: boolean, opts: Record<string, any>) => boolean; nvim_buf_detach: (buffer: number) => boolean; nvim_buf_get_lines: ( buffer: number, start: number, end: number, strict_indexing: boolean, ) => string[]; nvim_buf_set_lines: ( buffer: number, start: number, end: number, strict_indexing: boolean, replacement: string[], ) => void; nvim_buf_set_text: ( buffer: number, start_row: number, start_col: number, end_row: number, end_col: number, replacement: string[], ) => void; nvim_buf_get_offset: (buffer: number, index: number) => number; nvim_buf_get_var: (buffer: number, name: string) => any; nvim_buf_get_changedtick: (buffer: number) => number; nvim_buf_get_keymap: (buffer: number, mode: string) => Record<string, any>[]; nvim_buf_set_keymap: ( buffer: number, mode: string, lhs: string, rhs: string, opts: Record<string, any>, ) => void; nvim_buf_del_keymap: (buffer: number, mode: string, lhs: string) => void; nvim_buf_get_commands: (buffer: number, opts: Record<string, any>) => Record<string, any>; nvim_buf_set_var: (buffer: number, name: string, value: any) => void; nvim_buf_del_var: (buffer: number, name: string) => void; nvim_buf_get_option: (buffer: number, name: string) => any; nvim_buf_set_option: (buffer: number, name: string, value: any) => void; nvim_buf_get_name: (buffer: number) => string; nvim_buf_set_name: (buffer: number, name: string) => void; nvim_buf_is_loaded: (buffer: number) => boolean; nvim_buf_delete: (buffer: number, opts: Record<string, any>) => void; nvim_buf_is_valid: (buffer: number) => boolean; nvim_buf_get_mark: (buffer: number, name: string) => [number, number]; nvim_buf_get_extmark_by_id: ( buffer: number, ns_id: number, id: number, opts: Record<string, any>, ) => number[]; nvim_buf_get_extmarks: ( buffer: number, ns_id: number, start: any, end: any, opts: Record<string, any>, ) => Array<any>; nvim_buf_set_extmark: ( buffer: number, ns_id: number, line: number, col: number, opts: Record<string, any>, ) => number; nvim_buf_del_extmark: (buffer: number, ns_id: number, id: number) => boolean; nvim_buf_add_highlight: ( buffer: number, ns_id: number, hl_group: string, line: number, col_start: number, col_end: number, ) => number; nvim_buf_clear_namespace: ( buffer: number, ns_id: number, line_start: number, line_end: number, ) => void; nvim_buf_set_virtual_text: ( buffer: number, src_id: number, line: number, chunks: Array<any>, opts: Record<string, any>, ) => number; nvim_buf_call: (buffer: number, fun: any) => any; nvim_tabpage_list_wins: (tabpage: number) => number[]; nvim_tabpage_get_var: (tabpage: number, name: string) => any; nvim_tabpage_set_var: (tabpage: number, name: string, value: any) => void; nvim_tabpage_del_var: (tabpage: number, name: string) => void; nvim_tabpage_get_win: (tabpage: number) => number; nvim_tabpage_get_number: (tabpage: number) => number; nvim_tabpage_is_valid: (tabpage: number) => boolean; nvim_ui_attach: (width: number, height: number, options: Record<string, any>) => void; nvim_ui_detach: () => void; nvim_ui_try_resize: (width: number, height: number) => void; nvim_ui_set_option: (name: string, value: any) => void; nvim_ui_try_resize_grid: (grid: number, width: number, height: number) => void; nvim_ui_pum_set_height: (height: number) => void; nvim_ui_pum_set_bounds: (width: number, height: number, row: number, col: number) => void; nvim_exec: (src: string, output: boolean) => string; nvim_command: (command: string) => void; nvim_get_hl_by_name: (name: string, rgb: boolean) => Record<string, any>; nvim_get_hl_by_id: (hl_id: number, rgb: boolean) => Record<string, any>; nvim_get_hl_id_by_name: (name: string) => number; nvim_set_hl: (ns_id: number, name: string, val: Record<string, any>) => void; nvim_feedkeys: (keys: string, mode: string, escape_csi: boolean) => void; nvim_input: (keys: string) => number; nvim_input_mouse: ( button: string, action: string, modifier: string, grid: number, row: number, col: number, ) => void; nvim_replace_termcodes: ( str: string, from_part: boolean, do_lt: boolean, special: boolean, ) => string; nvim_eval: (expr: string) => any; nvim_exec_lua: (code: string, args: Array<any>) => any; nvim_notify: (msg: string, log_level: number, opts: Record<string, any>) => any; nvim_call_function: (fn: string, args: Array<any>) => any; nvim_call_dict_function: (dict: any, fn: string, args: Array<any>) => any; nvim_strwidth: (text: string) => number; nvim_list_runtime_paths: () => string[]; nvim_get_runtime_file: (name: string, all: boolean) => string[]; nvim_set_current_dir: (dir: string) => void; nvim_get_current_line: () => string; nvim_set_current_line: (line: string) => void; nvim_del_current_line: () => void; nvim_get_var: (name: string) => any; nvim_set_var: (name: string, value: any) => void; nvim_del_var: (name: string) => void; nvim_get_vvar: (name: string) => any; nvim_set_vvar: (name: string, value: any) => void; nvim_get_option: (name: string) => any; nvim_get_all_options_info: () => Record<string, any>; nvim_get_option_info: (name: string) => Record<string, any>; nvim_set_option: (name: string, value: any) => void; nvim_echo: (chunks: Array<any>, history: boolean, opts: Record<string, any>) => void; nvim_out_write: (str: string) => void; nvim_err_write: (str: string) => void; nvim_err_writeln: (str: string) => void; nvim_list_bufs: () => number[]; nvim_get_current_buf: () => number; nvim_set_current_buf: (buffer: number) => void; nvim_list_wins: () => number[]; nvim_get_current_win: () => number; nvim_set_current_win: (win: number) => void; nvim_create_buf: (listed: boolean, scratch: boolean) => number; nvim_open_term: (buffer: number, opts: Record<string, any>) => number; nvim_chan_send: (chan: number, data: string) => void; nvim_open_win: (buffer: number, enter: boolean, config: Record<string, any>) => number; nvim_list_tabpages: () => number[]; nvim_get_current_tabpage: () => number; nvim_set_current_tabpage: (tabpage: number) => void; nvim_create_namespace: (name: string) => number; nvim_get_namespaces: () => Record<string, any>; nvim_paste: (data: string, crlf: boolean, phase: number) => boolean; nvim_put: (lines: string[], type: string, after: boolean, follow: boolean) => void; nvim_subscribe: (event: string) => void; nvim_unsubscribe: (event: string) => void; nvim_get_color_by_name: (name: string) => number; nvim_get_color_map: () => Record<string, any>; nvim_get_context: (opts: Record<string, any>) => Record<string, any>; nvim_load_context: (dict: Record<string, any>) => any; nvim_get_mode: () => Record<string, any>; nvim_get_keymap: (mode: string) => Record<string, any>[]; nvim_set_keymap: (mode: string, lhs: string, rhs: string, opts: Record<string, any>) => void; nvim_del_keymap: (mode: string, lhs: string) => void; nvim_get_commands: (opts: Record<string, any>) => Record<string, any>; nvim_get_api_info: () => Array<any>; nvim_set_client_info: ( name: string, version: Record<string, any>, type: string, methods: Record<string, any>, attributes: Record<string, any>, ) => void; nvim_get_chan_info: (chan: number) => Record<string, any>; nvim_list_chans: () => Array<any>; nvim_call_atomic: (calls: Array<any>) => Array<any>; nvim_parse_expression: (expr: string, flags: string, highlight: boolean) => Record<string, any>; nvim_list_uis: () => Array<any>; nvim_get_proc_children: (pid: number) => Array<any>; nvim_get_proc: (pid: number) => any; nvim_select_popupmenu_item: ( item: number, insert: boolean, finish: boolean, opts: Record<string, any>, ) => void; nvim_set_decoration_provider: (ns_id: number, opts: Record<string, any>) => void; nvim_win_get_buf: (win: number) => number; nvim_win_set_buf: (win: number, buffer: number) => void; nvim_win_get_cursor: (win: number) => [number, number]; nvim_win_set_cursor: (win: number, pos: [number, number]) => void; nvim_win_get_height: (win: number) => number; nvim_win_set_height: (win: number, height: number) => void; nvim_win_get_width: (win: number) => number; nvim_win_set_width: (win: number, width: number) => void; nvim_win_get_var: (win: number, name: string) => any; nvim_win_set_var: (win: number, name: string, value: any) => void; nvim_win_del_var: (win: number, name: string) => void; nvim_win_get_option: (win: number, name: string) => any; nvim_win_set_option: (win: number, name: string, value: any) => void; nvim_win_get_position: (win: number) => [number, number]; nvim_win_get_tabpage: (win: number) => number; nvim_win_get_number: (win: number) => number; nvim_win_is_valid: (win: number) => boolean; nvim_win_set_config: (win: number, config: Record<string, any>) => void; nvim_win_get_config: (win: number) => Record<string, any>; nvim_win_hide: (win: number) => void; nvim_win_close: (win: number, force: boolean) => void; nvim_win_call: (win: number, fun: any) => any; };
the_stack
import * as React from "react"; import { Color, ItemEventData, ObservableArray } from "@nativescript/core"; import { ListView, CellViewContainer } from "react-nativescript"; export class ListViewTest extends React.Component<{}, {}> { render(){ type Item = number; const items: Item[] = [...Array(200).keys()]; /* There may be an argument for nesting the ListView within a LayoutBase once * dealing with the Safe Area (shall have to find out and see!). */ return ( <ListView _debug={{ logLevel: "info", onCellFirstLoad: (container: CellViewContainer) => { container.backgroundColor = "orange"; }, onCellRecycle: (container: CellViewContainer) => { container.backgroundColor = "blue"; }, }} height={{ unit: "%", value: 100 }} items={[...items.map((val: Item) => val)]} // cellFactory={(item: Item) => { // return ( // <label // // key={container._domId} // fontSize={24} // > // {`#${item}`} // </label> // ); // }} itemTemplateSelector={(item: Item, index: number, items: any): string => { return index % 2 === 0 ? "even" : "odd"; }} cellFactories={new Map([ [ "odd", { placeholderItem: 1, cellFactory: (item: Item) => { return ( <label // key={container._domId} fontSize={24} > {`ODD #${item}`} </label> ); } } ], [ "even", { placeholderItem: 0, cellFactory: (item: Item) => { return ( <textView // key={container._domId} fontSize={24} > {`EVEN #${item}`} </textView> ); } } ], ])} /> ); } } /** * Code below here ported to React NativeScript from React Native's RNTester app: * https://github.com/microsoft/react-native/blob/master/RNTester/js/ListViewExample.js * ... which carries the following copyright: * Copyright (c) 2015-present, Facebook, Inc. * All rights reserved. * * This source code is licensed under the BSD-style license found in the * LICENSE file in the root directory of this source tree. An additional grant * of patent rights can be found in the PATENTS file in the same directory. */ /** Used in accordance with React_Native_LICENSE.txt in the RNTester_Thumbnails folder. */ const THUMB_URLS: string[] = [ "~/images/RNTester_Thumbnails/like.png", "~/images/RNTester_Thumbnails/dislike.png", "~/images/RNTester_Thumbnails/call.png", "~/images/RNTester_Thumbnails/fist.png", "~/images/RNTester_Thumbnails/bandaged.png", "~/images/RNTester_Thumbnails/flowers.png", "~/images/RNTester_Thumbnails/heart.png", "~/images/RNTester_Thumbnails/liking.png", "~/images/RNTester_Thumbnails/party.png", "~/images/RNTester_Thumbnails/poke.png", "~/images/RNTester_Thumbnails/superlike.png", "~/images/RNTester_Thumbnails/victory.png", ]; const LOREM_IPSUM: string = "Lorem ipsum dolor sit amet, ius ad pertinax oportere accommodare, an vix civibus corrumpit referrentur. Te nam case ludus inciderint, te mea facilisi adipiscing. Sea id integre luptatum. In tota sale consequuntur nec. Erat ocurreret mei ei. Eu paulo sapientem vulputate est, vel an accusam intellegam interesset. Nam eu stet pericula reprimique, ea vim illud modus, putant invidunt reprehendunt ne qui."; function hashCode(str: string): number { let hash: number = 15; for(let ii = str.length - 1; ii >= 0; ii--){ hash = ((hash << 5) - hash) + str.charCodeAt(ii); } return hash; }; type IndexToContentItem = { index: number, content: string, }; export class DynamicListViewWithImages extends React.Component<{}, {}> { // private readonly _genRows = (pressData: Record<number, boolean>): string[] => { // const dataBlob: string[] = []; // for(let ii = 0; ii < 100; ii++){ // const pressedText = pressData[ii] ? " (pressed)" : ""; // dataBlob.push(`Row ${ii}${pressedText}`); // } // return dataBlob; // }; private readonly itemsToLoad: number = 100; /* Optimisation note: at list initialisation, Portals SHALL be rendered for each item in the starting list. */ private readonly items: ObservableArray<IndexToContentItem> = new ObservableArray( [...Array(this.itemsToLoad).keys()] .map((value: number) => ({ index: value, content: value.toString() })) ); private loadMore: boolean = true; private loadMoreTimeout?:any; /* Making this no-op is sufficient to restore this to being a static list view. */ private readonly onLoadMoreItems = (args: ItemEventData) => { if(!this.loadMore){ console.log(`[onLoadMoreItems] debouncing.`); return; } console.log(`[onLoadMoreItems] permitted.`); this.loadMoreTimeout = setTimeout(() => { const itemsToPush = []; for(let i = this.items.length; i < + this.items.length + this.itemsToLoad; i++){ const lastValueIncremented: number = i; itemsToPush.push({ index: lastValueIncremented, content: lastValueIncremented.toString() }); } this.items.push(itemsToPush); this.loadMore = true; }, 750); /* Ample time for a (typical) scroll action's inertia to settle, to avoid list jumpiness. */ this.loadMore = false; }; componentWillUnmount(){ if(this.loadMoreTimeout) clearTimeout(this.loadMoreTimeout); } private readonly styles = { row: { /* Tried with Flexbox, but it's far too non-compliant and doesn't function as expected. */ // flexDirection: "row" as "row", // justifyContent: "center" as "center", padding: 10, backgroundColor: new Color("#F6F6F6"), }, thumb: { width: { value: 64, unit: "px" as "px" }, height: { value: 64, unit: "px" as "px" }, }, bigThumb: { width: { value: 64, unit: "px" as "px" }, height: { value: 64, unit: "px" as "px" }, }, text: { flexGrow: 1 } }; render(){ return ( <ListView _debug={{ logLevel: "info", onCellFirstLoad: (container: CellViewContainer) => { // container.backgroundColor = "orange"; }, onCellRecycle: (container: CellViewContainer) => { // container.backgroundColor = "blue"; }, }} height={{ unit: "%", value: 100 }} width={{ unit: "%", value: 100 }} items={this.items} onLoadMoreItems={this.onLoadMoreItems} /* If you only have one template, there's no advantage in setting up a templated list (it's actually wasteful: one extra reconciliation). */ itemTemplateSelector={(item: IndexToContentItem, index: number, items: any): string => { return index % 2 === 0 ? "even" : "odd"; }} cellFactories={new Map([ [ "even", { placeholderItem: { index: 1, content: "PLACEHOLDER" }, cellFactory: (item: IndexToContentItem) => { const rowHash: number = Math.abs(hashCode(item.index.toString())); const imgSource: string = THUMB_URLS[rowHash % THUMB_URLS.length]; return ( <gridLayout rows={"*"} columns={"64 *"} > <image row={0} col={0} src={imgSource} style={this.styles.thumb} stretch={"aspectFill"} /> <textView row={0} col={1} // key={container._domId} text={item.index.toString()} fontSize={12} paddingRight={8} > {`${item.index} - ${LOREM_IPSUM.substr(0, rowHash % 301 + 10)}`} </textView> </gridLayout> ); } } ], [ "odd", { placeholderItem: { index: 1, content: "PLACEHOLDER" }, cellFactory: (item: IndexToContentItem) => { const rowHash: number = Math.abs(hashCode(item.index.toString())); const imgSource: string = THUMB_URLS[rowHash % THUMB_URLS.length]; return ( <gridLayout backgroundColor={new Color("yellow")} rows={"*"} columns={"* 64"} > <textView paddingLeft={8} row={0} col={0} // key={container._domId} text={item.index.toString()} fontSize={12} > {`${item.index} - ${LOREM_IPSUM.substr(0, rowHash % 301 + 10)}`} </textView> <image row={0} col={1} src={imgSource} style={this.styles.bigThumb} stretch={"aspectFill"} /> </gridLayout> ); } } ] ])} // cellFactory={(item: IndexToContentItem) => { // const rowHash: number = Math.abs(hashCode(item.index.toString())); // const imgSource: string = THUMB_URLS[rowHash % THUMB_URLS.length]; // return ( // <gridLayout // rows={[new ItemSpec(1, "star")]} // columns={[new ItemSpec(64, "pixel"), new ItemSpec(1, "star")]} // > // <image // row={0} // col={0} // src={imgSource} // style={this.styles.thumb} // stretch={"aspectFill"} // /> // <label // row={0} // col={1} // // key={container._domId} // text={item.index.toString()} // fontSize={12} // > // {`${item.index} - ${LOREM_IPSUM.substr(0, rowHash % 301 + 10)}`} // </label> // </gridLayout> // ); // }} /> ); } }
the_stack
import { isIterable, isFunction, isMissing, isInstance } from "@esfx/internal-guards"; import { Collection, ReadonlyCollection } from "@esfx/collection-core"; import { Equaler, EqualityComparison } from "@esfx/equatable"; const kList = Symbol("LinkedListNode.list"); const kPrevious = Symbol("LinkedListNode.previous"); const kNext = Symbol("LinkedListNode.next"); /** * A node in a [doubly-linked list](https://en.wikipedia.org/wiki/Doubly_linked_list). */ export class LinkedListNode<T> { [kList]: LinkedList<T> | undefined = undefined; [kPrevious]: LinkedListNode<T> | undefined = undefined; [kNext]: LinkedListNode<T> | undefined = undefined; /** * The value for the node. */ value: T; constructor(value: T) { this.value = value; } /** * Gets the list associated with this node. If the node is not attached to a {@link LinkedList}, then this returns * `undefined`. */ get list(): LinkedList<T> | undefined { return this[kList]; } /** * Gets the {@link LinkedListNode} preceding this node in the list. If this is the first node in the list, or the * node is not attached to a {@link LinkedList}, then this returns `undefined`. */ get previous(): LinkedListNode<T> | undefined { if (this[kPrevious] && this.list && this !== this.list.first) { return this[kPrevious]; } return undefined; } /** * Gets the {@link LinkedListNode} following this node in the list. If this is the last node in the list, or the * node is not attached to a {@link LinkedList}, then this returns `undefined`. */ get next(): LinkedListNode<T> | undefined { if (this[kNext] && this.list && this[kNext] !== this.list.first) { return this[kNext]; } return undefined; } /** * Removes this node from its associated list. * @returns `true` if the node was successfully removed from the list; otherwise, `false`. */ detachSelf() { return this.list ? this.list.deleteNode(this) : false; } [Symbol.toStringTag]!: string; } Object.defineProperty(LinkedListNode.prototype, Symbol.toStringTag, { enumerable: false, configurable: true, writable: true, value: "LinkedListNode" }); const enum Position { before, after } /** * A collection representing a [doubly-linked list](https://en.wikipedia.org/wiki/Doubly_linked_list). */ export class LinkedList<T> implements Collection<T> { private _size: number = 0; private _head: LinkedListNode<T> | undefined = undefined; private _equaler: Equaler<T>; constructor(equaler?: EqualityComparison<T> | Equaler<T>); constructor(iterable?: Iterable<T>, equaler?: EqualityComparison<T> | Equaler<T>); constructor(...args: [(EqualityComparison<T> | Equaler<T>)?] | [Iterable<T>?, (EqualityComparison<T> | Equaler<T>)?]) { let iterable: Iterable<T> | undefined; let equaler: EqualityComparison<T> | Equaler<T> | undefined; if (args.length > 0) { if (isIterable(args[0]) || isMissing(args[0])) { iterable = args[0]; if (args.length > 1) equaler = args[1]; } else { equaler = args[0]; } } if (isMissing(equaler)) { equaler = Equaler.defaultEqualer; } this._equaler = typeof equaler === "function" ? Equaler.create(equaler) : equaler; if (iterable) { for (const value of iterable) { this.push(value); } } } /** * Gets the {@link Equaler} used for equality comparisons in this list. */ get equaler(): Equaler<T> { return this._equaler; } /** * Gets the first node in the list. If the list is empty, this returns `undefined`. */ get first(): LinkedListNode<T> | undefined { return this._head; } /** * Gets the last node in the list. If the list is empty, this returns `undefined`. */ get last(): LinkedListNode<T> | undefined { if (this._head) { return this._head[kPrevious]; } return undefined; } /** * Gets the number of elements in the list. */ get size(): number { return this._size; } [Symbol.iterator]() { return this.values(); } * values(): IterableIterator<T> { for (const node of this.nodes()) { yield node.value; } } * nodes(): IterableIterator<LinkedListNode<T>> { let node: LinkedListNode<T>; let next = this.first; while (next !== undefined) { node = next; next = node.next; yield node; } } /** * Returns an iterator that removes each node from the list before yielding the node's value. */ * drain(): IterableIterator<T> { for (const node of this.nodes()) { this.deleteNode(node); yield node.value; } } /** * Finds the first node in the list with the provided value. * @param value The value to find. * @param fromNode When provided, starts looking for `value` starting at this node. */ nodeOf(value: T, fromNode?: LinkedListNode<T>): LinkedListNode<T> | undefined { if (!isMissing(fromNode) && !isInstance(fromNode, LinkedListNode)) throw new TypeError("LinkedListNode expected: fromNode"); if (!isMissing(fromNode) && fromNode.list !== this) throw new TypeError("Wrong list."); for (let node = fromNode || this.first; node; node = node.next) { if (this._equaler.equals(node.value, value)) { return node; } } return undefined; } /** * Finds the last node in the list with the provided value, starting from the end of the list. * @param value The value to find. * @param fromNode When provided, starts looking for `value` starting at this node and working backwards towards the front of the list. */ lastNodeOf(value: T, fromNode?: LinkedListNode<T>): LinkedListNode<T> | undefined { if (!isMissing(fromNode) && !isInstance(fromNode, LinkedListNode)) throw new TypeError("LinkedListNode expected: fromNode"); if (!isMissing(fromNode) && fromNode.list !== this) throw new TypeError("Wrong list."); for (let node = fromNode || this.last; node; node = node.previous) { if (this._equaler.equals(node.value, value)) { return node; } } return undefined; } /** * Finds the first value in the list that matches the provided callback. * @param callback The callback used to test each value and node. * @param thisArg The `this` value to use when executing `callback`. */ find<S extends T>(callback: (value: T, node: LinkedListNode<T>, list: LinkedList<T>) => value is S, thisArg?: any): S | undefined; /** * Finds the first value in the list that matches the provided callback. * @param callback The callback used to test each value and node. * @param thisArg The `this` value to use when executing `callback`. */ find(callback: (value: T, node: LinkedListNode<T>, list: LinkedList<T>) => boolean, thisArg?: any): T | undefined; find(callback: (value: T, node: LinkedListNode<T>, list: LinkedList<T>) => boolean, thisArg?: any): T | undefined { if (!isFunction(callback)) throw new TypeError("Function expected: callback"); let node: LinkedListNode<T>; let next = this.first; while (next !== undefined) { node = next; next = node.next; const value = node.value; if (callback.call(thisArg, value, node, this)) return value; } return undefined; } /** * Finds the last value in the list that matches the provided callback, starting from the end of the list. * @param callback The callback used to test each value and node. * @param thisArg The `this` value to use when executing `callback`. */ findLast<S extends T>(callback: (value: T, node: LinkedListNode<T>, list: LinkedList<T>) => value is S, thisArg?: any): S | undefined; /** * Finds the last value in the list that matches the provided callback, starting from the end of the list. * @param callback The callback used to test each value and node. * @param thisArg The `this` value to use when executing `callback`. */ findLast(callback: (value: T, node: LinkedListNode<T>, list: LinkedList<T>) => boolean, thisArg?: any): T | undefined; findLast(callback: (value: T, node: LinkedListNode<T>, list: LinkedList<T>) => boolean, thisArg?: any): T | undefined { if (!isFunction(callback)) throw new TypeError("Function expected: callback"); let node: LinkedListNode<T>; let prev = this.last; while (prev !== undefined) { node = prev; prev = node.previous; const value = node.value; if (callback.call(thisArg, value, node, this)) return value; } return undefined; } /** * Finds the first {@link LinkedListNode} in the list that matches the provided callback. * @param callback The callback used to test each value and node. * @param thisArg The `this` value to use when executing `callback`. */ findNode<S extends T>(callback: (value: T, node: LinkedListNode<T>, list: LinkedList<T>) => value is S, thisArg?: any): LinkedListNode<S> | undefined; /** * Finds the first {@link LinkedListNode} in the list that matches the provided callback. * @param callback The callback used to test each value and node. * @param thisArg The `this` value to use when executing `callback`. */ findNode(callback: (value: T, node: LinkedListNode<T>, list: LinkedList<T>) => boolean, thisArg?: any): LinkedListNode<T> | undefined; findNode(callback: (value: T, node: LinkedListNode<T>, list: LinkedList<T>) => boolean, thisArg?: any): LinkedListNode<T> | undefined { if (!isFunction(callback)) throw new TypeError("Function expected: callback"); let node: LinkedListNode<T>; let next = this.first; while (next !== undefined) { node = next; next = node.next; if (callback.call(thisArg, node.value, node, this)) return node; } return undefined; } /** * Finds the last {@link LinkedListNode} in the list that matches the provided callback, starting from the end of the list. * @param callback The callback used to test each value and node. * @param thisArg The `this` value to use when executing `callback`. */ findLastNode<S extends T>(callback: (value: T, node: LinkedListNode<T>, list: LinkedList<T>) => value is S, thisArg?: any): LinkedListNode<S> | undefined; /** * Finds the last {@link LinkedListNode} in the list that matches the provided callback, starting from the end of the list. * @param callback The callback used to test each value and node. * @param thisArg The `this` value to use when executing `callback`. */ findLastNode(callback: (value: T, node: LinkedListNode<T>, list: LinkedList<T>) => boolean, thisArg?: any): LinkedListNode<T> | undefined; findLastNode(callback: (value: T, node: LinkedListNode<T>, list: LinkedList<T>) => boolean, thisArg?: any): LinkedListNode<T> | undefined { if (!isFunction(callback)) throw new TypeError("Function expected: callback"); let node: LinkedListNode<T>; let prev = this.last; while (prev !== undefined) { node = prev; prev = node.previous; if (callback.call(thisArg, node.value, node, this)) return node; } return undefined; } /** * Returns a value indicating whether `value` exists within the list. */ has(value: T): boolean { return this.nodeOf(value) !== undefined; } /** * Inserts a new {@link LinkedListNode} containing `value` into the list before the provided `node`. * If `node` is either `null` or `undefined`, the new node is inserted at the beginning of the list. * @param node The node before which `value` will be inserted. * @param value The value to insert. * @returns The new {@link LinkedListNode} for `value`. */ insertBefore(node: LinkedListNode<T> | null | undefined, value: T): LinkedListNode<T> { if (!isMissing(node) && !isInstance(node, LinkedListNode)) throw new TypeError("LinkedListNode expected: node"); if (!isMissing(node) && node.list !== this) throw new Error("Wrong list."); return this._insertNode(node || undefined, new LinkedListNode(value), Position.before); } /** * Inserts `newNode` into the list before the provided `node`. If `node` is either `null` or `undefined`, `newNode` * is inserted at the beginning of the list. * @param node The node before which `newNode` will be inserted. * @param newNode The new node to insert. */ insertNodeBefore(node: LinkedListNode<T> | null | undefined, newNode: LinkedListNode<T>): void { if (!isMissing(node) && !isInstance(node, LinkedListNode)) throw new TypeError("LinkedListNode expected: node"); if (!isInstance(newNode, LinkedListNode)) throw new TypeError("LinkedListNode expected: newNode"); if (!isMissing(node) && node.list !== this) throw new Error("Wrong list."); if (!isMissing(newNode.list)) throw new Error("Node is already attached to a list."); this._insertNode(node || undefined, newNode, Position.before); } /** * Inserts a new {@link LinkedListNode} containing `value` into the list after the provided `node`. * If `node` is either `null` or `undefined`, the new node is inserted at the end of the list. * @param node The node after which `value` will be inserted. * @param value The value to insert. * @returns The new {@link LinkedListNode} for `value`. */ insertAfter(node: LinkedListNode<T> | null | undefined, value: T): LinkedListNode<T> { if (!isMissing(node) && !isInstance(node, LinkedListNode)) throw new TypeError("LinkedListNode expected: node"); if (!isMissing(node) && node.list !== this) throw new Error("Wrong list."); return this._insertNode(node || undefined, new LinkedListNode(value), Position.after); } /** * Inserts `newNode` into the list after the provided `node`. If `node` is either `null` or `undefined`, `newNode` * is inserted at the end of the list. * @param node The node after which `newNode` will be inserted. * @param newNode The new node to insert. */ insertNodeAfter(node: LinkedListNode<T> | null | undefined, newNode: LinkedListNode<T>): void { if (!isMissing(node) && !isInstance(node, LinkedListNode)) throw new TypeError("LinkedListNode expected: node"); if (!isInstance(newNode, LinkedListNode)) throw new TypeError("LinkedListNode expected: newNode"); if (!isMissing(node) && node.list !== this) throw new Error("Wrong list."); if (!isMissing(newNode.list)) throw new Error("Node is already attached to a list."); this._insertNode(node || undefined, newNode, Position.after); } /** * Inserts a new {@link LinkedListNode} containing `value` at the end of the list. * @param value The value to insert. * @returns The new {@link LinkedListNode} for `value`. */ push(value: T): LinkedListNode<T> { return this._insertNode(undefined, new LinkedListNode(value), Position.after); } /** * Inserts `newNode` at the end of the list. * @param newNode The node to insert. */ pushNode(newNode: LinkedListNode<T>): void { if (!isInstance(newNode, LinkedListNode)) throw new TypeError("LinkedListNode expected: newNode"); if (!isMissing(newNode.list)) throw new Error("Node is already attached to a list."); this._insertNode(undefined, newNode, Position.after); } /** * Removes the last node from the list and returns its value. If the list is empty, `undefined` is returned instead. */ pop(): T | undefined { const node = this.popNode(); return node ? node.value : undefined; } /** * Removes the last node from the list and returns it. If the lsit is empty, `undefined` is returned instead. */ popNode(): LinkedListNode<T> | undefined { const node = this.last; if (this.deleteNode(node)) { return node; } } /** * Removes the first node from the list and returns its value. If the list is empty, `undefined` is returned instead. */ shift(): T | undefined { const node = this.shiftNode(); return node ? node.value : undefined; } /** * Removes the first node from the list and returns it. If the list is empty, `undefined` is returned instead. */ shiftNode(): LinkedListNode<T> | undefined { const node = this.first; if (this.deleteNode(node)) { return node; } } /** * Inserts a new {@link LinkedListNode} containing `value` at the beginning of the list. * @param value The value to insert. * @returns The new {@link LinkedListNode} for `value`. */ unshift(value: T): LinkedListNode<T> { return this._insertNode(undefined, new LinkedListNode(value), Position.before); } /** * Inserts `newNode` at the beginning of the list. * @param newNode The node to insert. */ unshiftNode(newNode: LinkedListNode<T>): void { if (!isInstance(newNode, LinkedListNode)) throw new TypeError("LinkedListNode expected: newNode"); if (!isMissing(newNode.list)) throw new Error("Node is already attached to a list."); this._insertNode(undefined, newNode, Position.before); } /** * Finds the first node in the list containing `value`, removes it from the list, and returns it. If a node * containing `value` could not be found, `undefined` is returned instead. */ delete(value: T): LinkedListNode<T> | undefined { const node = this.nodeOf(value); if (node && this.deleteNode(node)) { return node; } return undefined; } /** * Removes the provided node from the list. * @returns `true` if the node was successfully removed from the list; otherwise, `false`. */ deleteNode(node: LinkedListNode<T> | null | undefined): boolean { if (!isMissing(node) && !isInstance(node, LinkedListNode)) throw new TypeError("LinkedListNode expected: node"); if (!isMissing(node) && !isMissing(node.list) && node.list !== this) throw new TypeError("Wrong list."); if (isMissing(node) || isMissing(node.list)) return false; return this._deleteNode(node); } /** * Removes all nodes from the list matching the supplied `predicate`. * @param predicate A callback function used to test each value and node in the list. * @param thisArg The `this` value to use when executing `predicate`. */ deleteAll(predicate: (value: T, node: LinkedListNode<T>, list: LinkedList<T>) => boolean, thisArg?: any) { if (!isFunction(predicate)) throw new TypeError("Function expected: predicate"); let count = 0; let node = this.first; while (node) { const next = node.next; if (predicate.call(thisArg, node.value, node, this) && node.list === this) { this._deleteNode(node); ++count; } node = next; } return count; } /** * Removes all nodes from the list. */ clear(): void { while (this.size > 0) { this.deleteNode(this.last); } } forEach(callback: (value: T, node: LinkedListNode<T>, list: LinkedList<T>) => void, thisArg?: any) { if (!isFunction(callback)) throw new TypeError("Function expected: callback"); let node: LinkedListNode<T>; let next = this.first; while (next !== undefined) { node = next; next = node.next; callback.call(thisArg, node.value, node, this); } } /** * Calls the provided `callback` function on each element of the list, and returns a new {@link LinkedList} that contains the results. * @param callback The callback to call for each value and node. * @param thisArg The `this` value to use when executing `callback`. */ map<U>(callback: (value: T, node: LinkedListNode<T>, list: LinkedList<T>) => U, thisArg?: any) { if (!isFunction(callback)) throw new TypeError("Function expected: callback"); [].map const mappedList = new LinkedList<U>(); let node: LinkedListNode<T>; let next = this.first; while (next !== undefined) { node = next; next = node.next; const mappedValue = callback.call(thisArg, node.value, node, this); mappedList.push(mappedValue); } return mappedList; } /** * Returns the elements of a the list that meet the condition specified in the provided `callback` function. * @param callback The `callback` to call for each value and node. * @param thisArg The `this` value to use when executing `callback`. */ filter<S extends T>(callback: (value: T, node: LinkedListNode<T>, list: LinkedList<T>) => value is S, thisArg?: any): LinkedList<S>; /** * Returns the elements of a the list that meet the condition specified in the provided `callback` function. * @param callback The `callback` to call for each value and node. * @param thisArg The `this` value to use when executing `callback`. */ filter(callback: (value: T, node: LinkedListNode<T>, list: LinkedList<T>) => boolean, thisArg?: any): LinkedList<T>; filter(callback: (value: T, node: LinkedListNode<T>, list: LinkedList<T>) => boolean, thisArg?: any) { if (!isFunction(callback)) throw new TypeError("Function expected: callback"); const mappedList = new LinkedList<T>(this.equaler); let node: LinkedListNode<T>; let next = this.first; while (next !== undefined) { node = next; next = node.next; const value = node.value; if (callback.call(thisArg, value, node, this)) { mappedList.push(value); } } return mappedList; } /** * Calls the specified `callback` function for all the nodes in the list. The return value of the callback function is the accumulated result, * and is provided as an argument in the next call to the callback function. * @param callback A function that accepts up to four arguments. The reduce method calls the callback function one time for each element in the list. */ reduce(callback: (previousValue: T, value: T, node: LinkedListNode<T>, list: LinkedList<T>) => T): T; /** * Calls the specified `callback` function for all the nodes in the list. The return value of the callback function is the accumulated result, * and is provided as an argument in the next call to the callback function. * @param callback A function that accepts up to four arguments. The reduce method calls the callback function one time for each element in the list. * @param initialValue If initialValue is specified, it is used as the initial value to start the accumulation. The first call to the `callback` function provides this value as an argument instead of a list value. */ reduce(callback: (previousValue: T, value: T, node: LinkedListNode<T>, list: LinkedList<T>) => T, initialValue: T): T; /** * Calls the specified `callback` function for all the nodes in the list. The return value of the callback function is the accumulated result, * and is provided as an argument in the next call to the callback function. * @param callback A function that accepts up to four arguments. The reduce method calls the callback function one time for each element in the list. * @param initialValue If initialValue is specified, it is used as the initial value to start the accumulation. The first call to the `callback` function provides this value as an argument instead of a list value. */ reduce<U>(callback: (previousValue: U, value: T, node: LinkedListNode<T>, list: LinkedList<T>) => U, initialValue: U): U; reduce(callback: (previousValue: T, value: T, node: LinkedListNode<T>, list: LinkedList<T>) => T, initialValue?: T) { if (!isFunction(callback)) throw new TypeError("Function expected: callback"); let hasInitialValue = arguments.length > 1; let result = initialValue; let node: LinkedListNode<T>; let next = this.first; while (next !== undefined) { node = next; next = node.next; const value = node.value; if (!hasInitialValue) { result = value; hasInitialValue = true; } else { result = callback(result!, value, node, this); } } return result; } /** * Calls the specified `callback` function for all the nodes in the list, in reverse. The return value of the callback function is the accumulated result, * and is provided as an argument in the next call to the callback function. * @param callback A function that accepts up to four arguments. The reduce method calls the callback function one time for each element in the list. */ reduceRight(callback: (previousValue: T, value: T, node: LinkedListNode<T>, list: LinkedList<T>) => T): T; /** * Calls the specified `callback` function for all the nodes in the list, in reverse. The return value of the callback function is the accumulated result, * and is provided as an argument in the next call to the callback function. * @param callback A function that accepts up to four arguments. The reduce method calls the callback function one time for each element in the list. * @param initialValue If initialValue is specified, it is used as the initial value to start the accumulation. The first call to the `callback` function provides this value as an argument instead of a list value. */ reduceRight(callback: (previousValue: T, value: T, node: LinkedListNode<T>, list: LinkedList<T>) => T, initialValue: T): T; /** * Calls the specified `callback` function for all the nodes in the list, in reverse. The return value of the callback function is the accumulated result, * and is provided as an argument in the next call to the callback function. * @param callback A function that accepts up to four arguments. The reduce method calls the callback function one time for each element in the list. * @param initialValue If initialValue is specified, it is used as the initial value to start the accumulation. The first call to the `callback` function provides this value as an argument instead of a list value. */ reduceRight<U>(callback: (previousValue: U, value: T, node: LinkedListNode<T>, list: LinkedList<T>) => U, initialValue: U): U; reduceRight(callback: (previousValue: T, value: T, node: LinkedListNode<T>, list: LinkedList<T>) => T, initialValue?: T) { if (!isFunction(callback)) throw new TypeError("Function expected: callback"); let hasInitialValue = arguments.length > 1; let result = initialValue; let node: LinkedListNode<T>; let prev = this.last; while (prev !== undefined) { node = prev; const value = node.value; if (!hasInitialValue) { result = value; hasInitialValue = true; } else { result = callback(result!, value, node, this); } prev = node.previous; } return result; } some(callback?: (value: T, node: LinkedListNode<T>, list: LinkedList<T>) => boolean, thisArg?: any) { if (!isMissing(callback) && !isFunction(callback)) throw new TypeError("Function expected: callback"); let node: LinkedListNode<T>; let next = this.first; while (next !== undefined) { node = next; next = node.next; if (!callback || callback.call(thisArg, node.value, node, this)) return true; } return false; } every(callback: (value: T, node: LinkedListNode<T>, list: LinkedList<T>) => boolean, thisArg?: any) { if (!isFunction(callback)) throw new TypeError("Function expected: callback"); let hasMatch = false; let node: LinkedListNode<T>; let next = this.first; while (next !== undefined) { node = next; next = node.next; if (!callback.call(thisArg, node.value, node, this)) return false; hasMatch = true; } return hasMatch; } private _deleteNode(node: LinkedListNode<T>): boolean { if (node[kNext] === node) { this._head = undefined; } else { node[kNext]![kPrevious] = node[kPrevious]; node[kPrevious]![kNext] = node[kNext]; if (this._head === node) { this._head = node[kNext]; } } node[kList] = undefined; node[kNext] = undefined; node[kPrevious] = undefined; this._size--; return true; } private _insertNode(adjacentNode: LinkedListNode<T> | undefined, newNode: LinkedListNode<T>, position: Position) { newNode[kList] = this; if (this._head === undefined) { newNode[kNext] = newNode; newNode[kPrevious] = newNode; this._head = newNode; } else { switch (position) { case Position.before: if (adjacentNode === undefined) { adjacentNode = this._head; this._head = newNode; } else if (adjacentNode === this._head) { this._head = newNode; } newNode[kNext] = adjacentNode; newNode[kPrevious] = adjacentNode[kPrevious]; adjacentNode[kPrevious]![kNext] = newNode; adjacentNode[kPrevious] = newNode; break; case Position.after: if (adjacentNode === undefined) { adjacentNode = this._head[kPrevious]!; } newNode[kPrevious] = adjacentNode; newNode[kNext] = adjacentNode[kNext]; adjacentNode[kNext]![kPrevious] = newNode; adjacentNode[kNext] = newNode; break; } } this._size++; return newNode; } [Symbol.toStringTag]!: string; // ReadonlyCollection<T> get [ReadonlyCollection.size]() { return this.size; } [ReadonlyCollection.has](value: T) { return this.has(value); } // Collection<T> [Collection.add](value: T) { this.push(value); } [Collection.delete](value: T) { return !!this.delete(value); } [Collection.clear]() { this.clear(); } } Object.defineProperty(LinkedList.prototype, Symbol.toStringTag, { enumerable: false, configurable: true, writable: true, value: "LinkedList" });
the_stack
* @packageDocumentation * @module Voice * @preferred * @publicapi */ import { EventEmitter } from 'events'; import AudioHelper from './audiohelper'; import Connection from './connection'; import { TwilioError } from './errors'; import { PreflightTest } from './preflight/preflight'; /** * @private */ export declare type IPStream = any; /** * @private */ export declare type IPublisher = any; /** * @private */ export declare type ISound = any; /** * Options that may be passed to the {@link Device} constructor for internal testing. * @private */ export interface IExtendedDeviceOptions extends Device.Options { /** * Custom {@link AudioHelper} constructor */ AudioHelper?: any; /** * Hostname of the signaling gateway to connect to. */ chunderw?: string; /** * Custom {@link Connection} constructor */ connectionFactory?: Connection; /** * Hostname of the event gateway to connect to. */ eventgw?: string; /** * File input stream to use instead of reading from mic */ fileInputStream?: MediaStream; /** * A list of specific ICE servers to use. Overridden by {@link Device.Options.rtcConfiguration}. * @deprecated */ iceServers?: Object[]; /** * Ignore browser support, disabling the exception that is thrown when neither WebRTC nor * ORTC are supported. */ ignoreBrowserSupport?: boolean; /** * Whether to disable audio flag in MediaPresence (rrowland: Do we need this?) */ noRegister?: boolean; /** * Whether this is a preflight call or not */ preflight?: boolean; /** * Custom PStream constructor */ pStreamFactory?: IPStream; /** * Custom Publisher constructor */ Publisher?: IPublisher; /** * Whether Insights events should be published */ publishEvents?: boolean; /** * RTC Constraints to pass to getUserMedia when making or accepting a Call. * The format of this object depends on browser. */ rtcConstraints?: Object; /** * Custom Sound constructor */ soundFactory?: ISound; } /** * A sound definition used to initialize a Sound file. * @private */ export interface ISoundDefinition { /** * Name of the sound file. */ filename: string; /** * The amount of time this sound file should play before being stopped automatically. */ maxDuration?: number; /** * Whether or not this sound should loop after playthrough finishes. */ shouldLoop?: boolean; } /** * Twilio Device. Allows registration for incoming calls, and placing outgoing calls. * @publicapi */ declare class Device extends EventEmitter { /** * The AudioContext to be used by {@link Device} instances. * @private */ static get audioContext(): AudioContext | undefined; /** * Which sound file extension is supported. * @private */ static get extension(): 'mp3' | 'ogg'; /** * Whether or not this SDK is supported by the current browser. */ static get isSupported(): boolean; /** * Package name of the SDK. */ static get packageName(): string; /** * Run some tests to identify issues, if any, prohibiting successful calling. * @param token - A Twilio JWT token string * @param options */ static runPreflight(token: string, options?: PreflightTest.Options): PreflightTest; /** * String representation of {@link Device} class. * @private */ static toString(): string; /** * Current SDK version. */ static get version(): string; /** * An AudioContext to share between {@link Device}s. */ private static _audioContext?; /** * A DialtonePlayer to play mock DTMF sounds through. */ private static _dialtonePlayer?; /** * Whether or not the browser uses unified-plan SDP by default. */ private static _isUnifiedPlanDefault; /** * Initializes the AudioContext instance shared across the Client SDK, * or returns the existing instance if one has already been initialized. */ private static _getOrCreateAudioContext; /** * The AudioHelper instance associated with this {@link Device}. */ audio: AudioHelper | null; /** * An array of {@link Connection}s. Though only one can be active, multiple may exist when there * are multiple incoming, unanswered {@link Connection}s. */ connections: Connection[]; /** * Whether or not {@link Device.setup} has been called. */ isInitialized: boolean; /** * Methods to enable/disable each sound. Empty if the {@link Device} has not * yet been set up. */ readonly sounds: Partial<Record<Device.SoundName, (value?: boolean) => void>>; /** * The JWT string currently being used to authenticate this {@link Device}. */ token: string | null; /** * The currently active {@link Connection}, if there is one. */ private _activeConnection; /** * The list of chunder URIs that will be passed to PStream */ private _chunderURIs; /** * An audio input MediaStream to pass to new {@link Connection} instances. */ private _connectionInputStream; /** * An array of {@link Device} IDs to be used to play sounds through, to be passed to * new {@link Connection} instances. */ private _connectionSinkIds; /** * The name of the edge the {@link Device} is connected to. */ private _edge; /** * Whether each sound is enabled. */ private _enabledSounds; /** * Whether SDK is run as a browser extension */ private _isBrowserExtension; /** * An instance of Logger to use. */ private _log; /** * Network related information * See https://developer.mozilla.org/en-US/docs/Web/API/Network_Information_API */ private _networkInformation; /** * An Insights Event Publisher. */ private _publisher; /** * The region the {@link Device} is connected to. */ private _region; /** * The current status of the {@link Device}. */ private _status; /** * Value of 'audio' determines whether we should be registered for incoming calls. */ private mediaPresence; /** * The options passed to {@link Device} constructor or Device.setup. */ private options; /** * A timeout ID for a setTimeout schedule to re-register the {@link Device}. */ private regTimer; /** * A Map of Sounds to play. */ private soundcache; /** * The Signaling stream. */ private stream; /** * Construct a {@link Device} instance, without setting up up. {@link Device.setup} must * be called later to initialize the {@link Device}. * @constructor * @param [token] - A Twilio JWT token string granting this {@link Device} access. * @param [options] */ constructor(); /** * Construct a {@link Device} instance, and set it up as part of the construction. * @constructor * @param [token] - A Twilio JWT token string granting this {@link Device} access. * @param [options] */ constructor(token: string, options?: Device.Options); /** * Return the active {@link Connection}. Null or undefined for backward compatibility. */ activeConnection(): Connection | null | undefined; /** * @deprecated Set a handler for the cancel event. * @param handler */ cancel(handler: (connection: Connection) => any): this; /** * Make an outgoing Call. * @param [params] - A flat object containing key:value pairs to be sent to the TwiML app. * @param [audioConstraints] * @param [rtcConfiguration] - An RTCConfiguration to override the one set in `Device.setup`. */ connect(params?: Record<string, string>, audioConstraints?: MediaTrackConstraints | boolean, rtcConfiguration?: RTCConfiguration): Connection; /** * Add a listener for the connect event. * @param handler - A handler to set on the connect event. */ connect(handler: (connection: Connection) => any): null; /** * Destroy the {@link Device}, freeing references to be garbage collected. */ destroy: () => void; /** * Set a handler for the disconnect event. * @deprecated Use {@link Device.on}. * @param handler */ disconnect(handler: (connection: Connection) => any): this; /** * Disconnect all {@link Connection}s. */ disconnectAll(): void; /** * Returns the {@link Edge} value the {@link Device} is currently connected * to. The value will be `null` when the {@link Device} is offline. */ get edge(): string | null; /** * Set a handler for the error event. * @deprecated Use {@link Device.on}. * @param handler */ error(handler: (error: Connection) => any): this; /** * Set a handler for the incoming event. * @deprecated Use {@link Device.on}. * @param handler */ incoming(handler: (connection: Connection) => any): this; /** * Set a handler for the offline event. * @deprecated Use {@link Device.on}. * @param handler */ offline(handler: (device: Device) => any): this; /** * Set a handler for the ready event. * @deprecated Use {@link Device.on}. * @param handler */ ready(handler: (device: Device) => any): this; /** * Get the {@link Region} string the {@link Device} is currently connected to, or 'offline' * if not connected. */ region(): string; /** * Register to receive incoming calls. Does not need to be called unless {@link Device.unregisterPresence} * has been called directly. */ registerPresence(): this; /** * Remove an event listener * @param event - The event name to stop listening for * @param listener - The callback to remove */ removeListener(event: Device.EventName, listener: (...args: any[]) => void): this; /** * Initialize the {@link Device}. * @param token - A Twilio JWT token string granting this {@link Device} access. * @param [options] */ setup(token: string, options?: Device.Options): this; /** * Get the status of this {@link Device} instance */ status(): Device.Status; /** * String representation of {@link Device} instance. * @private */ toString(): string; /** * Unregister to receiving incoming calls. */ unregisterPresence(): this; /** * Update the token and re-register. * @param token - The new token JWT string to register with. */ updateToken(token: string): void; /** * Add a handler for an EventEmitter and emit a deprecation warning on first call. * @param eventName - Name of the event * @param handler - A handler to call when the event is emitted */ private _addHandler; /** * Calls the emit API such that it is asynchronous. * Only use this internal API if you don't want to break the execution after raising an event. * This prevents the issue where events are not dispatched to all handlers when one of the handlers throws an error. * For example, our connection:accept is not triggered if the handler for device:connect handler throws an error. * As a side effect, we are not able to perform our internal routines such as stopping incoming sounds. * See connection:accept inside _makeConnection where we call emit('connect'). This can throw an error. * See connection:accept inside _onSignalingInvite. This handler won't get called if the error above is thrown. * @private */ private _asyncEmit; /** * Called on window's beforeunload event if closeProtection is enabled, * preventing users from accidentally navigating away from an active call. * @param event */ private _confirmClose; /** * Create the default Insights payload * @param [connection] */ private _createDefaultPayload; /** * Disconnect all {@link Connection}s. */ private _disconnectAll; /** * Find a {@link Connection} by its CallSid. * @param callSid */ private _findConnection; /** * Create a new {@link Connection}. * @param twimlParams - A flat object containing key:value pairs to be sent to the TwiML app. * @param [options] - Options to be used to instantiate the {@link Connection}. */ private _makeConnection; /** * Stop the incoming sound if no {@link Connection}s remain. */ private _maybeStopIncomingSound; /** * Called when a 'close' event is received from the signaling stream. */ private _onSignalingClose; /** * Called when a 'connected' event is received from the signaling stream. */ private _onSignalingConnected; /** * Called when an 'error' event is received from the signaling stream. */ private _onSignalingError; /** * Called when an 'invite' event is received from the signaling stream. */ private _onSignalingInvite; /** * Called when an 'offline' event is received from the signaling stream. */ private _onSignalingOffline; /** * Called when a 'ready' event is received from the signaling stream. */ private _onSignalingReady; /** * Publish a NetworkInformation#change event to Insights if there's an active {@link Connection}. */ private _publishNetworkChange; /** * Remove a {@link Connection} from device.connections by reference * @param connection */ private _removeConnection; /** * Register with the signaling server. */ private _sendPresence; /** * Set up the connection to the signaling server. * @param token */ private _setupStream; /** * Start playing the incoming ringtone, and subsequently emit the incoming event. * @param connection * @param play - The function to be used to play the sound. Must return a Promise. */ private _showIncomingConnection; /** * Set a timeout to send another register message to the signaling server. */ private _startRegistrationTimer; /** * Stop sending registration messages to the signaling server. */ private _stopRegistrationTimer; /** * Throw an Error if Device.setup has not been called for this instance. * @param methodName - The name of the method being called before setup() */ private _throwUnlessSetup; /** * Update the input stream being used for calls so that any current call and all future calls * will use the new input stream. * @param inputStream */ private _updateInputStream; /** * Update the device IDs of output devices being used to play the incoming ringtone through. * @param sinkIds - An array of device IDs */ private _updateRingtoneSinkIds; /** * Update the device IDs of output devices being used to play sounds through. * @param type - Whether to update ringtone or speaker sounds * @param sinkIds - An array of device IDs */ private _updateSinkIds; /** * Update the device IDs of output devices being used to play the non-ringtone sounds * and Call audio through. * @param sinkIds - An array of device IDs */ private _updateSpeakerSinkIds; /** * Register the {@link Device} * @param token */ private register; } declare namespace Device { /** * All valid {@link Device} event names. */ enum EventName { Cancel = "cancel", Connect = "connect", Disconnect = "disconnect", Error = "error", Incoming = "incoming", Offline = "offline", Ready = "ready" } /** * All possible {@link Device} statuses. */ enum Status { Busy = "busy", Offline = "offline", Ready = "ready" } /** * Names of all sounds handled by the {@link Device}. */ enum SoundName { Incoming = "incoming", Outgoing = "outgoing", Disconnect = "disconnect", Dtmf0 = "dtmf0", Dtmf1 = "dtmf1", Dtmf2 = "dtmf2", Dtmf3 = "dtmf3", Dtmf4 = "dtmf4", Dtmf5 = "dtmf5", Dtmf6 = "dtmf6", Dtmf7 = "dtmf7", Dtmf8 = "dtmf8", Dtmf9 = "dtmf9", DtmfS = "dtmfs", DtmfH = "dtmfh" } /** * Names of all togglable sounds. */ type ToggleableSound = Device.SoundName.Incoming | Device.SoundName.Outgoing | Device.SoundName.Disconnect; /** * The error format used by errors emitted from {@link Device}. */ interface Error { /** * Error code */ code: number; /** * Reference to the {@link Connection} * This is usually available if the error is coming from {@link Connection} */ connection?: Connection; /** * The info object from rtc/peerconnection or eventpublisher. May contain code and message (duplicated here). */ info?: { code?: number; message?: string; }; /** * Error message */ message: string; /** * Twilio Voice related error */ twilioError?: TwilioError; } /** * Options that may be passed to the {@link Device} constructor, or Device.setup via public API */ interface Options { [key: string]: any; /** * Whether the Device should raise the {@link incomingEvent} event when a new call invite is * received while already on an active call. Default behavior is false. */ allowIncomingWhileBusy?: boolean; /** * A name for the application that is instantiating the {@link Device}. This is used to improve logging * in Insights by associating Insights data with a specific application, particularly in the case where * one account may be connected to by multiple applications. */ appName?: string; /** * A version for the application that is instantiating the {@link Device}. This is used to improve logging * in Insights by associating Insights data with a specific version of the given application. This can help * track down when application-level bugs were introduced. */ appVersion?: string; /** * Audio Constraints to pass to getUserMedia when making or accepting a Call. * This is placed directly under `audio` of the MediaStreamConstraints object. */ audioConstraints?: MediaTrackConstraints | boolean; /** * Whether to enable close protection, to prevent users from accidentally * navigating away from the page during a call. If string, the value will * be used as a custom message. */ closeProtection?: boolean | string; /** * An ordered array of codec names, from most to least preferred. */ codecPreferences?: Connection.Codec[]; /** * Whether to enable debug logging. */ debug?: boolean; /** * Whether AudioContext sounds should be disabled. Useful for trouble shooting sound issues * that may be caused by AudioContext-specific sounds. If set to true, will fall back to * HTMLAudioElement sounds. */ disableAudioContextSounds?: boolean; /** * Whether to use googDscp in RTC constraints. */ dscp?: boolean; /** * The edge value corresponds to the geographic location that the client * will use to connect to Twilio infrastructure. The default value is * "roaming" which automatically selects an edge based on the latency of the * client relative to available edges. You may not specify both `edge` and * `region` in the Device options. Specifying both `edge` and `region` will * result in an `InvalidArgumentException`. */ edge?: string[] | string; /** * Whether to automatically restart ICE when media connection fails */ enableIceRestart?: boolean; /** * Whether the ringing state should be enabled on {@link Connection} objects. This is required * to enable answerOnBridge functionality. */ enableRingingState?: boolean; /** * Whether or not to override the local DTMF sounds with fake dialtones. This won't affect * the DTMF tone sent over the connection, but will prevent double-send issues caused by * using real DTMF tones for user interface. In 2.0, this will be enabled by default. */ fakeLocalDTMF?: boolean; /** * Experimental feature. * Whether to use ICE Aggressive nomination. */ forceAggressiveIceNomination?: boolean; /** * The maximum average audio bitrate to use, in bits per second (bps) based on * [RFC-7587 7.1](https://tools.ietf.org/html/rfc7587#section-7.1). By default, the setting * is not used. If you specify 0, then the setting is not used. Any positive integer is allowed, * but values outside the range 6000 to 510000 are ignored and treated as 0. The recommended * bitrate for speech is between 8000 and 40000 bps as noted in * [RFC-7587 3.1.1](https://tools.ietf.org/html/rfc7587#section-3.1.1). */ maxAverageBitrate?: number; /** * The region code of the region to connect to. * * @deprecated * * CLIENT-7519 This parameter is deprecated in favor of the `edge` * parameter. You may not specify both `edge` and `region` in the Device * options. * * This parameter will be removed in the next major version release. * * The following table lists the new edge names to region name mappings. * Instead of passing the `region` value in `options.region`, please pass the * following `edge` value in `options.edge`. * * | Region Value | Edge Value | * |:-------------|:-------------| * | au1 | sydney | * | br1 | sao-paulo | * | ie1 | dublin | * | de1 | frankfurt | * | jp1 | tokyo | * | sg1 | singapore | * | us1 | ashburn | * | us2 | umatilla | * | gll | roaming | * | us1-ix | ashburn-ix | * | us2-ix | san-jose-ix | * | ie1-ix | london-ix | * | de1-ix | frankfurt-ix | * | sg1-ix | singapore-ix | */ region?: string; /** * An RTCConfiguration to pass to the RTCPeerConnection constructor. */ rtcConfiguration?: RTCConfiguration; /** * A mapping of custom sound URLs by sound name. */ sounds?: Partial<Record<Device.SoundName, string>>; /** * Whether to enable warn logging. */ warnings?: boolean; } } export default Device;
the_stack
import { MockERC20Instance, UniswapV2FactoryInstance, UniswapV2Router02Instance, UniswapV2PairInstance, StrategyAllETHOnlyInstance, StrategyLiquidateInstance, BankInstance, SimpleBankConfigInstance, MStableGoblinInstance, MStableStakingRewardsInstance, WETHInstance, } from '../typechain'; const UniswapV2Factory = artifacts.require('UniswapV2Factory'); const UniswapV2Router02 = artifacts.require('UniswapV2Router02'); const UniswapV2Pair = artifacts.require('UniswapV2Pair'); const StrategyAllETHOnly = artifacts.require('StrategyAllETHOnly'); const StrategyAddTwoSidesOptimal = artifacts.require('StrategyAddTwoSidesOptimal'); const StrategyLiquidate = artifacts.require('StrategyLiquidate'); const Bank = artifacts.require('Bank'); const SimpleBankConfig = artifacts.require('SimpleBankConfig'); const MStableStakingRewards = artifacts.require('MStableStakingRewards'); const MStableGoblin = artifacts.require('MStableGoblin'); const WETH = artifacts.require('WETH'); const MockERC20 = artifacts.require('MockERC20'); const { expectRevert, time, BN, ether } = require('@openzeppelin/test-helpers'); // Assert that actual is less than 0.01% difference from expected function assertAlmostEqual(expected: string | BN, actual: string | BN) { const expectedBN = BN.isBN(expected) ? expected : new BN(expected); const actualBN = BN.isBN(actual) ? actual : new BN(actual); const diffBN = expectedBN.gt(actualBN) ? expectedBN.sub(actualBN) : actualBN.sub(expectedBN); return assert.ok( diffBN.lt(expectedBN.div(new BN('1000'))), `Not almost equal. Expected ${expectedBN.toString()}. Actual ${actualBN.toString()}` ); } const FOREVER = '2000000000'; contract('MStableBank', ([deployer, alice, bob, eve]) => { const SUSHI_REWARD_PER_BLOCK = ether('0.076'); const REINVEST_BOUNTY_BPS = new BN('100'); // 1% reinvest bounty const RESERVE_POOL_BPS = new BN('1000'); // 10% reserve pool const KILL_PRIZE_BPS = new BN('1000'); // 10% Kill prize const INTEREST_RATE = new BN('3472222222222'); // 30% per year const MIN_DEBT_SIZE = ether('1'); // 1 ETH min debt size const WORK_FACTOR = new BN('7000'); const KILL_FACTOR = new BN('8000'); let factory: UniswapV2FactoryInstance; let weth: WETHInstance; let router: UniswapV2Router02Instance; let mta: MockERC20Instance; let lp: UniswapV2PairInstance; let addStrat: StrategyAllETHOnlyInstance; let liqStrat: StrategyLiquidateInstance; let config: SimpleBankConfigInstance; let bank: BankInstance; let staking: MStableStakingRewardsInstance; let goblin: MStableGoblinInstance; beforeEach(async () => { factory = await UniswapV2Factory.new(deployer); weth = await WETH.new(); router = await UniswapV2Router02.new(factory.address, weth.address); mta = await MockERC20.new('MTA', 'MTA'); await mta.mint(deployer, ether('100')); await mta.mint(alice, ether('100')); await mta.mint(bob, ether('100')); await factory.createPair(weth.address, mta.address); lp = await UniswapV2Pair.at(await factory.getPair(mta.address, weth.address)); addStrat = await StrategyAllETHOnly.new(router.address); liqStrat = await StrategyLiquidate.new(router.address); config = await SimpleBankConfig.new(MIN_DEBT_SIZE, INTEREST_RATE, RESERVE_POOL_BPS, KILL_PRIZE_BPS); bank = await Bank.new(config.address); staking = await MStableStakingRewards.new(deployer, lp.address, mta.address, deployer); goblin = await MStableGoblin.new( bank.address, staking.address, router.address, mta.address, addStrat.address, liqStrat.address, REINVEST_BOUNTY_BPS ); await config.setGoblin(goblin.address, true, true, WORK_FACTOR, KILL_FACTOR); const twoSideStrat = await StrategyAddTwoSidesOptimal.new(router.address, goblin.address); await goblin.setStrategyOk([twoSideStrat.address], true); await goblin.setCriticalStrategies(twoSideStrat.address, liqStrat.address); // Deployer adds 1e17 MTA + 1e18 WEI await mta.approve(router.address, ether('0.1')); await router.addLiquidityETH(mta.address, ether('0.1'), '0', '0', deployer, FOREVER, { value: ether('1'), }); // Deployer transfer 1e18 MTA to StakingRewards contract and notify reward await mta.transfer(staking.address, ether('1')); await staking.notifyRewardAmount(ether('1')); }); it('should give rewards out when you stake LP tokens', async () => { // Deployer sends some LP tokens to Alice and Bob await lp.transfer(alice, ether('0.05')); await lp.transfer(bob, ether('0.05')); // Alice stakes 0.01 LP tokens and waits for 1 day await lp.approve(staking.address, ether('100'), { from: alice }); await staking.stake(web3.utils.toWei('0.01', 'ether'), { from: alice }); await time.increase(time.duration.days(1)); }); it('should allow positions without debt', async () => { // Deployer deposits 3 ETH to the bank await bank.deposit({ value: ether('3') }); // Alice can take 0 debt ok await bank.work( 0, goblin.address, ether('0'), '0', web3.eth.abi.encodeParameters( ['address', 'bytes'], [addStrat.address, web3.eth.abi.encodeParameters(['address', 'uint256'], [mta.address, '0'])] ), { value: ether('0.3'), from: alice } ); }); it('should not allow positions with debt less than MIN_DEBT_SIZE', async () => { // Deployer deposits 3 ETH to the bank await bank.deposit({ value: ether('3') }); // Alice cannot take 0.3 debt because it is too small await expectRevert( bank.work( 0, goblin.address, ether('0.3'), '0', web3.eth.abi.encodeParameters( ['address', 'bytes'], [addStrat.address, web3.eth.abi.encodeParameters(['address', 'uint256'], [mta.address, '0'])] ), { value: ether('0.3'), from: alice } ), 'too small debt size' ); }); it('should not allow positions with bad work factor', async () => { // Deployer deposits 3 ETH to the bank await bank.deposit({ value: ether('3') }); // Alice cannot take 1 ETH loan but only put in 0.3 ETH await expectRevert( bank.work( 0, goblin.address, ether('1'), '0', web3.eth.abi.encodeParameters( ['address', 'bytes'], [addStrat.address, web3.eth.abi.encodeParameters(['address', 'uint256'], [mta.address, '0'])] ), { value: ether('0.3'), from: alice } ), 'bad work factor' ); }); it('should not allow positions if Bank has less ETH than requested loan', async () => { // Alice cannot take 1 ETH loan because the contract does not have it await expectRevert( bank.work( 0, goblin.address, ether('1'), '0', web3.eth.abi.encodeParameters( ['address', 'bytes'], [addStrat.address, web3.eth.abi.encodeParameters(['address', 'uint256'], [mta.address, '0'])] ), { value: ether('1'), from: alice } ), 'insufficient ETH in the bank' ); }); it('should work', async () => { // Deployer deposits 3 ETH to the bank const deposit = ether('3'); await bank.deposit({ value: deposit }); // Now Alice can take 1 ETH loan + 1 ETH of her to create a new position const loan = ether('1'); await bank.work( 0, goblin.address, loan, '0', web3.eth.abi.encodeParameters( ['address', 'bytes'], [addStrat.address, web3.eth.abi.encodeParameters(['address', 'uint256'], [mta.address, '0'])] ), { value: ether('1'), from: alice } ); // Her position should have ~2 ETH health (minus some small trading fee) assert.equal('1997459271062521105', await goblin.health('1')); await time.increase(time.duration.days(1)); await goblin.reinvest({ from: eve }); assertAlmostEqual('1428571428571295', await mta.balanceOf(eve)); await bank.deposit(); // Random action to trigger interest computation const healthDebt = await bank.positionInfo('1'); expect(healthDebt[0]).to.be.bignumber.above(ether('2')); const interest = ether('0.3'); //30% interest rate assertAlmostEqual(healthDebt[1], interest.add(loan)); assertAlmostEqual(await web3.eth.getBalance(bank.address), deposit.sub(loan)); assertAlmostEqual(await bank.glbDebtVal(), interest.add(loan)); const reservePool = interest.mul(RESERVE_POOL_BPS).div(new BN('10000')); assertAlmostEqual(reservePool, await bank.reservePool()); assertAlmostEqual(deposit.add(interest).sub(reservePool), await bank.totalETH()); }); it('should not able to liquidate healthy position', async () => { // Deployer deposits 3 ETH to the bank const deposit = ether('3'); await bank.deposit({ value: deposit }); // Now Alice can take 1 ETH loan + 1 ETH of her to create a new position const loan = ether('1'); await bank.work( 0, goblin.address, loan, '0', web3.eth.abi.encodeParameters( ['address', 'bytes'], [addStrat.address, web3.eth.abi.encodeParameters(['address', 'uint256'], [mta.address, '0'])] ), { value: ether('1'), from: alice } ); // Her position should have ~2 ETH health (minus some small trading fee) await time.increase(time.duration.days(1)); await goblin.reinvest({ from: eve }); await bank.deposit(); // Random action to trigger interest computation // You can't liquidate her position yet await expectRevert(bank.kill('1'), "can't liquidate", { from: eve }); await time.increase(time.duration.days(1)); await expectRevert(bank.kill('1'), "can't liquidate", { from: eve }); }); it('should has correct interest rate growth', async () => { // Deployer deposits 3 ETH to the bank const deposit = ether('3'); await bank.deposit({ value: deposit }); // Now Alice can take 1 ETH loan + 1 ETH of her to create a new position const loan = ether('1'); await bank.work( 0, goblin.address, loan, '0', web3.eth.abi.encodeParameters( ['address', 'bytes'], [addStrat.address, web3.eth.abi.encodeParameters(['address', 'uint256'], [mta.address, '0'])] ), { value: ether('1'), from: alice } ); await time.increase(time.duration.days(1)); await goblin.reinvest({ from: eve }); await bank.deposit(); // Random action to trigger interest computation await time.increase(time.duration.days(1)); await time.increase(time.duration.days(1)); await bank.deposit(); // Random action to trigger interest computation const interest = ether('0.3'); //30% interest rate const reservePool = interest.mul(RESERVE_POOL_BPS).div(new BN('10000')); assertAlmostEqual( deposit .add(interest.sub(reservePool)) .add(interest.sub(reservePool).mul(new BN(13)).div(new BN(10))) .add(interest.sub(reservePool).mul(new BN(13)).div(new BN(10))), await bank.totalETH() ); }); it('should be able to liquidate bad position', async () => { // Deployer deposits 3 ETH to the bank const deposit = ether('3'); await bank.deposit({ value: deposit }); // Now Alice can take 1 ETH loan + 1 ETH of her to create a new position const loan = ether('1'); await bank.work( 0, goblin.address, loan, '0', web3.eth.abi.encodeParameters( ['address', 'bytes'], [addStrat.address, web3.eth.abi.encodeParameters(['address', 'uint256'], [mta.address, '0'])] ), { value: ether('1'), from: alice } ); await time.increase(time.duration.days(1)); await goblin.reinvest({ from: eve }); await bank.deposit(); // Random action to trigger interest computation await time.increase(time.duration.days(1)); await time.increase(time.duration.days(1)); await bank.deposit(); // Random action to trigger interest computation const interest = ether('0.3'); //30% interest rate const reservePool = interest.mul(RESERVE_POOL_BPS).div(new BN('10000')); assertAlmostEqual( deposit .add(interest.sub(reservePool)) .add(interest.sub(reservePool).mul(new BN(13)).div(new BN(10))) .add(interest.sub(reservePool).mul(new BN(13)).div(new BN(10))), await bank.totalETH() ); const eveBefore = new BN(await web3.eth.getBalance(eve)); // Now you can liquidate because of the insane interest rate await bank.kill('1', { from: eve }); expect(new BN(await web3.eth.getBalance(eve))).to.be.bignumber.gt(eveBefore); //Should get rewards assertAlmostEqual( deposit .add(interest) .add(interest.mul(new BN(13)).div(new BN(10))) .add(interest.mul(new BN(13)).div(new BN(10))), await web3.eth.getBalance(bank.address) ); assert.equal('0', await bank.glbDebtVal()); assertAlmostEqual( reservePool.add(reservePool.mul(new BN(13)).div(new BN(10))).add(reservePool.mul(new BN(13)).div(new BN(10))), await bank.reservePool() ); assertAlmostEqual( deposit .add(interest.sub(reservePool)) .add(interest.sub(reservePool).mul(new BN(13)).div(new BN(10))) .add(interest.sub(reservePool).mul(new BN(13)).div(new BN(10))), await bank.totalETH() ); // Alice creates a new position again console.log( ( await bank.work( 0, goblin.address, ether('1'), '0', web3.eth.abi.encodeParameters( ['address', 'bytes'], [addStrat.address, web3.eth.abi.encodeParameters(['address', 'uint256'], [mta.address, '0'])] ), { value: ether('1'), from: alice } ) ).receipt.gasUsed ); // She can close position await bank.work( 2, goblin.address, '0', '115792089237316195423570985008687907853269984665640564039457584007913129639935', web3.eth.abi.encodeParameters( ['address', 'bytes'], [liqStrat.address, web3.eth.abi.encodeParameters(['address', 'uint256'], [mta.address, '0'])] ), { from: alice } ); }); it('Should deposit and withdraw eth from Bank (bad debt case)', async () => { // Deployer deposits 10 ETH to the bank const deposit = ether('10'); await bank.deposit({ value: deposit }); expect(await bank.balanceOf(deployer)).to.be.bignumber.equal(deposit); // Bob borrows 2 ETH loan const loan = ether('2'); await bank.work( 0, goblin.address, loan, '0', // max return = 0, don't return ETH to the debt web3.eth.abi.encodeParameters( ['address', 'bytes'], [addStrat.address, web3.eth.abi.encodeParameters(['address', 'uint256'], [mta.address, '0'])] ), { value: ether('1'), from: bob } ); expect(new BN(await web3.eth.getBalance(bank.address))).to.be.bignumber.equal(deposit.sub(loan)); expect(await bank.glbDebtVal()).to.be.bignumber.equal(loan); expect(await bank.totalETH()).to.be.bignumber.equal(deposit); // Alice deposits 2 ETH const aliceDeposit = ether('2'); await bank.deposit({ value: aliceDeposit, from: alice, }); // check Alice gETH balance = 2/10 * 10 = 2 gETH assertAlmostEqual(aliceDeposit, await bank.balanceOf(alice)); assertAlmostEqual(deposit.add(aliceDeposit), await bank.totalSupply()); // Simulate ETH price is very high by swap fToken to ETH (reduce ETH supply) await mta.mint(deployer, ether('100')); await mta.approve(router.address, ether('100')); await router.swapExactTokensForTokens(ether('100'), '0', [mta.address, weth.address], deployer, FOREVER); assertAlmostEqual(deposit.sub(loan).add(aliceDeposit), await web3.eth.getBalance(bank.address)); // Alice liquidates Bob position#1 let aliceBefore = new BN(await web3.eth.getBalance(alice)); await bank.kill(1, { from: alice, gasPrice: 0 }); let aliceAfter = new BN(await web3.eth.getBalance(alice)); // Bank balance is increase by liquidation assertAlmostEqual('10002702699312215556', await web3.eth.getBalance(bank.address)); // Alice is liquidator, Alice should receive 10% Kill prize // ETH back from liquidation 3002999235795062, 10% of 3002999235795062 is 300299923579506 assertAlmostEqual('300299923579506', aliceAfter.sub(aliceBefore)); // Alice withdraws 2 gETH aliceBefore = new BN(await web3.eth.getBalance(alice)); await bank.withdraw(await bank.balanceOf(alice), { from: alice, gasPrice: 0, }); aliceAfter = new BN(await web3.eth.getBalance(alice)); // alice gots 2/12 * 10.002702699312215556 = 1.667117116552036 assertAlmostEqual('1667117116552036400', aliceAfter.sub(aliceBefore)); }); it('should liquidate user position correctly', async () => { // Bob deposits 20 ETH await bank.deposit({ value: ether('20'), from: bob, }); // Position#1: Alice borrows 10 ETH loan await bank.work( 0, goblin.address, ether('10'), '0', // max return = 0, don't return ETH to the debt web3.eth.abi.encodeParameters( ['address', 'bytes'], [addStrat.address, web3.eth.abi.encodeParameters(['address', 'uint256'], [mta.address, '0'])] ), { value: ether('10'), from: alice } ); await mta.mint(deployer, ether('100')); await mta.approve(router.address, ether('100')); // Price swing 10% // Add more token to the pool equals to sqrt(10*((0.1)**2) / 9) - 0.1 = 0.005409255338945984, (0.1 is the balance of token in the pool) await router.swapExactTokensForTokens( web3.utils.toWei('0.005409255338945984', 'ether'), '0', [mta.address, weth.address], deployer, FOREVER ); await expectRevert(bank.kill('1'), "can't liquidate"); // Price swing 20% // Add more token to the pool equals to // sqrt(10*((0.10540925533894599)**2) / 8) - 0.10540925533894599 = 0.012441874858811944 // (0.10540925533894599 is the balance of token in the pool) await router.swapExactTokensForTokens( web3.utils.toWei('0.012441874858811944', 'ether'), '0', [mta.address, weth.address], deployer, FOREVER ); await expectRevert(bank.kill('1'), "can't liquidate"); // Price swing 23.43% // Existing token on the pool = 0.10540925533894599 + 0.012441874858811944 = 0.11785113019775793 // Add more token to the pool equals to // sqrt(10*((0.11785113019775793)**2) / 7.656999999999999) - 0.11785113019775793 = 0.016829279312591913 await router.swapExactTokensForTokens( web3.utils.toWei('0.016829279312591913', 'ether'), '0', [mta.address, weth.address], deployer, FOREVER ); await expectRevert(bank.kill('1'), "can't liquidate"); // Price swing 30% // Existing token on the pool = 0.11785113019775793 + 0.016829279312591913 = 0.13468040951034985 // Add more token to the pool equals to // sqrt(10*((0.13468040951034985)**2) / 7) - 0.13468040951034985 = 0.026293469053292218 await router.swapExactTokensForTokens( web3.utils.toWei('0.026293469053292218', 'ether'), '0', [mta.address, weth.address], deployer, FOREVER ); // Bob can kill alice's position await bank.kill('1', { from: bob }); }); it('should reinvest correctly', async () => { // Set Bank's debt interests to 0% per year await config.setParams( ether('1'), // 1 ETH min debt size, '0', // 0% per year '1000', // 10% reserve pool '1000' // 10% Kill prize ); // Set Reinvest bounty to 10% of the reward await goblin.setReinvestBountyBps('1000'); // Bob deposits 10 ETH await bank.deposit({ value: ether('10'), from: bob, gasPrice: 0, }); // Alice deposits 12 ETH await bank.deposit({ value: ether('10'), from: alice, gasPrice: 0, }); // Position#1: Bob borrows 10 ETH loan await bank.work( 0, goblin.address, ether('10'), '0', // max return = 0, don't return ETH to the debt web3.eth.abi.encodeParameters( ['address', 'bytes'], [addStrat.address, web3.eth.abi.encodeParameters(['address', 'uint256'], [mta.address, '0'])] ), { value: ether('10'), from: bob, gasPrice: 0 } ); // Position#2: Alice borrows 2 ETH loan await bank.work( 0, goblin.address, ether('2'), '0', // max return = 0, don't return ETH to the debt web3.eth.abi.encodeParameters( ['address', 'bytes'], [addStrat.address, web3.eth.abi.encodeParameters(['address', 'uint256'], [mta.address, '0'])] ), { value: ether('1'), from: alice, gasPrice: 0 } ); // ---------------- Reinvest#1 ------------------- // Wait for 1 day and someone calls reinvest await time.increase(time.duration.days(1)); let goblinLPBefore = await staking.balanceOf(goblin.address); await goblin.reinvest({ from: eve }); // Goblin receives 142857142857129598 mta as a reward // Eve got 10% of 142857142857129598 mta = 0.1 * 142857142857129598 = 14285714285712960 bounty assertAlmostEqual('14285714285712960', await mta.balanceOf(eve)); // Remaining Goblin reward = 142857142857129598 - 14285714285712960 = 128571428571416638 (~90% reward) // Convert 128571428571416638 mta to 282085379060981681 ETH // Convert ETH to 17975920502268804 LP token let goblinLPAfter = await staking.balanceOf(goblin.address); // LP tokens of goblin should be inceased from reinvestment expect(goblinLPAfter).to.be.bignumber.gt(goblinLPBefore); // Check Bob position info await goblin.health('1'); let [bobHealth, bobDebtToShare] = await bank.positionInfo('1'); expect(bobHealth).to.be.bignumber.gt(ether('20')); // Get Reward and increase health assertAlmostEqual(ether('10'), bobDebtToShare); // Check Alice position info await goblin.health('2'); let [aliceHealth, aliceDebtToShare] = await bank.positionInfo('2'); expect(aliceHealth).to.be.bignumber.gt(ether('3')); // Get Reward and increase health assertAlmostEqual(ether('2'), aliceDebtToShare); // ---------------- Reinvest#2 ------------------- // Wait for 1 day and someone calls reinvest await time.increase(time.duration.days(1)); goblinLPBefore = await staking.balanceOf(goblin.address); await goblin.reinvest({ from: eve }); // Goblin receives 142858796296283038 mta as a reward // Eve got 10% of 142858796296283038 mta = 0.1 * 142858796296283038 = 14285879629628304 bounty // Now alice have 14285714285712960 mta (1st) + 14285879629628304 mta (2nd) = 28571593915341264 mta assertAlmostEqual('28571593915341264', await mta.balanceOf(eve)); // Remaining Goblin reward = 142858796296283038 - 14285879629628304 = 128572916666654734 (~90% reward) // Convert 128572916666654734 mta to 157462478899282341 ETH // Convert ETH to 5001669421841640 LP token goblinLPAfter = await staking.balanceOf(goblin.address); // LP tokens of goblin should be inceased from reinvestment expect(goblinLPAfter).to.be.bignumber.gt(goblinLPBefore); // Check Bob position info [bobHealth, bobDebtToShare] = await bank.positionInfo('1'); expect(bobHealth).to.be.bignumber.gt(ether('20')); // Get Reward and increase health assertAlmostEqual(ether('10'), bobDebtToShare); // Check Alice position info [aliceHealth, aliceDebtToShare] = await bank.positionInfo('2'); expect(aliceHealth).to.be.bignumber.gt(ether('3')); // Get Reward and increase health assertAlmostEqual(ether('2'), aliceDebtToShare); // ---------------- Reinvest#3 ------------------- // Wait for 1 day and someone calls reinvest await time.increase(time.duration.days(1)); goblinLPBefore = await staking.balanceOf(goblin.address); await goblin.reinvest({ from: eve }); // Goblin receives 142858796296283038 mta as a reward // Eve got 10% of 142858796296283038 mta = 0.1 * 142858796296283038 = 14285879629628304 bounty // Now alice have 14285714285712960 mta (1st) + 14285879629628304 mta (2nd) + 14285879629628304 mta (3rd) = 42857473544969568 mta assertAlmostEqual('42857473544969568', await mta.balanceOf(eve)); // Remaining Goblin reward = 142858796296283038 - 14285879629628304 = 128572916666654734 (~90% reward) // Convert 128572916666654734 mta to 74159218067697746 ETH // Convert ETH to 2350053120029788 LP token goblinLPAfter = await staking.balanceOf(goblin.address); // LP tokens of goblin should be inceased from reinvestment expect(goblinLPAfter).to.be.bignumber.gt(goblinLPBefore); const bobBefore = new BN(await web3.eth.getBalance(bob)); // Bob close position#1 await bank.work( 1, goblin.address, '0', '1000000000000000000000', web3.eth.abi.encodeParameters( ['address', 'bytes'], [liqStrat.address, web3.eth.abi.encodeParameters(['address', 'uint256'], [mta.address, '0'])] ), { from: bob, gasPrice: 0 } ); const bobAfter = new BN(await web3.eth.getBalance(bob)); // Check Bob account expect(bobAfter).to.be.bignumber.gt(bobBefore); //Bob must be richer // Alice add ETH again await bank.work( 2, goblin.address, 0, '0', // max return = 0, don't return ETH to the debt web3.eth.abi.encodeParameters( ['address', 'bytes'], [addStrat.address, web3.eth.abi.encodeParameters(['address', 'uint256'], [mta.address, '0'])] ), { value: web3.utils.toWei('10', 'ether'), from: alice } ); const aliceBefore = new BN(await web3.eth.getBalance(alice)); // Alice close position#2 await bank.work( 2, goblin.address, '0', '1000000000000000000000000000000', web3.eth.abi.encodeParameters( ['address', 'bytes'], [liqStrat.address, web3.eth.abi.encodeParameters(['address', 'uint256'], [mta.address, '0'])] ), { from: alice, gasPrice: 0 } ); const aliceAfter = new BN(await web3.eth.getBalance(alice)); // Check Alice account expect(aliceAfter).to.be.bignumber.gt(aliceBefore); //Alice must be richer }); });
the_stack
import { Either } from "../../../Data/Either" import { IO } from "../../../System/IO" import { MapEitherIO, mapMObjectIO } from "./MapEitherIOObject" import { YamlParser } from "./Parser" import { YamlNameMap, YamlSchemaMap } from "./SchemaMap" const handleOverrideParser = <A extends keyof YamlSchemaMap> ( parser : YamlParser | undefined, schemaRef : A ) : IO<Either<Error[], YamlSchemaMap[A]>> | undefined => parser === undefined ? undefined : parser (schemaRef) export const parseByFile = (univParser : YamlParser) => (defaultParser : YamlParser) => async (l10nParser : (YamlParser | undefined)) : MapEitherIO<Error[], YamlNameMap> => mapMObjectIO ({ AdvantagesL10nOverride: handleOverrideParser (l10nParser, "Schema/Advantages/Advantages.l10n.schema.json"), AdvantagesL10nDefault: defaultParser ("Schema/Advantages/Advantages.l10n.schema.json"), AdvantagesUniv: univParser ("Schema/Advantages/Advantages.univ.schema.json"), AnimistForcesL10nOverride: handleOverrideParser (l10nParser, "Schema/AnimistForces/AnimistForces.l10n.schema.json"), AnimistForcesL10nDefault: defaultParser ("Schema/AnimistForces/AnimistForces.l10n.schema.json"), AnimistForcesUniv: univParser ("Schema/AnimistForces/AnimistForces.univ.schema.json"), ArcaneBardTraditionsL10nOverride: handleOverrideParser ( l10nParser, "Schema/ArcaneBardTraditions/ArcaneBardTraditions.l10n.schema.json" ), ArcaneBardTraditionsL10nDefault: defaultParser ("Schema/ArcaneBardTraditions/ArcaneBardTraditions.l10n.schema.json"), ArcaneBardTraditionsUniv: univParser ("Schema/ArcaneBardTraditions/ArcaneBardTraditions.univ.schema.json"), ArcaneDancerTraditionsL10nOverride: handleOverrideParser ( l10nParser, "Schema/ArcaneDancerTraditions/ArcaneDancerTraditions.l10n.schema.json" ), ArcaneDancerTraditionsL10nDefault: defaultParser ("Schema/ArcaneDancerTraditions/ArcaneDancerTraditions.l10n.schema.json"), ArcaneDancerTraditionsUniv: univParser ("Schema/ArcaneDancerTraditions/ArcaneDancerTraditions.univ.schema.json"), ArmorTypesL10nOverride: handleOverrideParser (l10nParser, "Schema/ArmorTypes/ArmorTypes.l10n.schema.json"), ArmorTypesL10nDefault: defaultParser ("Schema/ArmorTypes/ArmorTypes.l10n.schema.json"), AspectsL10nOverride: handleOverrideParser (l10nParser, "Schema/Aspects/Aspects.l10n.schema.json"), AspectsL10nDefault: defaultParser ("Schema/Aspects/Aspects.l10n.schema.json"), AttributesL10nOverride: handleOverrideParser (l10nParser, "Schema/Attributes/Attributes.l10n.schema.json"), AttributesL10nDefault: defaultParser ("Schema/Attributes/Attributes.l10n.schema.json"), BlessedTraditionsL10nOverride: handleOverrideParser ( l10nParser, "Schema/BlessedTraditions/BlessedTraditions.l10n.schema.json" ), BlessedTraditionsL10nDefault: defaultParser ("Schema/BlessedTraditions/BlessedTraditions.l10n.schema.json"), BlessedTraditionsUniv: univParser ("Schema/BlessedTraditions/BlessedTraditions.univ.schema.json"), BlessingsL10nOverride: handleOverrideParser (l10nParser, "Schema/Blessings/Blessings.l10n.schema.json"), BlessingsL10nDefault: defaultParser ("Schema/Blessings/Blessings.l10n.schema.json"), BlessingsUniv: univParser ("Schema/Blessings/Blessings.univ.schema.json"), BooksL10nOverride: handleOverrideParser (l10nParser, "Schema/Books/Books.l10n.schema.json"), BooksL10nDefault: defaultParser ("Schema/Books/Books.l10n.schema.json"), BrewsL10nOverride: handleOverrideParser (l10nParser, "Schema/Brews/Brews.l10n.schema.json"), BrewsL10nDefault: defaultParser ("Schema/Brews/Brews.l10n.schema.json"), CantripsL10nOverride: handleOverrideParser (l10nParser, "Schema/Cantrips/Cantrips.l10n.schema.json"), CantripsL10nDefault: defaultParser ("Schema/Cantrips/Cantrips.l10n.schema.json"), CantripsUniv: univParser ("Schema/Cantrips/Cantrips.univ.schema.json"), CombatSpecialAbilityGroupsL10nOverride: handleOverrideParser ( l10nParser, "Schema/CombatSpecialAbilityGroups/CombatSpecialAbilityGroups.l10n.schema.json" ), CombatSpecialAbilityGroupsL10nDefault: // eslint-disable-next-line max-len defaultParser ("Schema/CombatSpecialAbilityGroups/CombatSpecialAbilityGroups.l10n.schema.json"), CombatTechniqueGroupsL10nOverride: handleOverrideParser ( l10nParser, "Schema/CombatTechniqueGroups/CombatTechniqueGroups.l10n.schema.json" ), CombatTechniqueGroupsL10nDefault: defaultParser ("Schema/CombatTechniqueGroups/CombatTechniqueGroups.l10n.schema.json"), CombatTechniquesL10nOverride: handleOverrideParser ( l10nParser, "Schema/CombatTechniques/CombatTechniques.l10n.schema.json" ), CombatTechniquesL10nDefault: defaultParser ("Schema/CombatTechniques/CombatTechniques.l10n.schema.json"), CombatTechniquesUniv: univParser ("Schema/CombatTechniques/CombatTechniques.univ.schema.json"), ConditionsL10nOverride: handleOverrideParser (l10nParser, "Schema/Conditions/Conditions.l10n.schema.json"), ConditionsL10nDefault: defaultParser ("Schema/Conditions/Conditions.l10n.schema.json"), CulturesL10nOverride: handleOverrideParser (l10nParser, "Schema/Cultures/Cultures.l10n.schema.json"), CulturesL10nDefault: defaultParser ("Schema/Cultures/Cultures.l10n.schema.json"), CulturesUniv: univParser ("Schema/Cultures/Cultures.univ.schema.json"), CursesL10nOverride: handleOverrideParser (l10nParser, "Schema/Curses/Curses.l10n.schema.json"), CursesL10nDefault: defaultParser ("Schema/Curses/Curses.l10n.schema.json"), CursesUniv: univParser ("Schema/Curses/Curses.univ.schema.json"), DerivedCharacteristicsL10nOverride: handleOverrideParser ( l10nParser, "Schema/DerivedCharacteristics/DerivedCharacteristics.l10n.schema.json" ), DerivedCharacteristicsL10nDefault: defaultParser ("Schema/DerivedCharacteristics/DerivedCharacteristics.l10n.schema.json"), DisadvantagesL10nOverride: handleOverrideParser (l10nParser, "Schema/Disadvantages/Disadvantages.l10n.schema.json"), DisadvantagesL10nDefault: defaultParser ("Schema/Disadvantages/Disadvantages.l10n.schema.json"), DisadvantagesUniv: univParser ("Schema/Disadvantages/Disadvantages.univ.schema.json"), DominationRitualsL10nOverride: handleOverrideParser ( l10nParser, "Schema/DominationRituals/DominationRituals.l10n.schema.json" ), DominationRitualsL10nDefault: defaultParser ("Schema/DominationRituals/DominationRituals.l10n.schema.json"), DominationRitualsUniv: univParser ("Schema/DominationRituals/DominationRituals.univ.schema.json"), ElvenMagicalSongsL10nOverride: handleOverrideParser ( l10nParser, "Schema/ElvenMagicalSongs/ElvenMagicalSongs.l10n.schema.json" ), ElvenMagicalSongsL10nDefault: defaultParser ("Schema/ElvenMagicalSongs/ElvenMagicalSongs.l10n.schema.json"), ElvenMagicalSongsUniv: univParser ("Schema/ElvenMagicalSongs/ElvenMagicalSongs.univ.schema.json"), EquipmentL10nOverride: handleOverrideParser (l10nParser, "Schema/Equipment/Equipment.l10n.schema.json"), EquipmentL10nDefault: defaultParser ("Schema/Equipment/Equipment.l10n.schema.json"), EquipmentUniv: univParser ("Schema/Equipment/Equipment.univ.schema.json"), EquipmentGroupsL10nOverride: handleOverrideParser ( l10nParser, "Schema/EquipmentGroups/EquipmentGroups.l10n.schema.json" ), EquipmentGroupsL10nDefault: defaultParser ("Schema/EquipmentGroups/EquipmentGroups.l10n.schema.json"), EquipmentPackagesL10nOverride: handleOverrideParser ( l10nParser, "Schema/EquipmentPackages/EquipmentPackages.l10n.schema.json" ), EquipmentPackagesL10nDefault: defaultParser ("Schema/EquipmentPackages/EquipmentPackages.l10n.schema.json"), EquipmentPackagesUniv: univParser ("Schema/EquipmentPackages/EquipmentPackages.univ.schema.json"), ExperienceLevelsL10nOverride: handleOverrideParser ( l10nParser, "Schema/ExperienceLevels/ExperienceLevels.l10n.schema.json" ), ExperienceLevelsL10nDefault: defaultParser ("Schema/ExperienceLevels/ExperienceLevels.l10n.schema.json"), ExperienceLevelsUniv: univParser ("Schema/ExperienceLevels/ExperienceLevels.univ.schema.json"), EyeColorsL10nOverride: handleOverrideParser (l10nParser, "Schema/EyeColors/EyeColors.l10n.schema.json"), EyeColorsL10nDefault: defaultParser ("Schema/EyeColors/EyeColors.l10n.schema.json"), FocusRulesL10nOverride: handleOverrideParser (l10nParser, "Schema/FocusRules/FocusRules.l10n.schema.json"), FocusRulesL10nDefault: defaultParser ("Schema/FocusRules/FocusRules.l10n.schema.json"), FocusRulesUniv: univParser ("Schema/FocusRules/FocusRules.univ.schema.json"), GeodeRitualsL10nOverride: handleOverrideParser (l10nParser, "Schema/GeodeRituals/GeodeRituals.l10n.schema.json"), GeodeRitualsL10nDefault: defaultParser ("Schema/GeodeRituals/GeodeRituals.l10n.schema.json"), GeodeRitualsUniv: univParser ("Schema/GeodeRituals/GeodeRituals.univ.schema.json"), HairColorsL10nOverride: handleOverrideParser (l10nParser, "Schema/HairColors/HairColors.l10n.schema.json"), HairColorsL10nDefault: defaultParser ("Schema/HairColors/HairColors.l10n.schema.json"), LiturgicalChantEnhancementsL10nOverride: handleOverrideParser ( l10nParser, "Schema/LiturgicalChantEnhancements/LiturgicalChantEnhancements.l10n.schema.json" ), LiturgicalChantEnhancementsL10nDefault: // eslint-disable-next-line max-len defaultParser ("Schema/LiturgicalChantEnhancements/LiturgicalChantEnhancements.l10n.schema.json"), LiturgicalChantEnhancementsUniv: // eslint-disable-next-line max-len univParser ("Schema/LiturgicalChantEnhancements/LiturgicalChantEnhancements.univ.schema.json"), LiturgicalChantGroupsL10nOverride: handleOverrideParser ( l10nParser, "Schema/LiturgicalChantGroups/LiturgicalChantGroups.l10n.schema.json" ), LiturgicalChantGroupsL10nDefault: defaultParser ("Schema/LiturgicalChantGroups/LiturgicalChantGroups.l10n.schema.json"), LiturgicalChantsL10nOverride: handleOverrideParser ( l10nParser, "Schema/LiturgicalChants/LiturgicalChants.l10n.schema.json" ), LiturgicalChantsL10nDefault: defaultParser ("Schema/LiturgicalChants/LiturgicalChants.l10n.schema.json"), LiturgicalChantsUniv: univParser ("Schema/LiturgicalChants/LiturgicalChants.univ.schema.json"), MagicalDancesL10nOverride: handleOverrideParser (l10nParser, "Schema/MagicalDances/MagicalDances.l10n.schema.json"), MagicalDancesL10nDefault: defaultParser ("Schema/MagicalDances/MagicalDances.l10n.schema.json"), MagicalDancesUniv: univParser ("Schema/MagicalDances/MagicalDances.univ.schema.json"), MagicalMelodiesL10nOverride: handleOverrideParser ( l10nParser, "Schema/MagicalMelodies/MagicalMelodies.l10n.schema.json" ), MagicalMelodiesL10nDefault: defaultParser ("Schema/MagicalMelodies/MagicalMelodies.l10n.schema.json"), MagicalMelodiesUniv: univParser ("Schema/MagicalMelodies/MagicalMelodies.univ.schema.json"), MagicalTraditionsL10nOverride: handleOverrideParser ( l10nParser, "Schema/MagicalTraditions/MagicalTraditions.l10n.schema.json" ), MagicalTraditionsL10nDefault: defaultParser ("Schema/MagicalTraditions/MagicalTraditions.l10n.schema.json"), MagicalTraditionsUniv: univParser ("Schema/MagicalTraditions/MagicalTraditions.univ.schema.json"), OptionalRulesL10nOverride: handleOverrideParser (l10nParser, "Schema/OptionalRules/OptionalRules.l10n.schema.json"), OptionalRulesL10nDefault: defaultParser ("Schema/OptionalRules/OptionalRules.l10n.schema.json"), PactsL10nOverride: handleOverrideParser (l10nParser, "Schema/Pacts/Pacts.l10n.schema.json"), PactsL10nDefault: defaultParser ("Schema/Pacts/Pacts.l10n.schema.json"), ProfessionsL10nOverride: handleOverrideParser (l10nParser, "Schema/Professions/Professions.l10n.schema.json"), ProfessionsL10nDefault: defaultParser ("Schema/Professions/Professions.l10n.schema.json"), ProfessionsUniv: univParser ("Schema/Professions/Professions.univ.schema.json"), ProfessionVariantsL10nOverride: handleOverrideParser ( l10nParser, "Schema/ProfessionVariants/ProfessionVariants.l10n.schema.json" ), ProfessionVariantsL10nDefault: defaultParser ("Schema/ProfessionVariants/ProfessionVariants.l10n.schema.json"), ProfessionVariantsUniv: univParser ("Schema/ProfessionVariants/ProfessionVariants.univ.schema.json"), PropertiesL10nOverride: handleOverrideParser (l10nParser, "Schema/Properties/Properties.l10n.schema.json"), PropertiesL10nDefault: defaultParser ("Schema/Properties/Properties.l10n.schema.json"), RacesL10nOverride: handleOverrideParser (l10nParser, "Schema/Races/Races.l10n.schema.json"), RacesL10nDefault: defaultParser ("Schema/Races/Races.l10n.schema.json"), RacesUniv: univParser ("Schema/Races/Races.univ.schema.json"), RaceVariantsL10nOverride: handleOverrideParser (l10nParser, "Schema/RaceVariants/RaceVariants.l10n.schema.json"), RaceVariantsL10nDefault: defaultParser ("Schema/RaceVariants/RaceVariants.l10n.schema.json"), RaceVariantsUniv: univParser ("Schema/RaceVariants/RaceVariants.univ.schema.json"), ReachesL10nOverride: handleOverrideParser (l10nParser, "Schema/Reaches/Reaches.l10n.schema.json"), ReachesL10nDefault: defaultParser ("Schema/Reaches/Reaches.l10n.schema.json"), RogueSpellsL10nOverride: handleOverrideParser (l10nParser, "Schema/RogueSpells/RogueSpells.l10n.schema.json"), RogueSpellsL10nDefault: defaultParser ("Schema/RogueSpells/RogueSpells.l10n.schema.json"), RogueSpellsUniv: univParser ("Schema/RogueSpells/RogueSpells.univ.schema.json"), SkillGroupsL10nOverride: handleOverrideParser (l10nParser, "Schema/SkillGroups/SkillGroups.l10n.schema.json"), SkillGroupsL10nDefault: defaultParser ("Schema/SkillGroups/SkillGroups.l10n.schema.json"), SkillsL10nOverride: handleOverrideParser (l10nParser, "Schema/Skills/Skills.l10n.schema.json"), SkillsL10nDefault: defaultParser ("Schema/Skills/Skills.l10n.schema.json"), SkillsUniv: univParser ("Schema/Skills/Skills.univ.schema.json"), SocialStatusesL10nOverride: handleOverrideParser (l10nParser, "Schema/SocialStatuses/SocialStatuses.l10n.schema.json"), SocialStatusesL10nDefault: defaultParser ("Schema/SocialStatuses/SocialStatuses.l10n.schema.json"), SpecialAbilitiesL10nOverride: handleOverrideParser ( l10nParser, "Schema/SpecialAbilities/SpecialAbilities.l10n.schema.json" ), SpecialAbilitiesL10nDefault: defaultParser ("Schema/SpecialAbilities/SpecialAbilities.l10n.schema.json"), SpecialAbilitiesUniv: univParser ("Schema/SpecialAbilities/SpecialAbilities.univ.schema.json"), SpecialAbilityGroupsL10nOverride: handleOverrideParser ( l10nParser, "Schema/SpecialAbilityGroups/SpecialAbilityGroups.l10n.schema.json" ), SpecialAbilityGroupsL10nDefault: defaultParser ("Schema/SpecialAbilityGroups/SpecialAbilityGroups.l10n.schema.json"), SpellEnhancementsL10nOverride: handleOverrideParser ( l10nParser, "Schema/SpellEnhancements/SpellEnhancements.l10n.schema.json" ), SpellEnhancementsL10nDefault: defaultParser ("Schema/SpellEnhancements/SpellEnhancements.l10n.schema.json"), SpellEnhancementsUniv: univParser ("Schema/SpellEnhancements/SpellEnhancements.univ.schema.json"), SpellGroupsL10nOverride: handleOverrideParser (l10nParser, "Schema/SpellGroups/SpellGroups.l10n.schema.json"), SpellGroupsL10nDefault: defaultParser ("Schema/SpellGroups/SpellGroups.l10n.schema.json"), SpellsL10nOverride: handleOverrideParser (l10nParser, "Schema/Spells/Spells.l10n.schema.json"), SpellsL10nDefault: defaultParser ("Schema/Spells/Spells.l10n.schema.json"), SpellsUniv: univParser ("Schema/Spells/Spells.univ.schema.json"), StatesL10nOverride: handleOverrideParser (l10nParser, "Schema/States/States.l10n.schema.json"), StatesL10nDefault: defaultParser ("Schema/States/States.l10n.schema.json"), SubjectsL10nOverride: handleOverrideParser (l10nParser, "Schema/Subjects/Subjects.l10n.schema.json"), SubjectsL10nDefault: defaultParser ("Schema/Subjects/Subjects.l10n.schema.json"), TribesL10nOverride: handleOverrideParser (l10nParser, "Schema/Tribes/Tribes.l10n.schema.json"), TribesL10nDefault: defaultParser ("Schema/Tribes/Tribes.l10n.schema.json"), UIL10nOverride: handleOverrideParser (l10nParser, "Schema/UI/UI.l10n.schema.json"), UIL10nDefault: defaultParser ("Schema/UI/UI.l10n.schema.json"), ZibiljaRitualsL10nOverride: handleOverrideParser (l10nParser, "Schema/ZibiljaRituals/ZibiljaRituals.l10n.schema.json"), ZibiljaRitualsL10nDefault: defaultParser ("Schema/ZibiljaRituals/ZibiljaRituals.l10n.schema.json"), ZibiljaRitualsUniv: univParser ("Schema/ZibiljaRituals/ZibiljaRituals.univ.schema.json"), })
the_stack
import { Collection, DeleteWriteOpResultObject, ObjectID } from 'mongodb'; const clone = require('rfdc')({ proto: true }); import { COLLECTION_KEY, CollectionProps, DBSource, Document, FindRequest, POST_KEY, PRE_KEY, UpdateByIdRequest, UpdateRequest, RepoEventArgs, RepoOperation, EventOptions } from './Types'; export class MongoRepository<DOC, DTO = DOC> { collection: Promise<Collection<DOC>>; readonly options: CollectionProps; // get options(): CollectionProps { // return Reflect.getMetadata(COLLECTION_KEY, this); // } /** * Creates an instance of MongoRepository. * @param {DBSource} dbSource Your MongoDB connection * @param opts Collection initialize options * @memberof MongoRepository */ constructor(public dbSource: DBSource, opts?: CollectionProps) { this.options = Object.assign({}, opts, Reflect.getMetadata(COLLECTION_KEY, this)); if (!this.options.name) { throw new Error('No name was provided for this collection'); } this.collection = this.getCollection(); } /** * Finds a record by id * * @param {string} id * @returns {Promise<DOC | null>} * @memberof MongoRepository */ findById(id: string): Promise<DOC | null> { return this.findOne({ _id: new ObjectID(id) }); } /** * Find multiple documents by a list of ids * * @param {string[]} ids * @returns {Promise<DOC[]>} * @memberof MongoRepository */ async findManyById(ids: string[]): Promise<DOC[]> { const collection = await this.collection; const query = { _id: { $in: ids.map(id => new ObjectID(id)) } }; const found = await collection.find(<object>query).toArray(); const results: DOC[] = []; for (const result of found) { results.push( await this.invokeEvents(POST_KEY, [RepoOperation.find, RepoOperation.findMany], this.toggleId(result, false)) ); } return results; } /** * Finds a record by a list of conditions * * @param {object} conditions * @returns {Promise<DOC | null>} * @memberof MongoRepository */ async findOne(conditions: object): Promise<DOC | null> { const collection = await this.collection; let document = await collection.findOne(conditions); if (document) { document = this.toggleId(document, false); document = await this.invokeEvents(POST_KEY, [RepoOperation.find, RepoOperation.findOne], document); } return document; } /** * Find records by a list of conditions * * @param {FindRequest} [req={ conditions: {} }] * @returns {Promise<PROJECTION[]>} * @memberof MongoRepository */ async find<PROJECTION = DOC>(req: FindRequest = { conditions: {} }): Promise<PROJECTION[]> { const collection = await this.collection; const conditions = this.toggleId(req.conditions, true); let cursor = collection.find(conditions); if (req.projection) { cursor = cursor.project(req.projection); } if (req.sort) { cursor = cursor.sort(req.sort); } if (req.skip) { cursor = cursor.skip(req.skip); } if (req.limit) { cursor = cursor.limit(req.limit); } const newDocuments = await cursor.toArray(); const results = []; for (let document of newDocuments) { document = this.toggleId(document, false); document = await this.invokeEvents(POST_KEY, [RepoOperation.find, RepoOperation.findMany], document); results.push(document); } return results; } /** * Create a document of type T * * @param {DTO} document * @returns {Promise<DOC>} * @memberof MongoRepository */ async create(document: DTO): Promise<DOC> { const collection = await this.collection; const eventResult = await this.invokeEvents(PRE_KEY, [RepoOperation.save, RepoOperation.create], document); const res = await collection.insertOne(eventResult); let newDocument = this.toggleId(res.ops[0], false); newDocument = await this.invokeEvents(POST_KEY, [RepoOperation.save, RepoOperation.create], newDocument); return newDocument; } /** * Save any changes to your document * * @param {Document} document * @returns {Promise<DOC>} * @memberof MongoRepository */ async save(document: Document): Promise<DOC> { const collection = await this.collection; // flip/flop ids const id = new ObjectID(document.id); const updates = await this.invokeEvents(PRE_KEY, [RepoOperation.save], document); delete updates['id']; delete updates['_id']; const query = { _id: id }; const originalDoc = await this.findOne(<object>query); const res = await collection.updateOne(<object>query, { $set: updates }, { upsert: true }); let newDocument = await collection.findOne(<object>query); // flip flop ids back this.toggleId(newDocument, false); newDocument = await this.invokeEvents(POST_KEY, [RepoOperation.save], newDocument, originalDoc); // project new items if (newDocument) { Object.assign(document, newDocument); } return newDocument; } /** * Find a record by ID and update with new values * * @param {string} id * @param {UpdateByIdRequest} req * @returns {Promise<DOC | null>} * @memberof MongoRepository */ async findOneByIdAndUpdate(id: string, req: UpdateByIdRequest): Promise<DOC | null> { return this.findOneAndUpdate({ conditions: { _id: new ObjectID(id) }, updates: req.updates, upsert: req.upsert }); } /** * Find a record and update with new values * * @param {UpdateRequest} req * @returns {Promise<DOC | null>} * @memberof MongoRepository */ async findOneAndUpdate(req: UpdateRequest): Promise<DOC | null> { const collection = await this.collection; const updates = await this.invokeEvents(PRE_KEY, [RepoOperation.update, RepoOperation.updateOne], req.updates); const originalDoc = await this.findOne(req.conditions); if (!req.upsert && !originalDoc) { return originalDoc; } const res = await collection.findOneAndUpdate(req.conditions, updates, { upsert: req.upsert, returnOriginal: false }); let document = res.value; if (document) { document = this.toggleId(document, false); document = await this.invokeEvents( POST_KEY, [RepoOperation.update, RepoOperation.updateOne], document, originalDoc ); } return document; } /** * Delete a record by ID * * @param {string} id * @returns {Promise<DeleteWriteOpResultObject>} * @memberof MongoRepository */ async deleteOneById(id: string): Promise<DeleteWriteOpResultObject> { return this.deleteOne({ _id: new ObjectID(id) }); } /** * Delete a record * * @param {*} conditions * @returns {Promise<DeleteWriteOpResultObject>} * @memberof MongoRepository */ async deleteOne(conditions: any): Promise<DeleteWriteOpResultObject> { const collection = await this.collection; await this.invokeEvents(PRE_KEY, [RepoOperation.delete, RepoOperation.deleteOne], conditions); const deleteResult = await collection.deleteOne(conditions); await this.invokeEvents(POST_KEY, [RepoOperation.delete, RepoOperation.deleteOne], deleteResult); return deleteResult; } /** * Delete multiple records * * @param {*} conditions * @returns {Promise<any>} * @memberof MongoRepository */ async deleteMany(conditions: any): Promise<DeleteWriteOpResultObject> { const collection = await this.collection; await this.invokeEvents(PRE_KEY, [RepoOperation.delete, RepoOperation.deleteMany], conditions); const deleteResult = await collection.deleteMany(conditions); await this.invokeEvents(POST_KEY, [RepoOperation.delete, RepoOperation.deleteMany], deleteResult); return deleteResult; } /** * Strip off Mongo's ObjectID and replace with string representation or in reverse * * @private * @param {*} document * @param {boolean} replace * @returns {any} * @memberof MongoRepository */ protected toggleId(document: any, replace: boolean): any { if (document && (document.id || document._id)) { if (replace) { document._id = new ObjectID(document.id); delete document.id; } else { document.id = document._id.toString(); delete document._id; } } return document; } /** * Apply functions to a record based on the type of event * * @private * @param {string} type any of the valid types, PRE_KEY POST_KEY * @param {RepoOperation[]} fns any of the valid functions: update, updateOne, save, create, find, findOne, findMany * @param {*} newDocument The document to apply functions to * @param originalDocument The original document before changes were applied * @param opts Options for event * @returns {Promise<any>} * @memberof MongoRepository */ protected async invokeEvents( type: string, fns: RepoOperation[], newDocument: any, originalDocument?: any, opts?: EventOptions ): Promise<any> { // local options override global collection options if (opts?.noClone === false || (opts?.noClone === undefined && this.options.eventOpts?.noClone !== true)) { // Dereference (aka clone) the target document(s) to // prevent down stream modifications in events on the original instance(s) newDocument = clone(newDocument); if (originalDocument) { originalDocument = clone(originalDocument); } } for (const fn of fns) { const events = Reflect.getMetadata(`${type}_${fn}`, this) || []; for (const event of events) { const repoEventArgs: RepoEventArgs = { originalDocument, operation: fn, operationType: type }; newDocument = event.bind(this)(newDocument, repoEventArgs); if (typeof newDocument.then === 'function') { newDocument = await newDocument; } } } return newDocument; } /** * Return a collection * If the collection doesn't exist, it will create it with the given options * * @private * @returns {Promise<Collection<DOC>>} * @memberof MongoRepository */ private getCollection(): Promise<Collection<DOC>> { return new Promise<Collection<DOC>>(async (resolve, reject) => { const db = await this.dbSource.db; db.collection(this.options.name, { strict: true }, async (err, collection) => { let ourCollection = collection; if (err) { try { ourCollection = await db.createCollection(this.options.name, { size: this.options.size, capped: this.options.capped, max: this.options.max }); } catch (createErr) { if (createErr.codeName === 'NamespaceExists') { // race condition. ignore for now, as I can't seem to get // transactions to work in mongo 4.4 as yet ourCollection = db.collection(this.options.name); } else { reject(err); } } } // assert indexes if (this.options.indexes) { for (const indexDefinition of this.options.indexes) { try { await ourCollection.createIndex(indexDefinition.fields, indexDefinition.options); } catch (indexErr) { if ( indexDefinition.overwrite && indexDefinition.options.name && indexErr.name === 'MongoError' && (indexErr.codeName === 'IndexKeySpecsConflict' || indexErr.codeName === 'IndexOptionsConflict') ) { // drop index and recreate try { await ourCollection.dropIndex(indexDefinition.options.name); await ourCollection.createIndex(indexDefinition.fields, indexDefinition.options); } catch (recreateErr) { reject(recreateErr); } } else { reject(indexErr); } } } } resolve(ourCollection); }); }); } }
the_stack
import * as adapterTypes from "./adapter-types"; import * as sdkTypes from "../../script/types"; import RequestManager from "../request-manager"; class Adapter { constructor(private readonly _requestManager: RequestManager) { } public toLegacyAccount(profile: adapterTypes.UserProfile): sdkTypes.Account { return { name: profile.name, email: profile.email, linkedProviders: [] }; } public toLegacyAccessKey(apiToken: adapterTypes.ApiToken): sdkTypes.AccessKey { const accessKey: sdkTypes.AccessKey = { createdTime: Date.parse(apiToken.created_at), expires: Date.parse('9999-12-31T23:59:59'), // never, key: apiToken.api_token, name: apiToken.description }; return accessKey; } public toLegacyAccessKeyList(apiTokens: adapterTypes.ApiTokensGetResponse[]): sdkTypes.AccessKey[] { console.log(apiTokens); const accessKeyList: sdkTypes.AccessKey[] = apiTokens.map((apiToken) => { const accessKey: sdkTypes.AccessKey = { createdTime: Date.parse(apiToken.created_at), expires: Date.parse('9999-12-31T23:59:59'), // never, name: apiToken.description, }; return accessKey; }); accessKeyList.sort( (first: sdkTypes.AccessKey, second: sdkTypes.AccessKey) => { const firstTime = first.createdTime || 0; const secondTime = second.createdTime || 0; return firstTime - secondTime; } ); return accessKeyList; } public async toLegacyApp(app: adapterTypes.App): Promise<sdkTypes.App> { const [user, deployments] = await Promise.all([this.getUser(), this.getDeployments(app.owner.name, app.name)]); const deploymentsNames = deployments.map((deployment: adapterTypes.Deployment) => deployment.name); return this.toLegacyRestApp(app, user, deploymentsNames); }; public async toLegacyApps(apps: adapterTypes.App[]): Promise<sdkTypes.App[]> { const user = await this.getUser(); const sortedApps = await Promise.all( apps.sort((first: adapterTypes.App, second: adapterTypes.App) => { const firstOwner = first.owner.name || ''; const secondOwner = second.owner.name || ''; // First sort by owner, then by app name if (firstOwner !== secondOwner) { return firstOwner.localeCompare(secondOwner); } else { return first.name.localeCompare(second.name); } }) ); const legacyApps = await Promise.all( sortedApps.map(async (app) => { const deployments: adapterTypes.Deployment[] = await this.getDeployments(app.owner.name, app.name); const deploymentsNames = deployments.map((deployment: adapterTypes.Deployment) => deployment.name); return this.toLegacyRestApp(app, user, deploymentsNames); }) ); return legacyApps; }; public toApigatewayAppCreationRequest(appToCreate: sdkTypes.AppCreationRequest): adapterTypes.ApigatewayAppCreationRequest { if ( appToCreate.os !== 'iOS' && appToCreate.os !== 'Android' && appToCreate.os !== 'Windows' && appToCreate.os !== 'Linux' ) { throw this.getCodePushError(`The app OS "${appToCreate.os}" isn't valid. It should be "iOS", "Android", "Windows" or "Linux".`, RequestManager.ERROR_CONFLICT); } if ( appToCreate.platform !== 'React-Native' && appToCreate.platform !== 'Cordova' && appToCreate.platform !== 'Electron' ) { throw this.getCodePushError(`The app platform "${appToCreate.platform}" isn't valid. It should be "React-Native", "Cordova" or "Electron".`, RequestManager.ERROR_CONFLICT); } const org: string = this.getOrgFromLegacyAppRequest(appToCreate); const appcenterClientApp: adapterTypes.App = this.toAppcenterClientApp(appToCreate); if (!this.isValidAppCenterAppName(appcenterClientApp.display_name)) { throw this.getCodePushError(`The app name "${appcenterClientApp.display_name}" isn't valid. It can only contain alphanumeric characters, dashes, periods, or underscores.`, RequestManager.ERROR_CONFLICT); } return { org, appcenterClientApp }; } public async addStandardDeployments(apiAppName: string): Promise<void> { const { appOwner, appName } = await this.parseApiAppName(apiAppName); const deploymentsToCreate = ['Staging', 'Production']; await Promise.all( deploymentsToCreate.map(async (deploymentName) => { const deployment = <sdkTypes.Deployment>{ name: deploymentName }; return await this._requestManager.post(`/apps/${appOwner}/${appName}/deployments/`, JSON.stringify(deployment), /*expectResponseBody=*/ true); }) ); return; }; public async getRenamedApp(newName: string, appOwner: string, oldName: string): Promise<adapterTypes.UpdatedApp> { const app = await this.getApp(appOwner, oldName); if (newName.indexOf('/') !== -1) { throw this.getCodePushError(`The new app name "${newName}" must be unqualified, not having a '/' character.`, RequestManager.ERROR_CONFLICT); } if (!this.isValidAppCenterAppName(newName)) { throw this.getCodePushError(`The app name "${newName}" isn't valid. It can only contain alphanumeric characters, dashes, periods, or underscores.`, RequestManager.ERROR_CONFLICT); } // If the display name was set on the existing app, then it was different than the app name. In that case, leave the display name unchanged; // the user can change the display name through the Mobile Center web portal if they want to rename it. // But if the display name and app name were the same, then rename them both. const updatedApp = app.name === app.display_name ? { name: newName, display_name: newName } : { name: newName }; return updatedApp; } public async resolveAccessKey(accessKeyName: string): Promise<adapterTypes.ApiTokensGetResponse> { const accessKeys = await this.getApiTokens(); const foundAccessKey = accessKeys.find((key) => { return key.description === accessKeyName; }); if (!foundAccessKey) { throw this.getCodePushError(`Access key "${accessKeyName}" does not exist.`, RequestManager.ERROR_NOT_FOUND); } return foundAccessKey; } public toLegacyDeployments(deployments: adapterTypes.Deployment[]): sdkTypes.Deployment[] { deployments.sort((first: adapterTypes.Deployment, second: adapterTypes.Deployment) => { return first.name.localeCompare(second.name); }); return this.toLegacyRestDeployments(deployments); }; public toLegacyDeployment(deployment: adapterTypes.Deployment): sdkTypes.Deployment { return this.toLegacyRestDeployment(deployment); }; public async toLegacyCollaborators( userList: adapterTypes.UserProfile[], appOwner: string, ): Promise<sdkTypes.CollaboratorMap> { const callingUser = await this.getUser(); const legacyCollaborators: sdkTypes.CollaboratorMap = {}; userList.forEach((user) => { legacyCollaborators[user.email] = { isCurrentAccount: callingUser.email === user.email, permission: this.toLegacyUserPermission(user.permissions[0], user.name && user.name === appOwner) }; }); return legacyCollaborators; } public async toLegacyDeploymentMetrics( deploymentMetrics: adapterTypes.DeploymentMetrics[], ): Promise<sdkTypes.DeploymentMetrics> { const legacyDeploymentMetrics: sdkTypes.DeploymentMetrics = {}; deploymentMetrics.forEach((deployment) => { legacyDeploymentMetrics[deployment.label] = { active: deployment.active, downloaded: deployment.downloaded, failed: deployment.failed, installed: deployment.installed }; }); return legacyDeploymentMetrics; } public async parseApiAppName(apiAppName: string): Promise<adapterTypes.appParams> { const callingUser = await this.getUser(); // If the separating / is not included, assume the owner is the calling user and only the app name is provided if (!apiAppName.includes("/")) { return { appOwner: callingUser.name, appName: apiAppName, }; } const [appOwner, appName] = apiAppName.split("/"); return { appOwner: appOwner, appName: appName, }; } public toLegacyDeploymentHistory(releases: adapterTypes.CodePushRelease[]): sdkTypes.Package[] { return releases.map((release) => this.releaseToPackage(release)); } private toLegacyRestApp(app: adapterTypes.App, user: adapterTypes.UserProfile, deployments: string[]): sdkTypes.App { const isCurrentAccount: boolean = user.id === app.owner.id; const isNameAndDisplayNameSame: boolean = app.name === app.display_name; let appName: string = app.name; if (!isCurrentAccount) { appName = app.owner.name + '/' + app.name; } if (!isNameAndDisplayNameSame) { appName += ` (${app.display_name})`; } return { name: appName, collaborators: { [app.owner.name]: { isCurrentAccount: user.id === app.owner.id, permission: 'Owner' } }, deployments, os: app.os, platform: app.platform }; } public toReleaseUploadProperties(updateMetadata: sdkTypes.PackageInfo, releaseUploadAssets: sdkTypes.ReleaseUploadAssets, deploymentName: string): sdkTypes.UploadReleaseProperties { const releaseUpload: sdkTypes.UploadReleaseProperties = { release_upload: releaseUploadAssets, target_binary_version: updateMetadata.appVersion, deployment_name: deploymentName, no_duplicate_release_error: false, // This property is not implemented in CodePush SDK Management } if (updateMetadata.description) releaseUpload.description = updateMetadata.description; if (updateMetadata.isDisabled) releaseUpload.disabled = updateMetadata.isDisabled; if (updateMetadata.isMandatory) releaseUpload.mandatory = updateMetadata.isMandatory; if (updateMetadata.rollout) releaseUpload.rollout = updateMetadata.rollout; return releaseUpload; } public toRestReleaseModification( legacyCodePushReleaseInfo: sdkTypes.PackageInfo ): adapterTypes.ReleaseModification { let releaseModification: adapterTypes.ReleaseModification = {} as adapterTypes.ReleaseModification ; if (legacyCodePushReleaseInfo.appVersion) releaseModification.target_binary_range = legacyCodePushReleaseInfo.appVersion; if (legacyCodePushReleaseInfo.isDisabled) releaseModification.is_disabled = legacyCodePushReleaseInfo.isDisabled; if (legacyCodePushReleaseInfo.isMandatory) releaseModification.is_mandatory = legacyCodePushReleaseInfo.isMandatory; if (legacyCodePushReleaseInfo.description) releaseModification.description = legacyCodePushReleaseInfo.description; if (legacyCodePushReleaseInfo.rollout) releaseModification.rollout = legacyCodePushReleaseInfo.rollout; if (legacyCodePushReleaseInfo.label) releaseModification.label = legacyCodePushReleaseInfo.label; return releaseModification; } public releaseToPackage(releasePackage: adapterTypes.CodePushRelease): sdkTypes.Package { const sdkPackage: sdkTypes.Package = { blobUrl: releasePackage.blob_url, size: releasePackage.size, uploadTime: releasePackage.upload_time, isDisabled: !!releasePackage.is_disabled, isMandatory: !!releasePackage.is_mandatory, } if (releasePackage.target_binary_range) sdkPackage.appVersion = releasePackage.target_binary_range; if (releasePackage.description) sdkPackage.description = releasePackage.description; if (releasePackage.label) sdkPackage.label = releasePackage.label; if (releasePackage.package_hash) sdkPackage.packageHash = releasePackage.package_hash; if (releasePackage.rollout) sdkPackage.rollout = releasePackage.rollout; if (releasePackage.diff_package_map) sdkPackage.diffPackageMap = releasePackage.diff_package_map; if (releasePackage.original_label) sdkPackage.originalLabel = releasePackage.original_label; if (releasePackage.original_deployment) sdkPackage.originalDeployment = releasePackage.original_deployment; if (releasePackage.released_by) sdkPackage.releasedBy = releasePackage.released_by; if (releasePackage.release_method) sdkPackage.releaseMethod = releasePackage.release_method; return sdkPackage; } private toLegacyRestDeployments(apiGatewayDeployments: adapterTypes.Deployment[]): sdkTypes.Deployment[] { const deployments: sdkTypes.Deployment[] = apiGatewayDeployments.map((deployment) => { return this.toLegacyRestDeployment(deployment); }); return deployments; } private toLegacyRestDeployment(deployment: adapterTypes.Deployment): sdkTypes.Deployment { const apiGatewayPackage = deployment.latest_release ? this.releaseToPackage(deployment.latest_release) : null; const restDeployment: sdkTypes.Deployment = { name: deployment.name, key: deployment.key, package: apiGatewayPackage }; return restDeployment; } private async getUser(): Promise<adapterTypes.UserProfile> { try { const res = await this._requestManager.get(`/user`); return res.body; } catch (error) { throw error; } } private async getApiTokens(): Promise<adapterTypes.ApiTokensGetResponse[]> { try { const res = await this._requestManager.get(`/api_tokens`); return res.body; } catch (error) { throw error; } } private async getApp(appOwner: string, appName: string): Promise<adapterTypes.App> { try { const res = await this._requestManager.get(`/apps/${appOwner}/${appName}`); return res.body; } catch (error) { throw error; } } private async getDeployments(appOwner: string, appName: string): Promise<adapterTypes.Deployment[]> { try { const res = await this._requestManager.get(`/apps/${appOwner}/${appName}/deployments/`); return res.body; } catch (error) { throw error; } } private toLegacyUserPermission(expectedPermission: adapterTypes.AppMemberPermissions, isOwner: boolean): string { if (expectedPermission === 'manager') { return isOwner ? 'Owner' : 'Manager'; } else if (expectedPermission === 'developer') { return 'Collaborator'; } return 'Reader'; } private getOrgFromLegacyAppRequest(legacyCreateAppRequest: sdkTypes.AppCreationRequest) { const slashIndex = legacyCreateAppRequest.name.indexOf('/'); const org = slashIndex !== -1 ? legacyCreateAppRequest.name.substring(0, slashIndex) : null; return org; } private toAppcenterClientApp(legacyCreateAppRequest: sdkTypes.AppCreationRequest): adapterTypes.App { // If the app name contains a slash, then assume that the app is intended to be owned by an org, with the org name // before the slash. Update the app info accordingly. const slashIndex = legacyCreateAppRequest.name.indexOf('/'); return { os: legacyCreateAppRequest.os as adapterTypes.AppOs, platform: legacyCreateAppRequest.platform as adapterTypes.AppPlatform, display_name: slashIndex !== -1 ? legacyCreateAppRequest.name.substring(slashIndex + 1) : legacyCreateAppRequest.name }; } private isValidAppCenterAppName(name: any): boolean { return this.getStringValidator(/*maxLength=*/ 1000, /*minLength=*/ 1)(name) && /^[a-zA-Z0-9-._]+$/.test(name); // Only allow alphanumeric characters, dashes, periods, or underscores } private getStringValidator(maxLength: number = 1000, minLength: number = 0): (value: any) => boolean { return function isValidString(value: string): boolean { if (typeof value !== 'string') { return false; } if (maxLength > 0 && value.length > maxLength) { return false; } return value.length >= minLength; }; } private getCodePushError(message: string, errorCode: number): sdkTypes.CodePushError { return { message: message, statusCode: errorCode }; } } export = Adapter;
the_stack
import sodium from 'libsodium-wrappers-sumo'; import pbkdf2 from 'pbkdf2'; import elliptic from 'elliptic'; import { getAddress, signOperation } from './ledger'; import { b58cencode, b58cdecode, textDecode, textEncode, hex2buf, buf2hex, mergebuf, } from './utility'; import { prefix } from './constants'; /** * Creates a key object from a base58 encoded key. * * @class Key * @param {Object} KeyConstructor * @param {string} [KeyConstructor.key] A public or secret key in base58 encoding, or a 15 word bip39 english mnemonic string. Not * providing a key will import a ledger public key. * @param {string} [KeyConstructor.passphrase] The passphrase used if the key provided is an encrypted private key or a fundraiser key * @param {string} [KeyConstructor.email] Email used if a fundraiser key is passed * @param {string} [KeyConstructor.ledgerPath="44'/1729'/0'/0'"] Ledger derivation path * @param {string} [KeyConstructor.ledgerCurve=tz1] Ledger curve * @example * const key = new Key({ key: 'edskRv6ZnkLQMVustbYHFPNsABu1Js6pEEWyMUFJQTqEZjVCU2WHh8ckcc7YA4uBzPiJjZCsv3pC1NDdV99AnyLzPjSip4uC3y' }); * await key.ready; * * const key = new Key({ ledgerPath: "44'/1729'/0'/1'" }); * await key.ready; */ export class Key { _curve: string; _publicKey: Uint8Array; _secretKey?: Uint8Array; _isSecret: boolean; _isLedger: boolean; _ledgerPath: string; _ledgerCurve: string; _ledgerTransport: any; _salt: Uint8Array; ready: Promise<boolean>; constructor({ key, passphrase, email, ledgerPath = "44'/1729'/0'/0'", ledgerCurve = 'tz1', ledgerTransport, }: { key?: string; passphrase?: string; email?: string; ledgerPath?: string; ledgerCurve?: string; ledgerTransport?: any; } = {}) { this._isLedger = !!ledgerTransport; this._ledgerPath = ledgerPath; this._ledgerCurve = ledgerCurve; this._ledgerTransport = ledgerTransport; this.ready = new Promise((resolve) => { this.initialize({ key, passphrase, email }, resolve); }); } get curve(): string { return this._curve; } get isLedger(): boolean { return this._isLedger; } set isLedger(value: boolean) { this._isLedger = value; } get ledgerPath(): string { return this._ledgerPath; } set ledgerPath(value: string) { this._ledgerPath = value; } get ledgerCurve(): string { return this._ledgerCurve; } set ledgerCurve(value: string) { this._ledgerCurve = value; } /** * @memberof Key * @description Returns the public key * @returns {string} The public key associated with the private key */ publicKey = (): string => b58cencode(this._publicKey, prefix[`${this._curve}pk`]); /** * @memberof Key * @description Returns the secret key * @param {string} [passphrase] The password used to encrypt the secret key, if applicable * @returns {string} The secret key associated with this key, if available */ secretKey = (passphrase?: string): string => { if (!this._secretKey) { throw new Error('Secret key not known.'); } let key = this._secretKey; if (passphrase) { if (this._curve === 'ed') { key = sodium.crypto_sign_ed25519_sk_to_seed(key, 'uint8array'); } const encryptionSalt = this._salt || sodium.randombytes_buf(8); const encryptionKey = pbkdf2.pbkdf2Sync( passphrase, encryptionSalt, 32768, 32, 'sha512', ); const encryptedSk = sodium.crypto_secretbox_easy( new Uint8Array(key), new Uint8Array(24), new Uint8Array(encryptionKey), ); key = mergebuf(encryptionSalt, encryptedSk); } return b58cencode(key, prefix[`${this._curve}${passphrase ? 'e' : ''}sk`]); }; /** * @memberof Key * @description Returns public key hash for this key * @returns {string} The public key hash for this key */ publicKeyHash = (): string => { const prefixMap: { [key: string]: Uint8Array } = { ed: prefix.tz1, sp: prefix.tz2, p2: prefix.tz3, }; return b58cencode( sodium.crypto_generichash(20, this._publicKey), prefixMap[this._curve], ); }; initialize = async ( { key, passphrase, email, }: { key?: string; passphrase?: string; email?: string }, setInit: (value: boolean) => void, ): Promise<void> => { await sodium.ready; if (this._isLedger || !key) { ({ publicKey: key } = await getAddress({ transport: this._ledgerTransport, path: this._ledgerPath, displayConfirm: true, curve: this._ledgerCurve, })); } if (email) { if (!passphrase) { throw new Error('Fundraiser key provided without a passphrase.'); } const salt = textDecode(textEncode(`${email}${passphrase}`)).normalize( 'NFKD', ); const seed = pbkdf2.pbkdf2Sync( key, `mnemonic${salt}`, 2048, 64, 'sha512', ); const { publicKey, privateKey } = sodium.crypto_sign_seed_keypair( new Uint8Array(seed.slice(0, 32)), ); this._publicKey = new Uint8Array(publicKey); this._secretKey = new Uint8Array(privateKey); this._curve = 'ed'; this._isSecret = true; setInit(true); return; } this._curve = key.substring(0, 2); if (!['sp', 'p2', 'ed'].includes(this._curve)) { throw new Error('Invalid prefix for a key encoding.'); } if (![54, 55, 88, 98].includes(key.length)) { throw new Error('Invalid length for a key encoding'); } const encrypted = key.substring(2, 3) === 'e'; const publicOrSecret = encrypted ? key.substring(3, 5) : key.substring(2, 4); if (!['pk', 'sk'].includes(publicOrSecret)) { throw new Error('Invalid prefix for a key encoding.'); } this._isSecret = publicOrSecret === 'sk'; let constructedKey: Uint8Array; if (this._isSecret) { constructedKey = b58cdecode( key, prefix[`${this._curve}${encrypted ? 'e' : ''}sk`], ); } else { constructedKey = b58cdecode(key, prefix[`${this._curve}pk`]); } if (encrypted) { if (!passphrase) { throw new Error('Encrypted key provided without a passphrase.'); } this._salt = constructedKey.slice(0, 8); const encryptedSk = constructedKey.slice(8); const encryptionKey = pbkdf2.pbkdf2Sync( passphrase, this._salt, 32768, 32, 'sha512', ); constructedKey = sodium.crypto_secretbox_open_easy( new Uint8Array(encryptedSk), new Uint8Array(24), new Uint8Array(encryptionKey), ); } if (!this._isSecret) { this._publicKey = new Uint8Array(constructedKey); this._secretKey = undefined; } else { this._secretKey = new Uint8Array(constructedKey); if (this._curve === 'ed') { if (constructedKey.length === 64) { // sk this._publicKey = new Uint8Array( sodium.crypto_sign_ed25519_sk_to_pk(this._secretKey), ); } else { // seed const { publicKey, privateKey } = sodium.crypto_sign_seed_keypair( constructedKey, 'uint8array', ); this._publicKey = new Uint8Array(publicKey); this._secretKey = new Uint8Array(privateKey); } } else if (this._curve === 'sp') { const keyPair = new elliptic.ec('secp256k1').keyFromPrivate( constructedKey, ); const prefixVal = keyPair.getPublic().getY().toArray()[31] % 2 ? 3 : 2; const pad = new Array(32).fill(0); this._publicKey = new Uint8Array( [prefixVal].concat( pad.concat(keyPair.getPublic().getX().toArray()).slice(-32), ), ); } else if (this._curve === 'p2') { const keyPair = new elliptic.ec('p256').keyFromPrivate(constructedKey); const prefixVal = keyPair.getPublic().getY().toArray()[31] % 2 ? 3 : 2; const pad = new Array(32).fill(0); this._publicKey = new Uint8Array( [prefixVal].concat( pad.concat(keyPair.getPublic().getX().toArray()).slice(-32), ), ); } else { throw new Error('Invalid key'); } } setInit(true); }; /** * @memberof Key * @description Sign a raw sequence of bytes * @param {string} bytes Sequence of bytes, raw format or hexadecimal notation * @param {Uint8Array} magicBytes The magic bytes for the operation * @returns {Promise} The signature object */ sign = async ( bytes: string, magicBytes?: Uint8Array, ): Promise<{ bytes: string; magicBytes: string; sig: string; prefixSig: string; sbytes: string; }> => { if (this._isLedger) { const signature = await signOperation({ transport: this._ledgerTransport, path: this._ledgerPath, rawTxHex: bytes, curve: this._ledgerCurve, magicBytes, }); const signatureBuffer = hex2buf(signature); const sbytes = bytes + signature; return { bytes, magicBytes: magicBytes ? buf2hex(magicBytes) : '', sig: b58cencode(signatureBuffer, prefix.sig), prefixSig: b58cencode(signatureBuffer, prefix[`${this._curve}sig`]), sbytes, }; } let bb = hex2buf(bytes); if (typeof magicBytes !== 'undefined') { bb = mergebuf(magicBytes, bb); } const bytesHash = sodium.crypto_generichash(32, bb); if (!this._secretKey) { throw new Error('Cannot sign operations without a secret key.'); } if (this._curve === 'ed') { const signature = sodium.crypto_sign_detached(bytesHash, this._secretKey); const sbytes = bytes + buf2hex(signature); return { bytes, magicBytes: magicBytes ? buf2hex(magicBytes) : '', sig: b58cencode(signature, prefix.sig), prefixSig: b58cencode(signature, prefix.edsig), sbytes, }; } if (this._curve === 'sp') { const key = new elliptic.ec('secp256k1').keyFromPrivate(this._secretKey); const sig = key.sign(bytesHash, { canonical: true }); const signature = new Uint8Array( sig.r.toArray(undefined, 32).concat(sig.s.toArray(undefined, 32)), ); const sbytes = bytes + buf2hex(signature); return { bytes, magicBytes: magicBytes ? buf2hex(magicBytes) : '', sig: b58cencode(signature, prefix.sig), prefixSig: b58cencode(signature, prefix.spsig), sbytes, }; } if (this._curve === 'p2') { const key = new elliptic.ec('p256').keyFromPrivate(this._secretKey); const sig = key.sign(bytesHash, { canonical: true }); const signature = new Uint8Array( sig.r.toArray(undefined, 32).concat(sig.s.toArray(undefined, 32)), ); const sbytes = bytes + buf2hex(signature); return { bytes, magicBytes: magicBytes ? buf2hex(magicBytes) : '', sig: b58cencode(signature, prefix.sig), prefixSig: b58cencode(signature, prefix.p2sig), sbytes, }; } throw new Error('Provided curve not supported'); }; /** * @memberof Key * @description Verify signature * @param {string} bytes Sequance of bytes, raw format or hexadecimal notation * @param {string} signature A signature in base58 encoding * @param {string} publicKey A public key * @returns {boolean} Whether the signature is valid */ verify = ( bytes: string, signature: string, publicKey: string = this.publicKey(), ): boolean => { if (!publicKey) { throw new Error('Cannot verify without a public key'); } const _curve = publicKey.substring(0, 2); const _publicKey = b58cdecode(publicKey, prefix[`${_curve}pk`]); if (signature.substring(0, 3) !== 'sig') { if (_curve !== signature.substring(0, 2)) { // 'sp', 'p2' 'ed' throw new Error('Signature and public key curves mismatch.'); } } const bytesBuffer = sodium.crypto_generichash(32, hex2buf(bytes)); let sig; if (signature.substring(0, 3) === 'sig') { sig = b58cdecode(signature, prefix.sig); } else if (signature.substring(0, 5) === `${_curve}sig`) { sig = b58cdecode(signature, prefix[`${_curve}sig`]); } else { throw new Error(`Invalid signature provided: ${signature}`); } if (_curve === 'ed') { try { return sodium.crypto_sign_verify_detached(sig, bytesBuffer, _publicKey); } catch (e) { return false; } } else if (_curve === 'sp') { const key = new elliptic.ec('secp256k1').keyFromPublic(_publicKey); const formattedSig = buf2hex(sig); const match = formattedSig.match(/([a-f\d]{64})/gi); if (match) { try { const [r, s] = match; return key.verify(bytesBuffer, { r, s }); } catch (e) { return false; } } return false; } else if (_curve === 'p2') { const key = new elliptic.ec('p256').keyFromPublic(_publicKey); const formattedSig = buf2hex(sig); const match = formattedSig.match(/([a-f\d]{64})/gi); if (match) { try { const [r, s] = match; return key.verify(bytesBuffer, { r, s }); } catch (e) { return false; } } return false; } else { throw new Error(`Curve '${_curve}' not supported`); } }; }
the_stack
import * as babel from "@babel/core"; import * as parser from "@babel/parser"; import traverse, { Node } from "@babel/traverse"; import { AssignmentExpression, Comment, Expression, ImportDeclaration, JSXAttribute, JSXElement, JSXEmptyExpression, JSXExpressionContainer, JSXFragment, JSXIdentifier, JSXNamespacedName, JSXSpreadAttribute, JSXSpreadChild, JSXText, ReturnStatement, } from "@babel/types"; import { diffChars } from "diff"; import * as L from "lodash"; import { cloneDeep } from "lodash"; import { cloneDeepWithHook } from "./cloneDeepWithHook"; import { assert, ensure, withoutNils } from "./common"; import { makeCallExpression, PlasmicASTNode, PlasmicTagOrComponent, wrapInJsxExprContainer, } from "./plasmic-ast"; import { CodeVersion, helperObject, isCallIgnoreArguments, isCallWithoutArguments, isJsxElementOrFragment, } from "./plasmic-parser"; import { code, formatted, isAttribute, nodesDeepEqualIgnoreComments, tagName, } from "./utils"; const mkJsxFragment = (children: JsxChildType[]) => { return babel.types.jsxFragment( babel.types.jsxOpeningFragment(), babel.types.jsxClosingFragment(), // Remove unnecessary {} children.map((child) => child.type === "JSXExpressionContainer" && child.expression.type === "JSXElement" ? child.expression : child ) ); }; const getRawNamedAttrs = (jsxElement: JSXElement) => { const attrs = new Map<string, JSXAttribute>(); for (const attr of jsxElement.openingElement.attributes) { if (attr.type !== "JSXAttribute") { continue; } assert(L.isString(attr.name.name)); attrs.set(attr.name.name, attr); } return attrs; }; const findParsedNamedAttrs = (node: PlasmicTagOrComponent, name: string) => { for (const attr of node.jsxElement.attrs) { if (!L.isArray(attr)) { continue; } if (attr[0] === name) { return attr[1]; } } return undefined; }; const mergedTag = ( newNode: PlasmicTagOrComponent, editedNode: PlasmicTagOrComponent, baseNode: PlasmicTagOrComponent ) => { const editedTag = editedNode.jsxElement.rawNode.openingElement.name; const newTag = newNode.jsxElement.rawNode.openingElement.name; const baseTagCode = tagName(baseNode.jsxElement.rawNode); const editedTagCode = tagName(editedNode.jsxElement.rawNode); if (baseTagCode === editedTagCode) { return newTag; } const newTagCode = tagName(newNode.jsxElement.rawNode); // User edited the tag. if (baseTagCode === newTagCode || editedTagCode === newTagCode) { return editedTag; } // Generate a bad tag identifier for user to resolve conflicts return babel.types.jsxIdentifier(`${editedTagCode}___${newTagCode}`); }; const wrapAsJsxAttrValue = ( rawValue: | Expression | JSXEmptyExpression | JSXExpressionContainer | JSXSpreadChild | JSXFragment | JSXText | undefined ) => { if (!rawValue) { return undefined; } if (rawValue.type === "JSXText" || rawValue.type === "JSXSpreadChild") { // Either newVersion or editedVersion was wrapped in a fragment. // We wrap too. mkJsxFragment([rawValue]); } else if ( babel.types.isExpression(rawValue) || babel.types.isJSXEmptyExpression(rawValue) ) { return babel.types.jsxExpressionContainer(rawValue); } else { return rawValue; } }; const mergeAttributeValue = ( attrName: string, newNode: PlasmicTagOrComponent, editedNode: PlasmicTagOrComponent, baseNode: PlasmicTagOrComponent, codeVersions: CodeVersions ) => { const parsedNewAttrValue = findParsedNamedAttrs(newNode, attrName); const parsedEditedAttrValue = findParsedNamedAttrs(editedNode, attrName); const parsedBaseAttrValue = findParsedNamedAttrs(baseNode, attrName); // These two must not be undefined (i.e. not found) assert(parsedNewAttrValue !== undefined); assert(parsedEditedAttrValue !== undefined); let mergedAttrValue: | Expression | JSXEmptyExpression | JSXExpressionContainer | JSXSpreadChild | JSXFragment | JSXText | undefined = undefined; if (!parsedNewAttrValue) { if (parsedEditedAttrValue) { mergedAttrValue = serializePlasmicASTNode( parsedEditedAttrValue, codeVersions ); } else { mergedAttrValue = undefined; } } else { if (!parsedEditedAttrValue) { mergedAttrValue = serializePlasmicASTNode( parsedNewAttrValue, codeVersions ); } else { // do merge, really! const asArray = (node: PlasmicASTNode | null | undefined) => !node ? [] : node.type === "jsx-fragment" ? node.children : [node]; const mergedNodes = mergeNodes( asArray(parsedNewAttrValue), asArray(parsedEditedAttrValue), asArray(parsedBaseAttrValue), codeVersions ); // If edited forced wrapping single node with JSXFragment, so do we // if the result is a single element. const editedForcedFragment = parsedEditedAttrValue.type === "jsx-fragment" && parsedEditedAttrValue.children.length === 1; mergedAttrValue = mergedNodes.length > 1 ? mkJsxFragment(mergedNodes) : mergedNodes.length === 1 ? editedForcedFragment ? mkJsxFragment(mergedNodes) : mergedNodes[0] : babel.types.jsxEmptyExpression(); } } return wrapAsJsxAttrValue(mergedAttrValue); }; const serializeNamedAttribute = ( attrName: JSXIdentifier | JSXNamespacedName, rawValue: PlasmicASTNode | null | undefined, codeVersions: CodeVersions ) => { const attrValue = rawValue ? serializePlasmicASTNode(rawValue, codeVersions) : undefined; return babel.types.jsxAttribute(attrName, wrapAsJsxAttrValue(attrValue)); }; const serializeJsxSpreadAttribute = ( editedAttr: PlasmicASTNode, newNodeHasPropsWithIdSpreador: boolean, nodeId: string, codeVersions: CodeVersions ) => { if ( !newNodeHasPropsWithIdSpreador && isCallWithoutArguments(editedAttr.rawNode, helperObject, `props${nodeId}`) ) { // delete the id spreador, if deleted from new version return undefined; } const attrValue = serializePlasmicASTNode(editedAttr, codeVersions); if (!attrValue || attrValue.type === "JSXEmptyExpression") { return undefined; } assert(attrValue.type !== "JSXText"); assert(attrValue.type !== "JSXSpreadChild"); if (babel.types.isExpression(attrValue)) { return babel.types.jsxSpreadAttribute(attrValue); } else if (attrValue.type === "JSXExpressionContainer") { return attrValue.expression.type === "JSXEmptyExpression" ? undefined : babel.types.jsxSpreadAttribute(attrValue.expression); } }; const mergeAttributes = ( newNode: PlasmicTagOrComponent, editedNode: PlasmicTagOrComponent, baseNode: PlasmicTagOrComponent, codeVersions: CodeVersions ) => { const { newVersion, editedVersion } = codeVersions; assert(editedNode.jsxElement.nameInId === newNode.jsxElement.nameInId); assert(editedNode.jsxElement.nameInId === baseNode.jsxElement.nameInId); const newNodePropsWithIdSpreador = newVersion.tryGetPropsIdSpreador(newNode); const editedHasPropsWithIdSpreador = editedVersion.hasPropsIdSpreador( editedNode ); const newNamedAttrs = getRawNamedAttrs(newNode.jsxElement.rawNode); const editedNamedAttrs = getRawNamedAttrs(editedNode.jsxElement.rawNode); const baseNamedAttrs = getRawNamedAttrs(baseNode.jsxElement.rawNode); const conflictResolution = ( name: string, baseAttr: JSXAttribute | undefined, editedAttr: JSXAttribute, newAttr: JSXAttribute ) => { // If attribute match, then emit either version is ok. Emitting it at the // place where the edited version emitted at is probably safer, and less // disturbing. if (nodesDeepEqualIgnoreComments(editedAttr, newAttr)) { return "emit-edited"; } if (!baseAttr) { // We don't know how to handle the conflict. Merge them and let developer // handle it. return "emit-merged"; } if (nodesDeepEqualIgnoreComments(baseAttr, editedAttr)) { // User didn't edit it. Emit the new version. return "emit-new"; } if ( name.startsWith("on") || (name === "value" && tagName(newNode.jsxElement.rawNode) === "PlasmicSlot") || nodesDeepEqualIgnoreComments(baseAttr, newAttr) ) { // Plasmic doesn't change it. Emit the edited version then. return "emit-edited"; } // Both Plasmic and developer edited it. Emit both. return "emit-merged"; }; const emitAttrInEditedNode = (attrName: string) => { const editedAttr = ensure(editedNamedAttrs.get(attrName)); const newAttr = newNamedAttrs.get(attrName); const baseAttr = baseNamedAttrs.get(attrName); if (newAttr) { const res = conflictResolution(attrName, baseAttr, editedAttr, newAttr); if (res === "emit-new") { // We emit the newAttr in place to minimize diff. return newAttr; } else if (res === "emit-merged") { const value = mergeAttributeValue( attrName, newNode, editedNode, baseNode, codeVersions ); return babel.types.jsxAttribute(newAttr.name, value); } assert(res === "emit-edited"); return editedAttr; } else if (!baseAttr) { // user added attribute in edited version. Emit the edited attribute // without any transformation. return serializeNamedAttribute( editedAttr.name, findParsedNamedAttrs(editedNode, attrName), codeVersions ); } else { // Attribute deleted in new version. However, user may have modified it. // Delete it only if there is no modification; otherwise, keep it for user // to fix the compilation failure. return nodesDeepEqualIgnoreComments(baseAttr, editedAttr) ? undefined : serializeNamedAttribute( editedAttr.name, findParsedNamedAttrs(editedNode, attrName), codeVersions ); } }; const mergedAttrs: Array<JSXAttribute | JSXSpreadAttribute> = []; newNamedAttrs.forEach((attr, name) => { const editedAttr = editedNamedAttrs.get(name); const baseAttr = baseNamedAttrs.get(name); if (!baseAttr && !editedAttr) { // newly added attribute in new version mergedAttrs.push( serializeNamedAttribute( attr.name, findParsedNamedAttrs(newNode, name), codeVersions ) ); } }); for (const attrInEditedNode of editedNode.jsxElement.attrs) { if (L.isArray(attrInEditedNode)) { const toEmit = emitAttrInEditedNode(attrInEditedNode[0]); if (toEmit) { mergedAttrs.push(toEmit); } } else { const serializedSpreador = serializeJsxSpreadAttribute( attrInEditedNode, !!newNodePropsWithIdSpreador, newNode.jsxElement.nameInId, codeVersions ); if (serializedSpreador) { mergedAttrs.push(serializedSpreador); } } } let classNameAt = mergedAttrs.findIndex((attr) => isAttribute(attr, "className") ); // insert className if missing in edited version, mostly to support old code. if (classNameAt === -1) { const newClassNameAttr = newNamedAttrs.get("className"); if (newClassNameAttr) { mergedAttrs.splice(0, 0, newClassNameAttr); classNameAt = 0; } } if (newNodePropsWithIdSpreador && !editedHasPropsWithIdSpreador) { // insert the new spreador right after className if any, always const insertSpreadorAt = classNameAt === -1 ? 0 : classNameAt + 1; mergedAttrs.splice(insertSpreadorAt, 0, newNodePropsWithIdSpreador); } return mergedAttrs; }; type JsxChildType = | JSXText | JSXExpressionContainer | JSXSpreadChild | JSXElement | JSXFragment; interface PerfectMatch { type: "perfect"; index: number; } interface TypeMatch { type: "type"; index: number; } interface NoMatch { type: "none"; } type MatchResult = PerfectMatch | TypeMatch | NoMatch; const computeDiff = (s1: string, s2: string) => { return L.sum(diffChars(s1, s2).map((part) => part.value.length)); }; const findMatch = ( nodes: PlasmicASTNode[], start: number, n: PlasmicASTNode ): MatchResult => { let matchingTypeAt = -1; if (n.type === "text" || n.type === "string-lit") { for (let i = start; i < nodes.length; i++) { const ni = nodes[i]; let lastDiff = 0; if (ni.type === "text" || ni.type === "string-lit") { if (ni.value === n.value) { return { type: "perfect", index: i }; } const diff = computeDiff(n.value, ni.value); // Find the best match, i.e. the one with least diff. if (matchingTypeAt === -1 || diff < lastDiff) { matchingTypeAt = i; lastDiff = diff; } } } } else if (n.type === "child-str-call") { for (let i = start; i < nodes.length; i++) { const ni = nodes[i]; if (ni.type === "child-str-call") { return { type: "perfect", index: i }; } if ( matchingTypeAt === -1 && (ni.type === "text" || ni.type === "string-lit") ) { matchingTypeAt = i; } } } else if (n.type === "tag-or-component") { for (let i = start; i < nodes.length; i++) { const ni = nodes[i]; if ( ni.type === "tag-or-component" && ni.jsxElement.nameInId === n.jsxElement.nameInId ) { return { type: "perfect", index: i }; } if (matchingTypeAt === -1 && ni.type === "tag-or-component") { matchingTypeAt = i; } } } return matchingTypeAt !== -1 ? { type: "type", index: matchingTypeAt } : { type: "none" }; }; const mergeNodes = ( newNodes: PlasmicASTNode[], editedNodes: PlasmicASTNode[], baseNodes: PlasmicASTNode[], codeVersions: CodeVersions ) => { let nextInsertStartAt = 0; const insertEditedNode = ( editedChild: PlasmicASTNode, prevEditedChild: PlasmicASTNode | undefined ) => { if (!prevEditedChild) { merged.splice(0, 0, editedChild); nextInsertStartAt = 1; } else { const prevMatch = findMatch(merged, nextInsertStartAt, prevEditedChild); if (prevMatch.type === "perfect" || prevMatch.type === "type") { // previous node matches merged[prevMatch]. insert current node at // prevMatch + 1. merged.splice(prevMatch.index + 1, 0, editedChild); nextInsertStartAt = prevMatch.index + 2; } else { merged.splice(nextInsertStartAt, 0, editedChild); nextInsertStartAt += 1; } } }; // remove tag node from new nodes list when there is no perfect match. const merged = newNodes.filter((newNode) => { if (newNode.type === "tag-or-component") { const matchInEditedVersion = findMatch(editedNodes, 0, newNode); const matchInBaseVersion = findMatch(baseNodes, 0, newNode); if ( matchInBaseVersion.type === "perfect" && matchInEditedVersion.type !== "perfect" ) { return false; } } return true; }); editedNodes.forEach((editedChild, i) => { if ( editedChild.type === "text" || editedChild.type === "string-lit" || editedChild.type === "child-str-call" ) { const matchInNewVersion = findMatch( merged, nextInsertStartAt, editedChild ); if (matchInNewVersion.type === "perfect") { // skip text node if it matches some text in new version. But make sure // subsequent nodes are inserted after the match. nextInsertStartAt = matchInNewVersion.index + 1; return; } const matchInBaseVersion = findMatch(baseNodes, 0, editedChild); if (matchInBaseVersion.type === "perfect") { // skip text node if it matches some text in base version return; } if (matchInBaseVersion.type === "type") { const matchInMergedVersion = findMatch( merged, nextInsertStartAt, baseNodes[matchInBaseVersion.index] ); if (matchInMergedVersion.type === "perfect") { // If base and new/merged version has a perfect match, then replace new version // with the edited version. merged.splice(matchInMergedVersion.index, 1, editedChild); return; } } insertEditedNode(editedChild, editedNodes[i - 1]); } else if (editedChild.type === "opaque") { insertEditedNode(editedChild, editedNodes[i - 1]); } // We intentially don't preserve PlasmicTagOrComponent nodes that are moved // from other places here (note that if the nodes were here before, then // merged should already contain that node). The reason is that it is easy // to do so in Plasmic, and that it enforces the consistency between Plasmic // studio and code. }); return withoutNils( merged.map((c) => { if (c.type === "opaque") { return c.rawNode as JsxChildType; } // Note that, if c is PlasmicTagOrComponent, it must come from newNodes. const n = serializeNonOpaquePlasmicASTNode(c, codeVersions); if (!n) { return undefined; } if (babel.types.isExpression(n)) { // need to wrap in expression container return n.type !== "JSXElement" && n.type !== "JSXFragment" ? babel.types.jsxExpressionContainer(n) : n; } return n; }) ); }; const mergedChildren = ( newNode: PlasmicTagOrComponent, editedNode: PlasmicTagOrComponent, baseNode: PlasmicTagOrComponent, codeVersions: CodeVersions ): Array<JsxChildType> => { return mergeNodes( newNode.jsxElement.children, editedNode.jsxElement.children, baseNode.jsxElement.children, codeVersions ); }; const makeJsxElementWithShowCall = (jsxElement: JSXElement, nodeId: string) => babel.types.logicalExpression( "&&", makeCallExpression(helperObject, `show${nodeId}`), jsxElement ); const serializeTagOrComponent = ( newNode: PlasmicTagOrComponent, codeVersions: CodeVersions ): Expression | JSXExpressionContainer | undefined => { const { newVersion, editedVersion, baseVersion } = codeVersions; // find node with same id in edited version. const editedNode = editedVersion.findTagOrComponent( newNode.jsxElement.nameInId ); const baseNode = baseVersion.findTagOrComponent(newNode.jsxElement.nameInId); if (editedNode) { // the node must exist in base version. assert(!!baseNode); const editedNodeJsxElementClone = babel.types.cloneDeep( editedNode.jsxElement.rawNode ); editedNodeJsxElementClone.openingElement.name = mergedTag( newNode, editedNode, baseNode ); if (editedNodeJsxElementClone.closingElement) { editedNodeJsxElementClone.closingElement.name = editedNodeJsxElementClone.openingElement.name; } editedNodeJsxElementClone.openingElement.attributes = mergeAttributes( newNode, editedNode, baseNode, codeVersions ); editedNodeJsxElementClone.children = mergedChildren( newNode, editedNode, baseNode, codeVersions ); if ( !editedNodeJsxElementClone.closingElement && editedNodeJsxElementClone.children.length > 0 ) { editedNodeJsxElementClone.closingElement = babel.types.jsxClosingElement( editedNodeJsxElementClone.openingElement.name ); editedNodeJsxElementClone.openingElement.selfClosing = false; } const secondaryNodes = new Map<Node, Node | undefined>( editedNode.secondaryNodes.map((n) => { const newSecondaryNode = newVersion.findTagOrComponent( n.jsxElement.nameInId ); if (!newSecondaryNode) { return [n.rawNode, undefined]; } const rawReplacement = serializePlasmicASTNode( newSecondaryNode, codeVersions ); return [n.rawNode, rawReplacement]; }) ); const newNodeCallShowFunc = newVersion.hasShowFuncCall(newNode); const editedNodeCallShowFunc = editedVersion.hasShowFuncCall(editedNode); const editedNodeClone = cloneDeepWithHook(editedNode.rawNode, (n: Node) => { if (n === editedNode.jsxElement.rawNode) { if (newNodeCallShowFunc && !editedNodeCallShowFunc) { // add the show call const expr = makeJsxElementWithShowCall( editedNodeJsxElementClone, editedNode.jsxElement.nameInId ); // add an expression container if the parent is JSXElement or Fragment return editedNode.jsxElement.rawParent && isJsxElementOrFragment(editedNode.jsxElement.rawParent) ? wrapInJsxExprContainer(expr) : expr; } return editedNodeJsxElementClone; } if (secondaryNodes.has(n)) { const replacement = secondaryNodes.get(n); // If deleted, an empty fragment instead return replacement || mkJsxFragment([]); } return undefined; }); if (editedNodeCallShowFunc && !newNodeCallShowFunc) { traverse(editedNodeClone, { noScope: true, CallExpression: function (path) { if ( isCallIgnoreArguments( path.node, helperObject, `show${editedNode.jsxElement.nameInId}` ) ) { path.replaceWithSourceString("true"); } }, }); } return editedNodeClone; } // check if the node has been deleted. if (baseNode) { // If so, don't output anything return undefined; } // This is new node. Just output self. const childrenReplacement = new Map<Node, Node>(); newNode.jsxElement.children.forEach((child) => { // Plasmic never emit opaque node. assert(child.type !== "opaque"); const childReplacement = serializeNonOpaquePlasmicASTNode( child, codeVersions ); if (childReplacement) { if (babel.types.isExpression(childReplacement)) { // need to wrap in expression container const maybeWrapped = childReplacement.type !== "JSXElement" && childReplacement.type !== "JSXFragment" ? babel.types.jsxExpressionContainer(childReplacement) : childReplacement; childrenReplacement.set(child.rawNode, maybeWrapped); } else { childrenReplacement.set(child.rawNode, childReplacement); } } }); // Attribute replacement const attrsReplacement = new Map<Node, Node>(); newNode.jsxElement.attrs.forEach((attr) => { if (L.isArray(attr)) { const [key, value] = attr; // className is an opaque attribute! if (value && value.type !== "opaque") { const attrReplacement = serializeNonOpaquePlasmicASTNode( value, codeVersions ); if (attrReplacement) { if (attrReplacement.type !== "JSXExpressionContainer") { assert(attrReplacement.type !== "JSXText"); attrsReplacement.set( value.rawNode, babel.types.jsxExpressionContainer(attrReplacement) ); } else { attrsReplacement.set(value.rawNode, attrReplacement); } } } } }); return cloneDeepWithHook( newNode.rawNode, (n: Node) => childrenReplacement.get(n) || attrsReplacement.get(n) ); }; const serializeNonOpaquePlasmicASTNode = ( newNode: PlasmicASTNode, codeVersions: CodeVersions ): Expression | JSXExpressionContainer | JSXText | JSXFragment | undefined => { assert(newNode.type !== "opaque"); if (newNode.type === "child-str-call") { // Just output the new version return newNode.rawNode; } else if (newNode.type === "string-lit") { // Just output the new version return newNode.rawNode; } else if (newNode.type === "text") { // Just output the new version return newNode.rawNode; } else if (newNode.type === "jsx-fragment") { return babel.types.jsxFragment( babel.types.jsxOpeningFragment(), babel.types.jsxClosingFragment(), withoutNils( newNode.children.map((child) => { const newRawNode = serializePlasmicASTNode(child, codeVersions); if (!newRawNode) { return undefined; } if ( babel.types.isExpression(newRawNode) || babel.types.isJSXEmptyExpression(newRawNode) ) { return babel.types.jsxExpressionContainer(newRawNode); } return newRawNode; }) ) ); } else { assert(newNode.type === "tag-or-component"); return serializeTagOrComponent(newNode, codeVersions); } }; interface CodeVersions { newVersion: CodeVersion; editedVersion: CodeVersion; baseVersion: CodeVersion; } const serializePlasmicASTNode = ( newNode: PlasmicASTNode, codeVersions: CodeVersions ): | Expression | JSXEmptyExpression | JSXExpressionContainer | JSXSpreadChild | JSXFragment | JSXText | undefined => { if (newNode.type === "opaque") { return newNode.rawNode; } return serializeNonOpaquePlasmicASTNode(newNode, codeVersions); }; export const renameAndSerializePlasmicASTNode = ( newNode: PlasmicASTNode, codeVersions: CodeVersions ): | Expression | JSXEmptyExpression | JSXExpressionContainer | JSXSpreadChild | JSXFragment | JSXText | undefined => { if (newNode.type === "opaque") { return newNode.rawNode; } return serializeNonOpaquePlasmicASTNode(newNode, { baseVersion: codeVersions.baseVersion.renameJsxTree( codeVersions.newVersion ), editedVersion: codeVersions.editedVersion.renameJsxTree( codeVersions.newVersion ), newVersion: codeVersions.newVersion, }); }; export class ComponentSkeletonModel { constructor( readonly uuid: string, readonly nameInIdToUuid: Map<string, string>, readonly fileContent: string ) {} toJSON() { return { uuid: this.uuid, nameInIdToUuid: [...this.nameInIdToUuid.entries()], fileContent: this.fileContent, }; } static fromJsObject(jsObj: any) { return new ComponentSkeletonModel( jsObj.uuid, new Map<string, string>(jsObj.nameInIdToUuid as Array<[string, string]>), jsObj.fileContent ); } } export class ProjectSyncMetadataModel { constructor(readonly components: ComponentSkeletonModel[]) {} toJSON() { return this.components; } static fromJson(json: string) { const j = JSON.parse(json); assert(L.isArray(j)); return new ProjectSyncMetadataModel( j.map((item) => ComponentSkeletonModel.fromJsObject(item)) ); } } export const makeCachedProjectSyncDataProvider = ( rawProvider: ProjectSyncDataProviderType ): ProjectSyncDataProviderType => { type Entry = { projectId: string; revision: number; model: ProjectSyncMetadataModel; }; const cache: Array<Entry> = []; return async (projectId: string, revision: number) => { const cached = cache.find( (ent) => ent.projectId === projectId && ent.revision === revision ); if (cached) { return cached.model; } const model = await rawProvider(projectId, revision); cache.push({ projectId, revision, model }); return model; }; }; export type ProjectSyncDataProviderType = ( projectId: string, revision: number ) => Promise<ProjectSyncMetadataModel>; interface PlasmicComponentSkeletonFile { jsx: Expression; file: babel.types.File; revision: number; identifyingComment: Comment; } interface VersionedJsx { jsx: Expression; revision: number; identifyingComment: Comment; } const tryExtractPlasmicJsxExpression = ( node: AssignmentExpression | ReturnStatement ): VersionedJsx | undefined => { for (const c of node.leadingComments || []) { const m = c.value.match(/^\s*plasmic-managed-jsx\/(\d+)\s*$/); if (m) { if (node.type === "AssignmentExpression") { return { jsx: node.right, identifyingComment: c, revision: +m[1] }; } else { return { jsx: ensure(node.argument), identifyingComment: c, revision: +m[1], }; } } } return undefined; }; const tryParseComponentSkeletonFile = ( fileContent: string ): PlasmicComponentSkeletonFile | undefined => { const file = parser.parse(fileContent, { strictMode: true, sourceType: "module", plugins: ["jsx", "typescript"], }); let jsx: VersionedJsx | undefined = undefined; traverse(file, { noScope: true, AssignmentExpression: function (path) { jsx = tryExtractPlasmicJsxExpression(path.node); if (jsx) { path.stop(); } }, ReturnStatement: function (path) { jsx = tryExtractPlasmicJsxExpression(path.node); if (jsx) { path.stop(); } }, }); // typescript treat jsx as never type... why? jsx = jsx as VersionedJsx | undefined; return jsx ? { ...jsx, file } : undefined; }; // merge slave into master const mergeImports = ( editedImport: ImportDeclaration, newImport: ImportDeclaration ) => { if ( editedImport.specifiers.find((s) => s.type === "ImportNamespaceSpecifier") ) { return cloneDeep(editedImport); } if (newImport.specifiers.find((s) => s.type === "ImportNamespaceSpecifier")) { return cloneDeep(newImport); } const cloned = cloneDeep(editedImport); for (const s2 of newImport.specifiers) { if (s2.type === "ImportDefaultSpecifier") { if ( editedImport.specifiers.find( (s1) => s1.type === "ImportDefaultSpecifier" && s1.local.name === s2.local.name ) ) { continue; } cloned.specifiers.push(s2); } else if (s2.type === "ImportSpecifier") { if ( editedImport.specifiers.find( (s1) => s1.type === "ImportSpecifier" && s1.local.name === s2.local.name && importedName(s1) === importedName(s2) ) ) { continue; } cloned.specifiers.push(s2); } else { assert(s2.type === "ImportNamespaceSpecifier"); // Plasmic doesn't generate namespace import statement. cloned.specifiers.push(s2); } } return cloned; }; function importedName(stmt: babel.types.ImportSpecifier) { if (stmt.imported.type === "Identifier") { return stmt.imported.name; } else { return stmt.imported.value; } } const mergePlasmicImports = ( mergedFile: babel.types.File, parsedNew: PlasmicComponentSkeletonFile, parsedEdited: PlasmicComponentSkeletonFile ) => { const newImports = parsedNew.file.program.body.filter( (stmt) => stmt.type === "ImportDeclaration" ) as ImportDeclaration[]; const editedImports = parsedEdited.file.program.body.filter( (stmt) => stmt.type === "ImportDeclaration" ) as ImportDeclaration[]; const firstImport = mergedFile.program.body.findIndex( (stmt) => stmt.type === "ImportDeclaration" ); mergedFile.program.body = mergedFile.program.body.filter( (stmt) => stmt.type !== "ImportDeclaration" ); const mergedImports: Array<ImportDeclaration> = []; for (const editedImport of editedImports) { const newImportAt = newImports.findIndex( (newImport) => editedImport.source.value === newImport.source.value ); if (newImportAt !== -1) { const newImport = newImports[newImportAt]; newImports.splice(newImportAt, 1); mergedImports.push(mergeImports(editedImport, newImport)); } else { mergedImports.push(editedImport); } } mergedImports.push(...newImports); const insertMergedImportsAt = firstImport > -1 ? firstImport : 0; mergedFile.program.body.splice(insertMergedImportsAt, 0, ...mergedImports); }; export type ComponentInfoForMerge = { // edited version of the code, i.e. the entire file. editedFile: string; newFile: string; // map for newCode newNameInIdToUuid: Map<string, string>; }; export class WarningInfo { private _rawWarnings: string[] = []; private _secondaryNodes: PlasmicTagOrComponent[] = []; addRawWarn(msg: string) { this._rawWarnings.push(msg); } setSecondaryNodes(nodes: PlasmicTagOrComponent[]) { this._secondaryNodes.push(...nodes); } rawWarnings() { return this._rawWarnings; } secondaryNodes() { return this._secondaryNodes; } maybeWarn() { this._rawWarnings.forEach((m) => console.warn(m)); if (this._secondaryNodes.length > 0) { const nodes = this._secondaryNodes .map((n) => n.jsxElement.nameInId) .join("\n\t"); console.warn( `Plasmic perform limited merge to the following nodes since they are secondary nodes.\n${nodes}` ); } } } export const mergeFiles = async ( componentByUuid: Map<string, ComponentInfoForMerge>, projectId: string, projectSyncDataProvider: ProjectSyncDataProviderType, preMergeFile?: ( compId: string, baseSrc: string, baseNameInIdToUuid: Map<string, string>, newSrc: string, newNameInIdToUuid: Map<string, string> ) => void, appendJsxTreeOnMissingBase?: boolean, // Output parameter, which is used to collect warning information warningInfos?: Map<string, WarningInfo> ) => { const updateableByComponentUuid = new Map< string, PlasmicComponentSkeletonFile >(); componentByUuid.forEach((codeVersions, uuid) => { const parsedEdited = tryParseComponentSkeletonFile(codeVersions.editedFile); if (parsedEdited) { updateableByComponentUuid.set(uuid, parsedEdited); } }); if (updateableByComponentUuid.size === 0) { // Nothing to update return undefined; } const mergedFiles = new Map<string, string>(); for (const [componentUuid, parsedEdited] of updateableByComponentUuid) { const warnInfo = new WarningInfo(); warningInfos?.set(componentUuid, warnInfo); let baseMetadata: ComponentSkeletonModel | undefined = undefined; try { const projectSyncData = await projectSyncDataProvider( projectId, parsedEdited.revision ); baseMetadata = projectSyncData.components.find( (c) => c.uuid === componentUuid ); } catch { warnInfo.addRawWarn( `missing merging base for ${projectId} at revision ${parsedEdited.revision}` ); } const component = ensure(componentByUuid.get(componentUuid)); const parsedNew = ensure(tryParseComponentSkeletonFile(component.newFile)); if (!baseMetadata) { if (appendJsxTreeOnMissingBase) { mergedFiles.set( componentUuid, formatted(`${component.editedFile} // Please perform merge with the following JSX manually. \`// plasmic-managed-jsx/${parsedNew.revision} return (${code(parsedNew.jsx).trimEnd()});\``) ); continue; } else { throw new Error( `Cannot perform three way merge due to missing base version. For Plasmic CLI users, please add '--append-jsx-on-missing-base' so that you can perform merging by yourselves.` ); } } if (preMergeFile) { preMergeFile( componentUuid, baseMetadata.fileContent, baseMetadata.nameInIdToUuid, component.newFile, component.newNameInIdToUuid ); } const parsedBase = ensure( tryParseComponentSkeletonFile(baseMetadata.fileContent) ); const newCodeVersion = new CodeVersion( parsedNew.jsx, component.newNameInIdToUuid ); const baseCodeVersion = new CodeVersion( parsedBase.jsx, baseMetadata.nameInIdToUuid ); // All other metadata const editedCodeVersion = new CodeVersion( parsedEdited.jsx, // edited version share the same nameInIdtoUuid mapping baseMetadata.nameInIdToUuid ); warnInfo.setSecondaryNodes([ ...editedCodeVersion.secondaryTagsOrComponents.values(), ]); const newJsx = renameAndSerializePlasmicASTNode(newCodeVersion.root, { newVersion: newCodeVersion, editedVersion: editedCodeVersion, baseVersion: baseCodeVersion, }); // Ideally, we should keep parsedEdited read-only, but, it is not a big deal // to modify the comment. parsedEdited.identifyingComment.value = ` plasmic-managed-jsx/${parsedNew.revision}`; const mergedFile = cloneDeepWithHook(parsedEdited.file, (n: Node) => { if (n === parsedEdited.jsx) { return newJsx; } return undefined; }); mergePlasmicImports(mergedFile, parsedNew, parsedEdited); const mergedCode = code(mergedFile, { retainLines: true }); mergedFiles.set(componentUuid, formatted(mergedCode)); } return mergedFiles; };
the_stack
import moment from 'moment'; import get from 'lodash/get'; import type { SelectProps, CheckboxProps } from 'antd'; import { Form, Checkbox, DatePicker, Select, Input } from 'antd'; import { scheduleConfigLayout, SCHEDULE_STATUS, TASK_PERIOD_ENUM } from '@/constant'; import type { IScheduleConfProps } from '@/interface'; import { forwardRef } from 'react'; import { useImperativeHandle } from 'react'; const { Option } = Select; const FormItem = Form.Item; interface IFormWrapProps { scheduleConf: Partial<IScheduleConfProps>; status: SCHEDULE_STATUS; /** * 是否为数据科学任务 */ isScienceTask?: boolean; /** * 是否为 workflow root */ isWorkflowRoot?: boolean; isWorkflowNode?: boolean; /** * 调度配置发生修改的回调函数 */ handleScheduleConf: () => void; /** * 调度状态项发生修改的回调函数 */ handleScheduleStatus: CheckboxProps['onChange']; /** * 调度周期发生修改的回调函数 */ handleScheduleType: SelectProps<string>['onChange']; } /** * 小时默认下拉选项,0 -> 23 */ const HOURS_OPTIONS = new Array(24) .fill(1) .map((_, i) => ({ label: i < 10 ? `0${i}` : i.toString(), value: i.toString() })); /** * 分钟默认下拉选择, 00 -> 59 */ const MINS_OPTIONS = new Array(60) .fill(1) .map((_, i) => ({ label: i < 10 ? `0${i}` : i.toString(), value: i.toString() })); /** * 分钟间隔默认下拉。5分钟,10分钟..., 55分钟 */ const GAP_OPTIONS = new Array(11).fill(1).map((_, i) => ({ label: `${(i + 1) * 5}分钟`, value: ((i + 1) * 5).toString(), })); /** * 小时间隔默认下拉,1小时,2小时...,23小时 */ const GAP_HOUR_OPTIONS = new Array(24).fill(1).map((_, i) => ({ label: `${i + 1}小时`, value: (i + 1).toString(), })); /** * 星期默认下拉选项 */ const WEEKS_OPTIONS = ['天', '一', '二', '三', '四', '五', '六'].map((day, index) => ({ label: `星期${day}`, value: (index + 1).toString(), })); /** * 日默认下拉选项,1 -> 30 */ const DAYS_OPTIONS = new Array(30).fill(1).map((_, i) => ({ label: `每月${i + 1}号`, value: (i + 1).toString(), })); /** * 重试次数下拉选项,1 -> 5 */ const RETRY_OPTIONS = new Array(5).fill(1).map((_, i) => ({ label: i + 1, value: (i + 1).toString(), })); export default forwardRef( ( { scheduleConf, status, isScienceTask, isWorkflowRoot, isWorkflowNode, handleScheduleStatus, handleScheduleConf, handleScheduleType, }: IFormWrapProps, ref, ) => { const [form] = Form.useForm(); const { periodType, beginDate, beginHour, beginMin, endHour, endMin, endDate, // isLastInstance, gapMin, weekDay, hour, min, day, gapHour, } = scheduleConf; useImperativeHandle(ref, () => ({ ...form, })); const changeStartDisabledDate = (currentDate: moment.Moment) => { const date = form.getFieldValue('endDate'); return date && currentDate.valueOf() > date; }; const changeEndDisabledDate = (currentDate: moment.Moment) => { const date = form.getFieldValue('beginDate'); return date && currentDate.valueOf() < date; }; const checkTimeS1 = () => { const currentBeginHour = +form.getFieldValue('beginHour'); const currentBeginMin = +form.getFieldValue('beginMin'); const currentEndHour = +form.getFieldValue('endHour') * 60 + 59; if (currentBeginHour * 60 + currentBeginMin > currentEndHour) { return Promise.reject(new Error('开始时间不能晚于结束时间')); } return Promise.resolve(); }; const checkTimeE1 = () => { const currentBeginHour = +form.getFieldValue('beginHour'); const currentBeginMin = +form.getFieldValue('beginMin'); const currentEndHour = +form.getFieldValue('endHour') * 60 + 59; if (currentBeginHour * 60 + currentBeginMin > currentEndHour) { return Promise.reject(new Error('结束时间不能早于开始时间')); } return Promise.resolve(); }; const renderTimeConfig = (type: number) => { switch (type) { case TASK_PERIOD_ENUM.MINUTE: { return ( <span key={type}> <FormItem {...scheduleConfigLayout} label="开始时间" required> <FormItem noStyle name="beginHour" rules={[ { required: true, }, { validator: checkTimeS1, }, ]} initialValue={`${beginHour}`} > <Select style={{ width: '40%' }} onChange={handleScheduleConf} options={HOURS_OPTIONS} /> </FormItem> <span className="mx-5px">时</span> <FormItem noStyle name="beginMin" rules={[ { required: true, }, { validator: checkTimeS1, }, ]} initialValue={`${beginMin || '0'}`} > <Select style={{ width: '40%' }} onChange={handleScheduleConf} options={MINS_OPTIONS} /> </FormItem> <span className="ml-5px">分</span> </FormItem> <FormItem {...scheduleConfigLayout} label="间隔时间" name="gapMin" rules={[ { required: true, }, ]} initialValue={`${gapMin}`} > <Select disabled={isScienceTask} onChange={handleScheduleConf} options={GAP_OPTIONS} /> </FormItem> <FormItem {...scheduleConfigLayout} label="结束时间" required> <FormItem noStyle name="endHour" rules={[ { required: true, }, { validator: checkTimeE1, }, ]} initialValue={`${endHour}`} > <Select style={{ width: '40%' }} onChange={handleScheduleConf} options={HOURS_OPTIONS} /> </FormItem> <span className="mx-5px">时</span> <FormItem noStyle name="endMin" rules={[ { required: true, }, { validator: checkTimeE1, }, ]} initialValue={`${endMin || '59'}`} > <Select style={{ width: '40%' }} onChange={handleScheduleConf} options={MINS_OPTIONS} /> </FormItem> <span className="ml-5px">分</span> </FormItem> </span> ); } case TASK_PERIOD_ENUM.HOUR: { return ( <span key={type}> <FormItem {...scheduleConfigLayout} label="开始时间" required> <FormItem noStyle name="beginHour" rules={[ { required: true, }, { validator: checkTimeS1, }, ]} initialValue={`${beginHour}`} > <Select style={{ width: '40%' }} onChange={handleScheduleConf} options={HOURS_OPTIONS} /> </FormItem> <span className="mx-5px">时</span> <FormItem noStyle name="beginMin" rules={[ { required: true, }, { validator: checkTimeS1, }, ]} initialValue={`${beginMin || '0'}`} > <Select style={{ width: '40%' }} onChange={handleScheduleConf} options={MINS_OPTIONS} /> </FormItem> <span className="ml-5px">分</span> </FormItem> <FormItem {...scheduleConfigLayout} label="间隔时间" name="gapHour" rules={[ { required: true, }, ]} initialValue={`${gapHour}`} > <Select onChange={handleScheduleConf} options={GAP_HOUR_OPTIONS} /> </FormItem> <FormItem {...scheduleConfigLayout} label="结束时间" required> <FormItem noStyle name="endHour" rules={[ { required: true, }, { validator: checkTimeE1, }, ]} initialValue={`${endHour}`} > <Select style={{ width: '40%' }} onChange={handleScheduleConf} options={HOURS_OPTIONS} /> </FormItem> <span className="mx-5px">时</span> <FormItem noStyle name="endMin" rules={[ { required: true, }, { validator: checkTimeE1, }, ]} initialValue={`${endMin || '59'}`} > <Select style={{ width: '40%' }} onChange={handleScheduleConf} options={MINS_OPTIONS} /> </FormItem> <span className="ml-5px">分</span> </FormItem> </span> ); } case TASK_PERIOD_ENUM.DAY: { const prefix = isWorkflowNode ? '起调' : '具体'; return ( <span key={type}> <FormItem {...scheduleConfigLayout} label={`${prefix}时间`} required> <FormItem noStyle name="hour" rules={[ { required: true, }, ]} initialValue={`${hour}`} > <Select style={{ width: '40%' }} onChange={handleScheduleConf} options={HOURS_OPTIONS} /> </FormItem> <span className="mx-5px">时</span> <FormItem noStyle name="min" rules={[ { required: true, }, ]} initialValue={`${min}`} > <Select style={{ width: '40%' }} onChange={handleScheduleConf} options={MINS_OPTIONS} /> </FormItem> <span className="ml-5px">分</span> </FormItem> </span> ); } case TASK_PERIOD_ENUM.WEEK: { return ( <span key={type}> <FormItem {...scheduleConfigLayout} label="选择时间" name="weekDay" rules={[ { required: true, }, ]} initialValue={`${weekDay}`.split(',')} > <Select mode="multiple" style={{ width: '100%' }} disabled={isScienceTask} onChange={handleScheduleConf} options={WEEKS_OPTIONS} /> </FormItem> <FormItem {...scheduleConfigLayout} label="具体时间" required> <FormItem noStyle name="hour" rules={[ { required: true, }, ]} initialValue={`${hour}`} > <Select style={{ width: '40%' }} onChange={handleScheduleConf} options={HOURS_OPTIONS} /> </FormItem> <span className="mx-5px">时</span> <FormItem noStyle name="min" rules={[ { required: true, }, ]} initialValue={`${min}`} > <Select style={{ width: '40%' }} onChange={handleScheduleConf} options={MINS_OPTIONS} /> </FormItem> <span className="ml-5px">分</span> </FormItem> </span> ); } case TASK_PERIOD_ENUM.MONTH: { return ( <span key={type}> <FormItem {...scheduleConfigLayout} label="选择时间" name="day" rules={[ { required: true, }, ]} initialValue={`${day}`.split(',')} > <Select mode="multiple" style={{ width: '100%' }} disabled={isScienceTask} onChange={handleScheduleConf} options={DAYS_OPTIONS} /> </FormItem> <FormItem {...scheduleConfigLayout} label="具体时间" required> <FormItem noStyle name="hour" rules={[ { required: true, }, ]} initialValue={`${hour}`} > <Select style={{ width: '40%' }} onChange={handleScheduleConf} options={HOURS_OPTIONS} /> </FormItem> <span className="mx-5px">时</span> <FormItem noStyle name="min" rules={[ { required: true, }, ]} initialValue={`${min}`} > <Select style={{ width: '40%' }} onChange={handleScheduleConf} options={MINS_OPTIONS} /> </FormItem> <span className="ml-5px">分</span> </FormItem> </span> ); } default: return <span>something wrong</span>; } }; return ( <Form form={form} className="schedule-form" initialValues={{ scheduleStatus: status === SCHEDULE_STATUS.FORZON || status === SCHEDULE_STATUS.STOPPED, selfReliance: scheduleConf.selfReliance, }} > <FormItem {...scheduleConfigLayout} label="调度状态" name="scheduleStatus" valuePropName="checked" > <Checkbox disabled={isScienceTask} onChange={handleScheduleStatus}> 冻结 </Checkbox> </FormItem> {!isWorkflowRoot && ( <> <FormItem {...scheduleConfigLayout} label="出错重试" name="isFailRetry" initialValue={get(scheduleConf, 'isFailRetry')} valuePropName="checked" > <Checkbox disabled={isScienceTask} onChange={handleScheduleConf}> 是 </Checkbox> </FormItem> <FormItem noStyle dependencies={['isFailRetry']}> {({ getFieldValue }) => getFieldValue('isFailRetry') && ( <FormItem {...scheduleConfigLayout} label="重试次数" required> <FormItem noStyle name="maxRetryNum" rules={[ { required: true, message: '请选择重试次数', }, ]} initialValue={get(scheduleConf, 'maxRetryNum', 3)} > <Select style={{ display: 'inline-block', width: 70, }} disabled={isScienceTask} onChange={handleScheduleConf} options={RETRY_OPTIONS} /> </FormItem> <span className="ml-5px">次,每次间隔2分钟</span> </FormItem> ) } </FormItem> </> )} {!isWorkflowNode && ( <div> <FormItem {...scheduleConfigLayout} label="生效日期" required> <FormItem name="beginDate" noStyle initialValue={moment(beginDate)} rules={[ { required: true, message: '请选择生效日期开始时间', }, ]} > <DatePicker allowClear={false} disabledDate={changeStartDisabledDate} disabled={isScienceTask} style={{ width: 115 }} onChange={handleScheduleConf} /> </FormItem> <span className="mx-5px">-</span> <FormItem noStyle name="endDate" initialValue={moment(endDate)} rules={[ { required: true, message: '请选择生效日期结束时间', }, ]} > <DatePicker allowClear={false} disabled={isScienceTask} disabledDate={changeEndDisabledDate} style={{ width: 115 }} onChange={handleScheduleConf} /> </FormItem> </FormItem> <FormItem {...scheduleConfigLayout} label="调度周期" name="periodType" initialValue={`${periodType}`} rules={[ { required: true, }, ]} > <Select disabled={isScienceTask} onChange={handleScheduleType}> <Option key={0} value={TASK_PERIOD_ENUM.MINUTE.toString()}> 分钟 </Option> <Option key={1} value={TASK_PERIOD_ENUM.HOUR.toString()}> 小时 </Option> <Option key={2} value={TASK_PERIOD_ENUM.DAY.toString()}> 天 </Option> <Option key={3} value={TASK_PERIOD_ENUM.WEEK.toString()}> 周 </Option> <Option key={4} value={TASK_PERIOD_ENUM.MONTH.toString()}> 月 </Option> </Select> </FormItem> </div> )} <FormItem noStyle name="selfReliance"> <Input disabled={isScienceTask} type="hidden" /> </FormItem> <FormItem dependencies={['periodType']} noStyle> {({ getFieldValue }) => renderTimeConfig(Number(getFieldValue('periodType')))} </FormItem> {/* <FormItem noStyle dependencies={['periodType']}> {({ getFieldValue }) => // 调度周期为小时或者分钟 [ TASK_PERIOD_ENUM.MINUTE.toString(), TASK_PERIOD_ENUM.HOUR.toString(), ].includes(getFieldValue('periodType').toString()) && ( <FormItem {...scheduleConfigLayout} label="延迟实例"> <FormItem noStyle name="isExpire" valuePropName="checked" initialValue={get(scheduleConf, 'isExpire')} > <Checkbox onChange={handleScheduleConf}>自动取消</Checkbox> </FormItem> <HelpDoc doc="autoSkipJobHelp" /> </FormItem> ) } </FormItem> */} {/* <FormItem noStyle dependencies={['isExpire']}> {({ getFieldValue }) => getFieldValue('isExpire') && ( <FormItem {...scheduleConfigLayout} label="当天最后实例"> <FormItem noStyle name="isLastInstance" initialValue={isLastInstance ?? true} > <Group onChange={handleScheduleConf}> <Radio value={true}>始终保留</Radio> <Radio value={false}>延迟至第二天后自动取消</Radio> </Group> </FormItem> <HelpDoc doc="theLastExample" /> </FormItem> ) } </FormItem> */} </Form> ); }, );
the_stack
import React, { useEffect, useState } from 'react' import { Screen } from '@island.is/web/types' import { withMainLayout } from '@island.is/web/layouts/main' import { SubpageLayout } from '@island.is/web/screens/Layouts/Layouts' import SidebarLayout from '@island.is/web/screens/Layouts/SidebarLayout' import { Text, Stack, Breadcrumbs, Box, Button, GridContainer, LoadingIcon, Navigation, Link, } from '@island.is/island-ui/core' import { ServiceList, SubpageDetailsContent, SubpageMainContent, RichText, ApiCatalogueFilter, } from '@island.is/web/components' import getConfig from 'next/config' import { CustomNextError } from '@island.is/web/units/errors' import { ContentLanguage, GetNamespaceQuery, QueryGetNamespaceArgs, GetSubpageHeaderQuery, QueryGetSubpageHeaderArgs, } from '@island.is/web/graphql/schema' import { Query, QueryGetApiCatalogueArgs, GetApiCatalogueInput, } from '@island.is/api/schema' import { Slice as SliceType } from '@island.is/island-ui/contentful' import { GET_CATALOGUE_QUERY, GET_NAMESPACE_QUERY, GET_SUBPAGE_HEADER_QUERY, } from '../queries' import { useNamespace } from '@island.is/web/hooks' import { useI18n } from '@island.is/web/i18n' import { useQuery } from '@apollo/client' import { AccessCategory, DataCategory, PricingCategory, TypeCategory, } from '@island.is/api-catalogue/consts' import { useLinkResolver } from '@island.is/web/hooks/useLinkResolver' const { publicRuntimeConfig } = getConfig() const LIMIT = 20 /* TEMPORARY LAYOUT CREATED TO SCAFFOLD API CATALOGUE INTO THE WEB */ interface ApiCatalogueProps { subpageHeader: GetSubpageHeaderQuery['getSubpageHeader'] staticContent: GetNamespaceQuery['getNamespace'] filterContent: GetNamespaceQuery['getNamespace'] navigationLinks: GetNamespaceQuery['getNamespace'] } const ApiCatalogue: Screen<ApiCatalogueProps> = ({ subpageHeader, staticContent, filterContent, navigationLinks, }) => { /* DISABLE FROM WEB WHILE WIP */ const { disableApiCatalog: disablePage } = publicRuntimeConfig if (disablePage === 'true') { throw new CustomNextError(404, 'Not found') } /* --- */ const { activeLocale } = useI18n() const sn = useNamespace(staticContent) const fn = useNamespace(filterContent) const nn = useNamespace(navigationLinks) const { linkResolver } = useLinkResolver() const onLoadMore = () => { if (data?.getApiCatalogue.pageInfo?.nextCursor === null) { return } const { nextCursor } = data?.getApiCatalogue?.pageInfo const param = { ...parameters, cursor: nextCursor } fetchMore({ variables: { input: param }, updateQuery: (prevResult, { fetchMoreResult }) => { fetchMoreResult.getApiCatalogue.services = [ ...prevResult.getApiCatalogue.services, ...fetchMoreResult.getApiCatalogue.services, ] return fetchMoreResult }, }) } const [parameters, setParameters] = useState<GetApiCatalogueInput>({ cursor: null, limit: LIMIT, query: '', pricing: [], data: [], type: [], access: [], }) const { data, loading, error, fetchMore, refetch } = useQuery< Query, QueryGetApiCatalogueArgs >(GET_CATALOGUE_QUERY, { variables: { input: parameters, }, }) useEffect(() => { refetch() }, [parameters]) const filterCategories = [ { id: 'pricing', label: fn('pricing'), selected: parameters.pricing, filters: [ { value: PricingCategory.FREE, label: fn('pricingFree'), }, { value: PricingCategory.PAID, label: fn('pricingPaid'), }, ], }, { id: 'data', label: fn('data'), selected: parameters.data, filters: [ { value: DataCategory.FINANCIAL, label: fn('dataFinancial'), }, { value: DataCategory.HEALTH, label: fn('dataHealth'), }, { value: DataCategory.OFFICIAL, label: fn('dataOfficial'), }, { value: DataCategory.OPEN, label: fn('dataOpen'), }, { value: DataCategory.PERSONAL, label: fn('dataPersonal'), }, { value: DataCategory.PUBLIC, label: fn('dataPublic'), }, ], }, { id: 'type', label: fn('type'), selected: parameters.type, filters: [ { value: TypeCategory.REST, label: fn('typeRest'), }, { value: TypeCategory.SOAP, label: fn('typeSoap'), }, ], }, { id: 'access', label: fn('access'), selected: parameters.access, filters: [ { value: AccessCategory.APIGW, label: fn('accessApigw'), }, { value: AccessCategory.XROAD, label: fn('accessXroad'), }, ], }, ] const navigationItems = [ { active: true, href: linkResolver('webservicespage').href, title: nn('linkServicesText'), }, { href: linkResolver('handbookpage').href, title: nn('linkHandbookNavText'), }, { href: nn('linkIslandUI'), title: nn('linkIslandUIText'), }, { href: nn('linkDesignSystem'), title: nn('linkDesignSystemText'), }, ] return ( <SubpageLayout main={ <SidebarLayout paddingTop={[0, 0, 9]} paddingBottom={[4, 4, 12]} sidebarContent={ <Navigation baseId="service-list-navigation" colorScheme="blue" items={navigationItems} title={nn('linkThrounText')} titleLink={{ href: linkResolver('developerspage').href, }} /> } > <SubpageMainContent main={ <Box> <Box display={['inline', 'inline', 'none']}> {/* Show when a device */} <Box paddingBottom={3}> <Button colorScheme="default" preTextIcon="arrowBack" size="small" variant="text" > <Link {...linkResolver('developerspage')}> {nn('linkThrounText')} </Link> </Button> </Box> <Box marginBottom={3}> <Navigation baseId="service-list-navigation" colorScheme="blue" isMenuDialog items={navigationItems} title={nn('linkThrounText')} titleLink={{ href: linkResolver('developerspage').href, }} /> </Box> </Box> <Box marginBottom={2} display={['none', 'none', 'inline']}> {/* Show when NOT a device */} <Breadcrumbs items={[ { title: nn('linkIslandIsText'), href: linkResolver('homepage').href, }, { title: nn('linkThrounText'), href: linkResolver('developerspage').href, }, ]} /> </Box> <Stack space={1}> <Text variant="h1">{subpageHeader.title}</Text> <Text variant="intro">{subpageHeader.summary}</Text> <Stack space={2}> {subpageHeader.body ? ( <RichText body={subpageHeader.body as SliceType[]} config={{ defaultPadding: [2, 2, 4] }} locale={activeLocale} /> ) : null} </Stack> </Stack> </Box> } image={ <Box width="full" height="full" display="flex" alignItems="center" > <img src={subpageHeader.featuredImage.url} alt={subpageHeader.featuredImage.title} width={subpageHeader.featuredImage.width} height={subpageHeader.featuredImage.height} /> </Box> } /> </SidebarLayout> } details={ <SubpageDetailsContent header={ <Text variant="h4" color="blue600"> {sn('title')} </Text> } content={ <SidebarLayout paddingTop={[3, 3, 5]} paddingBottom={[0, 0, 6]} sidebarContent={ <Box paddingRight={[0, 0, 3]}> <ApiCatalogueFilter labelClear={fn('clear')} labelOpen={fn('openFilterButton')} labelClose={fn('closeFilter')} labelResult={fn('mobileResult')} labelTitle={fn('mobileTitle')} resultCount={data?.getApiCatalogue?.services?.length ?? 0} onFilterClear={() => setParameters({ query: '', pricing: [], data: [], type: [], access: [], }) } inputPlaceholder={fn('search')} inputValue={parameters.query} onInputChange={(value) => setParameters({ ...parameters, query: value }) } labelCategoryClear={fn('clearCategory')} onCategoryChange={({ categoryId, selected }) => { setParameters({ ...parameters, [categoryId]: selected, }) }} onCategoryClear={(categoryId) => setParameters({ ...parameters, [categoryId]: [], }) } categories={filterCategories} /> </Box> } > <Box display={['block', 'block', 'none']} paddingBottom={4}> {/* <ApiCatalogueFilter isDialog={true} /> */} <ApiCatalogueFilter isDialog={true} labelClear={fn('clear')} labelOpen={fn('openFilterButton')} labelClose={fn('closeFilter')} labelResult={fn('mobileResult')} labelTitle={fn('mobileTitle')} resultCount={data?.getApiCatalogue?.services?.length ?? 0} onFilterClear={() => setParameters({ query: '', pricing: [], data: [], type: [], access: [], }) } inputPlaceholder={fn('search')} inputValue={parameters.query} onInputChange={(value) => setParameters({ ...parameters, query: value }) } labelCategoryClear={fn('clearCategory')} onCategoryChange={({ categoryId, selected }) => { setParameters({ ...parameters, [categoryId]: selected, }) }} onCategoryClear={(categoryId) => setParameters({ ...parameters, [categoryId]: [], }) } categories={filterCategories} /> </Box> {(error || data?.getApiCatalogue?.services.length < 1) && ( <GridContainer> {error ? ( <Text>{sn('errorHeading')}</Text> ) : loading ? ( <LoadingIcon animate color="blue400" size={32} /> ) : ( <Text>{sn('notFound')}</Text> )} </GridContainer> )} {data?.getApiCatalogue?.services.length > 0 && ( <GridContainer> <ServiceList baseUrl={linkResolver('webservicespage').href + '/'} services={data?.getApiCatalogue?.services} tagDisplayNames={filterContent} /> {data?.getApiCatalogue?.pageInfo?.nextCursor != null && ( <Box display="flex" justifyContent="center"> <Button onClick={() => onLoadMore()} variant="ghost"> {!loading ? ( sn('fmButton') ) : ( <LoadingIcon animate color="blue400" size={16} /> )} </Button> </Box> )} </GridContainer> )} </SidebarLayout> } /> } /> ) } ApiCatalogue.getInitialProps = async ({ apolloClient, locale, query }) => { const [ { data: { getSubpageHeader: subpageHeader }, }, staticContent, filterContent, navigationLinks, ] = await Promise.all([ apolloClient.query<GetSubpageHeaderQuery, QueryGetSubpageHeaderArgs>({ query: GET_SUBPAGE_HEADER_QUERY, variables: { input: { lang: locale as ContentLanguage, id: 'VefthjonusturHome', }, }, }), apolloClient .query<GetNamespaceQuery, QueryGetNamespaceArgs>({ query: GET_NAMESPACE_QUERY, variables: { input: { namespace: 'ApiCatalog', lang: locale as ContentLanguage, }, }, }) .then((res) => JSON.parse(res.data.getNamespace.fields)), apolloClient .query<GetNamespaceQuery, QueryGetNamespaceArgs>({ query: GET_NAMESPACE_QUERY, variables: { input: { namespace: 'ApiCatalogFilter', lang: locale as ContentLanguage, }, }, }) .then((res) => JSON.parse(res.data.getNamespace.fields)), apolloClient .query<GetNamespaceQuery, QueryGetNamespaceArgs>({ query: GET_NAMESPACE_QUERY, variables: { input: { namespace: 'ApiCatalogueLinks', lang: locale as ContentLanguage, }, }, }) .then((res) => JSON.parse(res.data.getNamespace.fields)), ]) return { subpageHeader, staticContent, filterContent, navigationLinks, } } export default withMainLayout(ApiCatalogue)
the_stack
import * as DiscoveryEntryWithMetaInfo from "../../generated/joynr/types/DiscoveryEntryWithMetaInfo"; import * as MessagingQos from "../messaging/MessagingQos"; import { OneWayRequest } from "./types/OneWayRequest"; import * as Reply from "./types/Reply"; import * as Request from "./types/Request"; import * as Typing from "../util/Typing"; import * as UtilInternal from "../util/UtilInternal"; import * as JSONSerializer from "../util/JSONSerializer"; import MethodInvocationException from "../exceptions/MethodInvocationException"; import ProviderRuntimeException from "../exceptions/ProviderRuntimeException"; import Version from "../../generated/joynr/types/Version"; import LoggingManager from "../system/LoggingManager"; import util from "util"; import Dispatcher = require("./Dispatcher"); import JoynrException = require("../exceptions/JoynrException"); const CLEANUP_CYCLE_INTERVAL = 1000; const log = LoggingManager.getLogger("joynr.dispatching.RequestReplyManager"); type ReplyCallback = (replySettings: any, reply: Reply.Reply) => void; type PromisifyCallback = (error: any, success?: any) => void; interface ReplyCaller { callback: PromisifyCallback; callbackSettings: any; expiresAt?: number; } class RequestReplyManager { private dispatcher: Dispatcher; /** * @name RequestReplyManager#sendRequest * @function * * @param settings * @param settings.from participantId of the sender * @param settings.toDiscoveryEntry DiscoveryEntry of the receiver * @param settings.messagingQos quality-of-service parameters such as time-to-live * @param settings.request the Request to send * @param callbackSettings additional settings to handle the reply. * @returns the Promise for the Request */ public sendRequest: ( settings: { from: string; toDiscoveryEntry: DiscoveryEntryWithMetaInfo; messagingQos: MessagingQos; request: Request.Request; }, callbackSettings: Record<string, any> ) => Promise<{ response: any[]; settings: { outputParameter: { name: string; type: string }[] }; }>; private cleanupInterval: NodeJS.Timer; private started: boolean = true; private replyCallers: Map<string, ReplyCaller>; private providers: Record<string, any> = {}; /** * The RequestReplyManager is responsible maintaining a list of providers that wish to * receive incoming requests, and also a list of requestReplyIds which is used to match * an incoming message with an expected reply. * * @constructor * * @param dispatcher */ public constructor(dispatcher: Dispatcher) { this.replyCallers = new Map(); this.cleanupInterval = setInterval(() => { const currentTime = Date.now(); for (const [id, caller] of this.replyCallers) { // eslint-disable-next-line @typescript-eslint/no-non-null-assertion if (caller.expiresAt! <= currentTime) { caller.callback(new Error(`Request with id "${id}" failed: ttl expired`)); this.replyCallers.delete(id); } } }, CLEANUP_CYCLE_INTERVAL); this.sendRequestInternal = this.sendRequestInternal.bind(this); this.sendRequest = util.promisify<any, any, any>(this.sendRequestInternal); this.dispatcher = dispatcher; } private checkIfReady(): void { if (!this.started) { throw new Error("RequestReplyManager is already shut down"); } } private sendRequestInternal( settings: { from: string; toDiscoveryEntry: DiscoveryEntryWithMetaInfo; messagingQos: MessagingQos; request: Request.Request; }, callbackSettings: Record<string, any>, callback: (error: any, success?: any) => void ): void { try { this.checkIfReady(); } catch (e) { callback(e); return; } this.addReplyCaller( settings.request.requestReplyId, { callback, callbackSettings }, settings.messagingQos.ttl ); this.dispatcher.sendRequest(settings); } private createReplyFromError( exception: JoynrException, requestReplyId: string, handleReplyCallback: ReplyCallback, replySettings: any ): void { const reply = Reply.create({ error: exception, requestReplyId }); return handleReplyCallback(replySettings, reply); } /** * @param settings * @param settings.from participantId of the sender * @param settings.toDiscoveryEntry DiscoveryEntry of the receiver * @param settings.messagingQos quality-of-service parameters such as time-to-live * @param settings.request the Request to send * @returns the Promise for the Request */ public sendOneWayRequest(settings: { from: string; toDiscoveryEntry: DiscoveryEntryWithMetaInfo; messagingQos: MessagingQos; request: OneWayRequest; }): Promise<any> { this.checkIfReady(); return this.dispatcher.sendOneWayRequest(settings); } /** * The function addRequestCaller is called when a provider wishes to receive * incoming requests for the given participantId * * @param participantId of the provider receiving the incoming requests * @param provider */ public addRequestCaller(participantId: string, provider: Record<string, any>): void { this.checkIfReady(); this.providers[participantId] = provider; } /** * The function addReplyCaller is called when a proxy get/set or rpc is called and * is waiting for a reply The reply caller is automatically * removed when the ttl expires. * * @param requestReplyId * @param replyCaller * @param ttlMs relative number of milliseconds to wait for the reply. * The replycaller will be removed in ttl_ms and and Error will be passed * to the replyCaller */ public addReplyCaller(requestReplyId: string, replyCaller: ReplyCaller, ttlMs: number): void { this.checkIfReady(); replyCaller.expiresAt = Date.now() + ttlMs; this.replyCallers.set(requestReplyId, replyCaller); } /** * The function removeRequestCaller is called when a provider no longer wishes to * receive incoming requests * * @param participantId */ public removeRequestCaller(participantId: string): void { this.checkIfReady(); try { delete this.providers[participantId]; } catch (error) { log.error(`error removing provider with participantId: ${participantId} error: ${error}`); } } /** * @param providerParticipantId * @param request * @param handleReplyCallback callback for handling the reply * @param replySettings settings for handleReplyCallback to avoid unnecessary function object creation * @returns */ public async handleRequest( providerParticipantId: string, request: Request.Request, handleReplyCallback: ReplyCallback, replySettings: Record<string, any> ): Promise<void> { let exception; try { this.checkIfReady(); } catch (error) { exception = new MethodInvocationException({ detailMessage: `error handling request: ${JSONSerializer.stringify( request )} for providerParticipantId ${providerParticipantId}. Joynr runtime already shut down.` }); return this.createReplyFromError(exception, request.requestReplyId, handleReplyCallback, replySettings); } const provider = this.providers[providerParticipantId]; if (!provider) { // TODO error handling request // TODO what if no provider is found in the mean time? // Do we need to add a task to handleRequest later? exception = new MethodInvocationException({ detailMessage: `error handling request: ${JSONSerializer.stringify( request )} for providerParticipantId ${providerParticipantId}` }); return this.createReplyFromError(exception, request.requestReplyId, handleReplyCallback, replySettings); } // if there's an operation available to call let result; if (provider[request.methodName] && provider[request.methodName].callOperation) { // may throw an immediate exception when callOperation checks the // arguments, in this case exception must be caught. // If final customer provided method implementation gets called, // that one may return either promise (preferred) or direct result // and may possibly also throw exception in the latter case. try { result = await provider[request.methodName].callOperation(request.params, request.paramDatatypes); } catch (internalException) { exception = internalException; } // otherwise, check whether request is an attribute get, set or an operation } else { const match = request.methodName.match(/([gs]et)?(\w+)/) as RegExpMatchArray; const getSet = match[1]; if (getSet) { const attributeName = match[2]; const attributeObject = provider[attributeName] || provider[UtilInternal.firstLower(attributeName)]; // if the attribute exists in the provider if (attributeObject && !attributeObject.callOperation) { try { if (getSet === "get") { result = await attributeObject.get(); } else if (getSet === "set") { // eslint-disable-next-line @typescript-eslint/no-non-null-assertion result = await attributeObject.set(request.params![0]); } } catch (internalGetterSetterException) { if (internalGetterSetterException instanceof ProviderRuntimeException) { exception = internalGetterSetterException; } else { exception = new ProviderRuntimeException({ detailMessage: `getter/setter method of attribute ${attributeName} reported an error ${internalGetterSetterException}` }); } } } else { // if neither an operation nor an attribute exists in the // provider => deliver MethodInvocationException exception = new MethodInvocationException({ detailMessage: `Could not find an operation "${ request.methodName }" or an attribute "${attributeName}" in the provider`, providerVersion: new Version({ majorVersion: provider.constructor.MAJOR_VERSION, minorVersion: provider.constructor.MINOR_VERSION }) }); } } else { // if no operation was found and methodName didn't start with "get" // or "set" => deliver MethodInvocationException exception = new MethodInvocationException({ detailMessage: `Could not find an operation "${request.methodName}" in the provider`, providerVersion: new Version({ majorVersion: provider.constructor.MAJOR_VERSION, minorVersion: provider.constructor.MINOR_VERSION }) }); } } /* both ProviderOperation.callOperation and ProviderAttribute.get/set have have asynchronous API. Therefore the result is always a promise and thus it's possible to await for its result. */ if (exception) { return this.createReplyFromError(exception, request.requestReplyId, handleReplyCallback, replySettings); } const reply = Reply.create({ response: result, requestReplyId: request.requestReplyId }); return handleReplyCallback(replySettings, reply); } /** * @param providerParticipantId * @param request */ public handleOneWayRequest(providerParticipantId: string, request: OneWayRequest): void { this.checkIfReady(); const provider = this.providers[providerParticipantId]; if (!provider) { throw new MethodInvocationException({ detailMessage: `error handling one-way request: ${JSONSerializer.stringify( request )} for providerParticipantId ${providerParticipantId}` }); } // if there's an operation available to call if (provider[request.methodName] && provider[request.methodName].callOperation) { // If final customer provided method implementation gets called, // that one may return either promise (preferred) or direct result // and may possibly also throw exception in the latter case. provider[request.methodName].callOperation(request.params, request.paramDatatypes); } else { throw new MethodInvocationException({ detailMessage: `Could not find an operation "${request.methodName}" in the provider`, providerVersion: new Version({ majorVersion: provider.constructor.MAJOR_VERSION, minorVersion: provider.constructor.MINOR_VERSION }) }); } } /** * @param reply */ public handleReply(reply: Reply.Reply): void { const replyCaller = this.replyCallers.get(reply.requestReplyId); if (replyCaller === undefined) { log.error( `error handling reply resolve, because replyCaller could not be found: ${JSONSerializer.stringify( reply )}` ); return; } try { if (reply.error) { log.info(`RequestReplyManager::handleReply got reply with exception ${util.inspect(reply.error)}`); if (reply.error instanceof Error) { replyCaller.callback(reply.error); } else { replyCaller.callback(Typing.augmentTypes(reply.error)); } } else { replyCaller.callback(undefined, { response: reply.response, settings: replyCaller.callbackSettings }); } this.replyCallers.delete(reply.requestReplyId); } catch (e) { log.error(`exception thrown during handling reply ${JSONSerializer.stringify(reply)}:\n${e.stack}`); } } /** * Shutdown the request reply manager */ public shutdown(): void { clearInterval(this.cleanupInterval); for (const replyCaller of this.replyCallers.values()) { if (replyCaller) { replyCaller.callback(new Error("RequestReplyManager is already shut down")); } } this.replyCallers.clear(); this.started = false; } } export = RequestReplyManager;
the_stack
import * as appInsights from "applicationinsights"; import * as assert from "assert"; import * as fs from "fs"; import * as mocha from "mocha"; import * as os from "os"; import * as defaults from "../src/defaults"; import * as officeAddinUsageData from "../src/usageData"; import * as jsonData from "../src/usageDataSettings"; let addInUsageData: officeAddinUsageData.OfficeAddinUsageData; const err = new Error(`this error contains a file path:C:/${os.homedir()}/AppData/Roaming/npm/node_modules//alanced-match/index.js`); const errWithBackslash = new Error(`this error contains a file path:C:\\Users\\admin\\AppData\\Local\Temp\\excel file .xlsx`); let usageData: string; const usageDataObject: officeAddinUsageData.IUsageDataOptions = { groupName: "office-addin-usage-data", projectName: "office-addin-usage-data", instrumentationKey: defaults.instrumentationKeyForOfficeAddinCLITools, promptQuestion: "-----------------------------------------\nDo you want to opt-in for usage data?[y/n]\n-----------------------------------------", raisePrompt: false, usageDataLevel: officeAddinUsageData.UsageDataLevel.on, method: officeAddinUsageData.UsageDataReportingMethod.applicationInsights, isForTesting: true, }; describe("Test office-addin-usage data-package", function() { this.beforeAll(function() { try { if (fs.existsSync(defaults.usageDataJsonFilePath) && fs.readFileSync(defaults.usageDataJsonFilePath, "utf8").toString() !== undefined) { usageData = JSON.parse(fs.readFileSync(defaults.usageDataJsonFilePath, "utf8").toString()); } } catch { usageData = undefined; } }); this.afterAll(function() { if (fs.existsSync(defaults.usageDataJsonFilePath) && usageData !== undefined) { fs.writeFileSync(defaults.usageDataJsonFilePath, JSON.stringify((usageData), null, 2)); } else if (fs.existsSync(defaults.usageDataJsonFilePath)) { fs.unlinkSync(defaults.usageDataJsonFilePath); } }); beforeEach(function() { if (fs.existsSync(defaults.usageDataJsonFilePath)) { fs.unlinkSync(defaults.usageDataJsonFilePath); } addInUsageData = new officeAddinUsageData.OfficeAddinUsageData(usageDataObject); addInUsageData.setUsageDataOn(); }); describe("Test constructor with minimal options", () => { it("Should successfully construct an OfficeAddInUsageData instance", () => { assert.doesNotThrow(() => { let testAddInUsageData = new officeAddinUsageData.OfficeAddinUsageData({ isForTesting: true, usageDataLevel: officeAddinUsageData.UsageDataLevel.off, projectName: "office-addin-usage-data", groupName: "TestGroupName", instrumentationKey: defaults.instrumentationKeyForOfficeAddinCLITools }); }); }); }); describe("Test reportEvent method", () => { it("should track event of object passed in with a project name", () => { const testEvent = { Test1: [true, 100], ScriptType: ["JavaScript", 1], }; addInUsageData.reportEvent("office-addin-usage-data", testEvent); assert.equal(addInUsageData.getEventsSent(), 1); }); }); describe("Test reportError method", () => { it("should send usage data exception", () => { addInUsageData.reportError("ReportErrorCheck", err); assert.equal(addInUsageData.getExceptionsSent(), 1); }); }); describe("Test promptForUsageData method", () => { it("Should return 'true' because usageDataJsonFilePath doesn't exist", () => { // delete officeAddinUsageData.json if (fs.existsSync(defaults.usageDataJsonFilePath)) { fs.unlinkSync(defaults.usageDataJsonFilePath); } assert.equal(jsonData.needToPromptForUsageData(usageDataObject.groupName), true); }); }); describe("Test promptForUsageData method", () => { it("Should return 'false' because usageDataJsonFilePath exists and groupName exists in file", () => { jsonData.writeUsageDataJsonData(usageDataObject.groupName, usageDataObject.usageDataLevel); assert.equal(jsonData.needToPromptForUsageData(usageDataObject.groupName), false); }); }); describe("Test promptForUsageData method", () => { it("Should return 'true' because usageDataJsonFilePath exists but groupName doesn't exist on file", () => { jsonData.writeUsageDataJsonData(usageDataObject.groupName, usageDataObject.usageDataLevel); assert.equal(jsonData.needToPromptForUsageData("test group name"), true); }); }); describe("Test usageDataOptIn method", () => { it("Should write out file with groupName set to true to usageDataJsonFilePath", () => { addInUsageData.usageDataOptIn(usageDataObject.isForTesting, "y"); const jsonTelemtryData = jsonData.readUsageDataJsonData(); assert.equal(jsonTelemtryData.usageDataInstances[usageDataObject.groupName].usageDataLevel, usageDataObject.usageDataLevel); }); }); describe("Test setUsageDataOff method", () => { it("should change samplingPercentage to 100, turns usage data on", () => { addInUsageData.setUsageDataOn(); addInUsageData.setUsageDataOff(); assert.equal(addInUsageData.isUsageDataOn(), false); }); }); describe("Test setUsageDataOn method", () => { it("should change samplingPercentage to 100, turns usage data on", () => { addInUsageData.setUsageDataOff(); addInUsageData.setUsageDataOn(); assert.equal(appInsights.defaultClient.config.samplingPercentage, 100); }); }); describe("Test isUsageDataOn method", () => { it("should return true if samplingPercentage is on(100)", () => { appInsights.defaultClient.config.samplingPercentage = 100; assert.equal(addInUsageData.isUsageDataOn(), true); }); it("should return false if samplingPercentage is off(0)", () => { appInsights.defaultClient.config.samplingPercentage = 0; assert.equal(addInUsageData.isUsageDataOn(), false); }); }); describe("Test getUsageDataKey method", () => { it("should return usage data key", () => { assert.equal(addInUsageData.getUsageDataKey(), "de0d9e7c-1f46-4552-bc21-4e43e489a015"); }); }); describe("Test getEventsSent method", () => { it("should return amount of events successfully sent", () => { addInUsageData.setUsageDataOff(); const testEvent = { Test1: [true, 100], ScriptType: ["Java", 1], }; addInUsageData.reportEvent("office-addin-usage-data", testEvent); assert.equal(addInUsageData.getEventsSent(), 1); }); }); describe("Test getExceptionsSent method", () => { it("should return amount of exceptions successfully sent ", () => { addInUsageData.setUsageDataOff(); addInUsageData.reportError("TestData", err); assert.equal(addInUsageData.getExceptionsSent(), 1); }); }); describe("Test UsageDataLevel method", () => { it("should return the usage data level of the object", () => { assert.equal("on", addInUsageData.getUsageDataLevel()); }); }); describe("Test maskFilePaths method", () => { it("should parse error file paths with slashs", () => { addInUsageData.setUsageDataOff(); const compareError = new Error(); compareError.name = "TestData-test"; compareError.message = "this error contains a file path:C:\\index.js"; // may throw error if change any part of the top of the test file compareError.stack = "this error contains a file path:C:\\.js"; addInUsageData.maskFilePaths(err); assert.equal(compareError.name, err.name); assert.equal(compareError.message, err.message); assert.equal(err.stack.includes(compareError.stack), true); }); it("should parse error file paths with backslashs", () => { addInUsageData.setUsageDataOff(); const compareErrorWithBackslash = new Error(); compareErrorWithBackslash.message = "this error contains a file path:C:\\excel file .xlsx"; compareErrorWithBackslash.stack = "this error contains a file path:C:\\.xlsx";; addInUsageData.maskFilePaths(errWithBackslash); assert.equal(compareErrorWithBackslash.message, errWithBackslash.message); assert.equal(errWithBackslash.stack.includes(compareErrorWithBackslash.stack), true); }); }); describe("Test modifySetting method", () => { it("should modify or create specific property to new value", () => { const usageDataLevel = usageDataObject.usageDataLevel; let jsonObject = {}; jsonObject[usageDataObject.groupName] = usageDataObject.usageDataLevel; jsonObject = { usageDataInstances: jsonData }; jsonObject = { usageDataInstances: { [usageDataObject.groupName]: { usageDataLevel } } }; fs.writeFileSync(defaults.usageDataJsonFilePath, JSON.stringify((jsonObject))); const usageDataJsonData = jsonData.readUsageDataJsonData(); const testPropertyName = "testProperty"; usageDataJsonData.usageDataInstances[usageDataObject.groupName][testPropertyName] = 0; jsonData.modifyUsageDataJsonData(usageDataObject.groupName, testPropertyName, 0); assert.equal(JSON.stringify(usageDataJsonData), JSON.stringify(jsonData.readUsageDataJsonData())); }); }); describe("Test readUsageDataJsonData method", () => { it("should read and return parsed object object from usage data", () => { const usageDataLevel = usageDataObject.usageDataLevel; let jsonObject = {}; jsonObject[usageDataObject.groupName] = usageDataObject.usageDataLevel; jsonObject = { usageDataInstances: jsonData }; jsonObject = { usageDataInstances: { [usageDataObject.groupName]: { usageDataLevel } } }; fs.writeFileSync(defaults.usageDataJsonFilePath, JSON.stringify((jsonObject))); assert.equal(JSON.stringify(jsonObject), JSON.stringify(jsonData.readUsageDataJsonData())); }); }); describe("Test readUsageDataLevel method", () => { it("should read and return object's usage data level from file", () => { const usageDataLevel = usageDataObject.usageDataLevel; let jsonObject = {}; jsonObject[usageDataObject.groupName] = usageDataObject.usageDataLevel; jsonObject = { usageDataInstances: jsonData }; jsonObject = { usageDataInstances: { [usageDataObject.groupName]: { usageDataLevel } } }; fs.writeFileSync(defaults.usageDataJsonFilePath, JSON.stringify((jsonObject))); assert.equal(officeAddinUsageData.UsageDataLevel.on, jsonData.readUsageDataLevel(usageDataObject.groupName)); }); }); describe("Test readUsageDataObjectProperty method", () => { it("should read and return parsed object object from usage data", () => { const usageDataLevel = usageDataObject.usageDataLevel; let jsonObject = {}; jsonObject[usageDataObject.groupName] = usageDataObject.usageDataLevel; jsonObject = { usageDataInstances: jsonData }; jsonObject = { usageDataInstances: { [usageDataObject.groupName]: { usageDataLevel } } }; fs.writeFileSync(defaults.usageDataJsonFilePath, JSON.stringify((jsonObject))); assert.equal(officeAddinUsageData.UsageDataLevel.on, jsonData.readUsageDataObjectProperty(usageDataObject.groupName, "usageDataLevel")); }); }); describe("Test writeUsageDataJsonData method", () => { it("should write to already existing file", () => { fs.writeFileSync(defaults.usageDataJsonFilePath, ""); const usageDataLevel = usageDataObject.usageDataLevel; let jsonObject = {}; jsonObject[usageDataObject.groupName] = usageDataObject.usageDataLevel; jsonObject = { usageDataInstances: jsonData }; jsonObject = { usageDataInstances: { [usageDataObject.groupName]: { usageDataLevel } } }; jsonData.writeUsageDataJsonData(usageDataObject.groupName, usageDataObject.usageDataLevel); assert.equal(JSON.stringify(jsonObject, null, 2), fs.readFileSync(defaults.usageDataJsonFilePath, "utf8")); }); }); describe("Test writeUsageDataJsonData method", () => { it("should create new existing file with correct format", () => { const usageDataLevel = usageDataObject.usageDataLevel; let jsonObject = {}; jsonObject[usageDataObject.groupName] = usageDataObject.usageDataLevel; jsonObject = { usageDataInstances: jsonData }; jsonObject = { usageDataInstances: { [usageDataObject.groupName]: { usageDataLevel } } }; jsonData.writeUsageDataJsonData(usageDataObject.groupName, usageDataObject.usageDataLevel); assert.equal(JSON.stringify(jsonObject, null, 2), fs.readFileSync(defaults.usageDataJsonFilePath, "utf8")); }); }); describe("Test groupNameExists method", () => { it("should check if groupName exists", () => { fs.writeFileSync(defaults.usageDataJsonFilePath, "test"); const usageDataLevel = usageDataObject.usageDataLevel; let jsonObject = {}; jsonObject[usageDataObject.groupName] = usageDataObject.usageDataLevel; jsonObject = { usageDataInstances: jsonData }; jsonObject = { usageDataInstances: { [usageDataObject.groupName]: { usageDataLevel } } }; fs.writeFileSync(defaults.usageDataJsonFilePath, JSON.stringify((jsonObject))); assert.equal(true, jsonData.groupNameExists("office-addin-usage-data")); }); }); describe("Test readUsageDataSettings method", () => { it("should read and return parsed usage data object group settings", () => { const usageDataLevel = usageDataObject.usageDataLevel; const jsonObject = { usageDataInstances: { [usageDataObject.groupName]: { usageDataLevel } } }; fs.writeFileSync(defaults.usageDataJsonFilePath, JSON.stringify((jsonObject))); assert.equal(JSON.stringify(jsonObject.usageDataInstances[usageDataObject.groupName]), JSON.stringify(jsonData.readUsageDataSettings(usageDataObject.groupName))); }); }); describe("Test reportSuccess", () => { it("should send success events successfully", () => { addInUsageData.reportSuccess("testMethod-reportSuccess", {TestVal: 42, OtherTestVal: "testing"}); assert.equal(addInUsageData.getEventsSent(), 1); }); it("should send success events successfully, even when there's no additional data", () => { addInUsageData.reportSuccess("testMethod-reportSuccess"); assert.equal(addInUsageData.getEventsSent(), 1); }); }); describe("Test reportExpectedException", () => { it("should send successful fail events successfully", () => { addInUsageData.reportExpectedException("testMethod-reportExpectedException", new Error("Test"), {TestVal: 42, OtherTestVal: "testing"}); assert.equal(addInUsageData.getEventsSent(), 1); }); it("should send successful fail events successfully, even when there's no additional data", () => { addInUsageData.reportExpectedException("testMethod-reportExpectedException", new Error("Test")); assert.equal(addInUsageData.getEventsSent(), 1); }); }); describe("Test sendUsageDataEvent", () => { it("should send events successfully", () => { addInUsageData.sendUsageDataEvent({TestVal: 42, OtherTestVal: "testing"}); assert.equal(addInUsageData.getEventsSent(), 1); }); it("should send events successfully, even when there's no data", () => { addInUsageData.sendUsageDataEvent(); assert.equal(addInUsageData.getEventsSent(), 1); }); }); describe("Test reportException", () => { it("should send exceptions successfully", () => { addInUsageData.reportException("testMethod-reportException", new Error("Test"), {TestVal: 42, OtherTestVal: "testing"}); assert.equal(addInUsageData.getExceptionsSent(), 1); }); it("should send exceptions successfully, even when there's no data", () => { addInUsageData.reportException("testMethod-reportException", new Error("Test")); assert.equal(addInUsageData.getExceptionsSent(), 1); }); }); });
the_stack
namespace annie { /** * TweenObj,具体的tween对象类 * @class annie.TweenObj * @public * @since 1.0.0 */ export class TweenObj extends AObject { public constructor() { super(); } /** * 是否暂停,默认false * @property pause * @type {boolean} */ public pause:boolean=false; /** * 当前帧 * @property currentFrame * @type {number} */ public currentFrame: number = 0; /** * 总帧数 * @property totalFrames * @type {number} */ public totalFrames: number = 0; protected _startData: any; protected _disData: any; /** * 当前被tween的对象 * @property target * @type {Object} */ public target: any; private _isTo: boolean; private _isLoop: number = 0; private _delay: number = 0; public _update: Function; public _completeFun: Function; public _ease: Function; private _isFront: boolean = true; private _cParams: any = null; private _loop: boolean = false; /** * 初始化数据 * @method init * @param target * @param times * @param data * @param isTo * @param isPlay * @public * @since 1.0.0 */ public init(target: any, times: number, data: any, isTo: boolean = true,isPlay:boolean=true): void { if (times <= 0 || typeof(times) != "number") { throw new Error("annie.Tween.to()或者annie.Tween.from()方法的第二个参数一定要是大于0的数字"); } let s = this; s.currentFrame = 1; let tTime: number = times * Stage._FPS >> 0; s.totalFrames = tTime > 0 ? tTime : 1; s.target = target; s._isTo = isTo; s._isLoop = 0; s._startData = {}; s._disData = {}; s._delay = 0; s._isFront = true; s._ease = null; s._update = null; s._cParams = null; s._loop = false; s._completeFun = null; for (let item in data) { switch (item) { case "useFrame": if (data[item] == true) { s.totalFrames = times; } break; case "yoyo": if (typeof (data[item]) == "number") { s._isLoop = data[item]; } else { if (data[item] == false) { s._isLoop = 0; } else if (data[item] == true) { s._isLoop = Number.MAX_VALUE; } } break; case "delay": if (data.useFrame) { s._delay = data[item]; } else { s._delay = data[item] * Stage._FPS >> 0; } break; case "ease": s._ease = data[item]; break; case "onUpdate": s._update = data[item]; break; case "onComplete": s._completeFun = data[item]; break; case "completeParams": s._cParams = data[item]; break; case "loop": s._loop = data[item]; break; default : if (typeof(data[item]) == "number") { if (isTo) { s._startData[item] = target[item]; s._disData[item] = data[item] - target[item]; } else { s._startData[item] = data[item]; s._disData[item] = target[item] - data[item]; target[item] = data[item]; } } } } } /** * 更新数据 * @method update * @since 1.0.0 * @public */ public update(): void { let s = this; if(s.pause)return; if (s._isFront && s._delay > 0) { s._delay--; return; } //更新数据 let per = s.currentFrame / s.totalFrames; if (per < 0 || per > 1) return; if (s._ease) { per = s._ease(per); } let isHave: boolean = false; for (let item in s._disData) { isHave = true; s.target[item] = s._startData[item] + s._disData[item] * per; } if (!isHave) { //如果发现tween被全新的tween全部给替换了,那就直接回收这个 Tween.kill(s.instanceId); return; } if (s._update) { s._update(per); } let cf = s._completeFun; let pm = s._cParams; if (s._isFront) { s.currentFrame++; if (s.currentFrame > s.totalFrames) { if (s._loop) { s.currentFrame = 1; } else { if (cf) { cf(pm,s._isLoop==0); } if (s._isLoop > 0) { s._isFront = false; s.currentFrame = s.totalFrames; s._isLoop--; } else { Tween.kill(s.instanceId); } } } } else { s.currentFrame--; if (s.currentFrame < 0) { if (cf) { cf(pm,s._isLoop==0); } if (s._isLoop > 0) { s._isFront = true; s.currentFrame = 1; } else { Tween.kill(s.instanceId); } } } } destroy(): void { let s = this; s._update = null; s._completeFun = null; s._ease = null; } } /** * 全局静态单列类,不要实例化此类 * @class annie.Tween * @public * @since 1.0.0 */ export class Tween { /** * 将target对象从data中指定的属性数值渐变到target属性当前的数值 * @method to * @static * @param {Object} target * @param {number} totalFrame 总时间长度 如果data.useFrame为true 这里就是帧数,如果data.useFrame为false则这里就是时间 * @param {Object} data 包含target对象的各种数字类型属性及其他一些方法属性 * @param {number:boolean} data.yoyo 是否像摆钟一样来回循环,默认为false.设置为true则会无限循环,或想只运行指定的摆动次数,将此参数设置为数字就行了。 * @param {number:boolean} data.loop 是否循环播放。 * @param {Function} data.onComplete 完成结束函数. 默认为null. 两个参数,第一个是data.completeParams的值,第二个是true或者false,表示是否真的结束了,或者是一次yoyo,一次loop的结束 * @param {Array} data.completeParams 完成函数参数. 默认为null,可以给完成函数里传参数 * @param {Function} data.onUpdate 进入每帧后执行函数,回传参数是当前的Tween时间比.默认为null * @param {Function} data.ease 缓动类型方法 * @param {boolean} data.useFrame 为false用时间秒值;为true则是以帧为单位 * @param {number} data.delay 延时,useFrame为true以帧为单位 useFrame为false以秒为单位 * @public * @since 1.0.0 */ public static to(target: any, totalFrame: number, data: Object): number { return Tween.createTween(target, totalFrame, data, true); } /** * 将target对象从data中指定的属性数值渐变到target属性当前的数值 * @method from * @static * @param {Object} target * @param {number} totalFrame 总时间长度 如果data.useFrame为true 这里就是帧数,如果data.useFrame为false则这里就是时间 * @param {Object} data 包含target对象的各种数字类型属性及其他一些方法属性 * @param {number:boolean} data.yoyo 是否像摆钟一样来回循环,默认为false.设置为true则会无限循环,或想只运行指定的摆动次数,将此参数设置为数字就行了。 * @param {number:boolean} data.loop 是否循环播放。 * @param {Function} data.onComplete 完成结束函数. 默认为null. 两个参数,第一个是data.completeParams的值,第二个是true或者false,表示是否真的结束了,或者是一次yoyo,一次loop的结束 * @param {Array} data.completeParams 完成函数参数. 默认为null,可以给完成函数里传参数 * @param {Function} data.onUpdate 进入每帧后执行函数,回传参数是当前的Tween时间比.默认为null * @param {Function} data.ease 缓动类型方法 * @param {boolean} data.useFrame 为false用时间秒值;为true则是以帧为单位 * @param {number} data.delay 延时,useFrame为true以帧为单位 useFrame为false以秒为单位 * @public * @since 1.0.0 */ public static from(target: any, totalFrame: number, data: Object): number{ return Tween.createTween(target, totalFrame, data, false); } public static createTween(target: any, totalFrame: number, data: any, isTo: boolean,isPlay:boolean=true): number { let tweenObj: Tween | any; let len = Tween._tweenList.length; for (let i = 0; i < len; i++) { tweenObj = Tween._tweenList[i]; if (target == tweenObj.target) { for (let item in tweenObj._startData) { if (data[item] != undefined) { delete tweenObj._startData[item]; delete tweenObj._disData[item]; } } } } len = Tween._tweenPool.length; if (len > 0) { tweenObj = Tween._tweenPool.shift(); //考虑到对象池回收后需要变更id tweenObj._instanceId = annie.AObject["_object_id"]++; } else { tweenObj = new TweenObj(); } Tween._tweenList.push(tweenObj); tweenObj.init(target, totalFrame, data, isTo,isPlay); return tweenObj.instanceId; } /** * 销毁所有正在运行的Tween对象 * @method killAll * @static * @public * @since 1.0.0 */ public static killAll(): void { let len: number = Tween._tweenList.length; let tweenObj: any; for (let i = 0; i < len; i++) { tweenObj = Tween._tweenList[i]; tweenObj.target = null; tweenObj._completeFun = null; tweenObj._cParams = null; tweenObj._update = null; tweenObj._ease = null; tweenObj._loop = false; Tween._tweenPool.push(tweenObj); } Tween._tweenList.length = 0; } /** * @通过创建Tween对象返回时的唯一id来销毁对应的Tween对象 * @method kill * @static * @public * @param {annie.Tween} tween * @since 1.0.0 */ public static kill(tweenId: number): void { let len: number = Tween._tweenList.length; let tweenObj: any; for (let i = 0; i < len; i++) { tweenObj = Tween._tweenList[i]; if (tweenObj.instanceId == tweenId) { tweenObj.target = null; tweenObj._completeFun = null; tweenObj._cParams = null; tweenObj._update = null; tweenObj._ease = null; tweenObj._loop = null; Tween._tweenPool.push(tweenObj); Tween._tweenList.splice(i, 1); break; } } } private static _tweenPool: Array<TweenObj> = []; private static _tweenList: Array<TweenObj> = []; /** * quadraticIn缓动类型 * @method quadraticIn * @static * @public * @since 1.0.0 * @param {number}k * @return {number} */ public static quadraticIn(k: number): number { return k * k; } /** * quadraticOut 缓动类型 * @method quadraticOut * @static * @public * @since 1.0.0 * @param {number}k * @return {number} */ public static quadraticOut(k: number): number { return k * (2 - k); } /** * quadraticInOut 缓动类型 * @method quadraticInOut * @static * @public * @since 1.0.0 * @param {number}k * @return {number} */ public static quadraticInOut(k: number): number { if ((k *= 2) < 1) { return 0.5 * k * k; } return -0.5 * (--k * (k - 2) - 1); } /** * cubicIn 缓动类型 * @method cubicIn * @static * @public * @since 1.0.0 * @param {number}k * @return {number} */ public static cubicIn(k: number): number { return k * k * k; } /** * cubicOut 缓动类型 * @method cubicOut * @static * @public * @since 1.0.0 * @param {number}k * @return {number} */ public static cubicOut(k: number): number { return --k * k * k + 1; } /** * cubicInOut 缓动类型 * @method cubicInOut * @static * @public * @since 1.0.0 * @param {number}k * @return {number} */ public static cubicInOut(k: number): number { if ((k *= 2) < 1) { return 0.5 * k * k * k; } return 0.5 * ((k -= 2) * k * k + 2); } /** * quarticIn 缓动类型 * @method quarticIn * @static * @public * @since 1.0.0 * @param {number}k * @return {number} */ public static quarticIn(k: number): number { return k * k * k * k; } /** * quarticOut 缓动类型 * @method quarticOut * @static * @public * @since 1.0.0 * @param {number}k * @return {number} */ public static quarticOut(k: number): number { return 1 - (--k * k * k * k); } /** * quarticInOut 缓动类型 * @method quarticInOut * @static * @public * @since 1.0.0 * @param {number}k * @return {number} */ public static quarticInOut(k: number): number { if ((k *= 2) < 1) { return 0.5 * k * k * k * k; } return -0.5 * ((k -= 2) * k * k * k - 2); } /** * quinticIn 缓动类型 * @method quinticIn * @static * @public * @since 1.0.0 * @param {number}k * @return {number} */ public static quinticIn(k: number): number { return k * k * k * k * k; } /** * quinticOut 缓动类型 * @method quinticOut * @static * @public * @since 1.0.0 * @param {number}k * @return {number} */ public static quinticOut(k: number): number { return --k * k * k * k * k + 1; } /** * quinticInOut 缓动类型 * @method quinticInOut * @static * @public * @since 1.0.0 * @param {number}k * @return {number} */ public static quinticInOut(k: number): number { if ((k *= 2) < 1) { return 0.5 * k * k * k * k * k; } return 0.5 * ((k -= 2) * k * k * k * k + 2); } /** * sinusoidalIn 缓动类型 * @method sinusoidalIn * @static * @public * @since 1.0.0 * @param {number}k * @return {number} */ public static sinusoidalIn(k: number): number { return 1 - Math.cos(k * Math.PI / 2); } /** * sinusoidalOut 缓动类型 * @method sinusoidalOut * @static * @public * @since 1.0.0 * @param {number}k * @return {number} */ public static sinusoidalOut(k: number): number { return Math.sin(k * Math.PI / 2); } /** * sinusoidalInOut 缓动类型 * @method sinusoidalInOut * @static * @public * @since 1.0.0 * @param {number}k * @return {number} */ public static sinusoidalInOut(k: number): number { return 0.5 * (1 - Math.cos(Math.PI * k)); } /** * exponentialIn 缓动类型 * @method exponentialIn * @static * @public * @since 1.0.0 * @param {number}k * @return {number} */ public static exponentialIn(k: number): number { return k == 0 ? 0 : Math.pow(1024, k - 1); } /** * exponentialOut 缓动类型 * @method exponentialOut * @static * @public * @since 1.0.0 * @param {number}k * @return {number} */ public static exponentialOut(k: number): number { return k == 1 ? 1 : 1 - Math.pow(2, -10 * k); } /** * exponentialInOut 缓动类型 * @method exponentialInOut * @static * @public * @since 1.0.0 * @param {number}k * @return {number} */ public static exponentialInOut(k: number): number { if (k == 0) { return 0; } if (k == 1) { return 1; } if ((k *= 2) < 1) { return 0.5 * Math.pow(1024, k - 1); } return 0.5 * (-Math.pow(2, -10 * (k - 1)) + 2); } /** * circularIn 缓动类型 * @method circularIn * @static * @public * @since 1.0.0 * @param {number}k * @return {number} */ public static circularIn(k: number): number { return 1 - Math.sqrt(1 - k * k); } /** * circularOut 缓动类型 * @method circularOut * @static * @public * @since 1.0.0 * @param {number}k * @return {number} */ public static circularOut(k: number): number { return Math.sqrt(1 - (--k * k)); } /** * circularInOut 缓动类型 * @method circularInOut * @static * @public * @since 1.0.0 * @param {number}k * @return {number} */ public static circularInOut(k: number): number { if ((k *= 2) < 1) { return -0.5 * (Math.sqrt(1 - k * k) - 1); } return 0.5 * (Math.sqrt(1 - (k -= 2) * k) + 1); } /** * elasticIn 缓动类型 * @method elasticIn * @static * @public * @since 1.0.0 * @param {number}k * @return {number} */ public static elasticIn(k: number): number { if (k == 0) { return 0; } if (k == 1) { return 1; } return -Math.pow(2, 10 * (k - 1)) * Math.sin((k - 1.1) * 5 * Math.PI); } /** * elasticOut 缓动类型 * @method elasticOut * @static * @public * @since 1.0.0 * @param {number}k * @return {number} */ public static elasticOut(k: number): number { if (k == 0) { return 0; } if (k == 1) { return 1; } return Math.pow(2, -10 * k) * Math.sin((k - 0.1) * 5 * Math.PI) + 1; } /** * elasticInOut 缓动类型 * @method elasticInOut * @static * @public * @since 1.0.0 * @param {number}k * @return {number} */ public static elasticInOut(k: number): number { if (k == 0) { return 0; } if (k == 1) { return 1; } k *= 2; if (k < 1) { return -0.5 * Math.pow(2, 10 * (k - 1)) * Math.sin((k - 1.1) * 5 * Math.PI); } return 0.5 * Math.pow(2, -10 * (k - 1)) * Math.sin((k - 1.1) * 5 * Math.PI) + 1; } /** * backIn 缓动类型 * @method backIn * @static * @public * @since 1.0.0 * @param {number}k * @return {number} */ public static backIn(k: number): number { let s = 1.70158; return k * k * ((s + 1) * k - s); } /** * backOut 缓动类型 * @method backOut * @static * @public * @since 1.0.0 * @param {number}k * @return {number} */ public static backOut(k: number): number { let s = 1.70158; return --k * k * ((s + 1) * k + s) + 1; } /** * backInOut 缓动类型 * @method backInOut * @static * @public * @since 1.0.0 * @param {number}k * @return {number} */ public static backInOut(k: number): number { let s = 1.70158 * 1.525; if ((k *= 2) < 1) { return 0.5 * (k * k * ((s + 1) * k - s)); } return 0.5 * ((k -= 2) * k * ((s + 1) * k + s) + 2); } /** * bounceIn 缓动类型 * @method bounceIn * @static * @public * @since 1.0.0 * @param {number}k * @return {number} */ public static bounceIn(k: number): number { return 1 - Tween.bounceOut(1 - k); } /** * bounceOut 缓动类型 * @method bounceOut * @static * @public * @since 1.0.0 * @param {number}k * @return {number} */ public static bounceOut(k: number): number { if (k < (1 / 2.75)) { return 7.5625 * k * k; } else if (k < (2 / 2.75)) { return 7.5625 * (k -= (1.5 / 2.75)) * k + 0.75; } else if (k < (2.5 / 2.75)) { return 7.5625 * (k -= (2.25 / 2.75)) * k + 0.9375; } else { return 7.5625 * (k -= (2.625 / 2.75)) * k + 0.984375; } } /** * bounceInOut 缓动类型 * @method bounceInOut * @static * @public * @since 1.0.0 * @param {number}k * @return {number} */ public static bounceInOut(k: number): number { if (k < 0.5) { return Tween.bounceIn(k * 2) * 0.5; } return Tween.bounceOut(k * 2 - 1) * 0.5 + 0.5; } //这里之所有要独立运行,是因为可能存在多个stage,不能把这个跟其中任何一个stage放在一起update private static flush(): void { let len: number = Tween._tweenList.length; for (let i = len - 1; i >= 0; i--) { if (Tween._tweenList[i]) { Tween._tweenList[i].update(); } else { Tween._tweenList.splice(i, 1); } } } } }
the_stack
import { Events } from "./events"; export namespace WebNavigation { /** * Cause of the navigation. The same transition types as defined in the history API are used. * These are the same transition types as defined in the $(topic:transition_types)[history API] except with <code> * "start_page"</code> in place of <code>"auto_toplevel"</code> (for backwards compatibility). */ type TransitionType = | "link" | "typed" | "auto_bookmark" | "auto_subframe" | "manual_subframe" | "generated" | "start_page" | "form_submit" | "reload" | "keyword" | "keyword_generated"; type TransitionQualifier = "client_redirect" | "server_redirect" | "forward_back" | "from_address_bar"; interface EventUrlFilters { url: Events.UrlFilter[]; } /** * Information about the frame to retrieve information about. */ interface GetFrameDetailsType { /** * The ID of the tab in which the frame is. */ tabId: number; /** * The ID of the process runs the renderer for this tab. * Optional. */ processId?: number; /** * The ID of the frame in the given tab. */ frameId: number; } /** * Information about the requested frame, null if the specified frame ID and/or tab ID are invalid. */ interface GetFrameCallbackDetailsType { /** * True if the last navigation in this frame was interrupted by an error, i.e. the onErrorOccurred event fired. * Optional. */ errorOccurred?: boolean; /** * The URL currently associated with this frame, if the frame identified by the frameId existed at one point in the given * tab. The fact that an URL is associated with a given frameId does not imply that the corresponding frame still exists. */ url: string; /** * The ID of the tab in which the frame is. */ tabId: number; /** * The ID of the frame. 0 indicates that this is the main frame; a positive value indicates the ID of a subframe. */ frameId: number; /** * ID of frame that wraps the frame. Set to -1 of no parent frame exists. */ parentFrameId: number; } /** * Information about the tab to retrieve all frames from. */ interface GetAllFramesDetailsType { /** * The ID of the tab. */ tabId: number; } interface GetAllFramesCallbackDetailsItemType { /** * True if the last navigation in this frame was interrupted by an error, i.e. the onErrorOccurred event fired. * Optional. */ errorOccurred?: boolean; /** * The ID of the tab in which the frame is. */ tabId: number; /** * The ID of the frame. 0 indicates that this is the main frame; a positive value indicates the ID of a subframe. */ frameId: number; /** * ID of frame that wraps the frame. Set to -1 of no parent frame exists. */ parentFrameId: number; /** * The URL currently associated with this frame. */ url: string; } interface OnBeforeNavigateDetailsType { /** * The ID of the tab in which the navigation is about to occur. */ tabId: number; url: string; /** * 0 indicates the navigation happens in the tab content window; a positive value indicates navigation in a subframe. * Frame IDs are unique for a given tab and process. */ frameId: number; /** * ID of frame that wraps the frame. Set to -1 of no parent frame exists. */ parentFrameId: number; /** * The time when the browser was about to start the navigation, in milliseconds since the epoch. */ timeStamp: number; } interface OnCommittedDetailsType { /** * The ID of the tab in which the navigation occurs. */ tabId: number; url: string; /** * 0 indicates the navigation happens in the tab content window; a positive value indicates navigation in a subframe. * Frame IDs are unique within a tab. */ frameId: number; /** * The time when the navigation was committed, in milliseconds since the epoch. */ timeStamp: number; } interface OnDOMContentLoadedDetailsType { /** * The ID of the tab in which the navigation occurs. */ tabId: number; url: string; /** * 0 indicates the navigation happens in the tab content window; a positive value indicates navigation in a subframe. * Frame IDs are unique within a tab. */ frameId: number; /** * The time when the page's DOM was fully constructed, in milliseconds since the epoch. */ timeStamp: number; } interface OnCompletedDetailsType { /** * The ID of the tab in which the navigation occurs. */ tabId: number; url: string; /** * 0 indicates the navigation happens in the tab content window; a positive value indicates navigation in a subframe. * Frame IDs are unique within a tab. */ frameId: number; /** * The time when the document finished loading, in milliseconds since the epoch. */ timeStamp: number; } interface OnErrorOccurredDetailsType { /** * The ID of the tab in which the navigation occurs. */ tabId: number; url: string; /** * 0 indicates the navigation happens in the tab content window; a positive value indicates navigation in a subframe. * Frame IDs are unique within a tab. */ frameId: number; /** * The time when the error occurred, in milliseconds since the epoch. */ timeStamp: number; } interface OnCreatedNavigationTargetDetailsType { /** * The ID of the tab in which the navigation is triggered. */ sourceTabId: number; /** * The ID of the process runs the renderer for the source tab. */ sourceProcessId: number; /** * The ID of the frame with sourceTabId in which the navigation is triggered. 0 indicates the main frame. */ sourceFrameId: number; /** * The URL to be opened in the new window. */ url: string; /** * The ID of the tab in which the url is opened */ tabId: number; /** * The time when the browser was about to create a new view, in milliseconds since the epoch. */ timeStamp: number; } interface OnReferenceFragmentUpdatedDetailsType { /** * The ID of the tab in which the navigation occurs. */ tabId: number; url: string; /** * 0 indicates the navigation happens in the tab content window; a positive value indicates navigation in a subframe. * Frame IDs are unique within a tab. */ frameId: number; /** * The time when the navigation was committed, in milliseconds since the epoch. */ timeStamp: number; } interface OnTabReplacedDetailsType { /** * The ID of the tab that was replaced. */ replacedTabId: number; /** * The ID of the tab that replaced the old tab. */ tabId: number; /** * The time when the replacement happened, in milliseconds since the epoch. */ timeStamp: number; } interface OnHistoryStateUpdatedDetailsType { /** * The ID of the tab in which the navigation occurs. */ tabId: number; url: string; /** * 0 indicates the navigation happens in the tab content window; a positive value indicates navigation in a subframe. * Frame IDs are unique within a tab. */ frameId: number; /** * The time when the navigation was committed, in milliseconds since the epoch. */ timeStamp: number; } /** * Fired when a navigation is about to occur. */ interface onBeforeNavigateEvent extends Events.Event<(details: OnBeforeNavigateDetailsType) => void> { /** * Registers an event listener <em>callback</em> to an event. * * @param callback Called when an event occurs. The parameters of this function depend on the type of event. * @param filters Optional. Conditions that the URL being navigated to must satisfy. The 'schemes' and 'ports' fields of * UrlFilter are ignored for this event. */ addListener(callback: (details: OnBeforeNavigateDetailsType) => void, filters?: EventUrlFilters): void; } /** * Fired when a navigation is committed. The document (and the resources it refers to, such as images and subframes) * might still be downloading, but at least part of the document has been received from the server and the browser has * decided to switch to the new document. */ interface onCommittedEvent extends Events.Event<(details: OnCommittedDetailsType) => void> { /** * Registers an event listener <em>callback</em> to an event. * * @param callback Called when an event occurs. The parameters of this function depend on the type of event. * @param filters Optional. Conditions that the URL being navigated to must satisfy. The 'schemes' and 'ports' fields of * UrlFilter are ignored for this event. */ addListener(callback: (details: OnCommittedDetailsType) => void, filters?: EventUrlFilters): void; } /** * Fired when the page's DOM is fully constructed, but the referenced resources may not finish loading. */ interface onDOMContentLoadedEvent extends Events.Event<(details: OnDOMContentLoadedDetailsType) => void> { /** * Registers an event listener <em>callback</em> to an event. * * @param callback Called when an event occurs. The parameters of this function depend on the type of event. * @param filters Optional. Conditions that the URL being navigated to must satisfy. The 'schemes' and 'ports' fields of * UrlFilter are ignored for this event. */ addListener(callback: (details: OnDOMContentLoadedDetailsType) => void, filters?: EventUrlFilters): void; } /** * Fired when a document, including the resources it refers to, is completely loaded and initialized. */ interface onCompletedEvent extends Events.Event<(details: OnCompletedDetailsType) => void> { /** * Registers an event listener <em>callback</em> to an event. * * @param callback Called when an event occurs. The parameters of this function depend on the type of event. * @param filters Optional. Conditions that the URL being navigated to must satisfy. The 'schemes' and 'ports' fields of * UrlFilter are ignored for this event. */ addListener(callback: (details: OnCompletedDetailsType) => void, filters?: EventUrlFilters): void; } /** * Fired when an error occurs and the navigation is aborted. This can happen if either a network error occurred, * or the user aborted the navigation. */ interface onErrorOccurredEvent extends Events.Event<(details: OnErrorOccurredDetailsType) => void> { /** * Registers an event listener <em>callback</em> to an event. * * @param callback Called when an event occurs. The parameters of this function depend on the type of event. * @param filters Optional. Conditions that the URL being navigated to must satisfy. The 'schemes' and 'ports' fields of * UrlFilter are ignored for this event. */ addListener(callback: (details: OnErrorOccurredDetailsType) => void, filters?: EventUrlFilters): void; } /** * Fired when a new window, or a new tab in an existing window, is created to host a navigation. */ interface onCreatedNavigationTargetEvent extends Events.Event<(details: OnCreatedNavigationTargetDetailsType) => void> { /** * Registers an event listener <em>callback</em> to an event. * * @param callback Called when an event occurs. The parameters of this function depend on the type of event. * @param filters Optional. Conditions that the URL being navigated to must satisfy. The 'schemes' and 'ports' fields of * UrlFilter are ignored for this event. */ addListener(callback: (details: OnCreatedNavigationTargetDetailsType) => void, filters?: EventUrlFilters): void; } /** * Fired when the reference fragment of a frame was updated. All future events for that frame will use the updated URL. */ interface onReferenceFragmentUpdatedEvent extends Events.Event<(details: OnReferenceFragmentUpdatedDetailsType) => void> { /** * Registers an event listener <em>callback</em> to an event. * * @param callback Called when an event occurs. The parameters of this function depend on the type of event. * @param filters Optional. Conditions that the URL being navigated to must satisfy. The 'schemes' and 'ports' fields of * UrlFilter are ignored for this event. */ addListener( callback: (details: OnReferenceFragmentUpdatedDetailsType) => void, filters?: EventUrlFilters ): void; } /** * Fired when the frame's history was updated to a new URL. All future events for that frame will use the updated URL. */ interface onHistoryStateUpdatedEvent extends Events.Event<(details: OnHistoryStateUpdatedDetailsType) => void> { /** * Registers an event listener <em>callback</em> to an event. * * @param callback Called when an event occurs. The parameters of this function depend on the type of event. * @param filters Optional. Conditions that the URL being navigated to must satisfy. The 'schemes' and 'ports' fields of * UrlFilter are ignored for this event. */ addListener(callback: (details: OnHistoryStateUpdatedDetailsType) => void, filters?: EventUrlFilters): void; } interface Static { /** * Retrieves information about the given frame. A frame refers to an &lt;iframe&gt; or a &lt;frame&gt; of a web page and is * identified by a tab ID and a frame ID. * * @param details Information about the frame to retrieve information about. */ getFrame(details: GetFrameDetailsType): Promise<GetFrameCallbackDetailsType>; /** * Retrieves information about all frames of a given tab. * * @param details Information about the tab to retrieve all frames from. */ getAllFrames(details: GetAllFramesDetailsType): Promise<GetAllFramesCallbackDetailsItemType[]>; /** * Fired when a navigation is about to occur. */ onBeforeNavigate: onBeforeNavigateEvent; /** * Fired when a navigation is committed. The document (and the resources it refers to, such as images and subframes) * might still be downloading, but at least part of the document has been received from the server and the browser has * decided to switch to the new document. */ onCommitted: onCommittedEvent; /** * Fired when the page's DOM is fully constructed, but the referenced resources may not finish loading. */ onDOMContentLoaded: onDOMContentLoadedEvent; /** * Fired when a document, including the resources it refers to, is completely loaded and initialized. */ onCompleted: onCompletedEvent; /** * Fired when an error occurs and the navigation is aborted. This can happen if either a network error occurred, * or the user aborted the navigation. */ onErrorOccurred: onErrorOccurredEvent; /** * Fired when a new window, or a new tab in an existing window, is created to host a navigation. */ onCreatedNavigationTarget: onCreatedNavigationTargetEvent; /** * Fired when the reference fragment of a frame was updated. All future events for that frame will use the updated URL. */ onReferenceFragmentUpdated: onReferenceFragmentUpdatedEvent; /** * Fired when the contents of the tab is replaced by a different (usually previously pre-rendered) tab. * * @param details */ onTabReplaced: Events.Event<(details: OnTabReplacedDetailsType) => void>; /** * Fired when the frame's history was updated to a new URL. All future events for that frame will use the updated URL. */ onHistoryStateUpdated: onHistoryStateUpdatedEvent; } }
the_stack
import { Provider, TransactionResponse, BlockTag, JsonRpcProvider } from '@ethersproject/providers' import { BigNumber, BigNumberish, ethers, Signer as AbstractSigner } from 'ethers' import { TypedDataDomain, TypedDataField } from '@ethersproject/abstract-signer' import { Interface } from '@ethersproject/abi' import { BytesLike } from '@ethersproject/bytes' import { Deferrable } from '@ethersproject/properties' import { ConnectionInfo } from '@ethersproject/web' import { walletContracts } from '@0xsequence/abi' import { Transaction, Transactionish, TransactionRequest, NonceDependency, isSequenceTransaction, readSequenceNonce, appendNonce, hasSequenceTransactions, toSequenceTransactions, sequenceTxAbiEncode, makeExpirable, makeAfterNonce, SignedTransactions, computeMetaTxnHash, digestOfTransactions, decodeNonce } from '@0xsequence/transactions' import { Relayer } from '@0xsequence/relayer' import { ChainIdLike, WalletContext, JsonRpcSender, NetworkConfig, isJsonRpcProvider, sequenceContext, getChainId } from '@0xsequence/network' import { WalletConfig, WalletState, addressOf, sortConfig, compareAddr, imageHash, isUsableConfig, DecodedSignature, encodeSignature, joinSignatures, recoverEOASigner, decodeSignature, isDecodedFullSigner } from '@0xsequence/config' import { encodeTypedDataDigest, packMessageData, subDigestOf } from '@0xsequence/utils' import { RemoteSigner } from './remote-signers' import { resolveArrayProperties } from './utils' import { isSequenceSigner, Signer, SignedTransactionsCallback } from './signer' import { fetchImageHash } from '.' // Wallet is a signer interface to a Smart Contract based Ethereum account. // // Wallet allows managing the account/wallet sub-keys, wallet address, signing // messages, signing transactions and updating/deploying the wallet config on a specific chain. // // Wallet instances represent a wallet at a particular config-state, in someways, the Wallet // instance is immutable, and if you update the config, then you'll need to call useConfig() // to instantiate a new Wallet instance with the updated config. export interface WalletOptions { // config is the wallet multi-sig configuration. Note: the first config of any wallet // before it is deployed is used to derive it's the account address of the wallet. config: WalletConfig // context is the WalletContext of deployed wallet-contract modules for the Smart Wallet context?: WalletContext // strict mode will ensure the WalletConfig is usable otherwise throw (on by default) strict?: boolean } export class Wallet extends Signer { readonly context: WalletContext readonly config: WalletConfig private readonly _signers: AbstractSigner[] // provider is an Ethereum Json RPC provider that is connected to a particular network (aka chain) // and access to the signer for signing transactions. provider: JsonRpcProvider // sender is a minimal Json RPC sender interface. It's here for convenience for other web3 // interfaces to use. sender: JsonRpcSender // relayer dispatches transactions to an Ethereum node directly // or through a remote transaction Web Service. relayer: Relayer // chainId is the node network id, used for memoization chainId?: number constructor(options: WalletOptions, ...signers: (BytesLike | AbstractSigner)[]) { super() const { config, context, strict } = options if (context) { this.context = { ...context } } else { // default context is to use @0xsequence/network deployed context this.context = { ...sequenceContext } } if (strict === true) { this.context.nonStrict = undefined } else if (strict === false) { this.context.nonStrict = true } if (!this.context.nonStrict && !isUsableConfig(config)) { throw new Error('wallet config is not usable (strict mode)') } this.config = sortConfig(config) this._signers = signers.map(s => (AbstractSigner.isSigner(s) ? s : new ethers.Wallet(s))) } // useConfig creates a new Wallet instance with the provided config, and uses the current provider // and relayer. It's common to initialize a counter-factual / undeployed wallet by initializing // it with the Wallet's init config, then calling useConfig() with the most-up-to-date config, // ie. new Wallet({ config: initConfig }).useConfig(latestConfig).useSigners(signers) useConfig(config: WalletConfig, strict?: boolean): Wallet { return new Wallet({ config, context: this.context, strict }, ...this._signers) .setProvider(this.provider) .setRelayer(this.relayer) } useSigners(...signers: (BytesLike | AbstractSigner)[]): Wallet { return new Wallet({ config: this.config, context: this.context }, ...signers) .setProvider(this.provider) .setRelayer(this.relayer) } // connect is a short-hand to create an Account instance and set the provider and relayer. // // The connect method is defined on the AbstractSigner as connect(Provider): AbstractSigner connect(provider: Provider, relayer?: Relayer): Wallet { if (isJsonRpcProvider(provider)) { return new Wallet({ config: this.config, context: this.context }, ...this._signers) .setProvider(provider) .setRelayer(relayer!) } else { throw new Error('Wallet provider argument is expected to be a JsonRpcProvider') } } // setProvider assigns a json-rpc provider to this wallet instance setProvider(provider: JsonRpcProvider | ConnectionInfo | string): Wallet { if (provider === undefined) return this if (Provider.isProvider(provider)) { this.provider = provider this.sender = new JsonRpcSender(provider) } else { const jsonProvider = new JsonRpcProvider(<ConnectionInfo | string>provider) this.provider = jsonProvider this.sender = new JsonRpcSender(jsonProvider) } this.chainId = undefined // reset chainId value return this } // setRelayer assigns a Sequence transaction relayer to this wallet instance setRelayer(relayer: Relayer): Wallet { if (relayer === undefined) return this this.relayer = relayer return this } async getProvider(chainId?: number): Promise<JsonRpcProvider> { if (chainId) await this.getChainIdNumber(chainId) return this.provider } async getRelayer(chainId?: number): Promise<Relayer> { if (chainId) await this.getChainIdNumber(chainId) return this.relayer } async getWalletContext(): Promise<WalletContext> { return this.context } async getWalletConfig(chainId?: ChainIdLike): Promise<WalletConfig[]> { chainId = await this.getChainIdNumber(chainId) const config = { ...this.config, chainId } return [config] } async getWalletState(_?: ChainIdLike): Promise<WalletState[]> { const [address, chainId, isDeployed] = await Promise.all([this.getAddress(), this.getChainId(), this.isDeployed()]) const state: WalletState = { context: this.context, config: this.config, address: address, chainId: chainId, deployed: isDeployed, imageHash: this.imageHash, lastImageHash: isDeployed ? await fetchImageHash(this) : undefined } // TODO: set published boolean by checking if we have the latest logs // that compute to the same hash as in lastImageHash return [state] } // connected reports if json-rpc provider has been connected get connected(): boolean { return this.sender !== undefined } // address returns the address of the wallet account address get address(): string { return addressOf(this.config, this.context) } // imageHash is the unique hash of the WalletConfig get imageHash(): string { return imageHash(this.config) } // getAddress returns the address of the wallet account address // // The getAddress method is defined on the AbstractSigner async getAddress(): Promise<string> { return this.address } // getSigners returns the list of public account addresses to the currently connected // signer objects for this wallet. Note: for a complete list of configured signers // on the wallet, query getWalletConfig() async getSigners(): Promise<string[]> { if (!this._signers || this._signers.length === 0) { return [] } return Promise.all(this._signers.map(s => s.getAddress().then(s => ethers.utils.getAddress(s)))) } // chainId returns the network connected to this wallet instance async getChainId(): Promise<number> { if (this.chainId) return this.chainId if (!this.provider) { throw new Error('provider is not set, first connect a provider') } this.chainId = (await this.provider.getNetwork()).chainId return this.chainId } async getNetworks(): Promise<NetworkConfig[]> { const chainId = await this.getChainId() return [ { chainId: chainId, name: '', rpcUrl: '' } ] } // getNonce returns the transaction nonce for this wallet, via the relayer async getNonce(blockTag?: BlockTag, space?: BigNumberish): Promise<BigNumberish> { return this.relayer.getNonce(this.config, this.context, space, blockTag) } // getTransactionCount returns the number of transactions (aka nonce) // // getTransactionCount method is defined on the AbstractSigner async getTransactionCount(blockTag?: BlockTag): Promise<number> { const encodedNonce = await this.getNonce(blockTag, 0) const [_, decodedNonce] = decodeNonce(encodedNonce) return ethers.BigNumber.from(decodedNonce).toNumber() } // sendTransaction will dispatch the transaction to the relayer for submission to the network. async sendTransaction( transaction: Deferrable<Transactionish>, chainId?: ChainIdLike, allSigners?: boolean, callback?: SignedTransactionsCallback ): Promise<TransactionResponse> { const signedTxs = await this.signTransactions(transaction, chainId, allSigners) if (callback) { const address = addressOf(signedTxs.config, signedTxs.context) const metaTxnHash = computeMetaTxnHash(address, signedTxs.chainId, ...signedTxs.transactions) callback(signedTxs, metaTxnHash) } return this.relayer.relay(signedTxs) } // sendTransactionBatch is a sugar for better readability, but is the same as sendTransaction async sendTransactionBatch( transactions: Deferrable<TransactionRequest[] | Transaction[]>, chainId?: ChainIdLike, allSigners: boolean = true, callback?: SignedTransactionsCallback ): Promise<TransactionResponse> { return this.sendTransaction(transactions, chainId, allSigners, callback) } // signTransactions will sign a Sequence transaction with the wallet signers // // NOTE: the txs argument of type Transactionish can accept one or many transactions. async signTransactions( txs: Deferrable<Transactionish>, chainId?: ChainIdLike, allSigners?: boolean ): Promise<SignedTransactions> { const signChainId = await this.getChainIdNumber(chainId) const transaction = await resolveArrayProperties<Transactionish>(txs) if (!this.provider) { throw new Error('missing provider') } if (!this.relayer) { throw new Error('missing relayer') } let stx: Transaction[] = [] if (Array.isArray(transaction)) { if (hasSequenceTransactions(transaction)) { stx = transaction as Transaction[] } else { stx = await toSequenceTransactions(this, transaction) } } else if (isSequenceTransaction(transaction)) { stx = [transaction] } else { stx = await toSequenceTransactions(this, [transaction]) } // If transaction is marked as expirable // append expirable require if ((<TransactionRequest>transaction).expiration) { stx = makeExpirable(this.context, stx, (<TransactionRequest>transaction).expiration!) } // If transaction depends on another nonce // append after nonce requirement if ((<TransactionRequest>transaction).afterNonce) { const after = (<TransactionRequest>transaction).afterNonce stx = makeAfterNonce( this.context, stx, (<NonceDependency>after).address ? { address: (<NonceDependency>after).address, nonce: (<NonceDependency>after).nonce, space: (<NonceDependency>after).space } : { address: this.address, nonce: <BigNumberish>after } ) } // If a transaction has 0 gasLimit and not revertOnError // compute all new gas limits if (stx.find(a => !a.revertOnError && ethers.BigNumber.from(a.gasLimit || 0).eq(ethers.constants.Zero))) { stx = await this.relayer.estimateGasLimits(this.config, this.context, ...stx) } // If provided nonce append it to all other transactions // otherwise get next nonce for this wallet const providedNonce = readSequenceNonce(...stx) const nonce = providedNonce ? providedNonce : await this.getNonce() stx = appendNonce(stx, nonce) // Get transactions digest const digest = digestOfTransactions(...stx) // Bundle with signature return { digest: digest, chainId: signChainId, context: this.context, config: this.config, transactions: stx, signature: await this.sign(digest, true, chainId, allSigners) } } async sendSignedTransactions(signedTxs: SignedTransactions, chainId?: ChainIdLike): Promise<TransactionResponse> { if (!this.relayer) { throw new Error('relayer is not set, first connect a relayer') } await this.getChainIdNumber(chainId) return this.relayer.relay(signedTxs) } // signMessage will sign a message for a particular chainId with the wallet signers // // NOTE: signMessage(message: Bytes | string): Promise<string> is defined on AbstractSigner async signMessage(message: BytesLike, chainId?: ChainIdLike, allSigners?: boolean, isDigest: boolean = false): Promise<string> { const data = typeof message === 'string' && !message.startsWith('0x') ? ethers.utils.toUtf8Bytes(message) : message return this.sign(data, isDigest, chainId, allSigners) } async signTypedData( domain: TypedDataDomain, types: Record<string, Array<TypedDataField>>, message: Record<string, any>, chainId?: ChainIdLike, allSigners?: boolean ): Promise<string> { const signChainId = await this.getChainIdNumber(chainId) const domainChainId = domain.chainId ? BigNumber.from(domain.chainId).toNumber() : undefined if (domainChainId && domainChainId !== signChainId) { throw new Error(`signTypedData: domain.chainId (${domain.chainId}) is expected to be ${signChainId}`) } const hash = encodeTypedDataDigest({ domain, types, message }) return this.sign(hash, true, signChainId, allSigners) } async _signTypedData( domain: TypedDataDomain, types: Record<string, Array<TypedDataField>>, message: Record<string, any>, chainId?: ChainIdLike, allSigners?: boolean ): Promise<string> { return this.signTypedData(domain, types, message, chainId, allSigners) } async subDigest(digest: BytesLike, chainId?: ChainIdLike): Promise<Uint8Array> { const solvedChainId = await this.getChainIdNumber(chainId) return ethers.utils.arrayify(subDigestOf(this.address, solvedChainId, digest)) } // sign is a helper method to sign a payload with the wallet signers async sign(msg: BytesLike, isDigest: boolean = true, chainId?: ChainIdLike, allSigners?: boolean): Promise<string> { const signChainId = await this.getChainIdNumber(chainId) const digest = isDigest ? msg : ethers.utils.keccak256(msg) // Generate sub-digest const subDigest = await this.subDigest(digest, chainId) // Sign sub-digest using a set of signers and some optional data const signWith = async (signers: AbstractSigner[], auxData?: string): Promise<DecodedSignature> => { const signersAddr = await Promise.all(signers.map(s => s.getAddress())) const parts = await Promise.all( this.config.signers.map(async s => { try { const signer = signers[signersAddr.indexOf(s.address)] // Is not a signer, return config entry as-is if (!signer) { return s } // Is another Sequence wallet as signer, sign and append '03' (ERC1271 type) if (isSequenceSigner(signer)) { if (signer === this) throw Error("Can't sign transactions for self") const signature = (await signer.signMessage(subDigest, signChainId, allSigners, true)) + '03' return { ...s, signature: signature } } // Is remote signer, call and deduce signature type if (RemoteSigner.isRemoteSigner(signer)) { const signature = await signer.signMessageWithData(subDigest, auxData, signChainId) try { // Check if signature can be recovered as EOA signature const isEOASignature = recoverEOASigner(subDigest, { weight: s.weight, signature: signature }) === s.address if (isEOASignature) { // Exclude address on EOA signatures return { weight: s.weight, signature: signature } } } catch {} // Prepare signature for full encoding return { ...s, signature: signature } } // Is EOA signer return { weight: s.weight, signature: (await signer.signMessage(subDigest)) + '02' } } catch (err) { if (allSigners) { throw err } else { console.warn(`Skipped signer ${s.address}`) return s } } }) ) return { threshold: this.config.threshold, signers: parts } } // Split local signers and remote signers const localSigners = this._signers.filter(s => !RemoteSigner.isRemoteSigner(s)) const remoteSigners = this._signers.filter(s => RemoteSigner.isRemoteSigner(s)) // Sign message first using localSigners // include local signatures for remote signers const localSignature = await signWith(localSigners, this.packMsgAndSig(digest, [], signChainId)) const remoteSignature = await signWith( remoteSigners, this.packMsgAndSig(digest, encodeSignature(localSignature), signChainId) ) // Aggregate both local and remote signatures return encodeSignature(joinSignatures(localSignature, remoteSignature)) } // signWeight will return the total weight of all signers available based on the config async signWeight(): Promise<BigNumber> { const signers = await this.getSigners() return signers.reduce((p, s) => { const sconfig = this.config.signers.find(c => c.address === s) if (!sconfig) return p return p.add(sconfig.weight) }, ethers.constants.Zero) } async isDeployed(chainId?: ChainIdLike): Promise<boolean> { await this.getChainIdNumber(chainId) const walletCode = await this.provider.getCode(this.address) return !!walletCode && walletCode !== '0x' } // updateConfig will build an updated config transaction and send it to the Ethereum // network via the relayer. Note, the updated wallet config is stored as an image hash, // unlike `publishConfig` which will store the entire WalletConfig object in logs. async updateConfig( config?: WalletConfig, nonce?: number, publish = false, indexed?: boolean, callback?: SignedTransactionsCallback ): Promise<[WalletConfig, TransactionResponse]> { if (!config) config = this.config const [txs, n] = await Promise.all([this.buildUpdateConfigTransaction(config, publish, indexed), nonce ?? this.getNonce()]) return [{ address: this.address, ...config }, await this.sendTransaction(appendNonce(txs, n), undefined, undefined, callback)] } // publishConfig will publish the current wallet config to the network via the relayer. // Publishing the config will also store the entire object of signers. async publishConfig( indexed?: boolean, nonce?: number, requireFreshSigners: string[] = [], callback?: SignedTransactionsCallback ): Promise<TransactionResponse> { return this.sendTransaction( this.config.address ? this.buildPublishConfigTransaction(this.config, indexed, nonce) : await this.buildPublishSignersTransaction(indexed, nonce, requireFreshSigners), undefined, undefined, callback ) } // buildUpdateConfigTransaction creates a transaction to update the imageHash of the wallet's config // on chain. Note, the transaction is not sent to the network by this method. // // The `publish` argument when true will also store the contents of the WalletConfig to a chain's logs. async buildUpdateConfigTransaction(config: WalletConfig, publish = false, indexed?: boolean): Promise<Transaction[]> { if (!this.context.nonStrict && !isUsableConfig(config)) throw new Error('wallet config is not usable (strict mode)') const isUpgradable = await (async () => { try { const implementation = await this.provider.getStorageAt( this.address, ethers.utils.defaultAbiCoder.encode(['address'], [this.address]) ) return compareAddr(implementation, this.context.mainModuleUpgradable) === 0 } catch { return false } })() const walletInterface = new Interface(walletContracts.mainModule.abi) // empirically, this seems to work for the tests: // const gasLimit = 100000 + 1800 * config.signers.length // // but we're going to play it safe with this instead: const gasLimit = 2 * (100000 + 1800 * config.signers.length) const preTransaction = isUpgradable ? [] : [ { delegateCall: false, revertOnError: true, gasLimit: ethers.constants.Zero, to: this.address, value: ethers.constants.Zero, data: walletInterface.encodeFunctionData(walletInterface.getFunction('updateImplementation'), [ this.context.mainModuleUpgradable ]) } ] const mainModuleInterface = new Interface(walletContracts.mainModuleUpgradable.abi) const transaction = { delegateCall: false, revertOnError: true, gasLimit: ethers.constants.Zero, to: this.address, value: ethers.constants.Zero, data: mainModuleInterface.encodeFunctionData(mainModuleInterface.getFunction('updateImageHash'), [imageHash(config)]) } const postTransaction = publish ? await this.buildPublishConfigTransaction(config, indexed) : [] const transactions = [...preTransaction, transaction, ...postTransaction] // If update config reguires a single transaction // skip nested selfExecute bundle if (transactions.length === 1) { return transactions } return [ { delegateCall: false, revertOnError: false, gasLimit: gasLimit, to: this.address, value: ethers.constants.Zero, data: walletInterface.encodeFunctionData(walletInterface.getFunction('selfExecute'), [sequenceTxAbiEncode(transactions)]) } ] } buildPublishConfigTransaction(config: WalletConfig, indexed: boolean = true, nonce?: number): Transaction[] { const sequenceUtilsInterface = new Interface(walletContracts.sequenceUtils.abi) return [ { delegateCall: false, revertOnError: true, gasLimit: ethers.constants.Zero, to: this.context.sequenceUtils!, value: ethers.constants.Zero, nonce: nonce, data: sequenceUtilsInterface.encodeFunctionData(sequenceUtilsInterface.getFunction('publishConfig'), [ this.address, config.threshold, sortConfig(config).signers.map(s => ({ weight: s.weight, signer: s.address })), indexed ]) } ] } async buildPublishSignersTransaction( indexed: boolean = true, nonce?: number, requireFreshSigners: string[] = [] ): Promise<Transaction[]> { const sequenceUtilsInterface = new Interface(walletContracts.sequenceUtils.abi) const requireFreshSignersInterface = new Interface(walletContracts.requireFreshSigner.abi) const message = ethers.utils.randomBytes(32) const signature = await this.signMessage(message, this.chainId, false) // TODO: This is only required because RequireUtils doesn't support dynamic signatures // remove this filtering of dynamic once a new version of RequireUtils is deployed const decodedSignature = decodeSignature(signature) const filteredSignature = encodeSignature({ threshold: decodedSignature.threshold, signers: decodedSignature.signers.map((s, i) => { if (isDecodedFullSigner(s)) { const a = this.config.signers[i] return { weight: a.weight, address: a.address } } return s }) }) const contextRequireFreshSigner = this.context.libs?.requireFreshSigner if (requireFreshSigners.length > 0 && contextRequireFreshSigner === undefined) { throw Error('requireFreshSigners missing library') } return [ ...requireFreshSigners.map(signer => ({ delegateCall: false, revertOnError: true, gasLimit: ethers.constants.Zero, to: contextRequireFreshSigner!, value: ethers.constants.Zero, nonce: nonce, data: requireFreshSignersInterface.encodeFunctionData(requireFreshSignersInterface.getFunction('requireFreshSigner'), [ signer ]) })), { delegateCall: false, revertOnError: true, gasLimit: ethers.constants.Zero, to: this.context.sequenceUtils!, value: ethers.constants.Zero, nonce: nonce, data: sequenceUtilsInterface.encodeFunctionData(sequenceUtilsInterface.getFunction('publishInitialSigners'), [ this.address, ethers.utils.keccak256(message), this.config.signers.length, filteredSignature, indexed ]) } ] } // getChainIdFromArgument will return the chainId of the argument, as well as ensure // we're not providing an invalid chainId that isn't connected to this wallet. private async getChainIdNumber(chainId?: ChainIdLike): Promise<number> { if (!chainId) { // it's valid for chainId argument to be undefined, in which case // we will use the connected value return await this.getChainId() } const id = getChainId(chainId) if (this.context.nonStrict) { // in non-strict mode, just return the chainId from argument return id } const connectedChainId = await this.getChainId() if (connectedChainId !== id) { throw new Error(`the specified chainId ${id} does not match the wallet's connected chainId ${connectedChainId}`) } return connectedChainId } // packMsgAndSig is used by RemoteSigners to include details as a string blob of data. private packMsgAndSig(msg: BytesLike, sig: BytesLike, chainId: BigNumberish): string { return ethers.utils.defaultAbiCoder.encode(['address', 'uint256', 'bytes', 'bytes'], [this.address, chainId, msg, sig]) } signTransaction(_: Deferrable<TransactionRequest>): Promise<string> { throw new Error('signTransaction method is not supported in Wallet, please use signTransactions(...)') } // singleOwner will create a Wallet instance with a single signer (ie. from a single EOA account) static async singleOwner(owner: BytesLike | AbstractSigner, context?: WalletContext): Promise<Wallet> { const signer = AbstractSigner.isSigner(owner) ? owner : new ethers.Wallet(owner) const config = { threshold: 1, signers: [ { weight: 1, address: ethers.utils.getAddress(await signer.getAddress()) } ] } return new Wallet({ config, context }, signer) } async hasEnoughSigners(chainId?: ChainIdLike): Promise<boolean> { if (chainId) await this.getChainIdNumber(chainId) return (await this.signWeight()).gte(this.config.threshold) } }
the_stack
import { RangeNavigator } from '../../../src/range-navigator/index'; import { Logarithmic, DateTime, LineSeries, AreaSeries, getElement } from '../../../src/chart/index'; import { IResizeRangeNavigatorEventArgs } from '../../../src/range-navigator/index'; import { createElement, remove } from '@syncfusion/ej2-base'; import { IChangedEventArgs, IRangeEventArgs } from '../../../src/range-navigator/model/range-navigator-interface'; import { MouseEvents } from '../../../spec/chart/base/events.spec'; import {profile , inMB, getMemoryProfile} from '../../common.spec'; RangeNavigator.Inject(Logarithmic, DateTime, LineSeries, AreaSeries); let value: number = 0; let point: Object; let data: Object[] = []; let args: IChangedEventArgs; let trigger: MouseEvents = new MouseEvents(); for (let j: number = 0; j < 100; j++) { value += (Math.random() * 10); point = { x: j, y: value }; data.push(point); } /** * Spec for range navigator */ describe('Range navigator', () => { beforeAll(() => { const isDef = (o: any) => o !== undefined && o !== null; if (!isDef(window.performance)) { console.log("Unsupported environment, window.performance.memory is unavailable"); this.skip(); //Skips test (in Chai) return; } }); describe('with Sliders double axis', () => { let element: Element; let targetElement: Element; let range: RangeNavigator; let rangeElement: HTMLElement = createElement('div', { id: 'container' }); let axisLabel: Element; let isCheck: boolean = false; beforeAll(() => { document.body.appendChild(rangeElement); range = new RangeNavigator({ series: [{ dataSource: [{ x: 10, y: 20 }, { x: 20, y: 12 }, { x: 30, y: 22 }, { x: 40, y: 16 }], xName: 'x', yName: 'y', type: 'Line', animation: { duration: 0 } }], value: [10, 20], allowSnapping: false }); range.appendTo('#container'); }); afterAll((): void => { range.destroy(); rangeElement.remove(); }); it('checking with left slider moving', (done: Function) => { range.loaded = (args: object) => { isCheck = true; element = document.getElementById('container_LeftSlider'); targetElement = <Element>element.childNodes[2]; let transform: string = element.getAttribute('transform'); let str1: string = transform.substring(transform.indexOf('(') + 1); let xValue: number = +str1.substring(0, str1.indexOf(',')); let cx: number = +targetElement.getAttribute('cx'); let cy: number = +targetElement.getAttribute('cy'); let leftElement: Element = document.getElementById('container_leftUnSelectedArea'); expect(leftElement.getAttribute('width')).toEqual('0'); range.rangeOnMouseDown(<PointerEvent>trigger.onTouchStart(targetElement, null, null, null, null, xValue + cx, cy)); range.mouseMove(<PointerEvent>trigger.onTouchMove(targetElement, null, null, null, null, xValue + cx + 100, cy)); range.mouseEnd(<PointerEvent>trigger.onTouchEnd(targetElement, null, null, null, null, xValue + cx + 100, cy)); expect(+leftElement.getAttribute('width')).not.toEqual(0); }; range.changed = (args: IChangedEventArgs) => { if (isCheck) { expect(Math.round(+args.start) >= 12 && Math.round(+args.start) < 15).toBe(true); expect(Math.round(+args.end)).toEqual(20); isCheck = false; done(); } }; range.navigatorStyleSettings.selectedRegionColor = 'pink'; range.enableDeferredUpdate = true; range.refresh(); }); it('checking with left slider moving enable RTL', (done: Function) => { range.loaded = (args: object) => { isCheck = true; element = document.getElementById('container_LeftSlider'); targetElement = <Element>element.childNodes[2]; let transform: string = element.getAttribute('transform'); let str1: string = transform.substring(transform.indexOf('(') + 1); let xValue: number = +str1.substring(0, str1.indexOf(',')); let cx: number = +targetElement.getAttribute('cx'); let cy: number = +targetElement.getAttribute('cy'); range.rangeOnMouseDown(<PointerEvent>trigger.onTouchStart(targetElement, null, null, null, null, xValue + cx, cy)); range.mouseMove(<PointerEvent>trigger.onTouchMove(targetElement, null, null, null, null, xValue + cx + 100, cy)); range.mouseEnd(<PointerEvent>trigger.onTouchEnd(targetElement, null, null, null, null, xValue + cx + 100, cy)); }; range.changed = (args: IChangedEventArgs) => { if (isCheck) { expect(Math.floor(+args.start)).toEqual(10); expect(Math.ceil(+args.end)).toEqual(20); isCheck = false; done(); } }; range.enableRtl = true; range.refresh(); }); it('checking with left slider ', (done: Function) => { range.loaded = (args: object) => { isCheck = true; element = document.getElementById('container_LeftSlider'); targetElement = <Element>element.childNodes[2]; let transform: string = element.getAttribute('transform'); let str1: string = transform.substring(transform.indexOf('(') + 1); let xValue: number = +str1.substring(0, str1.indexOf(',')); let cx: number = +targetElement.getAttribute('cx'); let cy: number = +targetElement.getAttribute('cy'); range.rangeOnMouseDown(<PointerEvent>trigger.onTouchStart(targetElement, null, null, null, null, xValue + cx, cy)); range.mouseMove(<PointerEvent>trigger.onTouchMove(targetElement, null, null, null, null, xValue + 100, cy)); range.mouseEnd(<PointerEvent>trigger.onTouchEnd(targetElement, null, null, null, null, xValue + 120, cy)); }; range.changed = (args: IChangedEventArgs) => { if (isCheck) { expect(Math.floor(+args.start)).toEqual(10); expect(Math.ceil(+args.end)).toEqual(20); let leftElement: Element = document.getElementById('container_leftUnSelectedArea'); expect((+leftElement.getAttribute('width')) > 100).toBe(true); isCheck = false; done(); } }; range.navigatorStyleSettings.selectedRegionColor = null; range.theme = 'Fabric'; range.refresh(); }); it('checking with left slider position less than startX', (done: Function) => { range.loaded = (args: object) => { isCheck = true; element = document.getElementById('container_LeftSlider'); targetElement = <Element>element.childNodes[2]; let transform: string = element.getAttribute('transform'); let str1: string = transform.substring(transform.indexOf('(') + 1); let xValue: number = +str1.substring(0, str1.indexOf(',')); let cx: number = +targetElement.getAttribute('cx'); let cy: number = +targetElement.getAttribute('cy'); let leftElement: Element = document.getElementById('container_leftUnSelectedArea'); expect(leftElement.getAttribute('width')).not.toEqual('0'); range.rangeOnMouseDown(<PointerEvent>trigger.onTouchStart(targetElement, null, null, null, null, xValue - 500, cy)); range.mouseMove(<PointerEvent>trigger.onTouchMove(targetElement, null, null, null, null, xValue - 500, cy)); range.mouseEnd(<PointerEvent>trigger.onTouchEnd(targetElement, null, null, null, null, xValue - 500, cy)); }; range.changed = (args: IChangedEventArgs) => { if (isCheck) { expect(Math.floor(+args.start)).toEqual(20); expect(Math.ceil(+args.end) > 20 && Math.ceil(+args.end) < 35).toBe(true); expect(getElement('container_Series_0').getAttribute('stroke')).toBe('#a16ee5'); isCheck = false; done(); } }; range.theme = 'Bootstrap'; range.refresh(); }); it('checking with right slider moving out side of selected area', (done: Function) => { range.loaded = (args: object) => { isCheck = true; element = document.getElementById('container_RightSlider'); targetElement = <Element>element.childNodes[2]; let transform: string = element.getAttribute('transform'); let str1: string = transform.substring(transform.indexOf('(') + 1); let xValue: number = +str1.substring(0, str1.indexOf(',')); let cx: number = +targetElement.getAttribute('cx'); let cy: number = +targetElement.getAttribute('cy'); range.rangeOnMouseDown(<PointerEvent>trigger.onTouchStart(targetElement, null, null, null, null, xValue + cx, cy)); range.mouseMove(<PointerEvent>trigger.onTouchMove(targetElement, null, null, null, null, xValue + cx + 100, cy)); range.mouseEnd(<PointerEvent>trigger.onTouchEnd(targetElement, null, null, null, null, xValue + cx + 100, cy)); }; range.changed = (args: IChangedEventArgs) => { if (isCheck) { expect(getElement('container_RightSlider_ThumpSymbol').getAttribute('fill')).toBe('#BFBFBF'); expect(Math.floor(+args.start)).toEqual(20); expect(Math.ceil(+args.end) > 22 && Math.ceil(+args.end) < 38).toBe(true); isCheck = false; done(); } }; range.enableRtl = false; range.theme = 'HighContrastLight'; range.refresh(); }); it('checking with right slider moving in side of selected area', (done: Function) => { range.loaded = (args: object) => { isCheck = true; element = document.getElementById('container_RightSlider'); targetElement = <Element>element.childNodes[2]; range.rangeOnMouseDown(<PointerEvent>trigger.onTouchStart(targetElement, null, null, null, null, 200, 20)); range.mouseMove(<PointerEvent>trigger.onTouchMove(targetElement, null, null, null, null, 100, 20)); range.mouseEnd(<PointerEvent>trigger.onTouchEnd(targetElement, null, null, null, null, 400, 20)); }; range.changed = (args: IChangedEventArgs) => { if (isCheck) { expect(Math.floor(+args.start) > 10 && Math.floor(+args.start) < 15).toBe(true); expect(Math.ceil(+args.end)).toEqual(20); isCheck = false; } done(); }; range.navigatorStyleSettings.selectedRegionColor = 'pink'; range.refresh(); }); it('checking with label click', (done: Function) => { range.loaded = (args: Object): void => { isCheck = true; let element: Element = <Element>document.getElementById('container_AxisLabels').firstChild.firstChild; let pageX: number = +element.getAttribute('x'); let pageY: number = +element.getAttribute('y'); range.rangeOnMouseDown(<PointerEvent>trigger.onTouchStart(element, null, null, null, null, pageX, pageY)); range.mouseMove(<PointerEvent>trigger.onTouchEnd(element, null, null, null, null, 0, pageY)); range.mouseEnd(<PointerEvent>trigger.onTouchEnd(element, null, null, null, null, 0, pageY)); }; range.changed = (args: IChangedEventArgs) => { if (isCheck) { expect(Math.ceil(+args.start) > 11 && Math.ceil(+args.start) < 30).toBe(true); isCheck = false; } done(); }; range.animationDuration = 0; range.navigatorStyleSettings.selectedRegionColor = 'green'; range.refresh(); }); }); describe('with Sliders double axis', () => { let element: Element; let targetElement: Element; let range: RangeNavigator; let rangeElement: HTMLElement = createElement('div', { id: 'container' }); let axisLabel: Element; let isCheck: boolean = false; beforeAll(() => { document.body.appendChild(rangeElement); range = new RangeNavigator({ series: [{ dataSource: [{ x: new Date(2000, 0), y: 20 }, { x: new Date(2000, 5), y: 12 }, { x: new Date(2001, 0), y: 22 }, { x: new Date(2001, 7), y: 16 }], xName: 'x', yName: 'y', type: 'Line', animation: { duration: 0 } }], value: [new Date(2000, 1), new Date(2001, 5)], allowSnapping: false, enableDeferredUpdate: true, valueType: 'DateTime' }); range.appendTo('#container'); }); afterAll((): void => { range.destroy(); rangeElement.remove(); }); it('checking resize event', (done: Function) => { range.loaded = (args: Object): void => { if (isCheck) { expect(range.svgObject).not.toEqual(null); done(); } else { range.rangeResize(); } }; range.resized = (args: IResizeRangeNavigatorEventArgs) => { isCheck = true; expect(args.name).toBe('resized'); }; range.changed = null; range.refresh(); }); }); it('memory leak', () => { profile.sample(); let average: any = inMB(profile.averageChange) //Check average change in memory samples to not be over 10MB expect(average).toBeLessThan(10); let memory: any = inMB(getMemoryProfile()) //Check the final memory usage against the first usage, there should be little change if everything was properly deallocated expect(memory).toBeLessThan(profile.samples[0] + 0.25); }) });
the_stack
import { NavbarComponent } from './custom-navbar-component' const supportedUrls = [ '//www.bilibili.com', '//t.bilibili.com', '//search.bilibili.com', '//space.bilibili.com', '//account.bilibili.com', '//pay.bilibili.com', '//member.bilibili.com', '//big.bilibili.com', '//message.bilibili.com', '//app.bilibili.com', '//passport.bilibili.com', '//game.bilibili.com', '//live.bilibili.com/blackboard/', ] const unsupportedUrls = [ '//t.bilibili.com/vote/h5/index/#/result', '//t.bilibili.com/lottery/h5/index/#/result', '//member.bilibili.com/video/upload', '//space.bilibili.com/ajax/', '//www.bilibili.com/h5/comment/', // '//www.bilibili.com/blackboard/', '//member.bilibili.com/v2', ] const loadSettings = () => { document.documentElement.style.setProperty('--navbar-bounds-padding', `0 ${settings.customNavbarBoundsPadding}%`) document.documentElement.style.setProperty('--navbar-blur-opacity', (settings.customNavbarBlurOpacity || 0.7).toString()) addSettingsListener('customNavbarBlurOpacity', value => { document.documentElement.style.setProperty('--navbar-blur-opacity', value) }) const fixedNotSupported = [ // 'https://search.bilibili.com/all', 'https://space.bilibili.com', 'https://www.bilibili.com/read', ] if (!fixedNotSupported.some(url => document.URL.startsWith(url))) { addSettingsListener('customNavbarGlobalFixed', value => { document.body.classList.toggle('fixed-navbar', value) }, true) } } const classHandler = (key: string, value: boolean, element: HTMLElement) => { element.classList.toggle(key, value) } const darkHandler = (force: boolean) => { (dq('.custom-navbar') as HTMLElement).classList.toggle('dark', force); (dq('.custom-navbar-settings') as HTMLElement).classList.toggle('dark', force) } export default (() => { const url = document.URL.replace(location.search, '') const isHome = url === 'https://www.bilibili.com/' || url === 'https://www.bilibili.com/index.html' if (isIframe() || (settings.bilibiliSimpleNewHomeCompatible && isHome) || document.contentType !== 'text/html') { resources.removeStyle('customNavbarStyle') return } loadSettings() const showWidget = !(!supportedUrls.some(it => document.URL.includes(it)) || unsupportedUrls.some(it => document.URL.includes(it))) // || document.URL.includes('//www.bilibili.com/blackboard/bnj2020.html') // 拜年祭2020 // || document.URL.includes('//www.bilibili.com/blackboard/help.html') // 帮助中心 if (showWidget) { document.body.classList.add('custom-navbar-loading'); (async () => { const html = await import((() => 'customNavbarHtml')()) document.body.insertAdjacentHTML('beforeend', html) addSettingsListener('useDarkStyle', darkHandler, true) const getNavbarElement = () => dq('.custom-navbar') as HTMLElement ['Fill', 'Shadow', 'Compact', 'Blur'].forEach(item => { const key = 'customNavbar' + item as keyof BilibiliEvolvedSettings addSettingsListener( key, value => classHandler(item.toLowerCase(), value, getNavbarElement()), true ) }) SpinQuery.select('#banner_link,.international-header .bili-banner, .bili-header__banner').then(banner => { if (banner === null || !(banner instanceof HTMLElement)) { return } if (banner.style.backgroundImage || dq(banner, '.animated-banner')) { addSettingsListener('customNavbarTransparent', value => { if (!settings.hideBanner) { getNavbarElement().classList.toggle('transparent', value) } }, true) addSettingsListener('hideBanner', value => { if (settings.customNavbarTransparent) { getNavbarElement().classList.toggle('transparent', !value) } }) } }) SpinQuery.condition(() => dq('#banner_link,.international-header .bili-banner'), banner => banner === null ? false : Boolean((banner as HTMLElement).style.backgroundImage), (banner: HTMLElement) => { Observer.attributes(banner, () => { const blurLayers = dqa('.custom-navbar .blur-layer') as HTMLElement[] blurLayers.forEach(blurLayer => { blurLayer.style.backgroundImage = banner.style.backgroundImage blurLayer.setAttribute('data-image', banner.style.backgroundImage) }) }) }) const { Blank } = await import('./simple/custom-navbar-blank') const { Logo } = await import('./simple/custom-navbar-logo') const { Category } = await import('./category/custom-navbar-category') const { SimpleLink } = await import('./simple/custom-navbar-simple-link') const { UserInfo } = await import('./simple/custom-navbar-user-info') const { SearchBox } = await import('./simple/custom-navbar-search-box') const { Iframe } = await import('./simple/custom-navbar-iframe') const { Rank } = await import('./simple/custom-navbar-rank') const components = [ new Blank(1), new Logo(), new Category(), new Rank(), new SimpleLink('相簿', 'https://h.bilibili.com', 'drawing'), new SimpleLink('番剧', 'https://www.bilibili.com/anime/', 'bangumi'), new SimpleLink('音频', 'https://www.bilibili.com/audio/home/', 'music'), new Iframe('游戏中心', 'https://game.bilibili.com/', { src: `https://www.bilibili.com/page-proxy/game-nav.html`, width: `680px`, height: `260px`, lazy: true, iframeName: 'games', }), new Iframe('直播', 'https://live.bilibili.com', { src: `https://live.bilibili.com/blackboard/dropdown-menu.html`, width: `528px`, height: `266px`, lazy: true, iframeName: 'lives', }), new SimpleLink('赛事', 'https://www.bilibili.com/v/game/match/', 'match'), new SimpleLink('会员购', 'https://show.bilibili.com', 'shop'), new Iframe('漫画', 'https://manga.bilibili.com', { src: 'https://manga.bilibili.com/eden/bilibili-nav-panel.html', width: '720px', height: '266px', lazy: true, iframeName: 'manga', }), new Blank(2), new SearchBox(), new UserInfo(), ] if (getUID()) { const { WatchlaterList } = await import('./watchlater-list/custom-navbar-watchlater-list') const { Messages } = await import('./simple/custom-navbar-messages') const { Activities } = await import('./activities/custom-navbar-activities') const { Subscriptions } = await import('./subscriptions/custom-navbar-subscriptions') const { FavoritesList } = await import('./favorites-list/custom-navbar-favorites-list') const { HistoryList } = await import('./history-list/custom-navbar-history-list') components.push( new Messages(), new Subscriptions(), new Activities(), new WatchlaterList(), new FavoritesList(), new HistoryList(), ) } const { Upload } = await import('./simple/custom-navbar-upload') const { DarkMode } = await import('./simple/custom-navbar-dark-mode') components.push(new Upload(), new Blank(3), new DarkMode()) new Vue({ el: '.custom-navbar', data: { components, }, methods: { async requestPopup(component: NavbarComponent) { if (!component.requestedPopup && !component.disabled /* && !component.active */) { this.$set(component, `requestedPopup`, true) if (component.initialPopup) { component.initialPopup() } return } if (component.onPopup) { component.onPopup() } } }, mounted() { document.body.classList.remove('custom-navbar-loading') const orderedComponents = [...components].sort(ascendingSort(c => c.order)) const checkPosition = () => { const checkPositions = () => { // console.log('recalculate positions') // components.forEach(c => c.checkPosition()) let left = 0 let leftResult = true let right = orderedComponents.length - 1 let rightResult = true while (left < right) { leftResult = orderedComponents[left].checkPosition(!leftResult) left++ rightResult = orderedComponents[right].checkPosition(!rightResult) right-- } } addSettingsListener('customNavbarOrder', checkPositions, true) addSettingsListener('customNavbarHidden', checkPositions) addSettingsListener('customNavbarBoundsPadding', checkPositions) window.addEventListener('resize', checkPositions) } if ('requestIdleCallback' in unsafeWindow && GM.info.scriptHandler !== 'Violentmonkey') { unsafeWindow.requestIdleCallback(checkPosition) } else { setTimeout(checkPosition) } }, }) })() } else { resources.removeStyle('customNavbarStyle') } return { widget: { content: /*html*/` <div class="gui-settings-flat-button" id="custom-navbar-settings"> <i class="mdi mdi-24px mdi-auto-fix"></i> <span>顶栏布局</span> </div>`, condition: () => showWidget, success: async () => { const { initSettingsPanel } = await import('./settings/custom-navbar-settings') await initSettingsPanel() }, }, unload: () => { const navbar = dqa('.custom-navbar,.custom-navbar-settings') navbar.forEach((it: HTMLElement) => it.style.display = 'none') resources.removeStyle('customNavbarStyle') }, reload: () => { const navbar = dqa('.custom-navbar,.custom-navbar-settings') navbar.forEach((it: HTMLElement) => it.style.display = 'flex') resources.applyImportantStyle('customNavbarStyle') }, } })()
the_stack
* @module WebGL */ import { assert } from "@itwin/core-bentley"; import { Range3d } from "@itwin/core-geometry"; import { Frustum, FrustumPlanes, RenderMode, ViewFlags } from "@itwin/core-common"; import { Decorations } from "../Decorations"; import { SurfaceType } from "../primitives/VertexTable"; import { GraphicList, RenderGraphic } from "../RenderGraphic"; import { AnimationBranchState } from "../GraphicBranch"; import { BranchStack } from "./BranchStack"; import { BatchState } from "./BatchState"; import { BranchState } from "./BranchState"; import { DrawCommands, PopBatchCommand, PopBranchCommand, PopClipCommand, PopCommand, PrimitiveCommand, PushBatchCommand, PushBranchCommand, PushClipCommand, PushCommand, PushStateCommand, } from "./DrawCommand"; import { Batch, Branch, Graphic, GraphicsArray } from "./Graphic"; import { Layer, LayerContainer } from "./Layer"; import { LayerCommandLists } from "./LayerCommands"; import { MeshGraphic } from "./Mesh"; import { Primitive } from "./Primitive"; import { CompositeFlags, RenderOrder, RenderPass } from "./RenderFlags"; import { TargetGraphics } from "./TargetGraphics"; import { Target } from "./Target"; import { ClipVolume } from "./ClipVolume"; /** A list of DrawCommands to be rendered, ordered by render pass. * @internal */ export class RenderCommands implements Iterable<DrawCommands> { private _frustumPlanes?: FrustumPlanes; private readonly _scratchFrustum = new Frustum(); private readonly _scratchRange = new Range3d(); private readonly _commands = new Array<DrawCommands>(RenderPass.COUNT); private _target: Target; private _stack: BranchStack; // refers to the Target's BranchStack private _batchState: BatchState; // refers to the Target's BatchState private _forcedRenderPass: RenderPass = RenderPass.None; private _addLayersAsNormalGraphics = false; private _opaqueOverrides = false; private _translucentOverrides = false; private _addTranslucentAsOpaque = false; // true when rendering for _ReadPixels to force translucent items to be drawn in opaque pass. private readonly _layers: LayerCommandLists; public get target(): Target { return this._target; } public [Symbol.iterator](): Iterator<DrawCommands> { return this._commands[Symbol.iterator](); } public get isEmpty(): boolean { for (const commands of this._commands) if (0 < commands.length) return false; return true; } public get isDrawingLayers() { switch (this._forcedRenderPass) { case RenderPass.OpaqueLayers: case RenderPass.TranslucentLayers: case RenderPass.OverlayLayers: return true; default: return false; } } public get currentViewFlags(): ViewFlags { return this._stack.top.viewFlags; } public get compositeFlags(): CompositeFlags { let flags = CompositeFlags.None; if (this.hasCommands(RenderPass.Translucent)) flags |= CompositeFlags.Translucent; if (this.hasCommands(RenderPass.Hilite) || this.hasCommands(RenderPass.HiliteClassification) || this.hasCommands(RenderPass.HilitePlanarClassification)) flags |= CompositeFlags.Hilite; if (this.target.wantAmbientOcclusion) flags |= CompositeFlags.AmbientOcclusion; return flags; } private get _curBatch(): Batch | undefined { return this._batchState.currentBatch; } public hasCommands(pass: RenderPass): boolean { return 0 !== this.getCommands(pass).length; } public isOpaquePass(pass: RenderPass): boolean { return pass >= RenderPass.OpaqueLinear && pass <= RenderPass.OpaqueGeneral; } constructor(target: Target, stack: BranchStack, batchState: BatchState) { this._target = target; this._stack = stack; this._batchState = batchState; this._layers = new LayerCommandLists(this); for (let i = 0; i < RenderPass.COUNT; ++i) this._commands[i] = []; } public reset(target: Target, stack: BranchStack, batchState: BatchState): void { this._target = target; this._stack = stack; this._batchState = batchState; this.clear(); } public collectGraphicsForPlanarProjection(scene: GraphicList): void { assert(this._forcedRenderPass === RenderPass.None); assert(!this._addLayersAsNormalGraphics); this._addLayersAsNormalGraphics = true; this.addGraphics(scene); this._addLayersAsNormalGraphics = false; } public addGraphics(scene: GraphicList, forcedPass: RenderPass = RenderPass.None): void { this._forcedRenderPass = forcedPass; scene.forEach((entry: RenderGraphic) => (entry as Graphic).addCommands(this)); this._forcedRenderPass = RenderPass.None; } /** Add backgroundMap graphics to their own render pass. */ public addBackgroundMapGraphics(backgroundMapGraphics: GraphicList): void { this._forcedRenderPass = RenderPass.BackgroundMap; backgroundMapGraphics.forEach((entry: RenderGraphic) => (entry as Graphic).addCommands(this)); this._forcedRenderPass = RenderPass.None; } /** Add overlay graphics to the world overlay pass */ public addOverlayGraphics(overlayGraphics: GraphicList): void { this._forcedRenderPass = RenderPass.WorldOverlay; overlayGraphics.forEach((entry: RenderGraphic) => (entry as Graphic).addCommands(this)); this._forcedRenderPass = RenderPass.None; } public addDecorations(dec: GraphicList, forcedPass: RenderPass = RenderPass.None): void { this._forcedRenderPass = forcedPass; for (const entry of dec) { (entry as Graphic).addCommands(this); } this._forcedRenderPass = RenderPass.None; } public addWorldDecorations(decs: GraphicList): void { const world = this.target.getWorldDecorations(decs); this.pushAndPopBranch(world, () => { for (const entry of world.branch.entries) { (entry as Graphic).addCommands(this); } }); } private addPickableDecorations(decs: Decorations): void { if (undefined !== decs.normal) { for (const normal of decs.normal) { const gf = normal as Graphic; if (gf.isPickable) gf.addCommands(this); } } if (undefined !== decs.world) { const world = this.target.getWorldDecorations(decs.world); this.pushAndPopBranch(world, () => { for (const gf of world.branch.entries) { if ((gf as Graphic).isPickable) (gf as Graphic).addCommands(this); } }); } } public addBackground(gf?: Graphic): void { if (undefined === gf) return; assert(RenderPass.None === this._forcedRenderPass); this._forcedRenderPass = RenderPass.Background; this.pushAndPopState(this.target.decorationsState, () => gf.addCommands(this)); this._forcedRenderPass = RenderPass.None; } public addSkyBox(gf?: Graphic): void { if (undefined === gf) return; assert(RenderPass.None === this._forcedRenderPass); this._forcedRenderPass = RenderPass.SkyBox; this.pushAndPopState(this.target.decorationsState, () => gf.addCommands(this)); this._forcedRenderPass = RenderPass.None; } public addPrimitiveCommand(command: PrimitiveCommand, pass?: RenderPass): void { if (undefined === pass) pass = command.getRenderPass(this.target); if (RenderPass.None === pass) // Edges will return none if they don't want to draw at all (edges not turned on). return; if (RenderPass.None !== this._forcedRenderPass) { // Add the command to the forced render pass (background). this.getCommands(this._forcedRenderPass).push(command); return; } const haveFeatureOverrides = (this._opaqueOverrides || this._translucentOverrides) && command.opcode && command.hasFeatures; if (RenderPass.Translucent === pass && this._addTranslucentAsOpaque) { switch (command.renderOrder) { case RenderOrder.PlanarLitSurface: case RenderOrder.PlanarUnlitSurface: case RenderOrder.BlankingRegion: pass = RenderPass.OpaquePlanar; break; case RenderOrder.LitSurface: case RenderOrder.UnlitSurface: pass = RenderPass.OpaqueGeneral; break; default: pass = RenderPass.OpaqueLinear; break; } } switch (pass) { // If this command ordinarily renders translucent, but some features have been overridden to be opaque, must draw in both passes case RenderPass.Translucent: if (this._opaqueOverrides && haveFeatureOverrides && !command.primitive.cachedGeometry.alwaysRenderTranslucent) { let opaquePass: RenderPass; switch (command.renderOrder) { case RenderOrder.PlanarLitSurface: case RenderOrder.PlanarUnlitSurface: case RenderOrder.BlankingRegion: opaquePass = RenderPass.OpaquePlanar; break; case RenderOrder.LitSurface: case RenderOrder.UnlitSurface: opaquePass = RenderPass.OpaqueGeneral; break; default: opaquePass = RenderPass.OpaqueLinear; break; } this.getCommands(opaquePass).push(command); } break; // If this command ordinarily renders opaque, but some features have been overridden to be translucent, // must draw in both passes unless we are overriding translucent geometry to draw in the opaque pass for _ReadPixels. case RenderPass.OpaqueLinear: case RenderPass.OpaquePlanar: // Want these items to draw in general opaque pass so they are not in pick data. if (!command.hasFeatures) pass = RenderPass.OpaqueGeneral; /* falls through */ case RenderPass.OpaqueGeneral: if (this._translucentOverrides && haveFeatureOverrides && !this._addTranslucentAsOpaque) this.getCommands(RenderPass.Translucent).push(command); break; } this.getCommands(pass).push(command); } public getCommands(pass: RenderPass): DrawCommands { let idx = pass as number; assert(idx < this._commands.length); if (idx >= this._commands.length) idx -= 1; return this._commands[idx]; } public replaceCommands(pass: RenderPass, cmds: DrawCommands): void { const idx = pass as number; this._commands[idx].splice(0); this._commands[idx] = cmds; } public addHiliteBranch(branch: Branch, pass: RenderPass): void { this.pushAndPopBranchForPass(pass, branch, () => { branch.branch.entries.forEach((entry: RenderGraphic) => (entry as Graphic).addHiliteCommands(this, pass)); }); } public processLayers(container: LayerContainer): void { assert(RenderPass.None === this._forcedRenderPass); if (RenderPass.None !== this._forcedRenderPass) return; this._forcedRenderPass = container.renderPass; this._layers.processLayers(container, () => container.graphic.addCommands(this)); this._forcedRenderPass = RenderPass.None; } public addLayerCommands(layer: Layer): void { if (this._addLayersAsNormalGraphics) { // GraphicsCollectorDrawArgs wants to collect graphics to project to a plane for masking. // It bypasses PlanProjectionTreeReference.createDrawArgs which would otherwise wrap the graphics in a LayerContainer. assert(this._forcedRenderPass === RenderPass.None); this._forcedRenderPass = RenderPass.OpaqueGeneral; layer.graphic.addCommands(this); this._forcedRenderPass = RenderPass.None; return; } assert(this.isDrawingLayers); if (!this.isDrawingLayers) return; // Let the graphic add its commands. Afterward, pull them out and add them to the LayerCommands. this._layers.currentLayer = layer; layer.graphic.addCommands(this); const cmds = this.getCommands(this._forcedRenderPass); this._layers.addCommands(cmds); cmds.length = 0; this._layers.currentLayer = undefined; } public addHiliteLayerCommands(graphic: Graphic, pass: RenderPass): void { assert(this.isDrawingLayers || this._addLayersAsNormalGraphics); if (!this.isDrawingLayers && !this._addLayersAsNormalGraphics) return; const prevPass = this._forcedRenderPass; this._forcedRenderPass = RenderPass.None; graphic.addHiliteCommands(this, pass); this._forcedRenderPass = prevPass; } private getAnimationBranchState(branch: Branch): AnimationBranchState | undefined { const animId = branch.branch.animationId; return undefined !== animId ? this.target.animationBranches?.get(animId) : undefined; } private pushAndPopBranchForPass(pass: RenderPass, branch: Branch, func: () => void): void { assert(!this.isDrawingLayers); const animState = this.getAnimationBranchState(branch); if (animState?.omit) return; assert(RenderPass.None !== pass); this._stack.pushBranch(branch); if (branch.planarClassifier) branch.planarClassifier.pushBatchState(this._batchState); const cmds = this.getCommands(pass); const clip = animState?.clip as ClipVolume | undefined; const pushClip = undefined !== clip ? new PushClipCommand(clip) : undefined; if (pushClip) cmds.push(pushClip); const push = new PushBranchCommand(branch); cmds.push(push); func(); this._stack.pop(); if (cmds[cmds.length - 1] === push) { cmds.pop(); if (pushClip) cmds.pop(); } else { cmds.push(PopBranchCommand.instance); if (pushClip) cmds.push(PopClipCommand.instance); } } private pushAndPop(push: PushCommand, pop: PopCommand, func: () => void): void { if (this.isDrawingLayers) { this._commands[RenderPass.Hilite].push(push); this._layers.pushAndPop(push, pop, func); const cmds = this._commands[RenderPass.Hilite]; if (0 < cmds.length && cmds[cmds.length - 1] === push) cmds.pop(); else cmds.push(pop); return; } if (RenderPass.None === this._forcedRenderPass) { // Need to make sure the push command precedes any subsequent commands added to any render pass. for (const cmds of this._commands) cmds.push(push); } else { // May want to add hilite commands as well - add the push command to that pass. this._commands[this._forcedRenderPass].push(push); this._commands[RenderPass.Hilite].push(push); } func(); // Remove push command from any passes that didn't receive any commands; add the pop command to any passes that did. if (RenderPass.None === this._forcedRenderPass) { for (const cmds of this._commands) { assert(0 < cmds.length); if (0 < cmds.length && cmds[cmds.length - 1] === push) cmds.pop(); else cmds.push(pop); } } else { assert(0 < this._commands[this._forcedRenderPass].length); assert(0 < this._commands[RenderPass.Hilite].length); let cmds = this._commands[this._forcedRenderPass]; if (cmds[cmds.length - 1] === push) cmds.pop(); else cmds.push(pop); cmds = this._commands[RenderPass.Hilite]; if (cmds[cmds.length - 1] === push) cmds.pop(); else cmds.push(pop); } } public pushAndPopBranch(branch: Branch, func: () => void): void { const animState = this.getAnimationBranchState(branch); if (animState?.omit) return; if (animState?.clip) this.pushAndPop(new PushClipCommand(animState.clip as ClipVolume), PopClipCommand.instance, () => this._pushAndPopBranch(branch, func)); else this._pushAndPopBranch(branch, func); } private _pushAndPopBranch(branch: Branch, func: () => void): void { this._stack.pushBranch(branch); if (branch.planarClassifier) branch.planarClassifier.pushBatchState(this._batchState); this.pushAndPop(new PushBranchCommand(branch), PopBranchCommand.instance, func); this._stack.pop(); } public pushAndPopState(state: BranchState, func: () => void): void { this._stack.pushState(state); this.pushAndPop(new PushStateCommand(state), PopBranchCommand.instance, func); this._stack.pop(); } public clear(): void { assert(this._batchState.isEmpty); this._clearCommands(); } private _clearCommands(): void { this._commands.forEach((cmds: DrawCommands) => { cmds.splice(0); }); this._layers.clear(); } public initForPickOverlays(sceneOverlays: GraphicList, overlayDecorations: GraphicList | undefined): void { this._clearCommands(); this._addTranslucentAsOpaque = true; for (const sceneGf of sceneOverlays) (sceneGf as Graphic).addCommands(this); if (undefined !== overlayDecorations) { this.pushAndPopState(this.target.decorationsState, () => { for (const overlay of overlayDecorations) { const gf = overlay as Graphic; if (gf.isPickable) gf.addCommands(this); } }); } this._addTranslucentAsOpaque = false; } public initForReadPixels(gfx: TargetGraphics): void { this.clear(); // Set flag to force translucent geometry to be put into the opaque pass. this._addTranslucentAsOpaque = true; // Add the scene graphics. this.addGraphics(gfx.foreground); // Also add any pickable decorations. if (undefined !== gfx.decorations) this.addPickableDecorations(gfx.decorations); // Also background map is pickable this.addBackgroundMapGraphics(gfx.background); this._addTranslucentAsOpaque = false; this.setupClassificationByVolume(); this._layers.outputCommands(); } public initForRender(gfx: TargetGraphics): void { this.clear(); this.addGraphics(gfx.foreground); this.addBackgroundMapGraphics(gfx.background); this.addOverlayGraphics(gfx.overlays); const dynamics = gfx.dynamics; if (dynamics && dynamics.length > 0) this.addDecorations(dynamics); const dec = gfx.decorations; if (undefined !== dec) { this.addBackground(dec.viewBackground as Graphic); this.addSkyBox(dec.skyBox as Graphic); if (undefined !== dec.normal && 0 < dec.normal.length) this.addGraphics(dec.normal); if (undefined !== dec.world && 0 < dec.world.length) this.addWorldDecorations(dec.world); this.pushAndPopState(this.target.decorationsState, () => { if (undefined !== dec.viewOverlay && 0 < dec.viewOverlay.length) this.addDecorations(dec.viewOverlay, RenderPass.ViewOverlay); if (undefined !== dec.worldOverlay && 0 < dec.worldOverlay.length) this.addDecorations(dec.worldOverlay, RenderPass.WorldOverlay); }); } this.setupClassificationByVolume(); this._layers.outputCommands(); } public addPrimitive(prim: Primitive): void { // ###TODO Would be nice if we could detect outside active volume here, but active volume only applies to specific render passes // if (this.target.isGeometryOutsideActiveVolume(prim.cachedGeometry)) // return; if (undefined !== this._frustumPlanes) { // See if we can cull this primitive. if (RenderPass.Classification === prim.getRenderPass(this.target)) { const geom = prim.cachedGeometry; geom.computeRange(this._scratchRange); let frustum = Frustum.fromRange(this._scratchRange, this._scratchFrustum); frustum = frustum.transformBy(this.target.currentTransform, frustum); if (FrustumPlanes.Containment.Outside === this._frustumPlanes.computeFrustumContainment(frustum)) { return; } } } const command = new PrimitiveCommand(prim); this.addPrimitiveCommand(command); if (RenderPass.None === this._forcedRenderPass && prim.isEdge) { const vf: ViewFlags = this.target.currentViewFlags; if (vf.renderMode !== RenderMode.Wireframe && vf.hiddenEdges) this.addPrimitiveCommand(command, RenderPass.HiddenEdge); } } public addBranch(branch: Branch): void { this.pushAndPopBranch(branch, () => { branch.branch.entries.forEach((entry: RenderGraphic) => (entry as Graphic).addCommands(this)); }); } public computeBatchHiliteRenderPass(batch: Batch): RenderPass { let pass = RenderPass.Hilite; if (batch.graphic instanceof MeshGraphic) { const mg = batch.graphic; if (SurfaceType.VolumeClassifier === mg.surfaceType) pass = RenderPass.HiliteClassification; } else if (batch.graphic instanceof GraphicsArray) { const ga = batch.graphic; if (ga.graphics[0] instanceof MeshGraphic) { const mg = ga.graphics[0]; if (SurfaceType.VolumeClassifier === mg.surfaceType) pass = RenderPass.HiliteClassification; } else if (ga.graphics[0] instanceof Branch) { const b = ga.graphics[0]; if (b.branch.entries.length > 0 && b.branch.entries[0] instanceof MeshGraphic) { const mg = b.branch.entries[0]; if (SurfaceType.VolumeClassifier === mg.surfaceType) pass = RenderPass.HiliteClassification; } } } return pass; } public addBatch(batch: Batch): void { if (batch.locateOnly && !this.target.isReadPixelsInProgress) return; // Batches (aka element tiles) should only draw during ordinary (translucent or opaque) passes. // They may draw during both, or neither. // NB: This is no longer true - pickable overlay decorations are defined as Batches. Problem? // assert(RenderPass.None === this._forcedRenderPass); assert(!this._opaqueOverrides && !this._translucentOverrides); assert(undefined === this._curBatch); // If all features are overridden to be invisible, draw no graphics in this batch const overrides = batch.getOverrides(this.target); if (overrides.allHidden) return; if (!batch.range.isNull) { // ###TODO Would be nice if we could detect outside active volume here, but active volume only applies to specific render passes // if (this.target.isRangeOutsideActiveVolume(batch.range)) // return; if (undefined !== this._frustumPlanes) { let frustum = Frustum.fromRange(batch.range, this._scratchFrustum); frustum = frustum.transformBy(this.target.currentTransform, frustum); if (FrustumPlanes.Containment.Outside === this._frustumPlanes.computeFrustumContainment(frustum)) { return; } } } const classifier = this._stack.top.planarClassifier; this._batchState.push(batch, true); this.pushAndPop(new PushBatchCommand(batch), PopBatchCommand.instance, () => { if (this.currentViewFlags.transparency) { this._opaqueOverrides = overrides.anyOpaque; this._translucentOverrides = overrides.anyTranslucent; if (undefined !== classifier) { this._opaqueOverrides = this._opaqueOverrides || classifier.anyOpaque; this._translucentOverrides = this._translucentOverrides || classifier.anyTranslucent; } } // If we have an active volume classifier then force all batches for the reality data being classified into a special render pass. let savedForcedRenderPass = RenderPass.None; if (undefined !== this.target.activeVolumeClassifierModelId && batch.featureTable.modelId === this.target.activeVolumeClassifierModelId) { savedForcedRenderPass = this._forcedRenderPass; this._forcedRenderPass = RenderPass.VolumeClassifiedRealityData; } (batch.graphic as Graphic).addCommands(this); if (RenderPass.VolumeClassifiedRealityData === this._forcedRenderPass) this._forcedRenderPass = savedForcedRenderPass; // If the batch contains hilited features, need to render them in the hilite pass const anyHilited = overrides.anyHilited; const planarClassifierHilited = undefined !== classifier && classifier.anyHilited; if (anyHilited || planarClassifierHilited) (batch.graphic as Graphic).addHiliteCommands(this, planarClassifierHilited ? RenderPass.HilitePlanarClassification : this.computeBatchHiliteRenderPass(batch)); }); this._opaqueOverrides = this._translucentOverrides = false; this._batchState.pop(); } // Define a culling frustum. Commands associated with Graphics whose ranges do not intersect the frustum will be skipped. public setCheckRange(frustum: Frustum) { this._frustumPlanes = new FrustumPlanes(frustum); } // Clear the culling frustum. public clearCheckRange(): void { this._frustumPlanes = undefined; } private setupClassificationByVolume(): void { // To make it easier to process the classifiers individually, set up a secondary command list for them where they // are each separated by their own pushes & pops so that they can easily be drawn individually. This now supports // nested branches and batches. const groupedCmds = this._commands[RenderPass.Classification]; const byIndexCmds = this._commands[RenderPass.ClassificationByIndex]; const pushCommands: DrawCommands = []; // will contain current set of pushes ahead of a primitive for (const cmd of groupedCmds) { switch (cmd.opcode) { case "pushBranch": case "pushBatch": case "pushState": pushCommands.push(cmd); break; case "drawPrimitive": for (const pushCmd of pushCommands) { byIndexCmds.push(pushCmd); } byIndexCmds.push(cmd); for (let i = pushCommands.length - 1; i >= 0; --i) { if ("pushBatch" === pushCommands[i].opcode) byIndexCmds.push(PopBatchCommand.instance); else // should be eith pushBranch or pushState opcode byIndexCmds.push(PopBranchCommand.instance); } break; case "popBatch": case "popBranch": pushCommands.pop(); break; } } } }
the_stack
import { expect } from "chai"; import * as React from "react"; import * as sinon from "sinon"; import { render } from "@testing-library/react"; import { ActivityMessageDetails, ActivityMessageEndReason, NotifyMessageDetails, OutputMessagePriority, OutputMessageType, } from "@itwin/core-frontend"; import { MessageSeverity, WidgetState } from "@itwin/appui-abstract"; import { MessageHyperlink, MessageLayout, MessageProgress, Toast } from "@itwin/appui-layout-react"; import { IconButton } from "@itwin/itwinui-react"; import { ToastPresentation } from "@itwin/itwinui-react/cjs/core/Toast/Toast"; import { AppNotificationManager, ConfigurableCreateInfo, ConfigurableUiControlType, MessageCenterField, StatusBar, StatusBarCenterSection, StatusBarLeftSection, StatusBarRightSection, StatusBarSpaceBetween, StatusBarWidgetControl, StatusBarWidgetControlArgs, WidgetDef, } from "../../appui-react"; import TestUtils, { mount } from "../TestUtils"; import { MessageManager } from "../../appui-react/messages/MessageManager"; import { StatusMessagesContainer } from "../../appui-react/messages/StatusMessagesContainer"; describe("StatusBar", () => { class AppStatusBarWidgetControl extends StatusBarWidgetControl { constructor(info: ConfigurableCreateInfo, options: any) { super(info, options); } public getReactNode({ isInFooterMode, onOpenWidget, openWidget }: StatusBarWidgetControlArgs): React.ReactNode { return ( <> <MessageCenterField isInFooterMode={isInFooterMode} onOpenWidget={onOpenWidget} openWidget={openWidget} /> </> ); } } let widgetControl: StatusBarWidgetControl | undefined; let notifications: AppNotificationManager; before(async () => { await TestUtils.initializeUiFramework(); const statusBarWidgetDef = new WidgetDef({ classId: AppStatusBarWidgetControl, defaultState: WidgetState.Open, isFreeform: false, isStatusBar: true, }); widgetControl = statusBarWidgetDef.getWidgetControl(ConfigurableUiControlType.StatusBarWidget) as StatusBarWidgetControl; notifications = new AppNotificationManager(); }); after(() => { TestUtils.terminateUiFramework(); }); beforeEach(() => { MessageManager.activeMessageManager.initialize(); }); it("StatusBar should mount", () => { const wrapper = mount(<StatusBar widgetControl={widgetControl} isInFooterMode={true} />); wrapper.unmount(); }); it("StatusBar should render a Toast message", async () => { const wrapper = mount(<StatusBar widgetControl={widgetControl} isInFooterMode={true} />); const details = new NotifyMessageDetails(OutputMessagePriority.None, "A brief message.", "A detailed message."); notifications.outputMessage(details); wrapper.update(); expect(wrapper.find(Toast).length).to.eq(1); // eslint-disable-line deprecation/deprecation expect(wrapper.find(ToastPresentation).length).to.eq(1); expect(wrapper.find(MessageLayout).length).to.eq(1); wrapper.unmount(); }); it("StatusBar should render a Toast message and animate out", async () => { const wrapper = mount(<StatusBar widgetControl={widgetControl} isInFooterMode={true} />); const details = new NotifyMessageDetails(OutputMessagePriority.Warning, "A brief message.", "A detailed message."); notifications.outputMessage(details); wrapper.update(); expect(wrapper.find(Toast).length).to.eq(1); // eslint-disable-line deprecation/deprecation const toast = wrapper.find(".nz-toast"); expect(toast.length).to.eq(1); toast.simulate("transitionEnd"); wrapper.update(); expect(wrapper.find(".nz-toast").length).to.eq(0); wrapper.unmount(); }); it("StatusBar should render a Sticky message", () => { const wrapper = mount(<StatusBar widgetControl={widgetControl} isInFooterMode={true} />); const details = new NotifyMessageDetails(OutputMessagePriority.Info, "A brief message.", "A detailed message.", OutputMessageType.Sticky); notifications.outputMessage(details); wrapper.update(); expect(wrapper.find(ToastPresentation).length).to.eq(1); expect(wrapper.find(MessageLayout).length).to.eq(1); expect(wrapper.find(IconButton).length).to.eq(1); wrapper.unmount(); }); it("Sticky message should close on button click", () => { const fakeTimers = sinon.useFakeTimers(); const wrapper = mount(<StatusBar widgetControl={widgetControl} isInFooterMode={true} />); const details = new NotifyMessageDetails(OutputMessagePriority.Error, "A brief message.", "A detailed message.", OutputMessageType.Sticky); notifications.outputMessage(details); wrapper.update(); expect(wrapper.find(IconButton).length).to.eq(1); wrapper.find(IconButton).simulate("click"); fakeTimers.tick(1000); fakeTimers.restore(); wrapper.update(); expect(wrapper.find(ToastPresentation).length).to.eq(0); wrapper.unmount(); }); it("StatusBar should render an Activity message", () => { const wrapper = mount(<StatusBar widgetControl={widgetControl} isInFooterMode={true} />); const details = new ActivityMessageDetails(true, true, false); notifications.setupActivityMessage(details); notifications.outputActivityMessage("Message text", 50); wrapper.update(); expect(wrapper.find(ToastPresentation).length).to.eq(1); expect(wrapper.find(MessageProgress).length).to.eq(1); notifications.endActivityMessage(ActivityMessageEndReason.Completed); wrapper.update(); expect(wrapper.find(ToastPresentation).length).to.eq(0); wrapper.unmount(); }); it("Activity message should be canceled", () => { const wrapper = mount(<StatusBar widgetControl={widgetControl} isInFooterMode={true} />); const details = new ActivityMessageDetails(true, true, true); notifications.setupActivityMessage(details); notifications.outputActivityMessage("Message text", 50); wrapper.update(); expect(wrapper.find(ToastPresentation).length).to.eq(1); wrapper.find(MessageHyperlink).simulate("click"); wrapper.update(); expect(wrapper.find(ToastPresentation).length).to.eq(0); wrapper.unmount(); }); it("Activity message should be dismissed", () => { const wrapper = mount(<StatusBar widgetControl={widgetControl} isInFooterMode={true} />); const details = new ActivityMessageDetails(true, true, true); notifications.setupActivityMessage(details); notifications.outputActivityMessage("Message text", 50); wrapper.update(); expect(wrapper.find(ToastPresentation).length).to.eq(1); wrapper.find(IconButton).simulate("click"); wrapper.update(); expect(wrapper.find(ToastPresentation).length).to.eq(0); wrapper.unmount(); }); it("StatusBar should render Toast, Sticky & Activity messages", async () => { const wrapper = mount(<StatusBar widgetControl={widgetControl} isInFooterMode={true} />); const details1 = new NotifyMessageDetails(OutputMessagePriority.None, "A brief message.", "A detailed message."); notifications.outputMessage(details1); const details2 = new NotifyMessageDetails(OutputMessagePriority.None, "A brief message.", "A detailed message.", OutputMessageType.Sticky); notifications.outputMessage(details2); const details3 = new ActivityMessageDetails(true, true, true); notifications.setupActivityMessage(details3); notifications.outputActivityMessage("Message text", 50); wrapper.update(); expect(wrapper.find(ToastPresentation).length).to.eq(3); wrapper.unmount(); }); it("StatusBar should render maximum of 3 Sticky messages", async () => { MessageManager.maxDisplayedStickyMessages = 3; const wrapper = mount(<StatusBar widgetControl={widgetControl} isInFooterMode={true} />); const details1 = new NotifyMessageDetails(OutputMessagePriority.None, "A brief message 1.", undefined, OutputMessageType.Sticky); notifications.outputMessage(details1); const details2 = new NotifyMessageDetails(OutputMessagePriority.None, "A brief message 2.", undefined, OutputMessageType.Sticky); notifications.outputMessage(details2); const details3 = new NotifyMessageDetails(OutputMessagePriority.None, "A brief message 3.", undefined, OutputMessageType.Sticky); notifications.outputMessage(details3); wrapper.update(); expect(wrapper.find(ToastPresentation).length).to.eq(3); const details4 = new NotifyMessageDetails(OutputMessagePriority.None, "A brief message 4.", undefined, OutputMessageType.Sticky); notifications.outputMessage(details4); wrapper.update(); expect(wrapper.find(ToastPresentation).length).to.eq(3); expect(wrapper.find(IconButton).length).to.eq(3); wrapper.unmount(); }); it("StatusBar should not render a Pointer message", () => { const wrapper = mount(<StatusBar widgetControl={widgetControl} isInFooterMode={true} />); const details = new NotifyMessageDetails(OutputMessagePriority.Info, "A brief message.", "A detailed message.", OutputMessageType.Pointer); notifications.outputMessage(details); wrapper.update(); expect(wrapper.find(ToastPresentation).length).to.eq(0); wrapper.unmount(); }); it("StatusBar should clear messages", () => { const wrapper = mount(<StatusBar widgetControl={widgetControl} isInFooterMode={true} />); const details = new NotifyMessageDetails(OutputMessagePriority.Info, "A brief message.", "A detailed message.", OutputMessageType.Sticky); notifications.outputMessage(details); wrapper.update(); expect(wrapper.find(ToastPresentation).length).to.eq(1); MessageManager.clearMessages(); wrapper.update(); expect(wrapper.find(ToastPresentation).length).to.eq(0); wrapper.unmount(); }); it("StatusMessageRenderer should render empty correctly", () => { const wrapper = mount(<StatusMessagesContainer messages={[]} activityMessageInfo={undefined} isActivityMessageVisible={false} toastTarget={null} closeMessage={() => { }} cancelActivityMessage={() => { }} dismissActivityMessage={() => { }} />); expect(wrapper.find("div").length).to.eq(0); wrapper.unmount(); }); it("StatusBarSpaceBetween should render correctly", () => { const wrapper = mount(<StatusBarSpaceBetween>Hello</StatusBarSpaceBetween>); expect(wrapper.find("div.uifw-statusbar-space-between").length).to.eq(1); wrapper.unmount(); }); it("StatusBarLeftSection should render correctly", () => { const wrapper = mount(<StatusBarLeftSection>Hello</StatusBarLeftSection>); expect(wrapper.find("div.uifw-statusbar-left").length).to.eq(1); wrapper.unmount(); }); it("StatusBarCenterSection should render correctly", () => { const wrapper = mount(<StatusBarCenterSection>Hello</StatusBarCenterSection>); expect(wrapper.find("div.uifw-statusbar-center").length).to.eq(1); wrapper.unmount(); }); it("StatusBarRightSection should render correctly", () => { const wrapper = mount(<StatusBarRightSection>Hello</StatusBarRightSection>); expect(wrapper.find("div.uifw-statusbar-right").length).to.eq(1); wrapper.unmount(); }); describe("<StatusMessagesContainer />", () => { const sandbox = sinon.createSandbox(); const messages = [ { id: "one", messageDetails: new NotifyMessageDetails(OutputMessagePriority.Info, "message1", "Detailed message1", OutputMessageType.Toast), severity: MessageSeverity.Information }, { id: "two", messageDetails: new NotifyMessageDetails(OutputMessagePriority.Info, "message2", "Detailed message3", OutputMessageType.Toast), severity: MessageSeverity.Information }, { id: "three", messageDetails: new NotifyMessageDetails(OutputMessagePriority.Info, "message3", "Detailed message3", OutputMessageType.Sticky), severity: MessageSeverity.Question }, ]; afterEach(() => { sandbox.restore(); }); it("will render with message container height < window.innerHeight, not scrollable", () => { sandbox.stub(window, "innerHeight").get(() => 1000); // eslint-disable-next-line prefer-arrow/prefer-arrow-functions sandbox.stub(Element.prototype, "getBoundingClientRect").callsFake(function (this: HTMLElement) { if (this.classList.contains("uifw-statusbar-messages-container")) { return DOMRect.fromRect({ width: 200, height: 200 }); } return new DOMRect(); }); const renderedComponent = render(<StatusMessagesContainer messages={messages} activityMessageInfo={undefined} isActivityMessageVisible={false} toastTarget={null} closeMessage={() => { }} cancelActivityMessage={() => { }} dismissActivityMessage={() => { }} />); expect(renderedComponent.container.querySelectorAll("div.uifw-statusbar-messages-container.uifw-scrollable").length).to.eq(0); renderedComponent.unmount(); }); it("will render with message container height > window.innerHeight, scrollable", () => { sandbox.stub(window, "innerHeight").get(() => 200); // eslint-disable-next-line prefer-arrow/prefer-arrow-functions sandbox.stub(Element.prototype, "getBoundingClientRect").callsFake(function (this: HTMLElement) { if (this.classList.contains("uifw-statusbar-messages-container")) { return DOMRect.fromRect({ width: 200, height: 300 }); } return new DOMRect(); }); const renderedComponent = render(<StatusMessagesContainer messages={messages} activityMessageInfo={undefined} isActivityMessageVisible={false} toastTarget={null} closeMessage={() => { }} cancelActivityMessage={() => { }} dismissActivityMessage={() => { }} />); expect(renderedComponent.container.querySelectorAll("div.uifw-statusbar-messages-container.uifw-scrollable").length).to.eq(1); renderedComponent.unmount(); }); }); });
the_stack
import React, { useEffect } from "react" import {withPrefix} from "gatsby" import { Layout } from "../../components/layout" import { Intl } from "../../components/Intl" import { VersionBar } from "../../components/VersionBar" import * as Adopt from "../../components/index/AdoptSteps" import { MigrationStories, GitHubBar, OSS } from "../../components/index/MigrationStories" import { indexCopy } from "../../copy/en/index2" import { createInternational } from "../../lib/createInternational" import { useIntl } from "react-intl" import "../pages/css/index.scss" import "../pages/css/documentation.scss" import { createIntlLink } from "../../components/IntlLink" import { AboveTheFold } from "../../components/index/AboveTheFold" import {Code as Grad1} from "../../components/index/twoslash/generated/IndexAdoptGrad1" import {Code as Grad2} from "../../components/index/twoslash/generated/IndexAdoptGrad2" import {Code as Del1} from "../../components/index/twoslash/generated/Index2Del1TS" import {Code as Del2} from "../../components/index/twoslash/generated/Index2Del2RM" import {Code as Del3} from "../../components/index/twoslash/generated/Index2Del3JS.js" const Section = (props: { children: any, color: string, className?: string }) => <div key={props.color} className={props.color + " " + (props.className ?? "")}><div className="container">{props.children}</div></div> const Row = (props: { children: any, className?: string, key?: string }) => <div key={props.key} className={[props.className, "row"].join(" ")}>{props.children}</div> const Col = (props: { children: any, className?: string }) => <div className={[props.className, "col1"].join(" ")}>{props.children}</div> const Col2 = (props: { children: any }) => <div className="col2">{props.children}</div> const Half = (props: { children: any, className?: string }) => <div className={[props.className, "half"].join(" ")}>{props.children}</div> type Props = { pageContext: any } const Index: React.FC<Props> = (props) => { const i = createInternational<typeof indexCopy>(useIntl()) const Link = createIntlLink(props.pageContext.lang) useEffect(() => { // NOOP on tiny devices where we need to re-orient the arrows. if (window.innerWidth < 900) return const adopt = document.getElementById("adopt-gradually-content")! adopt.classList.remove("no-js") adopt.classList.add("fancy-scroll") updateOnScroll(i)() // Handles setting the scroll window.addEventListener("scroll", updateOnScroll(i), { passive: true, capture: true }); return () => { window.removeEventListener("scroll", updateOnScroll(i)) } }); /** Basically a <p> with bold set up */ const P = (props: { ikey: keyof typeof indexCopy }) => <p key={props.ikey}>{i(props.ikey, { strong: (...chunk) => <strong>{chunk}</strong> })}</p> const GetStarted = (props: { href: string, title: any, subtitle: any, classes: string }) => ( <Link to={props.href} className={"get-started " + props.classes} > <div> <div className="fluid-button-title">{i(props.title)}</div> <div className="fluid-button-subtitle">{i(props.subtitle)}</div> </div> <div> <svg width="14" height="23" viewBox="0 0 14 23" fill="none" xmlns="http://www.w3.org/2000/svg"> <path d="M2 2L11 11.5L2 21" stroke="black" strokeWidth="4"/> </svg> </div> </Link> ) return ( <Layout title="JavaScript With Syntax For Types." description="TypeScript extends JavaScript by adding types to the language. TypeScript speeds up your development experience by catching errors and providing fixes before you even run your code." lang={props.pageContext.lang} suppressCustomization suppressDocRecommendations> <div id="index-2"> <Section color="blue" className="headline"> <AboveTheFold /> </Section> <VersionBar /> <Section color="white"> <h2>{i("index_2_what_is")}</h2> <Row> <Col key='what is js'> <h3>{i("index_2_what_is_js")}</h3> <P ikey="index_2_what_is_js_copy" /> </Col> <Col key='you can trust typescript'> <h3>{i("index_2_trust")}</h3> <P ikey="index_2_trust_copy" /> </Col> <Col key='TS improves JS'> <h3>{i("index_2_scale")}</h3> <P ikey="index_2_scale_copy" /> </Col> </Row> </Section> <Section color="light-grey" className="get-started-section"> <h2 id='get_started'>{i("index_2_started_title")}</h2> <Row> <Col key='handbook'> <GetStarted href="/docs/handbook/intro.html" classes="tall handbook" title="index_2_started_handbook" subtitle="index_2_started_handbook_blurb" /> </Col> <Col key='playground'> <GetStarted href="/play" classes="tall playground" title="nav_playground" subtitle="index_2_playground_blurb" /> </Col> <Col key='download'> <GetStarted href="/download" classes="tall download" title="nav_download" subtitle="index_2_install" /> </Col> </Row> </Section> <div id="get-started" className="animate"> <Section color="white"> <Half> <div id='adopt-gradually-content' className='no-js'> <h2 id='adopt-gradually'>{i("index_2_adopt")}</h2> <div id='adopt-step-slider'> <p id='adopt-step-blurb'></p> <Row> <Col key='handbook'> <P ikey="index_2_adopt_blurb_1" /> </Col> <Col key='playground'> <P ikey="index_2_adopt_blurb_2" /> </Col> </Row> <Row> <Col key='main'> <Adopt.StepOne i={i} /> <Adopt.StepTwo i={i} /> <Adopt.StepThree i={i} /> <Adopt.StepFour i={i} /> <Adopt.StepperAll /> </Col> </Row> </div> </div> </Half> </Section> </div> <Section color="light-grey"> <Row> <Col key='title'> <h3 id='describe-your-data'>{i("index_2_describe")}</h3> <P ikey="index_2_describe_blurb1" /> <P ikey="index_2_describe_blurb2" /> </Col> <Col key='ex1'> <Grad1 /> </Col> <Col key='ex2'> <Grad2 /> </Col> </Row> </Section> <Section color="white" className="via-delete"> <h2 id='via-delete-key'>{i("index_2_transform")}</h2> <Row> <Col key='title'> <Del1 /> <P ikey="index_2_transform_1"/> </Col> <Col key='ex1'> <Del2 /> <P ikey="index_2_transform_2"/> </Col> <Col key='ex2'> <Del3 /> <P ikey="index_2_transform_3"/> </Col> </Row> </Section> <Section color="light-grey" className="migrations"> <h2 id='migration_title'>{i("index_2_migration_title")}</h2> <div className="github-bar left"> <GitHubBar left /> </div> <div className="github-bar right"> <GitHubBar left={false} /> </div> <MigrationStories /> </Section> <Section color="dark-green" className="show-only-small"> <h3>{i("index_2_migration_oss")}</h3> <OSS /> </Section> <Section color="white"> <h2>{i("index_2_loved_by")} </h2> <Row> <Col key='TS improves JS'> <img src={withPrefix("/images/index/stack-overflow.svg")} alt="Image of the stack overflow logo, and a graph showing TypeScript as the 2nd most popular language" /> <div style={{ width: "60%", marginTop: "20px" }}> <p>{i("index_2_loved_stack", { strong: (...chunk) => <strong>{chunk}</strong>, so: (...chunk) => <a href="https://insights.stackoverflow.com/survey/2020#most-loved-dreaded-and-wanted" target="_blank">{chunk}</a> })}</p> </div> </Col> <div style={{ backgroundColor: "black", width: "1px" }} /> <Col key='you'> <Row> <div style={{ width: "160px", textAlign: "center" }}> <img src={withPrefix("/images/index/state-of-js.svg")} alt="Logo of the State of JS survey"/> </div> <div style={{ flex: 1 }}> <p>{i("index_2_loved_state_js", { strong: (...chunk) => <strong>{chunk}</strong>, js: (...chunk) => <a href="https://2020.stateofjs.com/en-US/technologies/javascript-flavors/" target="_blank">{chunk}</a> })}</p> <p>{i("index_2_loved_state_js2", { strong: (...chunk) => <strong>{chunk}</strong> })}</p> </div> </Row> </Col> </Row> </Section> <Section color="blue" className="get-started-section"> <h2 id='get_started_blue'>{i("index_2_started_title")}</h2> <Row> <Col key='handbook'> <GetStarted href="/docs/handbook/intro.html" classes="short handbook" title="index_2_started_handbook" subtitle="index_2_started_handbook_blurb" /> </Col> <Col key='playground'> <GetStarted href="/play" classes="short playground" title="nav_playground" subtitle="index_2_playground_blurb" /> </Col> <Col key='download'> <GetStarted href="/download" classes="short download" title="nav_download" subtitle="index_2_install" /> </Col> </Row> </Section> </div> </Layout >) } export default (props: Props) => <Intl locale={props.pageContext.lang}><Index {...props} /></Intl> // Recurses up to get the y pos of a node // https://stackoverflow.com/questions/442404/retrieve-the-position-x-y-of-an-html-element-relative-to-the-browser-window function getOffset( el ) { var _x = 0; var _y = 0; while( el && !isNaN( el.offsetLeft ) && !isNaN( el.offsetTop ) ) { _x += el.offsetLeft - el.scrollLeft; _y += el.offsetTop - el.scrollTop; el = el.offsetParent; } return { top: _y, left: _x }; } const updateOnScroll = (i: any) => () => { const adopt = document.getElementById("adopt-gradually-content") as HTMLDivElement if (!adopt) return const offset = getOffset(adopt).top const fromTop = window.scrollY const height = adopt.scrollHeight const quarterHeight = (height - 200)/4 const startPoint = 100 const y = fromTop - offset + startPoint const samples = adopt.getElementsByClassName("adopt-step") as HTMLCollectionOf<HTMLDivElement> let index: 0 | 1| 2| 3 = 0 if (y >= 0 && y < quarterHeight) index = 1 else if (y >= (quarterHeight) && y < (quarterHeight * 2)) index = 2 else if (y >= (quarterHeight * 2)) index =3 samples.item(0)!.style.opacity = index === 0 ? "1" : "0" samples.item(1)!.style.opacity = index === 1 ? "1" : "0" samples.item(2)!.style.opacity = index === 2 ? "1" : "0" samples.item(3)!.style.opacity = index === 3 ? "1" : "0" const stepper = document.getElementById("global-stepper") as HTMLDivElement stepper.children.item(0)!.classList.toggle("active", index === 0) stepper.children.item(1)!.classList.toggle("active", index === 1) stepper.children.item(2)!.classList.toggle("active", index === 2) stepper.children.item(3)!.classList.toggle("active", index === 3) const msg = ["index_2_migrate_1", "index_2_migrate_2", "index_2_migrate_3", "index_2_migrate_4"] const blurb = document.getElementById("adopt-step-blurb")! blurb.innerText = i(msg[index]) }
the_stack
'use strict'; import { commands, workspace, window, Uri, ThemableDecorationAttachmentRenderOptions, DecorationInstanceRenderOptions, DecorationOptions, OverviewRulerLane, Disposable, ExtensionContext, Range, QuickPickItem, TextDocument, TextEditor, TextEditorSelectionChangeEvent, WorkspaceFolder, MarkdownString } from 'vscode'; import * as Path from 'path'; import * as fs from 'fs'; import { PerforceService } from './PerforceService'; import { Display } from './Display'; import { Utils } from './Utils'; import { PerforceSCMProvider } from './ScmProvider'; export namespace PerforceCommands { export function registerCommands() { commands.registerCommand('perforce.add', addOpenFile); commands.registerCommand('perforce.edit', editOpenFile); commands.registerCommand('perforce.delete', deleteOpenFile); commands.registerCommand('perforce.revert', revert); commands.registerCommand('perforce.diff', diff); commands.registerCommand('perforce.diffRevision', diffRevision); commands.registerCommand('perforce.annotate', annotate); commands.registerCommand('perforce.opened', opened); commands.registerCommand('perforce.logout', logout); commands.registerCommand('perforce.login', login); commands.registerCommand('perforce.showOutput', showOutput); commands.registerCommand('perforce.menuFunctions', menuFunctions); } function addOpenFile() { var editor = window.activeTextEditor; if(!checkFileSelected()) { return false; } if(!editor || !editor.document) { return false; } var fileUri = editor.document.uri; if(checkFolderOpened()) { add(fileUri); } else { add(fileUri, Path.dirname(fileUri.fsPath)); } } export function add(fileUri: Uri, directoryOverride?: string) { const args = '"' + Utils.expansePath(fileUri.fsPath) + '"'; PerforceService.execute(fileUri, "add", (err, stdout, stderr) => { PerforceService.handleCommonServiceResponse(err, stdout, stderr); if(!err) { Display.showMessage("file opened for add"); } }, args, directoryOverride); } function editOpenFile() { var editor = window.activeTextEditor; if(!checkFileSelected()) { return false; } if (!editor || !editor.document) { return false; } var fileUri = editor.document.uri; //If folder not opened, run p4 in files folder. if(checkFolderOpened()) { edit(fileUri); } else { edit(fileUri, Path.dirname(fileUri.fsPath)); } } export function edit(fileUri: Uri, directoryOverride?: string): Promise<boolean> { return new Promise((resolve, reject) => { const args = '"' + Utils.expansePath(fileUri.fsPath) + '"'; PerforceService.execute(fileUri, "edit", (err, stdout, stderr) => { PerforceService.handleCommonServiceResponse(err, stdout, stderr); if(!err) { Display.showMessage("file opened for edit"); } resolve(!err); }, args, directoryOverride); }); } function deleteOpenFile() { var editor = window.activeTextEditor; if(!checkFileSelected()) { return false; } if(!editor || !editor.document) { return false; } revert(); var fileUri = editor.document.uri; p4delete(fileUri); } export function p4delete(fileUri: Uri) { const args = '"' + Utils.expansePath(fileUri.fsPath) + '"'; PerforceService.execute(fileUri, "delete", (err, stdout, stderr) => { PerforceService.handleCommonServiceResponse(err, stdout, stderr); if(!err) { Display.showMessage("file marked for delete"); } }, args); } export function revert() { var editor = window.activeTextEditor; if(!checkFileSelected()) { return false; } if (!editor || !editor.document) { return false; } //If folder not opened, overrided p4 directory var fileUri = editor.document.uri var directoryOverride; if(!checkFolderOpened()) { directoryOverride = Path.dirname(fileUri.fsPath); } const args = '"' + Utils.expansePath(fileUri.fsPath) + '"'; PerforceService.execute(fileUri, "revert", (err, stdout, stderr) => { PerforceService.handleCommonServiceResponse(err, stdout, stderr); if(!err) { Display.showMessage("file reverted"); } }, args, directoryOverride); } export function diff(revision?: number) { var editor = window.activeTextEditor; if(!checkFileSelected()) { return false; } if(!checkFolderOpened()) { return false; } if (!editor || !editor.document) { return false; } var doc = editor.document; if(!doc.isUntitled) { Utils.getFile('print', doc.uri, revision).then((tmpFile: string) => { var tmpFileUri = Uri.file(tmpFile) var revisionLabel = !revision || isNaN(revision) ? 'Most Recent Revision' : `Revision #${revision}`; commands.executeCommand('vscode.diff', tmpFileUri, doc.uri, Path.basename(doc.uri.fsPath) + ' - Diff Against ' + revisionLabel); }, (err) => { Display.showError(err.toString()); }) } } export function diffRevision() { var editor = window.activeTextEditor; if (!checkFileSelected()) { return false; } if (!checkFolderOpened()) { return false; } if (!editor || !editor.document) { return false; } var doc = editor.document; const args = '-s "' + Utils.expansePath(doc.uri.fsPath) + '"'; PerforceService.execute(doc.uri, 'filelog', (err, stdout, stderr) => { if (err) { Display.showError(err.message); } else if (stderr) { Display.showError(stderr.toString()); } else { let revisions = stdout.split('\n'); let revisionsData: QuickPickItem[] = []; revisions.shift(); // remove the first line - filename revisions.forEach(revisionInfo => { if (revisionInfo.indexOf('... #') === -1) return; let splits = revisionInfo.split(' '); let rev = splits[1].substring(1); // splice 1st character '#' let change = splits[3]; let label = `#${rev} change: ${change}`; let description = revisionInfo.substring(revisionInfo.indexOf(splits[9]) + splits[9].length + 1); revisionsData.push({ label, description }); }); window.showQuickPick(revisionsData).then( revision => { if (revision) { diff(parseInt(revision.label.substring(1))); } }) } }, args); } export async function annotate() { var editor = window.activeTextEditor; if (!checkFileSelected()) { return false; } if (!editor || !editor.document) { return false; } const doc = editor.document; const conf = workspace.getConfiguration('perforce') const cl = conf.get('annotate.changelist'); const usr = conf.get('annotate.user'); const swarmHost = conf.get('swarmHost'); let args = '-q'; if (cl) args += 'c'; if (usr) args += 'u'; const decorationType = window.createTextEditorDecorationType({ isWholeLine: true, before: { margin: '0 1.75em 0 0' } }); let decorateColors: string[] = ['rgb(153, 153, 153)', 'rgb(103, 103, 103)' ]; let decorations: DecorationOptions[] = []; let colorIndex = 0; let lastNum = ''; const output: string = await Utils.runCommandForFile('annotate', doc.uri, undefined, args); const annotations = output.split(/\r?\n/); for (let i = 0, n = annotations.length; i < n; ++i) { const matches = annotations[i].match(usr ? /^(\d+): (\S+ \S+)/ : /^(\d+): /); if(matches) { const num = matches[1]; const hoverMessage = swarmHost ? new MarkdownString(`[${num + ' ' + matches[2]}](${swarmHost}/changes/${num})`) : matches[2]; if (num !== lastNum) { lastNum = num; colorIndex = (colorIndex + 1) % decorateColors.length } const before: ThemableDecorationAttachmentRenderOptions = { contentText: (cl ? '' : '#') + num, color: decorateColors[colorIndex] }; const renderOptions: DecorationInstanceRenderOptions = { before }; decorations.push({ range: new Range(i, 0, i, 0), hoverMessage, renderOptions }); } } let p4Uri = doc.uri; let query = encodeURIComponent('-q'); p4Uri = p4Uri.with({ scheme: 'perforce', authority: 'print', path: doc.uri.path, query: query }); workspace.openTextDocument(p4Uri).then(d => { window.showTextDocument(d).then(e => { e.setDecorations(decorationType, decorations); }) }) } export function opened() { if(!checkFolderOpened()) { return false; } if (!workspace.workspaceFolders) { return false; } let resource = workspace.workspaceFolders[0].uri; if (workspace.workspaceFolders.length > 1 ) { // try to find the proper workspace if (window.activeTextEditor && window.activeTextEditor.document) { let wksFolder = workspace.getWorkspaceFolder(window.activeTextEditor.document.uri); if (wksFolder) { resource = wksFolder.uri; } } } PerforceService.execute(resource, 'opened', (err, stdout, stderr) => { if(err){ Display.showError(err.message); } else if(stderr) { Display.showError(stderr.toString()); } else { var opened = stdout.toString().trim().split('\n') if (opened.length === 0) { return false; } var options = opened.map((file) => { return { description: file, label: Path.basename(file) } }); window.showQuickPick(options, {matchOnDescription: true}).then(selection => { if (!selection) { return false; } let depotPath = selection.description; var whereFile = depotPath.substring(0, depotPath.indexOf('#')); where(whereFile).then((result) => { // https://www.perforce.com/perforce/r14.2/manuals/cmdref/p4_where.html var results = result.split(' '); if (results.length >= 3) { var fileToOpen = results[2].trim(); workspace.openTextDocument(Uri.file(fileToOpen)).then((document) => { window.showTextDocument(document); }, (reason) => { Display.showError(reason); }); } }).catch((reason) => { Display.showError(reason); }); }); } }); } function where(file: string): Promise<string> { return new Promise((resolve, reject) => { if(!checkFolderOpened()) { reject(); return; } let resource = Uri.file(file); const args = '"' + file + '"'; PerforceService.execute(resource, 'where', (err, stdout, stderr) => { if(err){ Display.showError(err.message); reject(err); } else if(stderr) { Display.showError(stderr.toString()); reject(stderr); } else { resolve(stdout.toString()); } }, args); }); } // Try to guess the proper workspace to use function guessWorkspaceUri(): Uri { if (window.activeTextEditor && !window.activeTextEditor.document.isUntitled) { let wksFolder = workspace.getWorkspaceFolder( window.activeTextEditor.document.uri ) if (wksFolder) { return wksFolder.uri; } } if (workspace.workspaceFolders) { return workspace.workspaceFolders[0].uri; } else { return Uri.parse(''); } } export function logout() { let resource = guessWorkspaceUri(); PerforceService.execute(resource, 'logout', (err, stdout, stderr) => { if(err) { Display.showError(err.message); return false; } else if(stderr) { Display.showError(stderr.toString()); return false; } else { Display.showMessage("Logout successful"); Display.updateEditor(); return true; } }); } export function login() { let resource = guessWorkspaceUri(); PerforceService.execute(resource, 'login', (err, stdout, stderr) => { if(err || stderr) { window.showInputBox({'prompt': 'Enter password', 'password': true}).then(passwd => { PerforceService.execute(resource, 'login', (err, stdout, stderr) => { if (err) { Display.showError(err.message); return false; } else if (stderr) { Display.showError(stderr.toString()); return false; } else { Display.showMessage("Login successful"); Display.updateEditor(); return true; } }, undefined, undefined, passwd); }); } else { Display.showMessage("Login successful"); Display.updateEditor(); return true; } }, '-s'); } export function showOutput() { Display.channel.show(); } export function menuFunctions() { var items: QuickPickItem[] = []; items.push({ label: "add", description: "Open a new file to add it to the depot" }); items.push({ label: "edit", description: "Open an existing file for edit" }); items.push({ label: "revert", description: "Discard changes from an opened file" }); items.push({ label: "diff", description: "Display diff of client file with depot file" }); items.push({ label: "diffRevision", description: "Display diff of client file with depot file at a specific revision" }); items.push({ label: "annotate", description: "Print file lines and their revisions" }); items.push({ label: "info", description: "Display client/server information" }); items.push({ label: "opened", description: "View 'open' files and open one in editor" }); items.push({ label: "login", description: "Log in to Perforce" }); items.push({ label: "logout", description: "Log out from Perforce" }); window.showQuickPick(items, {matchOnDescription: true, placeHolder: "Choose a Perforce command:"}).then(function (selection) { if(selection == undefined) return; switch (selection.label) { case "add": addOpenFile(); break; case "edit": editOpenFile(); break; case "revert": revert(); break; case "diff": diff(); break; case "diffRevision": diffRevision(); break; case "annotate": annotate(); break; case "opened": opened(); break; case "login": login(); break; case "logout": logout(); break; default: break; } }); } function checkFileSelected() { if(!window.activeTextEditor) { Display.showMessage("No file selected"); return false; } return true; } export function checkFolderOpened() { if (workspace.workspaceFolders === undefined) { Display.showMessage("No folder selected\n"); return false; } return true; } }
the_stack
import * as commands from 'app/client/components/commands'; import {GristDoc, IExtraTool, TabContent} from 'app/client/components/GristDoc'; import * as RefSelect from 'app/client/components/RefSelect'; import * as ViewConfigTab from 'app/client/components/ViewConfigTab'; import {domAsync} from 'app/client/lib/domAsync'; import * as imports from 'app/client/lib/imports'; import {createSessionObs} from 'app/client/lib/sessionObs'; import {reportError} from 'app/client/models/AppModel'; import {ViewSectionRec} from 'app/client/models/DocModel'; import {GridOptions} from 'app/client/ui/GridOptions'; import {attachPageWidgetPicker, IPageWidget, toPageWidget} from 'app/client/ui/PageWidgetPicker'; import {linkFromId, linkId, selectBy} from 'app/client/ui/selectBy'; import {VisibleFieldsConfig} from 'app/client/ui/VisibleFieldsConfig'; import {IWidgetType, widgetTypes} from 'app/client/ui/widgetTypes'; import {basicButton, primaryButton} from 'app/client/ui2018/buttons'; import {colors, testId, vars} from 'app/client/ui2018/cssVars'; import {textInput} from 'app/client/ui2018/editableLabel'; import {IconName} from 'app/client/ui2018/IconList'; import {icon} from 'app/client/ui2018/icons'; import {select} from 'app/client/ui2018/menus'; import {FieldBuilder} from 'app/client/widgets/FieldBuilder'; import {StringUnion} from 'app/common/StringUnion'; import {bundleChanges, Computed, Disposable, dom, domComputed, DomContents, DomElementArg, DomElementMethod, IDomComponent} from 'grainjs'; import {MultiHolder, Observable, styled, subscribe} from 'grainjs'; import * as ko from 'knockout'; // Represents a top tab of the right side-pane. const TopTab = StringUnion("pageWidget", "field"); // Represents a subtab of pageWidget in the right side-pane. const PageSubTab = StringUnion("widget", "sortAndFilter", "data"); // A map of widget type to the icon and label to use for a field of that widget. const fieldTypes = new Map<IWidgetType, {label: string, icon: IconName, pluralLabel: string}>([ ['record', {label: 'Column', icon: 'TypeCell', pluralLabel: 'Columns'}], ['detail', {label: 'Field', icon: 'TypeCell', pluralLabel: 'Fields'}], ['single', {label: 'Field', icon: 'TypeCell', pluralLabel: 'Fields'}], ['chart', {label: 'Series', icon: 'ChartLine', pluralLabel: 'Series'}], ['custom', {label: 'Column', icon: 'TypeCell', pluralLabel: 'Columns'}], ]); // Returns the icon and label of a type, default to those associate to 'record' type. export function getFieldType(widgetType: IWidgetType|null) { return fieldTypes.get(widgetType || 'record') || fieldTypes.get('record')!; } export class RightPanel extends Disposable { public readonly header: DomContents; public readonly content: DomContents; // If the panel is showing a tool, such as Action Log, instead of the usual section/field // configuration, this will be set to the tool's header and content. private _extraTool: Observable<IExtraTool|null>; // Which of the two standard top tabs (page widget or field) is selected, or was last selected. private _topTab = createSessionObs(this, "rightTopTab", "pageWidget", TopTab.guard); // Which subtab is open for configuring page widget. private _subTab = createSessionObs(this, "rightPageSubTab", "widget", PageSubTab.guard); // Which type of page widget is active, e.g. "record" or "chart". This affects the names and // icons in the top tab. private _pageWidgetType = Computed.create<IWidgetType|null>(this, (use) => { const section: ViewSectionRec = use(this._gristDoc.viewModel.activeSection); return (use(section.parentKey) || null) as IWidgetType; }); // Returns the active section if it's valid, null otherwise. private _validSection = Computed.create(this, (use) => { const sec = use(this._gristDoc.viewModel.activeSection); return sec.getRowId() ? sec : null; }); constructor(private _gristDoc: GristDoc, private _isOpen: Observable<boolean>) { super(); this._extraTool = _gristDoc.rightPanelTool; this.autoDispose(subscribe(this._extraTool, (_use, tool) => tool && _isOpen.set(true))); this.header = this._buildHeaderDom(); this.content = this._buildContentDom(); this.autoDispose(commands.createGroup({ fieldTabOpen: () => this._openFieldTab(), viewTabOpen: () => this._openViewTab(), sortFilterTabOpen: () => this._openSortFilter(), dataSelectionTabOpen: () => this._openDataSelection() }, this, true)); } private _openFieldTab() { this._open('field'); } private _openViewTab() { this._open('pageWidget', 'widget'); } private _openSortFilter() { this._open('pageWidget', 'sortAndFilter'); } private _openDataSelection() { this._open('pageWidget', 'data'); } private _open(topTab: typeof TopTab.type, subTab?: typeof PageSubTab.type) { bundleChanges(() => { this._isOpen.set(true); this._topTab.set(topTab); if (subTab) { this._subTab.set(subTab); } }); } private _buildHeaderDom() { return dom.domComputed((use) => { if (!use(this._isOpen)) { return null; } const tool = use(this._extraTool); return tool ? this._buildToolHeader(tool) : this._buildStandardHeader(); }); } private _buildToolHeader(tool: IExtraTool) { return cssTopBarItem(cssTopBarIcon(tool.icon), tool.label, cssHoverCircle(cssHoverIcon("CrossBig"), dom.on('click', () => this._gristDoc.showTool('none')), testId('right-tool-close'), ), cssTopBarItem.cls('-selected', true) ); } private _buildStandardHeader() { return dom.maybe(this._pageWidgetType, (type) => { const widgetInfo = widgetTypes.get(type) || {label: 'Table', icon: 'TypeTable'}; const fieldInfo = getFieldType(type); return [ cssTopBarItem(cssTopBarIcon(widgetInfo.icon), widgetInfo.label, cssTopBarItem.cls('-selected', (use) => use(this._topTab) === 'pageWidget'), dom.on('click', () => this._topTab.set("pageWidget")), testId('right-tab-pagewidget')), cssTopBarItem(cssTopBarIcon(fieldInfo.icon), fieldInfo.label, cssTopBarItem.cls('-selected', (use) => use(this._topTab) === 'field'), dom.on('click', () => this._topTab.set("field")), testId('right-tab-field')), ]; }); } private _buildContentDom() { return dom.domComputed((use) => { if (!use(this._isOpen)) { return null; } const tool = use(this._extraTool); if (tool) { return tabContentToDom(tool.content); } const topTab = use(this._topTab); if (topTab === 'field') { return dom.create(this._buildFieldContent.bind(this)); } if (topTab === 'pageWidget' && use(this._pageWidgetType)) { return dom.create(this._buildPageWidgetContent.bind(this)); } return null; }); } private _buildFieldContent(owner: MultiHolder) { const fieldBuilder = owner.autoDispose(ko.computed(() => { const vsi = this._gristDoc.viewModel.activeSection?.().viewInstance(); return vsi && vsi.activeFieldBuilder(); })); const docModel = this._gristDoc.docModel; const origColRef = owner.autoDispose(ko.computed(() => fieldBuilder()?.origColumn.origColRef() || 0)); const origColumn = owner.autoDispose(docModel.columns.createFloatingRowModel(origColRef)); const isColumnValid = owner.autoDispose(ko.computed(() => Boolean(origColRef()))); // Builder for the reference display column multiselect. const refSelect = owner.autoDispose(RefSelect.create({docModel, origColumn, fieldBuilder})); // build cursor position observable const cursor = owner.autoDispose(ko.computed(() => { const vsi = this._gristDoc.viewModel.activeSection?.().viewInstance(); return vsi?.cursor.currentPosition() ?? {}; })); return domAsync(imports.loadViewPane().then(ViewPane => { const {buildNameConfig, buildFormulaConfig} = ViewPane.FieldConfig; return dom.maybe(isColumnValid, () => buildConfigContainer( dom.create(buildNameConfig, origColumn, cursor), cssSeparator(), dom.create(buildFormulaConfig, origColumn, this._gristDoc, this._activateFormulaEditor.bind(this)), cssSeparator(), cssLabel('COLUMN TYPE'), dom.maybe<FieldBuilder|null>(fieldBuilder, builder => [ builder.buildSelectTypeDom(), builder.buildSelectWidgetDom(), builder.buildConfigDom() ]), cssSeparator(), dom.maybe(refSelect.isForeignRefCol, () => [ cssLabel('Add referenced columns'), cssRow(refSelect.buildDom()), cssSeparator() ]), cssLabel('TRANSFORM'), dom.maybe<FieldBuilder|null>(fieldBuilder, builder => builder.buildTransformDom()), this._disableIfReadonly(), ) ); })); } // Helper to activate the side-pane formula editor over the given HTML element. private _activateFormulaEditor(refElem: Element) { const vsi = this._gristDoc.viewModel.activeSection().viewInstance(); if (!vsi) { return; } const editRowModel = vsi.moveEditRowToCursor(); vsi.activeFieldBuilder.peek().openSideFormulaEditor(editRowModel, refElem); } private _buildPageWidgetContent(_owner: MultiHolder) { return [ cssSubTabContainer( cssSubTab('Widget', cssSubTab.cls('-selected', (use) => use(this._subTab) === 'widget'), dom.on('click', () => this._subTab.set("widget")), testId('config-widget')), cssSubTab('Sort & Filter', cssSubTab.cls('-selected', (use) => use(this._subTab) === 'sortAndFilter'), dom.on('click', () => this._subTab.set("sortAndFilter")), testId('config-sortAndFilter')), cssSubTab('Data', cssSubTab.cls('-selected', (use) => use(this._subTab) === 'data'), dom.on('click', () => this._subTab.set("data")), testId('config-data')), ), dom.domComputed(this._subTab, (subTab) => ( dom.maybe(this._validSection, (activeSection) => ( buildConfigContainer( subTab === 'widget' ? dom.create(this._buildPageWidgetConfig.bind(this), activeSection) : subTab === 'sortAndFilter' ? dom.create(this._buildPageSortFilterConfig.bind(this)) : subTab === 'data' ? dom.create(this._buildPageDataConfig.bind(this), activeSection) : null ) )) )) ]; } private _createViewConfigTab(owner: MultiHolder): Observable<null|ViewConfigTab> { const viewConfigTab = Observable.create<null|ViewConfigTab>(owner, null); const gristDoc = this._gristDoc; imports.loadViewPane() .then(ViewPane => { if (owner.isDisposed()) { return; } viewConfigTab.set(owner.autoDispose( ViewPane.ViewConfigTab.create({gristDoc, viewModel: gristDoc.viewModel, skipDomBuild: true}))); }) .catch(reportError); return viewConfigTab; } private _buildPageWidgetConfig(owner: MultiHolder, activeSection: ViewSectionRec) { // TODO: This uses private methods from ViewConfigTab. These methods are likely to get // refactored, but if not, should be made public. const viewConfigTab = this._createViewConfigTab(owner); return dom.maybe(viewConfigTab, (vct) => [ this._disableIfReadonly(), cssLabel('WIDGET TITLE', dom.style('margin-bottom', '14px')), cssRow(cssTextInput( Computed.create(owner, (use) => use(activeSection.titleDef)), val => activeSection.titleDef.saveOnly(val), testId('right-widget-title') )), cssRow(primaryButton('Change Widget', this._createPageWidgetPicker()), cssRow.cls('-top-space')), cssSeparator(), dom.maybe((use) => ['detail', 'single'].includes(use(this._pageWidgetType)!), () => [ cssLabel('Theme'), dom('div', vct._buildThemeDom(), vct._buildLayoutDom()) ]), domComputed((use) => { if (use(this._pageWidgetType) !== 'record') { return null; } return dom.create(GridOptions, activeSection); }), dom.maybe((use) => use(this._pageWidgetType) === 'chart', () => [ cssLabel('CHART TYPE'), vct._buildChartConfigDom(), ]), dom.maybe((use) => use(this._pageWidgetType) === 'custom', () => [ cssLabel('CUSTOM'), () => { const parts = vct._buildCustomTypeItems() as any[]; return [ // If 'customViewPlugin' feature is on, show the toggle that allows switching to // plugin mode. Note that the default mode for a new 'custom' view is 'url', so that's // the only one that will be shown without the feature flag. dom.maybe((use) => use(this._gristDoc.app.features).customViewPlugin, () => dom('div', parts[0].buildDom())), dom.maybe(use => use(activeSection.customDef.mode) === 'plugin', () => dom('div', parts[2].buildDom())), // In the default url mode, allow picking a url and granting/forbidding // access to data. dom.maybe(use => use(activeSection.customDef.mode) === 'url', () => dom('div', parts[1].buildDom())), ]; } ]), dom.maybe((use) => use(this._pageWidgetType) !== 'chart', () => [ cssSeparator(), dom.create(VisibleFieldsConfig, this._gristDoc, activeSection, true), ]), ]); } private _buildPageSortFilterConfig(owner: MultiHolder) { const viewConfigTab = this._createViewConfigTab(owner); return [ cssLabel('SORT'), dom.maybe(viewConfigTab, (vct) => vct.buildSortDom()), cssSeparator(), cssLabel('FILTER'), dom.maybe(viewConfigTab, (vct) => dom('div', vct._buildFilterDom())), ]; } private _buildPageDataConfig(owner: MultiHolder, activeSection: ViewSectionRec) { const viewConfigTab = this._createViewConfigTab(owner); const viewModel = this._gristDoc.viewModel; const table = activeSection.table; const groupedBy = Computed.create(owner, (use) => use(use(table).groupByColumns)); const link = Computed.create(owner, (use) => { return linkId({ srcSectionRef: use(activeSection.linkSrcSectionRef), srcColRef: use(activeSection.linkSrcColRef), targetColRef: use(activeSection.linkTargetColRef) }); }); // TODO: this computed is not enough to make sure that the linkOptions are up to date. Indeed // the selectBy function depends on a much greater number of observables. Creating that many // dependencies does not seem a better approach. Instead, we could refresh the list of // linkOptions only when the user clicks the dropdown. Such behaviour is not supported by the // weasel select function as of writing and would require a custom implementation. const linkOptions = Computed.create(owner, (use) => selectBy( this._gristDoc.docModel, use(viewModel.viewSections).peek(), activeSection, ) ); link.onWrite((val) => this._gristDoc.saveLink(linkFromId(val))); return [ this._disableIfReadonly(), cssLabel('DATA TABLE'), cssRow( cssIcon('TypeTable'), cssDataLabel('SOURCE DATA'), cssContent(dom.text((use) => use(use(table).primaryTableId)), testId('pwc-table')) ), dom( 'div', cssRow(cssIcon('Pivot'), cssDataLabel('GROUPED BY')), cssRow(domComputed(groupedBy, (cols) => cssList(cols.map((c) => ( cssListItem(dom.text(c.label), testId('pwc-groupedBy-col')) ))))), testId('pwc-groupedBy'), // hide if not a summary table dom.hide((use) => !use(use(table).summarySourceTable)), ), cssButtonRow(primaryButton('Edit Data Selection', this._createPageWidgetPicker(), testId('pwc-editDataSelection')), dom.maybe( use => Boolean(use(use(activeSection.table).summarySourceTable)), () => basicButton( 'Detach', dom.on('click', () => this._gristDoc.docData.sendAction( ["DetachSummaryViewSection", activeSection.getRowId()])), testId('detach-button'), )), cssRow.cls('-top-space'), ), // TODO: "Advanced settings" is for "on-demand" marking of tables. This should only be shown // for raw data tables (once that's supported), should have updated UI, and should possibly // be hidden for free plans. dom.maybe(viewConfigTab, (vct) => cssRow( dom('div', vct._buildAdvancedSettingsDom()), )), cssSeparator(), cssLabel('SELECT BY'), cssRow( select(link, linkOptions, {defaultLabel: 'Select Widget'}), testId('right-select-by') ), domComputed((use) => { const activeSectionRef = activeSection.getRowId(); const allViewSections = use(use(viewModel.viewSections).getObservable()); const selectorFor = allViewSections.filter((sec) => use(sec.linkSrcSectionRef) === activeSectionRef); // TODO: sections should be listed following the order of appearance in the view layout (ie: // left/right - top/bottom); return selectorFor.length ? [ cssLabel('SELECTOR FOR', testId('selector-for')), cssRow(cssList(selectorFor.map((sec) => this._buildSectionItem(sec)))) ] : null; }), ]; } private _createPageWidgetPicker(): DomElementMethod { const gristDoc = this._gristDoc; const section = gristDoc.viewModel.activeSection; const onSave = (val: IPageWidget) => gristDoc.saveViewSection(section.peek(), val); return (elem) => { attachPageWidgetPicker(elem, gristDoc.docModel, onSave, { buttonLabel: 'Save', value: () => toPageWidget(section.peek()), selectBy: (val) => gristDoc.selectBy(val), }); }; } // Returns dom for a section item. private _buildSectionItem(sec: ViewSectionRec) { return cssListItem( dom.text(sec.titleDef), testId('selector-for-entry') ); } // Returns a DomArg that disables the content of the panel by adding a transparent overlay on top // of it. private _disableIfReadonly() { if (this._gristDoc.docPageModel) { return dom.maybe(this._gristDoc.docPageModel.isReadonly, () => ( cssOverlay( testId('disable-overlay'), cssBottomText('You do not have edit access to this document'), ) )); } } } export function buildConfigContainer(...args: DomElementArg[]): HTMLElement { return cssConfigContainer( // The `position: relative;` style is needed for the overlay for the readonly mode. Note that // we cannot set it on the cssConfigContainer directly because it conflicts with how overflow // works. `padding-top: 1px;` prevents collapsing the top margins for the container and the // first child. dom('div', {style: 'position: relative; padding-top: 1px;'}, ...args), ); } // This logic is copied from SidePane.js for building DOM from TabContent. // TODO It may not be needed after new-ui refactoring of the side-pane content. function tabContentToDom(content: Observable<TabContent[]>|TabContent[]|IDomComponent) { function buildItemDom(item: any) { return dom('div.config_item', dom.show(item.showObs || true), item.buildDom() ); } if ("buildDom" in content) { return content.buildDom(); } return cssTabContents( dom.forEach(content, itemOrHeader => { if (itemOrHeader.header) { return dom('div.config_group', dom.show(itemOrHeader.showObs || true), itemOrHeader.label ? dom('div.config_header', itemOrHeader.label) : null, dom.forEach(itemOrHeader.items, item => buildItemDom(item)), ); } else { return buildItemDom(itemOrHeader); } }) ); } const cssOverlay = styled('div', ` background-color: white; opacity: 0.8; position: absolute; top: 0; left: 0; right: 0; bottom: 0; z-index: 100; `); const cssBottomText = styled('span', ` position: absolute; bottom: -40px; padding: 4px 16px; `); export const cssLabel = styled('div', ` text-transform: uppercase; margin: 16px 16px 12px 16px; font-size: ${vars.xsmallFontSize}; `); export const cssRow = styled('div', ` display: flex; margin: 8px 16px; align-items: center; &-top-space { margin-top: 24px; } `); export const cssButtonRow = styled(cssRow, ` margin-left: 0; margin-right: 0; & > button { margin-left: 16px; } `); export const cssIcon = styled(icon, ` flex: 0 0 auto; background-color: ${colors.slate}; `); const cssTopBarItem = styled('div', ` flex: 1 1 0px; height: 100%; background-color: ${colors.lightGrey}; font-weight: ${vars.headerControlTextWeight}; color: ${colors.dark}; --icon-color: ${colors.slate}; display: flex; align-items: center; cursor: default; &-selected { background-color: ${colors.lightGreen}; font-weight: initial; color: ${colors.light}; --icon-color: ${colors.light}; } &:not(&-selected):hover { background-color: ${colors.mediumGrey}; --icon-color: ${colors.lightGreen}; } `); const cssTopBarIcon = styled(icon, ` flex: none; margin: 16px; height: 16px; width: 16px; background-color: vars(--icon-color); `); const cssHoverCircle = styled('div', ` margin-left: auto; margin-right: 8px; width: 32px; height: 32px; background: none; border-radius: 16px; display: flex; align-items: center; justify-content: center; &:hover { background-color: ${colors.darkGreen}; } `); const cssHoverIcon = styled(icon, ` height: 16px; width: 16px; background-color: vars(--icon-color); `); export const cssSubTabContainer = styled('div', ` height: 48px; flex: none; display: flex; align-items: center; justify-content: space-between; `); export const cssSubTab = styled('div', ` color: ${colors.lightGreen}; flex: auto; height: 100%; display: flex; flex-direction: column; justify-content: flex-end; text-align: center; padding-bottom: 8px; border-bottom: 1px solid ${colors.mediumGrey}; cursor: default; &-selected { color: ${colors.dark}; border-bottom: 1px solid ${colors.lightGreen}; } &:not(&-selected):hover { color: ${colors.darkGreen}; } &:hover { border-bottom: 1px solid ${colors.lightGreen}; } .${cssSubTabContainer.className}:hover > &-selected:not(:hover) { border-bottom: 1px solid ${colors.mediumGrey}; } `); const cssTabContents = styled('div', ` padding: 16px 8px; overflow: auto; `); export const cssSeparator = styled('div', ` border-bottom: 1px solid ${colors.mediumGrey}; margin-top: 16px; `); const cssConfigContainer = styled('div', ` overflow: auto; --color-list-item: none; --color-list-item-hover: none; &:after { content: ""; display: block; height: 40px; } & .fieldbuilder_settings { margin: 16px 0 0 0; } `); const cssDataLabel = styled('div', ` flex: 0 0 81px; color: ${colors.slate}; font-size: ${vars.xsmallFontSize}; margin-left: 4px; margin-top: 2px; `); const cssContent = styled('div', ` flex: 0 1 auto; overflow: hidden; text-overflow: ellipsis; min-width: 1em; `); const cssList = styled('div', ` list-style: none; width: 100%; `); const cssListItem = styled('li', ` background-color: ${colors.mediumGrey}; border-radius: 2px; margin-bottom: 4px; white-space: nowrap; overflow: hidden; text-overflow: ellipsis; width: 100%; padding: 4px 8px; `); export const cssTextInput = styled(textInput, ` flex: 1 0 auto; `);
the_stack
import { buildTransform } from '@orbit/data'; import { SyncCacheIntegrityProcessor, SyncSchemaConsistencyProcessor } from '@orbit/record-cache'; import { cloneRecordIdentity as identity, InitializedRecord, RecordKeyMap, RecordOperation, RecordSchema, RecordSchemaSettings, RecordSource, RecordTransformBuilder } from '@orbit/records'; import { clone } from '@orbit/utils'; import { MemoryCache } from '../src/memory-cache'; import { MemorySource } from '../src/memory-source'; const { module, test } = QUnit; module('MemorySource', function (hooks) { const schemaDefinition: RecordSchemaSettings = { models: { star: { attributes: { name: { type: 'string' } }, relationships: { planets: { kind: 'hasMany', type: 'planet', inverse: 'star' } } }, planet: { attributes: { name: { type: 'string' }, classification: { type: 'string' } }, relationships: { moons: { kind: 'hasMany', type: 'moon', inverse: 'planet' }, star: { kind: 'hasOne', type: 'star', inverse: 'planets' } } }, moon: { attributes: { name: { type: 'string' } }, relationships: { planet: { kind: 'hasOne', type: 'planet', inverse: 'moons' } } }, binaryStar: { attributes: { name: { type: 'string' } }, relationships: { starOne: { kind: 'hasOne', type: 'star' }, starTwo: { kind: 'hasOne', type: 'star' } } }, planetarySystem: { attributes: { name: { type: 'string' } }, relationships: { star: { kind: 'hasOne', type: ['star', 'binaryStar'] }, bodies: { kind: 'hasMany', type: ['planet', 'moon'] } } } } }; let schema: RecordSchema; let keyMap: RecordKeyMap; hooks.beforeEach(function () { schema = new RecordSchema(schemaDefinition); keyMap = new RecordKeyMap(); }); test('its prototype chain is correct', function (assert) { const source = new MemorySource({ schema, keyMap }); assert.ok(source instanceof RecordSource, 'instanceof RecordSource'); assert.ok(source instanceof MemorySource, 'instanceof MemorySource'); assert.equal(source.name, 'memory', 'should have default name'); }); test("internal cache's settings can be specified with `cacheSettings`", function (assert) { const source = new MemorySource({ schema, keyMap, cacheSettings: { schema, processors: [ SyncCacheIntegrityProcessor, SyncSchemaConsistencyProcessor ] } }); assert.ok(source.cache, 'cache exists'); assert.equal(source.cache.processors.length, 2, 'cache has 2 processors'); }); test('can be assigned a custom `cacheClass`', function (assert) { class CustomCache extends MemoryCache { custom = true; } const source = new MemorySource({ schema, autoActivate: false, cacheClass: CustomCache }); assert.ok( (source.cache as CustomCache).custom, 'custom cacheClass has been instantiated' ); }); test('shares its `transformBuilder` and `queryBuilder` with its cache', function (assert) { const source = new MemorySource({ schema, keyMap }); assert.strictEqual( source.cache.transformBuilder, source.transformBuilder, 'transformBuilder is shared' ); assert.strictEqual( source.cache.queryBuilder, source.queryBuilder, 'queryBuilder is shared' ); }); test('shares its `defaultTransformOptions` and `defaultQueryOptions` with its cache', function (assert) { const source = new MemorySource({ schema, keyMap, defaultQueryOptions: { a: 1 }, defaultTransformOptions: { b: 1 } }); assert.strictEqual( source.cache.defaultTransformOptions, source.defaultTransformOptions, 'defaultTransformOptions are shared' ); assert.strictEqual( source.cache.defaultTransformOptions?.b, 1, 'cache.defaultTransformOptions are correct' ); assert.strictEqual( source.cache.defaultQueryOptions, source.defaultQueryOptions, 'defaultQueryOptions are shared' ); assert.strictEqual( source.cache.defaultQueryOptions?.a, 1, 'cache.defaultQueryOptions are correct' ); let newQueryOptions = { a: 2 }; source.defaultQueryOptions = newQueryOptions; assert.strictEqual( source.defaultQueryOptions?.a, 2, 'defaultQueryOptions are correct' ); assert.strictEqual( source.cache.defaultQueryOptions, source.defaultQueryOptions, 'updated defaultQueryOptions are shared' ); let newTransformOptions = { b: 2 }; source.defaultTransformOptions = newTransformOptions; assert.strictEqual( source.cache.defaultTransformOptions, source.defaultTransformOptions, 'updated defaultTransformOptions are shared' ); assert.strictEqual( source.cache.defaultTransformOptions?.b, 2, 'updated cache.defaultTransformOptions are correct' ); }); test('shares its `validatorFor` with its cache', function (assert) { const source = new MemorySource({ schema, keyMap }); assert.strictEqual( source.cache.validatorFor, source.validatorFor, 'validatorFor is shared' ); }); test('#sync - appends transform to log', async function (assert) { const source = new MemorySource({ schema, keyMap }); const recordA = { id: 'jupiter', type: 'planet', attributes: { name: 'Jupiter' } }; const addRecordATransform = buildTransform( source.transformBuilder.addRecord(recordA) ); await source.sync(addRecordATransform); assert.ok( source.transformLog.contains(addRecordATransform.id), 'log contains transform' ); }); test('#getTransform - returns a particular transform given an id', async function (assert) { const source = new MemorySource({ schema, keyMap }); const recordA = { id: 'jupiter', type: 'planet', attributes: { name: 'Jupiter' } }; const addRecordATransform = buildTransform( source.transformBuilder.addRecord(recordA) ); await source.sync(addRecordATransform); assert.strictEqual( source.getTransform(addRecordATransform.id), addRecordATransform ); }); test('#getInverseOperations - returns the inverse operations for a particular transform', async function (assert) { const source = new MemorySource({ schema, keyMap }); const recordA = { id: 'jupiter', type: 'planet', attributes: { name: 'Jupiter' } }; const addRecordATransform = buildTransform( source.transformBuilder.addRecord(recordA) ); await source.sync(addRecordATransform); assert.deepEqual(source.getInverseOperations(addRecordATransform.id), [ { op: 'removeRecord', record: identity(recordA) } ]); }); test('#getTransformsSince - returns all transforms since a specified transformId', async function (assert) { const source = new MemorySource({ schema, keyMap }); const recordA = { id: 'jupiter', type: 'planet', attributes: { name: 'Jupiter' } }; const recordB = { id: 'saturn', type: 'planet', attributes: { name: 'Saturn' } }; const recordC = { id: 'pluto', type: 'planet', attributes: { name: 'Pluto' } }; const tb = source.transformBuilder; const addRecordATransform = buildTransform(tb.addRecord(recordA)); const addRecordBTransform = buildTransform(tb.addRecord(recordB)); const addRecordCTransform = buildTransform(tb.addRecord(recordC)); await source.sync(addRecordATransform); await source.sync(addRecordBTransform); await source.sync(addRecordCTransform); assert.deepEqual( source.getTransformsSince(addRecordATransform.id), [addRecordBTransform, addRecordCTransform], 'returns transforms since the specified transform' ); }); test('#getAllTransforms - returns all tracked transforms', async function (assert) { const source = new MemorySource({ schema, keyMap }); const recordA = { id: 'jupiter', type: 'planet', attributes: { name: 'Jupiter' } }; const recordB = { id: 'saturn', type: 'planet', attributes: { name: 'Saturn' } }; const recordC = { id: 'pluto', type: 'planet', attributes: { name: 'Pluto' } }; const tb = source.transformBuilder; const addRecordATransform = buildTransform(tb.addRecord(recordA)); const addRecordBTransform = buildTransform(tb.addRecord(recordB)); const addRecordCTransform = buildTransform(tb.addRecord(recordC)); await source.sync(addRecordATransform); await source.sync(addRecordBTransform); await source.sync(addRecordCTransform); assert.deepEqual( source.getAllTransforms(), [addRecordATransform, addRecordBTransform, addRecordCTransform], 'tracks transforms in correct order' ); }); test('transformLog.truncate - clears transforms from log as well as tracked transforms before a specified transform', async function (assert) { const source = new MemorySource({ schema, keyMap }); const recordA = { id: 'jupiter', type: 'planet', attributes: { name: 'Jupiter' } }; const recordB = { id: 'saturn', type: 'planet', attributes: { name: 'Saturn' } }; const recordC = { id: 'pluto', type: 'planet', attributes: { name: 'Pluto' } }; const tb = source.transformBuilder; const addRecordATransform = buildTransform(tb.addRecord(recordA)); const addRecordBTransform = buildTransform(tb.addRecord(recordB)); const addRecordCTransform = buildTransform(tb.addRecord(recordC)); await source.sync(addRecordATransform); await source.sync(addRecordBTransform); await source.sync(addRecordCTransform); await source.transformLog.truncate(addRecordBTransform.id); assert.deepEqual( source.getAllTransforms(), [addRecordBTransform, addRecordCTransform], 'remaining transforms are in correct order' ); }); test('transformLog.clear - clears all transforms from log as well as tracked transforms', async function (assert) { const source = new MemorySource({ schema, keyMap }); const recordA = { id: 'jupiter', type: 'planet', attributes: { name: 'Jupiter' } }; const recordB = { id: 'saturn', type: 'planet', attributes: { name: 'Saturn' } }; const recordC = { id: 'pluto', type: 'planet', attributes: { name: 'Pluto' } }; const tb = source.transformBuilder; const addRecordATransform = buildTransform(tb.addRecord(recordA)); const addRecordBTransform = buildTransform(tb.addRecord(recordB)); const addRecordCTransform = buildTransform(tb.addRecord(recordC)); await source.sync(addRecordATransform); await source.sync(addRecordBTransform); await source.sync(addRecordCTransform); await source.transformLog.clear(); assert.deepEqual( source.getAllTransforms(), [], 'no transforms remain in history' ); assert.equal( source.cache.getRecordsSync().length, 3, 'records remain in cache' ); }); test('reset - clears transform log and resets cache', async function (assert) { const source = new MemorySource({ schema, keyMap }); const recordA = { id: 'jupiter', type: 'planet', attributes: { name: 'Jupiter' } }; const recordB = { id: 'saturn', type: 'planet', attributes: { name: 'Saturn' } }; const recordC = { id: 'pluto', type: 'planet', attributes: { name: 'Pluto' } }; const tb = source.transformBuilder; const addRecordATransform = buildTransform(tb.addRecord(recordA)); const addRecordBTransform = buildTransform(tb.addRecord(recordB)); const addRecordCTransform = buildTransform(tb.addRecord(recordC)); await source.sync(addRecordATransform); await source.sync(addRecordBTransform); await source.sync(addRecordCTransform); await source.reset(); assert.deepEqual( source.getAllTransforms(), [], 'no transforms remain in history' ); assert.equal( source.cache.getRecordsSync().length, 0, 'cache has been cleared' ); }); test('#fork - creates a new source that starts with the same schema, keyMap, and cache contents as the base source', async function (assert) { const source = new MemorySource({ schema, keyMap }); const jupiter: InitializedRecord = { type: 'planet', id: 'jupiter-id', attributes: { name: 'Jupiter', classification: 'gas giant' } }; await source.update((t) => t.addRecord(jupiter)); assert.deepEqual( source.cache.getRecordSync({ type: 'planet', id: 'jupiter-id' }), jupiter, 'verify source data' ); const fork = source.fork(); assert.deepEqual( fork.cache.getRecordSync({ type: 'planet', id: 'jupiter-id' }), jupiter, 'data in fork matches data in source' ); assert.strictEqual(fork.schema, source.schema, 'schema matches'); assert.strictEqual(fork.keyMap, source.keyMap, 'keyMap matches'); assert.strictEqual( fork.transformBuilder, source.transformBuilder, 'transformBuilder is shared' ); assert.strictEqual( fork.queryBuilder, source.queryBuilder, 'queryBuilder is shared' ); assert.strictEqual( fork.validatorFor, source.validatorFor, 'validatorFor is shared' ); assert.strictEqual( fork.forkPoint, source.transformLog.head, 'forkPoint is set on the forked source' ); assert.strictEqual( fork.base, source, 'base source is set on the forked source' ); }); test('#merge - merges changes from a forked source back into a base source', async function (assert) { const source = new MemorySource({ schema, keyMap }); const jupiter: InitializedRecord = { type: 'planet', id: 'jupiter-id', attributes: { name: 'Jupiter', classification: 'gas giant' } }; let fork = source.fork(); await fork.update((t) => t.addRecord(jupiter)); assert.deepEqual( fork.cache.getRecordSync({ type: 'planet', id: 'jupiter-id' }), jupiter, 'verify fork data' ); await source.merge(fork); assert.deepEqual( source.cache.getRecordSync({ type: 'planet', id: 'jupiter-id' }), jupiter, 'data in source matches data in fork' ); }); test("#merge - will apply all operations from a forked source's cache, if that cache is tracking update operations", async function (assert) { const source = new MemorySource({ schema, keyMap }); const jupiter: InitializedRecord = { type: 'planet', id: 'jupiter', attributes: { name: 'Jupiter', classification: 'gas giant' } }; const earth: InitializedRecord = { type: 'planet', id: 'earth', attributes: { name: 'Jupiter', classification: 'gas giant' } }; let fork = source.fork(); assert.ok( fork.cache.isTrackingUpdateOperations, "forked source's cache is tracking update operations" ); // apply change to fork.cache fork.cache.update((t) => t.addRecord(jupiter)); // apply other change to fork directly await fork.update((t) => t.addRecord(earth)); assert.deepEqual( fork.cache.getRecordSync({ type: 'planet', id: 'jupiter' }), jupiter, 'jupiter is present in fork.cache' ); assert.deepEqual( fork.cache.getRecordSync({ type: 'planet', id: 'earth' }), earth, 'earth is present in fork.cache' ); await source.merge(fork); assert.deepEqual( source.cache.getRecordSync({ type: 'planet', id: 'jupiter' }), jupiter, 'jupiter is present in source.cache' ); assert.deepEqual( source.cache.getRecordSync({ type: 'planet', id: 'earth' }), earth, 'earth is present in source.cache' ); }); test('#merge - will apply only operations from a forked source, if its cache is NOT tracking update operations', async function (assert) { const source = new MemorySource({ schema, keyMap }); const jupiter: InitializedRecord = { type: 'planet', id: 'jupiter', attributes: { name: 'Jupiter', classification: 'gas giant' } }; const earth: InitializedRecord = { type: 'planet', id: 'earth', attributes: { name: 'Jupiter', classification: 'gas giant' } }; let fork = source.fork({ cacheSettings: { trackUpdateOperations: false } }); assert.notOk( fork.cache.isTrackingUpdateOperations, "forked source's cache is NOT tracking update operations" ); // apply change to fork.cache fork.cache.update((t) => t.addRecord(jupiter)); // apply other change to fork directly await fork.update((t) => t.addRecord(earth)); assert.deepEqual( fork.cache.getRecordSync({ type: 'planet', id: 'jupiter' }), jupiter, 'jupiter is present in fork.cache' ); assert.deepEqual( fork.cache.getRecordSync({ type: 'planet', id: 'earth' }), earth, 'earth is present in fork.cache' ); await source.merge(fork); assert.strictEqual( source.cache.getRecordSync({ type: 'planet', id: 'jupiter' }), undefined, 'jupiter is NOT present in source.cache' ); assert.deepEqual( source.cache.getRecordSync({ type: 'planet', id: 'earth' }), earth, 'earth is present in source.cache' ); }); test('#merge - can accept options in deprecated `transformOptions` object that will be assigned to the resulting transform', async function (assert) { assert.expect(3); const source = new MemorySource({ schema, keyMap }); const jupiter: InitializedRecord = { type: 'planet', id: 'jupiter-id', attributes: { name: 'Jupiter', classification: 'gas giant' } }; let fork = source.fork(); source.on('update', (transform) => { assert.equal(transform.options.label, 'Create Jupiter'); }); await fork.update((t) => t.addRecord(jupiter)); assert.deepEqual( fork.cache.getRecordSync({ type: 'planet', id: 'jupiter-id' }), jupiter, 'verify fork data' ); await source.merge(fork, { transformOptions: { label: 'Create Jupiter' } }); assert.deepEqual( source.cache.getRecordSync({ type: 'planet', id: 'jupiter-id' }), jupiter, 'data in source matches data in fork' ); }); test('#merge - can accept options that will be assigned to the resulting transform', async function (assert) { assert.expect(3); const source = new MemorySource({ schema, keyMap }); const jupiter: InitializedRecord = { type: 'planet', id: 'jupiter-id', attributes: { name: 'Jupiter', classification: 'gas giant' } }; let fork = source.fork(); source.on('update', (transform) => { assert.equal(transform.options.label, 'Create Jupiter'); }); await fork.update((t) => t.addRecord(jupiter)); assert.deepEqual( fork.cache.getRecordSync({ type: 'planet', id: 'jupiter-id' }), jupiter, 'verify fork data' ); await source.merge(fork, { label: 'Create Jupiter' }); assert.deepEqual( source.cache.getRecordSync({ type: 'planet', id: 'jupiter-id' }), jupiter, 'data in source matches data in fork' ); }); test('#rebase - works with empty sources', function (assert) { assert.expect(1); const source = new MemorySource({ schema, keyMap }); let child = source.fork(); child.rebase(); assert.ok(true, 'no exception has been thrown'); }); test('#rebase - record ends up in child source', async function (assert) { assert.expect(3); const jupiter: InitializedRecord = { type: 'planet', id: 'jupiter-id', attributes: { name: 'Jupiter', classification: 'gas giant' } }; const source = new MemorySource({ schema, keyMap }); let child = source.fork(); await source.update((t) => t.addRecord(jupiter)); assert.deepEqual( source.cache.getRecordSync({ type: 'planet', id: 'jupiter-id' }), jupiter, 'verify source data' ); assert.equal( child.cache.getRecordsSync('planet').length, 0, 'child source is still empty' ); child.rebase(); assert.deepEqual( child.cache.getRecordSync({ type: 'planet', id: 'jupiter-id' }), jupiter, 'verify child data' ); }); test('#rebase - maintains only unique transforms in fork', async function (assert) { const source = new MemorySource({ schema, keyMap }); const recordA = { id: 'jupiter', type: 'planet', attributes: { name: 'Jupiter' } }; const recordB = { id: 'saturn', type: 'planet', attributes: { name: 'Saturn' } }; const recordC = { id: 'pluto', type: 'planet', attributes: { name: 'Pluto' } }; const recordD = { id: 'neptune', type: 'planet', attributes: { name: 'Neptune' } }; const recordE = { id: 'uranus', type: 'planet', attributes: { name: 'Uranus' } }; const tb = source.transformBuilder; const addRecordA = buildTransform(tb.addRecord(recordA)); const addRecordB = buildTransform(tb.addRecord(recordB)); const addRecordC = buildTransform(tb.addRecord(recordC)); const addRecordD = buildTransform(tb.addRecord(recordD)); const addRecordE = buildTransform(tb.addRecord(recordE)); let fork; await source.update(addRecordA); await source.update(addRecordB); fork = source.fork(); await fork.update(addRecordD); await source.update(addRecordC); await fork.update(addRecordE); fork.rebase(); assert.deepEqual(fork.getAllTransforms(), [addRecordD, addRecordE]); assert.deepEqual(fork.cache.getRecordSync(recordA), recordA); assert.deepEqual(fork.cache.getRecordSync(recordB), recordB); assert.deepEqual(fork.cache.getRecordSync(recordC), recordC); assert.deepEqual(fork.cache.getRecordSync(recordD), recordD); assert.deepEqual(fork.cache.getRecordSync(recordE), recordE); assert.deepEqual(fork.cache.getRecordsSync('planet').length, 5); }); test('#rebase - rebase orders conflicting transforms in expected way', async function (assert) { assert.expect(6); const source = new MemorySource({ schema, keyMap }); const jupiter: InitializedRecord = { type: 'planet', id: 'jupiter-id', attributes: { name: 'Jupiter', classification: 'gas giant' } }; const id = { type: 'planet', id: 'jupiter-id' }; let child: MemorySource; // 1. fill source with some data await source.update((t) => t.addRecord(jupiter)); // 2. create a child source assert.deepEqual( source.cache.getRecordSync(id), jupiter, 'verify source data' ); child = source.fork(); assert.deepEqual( child.cache.getRecordSync(id), jupiter, 'verify child data' ); // 3. update the child and the parent source (in any order) await child.update((t) => t.replaceAttribute(id, 'name', 'The Gas Giant')); await source.update((t) => t.replaceAttribute(id, 'name', 'Gassy Giant')); // 4. make sure updates were successful assert.equal( child.cache.getRecordSync(id)?.attributes?.name, 'The Gas Giant' ); assert.equal( source.cache.getRecordSync(id)?.attributes?.name, 'Gassy Giant' ); // 5. do the rebase child.rebase(); assert.equal( child.cache.getRecordSync(id)?.attributes?.name, 'The Gas Giant' ); assert.equal( source.cache.getRecordSync(id)?.attributes?.name, 'Gassy Giant' ); }); test('#rebase - calling rebase multiple times', async function (assert) { assert.expect(22); const source = new MemorySource({ schema, keyMap }); const jupiter: InitializedRecord = { type: 'planet', id: 'jupiter-id', attributes: { name: 'Jupiter', classification: 'gas giant' } }; const id = { type: 'planet', id: 'jupiter-id' }; let child: MemorySource; // 1. fill source with some data await source.update((t) => t.addRecord(jupiter)); // 2. create a child source assert.deepEqual( source.cache.getRecordSync(id), jupiter, 'verify source data' ); child = source.fork(); assert.deepEqual( child.cache.getRecordSync(id), jupiter, 'verify child data' ); // 3. update the child and the parent source (in any order) await child.update((t) => t.replaceAttribute(id, 'name', 'The Gas Giant')); await source.update((t) => t.replaceAttribute(id, 'name', 'Gassy Giant')); // 4. make sure updates were successful assert.equal( child.cache.getRecordSync(id)?.attributes?.name, 'The Gas Giant' ); assert.equal( source.cache.getRecordSync(id)?.attributes?.name, 'Gassy Giant' ); // 5. do the rebase child.rebase(); assert.equal( child.cache.getRecordSync(id)?.attributes?.name, 'The Gas Giant' ); assert.equal( source.cache.getRecordSync(id)?.attributes?.name, 'Gassy Giant' ); // 6. do a second update to the parent source assert.equal( source.cache.getRecordSync(id)?.attributes?.classification, 'gas giant' ); await source.update((t) => t.updateRecord({ ...id, attributes: { name: 'Gassy Giant II', classification: 'gas giant II' } }) ); // 7. make sure updates were successful assert.equal( child.cache.getRecordSync(id)?.attributes?.name, 'The Gas Giant' ); assert.equal( source.cache.getRecordSync(id)?.attributes?.name, 'Gassy Giant II' ); assert.equal( source.cache.getRecordSync(id)?.attributes?.classification, 'gas giant II' ); // 8. do the second rebase // make sure that changes from the child are still winning child.rebase(); assert.equal( child.cache.getRecordSync(id)?.attributes?.name, 'The Gas Giant' ); assert.equal( child.cache.getRecordSync(id)?.attributes?.classification, 'gas giant II' ); assert.equal( source.cache.getRecordSync(id)?.attributes?.name, 'Gassy Giant II' ); assert.equal( source.cache.getRecordSync(id)?.attributes?.classification, 'gas giant II' ); // 9. update the parent source a third time await source.update((t) => t.replaceAttribute(id, 'classification', 'gas giant III') ); // 10. make sure updates were successful assert.equal( child.cache.getRecordSync(id)?.attributes?.name, 'The Gas Giant' ); assert.equal( child.cache.getRecordSync(id)?.attributes?.classification, 'gas giant II' ); assert.equal( source.cache.getRecordSync(id)?.attributes?.name, 'Gassy Giant II' ); assert.equal( source.cache.getRecordSync(id)?.attributes?.classification, 'gas giant III' ); // 11. do the third rebase // make sure that transforms from the parent are applied in correct order child.rebase(); assert.equal( child.cache.getRecordSync(id)?.attributes?.name, 'The Gas Giant' ); assert.equal( child.cache.getRecordSync(id)?.attributes?.classification, 'gas giant III', 'classification has not been touched in child source => should be the same as in parent source' ); assert.equal( source.cache.getRecordSync(id)?.attributes?.name, 'Gassy Giant II' ); assert.equal( source.cache.getRecordSync(id)?.attributes?.classification, 'gas giant III' ); }); test('#rollback - rolls back transform log and replays transform inverses against the cache', async function (assert) { const source = new MemorySource({ schema, keyMap }); const recordA = { id: 'jupiter', type: 'planet', attributes: { name: 'Jupiter' } }; const recordB = { id: 'saturn', type: 'planet', attributes: { name: 'Saturn' } }; const recordC = { id: 'pluto', type: 'planet', attributes: { name: 'Pluto' } }; const recordD = { id: 'neptune', type: 'planet', attributes: { name: 'Neptune' } }; const recordE = { id: 'uranus', type: 'planet', attributes: { name: 'Uranus' } }; const tb = source.transformBuilder; const addRecordATransform = buildTransform(tb.addRecord(recordA)); const addRecordBTransform = buildTransform(tb.addRecord(recordB)); const addRecordCTransform = buildTransform(tb.addRecord(recordC)); const rollbackOperations: RecordOperation[] = []; await source.sync(addRecordATransform), await source.sync(addRecordBTransform), await source.sync(addRecordCTransform), await source.sync( buildTransform<RecordOperation, RecordTransformBuilder>([ tb.addRecord(recordD), tb.addRecord(recordE) ]) ); source.cache.on('patch', (operation: RecordOperation) => rollbackOperations.push(operation) ); await source.rollback(addRecordATransform.id); assert.deepEqual( rollbackOperations, [ { op: 'removeRecord', record: identity(recordE) }, { op: 'removeRecord', record: identity(recordD) }, { op: 'removeRecord', record: identity(recordC) }, { op: 'removeRecord', record: identity(recordB) } ], 'emits inverse operations in correct order' ); assert.equal( source.transformLog.head, addRecordATransform.id, 'rolls back transform log' ); }); test('#upgrade upgrades the cache to include new models introduced in a schema', async function (assert) { const source = new MemorySource({ schema, keyMap }); const person = { type: 'person', id: '1', relationships: { planet: { data: { type: 'planet', id: 'earth' } } } }; const models = clone(schema.models); models.planet.relationships.inhabitants = { kind: 'hasMany', type: 'person', inverse: 'planet' }; models.person = { relationships: { planet: { kind: 'hasOne', type: 'planet', inverse: 'inhabitants' } } }; schema.upgrade({ models }); await source.update((t) => t.addRecord(person)); assert.deepEqual( source.cache.getRecordSync({ type: 'person', id: '1' }), person, 'records match' ); }); });
the_stack
require("dotenv-safe").config(); import cors from "cors"; import express from "express"; import Router from "express-promise-router"; import helmet from "helmet"; import createError from "http-errors"; import passport from "passport"; import { Strategy as GitHubStrategy } from "passport-github"; import { join } from "path"; import "reflect-metadata"; import fetch from "node-fetch"; import { assert } from "superstruct"; import { createConnection, getConnection } from "typeorm"; import { createTokens } from "./auth/createTokens"; import { isAuth } from "./auth/isAuth"; import { activeSwipesMax, __prod__ } from "./constants"; import { Match } from "./entities/Match"; import { Message } from "./entities/Message"; import { User } from "./entities/User"; import { View } from "./entities/View"; import { getAge, getUserIdOrder } from "./utils"; import { GetMessageStruct, MessageStruct, OneUserStruct, ReportStruct, UnmatchStruct, UpdatePushTokenStruct, UpdateUser, UserCodeImgs, ViewStruct, } from "./validation"; import http from "http"; import WebSocket, { Server } from "ws"; import url from "url"; import { verify } from "jsonwebtoken"; import { getUser } from "./queries/getUser"; import { Report } from "./entities/Report"; import { createMessageAdapter } from "@slack/interactive-messages"; import { queuePushNotifToSend, startPushNotificationRunner, } from "./pushNotifications"; import Redis from "ioredis"; import { RateLimiterRedis, IRateLimiterStoreOptions, } from "rate-limiter-flexible"; import { rateLimitMiddleware } from "./rateLimitMiddleware"; import { resetNumSwipesDaily } from "./resetNumSwipesDaily"; import isUuid from "is-uuid"; const SECONDS_IN_A_HALF_A_DAY = 86400 / 2; const main = async () => { const conn = await createConnection({ type: "postgres", database: __prod__ ? undefined : "vsinder", url: __prod__ ? process.env.DATABASE_URL : undefined, entities: [join(__dirname, "./entities/*")], migrations: [join(__dirname, "./migrations/*")], // synchronize: !__prod__, logging: !__prod__, }); console.log("connected, running migrations now"); await conn.runMigrations(); console.log("migrations ran"); const redisClient = new Redis(process.env.REDIS_URL, { enableOfflineQueue: false, }); const defaultRateLimitOpts: IRateLimiterStoreOptions = { storeClient: redisClient, execEvenly: false, blockDuration: SECONDS_IN_A_HALF_A_DAY, }; startPushNotificationRunner(); resetNumSwipesDaily(); const wsUsers: Record< string, { ws: WebSocket; openChatUserId: string | null } > = {}; const wsSend = (key: string, v: any) => { if (key in wsUsers) { wsUsers[key].ws.send(JSON.stringify(v)); } }; passport.use( new GitHubStrategy( { clientID: process.env.GITHUB_CLIENT_ID, clientSecret: process.env.GITHUB_CLIENT_SECRET, callbackURL: `${process.env.SERVER_URL}/auth/github/callback`, }, async (githubAccessToken, _, profile, cb) => { try { let user = await User.findOne({ githubId: profile.id }); const data: Partial<User> = { githubAccessToken, githubId: profile.id, photoUrl: profile.photos?.[0].value || (profile._json as any).avatar_url || "", other: profile._json, profileUrl: profile.profileUrl, username: profile.username, }; if (user) { await User.update(user.id, data); } else { data.bio = (profile._json as any)?.bio || ""; data.displayName = profile.displayName; user = await User.create(data).save(); } cb(undefined, createTokens(user)); } catch (err) { console.log(err); cb(new Error("internal error")); } } ) ); passport.serializeUser((user: any, done) => { done(null, user.accessToken); }); const app = express(); app.set("trust proxy", 1); app.use(helmet()); app.use( cors({ origin: "*", maxAge: __prod__ ? 86400 : undefined, exposedHeaders: [ "access-token", "refresh-token", "content-type", "content-length", ], }) ); const slackInteractions = createMessageAdapter( process.env.SLACK_SIGNING_SECRET ); app.post("/slack", slackInteractions.expressMiddleware()); app.use(express.json()); app.use(passport.initialize()); const router = Router(); app.use(router); if (!__prod__) { app.get("/all-users", async (_, res) => res.send(await User.find())); app.post("/login", async (req, res) => res.send(createTokens((await User.findOne(req.body.userId))!)) ); } slackInteractions.action({ type: "button" }, async (payload, respond) => { if (!payload.actions || !payload.actions.length) { respond({ text: "no actions?" }); return; } const [{ action_id, value }] = payload.actions; if (action_id === "shadow-ban") { try { await User.update(value, { shadowBanned: true }); respond({ text: "banned" }); } catch (err) { respond({ text: "Something went wrong: " + err.message }); } } }); router.post("/email/login", async (req, res, next) => { const { email, password } = req.body; if ( email !== process.env.APPLE_EMAIL && password !== process.env.APPLE_PASSWORD ) { next( createError( 400, "this is for the apple tester only, you should login with github" ) ); return; } let user = await User.findOne({ appleId: process.env.APPLE_EMAIL }); if (!user) { user = await User.create({ appleId: process.env.APPLE_EMAIL, photoUrl: "https://via.placeholder.com/150x150", shadowBanned: true, }).save(); } res.send(createTokens(user)); }); router.post("/apple/login", async (req, res, next) => { const { user: appleId } = req.body; if (typeof appleId !== "string") { next(createError(400, "something went wrong with apple auth")); return; } let user = await User.findOne({ appleId }); if (!user) { user = await User.create({ displayName: req.body?.fullName?.givenName || "", goal: "friendship", birthday: new Date(), codeImgIds: ["v56pytkbl-1606765556556.png"], appleId, photoUrl: "https://via.placeholder.com/150x150", shadowBanned: true, }).save(); } else if (!user.goal) { user.displayName = req.body?.fullName?.givenName || ""; user.goal = "friendship"; user.birthday = new Date(); user.codeImgIds = ["v56pytkbl-1606765556556.png"]; await user.save(); } res.send(createTokens(user)); }); router.get("/auth/github/rn", (req, res, next) => { const state = Buffer.from(JSON.stringify({ rn: true })).toString("base64"); passport.authenticate("github", { session: false, state, })(req, res, next); }); router.get("/auth/github", (req, res, next) => { const state = Buffer.from(JSON.stringify({ rn: false })).toString("base64"); passport.authenticate("github", { session: false, state, })(req, res, next); }); router.get( "/auth/github/callback", passport.authenticate("github"), (req: any, res) => { if (!req.user.accessToken || !req.user.refreshToken) { res.send(`something went wrong`); return; } const { state } = req.query; const { rn } = JSON.parse(Buffer.from(state, "base64").toString()); if (rn) { res.redirect( `${ __prod__ ? `vsinder://` : `exp:${ process.env.SERVER_URL.replace("http:", "").split(":")[0] }:19005/--/` }tokens/${req.user.accessToken}/${req.user.refreshToken}` ); } else { res.redirect( `http://localhost:54321/callback/${req.user.accessToken}/${req.user.refreshToken}` ); } } ); router.put( "/user/imgs", isAuth(), rateLimitMiddleware( new RateLimiterRedis({ ...defaultRateLimitOpts, points: 100, duration: SECONDS_IN_A_HALF_A_DAY, keyPrefix: "rl/user/imgs/", }) ), async (req: any, res, next) => { try { assert(req.body, UserCodeImgs); } catch (err) { next(createError(400, err.message)); return; } await User.update(req.userId, req.body); res.json({ ok: true }); } ); router.put( "/user/push-token", isAuth(), rateLimitMiddleware( new RateLimiterRedis({ ...defaultRateLimitOpts, points: 20, duration: SECONDS_IN_A_HALF_A_DAY, keyPrefix: "rl/user/push-token/", }) ), async (req: any, res, next) => { try { assert(req.body, UpdatePushTokenStruct); } catch (err) { next(createError(400, err.message)); return; } await User.update(req.userId, req.body); res.json({ ok: true }); } ); router.put( "/user", isAuth(), rateLimitMiddleware( new RateLimiterRedis({ ...defaultRateLimitOpts, points: 100, duration: SECONDS_IN_A_HALF_A_DAY, keyPrefix: "rl/user/", }) ), async (req: any, res, next) => { if (req.body.goal === "friendship") { req.body.ageRangeMin = 18; req.body.ageRangeMax = 33; req.body.location = "online"; } if (!req.body.location) { req.body.location = "online"; } try { assert(req.body, UpdateUser); } catch (err) { next(createError(400, err.message)); return; } await User.update(req.userId, req.body); res.json({ user: await getUser(req.userId) }); } ); const MS_IN_HOUR = 1000 * 60 * 60; const cache: Record<string, { data: any; date: Date }> = {}; router.get("/leaderboard/:category?", async (req, res, next) => { let { category } = req.params; if (!category) { category = "overall"; } if (category !== "overall" && category !== "male") { next(createError(400, "invalid category")); return; } if ( !(category in cache) || new Date().getTime() - cache[category].date.getTime() > MS_IN_HOUR ) { const data = await getConnection().query(` select u.id, flair, "numLikes", "displayName", date_part('year', age(birthday)) "age", bio, "codeImgIds", "photoUrl" from "user" u ${category === "male" ? `where gender = 'male'` : ""} order by u."numLikes" DESC limit 10 `); cache[category] = { data, date: new Date() }; } res.send({ profiles: cache[category].data }); }); router.get( "/feed", isAuth(), rateLimitMiddleware( new RateLimiterRedis({ ...defaultRateLimitOpts, points: 500, duration: SECONDS_IN_A_HALF_A_DAY, keyPrefix: "rl/feed/", }), "You've been using the app too much and hit the rate limit, come back tomorrow" ), async (req: any, res, next) => { const user = await User.findOne(req.userId); if (!user) { next(createError(400, "your account got deleted")); return; } if (!user.birthday) { next( createError( 400, "you need to set your birthday in the profile settings" ) ); return; } const myAge = getAge(new Date(user.birthday)); const paramNum = user.global ? 6 : 4; const loveWhere = ` and goal = 'love' and ("genderToShow" = 'everyone' or "genderToShow" = $${paramNum}) and $${paramNum + 1} <= date_part('year', age(birthday)) and $${paramNum + 2} >= date_part('year', age(birthday)) and "ageRangeMin" <= $${paramNum + 3} and "ageRangeMax" >= $${paramNum + 4} and (location = $${paramNum + 5} ${ user.global ? `or global = true` : "" }) ${ user.genderToShow !== "everyone" ? `and gender = $${paramNum + 6}` : "" } `; const loveParams = [ req.userId, req.userId, req.userId, ...(user.global ? [user.location, user.location] : []), user.gender, // my gender matches their gender they want to see user.ageRangeMin, user.ageRangeMax, myAge, myAge, user.location, ]; if (user.genderToShow !== "everyone") { loveParams.push( user.genderToShow // their gender matches my gender I want to see ); } const friendWhere = `and date_part('year', age(birthday)) ${ myAge >= 18 ? ">=" : "<" } 18`; const friendParams = [req.userId, req.userId, req.userId]; const profiles = await getConnection().query( ` select u.id, flair, "displayName", date_part('year', age(birthday)) "age", bio, "codeImgIds", "photoUrl" from "user" u left join view v on v."viewerId" = $1 and u.id = v."targetId" left join view v2 on $2 = v2."targetId" and v2.liked = true and u.id = v2."viewerId" where v is null and u.id != $3 ${user.goal === "love" ? loveWhere : friendWhere} and array_length("codeImgIds", 1) >= 1 and "shadowBanned" != true order by (case ${ user.goal === "love" && user.global ? ` when (u.location = $4 and v2 is not null) then random() - 1.2 when (u.location = $5) then random() - 1 ` : "" } when (v2 is not null) then random() - .2 else random() end) - u."numSwipes" / ${activeSwipesMax} limit 20; `, user.goal === "love" ? loveParams : friendParams ); res.json({ profiles, }); } ); router.get( "/matches/:cursor", isAuth(), rateLimitMiddleware( new RateLimiterRedis({ ...defaultRateLimitOpts, points: 500, duration: SECONDS_IN_A_HALF_A_DAY, keyPrefix: "rl/matches/", }), "You've been using the app too much and hit the rate limit, come back tomorrow" ), async (req: any, res) => { res.send({ matches: await getConnection().query( ` select case when u.id = ma."userId1" then ma.read2 else ma.read1 end "read", ma.id "matchId", u.id "userId", u.flair, u."photoUrl", u."displayName", date_part('epoch', ma."createdAt") * 1000 "createdAt", (select json_build_object('text', text, 'createdAt', date_part('epoch', m."createdAt")*1000) from message m where (m."recipientId" = ma."userId1" and m."senderId" = ma."userId2") or (m."senderId" = ma."userId1" and m."recipientId" = ma."userId2") order by m."createdAt" desc limit 1) message from match ma inner join "user" u on u.id != $1 and (u.id = ma."userId1" or u.id = ma."userId2") where (ma."userId1" = $2 or ma."userId2" = $3) and ma.unmatched = false limit 150 `, [req.userId, req.userId, req.userId] ), }); } ); router.get( "/messages/:userId/:cursor?", isAuth(), async (req: any, res, next) => { try { req.params.cursor = req.params.cursor ? parseInt(req.params.cursor) : undefined; assert(req.params, GetMessageStruct); } catch (err) { next(createError(400, err.message)); return; } const { userId, cursor } = req.params; const qb = getConnection() .createQueryBuilder() .select("m") .from(Message, "m") .where( `((m."recipientId" = :u1 and m."senderId" = :u2) or (m."recipientId" = :u3 and m."senderId" = :u4))`, { u1: userId, u2: req.userId, u3: req.userId, u4: userId, } ) .orderBy(`"createdAt"`, "DESC") .take(21); if (cursor && Number.isInteger(cursor)) { qb.andWhere(`m."createdAt" < :cursor`, { cursor: new Date(cursor) }); } const messages = await qb.getMany(); res.send({ messages: messages.slice(0, 20), hasMore: messages.length === 21, }); if (req.userId in wsUsers) { wsUsers[req.userId].openChatUserId = userId; } if (!cursor) { const userIdOrder = getUserIdOrder(userId, req.userId); getConnection() .createQueryBuilder() .update(Match) .set({ [userIdOrder.userId1 === req.userId ? "read1" : "read2"]: true, }) .where(`"userId1" = :userId1 and "userId2" = :userId2`, userIdOrder) .execute(); } } ); router.post( "/unmatch", isAuth(), rateLimitMiddleware( new RateLimiterRedis({ ...defaultRateLimitOpts, points: 100, duration: SECONDS_IN_A_HALF_A_DAY, keyPrefix: "rl/unmatch/", }) ), async (req: any, res, next) => { try { assert(req.body, UnmatchStruct); } catch (err) { next(createError(400, err.message)); return; } const { userId } = req.body; await Match.delete(getUserIdOrder(req.userId, userId)); wsSend(userId, { type: "unmatch", userId: req.userId }); res.send({ ok: true }); } ); router.post( "/report", isAuth(), rateLimitMiddleware( new RateLimiterRedis({ ...defaultRateLimitOpts, points: 100, duration: SECONDS_IN_A_HALF_A_DAY, keyPrefix: "rl/report/", }) ), async (req: any, res, next) => { try { assert(req.body, ReportStruct); } catch (err) { next(createError(400, err.message)); return; } const { userId, message, unmatchOrReject } = req.body; if (unmatchOrReject === "unmatch") { await Match.delete(getUserIdOrder(req.userId, userId)); wsSend(userId, { type: "unmatch", userId: req.userId }); } if (unmatchOrReject === "reject") { await View.insert({ viewerId: req.userId, targetId: userId, liked: false, }); } res.send({ ok: true }); // sketchy not catching errors ;; Report.insert({ reporterId: req.userId, targetId: userId, message }); User.findOne(userId).then((u) => { fetch(process.env.SLACK_REPORT_URL, { method: "post", headers: { "Content-type": "application/json", }, body: JSON.stringify({ blocks: [ { type: "section", fields: [ { type: "mrkdwn", text: "*Reporter id:*\n" + req.userId, }, { type: "mrkdwn", text: "*Target id:*\n" + userId, }, { type: "mrkdwn", text: "*type:*\n" + unmatchOrReject, }, { type: "mrkdwn", text: "*message:*\n" + message, }, ], }, ...(u?.codeImgIds.map((id) => ({ type: "image", title: { type: "plain_text", text: id, emoji: true, }, image_url: `https://img.vsinder.com/${id}`, alt_text: "code", })) || []), ...(u?.photoUrl ? [ { type: "image", title: { type: "plain_text", text: u.displayName + " | " + u.gender + " | " + u.bio + " | " + u.photoUrl, emoji: true, }, image_url: u.photoUrl, alt_text: "code", }, ] : []), { type: "actions", elements: [ { type: "button", action_id: "shadow-ban", text: { type: "plain_text", emoji: true, text: "shadow ban", }, style: "primary", value: userId, }, ], }, ], }), }); }); } ); router.post( "/message", isAuth(), rateLimitMiddleware( new RateLimiterRedis({ ...defaultRateLimitOpts, points: 1000, duration: SECONDS_IN_A_HALF_A_DAY, keyPrefix: "rl/message/", }) ), async (req: any, res, next) => { try { assert(req.body, MessageStruct); } catch (err) { next(createError(400, err.message)); return; } if ( !(await Match.findOne(getUserIdOrder(req.userId, req.body.recipientId))) ) { next(createError(400, "you got unmatched")); return; } const m = await Message.create({ ...req.body, senderId: req.userId, } as Message).save(); wsSend(m.recipientId, { type: "new-message", message: m }); res.send({ message: m }); if ( !(m.recipientId in wsUsers) || wsUsers[m.recipientId].openChatUserId !== req.userId ) { const userIdOrder = getUserIdOrder(req.userId, m.recipientId); Match.update( { ...userIdOrder, unmatched: false }, { [userIdOrder.userId1 === m.recipientId ? "read1" : "read2"]: false } ); } if (!(m.recipientId in wsUsers)) { queuePushNotifToSend({ idToSendTo: m.recipientId, otherId: req.userId, type: "message", text: m.text.slice(0, 100), }); } } ); router.post( "/view", isAuth(), rateLimitMiddleware( new RateLimiterRedis({ ...defaultRateLimitOpts, points: 500, duration: SECONDS_IN_A_HALF_A_DAY, blockDuration: 0, keyPrefix: "rl/view/", }), `You've hit the rate limit of 500 swipes a day, come back tomorrow` ), async (req: any, res, next) => { try { assert(req.body, ViewStruct); } catch (err) { next(createError(400, err.message)); return; } const { userId, liked } = req.body; let fav: View | undefined = undefined; try { const [_fav] = await Promise.all([ liked ? View.findOne({ viewerId: userId, targetId: req.userId, liked: true, }) : Promise.resolve(undefined), View.insert({ viewerId: req.userId, targetId: userId, liked, }), ]); fav = _fav; } catch (err) { if (err.message.includes("duplicate key")) { res.json({ match: false, ok: false, }); return; } else { throw err; } } let match = false; if (fav) { await Match.insert(getUserIdOrder(userId, req.userId)); match = true; } res.json({ match, ok: true, }); if (match) { const ids = getUserIdOrder(userId, req.userId); wsSend(userId, { type: "new-match", ...ids, }); wsSend(req.userId, { type: "new-match", ...ids, }); // does not have a ws connection if (!(userId in wsUsers)) { queuePushNotifToSend({ idToSendTo: userId, otherId: req.userId, type: "match", }); } } if (liked) { User.update(userId, { numLikes: () => '"numLikes" + 1' }); wsSend(userId, { type: "new-like" }); } User.update(req.userId, { numSwipes: () => `LEAST("numSwipes" + 1, ${activeSwipesMax})`, }); } ); router.get( "/user/:id", isAuth(), rateLimitMiddleware( new RateLimiterRedis({ ...defaultRateLimitOpts, points: 200, duration: SECONDS_IN_A_HALF_A_DAY, keyPrefix: "rl/user/:id", }) ), async (req: any, res, next) => { try { assert(req.params, OneUserStruct); } catch (err) { next(createError(400, err.message)); return; } const { id } = req.params; const { userId1, userId2 } = getUserIdOrder(req.userId, id); const isMe = userId1 === userId2; const [user] = await getConnection().query( ` select u.id, flair, "displayName", date_part('year', age(birthday)) "age", bio, "codeImgIds", "photoUrl" ${ isMe ? ` from "user" u where u.id = $1 ` : ` from "user" u, match m where m."userId1" = $1 and m."userId2" = $2 and u.id = $3 ` } `, isMe ? [id] : [userId1, userId2, id] ); res.json({ user, }); } ); router.post("/account/delete", isAuth(), async (req: any, res) => { if (isUuid.v4(req.userId)) { await User.delete(req.userId); } res.json({ ok: true, }); }); router.get("/me", isAuth(false), async (req: any, res) => { if (!req.userId) { res.json({ user: null, }); return; } res.json({ user: await getUser(req.userId), }); }); router.use((err: any, _: any, res: any, next: any) => { if (res.headersSent) { return next(err); } if (err.statusCode) { res.status(err.statusCode).send(err.message); } else { console.log(err); res.status(500).send("internal server error"); } }); const server = http.createServer(app); const wss = new Server({ noServer: true }); wss.on("connection", (ws: WebSocket, userId: string) => { if (!userId) { ws.terminate(); return; } // console.log("ws open: ", userId); wsUsers[userId] = { openChatUserId: null, ws }; ws.on("message", (e: any) => { const { type, userId: openChatUserId, }: { type: "message-open"; userId: string } = JSON.parse(e); if (type === "message-open") { if (userId in wsUsers) { wsUsers[userId].openChatUserId = openChatUserId; } } }); ws.on("close", () => { // console.log("ws close: ", userId); delete wsUsers[userId]; }); }); server.on("upgrade", async function upgrade(request, socket, head) { const good = (userId: string) => { wss.handleUpgrade(request, socket, head, function done(ws) { wss.emit("connection", ws, userId); }); }; const bad = () => { socket.write("HTTP/1.1 401 Unauthorized\r\n\r\n"); socket.destroy(); }; try { const { query: { accessToken, refreshToken }, } = url.parse(request.url, true); if ( !accessToken || !refreshToken || typeof accessToken !== "string" || typeof refreshToken !== "string" ) { return bad(); } try { const data = verify( accessToken, process.env.ACCESS_TOKEN_SECRET ) as any; return good(data.userId); } catch {} try { const data = verify( refreshToken, process.env.REFRESH_TOKEN_SECRET ) as any; const user = await User.findOne(data.userId); // token has been invalidated or user deleted if (!user || user.tokenVersion !== data.tokenVersion) { return bad(); } return good(data.userId); } catch {} } catch {} return bad(); }); server.listen(process.env.PORT ? parseInt(process.env.PORT) : 3001, () => { console.log("server started"); }); }; main();
the_stack
import { Util } from '../util' type Segment = [string, ...number[]] function rotate(x: number, y: number, rad: number) { return { x: x * Math.cos(rad) - y * Math.sin(rad), y: x * Math.sin(rad) + y * Math.cos(rad), } } function q2c( x1: number, y1: number, ax: number, ay: number, x2: number, y2: number, ) { const v13 = 1 / 3 const v23 = 2 / 3 return [ v13 * x1 + v23 * ax, v13 * y1 + v23 * ay, v13 * x2 + v23 * ax, v13 * y2 + v23 * ay, x2, y2, ] } function a2c( x1: number, y1: number, rx: number, ry: number, angle: number, largeArcFlag: number, sweepFlag: number, x2: number, y2: number, recursive?: [number, number, number, number], ): any[] { // for more information of where this math came from visit: // http://www.w3.org/TR/SVG11/implnote.html#ArcImplementationNotes const v120 = (Math.PI * 120) / 180 const rad = (Math.PI / 180) * (+angle || 0) let res = [] let xy let f1 let f2 let cx let cy if (!recursive) { xy = rotate(x1, y1, -rad) x1 = xy.x // eslint-disable-line y1 = xy.y // eslint-disable-line xy = rotate(x2, y2, -rad) x2 = xy.x // eslint-disable-line y2 = xy.y // eslint-disable-line const x = (x1 - x2) / 2 const y = (y1 - y2) / 2 let h = (x * x) / (rx * rx) + (y * y) / (ry * ry) if (h > 1) { h = Math.sqrt(h) rx = h * rx // eslint-disable-line ry = h * ry // eslint-disable-line } const rx2 = rx * rx const ry2 = ry * ry const k = (largeArcFlag === sweepFlag ? -1 : 1) * Math.sqrt( Math.abs( (rx2 * ry2 - rx2 * y * y - ry2 * x * x) / (rx2 * y * y + ry2 * x * x), ), ) cx = (k * rx * y) / ry + (x1 + x2) / 2 cy = (k * -ry * x) / rx + (y1 + y2) / 2 f1 = Math.asin((y1 - cy) / ry) f2 = Math.asin((y2 - cy) / ry) f1 = x1 < cx ? Math.PI - f1 : f1 f2 = x2 < cx ? Math.PI - f2 : f2 if (f1 < 0) { f1 = Math.PI * 2 + f1 } if (f2 < 0) { f2 = Math.PI * 2 + f2 } if (sweepFlag && f1 > f2) { f1 -= Math.PI * 2 } if (!sweepFlag && f2 > f1) { f2 -= Math.PI * 2 } } else { f1 = recursive[0] f2 = recursive[1] cx = recursive[2] cy = recursive[3] } let df = f2 - f1 if (Math.abs(df) > v120) { const f2old = f2 const x2old = x2 const y2old = y2 f2 = f1 + v120 * (sweepFlag && f2 > f1 ? 1 : -1) x2 = cx + rx * Math.cos(f2) // eslint-disable-line y2 = cy + ry * Math.sin(f2) // eslint-disable-line res = a2c(x2, y2, rx, ry, angle, 0, sweepFlag, x2old, y2old, [ f2, f2old, cx, cy, ]) } df = f2 - f1 const c1 = Math.cos(f1) const s1 = Math.sin(f1) const c2 = Math.cos(f2) const s2 = Math.sin(f2) const t = Math.tan(df / 4) const hx = (4 / 3) * (rx * t) const hy = (4 / 3) * (ry * t) const m1 = [x1, y1] const m2 = [x1 + hx * s1, y1 - hy * c1] const m3 = [x2 + hx * s2, y2 - hy * c2] const m4 = [x2, y2] m2[0] = 2 * m1[0] - m2[0] m2[1] = 2 * m1[1] - m2[1] if (recursive) { return [m2, m3, m4].concat(res) } { res = [m2, m3, m4].concat(res).join().split(',') const newres = [] const ii = res.length for (let i = 0; i < ii; i += 1) { newres[i] = i % 2 ? rotate(+res[i - 1], +res[i], rad).y : rotate(+res[i], +res[i + 1], rad).x } return newres } } function parse(pathData: string) { if (!pathData) { return null } const spaces = '\x09\x0a\x0b\x0c\x0d\x20\xa0\u1680\u180e\u2000\u2001\u2002\u2003\u2004\u2005\u2006\u2007\u2008\u2009\u200a\u202f\u205f\u3000\u2028\u2029' // https://regexper.com/#%28%5Ba-z%5D%29%5B%5Cs%2C%5D*%28%28-%3F%5Cd*%5C.%3F%5C%5Cd*%28%3F%3Ae%5B%5C-%2B%5D%3F%5Cd%2B%29%3F%5B%5Cs%5D*%2C%3F%5B%5Cs%5D*%29%2B%29 const segmentReg = new RegExp( `([a-z])[${spaces},]*((-?\\d*\\.?\\d*(?:e[\\-+]?\\d+)?[${spaces}]*,?[${spaces}]*)+)`, // eslint-disable-line 'ig', ) // https://regexper.com/#%28-%3F%5Cd*%5C.%3F%5Cd*%28%3F%3Ae%5B%5C-%2B%5D%3F%5Cd%2B%29%3F%29%5B%5Cs%5D*%2C%3F%5B%5Cs%5D* const commandParamReg = new RegExp( // eslint-disable-next-line `(-?\\d*\\.?\\d*(?:e[\\-+]?\\d+)?)[${spaces}]*,?[${spaces}]*`, 'ig', ) const paramsCount = { a: 7, c: 6, h: 1, l: 2, m: 2, q: 4, s: 4, t: 2, v: 1, z: 0, } const segmetns: Segment[] = [] pathData.replace(segmentReg, (input: string, cmd: string, args: string) => { const params: number[] = [] let command = cmd.toLowerCase() args.replace(commandParamReg, (a: string, b: string) => { if (b) { params.push(+b) } return a }) if (command === 'm' && params.length > 2) { segmetns.push([cmd, ...params.splice(0, 2)]) command = 'l' cmd = cmd === 'm' ? 'l' : 'L' // eslint-disable-line } const count = paramsCount[command as keyof typeof paramsCount] while (params.length >= count) { segmetns.push([cmd, ...params.splice(0, count)]) if (!count) { break } } return input }) return segmetns } function abs(pathString: string) { const pathArray = parse(pathString) // if invalid string, return 'M 0 0' if (!pathArray || !pathArray.length) { return [['M', 0, 0]] } let x = 0 let y = 0 let mx = 0 let my = 0 const segments = [] for (let i = 0, ii = pathArray.length; i < ii; i += 1) { const r: any = [] segments.push(r) const segment = pathArray[i] const command = segment[0] if (command !== command.toUpperCase()) { r[0] = command.toUpperCase() switch (r[0]) { case 'A': r[1] = segment[1] r[2] = segment[2] r[3] = segment[3] r[4] = segment[4] r[5] = segment[5] r[6] = +segment[6] + x r[7] = +segment[7] + y break case 'V': r[1] = +segment[1] + y break case 'H': r[1] = +segment[1] + x break case 'M': mx = +segment[1] + x my = +segment[2] + y for (let j = 1, jj = segment.length; j < jj; j += 1) { r[j] = +segment[j] + (j % 2 ? x : y) } break default: for (let j = 1, jj = segment.length; j < jj; j += 1) { r[j] = +segment[j] + (j % 2 ? x : y) } break } } else { for (let j = 0, jj = segment.length; j < jj; j += 1) { r[j] = segment[j] } } switch (r[0]) { case 'Z': x = +mx y = +my break case 'H': x = r[1] break case 'V': y = r[1] break case 'M': mx = r[r.length - 2] my = r[r.length - 1] x = r[r.length - 2] y = r[r.length - 1] break default: x = r[r.length - 2] y = r[r.length - 1] break } } return segments } function normalize(path: string) { const pathArray = abs(path) const attrs = { x: 0, y: 0, bx: 0, by: 0, X: 0, Y: 0, qx: null, qy: null } function processPath(path: any[], d: any, pcom: string) { let nx let ny if (!path) { return ['C', d.x, d.y, d.x, d.y, d.x, d.y] } if (!(path[0] in { T: 1, Q: 1 })) { d.qx = null d.qy = null } switch (path[0]) { case 'M': d.X = path[1] d.Y = path[2] break case 'A': if (parseFloat(path[1]) === 0 || parseFloat(path[2]) === 0) { // https://www.w3.org/TR/SVG/paths.html#ArcOutOfRangeParameters // "If either rx or ry is 0, then this arc is treated as a // straight line segment (a "lineto") joining the endpoints." return ['L', path[6], path[7]] } return ['C'].concat(a2c.apply(0, [d.x, d.y].concat(path.slice(1)))) case 'S': if (pcom === 'C' || pcom === 'S') { // In 'S' case we have to take into account, if the previous command is C/S. nx = d.x * 2 - d.bx // And reflect the previous ny = d.y * 2 - d.by // command's control point relative to the current point. } else { // or some else or nothing nx = d.x ny = d.y } return ['C', nx, ny].concat(path.slice(1)) case 'T': if (pcom === 'Q' || pcom === 'T') { // In 'T' case we have to take into account, if the previous command is Q/T. d.qx = d.x * 2 - d.qx // And make a reflection similar d.qy = d.y * 2 - d.qy // to case 'S'. } else { // or something else or nothing d.qx = d.x d.qy = d.y } return ['C'].concat( q2c(d.x, d.y, d.qx, d.qy, path[1], path[2]) as any[], ) case 'Q': d.qx = path[1] d.qy = path[2] return ['C'].concat( q2c(d.x, d.y, path[1], path[2], path[3], path[4]) as any[], ) case 'H': return ['L'].concat(path[1], d.y) case 'V': return ['L'].concat(d.x, path[1]) case 'L': break case 'Z': break default: break } return path } function fixArc(pp: any[], i: number) { if (pp[i].length > 7) { pp[i].shift() const pi = pp[i] while (pi.length) { // if created multiple 'C's, their original seg is saved commands[i] = 'A' i += 1 // eslint-disable-line pp.splice(i, 0, ['C'].concat(pi.splice(0, 6))) } pp.splice(i, 1) ii = pathArray.length } } const commands = [] // path commands of original path p let prevCommand = '' // holder for previous path command of original path let ii = pathArray.length for (let i = 0; i < ii; i += 1) { let command = '' // temporary holder for original path command if (pathArray[i]) { command = pathArray[i][0] // save current path command } if (command !== 'C') { // C is not saved yet, because it may be result of conversion commands[i] = command // Save current path command if (i > 0) { prevCommand = commands[i - 1] // Get previous path command pcom } } // Previous path command is inputted to processPath pathArray[i] = processPath(pathArray[i], attrs, prevCommand) if (commands[i] !== 'A' && command === 'C') { commands[i] = 'C' // 'A' is the only command } // which may produce multiple 'C's // so we have to make sure that 'C' is also 'C' in original path fixArc(pathArray, i) // fixArc adds also the right amount of 'A's to pcoms const seg = pathArray[i] const seglen = seg.length attrs.x = seg[seglen - 2] attrs.y = seg[seglen - 1] attrs.bx = parseFloat(seg[seglen - 4]) || attrs.x attrs.by = parseFloat(seg[seglen - 3]) || attrs.y } // make sure normalized path data string starts with an M segment if (!pathArray[0][0] || pathArray[0][0] !== 'M') { pathArray.unshift(['M', 0, 0]) } return pathArray } /** * Converts provided SVG path data string into a normalized path data string. * * The normalization uses a restricted subset of path commands; all segments * are translated into lineto, curveto, moveto, and closepath segments. * * Relative path commands are changed into their absolute counterparts, * and chaining of coordinates is disallowed. * * The function will always return a valid path data string; if an input * string cannot be normalized, 'M 0 0' is returned. */ export function normalizePathData(pathData: string) { return normalize(pathData) .map((segment: Segment) => segment.map((item) => typeof item === 'string' ? item : Util.round(item, 2), ), ) .join(',') .split(',') .join(' ') }
the_stack
import { JsonObject, logging } from '@angular-devkit/core'; import chalk from 'chalk'; import program from 'commander'; import * as ejs from 'ejs'; import * as fs from 'fs'; import * as path from 'path'; import * as semver from 'semver'; import { packages } from './packages'; import * as versionsHelper from './versions'; const changelogTemplate = ejs.compile( fs.readFileSync(path.join(__dirname, './templates/changelog.ejs'), 'utf-8'), { client: true } ); const conventionalCommitsParser = require('conventional-commits-parser'); const gitRawCommits = require('git-raw-commits'); const ghGot = require('gh-got'); const through = require('through2'); export interface ChangelogOptions { to: string; githubTokenFile?: string; githubToken?: string; library?: string; stdout?: boolean; } const breakingChangesKeywords = ['BREAKING CHANGE', 'BREAKING CHANGES']; const deprecationsKeywords = ['DEPRECATION', 'DEPRECATED', 'DEPRECATIONS']; export default async function run( args: ChangelogOptions, logger: logging.Logger ) { const commits: JsonObject[] = []; let toSha: string | null = null; const breakingChanges: JsonObject[] = []; const deprecations: JsonObject[] = []; const versionFromTag = args.to .split('-') .filter((_, i) => i !== 0) .join('-'); const newVersion = semver.parse(versionFromTag, { includePrerelease: true, loose: true, }); let fromToken: string; try { const packageVersions = await versionsHelper.fetchPackageVersions( args.library! ); const previousVersion = versionsHelper.extractPreviousVersionForChangelog( packageVersions, newVersion?.version! ); fromToken = (previousVersion && args.to.split(newVersion?.version!).join(previousVersion)) as string; } catch (err) { // package not found - assuming first release fromToken = ''; } const githubToken = ( args.githubToken || (args.githubTokenFile && fs.readFileSync(args.githubTokenFile, 'utf-8')) || '' ).trim(); const libraryPaths: Record<string, string> = { '@spartacus/storefront': 'projects/storefrontlib', '@spartacus/core': 'projects/core', '@spartacus/styles': 'projects/storefrontstyles', '@spartacus/assets': 'projects/assets', '@spartacus/schematics': 'projects/schematics', '@spartacus/user': 'feature-libs/user', '@spartacus/cds': 'integration-libs/cds', '@spartacus/organization': 'feature-libs/organization', '@spartacus/product': 'feature-libs/product', '@spartacus/product-configurator': 'feature-libs/product-configurator', '@spartacus/storefinder': 'feature-libs/storefinder', '@spartacus/checkout': 'feature-libs/checkout', '@spartacus/asm': 'feature-libs/asm', '@spartacus/smartedit': 'feature-libs/smartedit', '@spartacus/tracking': 'feature-libs/tracking', '@spartacus/qualtrics': 'feature-libs/qualtrics', '@spartacus/cdc': 'integration-libs/cdc', '@spartacus/setup': 'core-libs/setup', '@spartacus/cart': 'feature-libs/cart', '@spartacus/order': 'feature-libs/order', '@spartacus/digital-payments': 'integration-libs/digital-payments', '@spartacus/epd-visualization': 'integration-libs/epd-visualization', }; const duplexUtil = through(function ( this: NodeJS.ReadStream, chunk: unknown, _: unknown, callback: () => {} ) { this.push(chunk); callback(); }); function getRawCommitsStream(to: string) { return gitRawCommits({ from: fromToken, to, path: args.library ? path.join(__dirname, '..', libraryPaths[args.library]) : path.join(__dirname, '..'), format: '%B%n-hash-%n%H%n-gitTags-%n%D%n-committerDate-%n%ci%n-authorName-%n%aN%n', }) as NodeJS.ReadStream; } function getCommitsStream(): NodeJS.ReadStream { getRawCommitsStream(args.to) .on('error', () => { getRawCommitsStream('HEAD') .on('error', (err) => { logger.fatal('An error happened: ' + err.message); return ''; }) .pipe(duplexUtil); }) .pipe(duplexUtil); return duplexUtil; } return new Promise((resolve) => { getCommitsStream() .pipe( through((chunk: Buffer, _: string, callback: Function) => { // Replace github URLs with `@XYZ#123` const commit = chunk .toString('utf-8') .replace(/https?:\/\/github.com\/(.*?)\/issues\/(\d+)/g, '@$1#$2'); callback(undefined, new Buffer(commit)); }) ) .pipe( conventionalCommitsParser({ headerPattern: /^(\w*)(?:\(([^)]*)\))?: (.*)$/, headerCorrespondence: ['type', 'scope', 'subject'], noteKeywords: [...breakingChangesKeywords, ...deprecationsKeywords], revertPattern: /^revert:\s([\s\S]*?)\s*This reverts commit (\w*)\./, revertCorrespondence: [`header`, `hash`], issuePrefixes: ['#', 'GH-', 'gh-'], }) ) .pipe( through.obj((chunk: JsonObject, _: string, cb: Function) => { try { const maybeTag = chunk.gitTags && (chunk.gitTags as string).match(/tag: (.*)/); const tags = maybeTag && maybeTag[1].split(/,/g); chunk['tags'] = tags; if (tags && tags.find((x) => x == args.to)) { toSha = chunk.hash as string; } const notes: any = chunk.notes; if (Array.isArray(notes)) { notes.forEach((note) => { if (breakingChangesKeywords.includes(note.title)) { breakingChanges.push({ content: note.text, commit: chunk, }); } else if (deprecationsKeywords.includes(note.title)) { deprecations.push({ content: note.text, commit: chunk, }); } }); } commits.push(chunk); cb(); } catch (err) { cb(err); } }) ) .on('finish', resolve); }) .then(() => { const markdown: string = changelogTemplate({ ...args, include: (x: string, v: {}) => ejs.render( fs.readFileSync( path.join(__dirname, './templates', `${x}.ejs`), 'utf-8' ), v ), commits, packages, breakingChanges, deprecations, }); if (args.stdout || !githubToken) { console.log(markdown); process.exit(0); } // Check if we need to edit or create a new one. return ghGot('repos/SAP/spartacus/releases').then((x: JsonObject) => [ x, markdown, ]); }) .then(([body, markdown]) => { const json = body.body; const maybeRelease = json.find((x: JsonObject) => x.tag_name == args.to); const id = maybeRelease ? `/${maybeRelease.id}` : ''; const semversion = (args.to && semver.parse(args.to)) || { prerelease: '', }; return ghGot('repos/SAP/spartacus/releases' + id, { body: { body: markdown, draft: true, name: args.to, prerelease: semversion.prerelease.length > 0, tag_name: args.to, ...(toSha ? { target_commitish: toSha } : {}), }, token: githubToken, }); }); } program .option('--to <commit>', 'To which commit/tag') .option('--verbose', 'Print output') .option('--githubToken <token>', 'Github token for release generation') .option('--tokenFile <pathToFile>', 'File with github token') .option('--lib <lib>', 'Changelog for passed library') .parse(process.argv); const config = { from: program.from, to: program.to, stdout: program.verbose || false, githubToken: program.githubToken, githubTokenFile: program.tokenFile, library: program.lib, }; if (typeof config.to === 'undefined') { console.error(chalk.red('Missing --to option with end commit/tag')); process.exit(1); } else if ( config.stdout === false && typeof config.githubToken === 'undefined' && typeof config.githubTokenFile === 'undefined' ) { console.error( chalk.red( 'Missing --githubToken/--tokenFile option with correct github token' ) ); process.exit(1); } else if (typeof config.library === 'string') { switch (config.library) { case 'core': case '@spartacus/core': config.library = '@spartacus/core'; break; case 'storefrontlib': case 'storefront': case '@spartacus/storefront': case '@spartacus/storefrontlib': config.library = '@spartacus/storefront'; break; case 'styles': case '@spartacus/styles': case 'storefrontstyles': config.library = '@spartacus/styles'; break; case 'assets': case '@spartacus/assets': config.library = '@spartacus/assets'; break; case 'schematics': case '@spartacus/schematics': config.library = '@spartacus/schematics'; break; case 'user': case '@spartacus/user': config.library = '@spartacus/user'; break; case 'cds': case '@spartacus/cds': config.library = '@spartacus/cds'; break; case 'organization': case '@spartacus/organization': config.library = '@spartacus/organization'; break; case 'product': case '@spartacus/product': case '@spartacus/product/configurators': case '@spartacus/product/configurators/common': case '@spartacus/product/configurators/cpq': case '@spartacus/product/configurators/variant': case '@spartacus/product/configurators/textfield': case '@spartacus/product/variants': config.library = '@spartacus/product'; break; case 'product-configurator': case '@spartacus/product-configurator': config.library = '@spartacus/product-configurator'; break; case 'cdc': case '@spartacus/cdc': config.library = '@spartacus/cdc'; break; case 'digital-payments': case '@spartacus/digital-payments': config.library = '@spartacus/digital-payments'; break; case 'storefinder': case '@spartacus/storefinder': config.library = '@spartacus/storefinder'; break; case 'checkout': case '@spartacus/checkout': config.library = '@spartacus/checkout'; break; case 'tracking': case '@spartacus/tracking': config.library = '@spartacus/tracking'; break; case 'qualtrics': case '@spartacus/qualtrics': config.library = '@spartacus/qualtrics'; break; case 'smartedit': case '@spartacus/smartedit': config.library = '@spartacus/smartedit'; break; case 'setup': case '@spartacus/setup': config.library = '@spartacus/setup'; break; case 'cart': case '@spartacus/cart': config.library = '@spartacus/cart'; break; case 'order': case '@spartacus/order': config.library = '@spartacus/order'; break; case 'digital-payments': case '@spartacus/digital-payments': config.library = '@spartacus/digital-payments'; break; case 'epd-visualization': case '@spartacus/epd-visualization': config.library = '@spartacus/epd-visualization'; break; default: config.library = undefined; } } run(config, new logging.NullLogger());
the_stack
import { LAMPORTS_PER_SOL, AccountInfo } from '@solana/web3.js'; import fs from 'fs'; import weighted from 'weighted'; import path from 'path'; import { BN, Program, web3 } from '@project-serum/anchor'; import { Token, TOKEN_PROGRAM_ID } from '@solana/spl-token'; import { StorageType } from './storage-type'; import { getAtaForMint } from './accounts'; import { CLUSTERS, DEFAULT_CLUSTER } from './constants'; import { Uses, UseMethod } from '@metaplex-foundation/mpl-token-metadata'; const { readFile } = fs.promises; export async function getCandyMachineV2Config( walletKeyPair: web3.Keypair, anchorProgram: Program, configPath: any, ): Promise<{ storage: StorageType; ipfsInfuraProjectId: string; number: number; ipfsInfuraSecret: string; awsS3Bucket: string; retainAuthority: boolean; mutable: boolean; batchSize: number; price: BN; treasuryWallet: web3.PublicKey; splToken: web3.PublicKey | null; gatekeeper: null | { expireOnUse: boolean; gatekeeperNetwork: web3.PublicKey; }; endSettings: null | [number, BN]; whitelistMintSettings: null | { mode: any; mint: web3.PublicKey; presale: boolean; discountPrice: null | BN; }; hiddenSettings: null | { name: string; uri: string; hash: Uint8Array; }; goLiveDate: BN | null; uuid: string; arweaveJwk: string; }> { if (configPath === undefined) { throw new Error('The configPath is undefined'); } const configString = fs.readFileSync(configPath); //@ts-ignore const config = JSON.parse(configString); const { storage, ipfsInfuraProjectId, number, ipfsInfuraSecret, awsS3Bucket, noRetainAuthority, noMutable, batchSize, price, splToken, splTokenAccount, solTreasuryAccount, gatekeeper, endSettings, hiddenSettings, whitelistMintSettings, goLiveDate, uuid, arweaveJwk, } = config; let wallet; let parsedPrice = price; const splTokenAccountFigured = splTokenAccount ? splTokenAccount : splToken ? ( await getAtaForMint( new web3.PublicKey(splToken), walletKeyPair.publicKey, ) )[0] : null; if (splToken) { if (solTreasuryAccount) { throw new Error( 'If spl-token-account or spl-token is set then sol-treasury-account cannot be set', ); } if (!splToken) { throw new Error( 'If spl-token-account is set, spl-token must also be set', ); } const splTokenKey = new web3.PublicKey(splToken); const splTokenAccountKey = new web3.PublicKey(splTokenAccountFigured); if (!splTokenAccountFigured) { throw new Error( 'If spl-token is set, spl-token-account must also be set', ); } const token = new Token( anchorProgram.provider.connection, splTokenKey, TOKEN_PROGRAM_ID, walletKeyPair, ); const mintInfo = await token.getMintInfo(); if (!mintInfo.isInitialized) { throw new Error(`The specified spl-token is not initialized`); } const tokenAccount = await token.getAccountInfo(splTokenAccountKey); if (!tokenAccount.isInitialized) { throw new Error(`The specified spl-token-account is not initialized`); } if (!tokenAccount.mint.equals(splTokenKey)) { throw new Error( `The spl-token-account's mint (${tokenAccount.mint.toString()}) does not match specified spl-token ${splTokenKey.toString()}`, ); } wallet = new web3.PublicKey(splTokenAccountKey); parsedPrice = price * 10 ** mintInfo.decimals; if (whitelistMintSettings?.discountPrice) { whitelistMintSettings.discountPrice *= 10 ** mintInfo.decimals; } } else { parsedPrice = price * 10 ** 9; if (whitelistMintSettings?.discountPrice) { whitelistMintSettings.discountPrice *= 10 ** 9; } wallet = solTreasuryAccount ? new web3.PublicKey(solTreasuryAccount) : walletKeyPair.publicKey; } if (whitelistMintSettings) { whitelistMintSettings.mint = new web3.PublicKey(whitelistMintSettings.mint); if (whitelistMintSettings?.discountPrice) { whitelistMintSettings.discountPrice = new BN( whitelistMintSettings.discountPrice, ); } } if (endSettings) { if (endSettings.endSettingType.date) { endSettings.number = new BN(parseDate(endSettings.value)); } else if (endSettings.endSettingType.amount) { endSettings.number = new BN(endSettings.value); } delete endSettings.value; } if (hiddenSettings) { const utf8Encode = new TextEncoder(); hiddenSettings.hash = utf8Encode.encode(hiddenSettings.hash); } if (gatekeeper) { gatekeeper.gatekeeperNetwork = new web3.PublicKey( gatekeeper.gatekeeperNetwork, ); } return { storage, ipfsInfuraProjectId, number, ipfsInfuraSecret, awsS3Bucket, retainAuthority: !noRetainAuthority, mutable: !noMutable, batchSize, price: new BN(parsedPrice), treasuryWallet: wallet, splToken: splToken ? new web3.PublicKey(splToken) : null, gatekeeper, endSettings, hiddenSettings, whitelistMintSettings, goLiveDate: goLiveDate ? new BN(parseDate(goLiveDate)) : null, uuid, arweaveJwk, }; } export async function readJsonFile(fileName: string) { const file = await readFile(fileName, 'utf-8'); return JSON.parse(file); } export function shuffle(array) { let currentIndex = array.length, randomIndex; // While there remain elements to shuffle... while (currentIndex != 0) { // Pick a remaining element... randomIndex = Math.floor(Math.random() * currentIndex); currentIndex--; // And swap it with the current element. [array[currentIndex], array[randomIndex]] = [ array[randomIndex], array[currentIndex], ]; } return array; } export const assertValidBreakdown = breakdown => { const total = Object.values(breakdown).reduce( (sum: number, el: number) => (sum += el), 0, ); if (total > 101 || total < 99) { console.log(breakdown); throw new Error('Breakdown not within 1% of 100! It is: ' + total); } }; export const generateRandomSet = (breakdown, dnp) => { let valid = true; let tmp = {}; do { valid = true; const keys = shuffle(Object.keys(breakdown)); keys.forEach(attr => { const breakdownToUse = breakdown[attr]; const formatted = Object.keys(breakdownToUse).reduce((f, key) => { if (breakdownToUse[key]['baseValue']) { f[key] = breakdownToUse[key]['baseValue']; } else { f[key] = breakdownToUse[key]; } return f; }, {}); assertValidBreakdown(formatted); const randomSelection = weighted.select(formatted); tmp[attr] = randomSelection; }); keys.forEach(attr => { let breakdownToUse = breakdown[attr]; keys.forEach(otherAttr => { if ( tmp[otherAttr] && typeof breakdown[otherAttr][tmp[otherAttr]] != 'number' && breakdown[otherAttr][tmp[otherAttr]][attr] ) { breakdownToUse = breakdown[otherAttr][tmp[otherAttr]][attr]; console.log( 'Because this item got attr', tmp[otherAttr], 'we are using different probabilites for', attr, ); assertValidBreakdown(breakdownToUse); const randomSelection = weighted.select(breakdownToUse); tmp[attr] = randomSelection; } }); }); Object.keys(tmp).forEach(attr1 => { Object.keys(tmp).forEach(attr2 => { if ( dnp[attr1] && dnp[attr1][tmp[attr1]] && dnp[attr1][tmp[attr1]][attr2] && dnp[attr1][tmp[attr1]][attr2].includes(tmp[attr2]) ) { console.log('Not including', tmp[attr1], tmp[attr2], 'together'); valid = false; tmp = {}; } }); }); } while (!valid); return tmp; }; export const getUnixTs = () => { return new Date().getTime() / 1000; }; export function sleep(ms: number): Promise<void> { return new Promise(resolve => setTimeout(resolve, ms)); } export function fromUTF8Array(data: number[]) { // array of bytes let str = '', i; for (i = 0; i < data.length; i++) { const value = data[i]; if (value < 0x80) { str += String.fromCharCode(value); } else if (value > 0xbf && value < 0xe0) { str += String.fromCharCode(((value & 0x1f) << 6) | (data[i + 1] & 0x3f)); i += 1; } else if (value > 0xdf && value < 0xf0) { str += String.fromCharCode( ((value & 0x0f) << 12) | ((data[i + 1] & 0x3f) << 6) | (data[i + 2] & 0x3f), ); i += 2; } else { // surrogate pair const charCode = (((value & 0x07) << 18) | ((data[i + 1] & 0x3f) << 12) | ((data[i + 2] & 0x3f) << 6) | (data[i + 3] & 0x3f)) - 0x010000; str += String.fromCharCode( (charCode >> 10) | 0xd800, (charCode & 0x03ff) | 0xdc00, ); i += 3; } } return str; } export function parsePrice(price: string, mantissa: number = LAMPORTS_PER_SOL) { return Math.ceil(parseFloat(price) * mantissa); } export function parseDate(date) { if (date === 'now') { return Date.now() / 1000; } return Date.parse(date) / 1000; } export const getMultipleAccounts = async ( connection: any, keys: string[], commitment: string, ) => { const result = await Promise.all( chunks(keys, 99).map(chunk => getMultipleAccountsCore(connection, chunk, commitment), ), ); const array = result .map( a => //@ts-ignore a.array.map(acc => { if (!acc) { return undefined; } const { data, ...rest } = acc; const obj = { ...rest, data: Buffer.from(data[0], 'base64'), } as AccountInfo<Buffer>; return obj; }) as AccountInfo<Buffer>[], ) //@ts-ignore .flat(); return { keys, array }; }; export function chunks(array, size) { return Array.apply(0, new Array(Math.ceil(array.length / size))).map( (_, index) => array.slice(index * size, (index + 1) * size), ); } export function generateRandoms( numberOfAttrs: number = 1, total: number = 100, ) { const numbers = []; const loose_percentage = total / numberOfAttrs; for (let i = 0; i < numberOfAttrs; i++) { const random = Math.floor(Math.random() * loose_percentage) + 1; numbers.push(random); } const sum = numbers.reduce((prev, cur) => { return prev + cur; }, 0); numbers.push(total - sum); return numbers; } export const getMetadata = ( name: string = '', symbol: string = '', index: number = 0, creators, description: string = '', seller_fee_basis_points: number = 500, attrs, collection, treatAttributesAsFileNames: boolean, ) => { const attributes = []; for (const prop in attrs) { attributes.push({ trait_type: prop, value: treatAttributesAsFileNames ? path.parse(attrs[prop]).name : attrs[prop], }); } return { name: `${name}${index + 1}`, symbol, image: `${index}.png`, properties: { files: [ { uri: `${index}.png`, type: 'image/png', }, ], category: 'image', creators, }, description, seller_fee_basis_points, attributes, collection, }; }; const getMultipleAccountsCore = async ( connection: any, keys: string[], commitment: string, ) => { const args = connection._buildArgs([keys], commitment, 'base64'); const unsafeRes = await connection._rpcRequest('getMultipleAccounts', args); if (unsafeRes.error) { throw new Error( 'failed to get info about account ' + unsafeRes.error.message, ); } if (unsafeRes.result.value) { const array = unsafeRes.result.value as AccountInfo<string[]>[]; return { keys, array }; } // TODO: fix throw new Error(); }; export const getPriceWithMantissa = async ( price: number, mint: web3.PublicKey, walletKeyPair: any, anchorProgram: Program, ): Promise<number> => { const token = new Token( anchorProgram.provider.connection, new web3.PublicKey(mint), TOKEN_PROGRAM_ID, walletKeyPair, ); const mintInfo = await token.getMintInfo(); const mantissa = 10 ** mintInfo.decimals; return Math.ceil(price * mantissa); }; export function getCluster(name: string): string { for (const cluster of CLUSTERS) { if (cluster.name === name) { return cluster.url; } } return DEFAULT_CLUSTER.url; } export function parseUses(useMethod: string, total: number): Uses | null { if (!!useMethod && !!total) { const realUseMethod = (UseMethod as any)[useMethod]; if (!realUseMethod) { throw new Error(`Invalid use method: ${useMethod}`); } return new Uses({ useMethod: realUseMethod, total, remaining: total }); } return null; }
the_stack
import { AfterViewInit, Component, OnDestroy } from '@angular/core'; import { Router } from '@angular/router'; import { LocalDataSource } from 'ng2-smart-table'; import { UsersService } from '../../@core/data/users.service'; import { OrdersService } from '../../@core/data/orders.service'; import User from '@modules/server.common/entities/User'; import Order from '@modules/server.common/entities/Order'; import { UserMutationComponent } from '../../@shared/user/user-mutation'; import { ToasterService } from 'angular2-toaster'; import { TranslateService } from '@ngx-translate/core'; import { Observable, forkJoin } from 'rxjs'; import _ from 'lodash'; import { NgbModal } from '@ng-bootstrap/ng-bootstrap'; import { Subject } from 'rxjs'; import { takeUntil, first } from 'rxjs/operators'; import { getCountryName } from '@modules/server.common/entities/GeoLocation'; import { CountryRenderComponent } from './+invites/country-render/country-render.component'; import { RedirectNameComponent } from '../../@shared/render-component/name-redirect/name-redirect.component'; import { CustomerImageComponent } from '../../@shared/render-component/customer-table/customer-table/customer-image.component'; import { NotifyService } from '../../@core/services/notify/notify.service'; import { CustomerOrdersNumberComponent } from '../../@shared/render-component/customer-table/customer-orders-number/customer-orders-number.component'; import { CustomerEmailComponent } from '../../@shared/render-component/customer-email/customer-email.component'; import { CustomerPhoneComponent } from '../../@shared/render-component/customer-phone/customer-phone.component'; import { BanConfirmComponent } from '@app/@shared/user/ban-confirm'; export interface CustomerViewModel { id: string; name: string; image: string; email: string; phone: string; country: string; city: string; address: string; ordersQty: number; isBanned: boolean; } const perPage = 7; @Component({ selector: 'ea-customers', templateUrl: './customers.component.html', styleUrls: ['/customers.component.scss'], }) export class CustomersComponent implements AfterViewInit, OnDestroy { private ngDestroy$ = new Subject<void>(); static noInfoSign = ''; public loading: boolean; public showBanLoading = false; protected customers: User[] = []; protected orders: Order[] = []; protected settingsSmartTable: object; protected sourceSmartTable = new LocalDataSource(); private _selectedCustomers: CustomerViewModel[] = []; private dataCount: number; private $users; public _showOnlyBanned: boolean; constructor( private readonly _router: Router, private readonly _ordersService: OrdersService, private readonly _usersService: UsersService, private readonly _modalService: NgbModal, private readonly _translateService: TranslateService, private readonly _notifyService: NotifyService ) { this._loadSettingsSmartTable(); } protected get hasSelectedCustomers(): boolean { return this._selectedCustomers.length > 0; } ngAfterViewInit() { this._addCustomHTMLElements(); this._applyTranslationOnSmartTable(); this.smartTableChange(); this._loadDataSmartTable(); } protected selectUser(ev) { const userId: string = ev.data.id; this._router.navigate(['/customers/list' + userId]); } protected showCreateUserModal() { this._modalService.open(UserMutationComponent, { size: 'lg', container: 'nb-layout', windowClass: 'ng-custom', backdrop: 'static', }); } protected selectCustomerTmp(ev) { this._selectedCustomers = ev.selected; } protected deleteSelectedRows() { const idsForDelete: string[] = this._selectedCustomers.map((w) => w.id); try { this.loading = true; this._usersService .removeByIds(idsForDelete) .pipe(first()) .toPromise(); this._selectedCustomers = []; this.loading = false; const message = `Users was removed`; this._notifyService.success(message); } catch (error) { let message = `Something went wrong`; if (error.message === 'Validation error') { message = error.message; } this.loading = false; this._notifyService.error(message); } } protected banSelectedRows() { if (this.isUserBanned) { this.showUnbanPopup(); } else { this.showBanPopup(); } } private showUnbanPopup() { const modal = this._modalService.open(BanConfirmComponent, { size: 'lg', container: 'nb-layout', windowClass: 'ng-custom', backdrop: 'static', }); modal.componentInstance.user = this._selectedCustomers[0]; modal.result .then(async (user) => { this.showBanLoading = true; await this._usersService.unbanUser(user.id); this._loadDataSmartTable(); this.showBanLoading = false; this._notifyService.success(`${user.name} is unbanned!`); }) .catch((_) => {}); } private showBanPopup() { const modal = this._modalService.open(BanConfirmComponent, { size: 'lg', container: 'nb-layout', windowClass: 'ng-custom', backdrop: 'static', }); modal.componentInstance.user = this._selectedCustomers[0]; modal.result .then(async (user) => { this.showBanLoading = true; await this._usersService.banUser(user.id); this._loadDataSmartTable(); this.showBanLoading = false; this._notifyService.success(`${user.name} is banned!`); }) .catch((_) => {}); } private _loadSettingsSmartTable() { const columnTitlePrefix = 'CUSTOMERS_VIEW.SMART_TABLE_COLUMNS.'; const getTranslate = (name: string): Observable<any> => this._translateService.get(columnTitlePrefix + name); forkJoin( this._translateService.get('Id'), getTranslate('IMAGE'), getTranslate('NAME'), getTranslate('EMAIL'), getTranslate('PHONE'), getTranslate('COUNTRY'), getTranslate('CITY'), getTranslate('ADDRESS'), getTranslate('ORDERS_QTY') ).subscribe( ([ id, image, name, email, phone, country, city, address, ordersQty, ]) => { this.settingsSmartTable = { actions: false, selectMode: 'multi', columns: { images: { title: image, class: 'customer-image', type: 'custom', renderComponent: CustomerImageComponent, onComponentInitFunction: (instance) => { instance.redirectPage = 'customers/list'; }, filter: false, }, name: { title: name, type: 'custom', renderComponent: RedirectNameComponent, onComponentInitFunction: (instance) => { instance.redirectPage = 'customers/list'; }, }, email: { title: email, type: 'custom', renderComponent: CustomerEmailComponent, }, phone: { title: phone, type: 'custom', renderComponent: CustomerPhoneComponent, }, country: { title: country, editor: { type: 'custom', component: CountryRenderComponent, }, }, city: { title: city }, address: { title: address }, ordersQty: { title: ordersQty, type: 'custom', renderComponent: CustomerOrdersNumberComponent, filter: false, }, }, pager: { display: true, perPage, }, }; } ); } private async _loadDataSmartTable(page = 1) { if (this.$users) { await this.$users.unsubscribe(); } let users: User[] = []; const loadData = async () => { const usersOrders = await this._ordersService.getUsersOrdersCountInfo( users.map((u) => u.id) ); let usersVM = users.map((user) => { const userOrders = usersOrders.find( (res) => res['id'] === user.id ); return { id: user.id, image: user.image || CustomersComponent.noInfoSign, name: user.firstName && user.lastName ? `${user.firstName} ${user.lastName}` : user.firstName ? user.firstName : user.lastName ? user.lastName : user.id, email: user.email || CustomersComponent.noInfoSign, phone: user.phone || CustomersComponent.noInfoSign, country: getCountryName(user.geoLocation.countryId).trim() || CustomersComponent.noInfoSign, city: user.geoLocation.city || CustomersComponent.noInfoSign, address: `st. ${ user.geoLocation.streetAddress || CustomersComponent.noInfoSign }, hse. № ${ user.geoLocation.house || CustomersComponent.noInfoSign }`, ordersQty: userOrders ? userOrders.ordersCount : 0, isBanned: user.isBanned, }; }); await this.loadDataCount(); if (this.showOnlyBanned) { usersVM = usersVM.filter((user) => user.isBanned); } const usersData = new Array(this.dataCount); usersData.splice(perPage * (page - 1), perPage, ...usersVM); await this.sourceSmartTable.load(usersData); }; // We call two times 'loadData' // This is need because in every change on one of them the server emit and we want to receive it this.$users = this._usersService .getUsers({ skip: perPage * (page - 1), limit: perPage, }) .pipe(takeUntil(this.ngDestroy$)) .subscribe(async (u: User[]) => { users = u; await loadData(); }); } private _applyTranslationOnSmartTable() { this._translateService.onLangChange .pipe(takeUntil(this.ngDestroy$)) .subscribe(() => { this._loadSettingsSmartTable(); }); } // This is just workaround to show some search icon on smart table, in the future maybe we must find better solution. private _addCustomHTMLElements(): any { document.querySelector( 'tr.ng2-smart-filters > th:nth-child(1)' ).innerHTML = '<i class="fa fa-search" style="font-size: 1.3em"/>'; } private async smartTableChange() { this.sourceSmartTable .onChanged() .pipe(takeUntil(this.ngDestroy$)) .subscribe(async (event) => { if (event.action === 'page') { const page = event.paging.page; this._loadDataSmartTable(page); } }); } private async loadDataCount() { this.dataCount = await this._usersService.getCountOfUsers(); } public get isOnlyOneCustomerSelected(): boolean { return this._selectedCustomers.length === 1; } public get isUserBanned() { return ( this._selectedCustomers[0] && this._selectedCustomers[0].isBanned ); } public set showOnlyBanned(v: boolean) { this._showOnlyBanned = v; this._loadDataSmartTable(); } public get showOnlyBanned(): boolean { return this._showOnlyBanned; } ngOnDestroy() { this.ngDestroy$.next(); this.ngDestroy$.complete(); } }
the_stack
// basic tag from form logic // types: // radio // text // email // tel // password // checkbox // radio // select // button // namespace namespace cf { // interface export interface ITag{ domElement?: HTMLInputElement | HTMLSelectElement | HTMLButtonElement | HTMLOptionElement, type: string, name: string, id: string, label: string, question: string, errorMessage: string, setTagValueAndIsValid(dto: FlowDTO): boolean; dealloc(): void; refresh(): void; reset(): void; value:string | Array <string>; inputPlaceholder?: string; required: boolean; defaultValue: string | number; disabled: boolean; skipUserInput: boolean; eventTarget: EventDispatcher; flowManager: FlowManager; hasConditions():boolean; hasConditionsFor(tagName: string):boolean; checkConditionalAndIsValid():boolean; validationCallback?(dto: FlowDTO, success: () => void, error: (optionalErrorMessage?: string) => void): void; } export const TagEvents = { ORIGINAL_ELEMENT_CHANGED: "cf-tag-dom-element-changed" } export interface TagChangeDTO{ tag: ITag, value: string } export interface ConditionalValue{ key: string, conditionals: Array<string | RegExp> } export interface ITagOptions{ domElement?: HTMLInputElement | HTMLSelectElement | HTMLButtonElement | HTMLOptionElement, questions?: Array<string>, label?: string, validationCallback?: (dto: FlowDTO, success: () => void, error: () => void) => void,// can be set through cf-validation attribute } // class export class Tag implements ITag { private errorMessages: Array<string>; private pattern: RegExp; private changeCallback: () => void; private conditionalTags: Array<ConditionalValue>; // input placeholder text, this is for the UserTextInput and not the tag it self. protected _inputPlaceholder: string; protected _eventTarget: EventDispatcher; protected _label: string; protected questions: Array<string>; // can also be set through cf-questions attribute. public flowManager: FlowManager public domElement: HTMLInputElement | HTMLSelectElement | HTMLButtonElement | HTMLOptionElement; public defaultValue: string | number; public initialDefaultValue: string | number; public validationCallback?: (dto: FlowDTO, success: () => void, error: (optionalErrorMessage?: string) => void) => void; // can be set through cf-validation attribute, get's called from FlowManager public skipUserInput: boolean; // Used by cf-robot-message which has no input and is just a robot message public get type (): string{ return this.domElement.getAttribute("type") || this.domElement.tagName.toLowerCase(); } public get name (): string{ return this.domElement.getAttribute("name"); } public get id (): string{ return this.domElement.getAttribute("id"); } public get inputPlaceholder (): string{ return this._inputPlaceholder; } public get formless (): boolean{ return TagsParser.isElementFormless(this.domElement) } public get label (): string{ return this.getLabel(); } public get value (): string | Array<string> { return this.domElement.value || <string> this.initialDefaultValue; } public get hasImage (): boolean{ return this.domElement.hasAttribute("cf-image"); } public get rows (): number { return this.domElement.hasAttribute("rows") ? parseInt(this.domElement.getAttribute("rows")) : 0; } public get disabled (): boolean{ // a tag is disabled if its conditions are not meet, also if it contains the disabled attribute return !this.checkConditionalAndIsValid() || (this.domElement.getAttribute("disabled") != undefined && this.domElement.getAttribute("disabled") != null); } public get required(): boolean{ return !!this.domElement.getAttribute("required") || this.domElement.getAttribute("required") == ""; } public get question():string{ // if questions are empty, then fall back to dictionary, every time if(!this.questions || this.questions.length == 0) return Dictionary.getRobotResponse(this.type); else return this.questions[Math.floor(Math.random() * this.questions.length)]; } public set eventTarget(value: EventDispatcher){ this._eventTarget = value; } public get errorMessage():string{ if(!this.errorMessages){ // custom tag error messages if(this.domElement.getAttribute("cf-error")){ this.errorMessages = Helpers.getValuesOfBars(this.domElement.getAttribute("cf-error")); }else if(this.domElement.parentNode && (<HTMLElement> this.domElement.parentNode).getAttribute("cf-error")){ this.errorMessages = Helpers.getValuesOfBars((<HTMLElement> this.domElement.parentNode).getAttribute("cf-error")); }else if(this.required){ this.errorMessages = [Dictionary.get("input-placeholder-required")] }else{ if(this.type == "file") this.errorMessages = [Dictionary.get("input-placeholder-file-error")]; else{ this.errorMessages = [Dictionary.get("input-placeholder-error")]; } } } return this.errorMessages[Math.floor(Math.random() * this.errorMessages.length)]; } constructor(options: ITagOptions){ this.domElement = options.domElement; this.initialDefaultValue = this.domElement.value || this.domElement.getAttribute("value") || ""; this.changeCallback = this.onDomElementChange.bind(this); this.domElement.addEventListener("change", this.changeCallback, false); // remove tabIndex from the dom element.. danger zone... should we or should we not... this.domElement.tabIndex = -1; this.skipUserInput = false; // questions array if(options.questions) this.questions = options.questions; // custom tag validation - must be a method on window to avoid unsafe eval() calls if(this.domElement.getAttribute("cf-validation")){ const fn = (window as any)[this.domElement.getAttribute("cf-validation")]; this.validationCallback = fn; } // reg ex pattern is set on the Tag, so use it in our validation if(this.domElement.getAttribute("pattern")) this.pattern = new RegExp(this.domElement.getAttribute("pattern")); if(this.type != "group" && ConversationalForm.illustrateAppFlow){ if(!ConversationalForm.suppressLog) console.log('Conversational Form > Tag registered:', this.type, this); } this.refresh(); } public dealloc(){ this.domElement.removeEventListener("change", this.changeCallback, false); this.changeCallback = null this.domElement = null; this.defaultValue = null; this.errorMessages = null; this.pattern = null; this._label = null; this.validationCallback = null; this.questions = null; } public static testConditions(tagValue: string | string[], condition: ConditionalValue):boolean{ const testValue = (value: string, conditional: string | RegExp) : boolean => { if(typeof conditional === "object"){ // regex return (<RegExp> conditional).test(value); } // string comparisson return <string>tagValue === conditional; } if(typeof tagValue === "string"){ // tag value is a string const value: string = <string> tagValue; let isValid: boolean = false; for (var i = 0; i < condition.conditionals.length; i++) { var conditional: string | RegExp = condition.conditionals[i]; isValid = testValue(value, conditional); if(isValid) break; } return isValid; }else{ if(!tagValue){ return false; }else{ // tag value is an array let isValid: boolean = false; for (var i = 0; i < condition.conditionals.length; i++) { var conditional: string | RegExp = condition.conditionals[i]; if(typeof tagValue !== "string"){ for (var j = 0; j < tagValue.length; j++) { isValid = testValue(<string>tagValue[j], conditional); if(isValid) break; } }else{ // string comparisson isValid = testValue((<string[]>tagValue).toString(), conditional); } if(isValid) break; } return isValid; } // arrays need to be the same } } public static isTagValid(element: HTMLElement):boolean{ if(element.getAttribute("type") === "hidden") return false; if(element.getAttribute("type") === "submit") return false; // ignore buttons, we submit the form automatially if(element.getAttribute("type") == "button") return false; if(element.style){ // element style can be null if markup is created from DOMParser if(element.style.display === "none") return false; if(element.style.visibility === "hidden") return false; } const isTagFormless: boolean = TagsParser.isElementFormless(element); const innerText: string = Helpers.getInnerTextOfElement(element); if(element.tagName.toLowerCase() == "option" && (!isTagFormless && innerText == "" || innerText == " ")){ return false; } if(element.tagName.toLowerCase() == "select" || element.tagName.toLowerCase() == "option") return true else if(isTagFormless){ return true; }else{ return !!(element.offsetWidth || element.offsetHeight || element.getClientRects().length); } } public static createTag(element: HTMLInputElement | HTMLSelectElement | HTMLButtonElement | HTMLOptionElement): ITag{ if(Tag.isTagValid(element)){ // ignore hidden tags let tag: ITag; if(element.tagName.toLowerCase() == "input"){ tag = new InputTag({ domElement: element }); }else if(element.tagName.toLowerCase() == "textarea"){ tag = new InputTag({ domElement: element }); }else if(element.tagName.toLowerCase() == "select"){ tag = new SelectTag({ domElement: element }); }else if(element.tagName.toLowerCase() == "button"){ tag = new ButtonTag({ domElement: element }); }else if(element.tagName.toLowerCase() == "option"){ tag = new OptionTag({ domElement: element }); }else if(element.tagName.toLowerCase() == "cf-robot-message"){ tag = new CfRobotMessageTag({ domElement: element }); } return tag; }else{ // console.warn("Tag is not valid!: "+ element); return null; } } public reset(){ this.refresh(); // this.disabled = false; // reset to initial value. this.defaultValue = this.domElement.value = this.initialDefaultValue.toString(); } public refresh(){ // default value of Tag, check every refresh this.defaultValue = this.domElement.value || this.domElement.getAttribute("value") || ""; this.questions = null; this.findAndSetQuestions(); this.findConditionalAttributes(); } public hasConditionsFor(tagName: string):boolean{ if(!this.hasConditions()){ return false; } for (var i = 0; i < this.conditionalTags.length; i++) { var condition: ConditionalValue = this.conditionalTags[i]; if("cf-conditional-"+tagName.toLowerCase() === condition.key.toLowerCase()){ return true; } } return false; } public hasConditions():boolean{ return this.conditionalTags && this.conditionalTags.length > 0; } /** * @name checkConditionalAndIsValid * checks for conditional logic, see documentaiton (wiki) * here we check after cf-conditional{-name}, if we find an attribute we look through tags for value, and ignore the tag if */ public checkConditionalAndIsValid(): boolean { // can we tap into disabled // if contains attribute, cf-conditional{-name} then check for conditional value across tags if(this.hasConditions()){ return this.flowManager.areConditionsInFlowFullfilled(this, this.conditionalTags); } // else return true, as no conditional means uncomplicated and happy tag return true; } public setTagValueAndIsValid(dto: FlowDTO):boolean{ // this sets the value of the tag in the DOM // validation let isValid: boolean = true; let valueText: string = dto.text; if ( this.domElement.hasAttribute('type') && this.domElement.getAttribute('type') === 'email' && !this.pattern && valueText.length > 0 ) { this.pattern = /^(([^<>()\[\]\\.,;:\s@"]+(\.[^<>()\[\]\\.,;:\s@"]+)*)|(".+"))@((\[[0-9]{1,3}\.[0-9]{1,3}\.[0-9]{1,3}\.[0-9]{1,3}])|(([a-zA-Z\-0-9]+\.)+[a-zA-Z]{2,}))$/; } else if ( // When NOT required: Reset in the event user already typed something, and now they clear their input and want to submit nothing ==> remove pattern previously applied this.domElement.hasAttribute('type') && this.domElement.getAttribute('type') === 'email' && this.pattern && valueText.length === 0 && !this.required ) { this.pattern = null; } if(this.pattern){ isValid = this.pattern.test(valueText); } if(valueText == "" && this.required){ isValid = false; } // https://developer.mozilla.org/en-US/docs/Web/HTML/Element/input#attr-minlength const min: number = parseInt(this.domElement.getAttribute("minlength"), 10) || -1; // https://developer.mozilla.org/en-US/docs/Web/HTML/Element/input#attr-maxlength const max: number = parseInt(this.domElement.getAttribute("maxlength"), 10) || -1; if(min != -1 && valueText.length < min){ isValid = false; } if(max != -1 && valueText.length > max){ isValid = false; } const isMaxMinValueValid = this.validateMaxMinValue(valueText); if (!isMaxMinValueValid) isValid = false; if(isValid){ // we cannot set the dom element value when type is file if(this.type != "file") this.domElement.value = valueText; } return isValid; } /** * Validates value against tag max and min attributes * * @private * @param {string} value * @returns {boolean} * @memberof Tag */ private validateMaxMinValue(value:string):boolean { if (!value) return true; const parsedValue:Number = parseInt(value, 10); const minValue: number = parseInt(this.domElement.getAttribute("min"), 10) || -1; const maxValue: number = parseInt(this.domElement.getAttribute("max"), 10) || -1; if (minValue !== -1 && parsedValue < minValue) return false; if (maxValue !== -1 && parsedValue > maxValue) return false; return true; } protected getLabel(): string{ if(!this._label) this.findAndSetLabel(); if(this._label) return this._label; return Dictionary.getRobotResponse(this.type); } /** * @name findConditionalAttributes * look for conditional attributes and map them */ protected findConditionalAttributes(){ const keys: any = this.domElement.attributes; if(keys.length > 0){ this.conditionalTags = []; for (var key in keys) { if (keys.hasOwnProperty(key)) { let attr: any = keys[key]; if(attr && attr.name && attr.name.indexOf("cf-conditional") !== -1){ // conditional found let _conditionals: Array<string | RegExp> = []; // TODO: when && use to combine multiple values to complete condition. let conditionalsFromAttribute: Array<string> = attr.value.indexOf("||") !== -1 ? attr.value.split("||") : attr.value.split("&&"); for (var i = 0; i < conditionalsFromAttribute.length; i++) { var _conditional: string = conditionalsFromAttribute[i]; try { _conditionals.push(new RegExp(_conditional)); } catch(e) { } _conditionals.push(_conditional); } this.conditionalTags.push(<ConditionalValue>{ key: attr.name, conditionals: _conditionals }); } } } } } protected findAndSetQuestions(){ if(this.questions) return; // <label tag with label:for attribute to el:id // check for label tag, we only go 2 steps backwards.. // from standardize markup: http://www.w3schools.com/tags/tag_label.asp if(this.domElement.getAttribute("cf-questions")){ this.questions = Helpers.getValuesOfBars(this.domElement.getAttribute("cf-questions")); if(this.domElement.getAttribute("cf-input-placeholder")) this._inputPlaceholder = this.domElement.getAttribute("cf-input-placeholder"); }else if(this.domElement.parentNode && (<HTMLElement> this.domElement.parentNode).getAttribute("cf-questions")){ // for groups the parentNode can have the cf-questions.. const parent: HTMLElement = (<HTMLElement> this.domElement.parentNode); this.questions = Helpers.getValuesOfBars(parent.getAttribute("cf-questions")); if(parent.getAttribute("cf-input-placeholder")) this._inputPlaceholder = parent.getAttribute("cf-input-placeholder"); }else{ // questions not set, so find it in the DOM // try a broader search using for and id attributes const elId: string = this.domElement.getAttribute("id"); const forLabel: HTMLElement = <HTMLElement> document.querySelector("label[for='"+elId+"']"); if(forLabel){ this.questions = [Helpers.getInnerTextOfElement(forLabel)]; } } if(!this.questions && this.domElement.getAttribute("placeholder")){ // check for placeholder attr if questions are still undefined this.questions = [this.domElement.getAttribute("placeholder")]; } } protected findAndSetLabel(){ // find label.. if(this.domElement.getAttribute("cf-label")){ this._label = this.domElement.getAttribute("cf-label"); }else{ const parentDomNode: Node = this.domElement.parentNode; if(parentDomNode){ // step backwards and check for label tag. let labelTags: NodeListOf<Element> | Array<Element> = (<HTMLElement> parentDomNode).tagName.toLowerCase() == "label" ? [(<HTMLElement> parentDomNode)] : (<HTMLElement> parentDomNode).getElementsByTagName("label"); if(labelTags.length == 0){ // check for innerText const innerText: string = Helpers.getInnerTextOfElement((<any>parentDomNode)); if(innerText && innerText.length > 0) labelTags = [(<HTMLLabelElement>parentDomNode)]; }else if(labelTags.length > 0){ // check for "for" attribute for (let i = 0; i < labelTags.length; i++) { let label = labelTags[i]; if(label.getAttribute("for") == this.id){ this._label = Helpers.getInnerTextOfElement(label); } } } if(!this._label && labelTags[0]){ this._label = Helpers.getInnerTextOfElement(labelTags[0]); } } } } /** * @name onDomElementChange * on dom element value change event, ex. w. browser autocomplete mode */ private onDomElementChange(): void { this._eventTarget.dispatchEvent(new CustomEvent(TagEvents.ORIGINAL_ELEMENT_CHANGED, { detail: <TagChangeDTO> { value: this.value, tag: this } })); } } }
the_stack
import jsHelper, { SearchResults, SearchParameters, } from 'algoliasearch-helper'; import { TAG_PLACEHOLDER } from '../../../lib/utils'; import connectRefinementList from '../connectRefinementList'; import { createInstantSearch } from '../../../../test/mock/createInstantSearch'; import { createDisposeOptions, createInitOptions, createRenderOptions, } from '../../../../test/mock/createWidget'; import { createSingleSearchResponse } from '../../../../test/mock/createAPIResponse'; import { createSearchClient } from '../../../../test/mock/createSearchClient'; import { castToJestMock } from '../../../../test/utils/castToJestMock'; import { wait } from '../../../../test/utils/wait'; describe('connectRefinementList', () => { const createWidgetFactory = () => { const rendering = jest.fn(); const makeWidget = connectRefinementList(rendering); return { rendering, makeWidget }; }; it('throws on bad usage', () => { expect(connectRefinementList).toThrowErrorMatchingInlineSnapshot(` "The render function is not valid (received type Undefined). See documentation: https://www.algolia.com/doc/api-reference/widgets/refinement-list/js/#connector" `); expect(() => connectRefinementList({ operator: 'and', } as any) ).toThrowErrorMatchingInlineSnapshot(` "The render function is not valid (received type Object). See documentation: https://www.algolia.com/doc/api-reference/widgets/refinement-list/js/#connector" `); // @ts-expect-error expect(() => connectRefinementList(() => {})()) .toThrowErrorMatchingInlineSnapshot(` "The \`attribute\` option is required. See documentation: https://www.algolia.com/doc/api-reference/widgets/refinement-list/js/#connector" `); expect(() => // @ts-expect-error connectRefinementList(() => {})({ operator: 'and', }) ).toThrowErrorMatchingInlineSnapshot(` "The \`attribute\` option is required. See documentation: https://www.algolia.com/doc/api-reference/widgets/refinement-list/js/#connector" `); expect(() => connectRefinementList(() => {})({ attribute: 'company', // @ts-expect-error operator: 'YUP', }) ).toThrowErrorMatchingInlineSnapshot(` "The \`operator\` must one of: \`\\"and\\"\`, \`\\"or\\"\` (got \\"YUP\\"). See documentation: https://www.algolia.com/doc/api-reference/widgets/refinement-list/js/#connector" `); expect(() => connectRefinementList(() => {})({ attribute: 'company', limit: 10, showMore: true, showMoreLimit: 10, }) ).toThrowErrorMatchingInlineSnapshot(` "\`showMoreLimit\` should be greater than \`limit\`. See documentation: https://www.algolia.com/doc/api-reference/widgets/refinement-list/js/#connector" `); expect(() => connectRefinementList(() => {})({ attribute: 'company', limit: 10, showMore: true, showMoreLimit: 5, }) ).toThrowErrorMatchingInlineSnapshot(` "\`showMoreLimit\` should be greater than \`limit\`. See documentation: https://www.algolia.com/doc/api-reference/widgets/refinement-list/js/#connector" `); }); it('is a widget', () => { const render = jest.fn(); const unmount = jest.fn(); const customRefinementList = connectRefinementList(render, unmount); const widget = customRefinementList({ attribute: 'facet' }); expect(widget).toEqual( expect.objectContaining({ $$type: 'ais.refinementList', init: expect.any(Function), render: expect.any(Function), dispose: expect.any(Function), getWidgetUiState: expect.any(Function), getWidgetSearchParameters: expect.any(Function), }) ); }); describe('options configuring the helper', () => { it('`attribute`', () => { const { makeWidget } = createWidgetFactory(); const widget = makeWidget({ attribute: 'myFacet', }); expect( widget.getWidgetSearchParameters(new SearchParameters(), { uiState: {}, }) ).toEqual( new SearchParameters({ disjunctiveFacets: ['myFacet'], disjunctiveFacetsRefinements: { myFacet: [] }, maxValuesPerFacet: 10, }) ); }); it('`limit`', () => { const { makeWidget } = createWidgetFactory(); const widget = makeWidget({ attribute: 'myFacet', limit: 20, }); expect( widget.getWidgetSearchParameters(new SearchParameters(), { uiState: {}, }) ).toEqual( new SearchParameters({ disjunctiveFacets: ['myFacet'], disjunctiveFacetsRefinements: { myFacet: [] }, maxValuesPerFacet: 20, }) ); expect( widget.getWidgetSearchParameters( new SearchParameters({ maxValuesPerFacet: 100 }), { uiState: {} } ) ).toEqual( new SearchParameters({ disjunctiveFacets: ['myFacet'], disjunctiveFacetsRefinements: { myFacet: [] }, maxValuesPerFacet: 100, }) ); }); it('`showMoreLimit`', () => { const { rendering, makeWidget } = createWidgetFactory(); const widget = makeWidget({ attribute: 'myFacet', limit: 20, showMore: true, showMoreLimit: 30, }); const helper = jsHelper( createSearchClient(), '', widget.getWidgetSearchParameters(new SearchParameters({}), { uiState: {}, }) ); helper.search = jest.fn(); widget.init!( createInitOptions({ helper, state: helper.state, createURL: () => '#', }) ); widget.render!( createRenderOptions({ results: new SearchResults(helper.state, [ createSingleSearchResponse({ hits: [], facets: { category: { c1: 880, c2: 47, c3: 880, c4: 47, }, }, }), createSingleSearchResponse({ facets: { category: { c1: 880, c2: 47, c3: 880, c4: 47, }, }, }), ]), state: helper.state, helper, createURL: () => '#', }) ); const secondRenderingOptions = rendering.mock.calls[1][0]; secondRenderingOptions.toggleShowMore(); expect( widget.getWidgetSearchParameters(new SearchParameters({}), { uiState: {}, }) ).toEqual( new SearchParameters({ disjunctiveFacets: ['myFacet'], disjunctiveFacetsRefinements: { myFacet: [] }, maxValuesPerFacet: 30, }) ); expect( widget.getWidgetSearchParameters( new SearchParameters({ maxValuesPerFacet: 100 }), { uiState: {} } ) ).toEqual( new SearchParameters({ disjunctiveFacets: ['myFacet'], disjunctiveFacetsRefinements: { myFacet: [] }, maxValuesPerFacet: 100, }) ); }); it('`showMoreLimit` without `showMore` does not set anything', () => { const { rendering, makeWidget } = createWidgetFactory(); const widget = makeWidget({ attribute: 'myFacet', limit: 20, showMoreLimit: 30, }); const helper = jsHelper( createSearchClient(), '', widget.getWidgetSearchParameters(new SearchParameters({}), { uiState: {}, }) ); helper.search = jest.fn(); widget.init!( createInitOptions({ helper, state: helper.state, createURL: () => '#', }) ); widget.render!( createRenderOptions({ results: new SearchResults(helper.state, [ createSingleSearchResponse({ hits: [], facets: { category: { c1: 880, c2: 47, c3: 880, c4: 47, }, }, }), createSingleSearchResponse({ facets: { category: { c1: 880, c2: 47, c3: 880, c4: 47, }, }, }), ]), state: helper.state, helper, createURL: () => '#', }) ); const secondRenderingOptions = rendering.mock.calls[1][0]; secondRenderingOptions.toggleShowMore(); expect( widget.getWidgetSearchParameters(new SearchParameters({}), { uiState: {}, }) ).toEqual( new SearchParameters({ disjunctiveFacets: ['myFacet'], disjunctiveFacetsRefinements: { myFacet: [] }, maxValuesPerFacet: 20, }) ); }); it('`operator="and"`', () => { const { makeWidget } = createWidgetFactory(); const widget = makeWidget({ attribute: 'myFacet', operator: 'and', }); expect( widget.getWidgetSearchParameters(new SearchParameters({}), { uiState: {}, }) ).toEqual( new SearchParameters({ facets: ['myFacet'], facetsRefinements: { myFacet: [] }, maxValuesPerFacet: 10, }) ); }); }); it('Renders during init and render', () => { const { makeWidget, rendering } = createWidgetFactory(); // test that the dummyRendering is called with the isFirstRendering // flag set accordingly const widget = makeWidget({ attribute: 'myFacet', limit: 9, }); const config = widget.getWidgetSearchParameters(new SearchParameters({}), { uiState: {}, }); expect(config).toEqual( new SearchParameters({ disjunctiveFacets: ['myFacet'], disjunctiveFacetsRefinements: { myFacet: [] }, maxValuesPerFacet: 9, }) ); // test if widget is not rendered yet at this point expect(rendering).not.toHaveBeenCalled(); const helper = jsHelper(createSearchClient(), '', config); helper.search = jest.fn(); widget.init!( createInitOptions({ helper, state: helper.state, createURL: () => '#', }) ); // test that rendering has been called during init with isFirstRendering = true expect(rendering).toHaveBeenCalledTimes(1); // test if isFirstRendering is true during init expect(rendering).toHaveBeenLastCalledWith(expect.any(Object), true); const firstRenderingOptions = rendering.mock.calls[0][0]; expect(firstRenderingOptions.canRefine).toBe(false); expect(firstRenderingOptions.widgetParams).toEqual({ attribute: 'myFacet', limit: 9, }); widget.render!( createRenderOptions({ results: new SearchResults(helper.state, [ createSingleSearchResponse({}), ]), state: helper.state, helper, createURL: () => '#', }) ); // test that rendering has been called during init with isFirstRendering = false expect(rendering).toHaveBeenCalledTimes(2); expect(rendering).toHaveBeenLastCalledWith(expect.any(Object), false); const secondRenderingOptions = rendering.mock.calls[1][0]; expect(secondRenderingOptions.canRefine).toBe(false); expect(secondRenderingOptions.widgetParams).toEqual({ attribute: 'myFacet', limit: 9, }); }); it('can render before getWidgetSearchParameters', () => { const { makeWidget, rendering } = createWidgetFactory(); const widget = makeWidget({ attribute: 'myFacet', limit: 9, }); const helper = jsHelper(createSearchClient(), ''); widget.render!( createRenderOptions({ results: new SearchResults(helper.state, [ createSingleSearchResponse({}), ]), state: helper.state, helper, createURL: () => '#', }) ); expect(rendering).toHaveBeenCalledWith( expect.objectContaining({ items: [], }), false ); }); it('transforms items if requested', () => { const { makeWidget, rendering } = createWidgetFactory(); const widget = makeWidget({ attribute: 'category', transformItems: (items) => items.map((item) => ({ ...item, label: 'transformed', value: 'transformed', highlighted: 'transformed', })), }); const helper = jsHelper( createSearchClient(), '', widget.getWidgetSearchParameters(new SearchParameters({}), { uiState: {}, }) ); helper.search = jest.fn(); widget.init!( createInitOptions({ helper, state: helper.state, }) ); const firstRenderingOptions = rendering.mock.calls[0][0]; expect(firstRenderingOptions.items).toEqual([]); widget.render!( createRenderOptions({ results: new SearchResults(helper.state, [ createSingleSearchResponse({ hits: [], facets: { category: { c1: 880, c2: 47, }, }, }), createSingleSearchResponse({ facets: { category: { c1: 880, c2: 47, }, }, }), ]), state: helper.state, helper, }) ); const secondRenderingOptions = rendering.mock.calls[1][0]; expect(secondRenderingOptions.items).toEqual([ expect.objectContaining({ label: 'transformed', value: 'transformed', highlighted: 'transformed', }), expect.objectContaining({ label: 'transformed', value: 'transformed', highlighted: 'transformed', }), ]); }); it('Provide a function to clear the refinements at each step (or)', () => { const { makeWidget, rendering } = createWidgetFactory(); const instantSearchInstance = createInstantSearch(); const widget = makeWidget({ attribute: 'category', }); const helper = jsHelper( createSearchClient(), '', widget.getWidgetSearchParameters(new SearchParameters({}), { uiState: {}, }) ); helper.search = jest.fn(); helper.toggleRefinement('category', 'value'); widget.init!( createInitOptions({ helper, state: helper.state, createURL: () => '#', instantSearchInstance, }) ); const firstRenderingOptions = rendering.mock.calls[0][0]; const { refine } = firstRenderingOptions; refine('value'); expect(helper.state.disjunctiveFacetsRefinements.category).toHaveLength(0); refine('value'); expect(helper.state.disjunctiveFacetsRefinements.category).toHaveLength(1); widget.render!( createRenderOptions({ results: new SearchResults(helper.state, [ createSingleSearchResponse(), createSingleSearchResponse(), ]), state: helper.state, helper, createURL: () => '#', }) ); const secondRenderingOptions = rendering.mock.calls[1][0]; const { refine: renderToggleRefinement } = secondRenderingOptions; renderToggleRefinement('value'); expect(helper.state.disjunctiveFacetsRefinements.category).toHaveLength(0); renderToggleRefinement('value'); expect(helper.state.disjunctiveFacetsRefinements.category).toHaveLength(1); }); it('Provide a function to clear the refinements at each step (and)', () => { const instantSearchInstance = createInstantSearch(); const { makeWidget, rendering } = createWidgetFactory(); const widget = makeWidget({ attribute: 'category', operator: 'and', }); const helper = jsHelper( createSearchClient(), '', widget.getWidgetSearchParameters(new SearchParameters({}), { uiState: {}, }) ); helper.search = jest.fn(); helper.toggleRefinement('category', 'value'); widget.init!( createInitOptions({ helper, state: helper.state, createURL: () => '#', instantSearchInstance, }) ); const firstRenderingOptions = rendering.mock.calls[0][0]; const { refine } = firstRenderingOptions; refine('value'); expect(helper.state.facetsRefinements.category).toHaveLength(0); refine('value'); expect(helper.state.facetsRefinements.category).toHaveLength(1); widget.render!( createRenderOptions({ results: new SearchResults(helper.state, [ createSingleSearchResponse(), createSingleSearchResponse(), ]), state: helper.state, helper, createURL: () => '#', }) ); const secondRenderingOptions = rendering.mock.calls[1][0]; const { refine: renderToggleRefinement } = secondRenderingOptions; renderToggleRefinement('value'); expect(helper.state.facetsRefinements.category).toHaveLength(0); renderToggleRefinement('value'); expect(helper.state.facetsRefinements.category).toHaveLength(1); }); it('If there are too few items then canToggleShowMore is false', () => { const { makeWidget, rendering } = createWidgetFactory(); const widget = makeWidget({ attribute: 'category', limit: 3, showMore: true, showMoreLimit: 10, }); const helper = jsHelper( createSearchClient(), '', widget.getWidgetSearchParameters(new SearchParameters({}), { uiState: {}, }) ); helper.search = jest.fn(); widget.init!( createInitOptions({ helper, state: helper.state, createURL: () => '#', }) ); widget.render!( createRenderOptions({ results: new SearchResults(helper.state, [ createSingleSearchResponse({ hits: [], facets: { category: { c1: 880, c2: 47, }, }, }), createSingleSearchResponse({ facets: { category: { c1: 880, c2: 47, }, }, }), ]), state: helper.state, helper, createURL: () => '#', }) ); const secondRenderingOptions = rendering.mock.calls[1][0]; expect(secondRenderingOptions.canToggleShowMore).toBe(false); }); it('If there are no showMoreLimit specified, canToggleShowMore is false', () => { const { makeWidget, rendering } = createWidgetFactory(); const widget = makeWidget({ attribute: 'category', limit: 1, }); const helper = jsHelper( createSearchClient(), '', widget.getWidgetSearchParameters(new SearchParameters({}), { uiState: {}, }) ); helper.search = jest.fn(); widget.init!( createInitOptions({ helper, state: helper.state, createURL: () => '#', }) ); widget.render!( createRenderOptions({ results: new SearchResults(helper.state, [ createSingleSearchResponse({ hits: [], facets: { category: { c1: 880, c2: 47, }, }, }), createSingleSearchResponse({ facets: { category: { c1: 880, c2: 47, }, }, }), ]), state: helper.state, helper, createURL: () => '#', }) ); expect(rendering).toHaveBeenLastCalledWith( expect.objectContaining({ canToggleShowMore: false, }), false ); }); it('If there are same amount of items then canToggleShowMore is false', () => { const { makeWidget, rendering } = createWidgetFactory(); const widget = makeWidget({ attribute: 'category', limit: 2, showMore: true, showMoreLimit: 10, }); const helper = jsHelper( createSearchClient(), '', widget.getWidgetSearchParameters(new SearchParameters({}), { uiState: {}, }) ); helper.search = jest.fn(); widget.init!( createInitOptions({ helper, state: helper.state, createURL: () => '#', }) ); widget.render!( createRenderOptions({ results: new SearchResults(helper.state, [ createSingleSearchResponse({ hits: [], facets: { category: { c1: 880, c2: 47, }, }, }), createSingleSearchResponse({ facets: { category: { c1: 880, c2: 47, }, }, }), ]), state: helper.state, helper, createURL: () => '#', }) ); expect(rendering).toHaveBeenLastCalledWith( expect.objectContaining({ canToggleShowMore: false, }), false ); }); it('If there are enough items then canToggleShowMore is true', () => { const { makeWidget, rendering } = createWidgetFactory(); const widget = makeWidget({ attribute: 'category', limit: 1, showMore: true, showMoreLimit: 10, }); const helper = jsHelper( createSearchClient(), '', widget.getWidgetSearchParameters(new SearchParameters({}), { uiState: {}, }) ); helper.search = jest.fn(); widget.init!( createInitOptions({ helper, state: helper.state, createURL: () => '#', }) ); widget.render!( createRenderOptions({ results: new SearchResults(helper.state, [ createSingleSearchResponse({ hits: [], facets: { category: { c1: 880, c2: 47, }, }, }), createSingleSearchResponse({ facets: { category: { c1: 880, c2: 47, }, }, }), ]), state: helper.state, helper, createURL: () => '#', }) ); const secondRenderingOptions = rendering.mock.calls[1][0]; expect(secondRenderingOptions.canToggleShowMore).toBe(true); // toggleShowMore will set the state of the show more to true // therefore it's always possible to go back and show less items secondRenderingOptions.toggleShowMore(); const thirdRenderingOptions = rendering.mock.calls[2][0]; expect(thirdRenderingOptions.canToggleShowMore).toBe(true); }); it('Show more should toggle between two limits', () => { const { makeWidget, rendering } = createWidgetFactory(); const widget = makeWidget({ attribute: 'category', limit: 1, showMore: true, showMoreLimit: 3, }); const helper = jsHelper( createSearchClient(), '', widget.getWidgetSearchParameters(new SearchParameters({}), { uiState: {}, }) ); helper.search = jest.fn(); widget.init!( createInitOptions({ helper, state: helper.state, createURL: () => '#', }) ); widget.render!( createRenderOptions({ results: new SearchResults(helper.state, [ createSingleSearchResponse({ hits: [], facets: { category: { c1: 880, c2: 47, c3: 880, c4: 47, }, }, }), createSingleSearchResponse({ facets: { category: { c1: 880, c2: 47, c3: 880, c4: 47, }, }, }), ]), state: helper.state, helper, createURL: () => '#', }) ); expect(rendering).toHaveBeenLastCalledWith( expect.objectContaining({ canToggleShowMore: true, items: [ { label: 'c1', value: 'c1', highlighted: 'c1', count: 880, isRefined: false, }, ], }), false ); const secondRenderingOptions = rendering.mock.calls[1][0]; // toggleShowMore does a new render secondRenderingOptions.toggleShowMore(); const thirdRenderingOptions = rendering.mock.calls[2][0]; expect(thirdRenderingOptions.items).toEqual([ { label: 'c1', value: 'c1', highlighted: 'c1', count: 880, isRefined: false, }, { label: 'c3', value: 'c3', highlighted: 'c3', count: 880, isRefined: false, }, { label: 'c2', value: 'c2', highlighted: 'c2', count: 47, isRefined: false, }, ]); }); it('show more should toggle between two limits after search', async () => { const { makeWidget, rendering } = createWidgetFactory(); const limit = 1; const showMoreLimit = 2; const widget = makeWidget({ attribute: 'category', limit, showMore: true, showMoreLimit, }); const helper = jsHelper( createSearchClient(), '', widget.getWidgetSearchParameters(new SearchParameters({}), { uiState: {}, }) ); helper.search = jest.fn(); helper.searchForFacetValues = jest.fn().mockReturnValue( Promise.resolve({ facetHits: [], }) ); widget.init!( createInitOptions({ helper, state: helper.state, createURL: () => '#', }) ); widget.render!( createRenderOptions({ results: new SearchResults(helper.state, [ createSingleSearchResponse({ hits: [], facets: { category: { c1: 880, c2: 47, c3: 880, c4: 47, }, }, }), createSingleSearchResponse({ facets: { category: { c1: 880, c2: 47, c3: 880, c4: 47, }, }, }), ]), state: helper.state, helper, createURL: () => '#', }) ); const renderingOptions2 = rendering.mock.calls[1][0]; expect(renderingOptions2).toEqual({ createURL: expect.any(Function), items: [ { count: 880, highlighted: 'c1', isRefined: false, label: 'c1', value: 'c1', }, ], refine: expect.any(Function), searchForItems: expect.any(Function), isFromSearch: false, canRefine: true, widgetParams: { attribute: 'category', limit: 1, showMore: true, showMoreLimit: 2, }, isShowingMore: false, canToggleShowMore: true, toggleShowMore: expect.any(Function), hasExhaustiveItems: false, sendEvent: expect.any(Function), instantSearchInstance: expect.any(Object), }); // `searchForItems` triggers a new render renderingOptions2.searchForItems('query triggering no results'); await wait(0); expect(helper.searchForFacetValues).toHaveBeenCalledWith( expect.anything(), expect.anything(), limit, expect.anything() ); expect(rendering).toHaveBeenCalledTimes(3); const renderingOptions3 = rendering.mock.calls[2][0]; expect(renderingOptions3).toEqual({ createURL: expect.any(Function), items: [], refine: expect.any(Function), searchForItems: expect.any(Function), isFromSearch: true, canRefine: true, widgetParams: { attribute: 'category', limit: 1, showMore: true, showMoreLimit: 2, }, isShowingMore: false, canToggleShowMore: false, toggleShowMore: expect.any(Function), hasExhaustiveItems: false, sendEvent: expect.any(Function), instantSearchInstance: expect.any(Object), }); // `searchForItems` triggers a new render renderingOptions3.searchForItems(''); await wait(0); expect(rendering).toHaveBeenCalledTimes(4); const renderingOptions4 = rendering.mock.calls[3][0]; expect(renderingOptions4).toEqual({ createURL: expect.any(Function), items: [ { count: 880, highlighted: 'c1', isRefined: false, label: 'c1', value: 'c1', }, ], refine: expect.any(Function), searchForItems: expect.any(Function), isFromSearch: false, canRefine: true, widgetParams: { attribute: 'category', limit: 1, showMore: true, showMoreLimit: 2, }, isShowingMore: false, canToggleShowMore: true, toggleShowMore: expect.any(Function), hasExhaustiveItems: false, sendEvent: expect.any(Function), instantSearchInstance: expect.any(Object), }); // `toggleShowMore` triggers a new render renderingOptions4.toggleShowMore(); expect(rendering).toHaveBeenCalledTimes(5); const renderingOptions5 = rendering.mock.calls[4][0]; expect(renderingOptions5).toEqual({ createURL: expect.any(Function), items: [ { count: 880, highlighted: 'c1', isRefined: false, label: 'c1', value: 'c1', }, { count: 880, highlighted: 'c3', isRefined: false, label: 'c3', value: 'c3', }, ], refine: expect.any(Function), searchForItems: expect.any(Function), isFromSearch: false, canRefine: true, widgetParams: { attribute: 'category', limit: 1, showMore: true, showMoreLimit: 2, }, isShowingMore: true, canToggleShowMore: true, toggleShowMore: expect.any(Function), hasExhaustiveItems: false, sendEvent: expect.any(Function), instantSearchInstance: expect.any(Object), }); renderingOptions5.searchForItems('new search'); expect(helper.searchForFacetValues).toHaveBeenCalledWith( expect.anything(), expect.anything(), showMoreLimit, expect.anything() ); }); it('Toggle show more should be enabled when refinement list is expanded and number of facet is above limit and below showMoreLimit', () => { const { makeWidget, rendering } = createWidgetFactory(); const widget = makeWidget({ attribute: 'category', limit: 1, showMore: true, showMoreLimit: 3, }); const helper = jsHelper(createSearchClient(), '', { ...widget.getWidgetSearchParameters(new SearchParameters({}), { uiState: {}, }), maxValuesPerFacet: 10, }); helper.search = jest.fn(); // 1st rendering: initialization widget.init!( createInitOptions({ helper, state: helper.state, createURL: () => '#', }) ); // 2nd rendering: with 4 results (collapsed refinement list with limit < showMoreLimit < facets) widget.render!( createRenderOptions({ results: new SearchResults(helper.state, [ createSingleSearchResponse({ hits: [], facets: { category: { c1: 880, c2: 47, c3: 880, c4: 47, }, }, }), createSingleSearchResponse({ facets: { category: { c1: 880, c2: 47, c3: 880, c4: 47, }, }, }), ]), state: helper.state, helper, createURL: () => '#', }) ); const secondRenderingOptions = rendering.mock.calls[1][0]; expect(secondRenderingOptions.canToggleShowMore).toEqual(true); // 3rd rendering: expand refinement list secondRenderingOptions.toggleShowMore(); // 4th rendering: with 2 results (expanded refinement list with limit < facets < showMoreLimit) widget.render!( createRenderOptions({ results: new SearchResults(helper.state, [ createSingleSearchResponse({ hits: [], facets: { category: { c1: 880, c2: 47, }, }, }), createSingleSearchResponse({ facets: { category: { c1: 880, c2: 47, }, }, }), ]), state: helper.state, helper, createURL: () => '#', }) ); const forthRenderingOptions = rendering.mock.calls[3][0]; expect(forthRenderingOptions.canToggleShowMore).toEqual(true); }); it('Toggle show more should be disabled when refinement list is expanded and number of facet is below limit', () => { const { makeWidget, rendering } = createWidgetFactory(); const widget = makeWidget({ attribute: 'category', limit: 2, showMore: true, showMoreLimit: 3, }); const helper = jsHelper(createSearchClient(), '', { ...widget.getWidgetSearchParameters(new SearchParameters({}), { uiState: {}, }), maxValuesPerFacet: 10, }); helper.search = jest.fn(); // 1st rendering: initialization widget.init!( createInitOptions({ helper, state: helper.state, createURL: () => '#', }) ); // 2nd rendering: with 4 results (collapsed refinement list with limit < showMoreLimit < facets) widget.render!( createRenderOptions({ results: new SearchResults(helper.state, [ createSingleSearchResponse({ hits: [], facets: { category: { c1: 880, c2: 47, c3: 880, c4: 47, }, }, }), createSingleSearchResponse({ facets: { category: { c1: 880, c2: 47, c3: 880, c4: 47, }, }, }), ]), state: helper.state, helper, createURL: () => '#', }) ); const secondRenderingOptions = rendering.mock.calls[1][0]; expect(secondRenderingOptions.canToggleShowMore).toEqual(true); // 3rd rendering: expand refinement list secondRenderingOptions.toggleShowMore(); // 4th rendering: with 1 result (expanded refinement list with facets < limit < showMoreLimit) widget.render!( createRenderOptions({ results: new SearchResults(helper.state, [ createSingleSearchResponse({ hits: [], facets: { category: { c1: 880, }, }, }), createSingleSearchResponse({ facets: { category: { c1: 880, }, }, }), ]), state: helper.state, helper, createURL: () => '#', }) ); const forthRenderingOptions = rendering.mock.calls[3][0]; expect(forthRenderingOptions.canToggleShowMore).toEqual(false); }); it('hasExhaustiveItems indicates if the items provided are exhaustive - without other widgets making the maxValuesPerFacet bigger', () => { const { makeWidget, rendering } = createWidgetFactory(); const widget = makeWidget({ attribute: 'category', limit: 2, }); const helper = jsHelper( createSearchClient(), '', widget.getWidgetSearchParameters(new SearchParameters({}), { uiState: {}, }) ); helper.search = jest.fn(); widget.init!( createInitOptions({ helper, state: helper.state, createURL: () => '#', }) ); expect(rendering.mock.calls[0][0].hasExhaustiveItems).toEqual(true); widget.render!( createRenderOptions({ results: new SearchResults(helper.state, [ createSingleSearchResponse({ hits: [], facets: { category: { c1: 880, c2: 880, }, }, }), createSingleSearchResponse({ facets: { category: { c1: 880, c2: 880, }, }, }), ]), state: helper.state, helper, createURL: () => '#', }) ); // this one is `false` because we're not sure that what we asked is the actual number of facet values expect(rendering.mock.calls[1][0].hasExhaustiveItems).toEqual(false); widget.render!( createRenderOptions({ results: new SearchResults(helper.state, [ createSingleSearchResponse({ hits: [], facets: { category: { c1: 880, c2: 34, c3: 440, }, }, }), createSingleSearchResponse({ facets: { category: { c1: 880, c2: 34, c3: 440, }, }, }), ]), state: helper.state, helper, createURL: () => '#', }) ); expect(rendering.mock.calls[2][0].hasExhaustiveItems).toEqual(false); }); it('hasExhaustiveItems indicates if the items provided are exhaustive - with an other widgets making the maxValuesPerFacet bigger', () => { const { makeWidget, rendering } = createWidgetFactory(); const widget = makeWidget({ attribute: 'category', limit: 2, }); const helper = jsHelper(createSearchClient(), '', { ...widget.getWidgetSearchParameters(new SearchParameters({}), { uiState: {}, }), maxValuesPerFacet: 3, }); helper.search = jest.fn(); widget.init!( createInitOptions({ helper, state: helper.state, createURL: () => '#', }) ); expect(rendering.mock.calls[0][0].hasExhaustiveItems).toEqual(true); widget.render!( createRenderOptions({ results: new SearchResults(helper.state, [ createSingleSearchResponse({ hits: [], facets: { category: { c1: 880, c2: 880, }, }, }), createSingleSearchResponse({ facets: { category: { c1: 880, c2: 880, }, }, }), ]), state: helper.state, helper, createURL: () => '#', }) ); expect(rendering.mock.calls[1][0].hasExhaustiveItems).toEqual(true); widget.render!( createRenderOptions({ results: new SearchResults(helper.state, [ createSingleSearchResponse({ hits: [], facets: { category: { c1: 880, c2: 34, c3: 440, c4: 440, }, }, }), createSingleSearchResponse({ facets: { category: { c1: 880, c2: 34, c3: 440, c4: 440, }, }, }), ]), state: helper.state, helper, createURL: () => '#', }) ); expect(rendering.mock.calls[2][0].hasExhaustiveItems).toEqual(false); }); it('can search in facet values', () => { const { makeWidget, rendering } = createWidgetFactory(); const widget = makeWidget({ attribute: 'category', limit: 2, escapeFacetValues: false, }); const helper = jsHelper( createSearchClient(), '', widget.getWidgetSearchParameters(new SearchParameters({}), { uiState: {}, }) ); helper.search = jest.fn(); helper.searchForFacetValues = jest.fn().mockReturnValue( Promise.resolve({ exhaustiveFacetsCount: true, facetHits: [ { count: 33, highlighted: 'Salvador <mark>Da</mark>li', value: 'Salvador Dali', }, { count: 9, highlighted: '<mark>Da</mark>vidoff', value: 'Davidoff', }, ], processingTimeMS: 1, }) ); // Simulate the lifecycle widget.init!( createInitOptions({ helper, state: helper.state, createURL: () => '#', }) ); expect(rendering).toHaveBeenCalledTimes(1); widget.render!( createRenderOptions({ results: new SearchResults(helper.state, [ createSingleSearchResponse({ hits: [], facets: { category: { c1: 880, c2: 880, c3: 880, c4: 880, }, }, }), createSingleSearchResponse({ facets: { category: { c1: 880, c2: 880, c3: 880, c4: 880, }, }, }), ]), state: helper.state, helper, createURL: () => '#', }) ); expect(rendering).toHaveBeenCalledTimes(2); // Simulation end const search = rendering.mock.calls[1][0].searchForItems; search('da'); const [sffvFacet, sffvQuery, maxNbItems, paramOverride] = castToJestMock( helper.searchForFacetValues ).mock.calls[0]; expect(sffvQuery).toBe('da'); expect(sffvFacet).toBe('category'); expect(maxNbItems).toBe(2); expect(paramOverride).toEqual({ highlightPreTag: '<mark>', highlightPostTag: '</mark>', }); return Promise.resolve().then(() => { expect(rendering).toHaveBeenCalledTimes(3); expect(rendering.mock.calls[2][0].items).toEqual([ { count: 33, highlighted: 'Salvador <mark>Da</mark>li', label: 'Salvador Dali', value: 'Salvador Dali', }, { count: 9, highlighted: '<mark>Da</mark>vidoff', label: 'Davidoff', value: 'Davidoff', }, ]); }); }); it('caps the search in facet values to 100 facet hits', () => { const { makeWidget, rendering } = createWidgetFactory(); const widget = makeWidget({ attribute: 'category', limit: 50, showMoreLimit: 1000, }); const helper = jsHelper( createSearchClient(), '', widget.getWidgetSearchParameters(new SearchParameters({}), { uiState: {}, }) ); helper.search = jest.fn(); helper.searchForFacetValues = jest.fn().mockReturnValue( Promise.resolve({ exhaustiveFacetsCount: true, facetHits: [], processingTimeMS: 1, }) ); widget.init!( createInitOptions({ helper, state: helper.state, createURL: () => '#', }) ); widget.render!( createRenderOptions({ results: new SearchResults(helper.state, [ createSingleSearchResponse({ hits: [], facets: { category: { c1: 880, }, }, }), createSingleSearchResponse({ facets: { category: { c1: 880, }, }, }), ]), state: helper.state, helper, createURL: () => '#', }) ); const { toggleShowMore } = rendering.mock.calls[1][0]; toggleShowMore(); const { searchForItems } = rendering.mock.calls[2][0]; searchForItems('query'); const maxNbItems = castToJestMock(helper.searchForFacetValues).mock .calls[0][2]; expect(maxNbItems).toBe(100); }); it('can search in facet values with transformed items', () => { const { makeWidget, rendering } = createWidgetFactory(); const widget = makeWidget({ attribute: 'category', limit: 2, escapeFacetValues: false, transformItems: (items) => items.map((item) => ({ ...item, label: 'transformed', value: 'transformed', highlighted: 'transformed', })), }); const helper = jsHelper( createSearchClient(), '', widget.getWidgetSearchParameters(new SearchParameters({}), { uiState: {}, }) ); helper.search = jest.fn(); helper.searchForFacetValues = jest.fn().mockReturnValue( Promise.resolve({ exhaustiveFacetsCount: true, facetHits: [ { count: 33, highlighted: 'will be transformed', value: 'will be transformed', }, { count: 9, highlighted: 'will be transformed', value: 'will be transformed', }, ], processingTimeMS: 1, }) ); // Simulate the lifecycle widget.init!( createInitOptions({ helper, state: helper.state, createURL: () => '#', }) ); expect(rendering).toHaveBeenCalledTimes(1); widget.render!( createRenderOptions({ results: new SearchResults(helper.state, [ createSingleSearchResponse({ hits: [], facets: { category: { c1: 880, }, }, }), createSingleSearchResponse({ facets: { category: { c1: 880, }, }, }), ]), state: helper.state, helper, createURL: () => '#', }) ); expect(rendering).toHaveBeenCalledTimes(2); // Simulation end const search = rendering.mock.calls[1][0].searchForItems; search('transfo'); const [sffvFacet, sffvQuery, maxNbItems, paramOverride] = castToJestMock( helper.searchForFacetValues ).mock.calls[0]; expect(sffvQuery).toBe('transfo'); expect(sffvFacet).toBe('category'); expect(maxNbItems).toBe(2); expect(paramOverride).toEqual({ highlightPreTag: '<mark>', highlightPostTag: '</mark>', }); return Promise.resolve().then(() => { expect(rendering).toHaveBeenCalledTimes(3); expect(rendering.mock.calls[2][0].items).toEqual([ expect.objectContaining({ highlighted: 'transformed', label: 'transformed', value: 'transformed', }), expect.objectContaining({ highlighted: 'transformed', label: 'transformed', value: 'transformed', }), ]); }); }); it('can search in facet values, and reset pre post tags if needed', () => { const { makeWidget, rendering } = createWidgetFactory(); const widget = makeWidget({ attribute: 'category', limit: 2, escapeFacetValues: false, }); const helper = jsHelper(createSearchClient(), '', { ...widget.getWidgetSearchParameters(new SearchParameters({}), { uiState: {}, }), // Here we simulate that another widget has set some highlight tags ...TAG_PLACEHOLDER, }); helper.search = jest.fn(); helper.searchForFacetValues = jest.fn().mockReturnValue( Promise.resolve({ exhaustiveFacetsCount: true, facetHits: [ { count: 33, highlighted: 'Salvador <mark>Da</mark>li', value: 'Salvador Dali', }, { count: 9, highlighted: '<mark>Da</mark>vidoff', value: 'Davidoff', }, ], processingTimeMS: 1, }) ); // Simulate the lifecycle widget.init!( createInitOptions({ helper, state: helper.state, createURL: () => '#', }) ); expect(rendering).toHaveBeenCalledTimes(1); widget.render!( createRenderOptions({ results: new SearchResults(helper.state, [ createSingleSearchResponse({ hits: [], facets: { category: { c1: 880, }, }, }), createSingleSearchResponse({ facets: { category: { c1: 880, }, }, }), ]), state: helper.state, helper, createURL: () => '#', }) ); expect(rendering).toHaveBeenCalledTimes(2); // Simulation end const search = rendering.mock.calls[1][0].searchForItems; search('da'); const [sffvFacet, sffvQuery, maxNbItems, paramOverride] = castToJestMock( helper.searchForFacetValues ).mock.calls[0]; expect(sffvQuery).toBe('da'); expect(sffvFacet).toBe('category'); expect(maxNbItems).toBe(2); expect(paramOverride).toEqual({ highlightPreTag: '<mark>', highlightPostTag: '</mark>', }); return Promise.resolve().then(() => { expect(rendering).toHaveBeenCalledTimes(3); expect(rendering.mock.calls[2][0].items).toEqual([ { count: 33, highlighted: 'Salvador <mark>Da</mark>li', label: 'Salvador Dali', value: 'Salvador Dali', }, { count: 9, highlighted: '<mark>Da</mark>vidoff', label: 'Davidoff', value: 'Davidoff', }, ]); }); }); it('can search in facet values, and set post and pre tags by default', () => { const { makeWidget, rendering } = createWidgetFactory(); const widget = makeWidget({ attribute: 'category', limit: 2, escapeFacetValues: true, }); const helper = jsHelper(createSearchClient(), '', { ...widget.getWidgetSearchParameters(new SearchParameters({}), { uiState: {}, }), // Here we simulate that another widget has set some highlight tags ...TAG_PLACEHOLDER, }); helper.search = jest.fn(); helper.searchForFacetValues = jest.fn().mockReturnValue( Promise.resolve({ exhaustiveFacetsCount: true, facetHits: [ { count: 33, highlighted: `Salvador ${TAG_PLACEHOLDER.highlightPreTag}Da${TAG_PLACEHOLDER.highlightPostTag}li`, value: 'Salvador Dali', }, { count: 9, highlighted: `${TAG_PLACEHOLDER.highlightPreTag}Da${TAG_PLACEHOLDER.highlightPostTag}vidoff`, value: 'Davidoff', }, ], processingTimeMS: 1, }) ); // Simulate the lifecycle widget.init!( createInitOptions({ helper, state: helper.state, createURL: () => '#', }) ); expect(rendering).toHaveBeenCalledTimes(1); widget.render!( createRenderOptions({ results: new SearchResults(helper.state, [ createSingleSearchResponse({ hits: [], facets: { category: { c1: 880, }, }, }), createSingleSearchResponse({ facets: { category: { c1: 880, }, }, }), ]), state: helper.state, helper, createURL: () => '#', }) ); expect(rendering).toHaveBeenCalledTimes(2); // Simulation end const search = rendering.mock.calls[1][0].searchForItems; search('da'); const [sffvFacet, sffvQuery, maxNbItems, paramOverride] = castToJestMock( helper.searchForFacetValues ).mock.calls[0]; expect(sffvQuery).toBe('da'); expect(sffvFacet).toBe('category'); expect(maxNbItems).toBe(2); expect(paramOverride).toEqual(TAG_PLACEHOLDER); return Promise.resolve().then(() => { expect(rendering).toHaveBeenCalledTimes(3); expect(rendering.mock.calls[2][0].items).toEqual([ { count: 33, highlighted: 'Salvador <mark>Da</mark>li', label: 'Salvador Dali', value: 'Salvador Dali', }, { count: 9, highlighted: '<mark>Da</mark>vidoff', label: 'Davidoff', value: 'Davidoff', }, ]); }); }); it('does not throw without the unmount function', () => { const rendering = () => {}; const makeWidget = connectRefinementList(rendering); const widget = makeWidget({ attribute: 'myFacet', }); const helper = jsHelper( createSearchClient(), '', widget.getWidgetSearchParameters(new SearchParameters({}), { uiState: {}, }) ); expect(() => widget.dispose!(createDisposeOptions({ helper, state: helper.state })) ).not.toThrow(); }); describe('dispose', () => { it('removes refinements completely on dispose (and)', () => { const rendering = jest.fn(); const makeWidget = connectRefinementList(rendering); const instantSearchInstance = createInstantSearch(); const widget = makeWidget({ attribute: 'category', operator: 'and', }); const indexName = 'my-index'; const helper = jsHelper( createSearchClient(), indexName, widget.getWidgetSearchParameters(new SearchParameters({}), { uiState: {}, }) ); helper.search = jest.fn(); widget.init!( createInitOptions({ helper, state: helper.state, createURL: () => '#', instantSearchInstance, }) ); widget.render!( createRenderOptions({ results: new SearchResults(helper.state, [ createSingleSearchResponse({ hits: [], facets: { category: { c1: 880, c2: 47, }, }, }), createSingleSearchResponse({ facets: { category: { c1: 880, c2: 47, }, }, }), ]), state: helper.state, helper, }) ); const { refine } = rendering.mock.calls[0][0]; expect(helper.state).toEqual( new SearchParameters({ facets: ['category'], facetsRefinements: { category: [], }, index: indexName, maxValuesPerFacet: 10, }) ); refine('zimbo'); expect(helper.state).toEqual( new SearchParameters({ facets: ['category'], facetsRefinements: { category: ['zimbo'], }, index: indexName, maxValuesPerFacet: 10, }) ); const newState = widget.dispose!( createDisposeOptions({ state: helper.state, helper, }) ); expect(newState).toEqual( new SearchParameters({ index: indexName, }) ); }); it('removes refinements completely on dispose (or)', () => { const rendering = jest.fn(); const makeWidget = connectRefinementList(rendering); const instantSearchInstance = createInstantSearch(); const widget = makeWidget({ attribute: 'category', operator: 'or', }); const indexName = 'my-index'; const helper = jsHelper( createSearchClient(), indexName, widget.getWidgetSearchParameters(new SearchParameters({}), { uiState: {}, }) ); helper.search = jest.fn(); widget.init!( createInitOptions({ helper, state: helper.state, createURL: () => '#', instantSearchInstance, }) ); widget.render!( createRenderOptions({ results: new SearchResults(helper.state, [ createSingleSearchResponse({ hits: [], facets: { category: { c1: 880, c2: 47, }, }, }), createSingleSearchResponse({ facets: { category: { c1: 880, c2: 47, }, }, }), ]), state: helper.state, helper, }) ); const { refine } = rendering.mock.calls[0][0]; expect(helper.state).toEqual( new SearchParameters({ disjunctiveFacets: ['category'], disjunctiveFacetsRefinements: { category: [], }, index: indexName, maxValuesPerFacet: 10, }) ); refine('zimbo'); expect(helper.state).toEqual( new SearchParameters({ disjunctiveFacets: ['category'], disjunctiveFacetsRefinements: { category: ['zimbo'], }, index: indexName, maxValuesPerFacet: 10, }) ); const newState = widget.dispose!( createDisposeOptions({ state: helper.state, helper, }) ); expect(newState).toEqual( new SearchParameters({ index: indexName, }) ); }); }); describe('getWidgetUiState', () => { test('returns the `uiState` empty', () => { const render = () => {}; const makeWidget = connectRefinementList(render); const helper = jsHelper(createSearchClient(), ''); const widget = makeWidget({ attribute: 'brand', }); const actual = widget.getWidgetUiState( {}, { searchParameters: helper.state, helper, } ); expect(actual).toEqual({}); }); test('returns the `uiState` with a refinement', () => { const render = () => {}; const makeWidget = connectRefinementList(render); const helper = jsHelper(createSearchClient(), '', { disjunctiveFacets: ['brand'], disjunctiveFacetsRefinements: { brand: ['Apple', 'Microsoft'], }, }); const widget = makeWidget({ attribute: 'brand', }); const actual = widget.getWidgetUiState( {}, { searchParameters: helper.state, helper, } ); expect(actual).toEqual({ refinementList: { brand: ['Apple', 'Microsoft'], }, }); }); test('returns the `uiState` without namespace overridden', () => { const render = () => {}; const makeWidget = connectRefinementList(render); const helper = jsHelper(createSearchClient(), '', { disjunctiveFacets: ['brand'], disjunctiveFacetsRefinements: { brand: ['Apple', 'Microsoft'], }, }); const widget = makeWidget({ attribute: 'brand', }); const actual = widget.getWidgetUiState( { refinementList: { categories: ['Phone', 'Tablet'], }, }, { searchParameters: helper.state, helper, } ); expect(actual).toEqual({ refinementList: { categories: ['Phone', 'Tablet'], brand: ['Apple', 'Microsoft'], }, }); }); }); describe('getRenderState', () => { it('returns the render state without results', () => { const renderFn = jest.fn(); const unmountFn = jest.fn(); const createRefinementList = connectRefinementList(renderFn, unmountFn); const refinementListWidget = createRefinementList({ attribute: 'brand' }); const helper = jsHelper(createSearchClient(), 'indexName', { disjunctiveFacets: ['brand'], disjunctiveFacetsRefinements: { brand: ['Apple', 'Microsoft'], }, }); const initOptions = createInitOptions({ state: helper.state, helper }); const renderState1 = refinementListWidget.getRenderState({}, initOptions); expect(renderState1.refinementList).toEqual({ brand: { canRefine: false, canToggleShowMore: false, createURL: expect.any(Function), hasExhaustiveItems: true, isFromSearch: false, isShowingMore: false, items: [], refine: expect.any(Function), searchForItems: expect.any(Function), toggleShowMore: expect.any(Function), sendEvent: expect.any(Function), widgetParams: { attribute: 'brand', }, }, }); }); it('returns the render state with results', () => { const renderFn = jest.fn(); const unmountFn = jest.fn(); const createRefinementList = connectRefinementList(renderFn, unmountFn); const refinementListWidget = createRefinementList({ attribute: 'brand' }); const helper = jsHelper(createSearchClient(), 'indexName', { disjunctiveFacets: ['brand'], disjunctiveFacetsRefinements: { brand: ['Apple', 'Microsoft'], }, }); const initOptions = createInitOptions({ state: helper.state, helper }); const renderState1 = refinementListWidget.getRenderState({}, initOptions); const results = new SearchResults(helper.state, [ createSingleSearchResponse({ hits: [], facets: { brand: { Apple: 88, Microsoft: 66, Samsung: 44, }, }, }), ]); const renderOptions = createRenderOptions({ helper, state: helper.state, results, }); const renderState2 = refinementListWidget.getRenderState( {}, renderOptions ); expect(renderState2.refinementList).toEqual({ brand: { canRefine: true, canToggleShowMore: false, createURL: expect.any(Function), hasExhaustiveItems: true, isFromSearch: false, isShowingMore: false, items: [ { count: 88, highlighted: 'Apple', isRefined: true, label: 'Apple', value: 'Apple', }, { count: 66, highlighted: 'Microsoft', isRefined: true, label: 'Microsoft', value: 'Microsoft', }, { count: 44, highlighted: 'Samsung', isRefined: false, label: 'Samsung', value: 'Samsung', }, ], refine: renderState1.refinementList.brand.refine, searchForItems: expect.any(Function), sendEvent: expect.any(Function), toggleShowMore: renderState1.refinementList.brand.toggleShowMore, widgetParams: { attribute: 'brand', }, }, }); }); }); describe('getWidgetRenderState', () => { it('returns the widget render state without results', () => { const renderFn = jest.fn(); const unmountFn = jest.fn(); const createRefinementList = connectRefinementList(renderFn, unmountFn); const refinementListWidget = createRefinementList({ attribute: 'brand' }); const helper = jsHelper(createSearchClient(), 'indexName', { disjunctiveFacets: ['brand'], disjunctiveFacetsRefinements: { brand: ['Apple', 'Microsoft'], }, }); const initOptions = createInitOptions({ state: helper.state, helper }); const renderState1 = refinementListWidget.getWidgetRenderState(initOptions); expect(renderState1).toEqual({ canRefine: false, canToggleShowMore: false, createURL: expect.any(Function), hasExhaustiveItems: true, isFromSearch: false, isShowingMore: false, items: [], refine: expect.any(Function), searchForItems: expect.any(Function), toggleShowMore: expect.any(Function), sendEvent: expect.any(Function), widgetParams: { attribute: 'brand', }, }); }); it('returns the widget render state with results', () => { const renderFn = jest.fn(); const unmountFn = jest.fn(); const createRefinementList = connectRefinementList(renderFn, unmountFn); const refinementListWidget = createRefinementList({ attribute: 'brand' }); const helper = jsHelper(createSearchClient(), 'indexName', { disjunctiveFacets: ['brand'], disjunctiveFacetsRefinements: { brand: ['Apple', 'Microsoft'], }, }); const initOptions = createInitOptions({ state: helper.state, helper }); const renderState1 = refinementListWidget.getWidgetRenderState(initOptions); const results = new SearchResults(helper.state, [ createSingleSearchResponse({ hits: [], facets: { brand: { Apple: 88, Microsoft: 66, Samsung: 44, }, }, }), ]); const renderOptions = createRenderOptions({ helper, state: helper.state, results, }); const renderState2 = refinementListWidget.getWidgetRenderState(renderOptions); expect(renderState2).toEqual( expect.objectContaining({ canRefine: true, canToggleShowMore: false, createURL: expect.any(Function), hasExhaustiveItems: true, isFromSearch: false, isShowingMore: false, items: [ { count: 88, highlighted: 'Apple', isRefined: true, label: 'Apple', value: 'Apple', }, { count: 66, highlighted: 'Microsoft', isRefined: true, label: 'Microsoft', value: 'Microsoft', }, { count: 44, highlighted: 'Samsung', isRefined: false, label: 'Samsung', value: 'Samsung', }, ], refine: renderState1.refine, searchForItems: expect.any(Function), toggleShowMore: renderState1.toggleShowMore, widgetParams: { attribute: 'brand', }, }) ); }); describe('facetOrdering', () => { const resultsViaFacetOrdering = [ { count: 66, highlighted: 'Microsoft', isRefined: false, label: 'Microsoft', value: 'Microsoft', }, { count: 88, highlighted: 'Apple', isRefined: true, label: 'Apple', value: 'Apple', }, { count: 44, highlighted: 'Samsung', isRefined: true, label: 'Samsung', value: 'Samsung', }, ]; const resultsViaDefaultSortBy = [ { count: 88, highlighted: 'Apple', isRefined: true, label: 'Apple', value: 'Apple', }, { count: 44, highlighted: 'Samsung', isRefined: true, label: 'Samsung', value: 'Samsung', }, { count: 66, highlighted: 'Microsoft', isRefined: false, label: 'Microsoft', value: 'Microsoft', }, ]; const resultsViaSortBy = [ { count: 44, highlighted: 'Samsung', isRefined: true, label: 'Samsung', value: 'Samsung', }, { count: 66, highlighted: 'Microsoft', isRefined: false, label: 'Microsoft', value: 'Microsoft', }, { count: 88, highlighted: 'Apple', isRefined: true, label: 'Apple', value: 'Apple', }, ]; test.each` facetOrderingInResult | sortBy | expected ${true} | ${undefined} | ${resultsViaFacetOrdering} ${false} | ${undefined} | ${resultsViaDefaultSortBy} ${true} | ${['name:desc']} | ${resultsViaSortBy} ${false} | ${['name:desc']} | ${resultsViaSortBy} `( 'renderingContent present: $facetOrderingInResult, sortBy: $sortBy', ({ facetOrderingInResult, sortBy, expected }) => { const renderFn = jest.fn(); const unmountFn = jest.fn(); const createRefinementList = connectRefinementList( renderFn, unmountFn ); const refinementList = createRefinementList({ attribute: 'brand', sortBy, }); const helper = jsHelper( createSearchClient(), 'indexName', refinementList.getWidgetSearchParameters(new SearchParameters(), { uiState: { refinementList: { brand: ['Apple', 'Samsung'] }, }, }) ); const renderingContent = facetOrderingInResult ? { facetOrdering: { values: { brand: { order: ['Microsoft'], sortRemainingBy: 'alpha' as const, }, }, }, } : undefined; const renderState1 = refinementList.getWidgetRenderState( createRenderOptions({ helper, results: new SearchResults(helper.state, [ createSingleSearchResponse({ renderingContent, facets: { brand: { Apple: 88, Microsoft: 66, Samsung: 44, }, }, }), ]), }) ); expect(renderState1.items).toEqual(expected); } ); }); }); describe('getWidgetSearchParameters', () => { describe('with `maxValuesPerFacet`', () => { test('returns the `SearchParameters` with default `limit`', () => { const render = () => {}; const makeWidget = connectRefinementList(render); const helper = jsHelper(createSearchClient(), ''); const widget = makeWidget({ attribute: 'brand', }); const actual = widget.getWidgetSearchParameters(helper.state, { uiState: {}, }); expect(actual.maxValuesPerFacet).toBe(10); }); test('returns the `SearchParameters` with provided `limit`', () => { const render = () => {}; const makeWidget = connectRefinementList(render); const helper = jsHelper(createSearchClient(), ''); const widget = makeWidget({ attribute: 'brand', limit: 5, }); const actual = widget.getWidgetSearchParameters(helper.state, { uiState: {}, }); expect(actual.maxValuesPerFacet).toBe(5); }); test('returns the `SearchParameters` with default `showMoreLimit`', () => { const render = () => {}; const makeWidget = connectRefinementList(render); const helper = jsHelper(createSearchClient(), ''); const widget = makeWidget({ attribute: 'brand', showMore: true, }); const actual = widget.getWidgetSearchParameters(helper.state, { uiState: {}, }); expect(actual.maxValuesPerFacet).toBe(20); }); test('returns the `SearchParameters` with provided `showMoreLimit`', () => { const render = () => {}; const makeWidget = connectRefinementList(render); const helper = jsHelper(createSearchClient(), ''); const widget = makeWidget({ attribute: 'brand', showMore: true, showMoreLimit: 15, }); const actual = widget.getWidgetSearchParameters(helper.state, { uiState: {}, }); expect(actual.maxValuesPerFacet).toBe(15); }); test('returns the `SearchParameters` with the previous value if higher than `limit`/`showMoreLimit`', () => { const render = () => {}; const makeWidget = connectRefinementList(render); const helper = jsHelper(createSearchClient(), '', { maxValuesPerFacet: 100, }); const widget = makeWidget({ attribute: 'brand', }); const actual = widget.getWidgetSearchParameters(helper.state, { uiState: {}, }); expect(actual.maxValuesPerFacet).toBe(100); }); test('returns the `SearchParameters` with `limit`/`showMoreLimit` if higher than previous value', () => { const render = () => {}; const makeWidget = connectRefinementList(render); const helper = jsHelper(createSearchClient(), '', { maxValuesPerFacet: 100, }); const widget = makeWidget({ attribute: 'brand', limit: 110, }); const actual = widget.getWidgetSearchParameters(helper.state, { uiState: {}, }); expect(actual.maxValuesPerFacet).toBe(110); }); }); describe('with conjunctive facet', () => { test('returns the `SearchParameters` with the default value', () => { const render = () => {}; const makeWidget = connectRefinementList(render); const helper = jsHelper(createSearchClient(), ''); const widget = makeWidget({ attribute: 'brand', operator: 'and', }); const actual = widget.getWidgetSearchParameters(helper.state, { uiState: {}, }); expect(actual.facets).toEqual(['brand']); expect(actual.facetsRefinements).toEqual({ brand: [], }); }); test('returns the `SearchParameters` with the default value without the previous refinement', () => { const render = () => {}; const makeWidget = connectRefinementList(render); const helper = jsHelper(createSearchClient(), '', { facets: ['brand'], facetsRefinements: { brand: ['Apple', 'Samsung'], }, }); const widget = makeWidget({ attribute: 'brand', operator: 'and', }); const actual = widget.getWidgetSearchParameters(helper.state, { uiState: {}, }); expect(actual.facets).toEqual(['brand']); expect(actual.facetsRefinements).toEqual({ brand: [], }); }); test('returns the `SearchParameters` with the value from `uiState`', () => { const render = () => {}; const makeWidget = connectRefinementList(render); const helper = jsHelper(createSearchClient(), ''); const widget = makeWidget({ attribute: 'brand', operator: 'and', }); const actual = widget.getWidgetSearchParameters(helper.state, { uiState: { refinementList: { brand: ['Apple', 'Samsung'], }, }, }); expect(actual.facets).toEqual(['brand']); expect(actual.facetsRefinements).toEqual({ brand: ['Apple', 'Samsung'], }); }); test('returns the `SearchParameters` with the value from `uiState` without the previous refinement', () => { const render = () => {}; const makeWidget = connectRefinementList(render); const helper = jsHelper(createSearchClient(), '', { facets: ['brand'], facetsRefinements: { brand: ['Microsoft'], }, }); const widget = makeWidget({ attribute: 'brand', operator: 'and', }); const actual = widget.getWidgetSearchParameters(helper.state, { uiState: { refinementList: { brand: ['Apple', 'Samsung'], }, }, }); expect(actual.facets).toEqual(['brand']); expect(actual.facetsRefinements).toEqual({ brand: ['Apple', 'Samsung'], }); }); }); describe('with disjunctive facet', () => { test('returns the `SearchParameters` with the default value', () => { const render = () => {}; const makeWidget = connectRefinementList(render); const helper = jsHelper(createSearchClient(), ''); const widget = makeWidget({ attribute: 'brand', }); const actual = widget.getWidgetSearchParameters(helper.state, { uiState: {}, }); expect(actual.disjunctiveFacets).toEqual(['brand']); expect(actual.disjunctiveFacetsRefinements).toEqual({ brand: [], }); }); test('returns the `SearchParameters` with the default value without the previous refinement', () => { const render = () => {}; const makeWidget = connectRefinementList(render); const helper = jsHelper(createSearchClient(), '', { disjunctiveFacets: ['brand'], disjunctiveFacetsRefinements: { brand: ['Apple', 'Samsung'], }, }); const widget = makeWidget({ attribute: 'brand', }); const actual = widget.getWidgetSearchParameters(helper.state, { uiState: {}, }); expect(actual.disjunctiveFacets).toEqual(['brand']); expect(actual.disjunctiveFacetsRefinements).toEqual({ brand: [], }); }); test('returns the `SearchParameters` with the value from `uiState`', () => { const render = () => {}; const makeWidget = connectRefinementList(render); const helper = jsHelper(createSearchClient(), ''); const widget = makeWidget({ attribute: 'brand', }); const actual = widget.getWidgetSearchParameters(helper.state, { uiState: { refinementList: { brand: ['Apple', 'Samsung'], }, }, }); expect(actual.disjunctiveFacets).toEqual(['brand']); expect(actual.disjunctiveFacetsRefinements).toEqual({ brand: ['Apple', 'Samsung'], }); }); test('returns the `SearchParameters` with the value from `uiState` without the previous refinement', () => { const render = () => {}; const makeWidget = connectRefinementList(render); const helper = jsHelper(createSearchClient(), '', { disjunctiveFacets: ['brand'], disjunctiveFacetsRefinements: { brand: ['Microsoft'], }, }); const widget = makeWidget({ attribute: 'brand', }); const actual = widget.getWidgetSearchParameters(helper.state, { uiState: { refinementList: { brand: ['Apple', 'Samsung'], }, }, }); expect(actual.disjunctiveFacets).toEqual(['brand']); expect(actual.disjunctiveFacetsRefinements).toEqual({ brand: ['Apple', 'Samsung'], }); }); }); }); describe('insights', () => { const createInitializedWidget = () => { const factoryResult = createWidgetFactory(); const makeWidget = factoryResult.makeWidget; const rendering = factoryResult.rendering; const instantSearchInstance = createInstantSearch(); const widget = makeWidget({ attribute: 'category', }); const helper = jsHelper( createSearchClient(), '', widget.getWidgetSearchParameters(new SearchParameters({}), { uiState: {}, }) ); helper.search = jest.fn(); widget.init!( createInitOptions({ helper, state: helper.state, createURL: () => '#', instantSearchInstance, }) ); return { rendering, instantSearchInstance, }; }; it('sends event when a facet is added', () => { const { rendering, instantSearchInstance } = createInitializedWidget(); const firstRenderingOptions = rendering.mock.calls[rendering.mock.calls.length - 1][0]; const { refine } = firstRenderingOptions; refine('value'); expect(instantSearchInstance.sendEventToInsights).toHaveBeenCalledTimes( 1 ); expect(instantSearchInstance.sendEventToInsights).toHaveBeenCalledWith({ attribute: 'category', eventType: 'click', insightsMethod: 'clickedFilters', payload: { eventName: 'Filter Applied', filters: ['category:value'], index: '', }, widgetType: 'ais.refinementList', }); }); it('does not send event when a facet is removed', () => { const { rendering, instantSearchInstance } = createInitializedWidget(); const firstRenderingOptions = rendering.mock.calls[rendering.mock.calls.length - 1][0]; const { refine } = firstRenderingOptions; refine('value'); expect(instantSearchInstance.sendEventToInsights).toHaveBeenCalledTimes( 1 ); refine('value'); expect(instantSearchInstance.sendEventToInsights).toHaveBeenCalledTimes( 1 ); // still the same }); }); });
the_stack
import Geometry from '../geometry/Geometry'; import Cell from '../cell/datatypes/Cell'; import Point from '../geometry/Point'; import EventObject from '../event/EventObject'; import InternalEvent from '../event/InternalEvent'; import { CURSOR_CONNECT, DEFAULT_VALID_COLOR, DIALECT_STRICTHTML, DIALECT_SVG, HIGHLIGHT_STROKEWIDTH, INVALID_COLOR, NONE, OUTLINE_HIGHLIGHT_COLOR, OUTLINE_HIGHLIGHT_STROKEWIDTH, TOOLTIP_VERTICAL_OFFSET, VALID_COLOR, } from '../../util/Constants'; import { convertPoint, getOffset, getRotatedPoint, toRadians } from '../../util/Utils'; import InternalMouseEvent from '../event/InternalMouseEvent'; import ImageShape from '../geometry/shape/node/ImageShape'; import CellMarker from '../cell/CellMarker'; import ConstraintHandler from './ConstraintHandler'; import PolylineShape from '../geometry/shape/edge/PolylineShape'; import EventSource from '../event/EventSource'; import Rectangle from '../geometry/Rectangle'; import mxLog from '../../util/gui/mxLog'; import { getClientX, getClientY, isAltDown, isConsumed, isShiftDown, } from '../../util/EventUtils'; import Image from '../image/ImageBox'; import CellState from '../cell/datatypes/CellState'; import { Graph } from '../Graph'; import ConnectionConstraint from './ConnectionConstraint'; import Shape from '../geometry/shape/Shape'; import { GraphPlugin, Listenable } from '../../types'; import CellArray from '../cell/datatypes/CellArray'; type FactoryMethod = (source: Cell | null, target: Cell | null, style?: string) => Cell; /** * Class: mxConnectionHandler * * Graph event handler that creates new connections. Uses <mxTerminalMarker> * for finding and highlighting the source and target vertices and * <factoryMethod> to create the edge instance. This handler is built-into * <mxGraph.connectionHandler> and enabled using <mxGraph.setConnectable>. * * Example: * * (code) * new mxConnectionHandler(graph, (source, target, style)=> * { * edge = new mxCell('', new mxGeometry()); * edge.setEdge(true); * edge.setStyle(style); * edge.geometry.relative = true; * return edge; * }); * (end) * * Here is an alternative solution that just sets a specific user object for * new edges by overriding <insertEdge>. * * (code) * mxConnectionHandlerInsertEdge = insertEdge; * insertEdge = (parent, id, value, source, target, style)=> * { * value = 'Test'; * * return mxConnectionHandlerInsertEdge.apply(this, arguments); * }; * (end) * * Using images to trigger connections: * * This handler uses mxTerminalMarker to find the source and target cell for * the new connection and creates a new edge using <connect>. The new edge is * created using <createEdge> which in turn uses <factoryMethod> or creates a * new default edge. * * The handler uses a "highlight-paradigm" for indicating if a cell is being * used as a source or target terminal, as seen in other diagramming products. * In order to allow both, moving and connecting cells at the same time, * <mxConstants.DEFAULT_HOTSPOT> is used in the handler to determine the hotspot * of a cell, that is, the region of the cell which is used to trigger a new * connection. The constant is a value between 0 and 1 that specifies the * amount of the width and height around the center to be used for the hotspot * of a cell and its default value is 0.5. In addition, * <mxConstants.MIN_HOTSPOT_SIZE> defines the minimum number of pixels for the * width and height of the hotspot. * * This solution, while standards compliant, may be somewhat confusing because * there is no visual indicator for the hotspot and the highlight is seen to * switch on and off while the mouse is being moved in and out. Furthermore, * this paradigm does not allow to create different connections depending on * the highlighted hotspot as there is only one hotspot per cell and it * normally does not allow cells to be moved and connected at the same time as * there is no clear indication of the connectable area of the cell. * * To come across these issues, the handle has an additional <createIcons> hook * with a default implementation that allows to create one icon to be used to * trigger new connections. If this icon is specified, then new connections can * only be created if the image is clicked while the cell is being highlighted. * The <createIcons> hook may be overridden to create more than one * <mxImageShape> for creating new connections, but the default implementation * supports one image and is used as follows: * * In order to display the "connect image" whenever the mouse is over the cell, * an DEFAULT_HOTSPOT of 1 should be used: * * (code) * mxConstants.DEFAULT_HOTSPOT = 1; * (end) * * In order to avoid confusion with the highlighting, the highlight color * should not be used with a connect image: * * (code) * mxConstants.HIGHLIGHT_COLOR = null; * (end) * * To install the image, the connectImage field of the mxConnectionHandler must * be assigned a new <mxImage> instance: * * (code) * connectImage = new mxImage('images/green-dot.gif', 14, 14); * (end) * * This will use the green-dot.gif with a width and height of 14 pixels as the * image to trigger new connections. In createIcons the icon field of the * handler will be set in order to remember the icon that has been clicked for * creating the new connection. This field will be available under selectedIcon * in the connect method, which may be overridden to take the icon that * triggered the new connection into account. This is useful if more than one * icon may be used to create a connection. * * Group: Events * * Event: mxEvent.START * * Fires when a new connection is being created by the user. The <code>state</code> * property contains the state of the source cell. * * Event: mxEvent.CONNECT * * Fires between begin- and endUpdate in <connect>. The <code>cell</code> * property contains the inserted edge, the <code>event</code> and <code>target</code> * properties contain the respective arguments that were passed to <connect> (where * target corresponds to the dropTarget argument). Finally, the <code>terminal</code> * property corresponds to the target argument in <connect> or the clone of the source * terminal if <createTarget> is enabled. * * Note that the target is the cell under the mouse where the mouse button was released. * Depending on the logic in the handler, this doesn't necessarily have to be the target * of the inserted edge. To print the source, target or any optional ports IDs that the * edge is connected to, the following code can be used. To get more details about the * actual connection point, <mxGraph.getConnectionConstraint> can be used. To resolve * the port IDs, use <Transactions.getCell>. * * (code) * graph.connectionHandler.addListener(mxEvent.CONNECT, (sender, evt)=> * { * let edge = evt.getProperty('cell'); * let source = graph.getModel().getTerminal(edge, true); * let target = graph.getModel().getTerminal(edge, false); * * let style = graph.getCellStyle(edge); * let sourcePortId = style[mxConstants.STYLE_SOURCE_PORT]; * let targetPortId = style[mxConstants.STYLE_TARGET_PORT]; * * mxLog.show(); * mxLog.debug('connect', edge, source.id, target.id, sourcePortId, targetPortId); * }); * (end) * * Event: mxEvent.RESET * * Fires when the <reset> method is invoked. * * Constructor: mxConnectionHandler * * Constructs an event handler that connects vertices using the specified * factory method to create the new edges. Modify * <mxConstants.ACTIVE_REGION> to setup the region on a cell which triggers * the creation of a new connection or use connect icons as explained * above. * * Parameters: * * graph - Reference to the enclosing <mxGraph>. * factoryMethod - Optional function to create the edge. The function takes * the source and target <mxCell> as the first and second argument and an * optional cell style from the preview as the third argument. It returns * the <mxCell> that represents the new edge. */ class ConnectionHandler extends EventSource implements GraphPlugin { static pluginId = 'ConnectionHandler'; // TODO: Document me! previous: CellState | null = null; iconState: CellState | null = null; icons: ImageShape[] = []; cell: Cell | null = null; currentPoint: Point | null = null; sourceConstraint: ConnectionConstraint | null = null; shape: Shape | null = null; icon: ImageShape | null = null; originalPoint: Point | null = null; currentState: CellState | null = null; selectedIcon: ImageShape | null = null; waypoints: Point[] = []; /** * Variable: graph * * Reference to the enclosing <mxGraph>. */ graph: Graph; /** * Variable: factoryMethod * * Function that is used for creating new edges. The function takes the * source and target <mxCell> as the first and second argument and returns * a new <mxCell> that represents the edge. This is used in <createEdge>. */ factoryMethod: FactoryMethod | null = null; /** * Variable: moveIconFront * * Specifies if icons should be displayed inside the graph container instead * of the overlay pane. This is used for HTML labels on vertices which hide * the connect icon. This has precendence over <moveIconBack> when set * to true. Default is false. */ moveIconFront = false; /** * Variable: moveIconBack * * Specifies if icons should be moved to the back of the overlay pane. This can * be set to true if the icons of the connection handler conflict with other * handles, such as the vertex label move handle. Default is false. */ moveIconBack = false; /** * Variable: connectImage * * <mxImage> that is used to trigger the creation of a new connection. This * is used in <createIcons>. Default is null. */ connectImage: Image | null = null; /** * Variable: targetConnectImage * * Specifies if the connect icon should be centered on the target state * while connections are being previewed. Default is false. */ targetConnectImage = false; /** * Variable: enabled * * Specifies if events are handled. Default is false. */ enabled = false; /** * Variable: select * * Specifies if new edges should be selected. Default is true. */ select = true; /** * Variable: createTarget * * Specifies if <createTargetVertex> should be called if no target was under the * mouse for the new connection. Setting this to true means the connection * will be drawn as valid if no target is under the mouse, and * <createTargetVertex> will be called before the connection is created between * the source cell and the newly created vertex in <createTargetVertex>, which * can be overridden to create a new target. Default is false. */ createTarget = false; /** * Variable: marker * * Holds the <mxTerminalMarker> used for finding source and target cells. */ marker: CellMarker; /** * Variable: constraintHandler * * Holds the <mxConstraintHandler> used for drawing and highlighting * constraints. */ constraintHandler: ConstraintHandler; /** * Variable: error * * Holds the current validation error while connections are being created. */ error: string | null = null; /** * Variable: waypointsEnabled * * Specifies if single clicks should add waypoints on the new edge. Default is * false. */ waypointsEnabled = false; /** * Variable: ignoreMouseDown * * Specifies if the connection handler should ignore the state of the mouse * button when highlighting the source. Default is false, that is, the * handler only highlights the source if no button is being pressed. */ ignoreMouseDown = false; /** * Variable: first * * Holds the <mxPoint> where the mouseDown took place while the handler is * active. */ first: Point | null = null; /** * Variable: connectIconOffset * * Holds the offset for connect icons during connection preview. * Default is mxPoint(0, <mxConstants.TOOLTIP_VERTICAL_OFFSET>). * Note that placing the icon under the mouse pointer with an * offset of (0,0) will affect hit detection. */ connectIconOffset = new Point(0, TOOLTIP_VERTICAL_OFFSET); /** * Variable: edgeState * * Optional <mxCellState> that represents the preview edge while the * handler is active. This is created in <createEdgeState>. */ edgeState: CellState | null = null; /** * Variable: changeHandler * * Holds the change event listener for later removal. */ changeHandler: (sender: Listenable) => void; /** * Variable: drillHandler * * Holds the drill event listener for later removal. */ drillHandler: (sender: Listenable) => void; /** * Variable: mouseDownCounter * * Counts the number of mouseDown events since the start. The initial mouse * down event counts as 1. */ mouseDownCounter = 0; /** * Variable: movePreviewAway * * Switch to enable moving the preview away from the mousepointer. This is required in browsers * where the preview cannot be made transparent to events and if the built-in hit detection on * the HTML elements in the page should be used. Default is the value of <mxClient.IS_VML>. */ movePreviewAway = false; /** * Variable: outlineConnect * * Specifies if connections to the outline of a highlighted target should be * enabled. This will allow to place the connection point along the outline of * the highlighted target. Default is false. */ outlineConnect = false; /** * Variable: livePreview * * Specifies if the actual shape of the edge state should be used for the preview. * Default is false. (Ignored if no edge state is created in <createEdgeState>.) */ livePreview = false; /** * Variable: cursor * * Specifies the cursor to be used while the handler is active. Default is null. */ cursor: string | null = null; /** * Variable: insertBeforeSource * * Specifies if new edges should be inserted before the source vertex in the * cell hierarchy. Default is false for backwards compatibility. */ insertBeforeSource = false; escapeHandler: () => void; constructor(graph: Graph, factoryMethod: FactoryMethod | null = null) { super(); this.graph = graph; this.factoryMethod = factoryMethod; this.graph.addMouseListener(this); this.marker = this.createMarker(); this.constraintHandler = new ConstraintHandler(this.graph); // Redraws the icons if the graph changes this.changeHandler = (sender: Listenable) => { if (this.iconState) { this.iconState = this.graph.getView().getState(this.iconState.cell); } if (this.iconState) { this.redrawIcons(this.icons, this.iconState); this.constraintHandler.reset(); } else if (this.previous && !this.graph.view.getState(this.previous.cell)) { this.reset(); } }; this.graph.getModel().addListener(InternalEvent.CHANGE, this.changeHandler); this.graph.getView().addListener(InternalEvent.SCALE, this.changeHandler); this.graph.getView().addListener(InternalEvent.TRANSLATE, this.changeHandler); this.graph .getView() .addListener(InternalEvent.SCALE_AND_TRANSLATE, this.changeHandler); // Removes the icon if we step into/up or start editing this.drillHandler = (sender: Listenable) => { this.reset(); }; this.graph.addListener(InternalEvent.START_EDITING, this.drillHandler); this.graph.getView().addListener(InternalEvent.DOWN, this.drillHandler); this.graph.getView().addListener(InternalEvent.UP, this.drillHandler); // Handles escape keystrokes this.escapeHandler = () => { this.reset(); }; this.graph.addListener(InternalEvent.ESCAPE, this.escapeHandler); } /** * Function: isEnabled * * Returns true if events are handled. This implementation * returns <enabled>. */ isEnabled() { return this.enabled; } /** * Function: setEnabled * * Enables or disables event handling. This implementation * updates <enabled>. * * Parameters: * * enabled - Boolean that specifies the new enabled state. */ setEnabled(enabled: boolean) { this.enabled = enabled; } /** * Function: isInsertBefore * * Returns <insertBeforeSource> for non-loops and false for loops. * * Parameters: * * edge - <mxCell> that represents the edge to be inserted. * source - <mxCell> that represents the source terminal. * target - <mxCell> that represents the target terminal. * evt - Mousedown event of the connect gesture. * dropTarget - <mxCell> that represents the cell under the mouse when it was * released. */ isInsertBefore( edge: Cell, source: Cell | null, target: Cell | null, evt: MouseEvent, dropTarget: Cell | null ) { return this.insertBeforeSource && source !== target; } /** * Function: isCreateTarget * * Returns <createTarget>. * * Parameters: * * evt - Current active native pointer event. */ isCreateTarget(evt: Event) { return this.createTarget; } /** * Function: setCreateTarget * * Sets <createTarget>. */ setCreateTarget(value: boolean) { this.createTarget = value; } /** * Function: createShape * * Creates the preview shape for new connections. */ createShape() { // Creates the edge preview const shape = this.livePreview && this.edgeState ? this.graph.cellRenderer.createShape(this.edgeState) : new PolylineShape([], INVALID_COLOR); if (shape && shape.node) { shape.dialect = DIALECT_SVG; shape.scale = this.graph.view.scale; shape.pointerEvents = false; shape.isDashed = true; shape.init(this.graph.getView().getOverlayPane()); InternalEvent.redirectMouseEvents(shape.node, this.graph, null); } return shape; } /** * Function: isConnectableCell * * Returns true if the given cell is connectable. This is a hook to * disable floating connections. This implementation returns true. */ isConnectableCell(cell: Cell) { return true; } /** * Function: createMarker * * Creates and returns the <mxCellMarker> used in <marker>. */ createMarker() { const self = this; class MyCellMarker extends CellMarker { hotspotEnabled = true; // Overrides to return cell at location only if valid (so that // there is no highlight for invalid cells) getCell(me: InternalMouseEvent) { let cell = super.getCell(me); self.error = null; // Checks for cell at preview point (with grid) if (!cell && self.currentPoint) { cell = self.graph.getCellAt(self.currentPoint.x, self.currentPoint.y); } // Uses connectable parent vertex if one exists if (cell && !cell.isConnectable() && self.cell) { const parent = self.cell.getParent(); if (parent && parent.isVertex() && parent.isConnectable()) { cell = parent; } } if (cell) { if ( (self.graph.isSwimlane(cell) && self.currentPoint != null && self.graph.hitsSwimlaneContent( cell, self.currentPoint.x, self.currentPoint.y )) || !self.isConnectableCell(cell) ) { cell = null; } } if (cell) { if (self.isConnecting()) { if (self.previous) { self.error = self.validateConnection(self.previous.cell, cell); if (self.error && self.error.length === 0) { cell = null; // Enables create target inside groups if (self.isCreateTarget(me.getEvent())) { self.error = null; } } } } else if (!self.isValidSource(cell, me)) { cell = null; } } else if ( self.isConnecting() && !self.isCreateTarget(me.getEvent()) && !self.graph.isAllowDanglingEdges() ) { self.error = ''; } return cell; } // Sets the highlight color according to validateConnection isValidState(state: CellState) { if (self.isConnecting()) { return !self.error; } return super.isValidState(state); } // Overrides to use marker color only in highlight mode or for // target selection getMarkerColor(evt: Event, state: CellState, isValid: boolean) { return !self.connectImage || self.isConnecting() ? super.getMarkerColor(evt, state, isValid) : NONE; } // Overrides to use hotspot only for source selection otherwise // intersects always returns true when over a cell intersects(state: CellState, evt: InternalMouseEvent) { if (self.connectImage || self.isConnecting()) { return true; } return super.intersects(state, evt); } } return new MyCellMarker(this.graph) as CellMarker; } /** * Function: start * * Starts a new connection for the given state and coordinates. */ start(state: CellState, x: number, y: number, edgeState: CellState) { this.previous = state; this.first = new Point(x, y); this.edgeState = edgeState ?? this.createEdgeState(); // Marks the source state this.marker.currentColor = this.marker.validColor; this.marker.markedState = state; this.marker.mark(); this.fireEvent(new EventObject(InternalEvent.START, 'state', this.previous)); } /** * Function: isConnecting * * Returns true if the source terminal has been clicked and a new * connection is currently being previewed. */ isConnecting() { return !!this.first && !!this.shape; } /** * Function: isValidSource * * Returns <mxGraph.isValidSource> for the given source terminal. * * Parameters: * * cell - <mxCell> that represents the source terminal. * me - <mxMouseEvent> that is associated with this call. */ isValidSource(cell: Cell, me: InternalMouseEvent) { return this.graph.isValidSource(cell); } /** * Function: isValidTarget * * Returns true. The call to <mxGraph.isValidTarget> is implicit by calling * <mxGraph.getEdgeValidationError> in <validateConnection>. This is an * additional hook for disabling certain targets in this specific handler. * * Parameters: * * cell - <mxCell> that represents the target terminal. */ isValidTarget(cell: Cell) { return true; } /** * Function: validateConnection * * Returns the error message or an empty string if the connection for the * given source target pair is not valid. Otherwise it returns null. This * implementation uses <mxGraph.getEdgeValidationError>. * * Parameters: * * source - <mxCell> that represents the source terminal. * target - <mxCell> that represents the target terminal. */ validateConnection(source: Cell, target: Cell) { if (!this.isValidTarget(target)) { return ''; } return this.graph.getEdgeValidationError(null, source, target); } /** * Function: getConnectImage * * Hook to return the <mxImage> used for the connection icon of the given * <mxCellState>. This implementation returns <connectImage>. * * Parameters: * * state - <mxCellState> whose connect image should be returned. */ getConnectImage(state: CellState) { return this.connectImage; } /** * Function: isMoveIconToFrontForState * * Returns true if the state has a HTML label in the graph's container, otherwise * it returns <moveIconFront>. * * Parameters: * * state - <mxCellState> whose connect icons should be returned. */ isMoveIconToFrontForState(state: CellState) { if (state.text && state.text.node.parentNode === this.graph.container) { return true; } return this.moveIconFront; } /** * Function: createIcons * * Creates the array <mxImageShapes> that represent the connect icons for * the given <mxCellState>. * * Parameters: * * state - <mxCellState> whose connect icons should be returned. */ createIcons(state: CellState) { const image = this.getConnectImage(state); if (image) { this.iconState = state; const icons = []; // Cannot use HTML for the connect icons because the icon receives all // mouse move events in IE, must use VML and SVG instead even if the // connect-icon appears behind the selection border and the selection // border consumes the events before the icon gets a chance const bounds = new Rectangle(0, 0, image.width, image.height); const icon = new ImageShape(bounds, image.src, undefined, undefined, 0); icon.preserveImageAspect = false; if (this.isMoveIconToFrontForState(state)) { icon.dialect = DIALECT_STRICTHTML; icon.init(this.graph.container); } else { icon.dialect = DIALECT_SVG; icon.init(this.graph.getView().getOverlayPane()); // Move the icon back in the overlay pane if (this.moveIconBack && icon.node.parentNode && icon.node.previousSibling) { icon.node.parentNode.insertBefore(icon.node, icon.node.parentNode.firstChild); } } icon.node.style.cursor = CURSOR_CONNECT; // Events transparency const getState = () => { return this.currentState ?? state; }; // Updates the local icon before firing the mouse down event. const mouseDown = (evt: MouseEvent) => { if (!isConsumed(evt)) { this.icon = icon; this.graph.fireMouseEvent( InternalEvent.MOUSE_DOWN, new InternalMouseEvent(evt, getState()) ); } }; InternalEvent.redirectMouseEvents(icon.node, this.graph, getState, mouseDown); icons.push(icon); this.redrawIcons(icons, this.iconState); return icons; } return []; } /** * Function: redrawIcons * * Redraws the given array of <mxImageShapes>. * * Parameters: * * icons - Array of <mxImageShapes> to be redrawn. */ redrawIcons(icons: ImageShape[], state: CellState) { if (icons[0] && icons[0].bounds) { const pos = this.getIconPosition(icons[0], state); icons[0].bounds.x = pos.x; icons[0].bounds.y = pos.y; icons[0].redraw(); } } // TODO: Document me! =========================================================================================================== getIconPosition(icon: ImageShape, state: CellState) { const { scale } = this.graph.getView(); let cx = state.getCenterX(); let cy = state.getCenterY(); if (this.graph.isSwimlane(state.cell)) { const size = this.graph.getStartSize(state.cell); cx = size.width !== 0 ? state.x + (size.width * scale) / 2 : cx; cy = size.height !== 0 ? state.y + (size.height * scale) / 2 : cy; const alpha = toRadians(state.style.rotation ?? 0); if (alpha !== 0) { const cos = Math.cos(alpha); const sin = Math.sin(alpha); const ct = new Point(state.getCenterX(), state.getCenterY()); const pt = getRotatedPoint(new Point(cx, cy), cos, sin, ct); cx = pt.x; cy = pt.y; } } return new Point(cx - icon.bounds!.width / 2, cy - icon.bounds!.height / 2); } /** * Function: destroyIcons * * Destroys the connect icons and resets the respective state. */ destroyIcons() { for (let i = 0; i < this.icons.length; i += 1) { this.icons[i].destroy(); } this.icons = []; this.icon = null; this.selectedIcon = null; this.iconState = null; } /** * Function: isStartEvent * * Returns true if the given mouse down event should start this handler. The * This implementation returns true if the event does not force marquee * selection, and the currentConstraint and currentFocus of the * <constraintHandler> are not null, or <previous> and <error> are not null and * <icons> is null or <icons> and <icon> are not null. */ isStartEvent(me: InternalMouseEvent) { return ( (this.constraintHandler.currentFocus !== null && this.constraintHandler.currentConstraint !== null) || (this.previous !== null && this.error === null && (this.icons.length === 0 || this.icon !== null)) ); } /** * Function: mouseDown * * Handles the event by initiating a new connection. */ mouseDown(sender: EventSource, me: InternalMouseEvent) { this.mouseDownCounter += 1; if ( this.isEnabled() && this.graph.isEnabled() && !me.isConsumed() && !this.isConnecting() && this.isStartEvent(me) ) { if ( this.constraintHandler.currentConstraint && this.constraintHandler.currentFocus && this.constraintHandler.currentPoint ) { this.sourceConstraint = this.constraintHandler.currentConstraint; this.previous = this.constraintHandler.currentFocus; this.first = this.constraintHandler.currentPoint.clone(); } else { // Stores the location of the initial mousedown this.first = new Point(me.getGraphX(), me.getGraphY()); } this.edgeState = this.createEdgeState(me); this.mouseDownCounter = 1; if (this.waypointsEnabled && !this.shape) { this.waypoints = []; this.shape = this.createShape(); if (this.edgeState) { this.shape.apply(this.edgeState); } } // Stores the starting point in the geometry of the preview if (!this.previous && this.edgeState && this.edgeState.cell.geometry) { const pt = this.graph.getPointForEvent(me.getEvent()); this.edgeState.cell.geometry.setTerminalPoint(pt, true); } this.fireEvent(new EventObject(InternalEvent.START, 'state', this.previous)); me.consume(); } this.selectedIcon = this.icon; this.icon = null; } /** * Function: isImmediateConnectSource * * Returns true if a tap on the given source state should immediately start * connecting. This implementation returns true if the state is not movable * in the graph. */ isImmediateConnectSource(state: CellState) { return !this.graph.isCellMovable(state.cell); } /** * Function: createEdgeState * * Hook to return an <mxCellState> which may be used during the preview. * This implementation returns null. * * Use the following code to create a preview for an existing edge style: * * (code) * graph.connectionHandler.createEdgeState(me) * { * var edge = graph.createEdge(null, null, null, null, null, 'edgeStyle=elbowEdgeStyle'); * * return new mxCellState(this.graph.view, edge, this.graph.getCellStyle(edge)); * }; * (end) */ createEdgeState(me?: InternalMouseEvent): CellState | null { return null; } /** * Function: isOutlineConnectEvent * * Returns true if <outlineConnect> is true and the source of the event is the outline shape * or shift is pressed. */ isOutlineConnectEvent(me: InternalMouseEvent) { if (!this.currentPoint) return false; const offset = getOffset(this.graph.container); const evt = me.getEvent(); const clientX = getClientX(evt); const clientY = getClientY(evt); const doc = document.documentElement; const left = (window.pageXOffset || doc.scrollLeft) - (doc.clientLeft || 0); const top = (window.pageYOffset || doc.scrollTop) - (doc.clientTop || 0); const gridX = this.currentPoint.x - this.graph.container.scrollLeft + offset.x - left; const gridY = this.currentPoint.y - this.graph.container.scrollTop + offset.y - top; return ( this.outlineConnect && !isShiftDown(me.getEvent()) && (me.isSource(this.marker.highlight.shape) || (isAltDown(me.getEvent()) && me.getState() != null) || this.marker.highlight.isHighlightAt(clientX, clientY) || ((gridX !== clientX || gridY !== clientY) && me.getState() == null && this.marker.highlight.isHighlightAt(gridX, gridY))) ); } /** * Function: updateCurrentState * * Updates the current state for a given mouse move event by using * the <marker>. */ updateCurrentState(me: InternalMouseEvent, point: Point): void { this.constraintHandler.update( me, !this.first, false, !this.first || me.isSource(this.marker.highlight.shape) ? null : point ); if ( this.constraintHandler.currentFocus != null && this.constraintHandler.currentConstraint != null ) { // Handles special case where grid is large and connection point is at actual point in which // case the outline is not followed as long as we're < gridSize / 2 away from that point if ( this.marker.highlight && this.marker.highlight.state && this.marker.highlight.state.cell === this.constraintHandler.currentFocus.cell && this.marker.highlight.shape ) { // Direct repaint needed if cell already highlighted if (this.marker.highlight.shape.stroke !== 'transparent') { this.marker.highlight.shape.stroke = 'transparent'; this.marker.highlight.repaint(); } } else { this.marker.markCell(this.constraintHandler.currentFocus.cell, 'transparent'); } // Updates validation state if (this.previous) { this.error = this.validateConnection( this.previous.cell, this.constraintHandler.currentFocus.cell ); if (!this.error) { this.currentState = this.constraintHandler.currentFocus; } if ( this.error || (this.currentState && !this.isCellEnabled(this.currentState.cell)) ) { this.constraintHandler.reset(); } } } else { if (this.graph.isIgnoreTerminalEvent(me.getEvent())) { this.marker.reset(); this.currentState = null; } else { this.marker.process(me); this.currentState = this.marker.getValidState(); } if (this.currentState != null && !this.isCellEnabled(this.currentState.cell)) { this.constraintHandler.reset(); this.marker.reset(); this.currentState = null; } const outline = this.isOutlineConnectEvent(me); if (this.currentState != null && outline) { // Handles special case where mouse is on outline away from actual end point // in which case the grid is ignored and mouse point is used instead if (me.isSource(this.marker.highlight.shape)) { point = new Point(me.getGraphX(), me.getGraphY()); } const constraint = this.graph.getOutlineConstraint(point, this.currentState, me); this.constraintHandler.setFocus(me, this.currentState, false); this.constraintHandler.currentConstraint = constraint; this.constraintHandler.currentPoint = point; } if (this.outlineConnect) { if (this.marker.highlight != null && this.marker.highlight.shape != null) { const s = this.graph.view.scale; if ( this.constraintHandler.currentConstraint != null && this.constraintHandler.currentFocus != null ) { this.marker.highlight.shape.stroke = OUTLINE_HIGHLIGHT_COLOR; this.marker.highlight.shape.strokeWidth = OUTLINE_HIGHLIGHT_STROKEWIDTH / s / s; this.marker.highlight.repaint(); } else if (this.marker.hasValidState()) { const cell = me.getCell(); // Handles special case where actual end point of edge and current mouse point // are not equal (due to grid snapping) and there is no hit on shape or highlight // but ignores cases where parent is used for non-connectable child cells if ( cell && cell.isConnectable() && this.marker.getValidState() !== me.getState() ) { this.marker.highlight.shape.stroke = 'transparent'; this.currentState = null; } else { this.marker.highlight.shape.stroke = DEFAULT_VALID_COLOR; } this.marker.highlight.shape.strokeWidth = HIGHLIGHT_STROKEWIDTH / s / s; this.marker.highlight.repaint(); } } } } } /** * Function: isCellEnabled * * Returns true if the given cell does not allow new connections to be created. */ isCellEnabled(cell: Cell) { return true; } /** * Function: convertWaypoint * * Converts the given point from screen coordinates to model coordinates. */ convertWaypoint(point: Point) { const scale = this.graph.getView().getScale(); const tr = this.graph.getView().getTranslate(); point.x = point.x / scale - tr.x; point.y = point.y / scale - tr.y; } /** * Function: snapToPreview * * Called to snap the given point to the current preview. This snaps to the * first point of the preview if alt is not pressed. */ snapToPreview(me: InternalMouseEvent, point: Point) { if (!isAltDown(me.getEvent()) && this.previous) { const tol = (this.graph.getGridSize() * this.graph.view.scale) / 2; const tmp = this.sourceConstraint && this.first ? this.first : new Point(this.previous.getCenterX(), this.previous.getCenterY()); if (Math.abs(tmp.x - me.getGraphX()) < tol) { point.x = tmp.x; } if (Math.abs(tmp.y - me.getGraphY()) < tol) { point.y = tmp.y; } } } /** * Function: mouseMove * * Handles the event by updating the preview edge or by highlighting * a possible source or target terminal. */ mouseMove(sender: EventSource, me: InternalMouseEvent) { if ( !me.isConsumed() && (this.ignoreMouseDown || this.first || !this.graph.isMouseDown) ) { // Handles special case when handler is disabled during highlight if (!this.isEnabled() && this.currentState) { this.destroyIcons(); this.currentState = null; } const view = this.graph.getView(); const { scale } = view; const tr = view.translate; let point = new Point(me.getGraphX(), me.getGraphY()); this.error = null; if (this.graph.isGridEnabledEvent(me.getEvent())) { point = new Point( (this.graph.snap(point.x / scale - tr.x) + tr.x) * scale, (this.graph.snap(point.y / scale - tr.y) + tr.y) * scale ); } this.snapToPreview(me, point); this.currentPoint = point; if ( (this.first || (this.isEnabled() && this.graph.isEnabled())) && (this.shape || !this.first || Math.abs(me.getGraphX() - this.first.x) > this.graph.getEventTolerance() || Math.abs(me.getGraphY() - this.first.y) > this.graph.getEventTolerance()) ) { this.updateCurrentState(me, point); } if (this.first) { let constraint = null; let current: Point | null = point; // Uses the current point from the constraint handler if available if ( this.constraintHandler.currentConstraint && this.constraintHandler.currentFocus && this.constraintHandler.currentPoint ) { constraint = this.constraintHandler.currentConstraint; current = this.constraintHandler.currentPoint.clone(); } else if ( this.previous && !this.graph.isIgnoreTerminalEvent(me.getEvent()) && isShiftDown(me.getEvent()) ) { if ( Math.abs(this.previous.getCenterX() - point.x) < Math.abs(this.previous.getCenterY() - point.y) ) { point.x = this.previous.getCenterX(); } else { point.y = this.previous.getCenterY(); } } let pt2: Point | null = this.first; // Moves the connect icon with the mouse if (this.selectedIcon && this.selectedIcon.bounds) { const w = this.selectedIcon.bounds.width; const h = this.selectedIcon.bounds.height; if (this.currentState && this.targetConnectImage) { const pos = this.getIconPosition(this.selectedIcon, this.currentState); this.selectedIcon.bounds.x = pos.x; this.selectedIcon.bounds.y = pos.y; } else { const bounds = new Rectangle( me.getGraphX() + this.connectIconOffset.x, me.getGraphY() + this.connectIconOffset.y, w, h ); this.selectedIcon.bounds = bounds; } this.selectedIcon.redraw(); } // Uses edge state to compute the terminal points if (this.edgeState) { this.updateEdgeState(current, constraint); current = this.edgeState.absolutePoints[ this.edgeState.absolutePoints.length - 1 ]; pt2 = this.edgeState.absolutePoints[0]; } else { if (this.currentState) { if (!this.constraintHandler.currentConstraint) { const tmp = this.getTargetPerimeterPoint(this.currentState, me); if (tmp != null) { current = tmp; } } } // Computes the source perimeter point if (!this.sourceConstraint && this.previous) { const next = this.waypoints.length > 0 ? this.waypoints[0] : current; const tmp = this.getSourcePerimeterPoint(this.previous, next as Point, me); if (tmp) { pt2 = tmp; } } } // Makes sure the cell under the mousepointer can be detected // by moving the preview shape away from the mouse. This // makes sure the preview shape does not prevent the detection // of the cell under the mousepointer even for slow gestures. if (!this.currentState && this.movePreviewAway && current) { let tmp = pt2; if (this.edgeState && this.edgeState.absolutePoints.length >= 2) { const tmp2 = this.edgeState.absolutePoints[ this.edgeState.absolutePoints.length - 2 ]; if (tmp2) { tmp = tmp2; } } if (tmp) { const dx = current.x - tmp.x; const dy = current.y - tmp.y; const len = Math.sqrt(dx * dx + dy * dy); if (len === 0) { return; } // Stores old point to reuse when creating edge this.originalPoint = current.clone(); current.x -= (dx * 4) / len; current.y -= (dy * 4) / len; } } else { this.originalPoint = null; } // Creates the preview shape (lazy) if (!this.shape) { const dx = Math.abs(me.getGraphX() - this.first.x); const dy = Math.abs(me.getGraphY() - this.first.y); if ( dx > this.graph.getEventTolerance() || dy > this.graph.getEventTolerance() ) { this.shape = this.createShape(); if (this.edgeState) { this.shape.apply(this.edgeState); } // Revalidates current connection this.updateCurrentState(me, point); } } // Updates the points in the preview edge if (this.shape) { if (this.edgeState) { this.shape.points = this.edgeState.absolutePoints; } else { let pts = [pt2]; if (this.waypoints.length > 0) { pts = pts.concat(this.waypoints); } pts.push(current); this.shape.points = pts; } this.drawPreview(); } // Makes sure endpoint of edge is visible during connect if (this.cursor) { this.graph.container.style.cursor = this.cursor; } InternalEvent.consume(me.getEvent()); me.consume(); } else if (!this.isEnabled() || !this.graph.isEnabled()) { this.constraintHandler.reset(); } else if (this.previous !== this.currentState && !this.edgeState) { this.destroyIcons(); // Sets the cursor on the current shape if ( this.currentState && !this.error && !this.constraintHandler.currentConstraint ) { this.icons = this.createIcons(this.currentState); if (this.icons.length === 0) { this.currentState.setCursor(CURSOR_CONNECT); me.consume(); } } this.previous = this.currentState; } else if ( this.previous === this.currentState && this.currentState != null && this.icons.length === 0 && !this.graph.isMouseDown ) { // Makes sure that no cursors are changed me.consume(); } if (!this.graph.isMouseDown && this.currentState != null && this.icons != null) { let hitsIcon = false; const target = me.getSource(); for (let i = 0; i < this.icons.length && !hitsIcon; i += 1) { hitsIcon = target === this.icons[i].node || // @ts-ignore parentNode should exist. (!!target && target.parentNode === this.icons[i].node); } if (!hitsIcon) { this.updateIcons(this.currentState, this.icons, me); } } } else { this.constraintHandler.reset(); } } /** * Function: updateEdgeState * * Updates <edgeState>. */ updateEdgeState(current: Point | null, constraint: ConnectionConstraint | null) { if (!this.edgeState) return; // TODO: Use generic method for writing constraint to style if (this.sourceConstraint && this.sourceConstraint.point) { this.edgeState.style.exitX = this.sourceConstraint.point.x; this.edgeState.style.exitY = this.sourceConstraint.point.y; } if (constraint && constraint.point) { this.edgeState.style.entryX = constraint.point.x; this.edgeState.style.entryY = constraint.point.y; } else { this.edgeState.style.entryX = 0; this.edgeState.style.entryY = 0; } this.edgeState.absolutePoints = [null, this.currentState != null ? null : current]; if (this.sourceConstraint) { this.graph.view.updateFixedTerminalPoint( this.edgeState, this.previous, true, this.sourceConstraint ); } if (this.currentState != null) { if (constraint == null) { constraint = this.graph.getConnectionConstraint( this.edgeState, this.previous, false ); } this.edgeState.setAbsoluteTerminalPoint(null, false); this.graph.view.updateFixedTerminalPoint( this.edgeState, this.currentState, false, constraint ); } // Scales and translates the waypoints to the model let realPoints = []; for (let i = 0; i < this.waypoints.length; i += 1) { const pt = this.waypoints[i].clone(); this.convertWaypoint(pt); realPoints[i] = pt; } this.graph.view.updatePoints( this.edgeState, realPoints, this.previous, this.currentState ); this.graph.view.updateFloatingTerminalPoints( this.edgeState, this.previous, this.currentState ); } /** * Function: getTargetPerimeterPoint * * Returns the perimeter point for the given target state. * * Parameters: * * state - <mxCellState> that represents the target cell state. * me - <mxMouseEvent> that represents the mouse move. */ getTargetPerimeterPoint(state: CellState, me: InternalMouseEvent) { let result: Point | null = null; const { view } = state; const targetPerimeter = view.getPerimeterFunction(state); if (targetPerimeter && this.previous) { const next = this.waypoints.length > 0 ? this.waypoints[this.waypoints.length - 1] : new Point(this.previous.getCenterX(), this.previous.getCenterY()); const tmp = targetPerimeter( view.getPerimeterBounds(state), this.edgeState, next, false ); if (tmp) { result = tmp; } } else { result = new Point(state.getCenterX(), state.getCenterY()); } return result; } /** * Function: getSourcePerimeterPoint * * Hook to update the icon position(s) based on a mouseOver event. This is * an empty implementation. * * Parameters: * * state - <mxCellState> that represents the target cell state. * next - <mxPoint> that represents the next point along the previewed edge. * me - <mxMouseEvent> that represents the mouse move. */ getSourcePerimeterPoint(state: CellState, next: Point, me: InternalMouseEvent) { let result = null; const { view } = state; const sourcePerimeter = view.getPerimeterFunction(state); const c = new Point(state.getCenterX(), state.getCenterY()); if (sourcePerimeter) { const theta = state.style.rotation ?? 0; const rad = -theta * (Math.PI / 180); if (theta !== 0) { next = getRotatedPoint( new Point(next.x, next.y), Math.cos(rad), Math.sin(rad), c ); } let tmp = sourcePerimeter(view.getPerimeterBounds(state), state, next, false); if (tmp) { if (theta !== 0) { tmp = getRotatedPoint( new Point(tmp.x, tmp.y), Math.cos(-rad), Math.sin(-rad), c ); } result = tmp; } } else { result = c; } return result; } /** * Function: updateIcons * * Hook to update the icon position(s) based on a mouseOver event. This is * an empty implementation. * * Parameters: * * state - <mxCellState> under the mouse. * icons - Array of currently displayed icons. * me - <mxMouseEvent> that contains the mouse event. */ updateIcons(state: CellState, icons: ImageShape[], me: InternalMouseEvent) { // empty } /** * Function: isStopEvent * * Returns true if the given mouse up event should stop this handler. The * connection will be created if <error> is null. Note that this is only * called if <waypointsEnabled> is true. This implemtation returns true * if there is a cell state in the given event. */ isStopEvent(me: InternalMouseEvent) { return !!me.getState(); } /** * Function: addWaypoint * * Adds the waypoint for the given event to <waypoints>. */ addWaypointForEvent(me: InternalMouseEvent) { if (!this.first) return; let point = convertPoint(this.graph.container, me.getX(), me.getY()); const dx = Math.abs(point.x - this.first.x); const dy = Math.abs(point.y - this.first.y); const addPoint = this.waypoints.length > 0 || (this.mouseDownCounter > 1 && (dx > this.graph.getEventTolerance() || dy > this.graph.getEventTolerance())); if (addPoint) { const { scale } = this.graph.view; point = new Point( this.graph.snap(me.getGraphX() / scale) * scale, this.graph.snap(me.getGraphY() / scale) * scale ); this.waypoints.push(point); } } /** * Function: checkConstraints * * Returns true if the connection for the given constraints is valid. This * implementation returns true if the constraints are not pointing to the * same fixed connection point. */ checkConstraints(c1: ConnectionConstraint | null, c2: ConnectionConstraint | null) { return ( !c1 || !c2 || !c1.point || !c2.point || !c1.point.equals(c2.point) || c1.dx !== c2.dx || c1.dy !== c2.dy || c1.perimeter !== c2.perimeter ); } /** * Function: mouseUp * * Handles the event by inserting the new connection. */ mouseUp(sender: EventSource, me: InternalMouseEvent) { if (!me.isConsumed() && this.isConnecting()) { if (this.waypointsEnabled && !this.isStopEvent(me)) { this.addWaypointForEvent(me); me.consume(); return; } const c1 = this.sourceConstraint; const c2 = this.constraintHandler.currentConstraint; const source = this.previous ? this.previous.cell : null; let target = null; if ( this.constraintHandler.currentConstraint && this.constraintHandler.currentFocus ) { target = this.constraintHandler.currentFocus.cell; } if (!target && this.currentState) { target = this.currentState.cell; } // Inserts the edge if no validation error exists and if constraints differ if ( !this.error && (!source || !target || source !== target || this.checkConstraints(c1, c2)) ) { this.connect(source, target, me.getEvent(), me.getCell()); } else { // Selects the source terminal for self-references if ( this.previous != null && this.marker.validState != null && this.previous.cell === this.marker.validState.cell ) { this.graph.selectCellForEvent(this.marker.validState.cell, me.getEvent()); } // Displays the error message if it is not an empty string, // for empty error messages, the event is silently dropped if (this.error != null && this.error.length > 0) { this.graph.validationAlert(this.error); } } // Redraws the connect icons and resets the handler state this.destroyIcons(); me.consume(); } if (this.first != null) { this.reset(); } } /** * Function: reset * * Resets the state of this handler. */ reset(): void { if (this.shape != null) { this.shape.destroy(); this.shape = null; } // Resets the cursor on the container if (this.cursor != null && this.graph.container != null) { this.graph.container.style.cursor = ''; } this.destroyIcons(); this.marker.reset(); this.constraintHandler.reset(); this.originalPoint = null; this.currentPoint = null; this.edgeState = null; this.previous = null; this.error = null; this.sourceConstraint = null; this.mouseDownCounter = 0; this.first = null; this.fireEvent(new EventObject(InternalEvent.RESET)); } /** * Function: drawPreview * * Redraws the preview edge using the color and width returned by * <getEdgeColor> and <getEdgeWidth>. */ drawPreview() { this.updatePreview(this.error === null); if (this.shape) this.shape.redraw(); } /** * Function: getEdgeColor * * Returns the color used to draw the preview edge. This returns green if * there is no edge validation error and red otherwise. * * Parameters: * * valid - Boolean indicating if the color for a valid edge should be * returned. */ updatePreview(valid: boolean) { if (this.shape) { this.shape.strokeWidth = this.getEdgeWidth(valid); this.shape.stroke = this.getEdgeColor(valid); } } /** * Function: getEdgeColor * * Returns the color used to draw the preview edge. This returns green if * there is no edge validation error and red otherwise. * * Parameters: * * valid - Boolean indicating if the color for a valid edge should be * returned. */ getEdgeColor(valid: boolean) { return valid ? VALID_COLOR : INVALID_COLOR; } /** * Function: getEdgeWidth * * Returns the width used to draw the preview edge. This returns 3 if * there is no edge validation error and 1 otherwise. * * Parameters: * * valid - Boolean indicating if the width for a valid edge should be * returned. */ getEdgeWidth(valid: boolean): number { return valid ? 3 : 1; } /** * Function: connect * * Connects the given source and target using a new edge. This * implementation uses <createEdge> to create the edge. * * Parameters: * * source - <mxCell> that represents the source terminal. * target - <mxCell> that represents the target terminal. * evt - Mousedown event of the connect gesture. * dropTarget - <mxCell> that represents the cell under the mouse when it was * released. */ connect( source: Cell | null, target: Cell | null, evt: MouseEvent, dropTarget: Cell | null = null ) { if (target || this.isCreateTarget(evt) || this.graph.isAllowDanglingEdges()) { // Uses the common parent of source and target or // the default parent to insert the edge const model = this.graph.getModel(); let terminalInserted = false; let edge: Cell | null = null; model.beginUpdate(); try { if ( source && !target && !this.graph.isIgnoreTerminalEvent(evt) && this.isCreateTarget(evt) ) { target = this.createTargetVertex(evt, source); if (target) { dropTarget = this.graph.getDropTarget(new CellArray(target), evt, dropTarget); terminalInserted = true; // Disables edges as drop targets if the target cell was created // FIXME: Should not shift if vertex was aligned (same in Java) if (dropTarget == null || !dropTarget.isEdge()) { const pstate = dropTarget ? this.graph.getView().getState(dropTarget) : null; if (pstate) { const tmp = target.getGeometry(); if (tmp) { tmp.x -= pstate.origin.x; tmp.y -= pstate.origin.y; } } } else { dropTarget = this.graph.getDefaultParent(); } this.graph.addCell(target, dropTarget); } } let parent: Cell | null = this.graph.getDefaultParent(); if ( source && target && source.getParent() === target.getParent() && source.getParent()?.getParent() !== model.getRoot() ) { parent = source.getParent(); if ( source.geometry && source.geometry.relative && target.geometry && target.geometry.relative ) { parent = parent!.getParent(); } } // Uses the value of the preview edge state for inserting // the new edge into the graph let value = null; let style = ''; if (this.edgeState) { value = this.edgeState.cell.value; style = this.edgeState.cell.style ?? ''; } edge = this.insertEdge(parent as Cell, '', value, source, target, style); if (edge && source) { // Updates the connection constraints this.graph.setConnectionConstraint(edge, source, true, this.sourceConstraint); this.graph.setConnectionConstraint( edge, target, false, this.constraintHandler.currentConstraint ); // Uses geometry of the preview edge state if (this.edgeState && this.edgeState.cell && this.edgeState.cell.geometry) { model.setGeometry(edge, this.edgeState.cell.geometry); } parent = source.getParent(); // Inserts edge before source if (this.isInsertBefore(edge, source, target, evt, dropTarget)) { const index = null; let tmp: Cell | null = source; while ( tmp && tmp.parent != null && tmp.geometry != null && tmp.geometry.relative && tmp.parent !== edge.parent ) { tmp = tmp.getParent(); } if (tmp != null && tmp.parent != null && tmp.parent === edge.parent) { model.add(parent, edge, tmp.parent.getIndex(tmp)); } } // Makes sure the edge has a non-null, relative geometry let geo = edge.getGeometry(); if (geo == null) { geo = new Geometry(); geo.relative = true; model.setGeometry(edge, geo); } // Uses scaled waypoints in geometry if (this.waypoints.length > 0) { const s = this.graph.view.scale; const tr = this.graph.view.translate; geo.points = []; for (let i = 0; i < this.waypoints.length; i += 1) { const pt = this.waypoints[i]; geo.points.push(new Point(pt.x / s - tr.x, pt.y / s - tr.y)); } } if (!target && this.currentPoint) { const t = this.graph.view.translate; const s = this.graph.view.scale; const pt = this.originalPoint != null ? new Point( this.originalPoint.x / s - t.x, this.originalPoint.y / s - t.y ) : new Point(this.currentPoint.x / s - t.x, this.currentPoint.y / s - t.y); pt.x -= this.graph.getPanDx() / this.graph.view.scale; pt.y -= this.graph.getPanDy() / this.graph.view.scale; geo.setTerminalPoint(pt, false); } this.fireEvent( new EventObject( InternalEvent.CONNECT, 'cell', edge, 'terminal', target, 'event', evt, 'target', dropTarget, 'terminalInserted', terminalInserted ) ); } } catch (e) { mxLog.show(); // mxLog.debug(e.message); } finally { model.endUpdate(); } if (this.select) { this.selectCells(edge, terminalInserted ? target : null); } } } /** * Function: selectCells * * Selects the given edge after adding a new connection. The target argument * contains the target vertex if one has been inserted. */ selectCells(edge: Cell | null, target: Cell | null) { this.graph.setSelectionCell(edge); } /** * Function: insertEdge * * Creates, inserts and returns the new edge for the given parameters. This * implementation does only use <createEdge> if <factoryMethod> is defined, * otherwise <mxGraph.insertEdge> will be used. */ insertEdge( parent: Cell, id: string, value: any, source: Cell | null, target: Cell | null, style: string ): Cell { if (!this.factoryMethod) { return this.graph.insertEdge(parent, id, value, source, target, style); } let edge = this.createEdge(value, source, target, style); edge = this.graph.addEdge(edge, parent, source, target); return edge; } /** * Function: createTargetVertex * * Hook method for creating new vertices on the fly if no target was * under the mouse. This is only called if <createTarget> is true and * returns null. * * Parameters: * * evt - Mousedown event of the connect gesture. * source - <mxCell> that represents the source terminal. */ createTargetVertex(evt: MouseEvent, source: Cell) { // Uses the first non-relative source let geo = source.getGeometry(); while (geo && geo.relative) { source = source.getParent() as Cell; geo = source.getGeometry(); } const clone = this.graph.cloneCell(source); geo = clone.getGeometry(); if (geo && this.currentPoint) { const t = this.graph.view.translate; const s = this.graph.view.scale; const point = new Point( this.currentPoint.x / s - t.x, this.currentPoint.y / s - t.y ); geo.x = Math.round(point.x - geo.width / 2 - this.graph.getPanDx() / s); geo.y = Math.round(point.y - geo.height / 2 - this.graph.getPanDy() / s); // Aligns with source if within certain tolerance const tol = this.getAlignmentTolerance(); if (tol > 0) { const sourceState = this.graph.view.getState(source); if (sourceState != null) { const x = sourceState.x / s - t.x; const y = sourceState.y / s - t.y; if (Math.abs(x - geo.x) <= tol) { geo.x = Math.round(x); } if (Math.abs(y - geo.y) <= tol) { geo.y = Math.round(y); } } } } return clone; } /** * Function: getAlignmentTolerance * * Returns the tolerance for aligning new targets to sources. This returns the grid size / 2. */ getAlignmentTolerance(evt?: MouseEvent): number { return this.graph.isGridEnabled() ? this.graph.getGridSize() / 2 : this.graph.getSnapTolerance(); } /** * Function: createEdge * * Creates and returns a new edge using <factoryMethod> if one exists. If * no factory method is defined, then a new default edge is returned. The * source and target arguments are informal, the actual connection is * setup later by the caller of this function. * * Parameters: * * value - Value to be used for creating the edge. * source - <mxCell> that represents the source terminal. * target - <mxCell> that represents the target terminal. * style - Optional style from the preview edge. */ createEdge(value: any, source: Cell | null, target: Cell | null, style: string = '') { let edge = null; // Creates a new edge using the factoryMethod if (this.factoryMethod != null) { edge = this.factoryMethod(source, target, style); } if (edge == null) { edge = new Cell(value || ''); edge.setEdge(true); edge.setStyle(style); const geo = new Geometry(); geo.relative = true; edge.setGeometry(geo); } return edge; } /** * Function: destroy * * Destroys the handler and all its resources and DOM nodes. This should be * called on all instances. It is called automatically for the built-in * instance created for each <mxGraph>. */ onDestroy() { this.graph.removeMouseListener(this); if (this.shape) { this.shape.destroy(); this.shape = null; } if (this.marker) { this.marker.destroy(); // @ts-expect-error this.marker is null when it is destroyed. this.marker = null; } if (this.constraintHandler) { this.constraintHandler.destroy(); } if (this.changeHandler) { this.graph.getModel().removeListener(this.changeHandler); this.graph.getView().removeListener(this.changeHandler); } if (this.drillHandler) { this.graph.removeListener(this.drillHandler); this.graph.getView().removeListener(this.drillHandler); } if (this.escapeHandler) { this.graph.removeListener(this.escapeHandler); } } } export default ConnectionHandler;
the_stack