text
stringlengths
2.5k
6.39M
kind
stringclasses
3 values
import {AriaLabelingProps} from '@react-types/shared'; import {HTMLAttributes, MutableRefObject, useCallback, useEffect, useState} from 'react'; import {useLayoutEffect} from '@react-aria/utils'; export type AriaLandmarkRole = 'main' | 'region' | 'search' | 'navigation' | 'form' | 'banner' | 'contentinfo' | 'complementary'; export interface AriaLandmarkProps extends AriaLabelingProps { role: AriaLandmarkRole } interface LandmarkAria { landmarkProps: HTMLAttributes<HTMLElement> } type Landmark = { ref: MutableRefObject<HTMLElement>, role: AriaLandmarkRole, label?: string, lastFocused?: HTMLElement, focus: () => void, blur: () => void }; class LandmarkManager { private landmarks: Array<Landmark> = []; private static instance: LandmarkManager; private isListening = false; private constructor() { this.f6Handler = this.f6Handler.bind(this); this.focusinHandler = this.focusinHandler.bind(this); this.focusoutHandler = this.focusoutHandler.bind(this); } public static getInstance(): LandmarkManager { if (!LandmarkManager.instance) { LandmarkManager.instance = new LandmarkManager(); } return LandmarkManager.instance; } private setup() { document.addEventListener('keydown', this.f6Handler, {capture: true}); document.addEventListener('focusin', this.focusinHandler, {capture: true}); document.addEventListener('focusout', this.focusoutHandler, {capture: true}); this.isListening = true; } private teardown() { document.removeEventListener('keydown', this.f6Handler, {capture: true}); document.removeEventListener('focusin', this.focusinHandler, {capture: true}); document.removeEventListener('focusout', this.focusoutHandler, {capture: true}); this.isListening = false; } private focusLandmark(landmark: HTMLElement) { this.landmarks.find(l => l.ref.current === landmark)?.focus(); } /** * Return set of landmarks with a specific role. */ public getLandmarksByRole(role: AriaLandmarkRole) { return new Set(this.landmarks.filter(l => l.role === role)); } /** * Return first landmark with a specific role. */ public getLandmarkByRole(role: AriaLandmarkRole) { return this.landmarks.find(l => l.role === role); } public addLandmark(newLandmark: Landmark) { if (!this.isListening) { this.setup(); } if (this.landmarks.find(landmark => landmark.ref === newLandmark.ref)) { return; } if (this.landmarks.filter(landmark => landmark.role === 'main').length > 1) { console.error('Page can contain no more than one landmark with the role "main".'); } if (this.landmarks.length === 0) { this.landmarks = [newLandmark]; return; } // Binary search to insert new landmark based on position in document relative to existing landmarks. // https://developer.mozilla.org/en-US/docs/Web/API/Node/compareDocumentPosition let start = 0; let end = this.landmarks.length - 1; while (start <= end) { let mid = Math.floor((start + end) / 2); let comparedPosition = newLandmark.ref.current.compareDocumentPosition(this.landmarks[mid].ref.current as Node); let isNewAfterExisting = Boolean((comparedPosition & Node.DOCUMENT_POSITION_PRECEDING) || (comparedPosition & Node.DOCUMENT_POSITION_CONTAINS)); if (isNewAfterExisting) { start = mid + 1; } else { end = mid - 1; } } this.landmarks.splice(start, 0, newLandmark); } public updateLandmark(landmark: Pick<Landmark, 'ref'> & Partial<Landmark>) { let index = this.landmarks.findIndex(l => l.ref === landmark.ref); if (index >= 0) { this.landmarks[index] = {...this.landmarks[index], ...landmark}; this.checkLabels(this.landmarks[index].role); } } public removeLandmark(ref: MutableRefObject<HTMLElement>) { this.landmarks = this.landmarks.filter(landmark => landmark.ref !== ref); if (this.landmarks.length === 0) { this.teardown(); } } /** * Warn if there are 2+ landmarks with the same role but no label. * Labels for landmarks with the same role must also be unique. * * See https://www.w3.org/TR/wai-aria-practices/examples/landmarks/navigation.html. */ private checkLabels(role: AriaLandmarkRole) { let landmarksWithRole = this.getLandmarksByRole(role); if (landmarksWithRole.size > 1) { let duplicatesWithoutLabel = [...landmarksWithRole].filter(landmark => !landmark.label); if (duplicatesWithoutLabel.length > 0) { console.warn( `Page contains more than one landmark with the '${role}' role. If two or more landmarks on a page share the same role, all must be labeled with an aria-label or aria-labelledby attribute: `, duplicatesWithoutLabel.map(landmark => landmark.ref.current) ); } else { let labels = [...landmarksWithRole].map(landmark => landmark.label); let duplicateLabels = labels.filter((item, index) => labels.indexOf(item) !== index); duplicateLabels.forEach((label) => { console.warn( `Page contains more than one landmark with the '${role}' role and '${label}' label. If two or more landmarks on a page share the same role, they must have unique labels: `, [...landmarksWithRole].filter(landmark => landmark.label === label).map(landmark => landmark.ref.current) ); }); } } } /** * Get the landmark that is the closest parent in the DOM. * Returns undefined if no parent is a landmark. */ private closestLandmark(element: HTMLElement) { let landmarkMap = new Map(this.landmarks.map(l => [l.ref.current, l])); let currentElement = element; while (!landmarkMap.has(currentElement) && currentElement !== document.body) { currentElement = currentElement.parentElement; } return landmarkMap.get(currentElement); } /** * Gets the next landmark, in DOM focus order, or previous if backwards is specified. * If last landmark, next should be the first landmark. * If not inside a landmark, will return first landmark. * Returns undefined if there are no landmarks. */ public getNextLandmark(element: HTMLElement, {backward}: {backward?: boolean }) { if (this.landmarks.length === 0) { return undefined; } let currentLandmark = this.closestLandmark(element); let nextLandmarkIndex = backward ? -1 : 0; if (currentLandmark) { nextLandmarkIndex = this.landmarks.findIndex(landmark => landmark === currentLandmark) + (backward ? -1 : 1); } // Wrap if necessary if (nextLandmarkIndex < 0) { nextLandmarkIndex = this.landmarks.length - 1; } else if (nextLandmarkIndex >= this.landmarks.length) { nextLandmarkIndex = 0; } return this.landmarks[nextLandmarkIndex]; } /** * Look at next landmark. If an element was previously focused inside, restore focus there. * If not, focus the landmark itself. * If no landmarks at all, or none with focusable elements, don't move focus. */ public f6Handler(e: KeyboardEvent) { if (e.key === 'F6') { e.preventDefault(); e.stopPropagation(); let backward = e.shiftKey; let nextLandmark = this.getNextLandmark(e.target as HTMLElement, {backward}); // If no landmarks, return if (!nextLandmark) { return; } // If alt key pressed, focus main landmark if (e.altKey) { let main = this.getLandmarkByRole('main'); if (main && document.contains(main.ref.current)) { this.focusLandmark(main.ref.current); } return; } // If something was previously focused in the next landmark, then return focus to it if (nextLandmark.lastFocused) { let lastFocused = nextLandmark.lastFocused; if (document.body.contains(lastFocused)) { lastFocused.focus(); return; } } // Otherwise, focus the landmark itself if (document.contains(nextLandmark.ref.current)) { this.focusLandmark(nextLandmark.ref.current); } } } /** * Sets lastFocused for a landmark, if focus is moved within that landmark. * Lets the last focused landmark know it was blurred if something else is focused. */ public focusinHandler(e: FocusEvent) { let currentLandmark = this.closestLandmark(e.target as HTMLElement); if (currentLandmark && currentLandmark.ref.current !== e.target) { this.updateLandmark({ref: currentLandmark.ref, lastFocused: e.target as HTMLElement}); } let previousFocusedElement = e.relatedTarget as HTMLElement; if (previousFocusedElement) { let closestPreviousLandmark = this.closestLandmark(previousFocusedElement); if (closestPreviousLandmark && closestPreviousLandmark.ref.current === previousFocusedElement) { closestPreviousLandmark.blur(); } } } /** * Track if the focus is lost to the body. If it is, do cleanup on the landmark that last had focus. */ public focusoutHandler(e: FocusEvent) { let previousFocusedElement = e.target as HTMLElement; let nextFocusedElement = e.relatedTarget; // the === document seems to be a jest thing for focus to go there on generic blur event such as landmark.blur(); // browsers appear to send focus instead to document.body and the relatedTarget is null when that happens if (!nextFocusedElement || nextFocusedElement === document) { let closestPreviousLandmark = this.closestLandmark(previousFocusedElement); if (closestPreviousLandmark && closestPreviousLandmark.ref.current === previousFocusedElement) { closestPreviousLandmark.blur(); } } } } /** * Provides landmark navigation in an application. Call this with a role and label to register a landmark navigable with F6. * @param props - Props for the landmark. * @param ref - Ref to the landmark. */ export function useLandmark(props: AriaLandmarkProps, ref: MutableRefObject<HTMLElement>): LandmarkAria { const { role, 'aria-label': ariaLabel, 'aria-labelledby': ariaLabelledby } = props; let manager = LandmarkManager.getInstance(); let label = ariaLabel || ariaLabelledby; let [isLandmarkFocused, setIsLandmarkFocused] = useState(false); let focus = useCallback(() => { setIsLandmarkFocused(true); }, [setIsLandmarkFocused]); let blur = useCallback(() => { setIsLandmarkFocused(false); }, [setIsLandmarkFocused]); useLayoutEffect(() => { manager.addLandmark({ref, role, label, focus, blur}); return () => { manager.removeLandmark(ref); }; // eslint-disable-next-line react-hooks/exhaustive-deps }, []); useLayoutEffect(() => { manager.updateLandmark({ref, label, role, focus, blur}); // eslint-disable-next-line react-hooks/exhaustive-deps }, [label, ref, role]); useEffect(() => { if (isLandmarkFocused) { ref.current.focus(); } }, [isLandmarkFocused, ref]); return { landmarkProps: { role, tabIndex: isLandmarkFocused ? -1 : undefined } }; }
the_stack
import * as pulumi from "@pulumi/pulumi"; import * as utilities from "../utilities"; /** * Manages a Log Analytics Linked Service. * * ## Example Usage * * ```typescript * import * as pulumi from "@pulumi/pulumi"; * import * as azure from "@pulumi/azure"; * * const exampleResourceGroup = new azure.core.ResourceGroup("exampleResourceGroup", {location: "West Europe"}); * const exampleAccount = new azure.automation.Account("exampleAccount", { * location: exampleResourceGroup.location, * resourceGroupName: exampleResourceGroup.name, * skuName: "Basic", * tags: { * environment: "development", * }, * }); * const exampleAnalyticsWorkspace = new azure.operationalinsights.AnalyticsWorkspace("exampleAnalyticsWorkspace", { * location: exampleResourceGroup.location, * resourceGroupName: exampleResourceGroup.name, * sku: "PerGB2018", * retentionInDays: 30, * }); * const exampleLinkedService = new azure.loganalytics.LinkedService("exampleLinkedService", { * resourceGroupName: exampleResourceGroup.name, * workspaceId: exampleAnalyticsWorkspace.id, * readAccessId: exampleAccount.id, * }); * ``` * * ## Import * * Log Analytics Workspaces can be imported using the `resource id`, e.g. * * ```sh * $ pulumi import azure:loganalytics/linkedService:LinkedService example /subscriptions/00000000-0000-0000-0000-000000000000/resourceGroups/mygroup1/providers/Microsoft.OperationalInsights/workspaces/workspace1/linkedServices/Automation * ``` */ export class LinkedService extends pulumi.CustomResource { /** * Get an existing LinkedService resource's state with the given name, ID, and optional extra * properties used to qualify the lookup. * * @param name The _unique_ name of the resulting resource. * @param id The _unique_ provider ID of the resource to lookup. * @param state Any extra arguments used during the lookup. * @param opts Optional settings to control the behavior of the CustomResource. */ public static get(name: string, id: pulumi.Input<pulumi.ID>, state?: LinkedServiceState, opts?: pulumi.CustomResourceOptions): LinkedService { return new LinkedService(name, <any>state, { ...opts, id: id }); } /** @internal */ public static readonly __pulumiType = 'azure:loganalytics/linkedService:LinkedService'; /** * Returns true if the given object is an instance of LinkedService. This is designed to work even * when multiple copies of the Pulumi SDK have been loaded into the same process. */ public static isInstance(obj: any): obj is LinkedService { if (obj === undefined || obj === null) { return false; } return obj['__pulumiType'] === LinkedService.__pulumiType; } /** * Name of the type of linkedServices resource to connect to the Log Analytics Workspace specified in workspace_name. Accepted values are `automation` and `cluster`. Defaults to `automation`. Changing this forces a new resource to be created. * * @deprecated This field has been deprecated and will be removed in a future version of the provider */ public readonly linkedServiceName!: pulumi.Output<string>; /** * The generated name of the Linked Service. The format for this attribute is always `<workspace name>/<linked service type>`(e.g. `workspace1/Automation` or `workspace1/Cluster`) */ public /*out*/ readonly name!: pulumi.Output<string>; /** * The ID of the readable Resource that will be linked to the workspace. This should be used for linking to an Automation Account resource. */ public readonly readAccessId!: pulumi.Output<string>; /** * The name of the resource group in which the Log Analytics Linked Service is created. Changing this forces a new resource to be created. */ public readonly resourceGroupName!: pulumi.Output<string>; /** * The ID of the Resource that will be linked to the workspace. This should be used for linking to an Automation Account resource. * * @deprecated This field has been deprecated in favour of `read_access_id` and will be removed in a future version of the provider */ public readonly resourceId!: pulumi.Output<string>; /** * A mapping of tags to assign to the resource. */ public readonly tags!: pulumi.Output<{[key: string]: string} | undefined>; /** * The ID of the Log Analytics Workspace that will contain the Log Analytics Linked Service resource. Changing this forces a new resource to be created. */ public readonly workspaceId!: pulumi.Output<string>; /** * The name of the Log Analytics Workspace that will contain the Log Analytics Linked Service resource. Changing this forces a new resource to be created. * * @deprecated This field has been deprecated in favour of `workspace_id` and will be removed in a future version of the provider */ public readonly workspaceName!: pulumi.Output<string>; /** * The ID of the writable Resource that will be linked to the workspace. This should be used for linking to a Log Analytics Cluster resource. */ public readonly writeAccessId!: pulumi.Output<string | undefined>; /** * Create a LinkedService resource with the given unique name, arguments, and options. * * @param name The _unique_ name of the resource. * @param args The arguments to use to populate this resource's properties. * @param opts A bag of options that control this resource's behavior. */ constructor(name: string, args: LinkedServiceArgs, opts?: pulumi.CustomResourceOptions) constructor(name: string, argsOrState?: LinkedServiceArgs | LinkedServiceState, opts?: pulumi.CustomResourceOptions) { let inputs: pulumi.Inputs = {}; opts = opts || {}; if (opts.id) { const state = argsOrState as LinkedServiceState | undefined; inputs["linkedServiceName"] = state ? state.linkedServiceName : undefined; inputs["name"] = state ? state.name : undefined; inputs["readAccessId"] = state ? state.readAccessId : undefined; inputs["resourceGroupName"] = state ? state.resourceGroupName : undefined; inputs["resourceId"] = state ? state.resourceId : undefined; inputs["tags"] = state ? state.tags : undefined; inputs["workspaceId"] = state ? state.workspaceId : undefined; inputs["workspaceName"] = state ? state.workspaceName : undefined; inputs["writeAccessId"] = state ? state.writeAccessId : undefined; } else { const args = argsOrState as LinkedServiceArgs | undefined; if ((!args || args.resourceGroupName === undefined) && !opts.urn) { throw new Error("Missing required property 'resourceGroupName'"); } inputs["linkedServiceName"] = args ? args.linkedServiceName : undefined; inputs["readAccessId"] = args ? args.readAccessId : undefined; inputs["resourceGroupName"] = args ? args.resourceGroupName : undefined; inputs["resourceId"] = args ? args.resourceId : undefined; inputs["tags"] = args ? args.tags : undefined; inputs["workspaceId"] = args ? args.workspaceId : undefined; inputs["workspaceName"] = args ? args.workspaceName : undefined; inputs["writeAccessId"] = args ? args.writeAccessId : undefined; inputs["name"] = undefined /*out*/; } if (!opts.version) { opts = pulumi.mergeOptions(opts, { version: utilities.getVersion()}); } super(LinkedService.__pulumiType, name, inputs, opts); } } /** * Input properties used for looking up and filtering LinkedService resources. */ export interface LinkedServiceState { /** * Name of the type of linkedServices resource to connect to the Log Analytics Workspace specified in workspace_name. Accepted values are `automation` and `cluster`. Defaults to `automation`. Changing this forces a new resource to be created. * * @deprecated This field has been deprecated and will be removed in a future version of the provider */ linkedServiceName?: pulumi.Input<string>; /** * The generated name of the Linked Service. The format for this attribute is always `<workspace name>/<linked service type>`(e.g. `workspace1/Automation` or `workspace1/Cluster`) */ name?: pulumi.Input<string>; /** * The ID of the readable Resource that will be linked to the workspace. This should be used for linking to an Automation Account resource. */ readAccessId?: pulumi.Input<string>; /** * The name of the resource group in which the Log Analytics Linked Service is created. Changing this forces a new resource to be created. */ resourceGroupName?: pulumi.Input<string>; /** * The ID of the Resource that will be linked to the workspace. This should be used for linking to an Automation Account resource. * * @deprecated This field has been deprecated in favour of `read_access_id` and will be removed in a future version of the provider */ resourceId?: pulumi.Input<string>; /** * A mapping of tags to assign to the resource. */ tags?: pulumi.Input<{[key: string]: pulumi.Input<string>}>; /** * The ID of the Log Analytics Workspace that will contain the Log Analytics Linked Service resource. Changing this forces a new resource to be created. */ workspaceId?: pulumi.Input<string>; /** * The name of the Log Analytics Workspace that will contain the Log Analytics Linked Service resource. Changing this forces a new resource to be created. * * @deprecated This field has been deprecated in favour of `workspace_id` and will be removed in a future version of the provider */ workspaceName?: pulumi.Input<string>; /** * The ID of the writable Resource that will be linked to the workspace. This should be used for linking to a Log Analytics Cluster resource. */ writeAccessId?: pulumi.Input<string>; } /** * The set of arguments for constructing a LinkedService resource. */ export interface LinkedServiceArgs { /** * Name of the type of linkedServices resource to connect to the Log Analytics Workspace specified in workspace_name. Accepted values are `automation` and `cluster`. Defaults to `automation`. Changing this forces a new resource to be created. * * @deprecated This field has been deprecated and will be removed in a future version of the provider */ linkedServiceName?: pulumi.Input<string>; /** * The ID of the readable Resource that will be linked to the workspace. This should be used for linking to an Automation Account resource. */ readAccessId?: pulumi.Input<string>; /** * The name of the resource group in which the Log Analytics Linked Service is created. Changing this forces a new resource to be created. */ resourceGroupName: pulumi.Input<string>; /** * The ID of the Resource that will be linked to the workspace. This should be used for linking to an Automation Account resource. * * @deprecated This field has been deprecated in favour of `read_access_id` and will be removed in a future version of the provider */ resourceId?: pulumi.Input<string>; /** * A mapping of tags to assign to the resource. */ tags?: pulumi.Input<{[key: string]: pulumi.Input<string>}>; /** * The ID of the Log Analytics Workspace that will contain the Log Analytics Linked Service resource. Changing this forces a new resource to be created. */ workspaceId?: pulumi.Input<string>; /** * The name of the Log Analytics Workspace that will contain the Log Analytics Linked Service resource. Changing this forces a new resource to be created. * * @deprecated This field has been deprecated in favour of `workspace_id` and will be removed in a future version of the provider */ workspaceName?: pulumi.Input<string>; /** * The ID of the writable Resource that will be linked to the workspace. This should be used for linking to a Log Analytics Cluster resource. */ writeAccessId?: pulumi.Input<string>; }
the_stack
import { DocumentNode, Reference, StoreObject, useQuery } from '@apollo/client' import { useRef, useCallback, useMemo } from 'react' import { ChannelContentsConnectable } from '__generated__/ChannelContentsConnectable' import { moveConnectableMutationVariables, moveConnectableMutation as moveConnectableMutationData, } from '__generated__/moveConnectableMutation' import { BaseConnectableTypeEnum, ConnectableTypeEnum, SortDirection, Sorts, } from '__generated__/globalTypes' import { ChannelContentCount, ChannelContentCountVariables, } from '__generated__/ChannelContentCount' import moveConnectableMutation from 'v2/components/ChannelContents/mutations/moveConnectable' import { getConnectableType } from 'v2/util/getConnectableType' import { CHANNEL_CONTENT_COUNT } from './ChannelContentCount' /** * The minimum required shape for the channel query */ interface RequiredChannelQueryData { channel: null | { __typename: 'Channel' id: number blokks: null | Array<{ __typename: ChannelContentsConnectable['__typename'] id: number } | null> counts: null | { __typename: 'ChannelCounts' contents: number | null blocks: number | null channels: number | null } } } /** * The minimum required shape for the channel query variables */ interface RequiredChannelQueryVariables { id: string page: number per: number sort?: Sorts | null direction?: SortDirection | null type?: ConnectableTypeEnum | null user_id?: string | null } /** * The minimum required shape for the block query */ interface RequiredBlockQueryData { blokk: null | { __typename: ChannelContentsConnectable['__typename'] id: number } } /** * The minimum required shape for the block query variables */ interface RequiredBlockQueryVariables { id: string } /** * The base arguments for usePaginatedBlocks */ interface UsePaginatedBlocksBaseArgs { channelId: string channelQuery: DocumentNode per: number sort?: Sorts | null direction?: SortDirection | null type?: ConnectableTypeEnum | null user_id?: string | null ssr?: boolean } /** * The full arguments for usePaginatedBlocks */ interface UsePaginatedBlocksArgs extends UsePaginatedBlocksBaseArgs { blockquery: DocumentNode } /** * The contents of the blokks field */ type Block<ChannelQueryData extends RequiredChannelQueryData> = | NonNullable<NonNullable<ChannelQueryData['channel']>['blokks']>[number] | null /** * A type that asserts the channel query and block query have * a matching blokk shape */ interface MatchingBlockQueryData< ChannelQueryData extends RequiredChannelQueryData > extends RequiredBlockQueryData { blokk: Block<ChannelQueryData> | null } /** * The base return type for usePaginatedBlocks */ interface UsePaginatedBlocksBaseApi< ChannelQueryData extends RequiredChannelQueryData > { blocks: Array<Block<ChannelQueryData>> contentCount: number getPage: (pageNumber: number) => void hasQueriedPage: (pageNumber: number) => boolean getPageFromIndex: (index: number) => number removeBlock: (args: { id: number; type: string }) => void moveBlock: (args: { oldIndex: number; newIndex: number }) => void addBlock: () => void getBlocksFromCache: () => Array<Block<ChannelQueryData>> loading: boolean } /** * The full return type for usePaginatedBlocks */ interface UsePaginatedBlocksApi< ChannelQueryData extends RequiredChannelQueryData > extends UsePaginatedBlocksBaseApi<ChannelQueryData> { updateBlock: (args: { id: string type: BaseConnectableTypeEnum | false }) => Promise<void> } /** * The base overload of usePaginatedBlocks which doesn't support * the updateBlock function */ export function usePaginatedBlocks< ChannelQueryData extends RequiredChannelQueryData, // eslint-disable-next-line @typescript-eslint/no-unused-vars ChannelQueryVariables extends RequiredChannelQueryVariables >( unsafeArgs: UsePaginatedBlocksBaseArgs ): UsePaginatedBlocksBaseApi<ChannelQueryData> /** * The full overload of usePaginatedBlocks */ export function usePaginatedBlocks< ChannelQueryData extends RequiredChannelQueryData, // eslint-disable-next-line @typescript-eslint/no-unused-vars ChannelQueryVariables extends RequiredChannelQueryVariables, // eslint-disable-next-line @typescript-eslint/no-unused-vars BlockQueryData extends MatchingBlockQueryData<ChannelQueryData>, // eslint-disable-next-line @typescript-eslint/no-unused-vars BlockQueryVariables extends RequiredBlockQueryVariables >(unsafeArgs: UsePaginatedBlocksArgs): UsePaginatedBlocksApi<ChannelQueryData> /** * A hook to easily work with a collection of blocks from a channel. * Returns the channel's blocks as well as utility methods to fetch more, * move blocks around, add blocks, and delete blocks. */ export function usePaginatedBlocks< ChannelQueryData extends RequiredChannelQueryData, ChannelQueryVariables extends RequiredChannelQueryVariables, BlockQueryData extends MatchingBlockQueryData<ChannelQueryData>, BlockQueryVariables extends RequiredBlockQueryVariables >({ channelQuery, channelId, per, sort, direction, ssr, type, user_id, blockquery, }: UsePaginatedBlocksBaseArgs & Partial<UsePaginatedBlocksArgs>): UsePaginatedBlocksBaseApi< ChannelQueryData > & Partial<UsePaginatedBlocksApi<ChannelQueryData>> { // ============================= // "Private" fields of this hook // ============================= /** * A set that keeps track of which pages have already been queried for */ const queriedPageNumbersRef = useRef(new Set<number>()) /** * A variable that stores all the identifiable information of * to the current query. If any of this data changes, reset * the queriedPageNumbersRef. */ const channelQueryData: { query: DocumentNode variables: ChannelQueryVariables } = useMemo(() => { queriedPageNumbersRef.current = new Set() return { query: channelQuery, variables: { id: channelId, page: 1, per: per, sort: sort, direction: direction, type: type, user_id: user_id, } as ChannelQueryVariables, } }, [channelId, channelQuery, direction, per, sort, type, user_id]) /** * The current blocks that we have for a channel */ const { data: unsafeData, fetchMore, client, loading } = useQuery< ChannelQueryData, ChannelQueryVariables >(channelQueryData.query, { variables: channelQueryData.variables, ssr: ssr, context: { queryDeduplication: false }, }) /** * A function to get the currently cached query data. Useful if * you want to use this data in a memoized function without re-memoizing * every time the query data changes (which happens a lot) */ const getQueryFromCache: () => ChannelQueryData | null = useCallback(() => { return client.readQuery<ChannelQueryData, ChannelQueryVariables>({ query: channelQueryData.query, variables: channelQueryData.variables, }) }, [client, channelQueryData]) /** * A function that allows you to directly modify the channel's "blokks" * cache value. If the length of blokks changes, the channel.counts.contents * field will be updated to the new value. */ const updateCache: ( updater: (args: { prevBlocks: Array<Block<ChannelQueryData>> | null prevCount: number }) => { newBlocks?: Array<StoreObject | Reference | null> newCount?: number } | null ) => void = useCallback( updater => { client.cache.updateQuery<ChannelQueryData, ChannelQueryVariables>( { query: channelQueryData.query, variables: channelQueryData.variables, }, data => { const prevBlocks = data?.channel?.blokks ?? null const prevCount = data?.channel?.counts?.contents ?? 0 const newValues = updater({ prevBlocks, prevCount }) if (!newValues) { return null } const result: ChannelQueryData = { ...data, channel: { ...data?.channel, counts: { ...data?.channel?.counts, contents: newValues.newCount ?? prevCount, }, blokks: newValues.newBlocks ?? prevBlocks, }, } as ChannelQueryData return result } ) }, [channelQueryData, client.cache] ) /** * A helper function to re-query for pages that have already been * queried. This is used after a mutation updates the blocks array. */ const revalidatePages = useCallback( (fromPage: number, toPage: number) => { const dir = toPage > fromPage ? 1 : -1 for (let page = fromPage; page !== toPage + dir; page += dir) { if (queriedPageNumbersRef.current.has(page)) { fetchMore({ variables: { page: page, }, }) } } }, [fetchMore] ) // ===================== // The hook's public api // ===================== /** * An array of blocks that apollo currently has cached */ const blocks: UsePaginatedBlocksApi<ChannelQueryData>['blocks'] = unsafeData?.channel?.blokks ?? [] /** * The total number of blocks/channels that a channel has. Note that this * could be different than the current length of the "blocks" array * due to not downloading all the block information from a channel */ const { data } = useQuery<ChannelContentCount, ChannelContentCountVariables>( CHANNEL_CONTENT_COUNT, { fetchPolicy: 'cache-only', variables: { id: channelId, type: type, user_id: user_id, }, } ) const contentCount: UsePaginatedBlocksApi<ChannelQueryData>['contentCount'] = data?.channel?.counts?.contents ?? 0 /** * Gets block data from a given page */ const getPage: UsePaginatedBlocksApi< ChannelQueryData >['getPage'] = useCallback( pageNumber => { queriedPageNumbersRef.current.add(pageNumber) fetchMore({ variables: { page: pageNumber, }, }) }, [fetchMore] ) /** * Returns if a given page has already been queried for or not */ const hasQueriedPage: UsePaginatedBlocksApi< ChannelQueryData >['hasQueriedPage'] = useCallback(pageNember => { return queriedPageNumbersRef.current.has(pageNember) }, []) /** * Returns the page number that a block's index would be in */ const getPageFromIndex: UsePaginatedBlocksApi< ChannelQueryData >['getPageFromIndex'] = useCallback( index => { return Math.floor(index / per) + 1 }, [per] ) /** * Removes a block from a channel ONLY on the frontend. Does not do any * actual mutation/network request. */ const removeBlock: UsePaginatedBlocksApi< ChannelQueryData >['removeBlock'] = useCallback( ({ id, type }) => { updateCache(({ prevBlocks, prevCount }) => { // Early exit if there aren't any blocks in the cache yet if (!prevBlocks) { return null } // Find the block in the blocks array const blockIndex = prevBlocks.findIndex( block => block && block.id === id && block.__typename === type ) // Early exit if the block can't be found if (blockIndex === -1) { return null } // Build the new cache data const newCount = prevCount - 1 const newBlocks = [...prevBlocks] newBlocks.splice(blockIndex, 1) // Revalidate pages between the block index that was removed and // the end of the blocks array revalidatePages( getPageFromIndex(blockIndex), getPageFromIndex(newCount - 1) ) return { newBlocks: newBlocks, newCount: newCount, } }) }, [getPageFromIndex, revalidatePages, updateCache] ) /** * Moves a block from an old index to a new index and triggers an * apollo mutation */ const moveBlock: UsePaginatedBlocksApi< ChannelQueryData >['moveBlock'] = useCallback( ({ oldIndex, newIndex }) => { updateCache(({ prevBlocks, prevCount }) => { // Early exit if there aren't any blocks in the cache yet if (!prevBlocks) { return null } // Moving to the "bottom". Convert a -1 newIndex value to a // synonymous "count - 1" value that the mutation can understand if (newIndex === -1) { newIndex = prevCount - 1 } // Get the block reference in the cache. Early exit if we can't // read it const block = prevBlocks[oldIndex] if (!block) { return null } // Get the id and typename from the cache. Early exit if we // cant read any of those values const id = block.id || undefined const typename = block.__typename || undefined if (id === undefined || typename === undefined) { return null } // Fire the mutation client.mutate< moveConnectableMutationData, moveConnectableMutationVariables >({ mutation: moveConnectableMutation, variables: { channel_id: channelId, connectable: { id: id.toString(), type: getConnectableType( typename as ChannelContentsConnectable['__typename'] ), }, insert_at: prevCount - newIndex, }, }) // Return the updated cache of the blocks array const newBlocks: typeof prevBlocks = [] for (let i = 0; i < Math.max(prevBlocks.length, newIndex + 1); i++) { newBlocks.push(prevBlocks[i] ?? null) } const [removed] = newBlocks.splice(oldIndex, 1) newBlocks.splice(newIndex, 0, removed) return { newBlocks } }) }, [channelId, client, updateCache] ) /** * A helper function to pull the most recent block data from the cache, * instead of passing the blocks data in as a dependency that will change * whenever the blocks are mutated */ const getBlocksFromCache: UsePaginatedBlocksApi< ChannelQueryData >['getBlocksFromCache'] = useCallback(() => { const cachedQuery = getQueryFromCache() return cachedQuery?.channel?.blokks ?? [] }, [getQueryFromCache]) /** * Refetch block and update cache */ const updateBlock: UsePaginatedBlocksApi< ChannelQueryData >['updateBlock'] = useCallback( async ({ id, type }) => { if (!blockquery) { return } // No need to update a channel block, just return early if (type === BaseConnectableTypeEnum.CHANNEL) { return } // Refetch the block let block: BlockQueryData['blokk'] | null = null try { const result = await client.query<BlockQueryData, BlockQueryVariables>({ query: blockquery, variables: { id: id.toString(), } as BlockQueryVariables, fetchPolicy: 'network-only', }) block = result.data.blokk } catch { // do nothing } // Early exit if we can't find a block if (!block) { return } // Update the cache to replace the previous block with the new block updateCache(({ prevBlocks }) => { // Early exit if there aren't any blocks in the cache yet if (!prevBlocks) { return null } // Early exit if we can't find a block if (!block) { return null } // Find the block in the blocks array const blockIndex = prevBlocks.findIndex(b => { return b && b.id === parseInt(id, 10) }) // Early exit if the block can't be found if (blockIndex === -1) { return null } // Build the new blocks array const newBlocks = prevBlocks.map((prevBlock, i) => i === blockIndex ? block : prevBlock ) return { newBlocks, } }) }, [blockquery, updateCache, client] ) /** * Refetch query and wipe queriedPageNumbersRef */ const addBlock: UsePaginatedBlocksApi< ChannelQueryData >['addBlock'] = useCallback(() => { queriedPageNumbersRef.current = new Set() client.refetchQueries({ include: [channelQuery], optimistic: true, }) }, [channelQuery, client]) // ============================== // Build and return the final api // ============================== const api: UsePaginatedBlocksApi<ChannelQueryData> = { blocks, contentCount, getPage, hasQueriedPage, getPageFromIndex, moveBlock, removeBlock, addBlock, updateBlock, getBlocksFromCache, loading, } return api }
the_stack
import createEditor from '../../helpers/create-editor' import $ from '../../../src/utils/dom-core' import dispatchEvent from '../../helpers/mock-dispatch-event' import { UA } from '../../../src/utils/util' import { EMPTY_P } from '../../../src/utils/const' let editor: ReturnType<typeof createEditor> let id = 1 const nodeList = [ { tag: 'div', attrs: [], children: [ { tag: 'span', attrs: [ { name: 'id', value: 'child', }, ], children: [], }, ], }, { tag: 'p', attrs: [ { name: 'id', value: 'node2', }, ], children: [], }, ] const nodeListHtml = '<div><span id="child"></span></div><p id="node2"></p>' describe('Editor Text test', () => { beforeEach(() => { editor = createEditor(document, `div${id++}`) }) test('编辑器初始化,也会初始化 Text', () => { expect(editor.txt).not.toBeUndefined() expect(editor.txt.eventHooks).not.toBeUndefined() }) test('编辑器初始化,会绑定一系列事件', () => { const eventHooks = editor.txt.eventHooks Object.keys(eventHooks).forEach(key => { // @ts-ignore expect(eventHooks[key].length).toBeGreaterThanOrEqual(0) }) }) test('编辑器初始化后,调用 txt togglePlaceholder 如果 editor txt 没有 html 内容则会展示 placeholder', () => { editor.txt.togglePlaceholder() expect(editor.$textContainerElem.find('.placeholder').elems[0]).not.toBeUndefined() expect(editor.$textContainerElem.find('.placeholder').elems[0]).toHaveStyle('display:block') }) test('编辑器初始化后,调用 txt togglePlaceholder 如果 editor txt 有 html 内容则不展示 placeholder', () => { editor.txt.html('<p>123</p>') editor.txt.togglePlaceholder() expect(editor.$textContainerElem.find('.placeholder').elems[0]).toHaveStyle('display:none') }) test('编辑器初始化后,调用 txt clear 方法,清空编辑内容,只留下 EMPTY_P', () => { editor.txt.html('<p>123</p>') editor.txt.clear() expect(editor.txt.html()).toBe('') expect(editor.$textElem.elems[0].innerHTML).toBe(EMPTY_P) }) test('编辑器初始化后,调用 txt setJSON 方法将 JSON 内容设置成 html', () => { editor.txt.setJSON(nodeList) expect(editor.txt.html()).toBe(nodeListHtml) }) test('编辑器初始化后,调用 txt getJSON 方法将 html 内容还原成JSON', () => { editor.txt.html(nodeListHtml) const res = editor.txt.getJSON() expect(res).toEqual(nodeList) }) test('编辑器初始化后,调用 txt text 方法 能获取 html text', () => { editor.txt.html('<p>12345</p>') expect(editor.txt.text()).toEqual('12345') }) test('编辑器初始化后,调用 txt text 方法 能设置 text', () => { editor.txt.text('12345') expect(editor.txt.html()).toEqual('<p>12345</p>') }) test('编辑器初始化后,调用 txt append 方法 能追加 html', () => { editor.txt.append('12345<span>1234</span>') expect(editor.txt.html()).toEqual('<p>12345<span>1234</span></p>') }) test('编辑器初始化后,编辑器区域会绑定 keyup 事件,触发保存range和激活菜单函数', () => { const saveRangeFn = jest.fn() const changeActiveFn = jest.fn() jest.spyOn(editor.selection, 'saveRange').mockImplementation(saveRangeFn) jest.spyOn(editor.menus, 'changeActive').mockImplementation(changeActiveFn) dispatchEvent(editor.$textElem, 'keyup', 'KeyBoardEvent') expect(saveRangeFn).toBeCalled() expect(changeActiveFn).toBeCalled() }) test('编辑器初始化后,编辑器区域会绑定 mouseup mousedown 事件,对range进行处理,如果range不存在,不处理', () => { const saveRangeFn = jest.fn() const getRangeFn = jest.fn(() => null) jest.spyOn(editor.selection, 'saveRange').mockImplementation(saveRangeFn) jest.spyOn(editor.selection, 'getRange').mockImplementation(getRangeFn) dispatchEvent(editor.$textElem, 'mousedown', 'MouseEvent') dispatchEvent(editor.$textElem, 'mouseup', 'MouseEvent') expect(saveRangeFn).not.toBeCalled() }) test('编辑器初始化后,编辑器区域会绑定 mouseup mousedown 事件,对存在的range进行处理', (done: jest.DoneCallback) => { const saveRangeFn = jest.fn() const getRangeFn = jest.fn(() => ({ startOffest: 10, endOffset: 14, endContainer: $('<p>12345</p>').elems[0], setStart: jest.fn(), })) jest.spyOn(editor.selection, 'saveRange').mockImplementation(saveRangeFn) // @ts-ignore jest.spyOn(editor.selection, 'getRange').mockImplementation(getRangeFn) dispatchEvent(editor.$textElem, 'mousedown', 'MouseEvent') dispatchEvent(editor.$textElem, 'mouseup', 'MouseEvent') setTimeout(() => { expect(saveRangeFn).toBeCalled() done() }, 0) }) test('编辑器初始化后,编辑器区域会绑定 click 事件,触发执行eventsHook clickEvent的函数执行', () => { const mockClickFn = jest.fn() Object.defineProperty(editor.txt.eventHooks, 'clickEvents', { value: [mockClickFn, mockClickFn], }) dispatchEvent(editor.$textElem, 'click') expect(mockClickFn.mock.calls.length).toEqual(2) }) test('编辑器初始化后,编辑器区域会绑定 enter键 keyup 事件,触发执行eventsHook enterUpEvents的函数执行', () => { const mockClickFn = jest.fn() Object.defineProperty(editor.txt.eventHooks, 'enterUpEvents', { value: [mockClickFn, mockClickFn], }) dispatchEvent(editor.$textElem, 'keyup', 'KeyBoardEvent', { keyCode: 13, }) // 模拟不是enter键的情况 dispatchEvent(editor.$textElem, 'keyup', 'KeyBoardEvent', { keyCode: 0, }) expect(mockClickFn.mock.calls.length).toEqual(2) }) test('编辑器初始化后,编辑器区域会绑定 keyup 事件,触发执行eventsHook keyupEvents的函数执行', () => { const mockClickFn = jest.fn() Object.defineProperty(editor.txt.eventHooks, 'keyupEvents', { value: [mockClickFn, mockClickFn], }) dispatchEvent(editor.$textElem, 'keyup', 'KeyBoardEvent') expect(mockClickFn.mock.calls.length).toEqual(2) }) test('编辑器初始化后,编辑器区域会绑定 delete键 keyup 事件,触发执行eventsHook deleteUpEvents的函数执行', () => { const mockClickFn = jest.fn() Object.defineProperty(editor.txt.eventHooks, 'deleteUpEvents', { value: [mockClickFn, mockClickFn], }) dispatchEvent(editor.$textElem, 'keyup', 'KeyBoardEvent', { keyCode: 8, }) // 模拟不是delete键的情况 dispatchEvent(editor.$textElem, 'keyup', 'KeyBoardEvent', { keyCode: 0, }) expect(mockClickFn.mock.calls.length).toEqual(2) }) test('编辑器初始化后,编辑器区域会绑定 delete键 keydown 事件,触发执行eventsHook deleteDownEvents的函数执行', () => { const mockClickFn = jest.fn() Object.defineProperty(editor.txt.eventHooks, 'deleteDownEvents', { value: [mockClickFn, mockClickFn], }) dispatchEvent(editor.$textElem, 'keydown', 'KeyBoardEvent', { keyCode: 8, }) // 模拟不是delete键的情况 dispatchEvent(editor.$textElem, 'keydown', 'KeyBoardEvent', { keyCode: 0, }) expect(mockClickFn.mock.calls.length).toEqual(2) }) test('编辑器初始化后,编辑器区域会绑定 paste 事件,触发执行eventsHook pasteEvents的函数执行', () => { const mockClickFn = jest.fn() Object.defineProperty(editor.txt.eventHooks, 'pasteEvents', { value: [mockClickFn, mockClickFn], }) // 模拟IE jest.spyOn(UA, 'isIE') .mockImplementationOnce(() => true) .mockImplementationOnce(() => false) dispatchEvent(editor.$textElem, 'paste', 'ClipboardEvent') expect(mockClickFn.mock.calls.length).toEqual(0) dispatchEvent(editor.$textElem, 'paste', 'ClipboardEvent') expect(mockClickFn.mock.calls.length).toEqual(2) }) test('编辑器初始化后,编辑器区域会绑定 撤销和取消 快捷键,触发执行历史撤销和重做的函数执行', () => { const restoreFn = jest.fn() const revokeFn = jest.fn() jest.spyOn(editor.history, 'restore').mockImplementation(restoreFn) jest.spyOn(editor.history, 'revoke').mockImplementation(revokeFn) Object.defineProperty(editor, 'isFocus', { value: true, }) // 重做事件 dispatchEvent(editor.$textElem, 'keydown', 'KeyBoardEvent', { keyCode: 90, shiftKey: true, ctrlKey: true, }) expect(restoreFn).toBeCalled() // 撤回事件 dispatchEvent(editor.$textElem, 'keydown', 'KeyBoardEvent', { keyCode: 90, shiftKey: false, ctrlKey: true, }) expect(revokeFn).toBeCalled() }) test('编辑器初始化后,编辑器区域会绑定 tab键 keyup 事件,触发执行eventsHook tabUpEvents的函数执行', () => { const mockClickFn = jest.fn() Object.defineProperty(editor.txt.eventHooks, 'tabUpEvents', { value: [mockClickFn, mockClickFn], }) // 模拟不是tab键的情况 dispatchEvent(editor.$textElem, 'keyup', 'KeyBoardEvent', { keyCode: 0, }) expect(mockClickFn.mock.calls.length).toEqual(0) dispatchEvent(editor.$textElem, 'keyup', 'KeyBoardEvent', { keyCode: 9, }) expect(mockClickFn.mock.calls.length).toEqual(2) }) test('编辑器初始化后,编辑器区域会绑定 tab键 keydown 事件,触发执行eventsHook tabDownEvents的函数执行', () => { const mockClickFn = jest.fn() Object.defineProperty(editor.txt.eventHooks, 'tabDownEvents', { value: [mockClickFn, mockClickFn], }) // 模拟不是tab键的情况 dispatchEvent(editor.$textElem, 'keydown', 'KeyBoardEvent', { keyCode: 0, }) expect(mockClickFn.mock.calls.length).toEqual(0) dispatchEvent(editor.$textElem, 'keydown', 'KeyBoardEvent', { keyCode: 9, }) expect(mockClickFn.mock.calls.length).toEqual(2) }) // todo 没法模拟 test('编辑器初始化后,编辑器区域会绑定 scroll 事件,触发执行eventsHook textScrollEvents的函数执行', () => { const mockClickFn = jest.fn() Object.defineProperty(editor.txt.eventHooks, 'textScrollEvents', { value: [mockClickFn, mockClickFn], }) dispatchEvent(editor.$textElem, 'scroll', 'Event') expect(mockClickFn.mock.calls.length).toEqual(0) }) // todo 没法模拟 test('编辑器初始化后,编辑器区域会禁用 dcument dragleave、drop、dragenter、dragover 事件', () => { const preventDefaultFn = jest.fn() dispatchEvent(editor.$textElem, 'dragleave', 'MouseEvent', { preventDefault: preventDefaultFn, }) dispatchEvent(editor.$textElem, 'drop', 'MouseEvent', { preventDefault: preventDefaultFn, }) dispatchEvent(editor.$textElem, 'dragenter', 'MouseEvent', { preventDefault: preventDefaultFn, }) dispatchEvent(editor.$textElem, 'dragover', 'MouseEvent', { preventDefault: preventDefaultFn, }) expect(preventDefaultFn.mock.calls.length).toEqual(0) }) test('编辑器初始化后,编辑器区域 监听 链接点击事件, 触发执行eventsHook linkClickEvents的函数执行', () => { const mockClickFn = jest.fn() Object.defineProperty(editor.txt.eventHooks, 'linkClickEvents', { value: [mockClickFn, mockClickFn], }) const a = $('<a href="http://www.wangeditor.com">wangeditor</a>') editor.$textElem.append(a) dispatchEvent(a, 'click', 'Event', { target: a.elems[0], }) expect(mockClickFn.mock.calls.length).toEqual(2) // 模拟事件代理的情况 const target = $('<li></li>') const link = $('<a href="http://www.wangeditor.com">wangeditor</a>').append(target) editor.$textElem.append(link) dispatchEvent(target, 'click', 'Event', { target, }) expect(mockClickFn.mock.calls.length).toEqual(4) }) test('编辑器初始化后,编辑器区域 监听 img点击事件, 触发执行eventsHook imgClickEvents的函数执行', () => { const mockClickFn = jest.fn() Object.defineProperty(editor.txt.eventHooks, 'imgClickEvents', { value: [mockClickFn, mockClickFn], }) const img = $('<img src="http://www.wangeditor.com/imgs/ali-pay.jpeg" />') editor.$textElem.append(img) dispatchEvent(img, 'click', 'Event', { target: img.elems[0], }) expect(mockClickFn.mock.calls.length).toEqual(2) // 模拟表情点击的情况,不执行图片钩子函数 const emotiomImg = $( '<img class="eleImg" data-emoji="emoji" src="http://www.wangeditor.com/imgs/ali-pay.jpeg" />' ) editor.$textElem.append(emotiomImg) dispatchEvent(emotiomImg, 'click', 'Event', { target: emotiomImg.elems[0], }) expect(mockClickFn.mock.calls.length).toEqual(2) }) test('编辑器初始化后,编辑器区域 监听 code区域点击事件, 触发执行eventsHook codeClickEvents的函数执行', () => { const mockClickFn = jest.fn() Object.defineProperty(editor.txt.eventHooks, 'codeClickEvents', { value: [mockClickFn, mockClickFn], }) const code = $('<pre>123</pre>') editor.$textElem.append(code) dispatchEvent(code, 'click', 'Event', { target: code.elems[0], }) expect(mockClickFn.mock.calls.length).toEqual(2) // 模拟点击pre里面的元素 const codeWrapper = $('<pre>123</pre>') const target = $('<span>123</span>') codeWrapper.append(target) editor.$textElem.append(codeWrapper) dispatchEvent(target, 'click', 'Event', { target: target.elems[0], }) editor.txt.html('') // 模拟不是点击pre区域情况 dispatchEvent(editor.$textElem, 'click', 'Event', { target: editor.$textElem.elems[0], }) expect(mockClickFn.mock.calls.length).toEqual(4) }) test('编辑器初始化后,编辑器区域 监听 hr标签点击事件, 触发执行eventsHook splitLineEvents的函数执行', () => { const mockClickFn = jest.fn() Object.defineProperty(editor.txt.eventHooks, 'splitLineEvents', { value: [mockClickFn, mockClickFn], }) const hr = $('<hr />') editor.$textElem.append(hr) dispatchEvent(hr, 'click', 'Event', { target: hr.elems[0], }) expect(mockClickFn.mock.calls.length).toEqual(2) // 模拟点击不是hr情况 const target = $('<span>123</span>') editor.$textElem.append(target) dispatchEvent(target, 'click', 'Event', { target: target.elems[0], }) expect(mockClickFn.mock.calls.length).toEqual(2) }) test('编辑器初始化后,编辑区域容器添加监听点击事件, 点击的元素是图片拖拽调整大小的 bar, 触发执行eventsHook imgDragBarMouseDownEvents的函数执行', () => { const mockClickFn = jest.fn() Object.defineProperty(editor.txt.eventHooks, 'imgDragBarMouseDownEvents', { value: [mockClickFn, mockClickFn], }) const target = $('<div class="w-e-img-drag-rb"></div>') editor.$textContainerElem.append(target) dispatchEvent(target, 'mousedown', 'KeyBoardEvent') expect(mockClickFn.mock.calls.length).toEqual(2) }) test('编辑器初始化后,编辑器区域监听表格区域点击事件, 触发执行eventsHook tableClickEvents的函数执行', () => { const mockClickFn = jest.fn() Object.defineProperty(editor.txt.eventHooks, 'tableClickEvents', { value: [mockClickFn, mockClickFn], }) const table = $('<table><tr><td>123</td></tr></table>') editor.$textElem.append(table) dispatchEvent($(table.childNodes()), 'click') expect(mockClickFn.mock.calls.length).toEqual(2) // 模拟点击非表格区域 const target = $('<span>123</span>') editor.$textElem.append(target) dispatchEvent(target, 'click', 'Event') expect(mockClickFn.mock.calls.length).toEqual(2) }) test('编辑器初始化后,编辑器区域监听 ednter keydown 事件, 触发执行eventsHook enterDownEvents的函数执行', () => { const mockClickFn = jest.fn() Object.defineProperty(editor.txt.eventHooks, 'enterDownEvents', { value: [mockClickFn, mockClickFn], }) dispatchEvent(editor.$textElem, 'keydown', 'KeyBoardEvent', { keyCode: 13, }) // 模拟非enter键按下 dispatchEvent(editor.$textElem, 'keydown', 'KeyBoardEvent', { keyCode: 0, }) expect(mockClickFn.mock.calls.length).toEqual(2) }) })
the_stack
import * as assert from 'assert'; import { timeout } from 'vs/base/common/async'; import { bufferedStreamToBuffer, bufferToReadable, bufferToStream, decodeBase64, encodeBase64, newWriteableBufferStream, readableToBuffer, streamToBuffer, VSBuffer } from 'vs/base/common/buffer'; import { peekStream } from 'vs/base/common/stream'; suite('Buffer', () => { test('issue #71993 - VSBuffer#toString returns numbers', () => { const data = new Uint8Array([1, 2, 3, 'h'.charCodeAt(0), 'i'.charCodeAt(0), 4, 5]).buffer; const buffer = VSBuffer.wrap(new Uint8Array(data, 3, 2)); assert.deepStrictEqual(buffer.toString(), 'hi'); }); test('bufferToReadable / readableToBuffer', () => { const content = 'Hello World'; const readable = bufferToReadable(VSBuffer.fromString(content)); assert.strictEqual(readableToBuffer(readable).toString(), content); }); test('bufferToStream / streamToBuffer', async () => { const content = 'Hello World'; const stream = bufferToStream(VSBuffer.fromString(content)); assert.strictEqual((await streamToBuffer(stream)).toString(), content); }); test('bufferedStreamToBuffer', async () => { const content = 'Hello World'; const stream = await peekStream(bufferToStream(VSBuffer.fromString(content)), 1); assert.strictEqual((await bufferedStreamToBuffer(stream)).toString(), content); }); test('bufferWriteableStream - basics (no error)', async () => { const stream = newWriteableBufferStream(); let chunks: VSBuffer[] = []; stream.on('data', data => { chunks.push(data); }); let ended = false; stream.on('end', () => { ended = true; }); let errors: Error[] = []; stream.on('error', error => { errors.push(error); }); await timeout(0); stream.write(VSBuffer.fromString('Hello')); await timeout(0); stream.end(VSBuffer.fromString('World')); assert.strictEqual(chunks.length, 2); assert.strictEqual(chunks[0].toString(), 'Hello'); assert.strictEqual(chunks[1].toString(), 'World'); assert.strictEqual(ended, true); assert.strictEqual(errors.length, 0); }); test('bufferWriteableStream - basics (error)', async () => { const stream = newWriteableBufferStream(); let chunks: VSBuffer[] = []; stream.on('data', data => { chunks.push(data); }); let ended = false; stream.on('end', () => { ended = true; }); let errors: Error[] = []; stream.on('error', error => { errors.push(error); }); await timeout(0); stream.write(VSBuffer.fromString('Hello')); await timeout(0); stream.error(new Error()); stream.end(); assert.strictEqual(chunks.length, 1); assert.strictEqual(chunks[0].toString(), 'Hello'); assert.strictEqual(ended, true); assert.strictEqual(errors.length, 1); }); test('bufferWriteableStream - buffers data when no listener', async () => { const stream = newWriteableBufferStream(); await timeout(0); stream.write(VSBuffer.fromString('Hello')); await timeout(0); stream.end(VSBuffer.fromString('World')); let chunks: VSBuffer[] = []; stream.on('data', data => { chunks.push(data); }); let ended = false; stream.on('end', () => { ended = true; }); let errors: Error[] = []; stream.on('error', error => { errors.push(error); }); assert.strictEqual(chunks.length, 1); assert.strictEqual(chunks[0].toString(), 'HelloWorld'); assert.strictEqual(ended, true); assert.strictEqual(errors.length, 0); }); test('bufferWriteableStream - buffers errors when no listener', async () => { const stream = newWriteableBufferStream(); await timeout(0); stream.write(VSBuffer.fromString('Hello')); await timeout(0); stream.error(new Error()); let chunks: VSBuffer[] = []; stream.on('data', data => { chunks.push(data); }); let errors: Error[] = []; stream.on('error', error => { errors.push(error); }); let ended = false; stream.on('end', () => { ended = true; }); stream.end(); assert.strictEqual(chunks.length, 1); assert.strictEqual(chunks[0].toString(), 'Hello'); assert.strictEqual(ended, true); assert.strictEqual(errors.length, 1); }); test('bufferWriteableStream - buffers end when no listener', async () => { const stream = newWriteableBufferStream(); await timeout(0); stream.write(VSBuffer.fromString('Hello')); await timeout(0); stream.end(VSBuffer.fromString('World')); let ended = false; stream.on('end', () => { ended = true; }); let chunks: VSBuffer[] = []; stream.on('data', data => { chunks.push(data); }); let errors: Error[] = []; stream.on('error', error => { errors.push(error); }); assert.strictEqual(chunks.length, 1); assert.strictEqual(chunks[0].toString(), 'HelloWorld'); assert.strictEqual(ended, true); assert.strictEqual(errors.length, 0); }); test('bufferWriteableStream - nothing happens after end()', async () => { const stream = newWriteableBufferStream(); let chunks: VSBuffer[] = []; stream.on('data', data => { chunks.push(data); }); await timeout(0); stream.write(VSBuffer.fromString('Hello')); await timeout(0); stream.end(VSBuffer.fromString('World')); let dataCalledAfterEnd = false; stream.on('data', data => { dataCalledAfterEnd = true; }); let errorCalledAfterEnd = false; stream.on('error', error => { errorCalledAfterEnd = true; }); let endCalledAfterEnd = false; stream.on('end', () => { endCalledAfterEnd = true; }); await timeout(0); stream.write(VSBuffer.fromString('Hello')); await timeout(0); stream.error(new Error()); await timeout(0); stream.end(VSBuffer.fromString('World')); assert.strictEqual(dataCalledAfterEnd, false); assert.strictEqual(errorCalledAfterEnd, false); assert.strictEqual(endCalledAfterEnd, false); assert.strictEqual(chunks.length, 2); assert.strictEqual(chunks[0].toString(), 'Hello'); assert.strictEqual(chunks[1].toString(), 'World'); }); test('bufferWriteableStream - pause/resume (simple)', async () => { const stream = newWriteableBufferStream(); let chunks: VSBuffer[] = []; stream.on('data', data => { chunks.push(data); }); let ended = false; stream.on('end', () => { ended = true; }); let errors: Error[] = []; stream.on('error', error => { errors.push(error); }); stream.pause(); await timeout(0); stream.write(VSBuffer.fromString('Hello')); await timeout(0); stream.end(VSBuffer.fromString('World')); assert.strictEqual(chunks.length, 0); assert.strictEqual(errors.length, 0); assert.strictEqual(ended, false); stream.resume(); assert.strictEqual(chunks.length, 1); assert.strictEqual(chunks[0].toString(), 'HelloWorld'); assert.strictEqual(ended, true); assert.strictEqual(errors.length, 0); }); test('bufferWriteableStream - pause/resume (pause after first write)', async () => { const stream = newWriteableBufferStream(); let chunks: VSBuffer[] = []; stream.on('data', data => { chunks.push(data); }); let ended = false; stream.on('end', () => { ended = true; }); let errors: Error[] = []; stream.on('error', error => { errors.push(error); }); await timeout(0); stream.write(VSBuffer.fromString('Hello')); stream.pause(); await timeout(0); stream.end(VSBuffer.fromString('World')); assert.strictEqual(chunks.length, 1); assert.strictEqual(chunks[0].toString(), 'Hello'); assert.strictEqual(errors.length, 0); assert.strictEqual(ended, false); stream.resume(); assert.strictEqual(chunks.length, 2); assert.strictEqual(chunks[0].toString(), 'Hello'); assert.strictEqual(chunks[1].toString(), 'World'); assert.strictEqual(ended, true); assert.strictEqual(errors.length, 0); }); test('bufferWriteableStream - pause/resume (error)', async () => { const stream = newWriteableBufferStream(); let chunks: VSBuffer[] = []; stream.on('data', data => { chunks.push(data); }); let ended = false; stream.on('end', () => { ended = true; }); let errors: Error[] = []; stream.on('error', error => { errors.push(error); }); stream.pause(); await timeout(0); stream.write(VSBuffer.fromString('Hello')); await timeout(0); stream.error(new Error()); stream.end(); assert.strictEqual(chunks.length, 0); assert.strictEqual(ended, false); assert.strictEqual(errors.length, 0); stream.resume(); assert.strictEqual(chunks.length, 1); assert.strictEqual(chunks[0].toString(), 'Hello'); assert.strictEqual(ended, true); assert.strictEqual(errors.length, 1); }); test('bufferWriteableStream - destroy', async () => { const stream = newWriteableBufferStream(); let chunks: VSBuffer[] = []; stream.on('data', data => { chunks.push(data); }); let ended = false; stream.on('end', () => { ended = true; }); let errors: Error[] = []; stream.on('error', error => { errors.push(error); }); stream.destroy(); await timeout(0); stream.write(VSBuffer.fromString('Hello')); await timeout(0); stream.end(VSBuffer.fromString('World')); assert.strictEqual(chunks.length, 0); assert.strictEqual(ended, false); assert.strictEqual(errors.length, 0); }); test('Performance issue with VSBuffer#slice #76076', function () { // TODO@alexdima this test seems to fail in web (https://github.com/microsoft/vscode/issues/114042) // Buffer#slice creates a view if (typeof Buffer !== 'undefined') { const buff = Buffer.from([10, 20, 30, 40]); const b2 = buff.slice(1, 3); assert.strictEqual(buff[1], 20); assert.strictEqual(b2[0], 20); buff[1] = 17; // modify buff AND b2 assert.strictEqual(buff[1], 17); assert.strictEqual(b2[0], 17); } // TypedArray#slice creates a copy { const unit = new Uint8Array([10, 20, 30, 40]); const u2 = unit.slice(1, 3); assert.strictEqual(unit[1], 20); assert.strictEqual(u2[0], 20); unit[1] = 17; // modify unit, NOT b2 assert.strictEqual(unit[1], 17); assert.strictEqual(u2[0], 20); } // TypedArray#subarray creates a view { const unit = new Uint8Array([10, 20, 30, 40]); const u2 = unit.subarray(1, 3); assert.strictEqual(unit[1], 20); assert.strictEqual(u2[0], 20); unit[1] = 17; // modify unit AND b2 assert.strictEqual(unit[1], 17); assert.strictEqual(u2[0], 17); } }); suite('base64', () => { /* Generated with: const crypto = require('crypto'); for (let i = 0; i < 16; i++) { const buf = crypto.randomBytes(i); console.log(`[new Uint8Array([${Array.from(buf).join(', ')}]), '${buf.toString('base64')}'],`) } */ const testCases: [Uint8Array, string][] = [ [new Uint8Array([]), ''], [new Uint8Array([56]), 'OA=='], [new Uint8Array([209, 4]), '0QQ='], [new Uint8Array([19, 57, 119]), 'Ezl3'], [new Uint8Array([199, 237, 207, 112]), 'x+3PcA=='], [new Uint8Array([59, 193, 173, 26, 242]), 'O8GtGvI='], [new Uint8Array([81, 226, 95, 231, 116, 126]), 'UeJf53R+'], [new Uint8Array([11, 164, 253, 85, 8, 6, 56]), 'C6T9VQgGOA=='], [new Uint8Array([164, 16, 88, 88, 224, 173, 144, 114]), 'pBBYWOCtkHI='], [new Uint8Array([0, 196, 99, 12, 21, 229, 78, 101, 13]), 'AMRjDBXlTmUN'], [new Uint8Array([167, 114, 225, 116, 226, 83, 51, 48, 88, 114]), 'p3LhdOJTMzBYcg=='], [new Uint8Array([75, 33, 118, 10, 77, 5, 168, 194, 59, 47, 59]), 'SyF2Ck0FqMI7Lzs='], [new Uint8Array([203, 182, 165, 51, 208, 27, 123, 223, 112, 198, 127, 147]), 'y7alM9Abe99wxn+T'], [new Uint8Array([154, 93, 222, 41, 117, 234, 250, 85, 95, 144, 16, 94, 18]), 'ml3eKXXq+lVfkBBeEg=='], [new Uint8Array([246, 186, 88, 105, 192, 57, 25, 168, 183, 164, 103, 162, 243, 56]), '9rpYacA5Gai3pGei8zg='], [new Uint8Array([149, 240, 155, 96, 30, 55, 162, 172, 191, 187, 33, 124, 169, 183, 254]), 'lfCbYB43oqy/uyF8qbf+'], ]; test('encodes', () => { for (const [bytes, expected] of testCases) { assert.strictEqual(encodeBase64(VSBuffer.wrap(bytes)), expected); } }); test('decodes', () => { for (const [expected, encoded] of testCases) { assert.deepStrictEqual(new Uint8Array(decodeBase64(encoded).buffer), expected); } }); test('throws error on invalid encoding', () => { assert.throws(() => decodeBase64('invalid!')); }); }); });
the_stack
import React, {createRef, RefObject, useEffect} from 'react'; import PropTypes from 'prop-types'; /* Components */ import {ItemComponent} from './itemComponent'; /* Context */ import {GridProvider} from '../contexts'; /* Controllers */ import { ChildrenController, FiberController, ItemAddController, ItemRemoveController, LayoutController, } from '../controllers'; /* Utils */ import {invariant} from '../invariant'; import {fillGridElement, fillGrid} from '../utils/fillers'; import {useReference, useMemoized} from '../utils/hooks'; import {addDecoration, getDecoration, isDecorated} from '../utils/decorators'; import { addItems, filterItems, getGridClass, getItemClasses, hideItems, removeItems, showItems, sortItems, } from '../utils/grid'; /* Interfaces */ import type {GridComponentProps, DecoratedItem} from '../interfaces'; // Grid component. export function GridComponent({ children, gridProps, grid, filter, sort, sortOptions, addOptions, propsToData, onSend, onDragStart, onDragEnd, onFilter, onSort, onMount, onUnmount, forceSync, dragFixed, dragEnabled, instantLayout, }: GridComponentProps) { /* ------------------ */ /* ----- STORES ----- */ /* ------------------ */ // Store references of objects // generated in previous renders. const store = useMemoized<{ // The grid ref. gridRef: RefObject<HTMLDivElement>; // The grid className. gridClass: string; // The items classNames. itemClasses: string[]; // Controller that manages the children. childrenController: ChildrenController; // Controller that manages the fibers. fiberController: FiberController; // Controller that manages the items to add. itemAddController: ItemAddController; // Controller that manages the items to remove. itemRemoveController: ItemRemoveController; // Controller that manages the items layout. layoutController: LayoutController; // Keep a reference of the onUnmount function. onUnmount?: GridComponentProps['onUnmount']; // Keep a reference of the onDragStart function. onDragStart?: GridComponentProps['onDragStart']; // Keep a reference of the onDragEnd function. onDragEnd?: GridComponentProps['onDragEnd']; // Keep a reference of the onFilter function. onFilter?: GridComponentProps['onFilter']; // Keep a reference of the onSort function. onSort?: GridComponentProps['onSort']; // Keep a reference of the onSend function. onSend?: GridComponentProps['onSend']; }>(() => ({ // Grid and items data. gridRef: /* */ createRef(), gridClass: /* */ getGridClass(grid), itemClasses: /* */ getItemClasses(grid), // Controllers. childrenController: /* */ new ChildrenController(), fiberController: /* */ new FiberController(), itemAddController: /* */ new ItemAddController(), itemRemoveController: /* */ new ItemRemoveController(), layoutController: /* */ new LayoutController(), // Events. onUnmount, onDragStart, onDragEnd, onFilter, onSort, onSend, })); // Store references of objects // that are used inside useEffect. // The references are flushed on each new render. const vars: { /** The positions of the new items. */ indicesToAdd: number[]; /** The DOM elements of the new items. */ addedDOMItems: HTMLElement[]; /** The items instances to remove. */ itemsToRemove: DecoratedItem[]; /** The items instances to refresh. */ itemsToRefresh: DecoratedItem[]; /** The items instances to show. */ itemsToShow: DecoratedItem[]; /** The items instances to hide. */ itemsToHide: DecoratedItem[]; /** If an item has been added. */ hasAdded: boolean; /** If an item has been removed. */ hasRemoved: boolean; /** If the grid has been filtered. */ hasFiltered: boolean; /** If the grid has been sorted. */ hasSorted: boolean; /** If an item has been refreshed. */ hasRefreshed: boolean; /** If an item has been shown. */ hasShown: boolean; /** If an item has been hiiden. */ hasHidden: boolean; } = { // Items data. indicesToAdd: /* */ [], addedDOMItems: /* */ [], itemsToRemove: /* */ [], itemsToRefresh: /* */ [], itemsToShow: /* */ [], itemsToHide: /* */ [], // Items flags. hasAdded: /* */ false, hasRemoved: /* */ false, hasFiltered: /* */ false, hasSorted: /* */ false, hasRefreshed: /* */ false, hasShown: /* */ false, hasHidden: /* */ false, }; /* ----------------- */ /* ----- MOUNT ----- */ /* ----------------- */ // Initialize the grid on mount. useEffect(() => { /* ------------------ */ /* ----- EVENTS ----- */ /* ------------------ */ // Add all the event handlers. grid // "Send" and "receive" events. .on('beforeSend', ({item, fromGrid, fromIndex}) => { if (!getDecoration(item).sentPayload) { // Generate the sentPayload. const sentPayload = { fromChildrenController: store.childrenController, fromFiberController: store.fiberController, fromGrid, fromIndex, }; // Add the decoration. addDecoration(item, {sentPayload}); } }) .on('receive', ({item, toGrid, toIndex}) => { // Controllers. const toChildrenController = store.childrenController; const toFiberController = store.fiberController; // If the method is activated by user interaction (the item is being dragged) // the synchronization will be performed during the "dragEnd" event. // If the method is called via Muuri's instance (the item is not being dragged) // the synchronization takes place here, but the onSend callback is not fired. if (item.isDragging()) { // Generate the receivedPayload. const receivedPayload = { toChildrenController, toFiberController, toGrid, toIndex, }; // Add the decoration. addDecoration(item, {receivedPayload}); } else { // Payloads data. const sentPayload = getDecoration(item).sentPayload; // The payload must have been created in the send method. invariant(sentPayload !== null && typeof sentPayload === 'object'); // Controllers. const {fromChildrenController, fromFiberController} = sentPayload; // Remove the payload. addDecoration(item, {sentPayload: null}); // Remove the item instances from the old GridComponent. const itemFiber = fromFiberController.remove(item.getKey()); const itemComponent = fromChildrenController.remove(itemFiber.index); // Add the item instances to the new GridComponent. toFiberController.append(itemFiber); toChildrenController.append(itemComponent); } // Emit the "send" event. getDecoration(item).eventController.emitEvent('send', grid); }) // Drag events. .on('dragInit', (item, event) => { // The childrenController must change the positions of // the newly added components if any items are being // dragged to add the safely. store.childrenController.incrementDragCounter(); // Emit the "drag" event. // This event is used instead of "dragStart" to allow the // reRender of the component when the item is not inside // the dragContainer, this makes it possible to change // the style of the element safely (e.g. using relative dimensions). getDecoration(item).eventController.emitEvent('drag', true); // "onDragStart" Callback. if (store.onDragStart) store.onDragStart(item, event); }) .on('dragEnd', (item) => { // Payloads. const sentPayload = getDecoration(item).sentPayload; const receivedPayload = getDecoration(item).receivedPayload; // If an item was sent during the drag the // GridComponents are synchronized. if (sentPayload && receivedPayload) { // SentPayload data. const { fromChildrenController, fromFiberController, fromGrid, fromIndex, } = sentPayload; // ReceivedPayload data. const { toChildrenController, toFiberController, toGrid, toIndex, } = receivedPayload; // Reset the payloads. addDecoration(item, {sentPayload: null, receivedPayload: null}); // Check if the item has been sended. if (fromGrid !== toGrid) { // "onSend" will be called with the receive event. invariant( typeof store.onSend === 'function', 'An item cannot be sent to another MuuriComponent if the ' + "'onSend' property has not been passed to the MuuriComponent." ); // Remove the item instances from the old GridComponent. const itemFiber = fromFiberController.remove(item.getKey()); const itemComponent = fromChildrenController.remove( itemFiber.index ); // Add the item instances to the new GridComponent. toFiberController.append(itemFiber); toChildrenController.append(itemComponent); // "onSend" callback. // DragEnd is called in the grid where // the drag start, so onSend. store.onSend({ // The key the user has set. key: getDecoration(item).key, // From. fromGrid, fromIndex, fromId: getDecoration(fromGrid).id, fromGroupIds: getDecoration(fromGrid).groupIds, // To. toGrid, toIndex, toId: getDecoration(toGrid).id, toGroupIds: getDecoration(toGrid).groupIds, }); } } }) .on('dragReleaseEnd', (item) => { // The childrenController must change the positions of // the newly added components if any items are being // dragged to add the safely. store.childrenController.decrementDragCounter(); // Emit the event. // This event is used instead of "dragEnd" to allow the // reRender of the component when the item is not inside // the dragContainer, this makes it possible to change // the style of the element safely (e.g. using relative dimensions). getDecoration(item).eventController.emitEvent('drag', false); // Call the event. if (store.onDragEnd) store.onDragEnd(item); }) // Show and hide events. .on('showStart', (items) => { // The items could be shown before they are decorated. if (!isDecorated(items[0])) return; // Emit the event. items.forEach((item) => { const eventController = getDecoration(item).eventController; // The event is triggered also for items that have not // changed their "visibility" state. // This check is done to avoid useless re-rendering. if (eventController.getPayload('show') !== true) { eventController.emitEvent('show', true); } }); }) .on('hideEnd', (items) => { // Emit the event. items.forEach((item) => { const eventController = getDecoration(item).eventController; // The event is triggered also for items that have not // changed their "visibility" state. // This check is done to avoid useless re-rendering. if (eventController.getPayload('show') !== false) { eventController.emitEvent('show', false); } }); }) // Filter and sort events. .on('filter', (shownItems, hiddenItems) => { if (store.onFilter) store.onFilter(shownItems, hiddenItems); }) .on('sort', (currentOrder, previousOrder) => { if (store.onSort) store.onSort(currentOrder, previousOrder); }); // Fix the dimensions of the items when they are dragged. if (dragFixed) { grid .on('dragInit', (item) => { // Let's set fixed widht/height to the dragged item // so that it does not stretch unwillingly when // it's appended to the document body for the // duration of the drag. const element = item.getElement(); // The element must exist. invariant(element !== undefined); // Get the computed dimensions. const {width, height, paddingTop} = getComputedStyle(element); // Save the previous style in case it was setted. addDecoration(item, { dragWidth: element.style.width, dragHeight: element.style.height, dragPaddingTop: element.style.paddingTop, }); // Set the new style. element.style.width = width; element.style.height = height; element.style.paddingTop = paddingTop; }) .on('dragReleaseEnd', (item) => { // Let's remove the fixed width/height from the // dragged item now that it is back in a grid // column and can freely adjust to it's // surroundings. const element = item.getElement(); // The element must exist. invariant(element !== undefined); // Get the old style. const {dragWidth, dragHeight, dragPaddingTop} = getDecoration(item); // Restore the previous style in case it was setted. element.style.width = dragWidth; element.style.height = dragHeight; element.style.paddingTop = dragPaddingTop; }); } /* ---------------- */ /* ----- GRID ----- */ /* -----------------*/ // Check . invariant(store.gridRef.current !== null); // Work with the grid. // @ts-ignore grid._element = store.gridRef.current; fillGridElement(store.gridRef.current, store.gridClass); fillGrid(grid); // "onMount" Callback. if (onMount) onMount(grid); // Delete the instance from the global map. return () => { // Destroy the controllers. store.childrenController.destroy(); store.fiberController.destroy(); store.itemRemoveController.destroy(); store.itemAddController.destroy(); store.layoutController.destroy(); }; }, []); // eslint-disable-line /* ---------------- */ /* ----- INIT ----- */ /* -----------------*/ // Init the controllers. store.childrenController.useInit(children); store.fiberController.useInit(store.gridRef); store.itemRemoveController.useInit(); store.itemAddController.useInit(); store.layoutController.useInit(); // IsChanged flags. const isFilterChanged = useReference([filter]); const isSortChanged = useReference([sort, sortOptions]); // Get items to add/remove. useEffect(() => { // Set drag enabled option. addDecoration(grid, {dragEnabled}); // Set the items data. vars.indicesToAdd = store.childrenController.getIndicesToAdd(); vars.addedDOMItems = store.fiberController.getStateNodes(vars.indicesToAdd); vars.itemsToRemove = store.itemRemoveController.getItemsToRemove(); vars.itemsToRefresh = store.layoutController.getItemsToRefresh(); vars.itemsToShow = store.layoutController.getItemsToShow(); vars.itemsToHide = store.layoutController.getItemsToHide(); // This will remove lot of the implementation // problems for the user. store.onUnmount = onUnmount; store.onDragStart = onDragStart; store.onDragEnd = onDragEnd; store.onFilter = onFilter; store.onSort = onSort; store.onSend = onSend; }); /* ------------------- */ /* ----- ACTIONS ----- */ /* ------------------- */ useEffect(() => { /* ---------------------- */ /* ---- ADD & REMOVE ---- */ /* ---------------------- */ // Remove items. if (vars.itemsToRemove.length) { removeItems(grid, vars.itemsToRemove); // Set the flag. vars.hasRemoved = true; } // Add items after the old ones are removed // to add them in the right positions. if (vars.indicesToAdd.length) { addItems(grid, vars.addedDOMItems, vars.indicesToAdd, addOptions, filter); // New Items. const addedItems = grid.getItems(vars.indicesToAdd); // Emit the new items to the itemComponents. store.itemAddController.emit(addedItems); // Set the flag. vars.hasAdded = true; } /* ------------------------- */ /* ----- SORT & FILTER ----- */ /* ------------------------- */ // Filter items. if (filter && (isFilterChanged || vars.hasAdded || forceSync)) { filterItems(grid, filter); // Set the flag. vars.hasFiltered = true; } // Sort items. if (sort && (isSortChanged || vars.hasAdded || forceSync)) { sortItems(grid, sort, sortOptions); // Set the flag. vars.hasSorted = true; } /* ----------------------- */ /* ----- SHOW & HIDE ----- */ /* ----------------------- */ // Filter has priority on the items visibility. if (!filter && vars.itemsToShow.length) { showItems(grid, vars.itemsToShow); // Set the flag. vars.hasShown = true; } // Filter has priority on the items visibility. if (!filter && vars.itemsToHide.length) { hideItems(grid, vars.itemsToHide); // Set the flag. vars.hasHidden = true; } /* ------------------- */ /* ----- REFRESH ----- */ /* ------------------- */ // Items with dimensions to refresh. if (vars.itemsToRefresh.length) { grid.refreshItems(vars.itemsToRefresh); // Set the flag. vars.hasRefreshed = true; } /* ------------------ */ /* ----- LAYOUT ----- */ /* ------------------ */ // Layout is calculated only in the end. // Check the previous flags. if ( vars.hasAdded || vars.hasRemoved || vars.hasSorted || vars.hasFiltered || vars.hasRefreshed || vars.hasShown || vars.hasHidden ) { grid.layout(instantLayout); } }); /* ------------------ */ /* ----- RENDER ----- */ /* ------------------ */ // Provided value doesn't change the reference. const value = useMemoized(() => ({ layoutController: store.layoutController, grid, })); // render. return ( <GridProvider value={value}> <div {...gridProps} ref={store.gridRef} {...store.fiberController.getFlagProp()}> {/** The children controller handle some memoization */} {store.childrenController.render((child, key) => ( <ItemComponent key={key} itemKey={key} grid={grid} propsToData={propsToData} itemClasses={store.itemClasses} itemAddController={store.itemAddController} itemRemoveController={store.itemRemoveController}> {child} </ItemComponent> ))} </div> </GridProvider> ); } // Proptypes. GridComponent.propTypes = { grid: PropTypes.object.isRequired, gridProps: PropTypes.object, filter: PropTypes.oneOfType([PropTypes.string, PropTypes.func]), sort: PropTypes.oneOfType([ PropTypes.string, PropTypes.func, PropTypes.arrayOf(PropTypes.string), ]), sortOptions: PropTypes.exact({ descending: PropTypes.bool, }), addOptions: PropTypes.exact({ show: PropTypes.bool, }), onSend: PropTypes.func, onDragStart: PropTypes.func, onDragEnd: PropTypes.func, onFilter: PropTypes.func, onSort: PropTypes.func, onMount: PropTypes.func, onUnmount: PropTypes.func, forceSync: PropTypes.bool, dragFixed: PropTypes.bool, dragEnabled: PropTypes.bool, instantLayout: PropTypes.bool, }; // Default props. GridComponent.defaultProps = { gridProps: {}, addOptions: {show: true}, sortOptions: {descending: false}, forceSync: false, dragFixed: false, dragEnabled: false, instantLayout: false, }; // Display name. GridComponent.displayName = 'GridComponent';
the_stack
import { PagedAsyncIterableIterator } from "@azure/core-paging"; import { ContentKeyPolicies } from "../operationsInterfaces"; import * as coreClient from "@azure/core-client"; import * as Mappers from "../models/mappers"; import * as Parameters from "../models/parameters"; import { AzureMediaServices } from "../azureMediaServices"; import { ContentKeyPolicy, ContentKeyPoliciesListNextOptionalParams, ContentKeyPoliciesListOptionalParams, ContentKeyPoliciesListResponse, ContentKeyPoliciesGetOptionalParams, ContentKeyPoliciesGetResponse, ContentKeyPoliciesCreateOrUpdateOptionalParams, ContentKeyPoliciesCreateOrUpdateResponse, ContentKeyPoliciesDeleteOptionalParams, ContentKeyPoliciesUpdateOptionalParams, ContentKeyPoliciesUpdateResponse, ContentKeyPoliciesGetPolicyPropertiesWithSecretsOptionalParams, ContentKeyPoliciesGetPolicyPropertiesWithSecretsResponse, ContentKeyPoliciesListNextResponse } from "../models"; /// <reference lib="esnext.asynciterable" /> /** Class containing ContentKeyPolicies operations. */ export class ContentKeyPoliciesImpl implements ContentKeyPolicies { private readonly client: AzureMediaServices; /** * Initialize a new instance of the class ContentKeyPolicies class. * @param client Reference to the service client */ constructor(client: AzureMediaServices) { this.client = client; } /** * Lists the Content Key Policies in the account * @param resourceGroupName The name of the resource group within the Azure subscription. * @param accountName The Media Services account name. * @param options The options parameters. */ public list( resourceGroupName: string, accountName: string, options?: ContentKeyPoliciesListOptionalParams ): PagedAsyncIterableIterator<ContentKeyPolicy> { const iter = this.listPagingAll(resourceGroupName, accountName, options); return { next() { return iter.next(); }, [Symbol.asyncIterator]() { return this; }, byPage: () => { return this.listPagingPage(resourceGroupName, accountName, options); } }; } private async *listPagingPage( resourceGroupName: string, accountName: string, options?: ContentKeyPoliciesListOptionalParams ): AsyncIterableIterator<ContentKeyPolicy[]> { let result = await this._list(resourceGroupName, accountName, options); yield result.value || []; let continuationToken = result.odataNextLink; while (continuationToken) { result = await this._listNext( resourceGroupName, accountName, continuationToken, options ); continuationToken = result.odataNextLink; yield result.value || []; } } private async *listPagingAll( resourceGroupName: string, accountName: string, options?: ContentKeyPoliciesListOptionalParams ): AsyncIterableIterator<ContentKeyPolicy> { for await (const page of this.listPagingPage( resourceGroupName, accountName, options )) { yield* page; } } /** * Lists the Content Key Policies in the account * @param resourceGroupName The name of the resource group within the Azure subscription. * @param accountName The Media Services account name. * @param options The options parameters. */ private _list( resourceGroupName: string, accountName: string, options?: ContentKeyPoliciesListOptionalParams ): Promise<ContentKeyPoliciesListResponse> { return this.client.sendOperationRequest( { resourceGroupName, accountName, options }, listOperationSpec ); } /** * Get the details of a Content Key Policy in the Media Services account * @param resourceGroupName The name of the resource group within the Azure subscription. * @param accountName The Media Services account name. * @param contentKeyPolicyName The Content Key Policy name. * @param options The options parameters. */ get( resourceGroupName: string, accountName: string, contentKeyPolicyName: string, options?: ContentKeyPoliciesGetOptionalParams ): Promise<ContentKeyPoliciesGetResponse> { return this.client.sendOperationRequest( { resourceGroupName, accountName, contentKeyPolicyName, options }, getOperationSpec ); } /** * Create or update a Content Key Policy in the Media Services account * @param resourceGroupName The name of the resource group within the Azure subscription. * @param accountName The Media Services account name. * @param contentKeyPolicyName The Content Key Policy name. * @param parameters The request parameters * @param options The options parameters. */ createOrUpdate( resourceGroupName: string, accountName: string, contentKeyPolicyName: string, parameters: ContentKeyPolicy, options?: ContentKeyPoliciesCreateOrUpdateOptionalParams ): Promise<ContentKeyPoliciesCreateOrUpdateResponse> { return this.client.sendOperationRequest( { resourceGroupName, accountName, contentKeyPolicyName, parameters, options }, createOrUpdateOperationSpec ); } /** * Deletes a Content Key Policy in the Media Services account * @param resourceGroupName The name of the resource group within the Azure subscription. * @param accountName The Media Services account name. * @param contentKeyPolicyName The Content Key Policy name. * @param options The options parameters. */ delete( resourceGroupName: string, accountName: string, contentKeyPolicyName: string, options?: ContentKeyPoliciesDeleteOptionalParams ): Promise<void> { return this.client.sendOperationRequest( { resourceGroupName, accountName, contentKeyPolicyName, options }, deleteOperationSpec ); } /** * Updates an existing Content Key Policy in the Media Services account * @param resourceGroupName The name of the resource group within the Azure subscription. * @param accountName The Media Services account name. * @param contentKeyPolicyName The Content Key Policy name. * @param parameters The request parameters * @param options The options parameters. */ update( resourceGroupName: string, accountName: string, contentKeyPolicyName: string, parameters: ContentKeyPolicy, options?: ContentKeyPoliciesUpdateOptionalParams ): Promise<ContentKeyPoliciesUpdateResponse> { return this.client.sendOperationRequest( { resourceGroupName, accountName, contentKeyPolicyName, parameters, options }, updateOperationSpec ); } /** * Get a Content Key Policy including secret values * @param resourceGroupName The name of the resource group within the Azure subscription. * @param accountName The Media Services account name. * @param contentKeyPolicyName The Content Key Policy name. * @param options The options parameters. */ getPolicyPropertiesWithSecrets( resourceGroupName: string, accountName: string, contentKeyPolicyName: string, options?: ContentKeyPoliciesGetPolicyPropertiesWithSecretsOptionalParams ): Promise<ContentKeyPoliciesGetPolicyPropertiesWithSecretsResponse> { return this.client.sendOperationRequest( { resourceGroupName, accountName, contentKeyPolicyName, options }, getPolicyPropertiesWithSecretsOperationSpec ); } /** * ListNext * @param resourceGroupName The name of the resource group within the Azure subscription. * @param accountName The Media Services account name. * @param nextLink The nextLink from the previous successful call to the List method. * @param options The options parameters. */ private _listNext( resourceGroupName: string, accountName: string, nextLink: string, options?: ContentKeyPoliciesListNextOptionalParams ): Promise<ContentKeyPoliciesListNextResponse> { return this.client.sendOperationRequest( { resourceGroupName, accountName, nextLink, options }, listNextOperationSpec ); } } // Operation Specifications const serializer = coreClient.createSerializer(Mappers, /* isXml */ false); const listOperationSpec: coreClient.OperationSpec = { path: "/subscriptions/{subscriptionId}/resourceGroups/{resourceGroupName}/providers/Microsoft.Media/mediaServices/{accountName}/contentKeyPolicies", httpMethod: "GET", responses: { 200: { bodyMapper: Mappers.ContentKeyPolicyCollection }, default: { bodyMapper: Mappers.ErrorResponse } }, queryParameters: [ Parameters.apiVersion, Parameters.filter, Parameters.top, Parameters.orderby ], urlParameters: [ Parameters.$host, Parameters.subscriptionId, Parameters.resourceGroupName, Parameters.accountName ], headerParameters: [Parameters.accept], serializer }; const getOperationSpec: coreClient.OperationSpec = { path: "/subscriptions/{subscriptionId}/resourceGroups/{resourceGroupName}/providers/Microsoft.Media/mediaServices/{accountName}/contentKeyPolicies/{contentKeyPolicyName}", httpMethod: "GET", responses: { 200: { bodyMapper: Mappers.ContentKeyPolicy }, default: { bodyMapper: Mappers.ErrorResponse } }, queryParameters: [Parameters.apiVersion], urlParameters: [ Parameters.$host, Parameters.subscriptionId, Parameters.resourceGroupName, Parameters.accountName, Parameters.contentKeyPolicyName ], headerParameters: [Parameters.accept], serializer }; const createOrUpdateOperationSpec: coreClient.OperationSpec = { path: "/subscriptions/{subscriptionId}/resourceGroups/{resourceGroupName}/providers/Microsoft.Media/mediaServices/{accountName}/contentKeyPolicies/{contentKeyPolicyName}", httpMethod: "PUT", responses: { 200: { bodyMapper: Mappers.ContentKeyPolicy }, 201: { bodyMapper: Mappers.ContentKeyPolicy }, default: { bodyMapper: Mappers.ErrorResponse } }, requestBody: Parameters.parameters10, queryParameters: [Parameters.apiVersion], urlParameters: [ Parameters.$host, Parameters.subscriptionId, Parameters.resourceGroupName, Parameters.accountName, Parameters.contentKeyPolicyName ], headerParameters: [Parameters.accept, Parameters.contentType], mediaType: "json", serializer }; const deleteOperationSpec: coreClient.OperationSpec = { path: "/subscriptions/{subscriptionId}/resourceGroups/{resourceGroupName}/providers/Microsoft.Media/mediaServices/{accountName}/contentKeyPolicies/{contentKeyPolicyName}", httpMethod: "DELETE", responses: { 200: {}, 204: {}, default: { bodyMapper: Mappers.ErrorResponse } }, queryParameters: [Parameters.apiVersion], urlParameters: [ Parameters.$host, Parameters.subscriptionId, Parameters.resourceGroupName, Parameters.accountName, Parameters.contentKeyPolicyName ], headerParameters: [Parameters.accept], serializer }; const updateOperationSpec: coreClient.OperationSpec = { path: "/subscriptions/{subscriptionId}/resourceGroups/{resourceGroupName}/providers/Microsoft.Media/mediaServices/{accountName}/contentKeyPolicies/{contentKeyPolicyName}", httpMethod: "PATCH", responses: { 200: { bodyMapper: Mappers.ContentKeyPolicy }, default: { bodyMapper: Mappers.ErrorResponse } }, requestBody: Parameters.parameters10, queryParameters: [Parameters.apiVersion], urlParameters: [ Parameters.$host, Parameters.subscriptionId, Parameters.resourceGroupName, Parameters.accountName, Parameters.contentKeyPolicyName ], headerParameters: [Parameters.accept, Parameters.contentType], mediaType: "json", serializer }; const getPolicyPropertiesWithSecretsOperationSpec: coreClient.OperationSpec = { path: "/subscriptions/{subscriptionId}/resourceGroups/{resourceGroupName}/providers/Microsoft.Media/mediaServices/{accountName}/contentKeyPolicies/{contentKeyPolicyName}/getPolicyPropertiesWithSecrets", httpMethod: "POST", responses: { 200: { bodyMapper: Mappers.ContentKeyPolicyProperties }, default: { bodyMapper: Mappers.ErrorResponse } }, queryParameters: [Parameters.apiVersion], urlParameters: [ Parameters.$host, Parameters.subscriptionId, Parameters.resourceGroupName, Parameters.accountName, Parameters.contentKeyPolicyName ], headerParameters: [Parameters.accept], serializer }; const listNextOperationSpec: coreClient.OperationSpec = { path: "{nextLink}", httpMethod: "GET", responses: { 200: { bodyMapper: Mappers.ContentKeyPolicyCollection }, default: { bodyMapper: Mappers.ErrorResponse } }, queryParameters: [ Parameters.apiVersion, Parameters.filter, Parameters.top, Parameters.orderby ], urlParameters: [ Parameters.$host, Parameters.subscriptionId, Parameters.resourceGroupName, Parameters.accountName, Parameters.nextLink ], headerParameters: [Parameters.accept], serializer };
the_stack
module CorsicaTests { "use strict"; var S = WinJS.Utilities.Scheduler; var global: any = window; function schedulePromise(priority) { var s = new WinJS._Signal(); S.schedule(s.complete.bind(s), priority, null, "Scheduled Promise"); return s.promise; } interface IXHRRequest { type: string; url: string; async: boolean; user: string; password: string; headers: any; } class mockXMLHttpRequest { readyState = 0; _aborted = false; _readyStatePromise = WinJS.Promise.wrap<void>(); _inheritedSchedulerPriority = S.currentPriority; _request: IXHRRequest; responseType: string; onreadystatechange; status: number; response; responseText: string; open(type: string, url: string, async: boolean, user: string, password: string) { this._readyStatePromise = this._readyStatePromise.then<void>(() => { this._request = { type: type, url: url, async: async, user: user, password: password, headers: {} }; this.responseType = "text"; this.readyState = 1; return this._fireonreadystatechange(); }); } _fireonreadystatechange() { if (this._request.async == true) { return WinJS.Promise.timeout().then(() => { if (!this._aborted) { this.onreadystatechange(); } return schedulePromise(this._inheritedSchedulerPriority); }); } else { this.onreadystatechange(); return schedulePromise(this._inheritedSchedulerPriority); } } setRequestHeader(name, value) { this._request.headers[name] = value; } send(data) { this._readyStatePromise = this._readyStatePromise. then<void>(() => { this.readyState = 2; return this._fireonreadystatechange(); }). then<void>(() => { var nextState = () => { var response = this.mockResponse(this._request, data); this.status = response.status; if (this.responseType == "blob") { this.response = response.responseText; } else if (this.responseType == "text" || !this.responseType) { this.responseText = response.responseText; } this.readyState = 4; return this._fireonreadystatechange(); }; if (this._request.async) { return WinJS.Promise.timeout().then(nextState); } else { return nextState(); } }); } abort() { this.readyState = 0; this.onreadystatechange = null; this.status = 0; this._aborted = true; this._readyStatePromise.cancel(); var that = this; this._readyStatePromise = WinJS.Promise.wrap().then(function () { that.readyState = 0; return that._fireonreadystatechange(); }).then(function () { that.onreadystatechange = null; }); } //override me. mockResponse(request: IXHRRequest, data: any) { return { status: 400, responseText: "" }; } } export class XHR { testSimpleGet(complete) { var oldXHR = global.XMLHttpRequest; global.XMLHttpRequest = mockXMLHttpRequest; mockXMLHttpRequest.prototype.mockResponse = function (request) { LiveUnit.Assert.areEqual('GET', request.type); LiveUnit.Assert.areEqual('SimpleFile.txt', request.url); LiveUnit.Assert.areEqual(true, request.async); return { status: 200, responseText: "42" }; } try { var options = { url: 'SimpleFile.txt' }; var callback = function (success, response) { LiveUnit.Assert.areEqual(true, success, "File not successfully retrieved with XHR"); LiveUnit.Assert.areEqual("42", response.responseText); complete(); } WinJS.xhr(options). then( function (req) { callback(true, req); }, function (req) { callback(false, req); } ); } finally { global.XMLHttpRequest = oldXHR; } } testSimpleGetBlob(complete) { var oldXHR = global.XMLHttpRequest; global.XMLHttpRequest = mockXMLHttpRequest; mockXMLHttpRequest.prototype.mockResponse = function (request) { LiveUnit.Assert.areEqual('GET', request.type); LiveUnit.Assert.areEqual('SimpleFile.txt', request.url); LiveUnit.Assert.areEqual('blob', this.responseType); LiveUnit.Assert.areEqual(true, request.async); return { status: 200, responseText: "42" }; } try { var options = { url: 'SimpleFile.txt', responseType: 'blob' }; var callback = function (success, response) { LiveUnit.Assert.areEqual(true, success, "File not successfully retrieved with XHR"); LiveUnit.Assert.areEqual("42", response.response); complete(); } WinJS.xhr(options). then( function (req) { callback(true, req); }, function (req) { callback(false, req); } ); } finally { global.XMLHttpRequest = oldXHR; } } testSimpleGetError(complete) { var oldXHR = global.XMLHttpRequest; global.XMLHttpRequest = mockXMLHttpRequest; mockXMLHttpRequest.prototype.mockResponse = function (request) { LiveUnit.Assert.areEqual('GET', request.type); LiveUnit.Assert.areEqual('SimpleFile.txt', request.url); LiveUnit.Assert.areEqual(true, request.async); return { status: 404, responseText: "" }; } try { var options = { url: 'SimpleFile.txt' }; var callback = function (success, response) { LiveUnit.Assert.areEqual(false, success, "Expected file not to be retrieved."); complete(); } WinJS.xhr(options). then( function (req) { callback(true, req); }, function (req) { callback(false, req); } ); } finally { global.XMLHttpRequest = oldXHR; } } testPost(complete) { var oldXHR = global.XMLHttpRequest; global.XMLHttpRequest = mockXMLHttpRequest; mockXMLHttpRequest.prototype.mockResponse = function (request, data) { LiveUnit.Assert.areEqual('POST', request.type); LiveUnit.Assert.areEqual('posthandler.aspx', request.url); LiveUnit.Assert.areEqual(true, request.async); LiveUnit.Assert.areEqual("somedata", data); LiveUnit.Assert.areEqual("data1", request.headers["Foo"]); LiveUnit.Assert.areEqual("data2", request.headers["Bar"]); return { status: 200, responseText: "woot" }; } try { var options = { url: 'posthandler.aspx', type: 'POST', data: 'somedata', headers: { "Foo": "data1", "Bar": "data2" } } var callback = function (success, response) { LiveUnit.Assert.areEqual(true, success); complete(); } WinJS.xhr(options). then( function (req) { callback(true, req); }, function (req) { callback(false, req); } ); } finally { global.XMLHttpRequest = oldXHR; } } // Verifies that the complete and error handlers of the XHR promise // are executed in the priority context at which the XHR was created. // testPriorityInheritance(complete) { var Scheduler = WinJS.Utilities.Scheduler, Priority = Scheduler.Priority, oldXHR = global.XMLHttpRequest; global.XMLHttpRequest = mockXMLHttpRequest; function test(priority, expectSuccess) { mockXMLHttpRequest.prototype.mockResponse = function (request, data) { return expectSuccess ? { status: 200, responseText: "woot" } : { status: 404, responseText: "" }; } return new WinJS.Promise(function (subTestComplete) { Scheduler.schedule(function () { var async = false; var options = { url: 'posthandler.aspx', type: 'POST', data: 'somedata', headers: { "Foo": "data1", "Bar": "data2" } } var done = function (success) { LiveUnit.Assert.isTrue(async, "Request should have completed asynchronously relative to creation of XHR"); LiveUnit.Assert.areEqual(success, expectSuccess, "Request unexpectedly completed (un)successfully"); LiveUnit.Assert.areEqual(priority, Scheduler.currentPriority, "Request completed in wrong priority context"); subTestComplete(); }; WinJS.xhr(options). then( function (req) { done(true); }, function (req) { done(false); } ); async = true; }, priority); }); } var promise = WinJS.Promise.wrap(); [Priority.high, Priority.normal, Priority.idle].forEach(function (priority) { [true, false].forEach(function (success) { promise = promise.then(function () { return test(priority, success); }); }); }); promise.then(function () { global.XMLHttpRequest = oldXHR; complete(); }); } testAbort(complete) { var oldXHR = global.XMLHttpRequest; global.XMLHttpRequest = mockXMLHttpRequest; mockXMLHttpRequest.prototype.mockResponse = function (request) { return { status: 200, responseText: "42" }; } try { var options = { url: 'SimpleFile.txt' }; var hitCompleteCount = 0, hitErrorCount = 0; var request = WinJS.xhr(options); request.then( function () { hitCompleteCount++; }, function () { hitErrorCount++; } ); request.cancel(); global.setTimeout(function () { LiveUnit.Assert.areEqual(0, hitCompleteCount); LiveUnit.Assert.areEqual(1, hitErrorCount); complete(); }, 1); } finally { global.XMLHttpRequest = oldXHR; } } testReadyStateChange(complete) { var oldXHR = global.XMLHttpRequest; global.XMLHttpRequest = mockXMLHttpRequest; mockXMLHttpRequest.prototype.mockResponse = function (request) { return { status: 200, responseText: "42" }; } try { var options = { url: 'SimpleFile.txt', async: false }; var progress = [ { readyState: 1, status: undefined, responseText: undefined }, { readyState: 2, status: undefined, responseText: undefined } ]; var progressPos = -1; var callback = function (success) { LiveUnit.Assert.areEqual(true, success); LiveUnit.Assert.areEqual(1, progressPos); WinJS.Utilities._setImmediate(complete); } WinJS.xhr(options). then( function (req) { LiveUnit.Assert.areEqual(4, req.readyState); LiveUnit.Assert.areEqual(200, req.status); LiveUnit.Assert.areEqual("42", req.responseText); }, function (req) { LiveUnit.Assert.fail("Response should be successful"); }, function (req) { var expected = progress[++progressPos]; LiveUnit.Assert.areEqual(expected.readyState, req.readyState); LiveUnit.Assert.areEqual(expected.status, req.status); LiveUnit.Assert.areEqual(expected.responseText, req.responseText); } ).then( function () { callback(true); }, function () { callback(false); }); } finally { global.XMLHttpRequest = oldXHR; } } testXHR100(complete) { var fragmentFiles = ["FragmentBasic.html", "FragmentFindmeInternal.html", "FragmentWithExternalScriptAndStyles.html", "FragmentWithScriptAndStyles.html", "FragmentWithScriptAndStylesNoBody.html", "FragmentWithScriptAndStylesNoBodyNoLoad.html"]; var numFragments = 200; var href; var xhrPromises = []; for (var i = 0; i < numFragments; i++) { // get one of the fragment files from the array href = fragmentFiles[i % fragmentFiles.length]; xhrPromises.push(WinJS.xhr({ url: href })); } WinJS.Promise.join(xhrPromises). done(function (results) { complete(); }, function (error) { LiveUnit.Assert.fail("error from Promise.join: " + error); complete(); }); } testCustomRequestInitializer(complete) { var isCallbackCalled = false; function customRequestInitializerFunction(req) { isCallbackCalled = true; } var oldXHR = global.XMLHttpRequest; global.XMLHttpRequest = mockXMLHttpRequest; mockXMLHttpRequest.prototype.mockResponse = function (request, data) { return { status: 200, responseText: "" }; } try { var options = { url: 'SimpleFile.txt', customRequestInitializer: customRequestInitializerFunction }; // var callback = function (success) { LiveUnit.Assert.areEqual(true, isCallbackCalled, "customRequestInitializer is not called"); LiveUnit.Assert.areEqual(true, success, "File not successfully retrieved with XHR"); complete(); } WinJS.xhr(options). then( function () { callback(true); }, function () { callback(false); } ); } finally { global.XMLHttpRequest = oldXHR; } } // Cordova returns status of '0' when successfully retrieving local // file system resources with the file:// protocol. testCordovaXHR(complete) { var oldXHR = global.XMLHttpRequest; global.XMLHttpRequest = mockXMLHttpRequest; mockXMLHttpRequest.prototype.mockResponse = function (request) { LiveUnit.Assert.areEqual('GET', request.type); LiveUnit.Assert.areEqual('file://SimpleFile.txt', request.url); LiveUnit.Assert.areEqual(true, request.async); return { status: 0, responseText: "42" }; } try { var options = { url: 'file://SimpleFile.txt' }; var callback = function (success, response) { LiveUnit.Assert.areEqual(true, success, "File not successfully retrieved with XHR"); LiveUnit.Assert.areEqual("42", response.responseText); complete(); } WinJS.xhr(options). then( function (req) { callback(true, req); }, function (req) { callback(false, req); } ); } finally { global.XMLHttpRequest = oldXHR; } } }; } LiveUnit.registerTestClass("CorsicaTests.XHR");
the_stack
import {Component, EventEmitter, Injector, OnInit} from "@angular/core"; import {FormGroup} from "@angular/forms"; import { CommandLineToolModel, isType, WorkflowFactory, WorkflowModel, WorkflowStepInputModel, WorkflowStepOutputModel, CommandInputParameterModel } from "cwlts/models"; import {CommandLineToolFactory} from "cwlts/models/generic/CommandLineToolFactory"; import {CommandLinePart} from "cwlts/models/helpers/CommandLinePart"; import {JobHelper} from "cwlts/models/helpers/JobHelper"; import {ReplaySubject} from "rxjs/ReplaySubject"; import {Subject} from "rxjs/Subject"; import {AppMetaManager} from "../core/app-meta/app-meta-manager"; import {AppMetaManagerToken, appMetaManagerFactory} from "../core/app-meta/app-meta-manager-factory"; import {CodeSwapService} from "../core/code-content-service/code-content.service"; import {DataGatewayService} from "../core/data-gateway/data-gateway.service"; import {AppModelToken, appModelFactory} from "../core/factories/app-model-provider-factory"; import {WorkboxService} from "../core/workbox/workbox.service"; import {AppEditorBase} from "../editor-common/app-editor-base/app-editor-base"; import {AppValidatorService} from "../editor-common/app-validator/app-validator.service"; import {PlatformAppService} from "../editor-common/components/platform-app-common/platform-app.service"; import {GraphJobEditorComponent} from "../job-editor/graph-job-editor/graph-job-editor.component"; import {EditorInspectorService} from "../editor-common/inspector/editor-inspector.service"; import {AppSaverToken} from "../editor-common/services/app-saving/app-saver.interface"; import {LocalFileSavingService} from "../editor-common/services/app-saving/local-file-saving.service"; import {PlatformAppSavingService} from "../editor-common/services/app-saving/platform-app-saving.service"; import {ExecutorService} from "../executor-service/executor.service"; import {NotificationBarService} from "../layout/notification-bar/notification-bar.service"; import {StatusBarService} from "../layout/status-bar/status-bar.service"; import {LocalRepositoryService} from "../repository/local-repository.service"; import {PlatformRepositoryService} from "../repository/platform-repository.service"; import {IpcService} from "../services/ipc.service"; import {ModalService} from "../ui/modal/modal.service"; import {FileRepositoryService} from "../file-repository/file-repository.service"; import {Subscription} from "rxjs/Subscription"; import {ExportAppService} from "../services/export-app/export-app.service"; import {Store} from "@ngrx/store"; import {AuthService} from "../auth/auth.service"; import {AppInfoToken, appInfoFactory, AppInfo} from "../editor-common/factories/app-info.factory"; import {AppState} from "./reducers"; import {appTestData} from "./reducers/selectors"; import {fixJob} from "../editor-common/utilities/job-adapter/job-adapter"; import {take} from "rxjs/operators"; import { AppMockValuesChange, LoadTestJobAction, InputTestValueChangeAction, InputRemoveAction, InputIDChangeAction } from "./reducers/actions"; import {fromEvent} from "rxjs/observable/fromEvent"; import {BehaviorSubject} from "rxjs/BehaviorSubject"; import {RevisionListComponent} from "../editor-common/components/revision-list/revision-list.component"; export function appSaverFactory(comp: ToolEditorComponent, ipc: IpcService, modal: ModalService, platformRepository: PlatformRepositoryService) { if (comp.tabData.dataSource === "local") { return new LocalFileSavingService(ipc); } return new PlatformAppSavingService(platformRepository, modal); } @Component({ selector: "ct-tool-editor", styleUrls: ["../editor-common/app-editor-base/app-editor-base.scss"], templateUrl: "./tool-editor.component.html", providers: [ EditorInspectorService, NotificationBarService, CodeSwapService, PlatformAppService, { provide: AppSaverToken, useFactory: appSaverFactory, deps: [ToolEditorComponent, IpcService, ModalService, PlatformRepositoryService] }, { provide: AppMetaManagerToken, useFactory: appMetaManagerFactory, deps: [ToolEditorComponent, LocalRepositoryService, PlatformRepositoryService] }, { provide: AppModelToken, useFactory: appModelFactory, deps: [ToolEditorComponent] }, { provide: AppInfoToken, useFactory: appInfoFactory, deps: [ToolEditorComponent] } ] }) export class ToolEditorComponent extends AppEditorBase implements OnInit { /** Default view mode. */ viewMode: "code" | "gui" | "test" | "info"; /** Flag for bottom panel, shows validation-issues, commandline, or neither */ reportPanel: "validation" | "commandLinePreview" | undefined; /** Model that's recreated on document change */ dataModel: CommandLineToolModel; workflowWrapper: WorkflowModel; /** Sorted array of resulting command line parts */ commandLineParts: Subject<CommandLinePart[]> = new ReplaySubject(1); toolGroup: FormGroup; dirty = new EventEmitter(); jobSubscription: Subscription; private testJob = new BehaviorSubject({}); private appID: string; constructor(statusBar: StatusBarService, notificationBarService: NotificationBarService, modal: ModalService, inspector: EditorInspectorService, dataGateway: DataGatewayService, injector: Injector, appValidator: AppValidatorService, codeSwapService: CodeSwapService, platformRepository: PlatformRepositoryService, platformAppService: PlatformAppService, localRepository: LocalRepositoryService, fileRepository: FileRepositoryService, workbox: WorkboxService, exportApp: ExportAppService, public store: Store<AppState>, auth: AuthService, executor: ExecutorService) { super( statusBar, notificationBarService, modal, inspector, dataGateway, injector, appValidator, codeSwapService, platformAppService, platformRepository, localRepository, fileRepository, workbox, exportApp, store, auth, executor, ); } ngOnInit(): any { super.ngOnInit(); const appInfo = this.injector.get(AppInfoToken) as AppInfo; this.appID = appInfo.id; this.toolGroup = new FormGroup({}); this.dirty.subscribeTracked(this, () => { this.syncModelAndCode(false); }); this.store.select(appTestData(this.appID)).subscribeTracked(this, this.testJob); } openRevision(revisionNumber: number | string, revisionListComponent: RevisionListComponent) { return super.openRevision(revisionNumber, revisionListComponent).then(() => { this.toolGroup.reset(); }); } switchTab(tabName): void { super.switchTab(tabName); if (this.jobSubscription) { this.jobSubscription.unsubscribe(); this.jobSubscription = null; } if (!this.dataModel) return; if (tabName === "test") { // create the workflow model that will be displayed on the test tab this.workflowWrapper = WorkflowFactory.from({cwlVersion: this.dataModel.cwlVersion} as any); // add this tool as its only step const step = this.workflowWrapper.addStepFromProcess(this.dataModel.serialize()); /** * Adding a step sometimes generates a different id for that step than that of an app that it was made from. * On graph job representation, step progress plugin knows about tool id, and will try to update execution state on it. * If this representation has a different id, they will not match and step will not be found on the SVG. * This is a place to fix that since this workflow is not a source of truth for the data, but just a utility * to help us render a graph, so just patch the ID to ensure that it's exactly what we expect to find. * * However, ID is not required by CWL, so this applies only if dataModel has one. */ if (this.dataModel.id) { this.workflowWrapper.changeStepId(step, this.dataModel.id); } // iterate through all inputs of the tool this.workflowWrapper.steps[0].in.forEach((input: WorkflowStepInputModel) => { if (isType(input, ["File", "Directory"])) { // create inputs from file ports this.workflowWrapper.createInputFromPort(input); } else { // everything else should be exposed (show up in the step inspector) this.workflowWrapper.exposePort(input); } }); this.workflowWrapper.steps[0].out.forEach((output: WorkflowStepOutputModel) => { this.workflowWrapper.createOutputFromPort(output); }); // set job on the tool to be the actual job, so the command line is the real thing this.jobSubscription = (this.injector.get(AppMetaManagerToken) as AppMetaManager).getAppMeta("job").subscribeTracked(this, (job) => { this.dataModel.setJobInputs(job); }); } else { this.dataModel.setJobInputs(this.testJob.getValue()); } } protected getPreferredTab(): string { return "gui"; } protected getPreferredReportPanel(): string { return "commandLinePreview"; } protected recreateModel(json: Object): void { this.dataModel = CommandLineToolFactory.from(json as any, "document"); if (!this.dataModel.namespaces.has("sbg")) { this.dataModel.namespaces.set("sbg", "https://www.sevenbridges.com/"); } this.dataModel.onCommandLineResult(cmdResult => { this.commandLineParts.next(cmdResult); }); this.dataModel.updateCommandLine(); this.dataModel.setValidationCallback(this.afterModelValidation.bind(this)); this.dataModel.validate().then(this.afterModelValidation.bind(this)); } protected afterModelCreated(isFirstCreation: boolean): void { super.afterModelCreated(isFirstCreation); if (isFirstCreation) { // Backend might have a stored test job that we should load // This is implemented as a side effect because if it doesn't happen, it's not a big deal this.store.dispatch(new LoadTestJobAction(this.appID)); } // When we get the first result from a test job, ensure that it conforms to the model that we have this.testJob.pipe(take(1)).subscribe(data => { this.store.dispatch(new AppMockValuesChange(this.appID, fixJob(data, this.dataModel))); }); this.testJob.subscribe(job => this.dataModel.setJobInputs(job)); this.dataModel.on("input.create", (input: CommandInputParameterModel) => { // When input is created it emits an event, but its type is set afterwards from Composer // So we will wait just a bit before generating a job value so it knows that the type is not undefined setTimeout(() => { const jobData = JobHelper.generateMockJobData(input); this.store.dispatch(new InputTestValueChangeAction(this.appID, input.id, jobData)); }); }); this.dataModel.on("input.remove", input => { this.store.dispatch(new InputRemoveAction(this.appID, input.id)); }); this.dataModel.on("input.change.id", (data: { oldId: string; newId: string; port: CommandInputParameterModel }) => { const {oldId, newId, port} = data; // We want to react to root input id changes and migrate data, for nested stuff, just regenerate for now if (port.loc && port.loc.split(".").length === 2) { this.store.dispatch(new InputIDChangeAction(this.appID, oldId, newId)); } else { const fixed = fixJob(this.testJob.getValue(), this.dataModel); this.store.dispatch(new AppMockValuesChange(this.appID, fixed)); } }); fromEvent(this.dataModel, "io.change.type").subscribe((loc: string) => { setTimeout(() => { const fixed = fixJob(this.testJob.getValue(), this.dataModel); this.store.dispatch(new AppMockValuesChange(this.appID, fixed)); }); }); } onGraphJobEditorDraw(editor: GraphJobEditorComponent) { editor.inspectStep(this.workflowWrapper.steps[0].connectionId); } }
the_stack
import * as msRest from "@azure/ms-rest-js"; import * as Models from "../models"; import * as Mappers from "../models/jobsMappers"; import * as Parameters from "../models/parameters"; import { IotHubGatewayServiceAPIsContext } from "../iotHubGatewayServiceAPIsContext"; /** Class representing a Jobs. */ export class Jobs { private readonly client: IotHubGatewayServiceAPIsContext; /** * Create a Jobs. * @param {IotHubGatewayServiceAPIsContext} client Reference to the service client. */ constructor(client: IotHubGatewayServiceAPIsContext) { this.client = client; } /** * Creates a new import or export job on the IoT Hub. See * https://docs.microsoft.com/en-us/azure/iot-hub/iot-hub-devguide-identity-registry#import-and-export-device-identities * for more information. * @param jobProperties The job specifications. * @param [options] The optional parameters * @returns Promise<Models.JobsCreateImportExportJobResponse> */ createImportExportJob(jobProperties: Models.JobProperties, options?: msRest.RequestOptionsBase): Promise<Models.JobsCreateImportExportJobResponse>; /** * @param jobProperties The job specifications. * @param callback The callback */ createImportExportJob(jobProperties: Models.JobProperties, callback: msRest.ServiceCallback<Models.JobProperties>): void; /** * @param jobProperties The job specifications. * @param options The optional parameters * @param callback The callback */ createImportExportJob(jobProperties: Models.JobProperties, options: msRest.RequestOptionsBase, callback: msRest.ServiceCallback<Models.JobProperties>): void; createImportExportJob(jobProperties: Models.JobProperties, options?: msRest.RequestOptionsBase | msRest.ServiceCallback<Models.JobProperties>, callback?: msRest.ServiceCallback<Models.JobProperties>): Promise<Models.JobsCreateImportExportJobResponse> { return this.client.sendOperationRequest( { jobProperties, options }, createImportExportJobOperationSpec, callback) as Promise<Models.JobsCreateImportExportJobResponse>; } /** * Gets the status of all import and export jobs in the IoT Hub. See * https://docs.microsoft.com/en-us/azure/iot-hub/iot-hub-devguide-identity-registry#import-and-export-device-identities * for more information. * @param [options] The optional parameters * @returns Promise<Models.JobsGetImportExportJobsResponse> */ getImportExportJobs(options?: msRest.RequestOptionsBase): Promise<Models.JobsGetImportExportJobsResponse>; /** * @param callback The callback */ getImportExportJobs(callback: msRest.ServiceCallback<Models.JobProperties[]>): void; /** * @param options The optional parameters * @param callback The callback */ getImportExportJobs(options: msRest.RequestOptionsBase, callback: msRest.ServiceCallback<Models.JobProperties[]>): void; getImportExportJobs(options?: msRest.RequestOptionsBase | msRest.ServiceCallback<Models.JobProperties[]>, callback?: msRest.ServiceCallback<Models.JobProperties[]>): Promise<Models.JobsGetImportExportJobsResponse> { return this.client.sendOperationRequest( { options }, getImportExportJobsOperationSpec, callback) as Promise<Models.JobsGetImportExportJobsResponse>; } /** * Gets the status of an import or export job in the IoT Hub. See * https://docs.microsoft.com/en-us/azure/iot-hub/iot-hub-devguide-identity-registry#import-and-export-device-identities * for more information. * @param id The unique identifier of the job. * @param [options] The optional parameters * @returns Promise<Models.JobsGetImportExportJobResponse> */ getImportExportJob(id: string, options?: msRest.RequestOptionsBase): Promise<Models.JobsGetImportExportJobResponse>; /** * @param id The unique identifier of the job. * @param callback The callback */ getImportExportJob(id: string, callback: msRest.ServiceCallback<Models.JobProperties>): void; /** * @param id The unique identifier of the job. * @param options The optional parameters * @param callback The callback */ getImportExportJob(id: string, options: msRest.RequestOptionsBase, callback: msRest.ServiceCallback<Models.JobProperties>): void; getImportExportJob(id: string, options?: msRest.RequestOptionsBase | msRest.ServiceCallback<Models.JobProperties>, callback?: msRest.ServiceCallback<Models.JobProperties>): Promise<Models.JobsGetImportExportJobResponse> { return this.client.sendOperationRequest( { id, options }, getImportExportJobOperationSpec, callback) as Promise<Models.JobsGetImportExportJobResponse>; } /** * Cancels an import or export job in the IoT Hub. * @param id The unique identifier of the job. * @param [options] The optional parameters * @returns Promise<Models.JobsCancelImportExportJobResponse> */ cancelImportExportJob(id: string, options?: msRest.RequestOptionsBase): Promise<Models.JobsCancelImportExportJobResponse>; /** * @param id The unique identifier of the job. * @param callback The callback */ cancelImportExportJob(id: string, callback: msRest.ServiceCallback<any>): void; /** * @param id The unique identifier of the job. * @param options The optional parameters * @param callback The callback */ cancelImportExportJob(id: string, options: msRest.RequestOptionsBase, callback: msRest.ServiceCallback<any>): void; cancelImportExportJob(id: string, options?: msRest.RequestOptionsBase | msRest.ServiceCallback<any>, callback?: msRest.ServiceCallback<any>): Promise<Models.JobsCancelImportExportJobResponse> { return this.client.sendOperationRequest( { id, options }, cancelImportExportJobOperationSpec, callback) as Promise<Models.JobsCancelImportExportJobResponse>; } /** * Gets details of a scheduled job from the IoT Hub. See * https://docs.microsoft.com/en-us/azure/iot-hub/iot-hub-devguide-jobs for more information. * @param id The unique identifier of the job. * @param [options] The optional parameters * @returns Promise<Models.JobsGetScheduledJobResponse> */ getScheduledJob(id: string, options?: msRest.RequestOptionsBase): Promise<Models.JobsGetScheduledJobResponse>; /** * @param id The unique identifier of the job. * @param callback The callback */ getScheduledJob(id: string, callback: msRest.ServiceCallback<Models.JobResponse>): void; /** * @param id The unique identifier of the job. * @param options The optional parameters * @param callback The callback */ getScheduledJob(id: string, options: msRest.RequestOptionsBase, callback: msRest.ServiceCallback<Models.JobResponse>): void; getScheduledJob(id: string, options?: msRest.RequestOptionsBase | msRest.ServiceCallback<Models.JobResponse>, callback?: msRest.ServiceCallback<Models.JobResponse>): Promise<Models.JobsGetScheduledJobResponse> { return this.client.sendOperationRequest( { id, options }, getScheduledJobOperationSpec, callback) as Promise<Models.JobsGetScheduledJobResponse>; } /** * Creates a new job to schedule twin updates or direct methods on the IoT Hub at a scheduled time. * See https://docs.microsoft.com/en-us/azure/iot-hub/iot-hub-devguide-jobs for more information. * @param id The unique identifier of the job. * @param jobRequest The job request info. * @param [options] The optional parameters * @returns Promise<Models.JobsCreateScheduledJobResponse> */ createScheduledJob(id: string, jobRequest: Models.JobRequest, options?: msRest.RequestOptionsBase): Promise<Models.JobsCreateScheduledJobResponse>; /** * @param id The unique identifier of the job. * @param jobRequest The job request info. * @param callback The callback */ createScheduledJob(id: string, jobRequest: Models.JobRequest, callback: msRest.ServiceCallback<Models.JobResponse>): void; /** * @param id The unique identifier of the job. * @param jobRequest The job request info. * @param options The optional parameters * @param callback The callback */ createScheduledJob(id: string, jobRequest: Models.JobRequest, options: msRest.RequestOptionsBase, callback: msRest.ServiceCallback<Models.JobResponse>): void; createScheduledJob(id: string, jobRequest: Models.JobRequest, options?: msRest.RequestOptionsBase | msRest.ServiceCallback<Models.JobResponse>, callback?: msRest.ServiceCallback<Models.JobResponse>): Promise<Models.JobsCreateScheduledJobResponse> { return this.client.sendOperationRequest( { id, jobRequest, options }, createScheduledJobOperationSpec, callback) as Promise<Models.JobsCreateScheduledJobResponse>; } /** * Cancels a scheduled job on the IoT Hub. See * https://docs.microsoft.com/en-us/azure/iot-hub/iot-hub-devguide-jobs for more information. * @param id The unique identifier of the job. * @param [options] The optional parameters * @returns Promise<Models.JobsCancelScheduledJobResponse> */ cancelScheduledJob(id: string, options?: msRest.RequestOptionsBase): Promise<Models.JobsCancelScheduledJobResponse>; /** * @param id The unique identifier of the job. * @param callback The callback */ cancelScheduledJob(id: string, callback: msRest.ServiceCallback<Models.JobResponse>): void; /** * @param id The unique identifier of the job. * @param options The optional parameters * @param callback The callback */ cancelScheduledJob(id: string, options: msRest.RequestOptionsBase, callback: msRest.ServiceCallback<Models.JobResponse>): void; cancelScheduledJob(id: string, options?: msRest.RequestOptionsBase | msRest.ServiceCallback<Models.JobResponse>, callback?: msRest.ServiceCallback<Models.JobResponse>): Promise<Models.JobsCancelScheduledJobResponse> { return this.client.sendOperationRequest( { id, options }, cancelScheduledJobOperationSpec, callback) as Promise<Models.JobsCancelScheduledJobResponse>; } /** * Gets the information about jobs using an IoT Hub query. See * https://docs.microsoft.com/azure/iot-hub/iot-hub-devguide-query-language for more information. * @param [options] The optional parameters * @returns Promise<Models.JobsQueryScheduledJobsResponse> */ queryScheduledJobs(options?: Models.JobsQueryScheduledJobsOptionalParams): Promise<Models.JobsQueryScheduledJobsResponse>; /** * @param callback The callback */ queryScheduledJobs(callback: msRest.ServiceCallback<Models.QueryResult>): void; /** * @param options The optional parameters * @param callback The callback */ queryScheduledJobs(options: Models.JobsQueryScheduledJobsOptionalParams, callback: msRest.ServiceCallback<Models.QueryResult>): void; queryScheduledJobs(options?: Models.JobsQueryScheduledJobsOptionalParams | msRest.ServiceCallback<Models.QueryResult>, callback?: msRest.ServiceCallback<Models.QueryResult>): Promise<Models.JobsQueryScheduledJobsResponse> { return this.client.sendOperationRequest( { options }, queryScheduledJobsOperationSpec, callback) as Promise<Models.JobsQueryScheduledJobsResponse>; } } // Operation Specifications const serializer = new msRest.Serializer(Mappers); const createImportExportJobOperationSpec: msRest.OperationSpec = { httpMethod: "POST", path: "jobs/create", queryParameters: [ Parameters.apiVersion ], requestBody: { parameterPath: "jobProperties", mapper: { ...Mappers.JobProperties, required: true } }, responses: { 200: { bodyMapper: Mappers.JobProperties }, default: {} }, serializer }; const getImportExportJobsOperationSpec: msRest.OperationSpec = { httpMethod: "GET", path: "jobs", queryParameters: [ Parameters.apiVersion ], responses: { 200: { bodyMapper: { serializedName: "parsedResponse", type: { name: "Sequence", element: { type: { name: "Composite", className: "JobProperties" } } } } }, default: {} }, serializer }; const getImportExportJobOperationSpec: msRest.OperationSpec = { httpMethod: "GET", path: "jobs/{id}", urlParameters: [ Parameters.id ], queryParameters: [ Parameters.apiVersion ], responses: { 200: { bodyMapper: Mappers.JobProperties }, default: {} }, serializer }; const cancelImportExportJobOperationSpec: msRest.OperationSpec = { httpMethod: "DELETE", path: "jobs/{id}", urlParameters: [ Parameters.id ], queryParameters: [ Parameters.apiVersion ], responses: { 200: { bodyMapper: { serializedName: "parsedResponse", type: { name: "Object" } } }, 204: {}, default: {} }, serializer }; const getScheduledJobOperationSpec: msRest.OperationSpec = { httpMethod: "GET", path: "jobs/v2/{id}", urlParameters: [ Parameters.id ], queryParameters: [ Parameters.apiVersion ], responses: { 200: { bodyMapper: Mappers.JobResponse }, default: {} }, serializer }; const createScheduledJobOperationSpec: msRest.OperationSpec = { httpMethod: "PUT", path: "jobs/v2/{id}", urlParameters: [ Parameters.id ], queryParameters: [ Parameters.apiVersion ], requestBody: { parameterPath: "jobRequest", mapper: { ...Mappers.JobRequest, required: true } }, responses: { 200: { bodyMapper: Mappers.JobResponse }, default: {} }, serializer }; const cancelScheduledJobOperationSpec: msRest.OperationSpec = { httpMethod: "POST", path: "jobs/v2/{id}/cancel", urlParameters: [ Parameters.id ], queryParameters: [ Parameters.apiVersion ], responses: { 200: { bodyMapper: Mappers.JobResponse }, default: {} }, serializer }; const queryScheduledJobsOperationSpec: msRest.OperationSpec = { httpMethod: "GET", path: "jobs/v2/query", queryParameters: [ Parameters.jobType, Parameters.jobStatus, Parameters.apiVersion ], responses: { 200: { bodyMapper: Mappers.QueryResult }, default: {} }, serializer };
the_stack
import * as fs from "fs-plus"; import * as path from "path"; import * as vscode from "vscode"; import { ArgumentEmptyOrNullError } from "../common/Error/OperationFailedErrors/ArgumentEmptyOrNullError"; import { WorkspaceNotOpenError } from "../common/Error/OperationFailedErrors/WorkspaceNotOpenError"; import { OperationCanceledError } from "../common/Error/OperationCanceledError"; import { WorkspaceConfigNotFoundError } from "../common/Error/SystemErrors/WorkspaceConfigNotFoundError"; import { ConfigHandler } from "../configHandler"; import { ConfigKey, FileNames, OperationType, OSPlatform, PlatformType, ScaffoldType } from "../constants"; import { FileUtility } from "../FileUtility"; import { TelemetryContext } from "../telemetry"; import * as utils from "../utils"; import { Board } from "./Interfaces/Board"; import { ComponentType } from "./Interfaces/Component"; import { Device, DeviceType } from "./Interfaces/Device"; import { TemplateFileInfo } from "./Interfaces/ProjectTemplate"; import { OTA } from "./OTA"; import { DirectoryNotFoundError } from "../common/Error/OperationFailedErrors/DirectoryNotFoundError"; import { FileNotFoundError } from "../common/Error/OperationFailedErrors/FileNotFound"; import { checkExtensionAvailable } from "./Apis"; import { DependentExtensionNotFoundError } from "../common/Error/OperationFailedErrors/DependentExtensionNotFoundError"; import { ExtensionName } from "./Interfaces/Api"; const constants = { defaultSketchFileName: "device.ino", arduinoJsonFileName: "arduino.json", cppPropertiesFileName: "c_cpp_properties.json", cppPropertiesFileNameMac: "c_cpp_properties_macos.json", cppPropertiesFileNameLinux: "c_cpp_properties_linux.json", cppPropertiesFileNameWin: "c_cpp_properties_win32.json", outputPath: "./.build", compileTaskName: "Arduino Compile", uploadTaskName: "Arduino Upload", environmentTemplateFolderName: "Arduino Task" }; export abstract class ArduinoDeviceBase implements Device { protected deviceType: DeviceType; protected componentType: ComponentType; protected deviceFolder: string; protected vscodeFolderPath: string; protected boardFolderPath: string; protected channel: vscode.OutputChannel; protected extensionContext: vscode.ExtensionContext; protected telemetryContext: TelemetryContext; protected templateFiles: TemplateFileInfo[] = []; abstract name: string; abstract id: string; abstract board: Board; constructor( context: vscode.ExtensionContext, devicePath: string, channel: vscode.OutputChannel, telemetryContext: TelemetryContext, deviceType: DeviceType ) { this.deviceType = deviceType; this.componentType = ComponentType.Device; this.deviceFolder = devicePath; this.extensionContext = context; this.vscodeFolderPath = path.join(this.deviceFolder, FileNames.vscodeSettingsFolderName); this.boardFolderPath = context.asAbsolutePath( path.join(FileNames.resourcesFolderName, FileNames.templatesFolderName) ); this.telemetryContext = telemetryContext; this.channel = channel; } getDeviceType(): DeviceType { return this.deviceType; } getComponentType(): ComponentType { return this.componentType; } static async isAvailable(): Promise<boolean> { return await checkExtensionAvailable(ExtensionName.Arduino); } async checkPrerequisites(operation: string): Promise<void> { const res = await ArduinoDeviceBase.isAvailable(); if (!res) { throw new DependentExtensionNotFoundError(operation, ExtensionName.Arduino); } } async compile(): Promise<boolean> { const result = await this.preCompileAction(); if (!result) { return false; } await utils.fetchAndExecuteTask( this.extensionContext, this.channel, this.telemetryContext, this.deviceFolder, OperationType.Compile, PlatformType.Arduino, constants.compileTaskName ); return true; } async upload(): Promise<boolean> { const result = await this.preUploadAction(); if (!result) { return false; } await utils.fetchAndExecuteTask( this.extensionContext, this.channel, this.telemetryContext, this.deviceFolder, OperationType.Upload, PlatformType.Arduino, constants.uploadTaskName ); return true; } abstract async configDeviceSettings(): Promise<void>; async load(): Promise<void> { const loadTimeScaffoldType = ScaffoldType.Workspace; if (!(await FileUtility.directoryExists(loadTimeScaffoldType, this.deviceFolder))) { throw new DirectoryNotFoundError( "load Arduino device", `device folder ${this.deviceFolder}`, "Please initialize the device first." ); } await this.generateCppPropertiesFile(loadTimeScaffoldType, this.board); } abstract async create(): Promise<void>; async createCore(): Promise<void> { // Generate template files const createTimeScaffoldType = ScaffoldType.Local; if (!(await FileUtility.directoryExists(createTimeScaffoldType, this.deviceFolder))) { throw new DirectoryNotFoundError( "create Arduino device", `device folder ${this.deviceFolder}`, "Please initialize the device first." ); } for (const fileInfo of this.templateFiles) { await utils.generateTemplateFile(this.deviceFolder, createTimeScaffoldType, fileInfo); } await this.generateCppPropertiesFile(createTimeScaffoldType, this.board); // Configurate device environment await this.configDeviceEnvironment(this.deviceFolder, createTimeScaffoldType); } // Backward compatibility: Check configuration abstract async preCompileAction(): Promise<boolean>; abstract async preUploadAction(): Promise<boolean>; abstract get version(): string; private async writeCppPropertiesFile(boardId: string, type: ScaffoldType, platform: string): Promise<void> { const cppPropertiesFilePath = path.join(this.vscodeFolderPath, constants.cppPropertiesFileName); if (await FileUtility.fileExists(type, cppPropertiesFilePath)) { return; } let cppPropertiesTemplateFileName: string; let changeRootPath = false; let rootPath: string = await utils.getHomeDir(); if (platform === OSPlatform.WIN32) { rootPath = path.join(rootPath, "AppData", "Local").replace(/\\/g, "\\\\"); cppPropertiesTemplateFileName = constants.cppPropertiesFileNameWin; changeRootPath = true; } else if (platform === OSPlatform.LINUX) { cppPropertiesTemplateFileName = constants.cppPropertiesFileNameLinux; changeRootPath = true; } else { // TODO: Let's use the MacOS template file for OS that is not win32/linux. // Revisit this part if want to support other OS. cppPropertiesTemplateFileName = constants.cppPropertiesFileNameMac; } const cppPropertiesTemplateFilePath = this.extensionContext.asAbsolutePath( path.join(FileNames.resourcesFolderName, FileNames.templatesFolderName, boardId, cppPropertiesTemplateFileName) ); const propertiesContent = await FileUtility.readFile(type, cppPropertiesTemplateFilePath); const propertiesContentString = propertiesContent.toString(); const versionPattern = /{VERSION}/g; let content = propertiesContentString.replace(versionPattern, this.version); if (changeRootPath) { const rootPathPattern = /{ROOTPATH}/g; content = content.replace(rootPathPattern, rootPath); } await FileUtility.writeFile(type, cppPropertiesFilePath, content); } async generateCppPropertiesFile(type: ScaffoldType, board: Board): Promise<void> { if (!(await FileUtility.directoryExists(type, this.vscodeFolderPath))) { await FileUtility.mkdirRecursively(type, this.vscodeFolderPath); } // Create c_cpp_properties.json file const platform = await utils.getPlatform(); await this.writeCppPropertiesFile(board.id, type, platform); } async generateCrc(channel: vscode.OutputChannel): Promise<void> { const devicePath = ConfigHandler.get<string>(ConfigKey.devicePath); if (!devicePath) { throw new WorkspaceConfigNotFoundError(ConfigKey.devicePath); } const rootPath = utils.getProjectDeviceRootPath(); if (!rootPath) { throw new WorkspaceNotOpenError("generate CRC"); } const deviceBuildLocation = path.join(rootPath, "..", devicePath, ".build"); if (!fs.isDirectorySync(deviceBuildLocation)) { throw new DirectoryNotFoundError( "generate CRC", "device build output folder", "Please compile the project first." ); } const binFiles = fs.listSync(deviceBuildLocation, ["bin"]); if (!binFiles || !binFiles.length) { throw new FileNotFoundError("generate CRC", "bin file", "Please compile the project first."); } let binFilePath = ""; if (binFiles.length === 1) { binFilePath = binFiles[0]; } else { const binFilePickItems: vscode.QuickPickItem[] = []; for (const file of binFiles) { const fileName = path.basename(file); binFilePickItems.push({ label: fileName, description: file }); } const choice = await vscode.window.showQuickPick(binFilePickItems, { ignoreFocusOut: true, matchOnDescription: true, matchOnDetail: true, placeHolder: "Select bin file" }); if (!choice || !choice.description) { throw new OperationCanceledError("Bin file selection cancelled."); } binFilePath = choice.description; } if (!binFilePath || !fs.existsSync(binFilePath)) { throw new FileNotFoundError("generate CRC", `bin file ${binFilePath}`, "Please compile the project first."); } const res = OTA.generateCrc(binFilePath); vscode.window.showInformationMessage("Generate CRC succeeded."); channel.show(); channel.appendLine("========== CRC Information =========="); channel.appendLine(""); channel.appendLine("fwPath: " + binFilePath); channel.appendLine("fwPackageCheckValue: " + res.crc); channel.appendLine("fwSize: " + res.size); channel.appendLine(""); channel.appendLine("======================================"); } async configDeviceEnvironment(deviceRootPath: string, scaffoldType: ScaffoldType): Promise<void> { if (!deviceRootPath) { throw new ArgumentEmptyOrNullError( "configurate device environment", "device root path", "Please open the folder and initialize project again." ); } const templateFilesInfo = await utils.getEnvTemplateFilesAndAskOverwrite( this.extensionContext, this.deviceFolder, scaffoldType, constants.environmentTemplateFolderName ); // Configure project environment with template files for (const fileInfo of templateFilesInfo) { await utils.generateTemplateFile(deviceRootPath, scaffoldType, fileInfo); } const message = "Arduino device configuration done."; utils.channelShowAndAppendLine(this.channel, message); } }
the_stack
import React, { Fragment, useState, createRef, ChangeEvent } from "react"; import { Dialog, Transition } from "@headlessui/react"; import { useForgotPasswordMutation, useLogoutMutation, useMeQuery, useUpdateNameMutation, } from "../../../generated/graphql"; import { useApolloClient } from "@apollo/client"; import { useRouter } from "next/router"; import { Spinner } from "../../shared/Spinner"; import Axios from "axios"; interface SettingsModalProps { open: boolean; setOpen: any; } export const SettingsModal: React.FC<SettingsModalProps> = ({ open, setOpen, }) => { const { data, loading } = useMeQuery(); const [name, setName] = useState(data && !loading && data?.me?.name); const [sentEmailLink, setSentEmailLink] = useState(false); const [forgotPasswordMutation] = useForgotPasswordMutation(); const client = useApolloClient(); const router = useRouter(); const [logout] = useLogoutMutation(); const [updateNameMutation] = useUpdateNameMutation(); const fileInputRef = createRef<HTMLInputElement>(); const forgotPassword = async () => { await forgotPasswordMutation({ variables: { email: data?.me?.email || "", }, }); setSentEmailLink(true); }; const logUserOut = async () => { await logout(); router.push("/"); await client.resetStore(); }; const updateName = async () => { await updateNameMutation({ variables: { name: name || data?.me?.name || "", }, }); await client.resetStore(); }; const uploadImage = async (event: ChangeEvent<HTMLInputElement>) => { const file = (event.target as any).files[0]; console.log(file); const formData = new FormData(); formData.append("file", file); formData.append("userId", data?.me?.id as any); try { await Axios.post( `${process.env.NEXT_PUBLIC_API_URL}/upload/avatar`, formData, { headers: { "Content-Type": "multipart/form-data" }, withCredentials: true, } ); await client.resetStore(); } catch (err) { console.log(err); } }; return ( <Transition.Root show={open} as={Fragment}> <Dialog as="div" className="fixed inset-0 z-10 overflow-y-auto" onClose={setOpen} > <div className="flex items-end justify-center min-h-screen px-4 pt-4 pb-20 text-center sm:block sm:p-0"> <Transition.Child as={Fragment} enter="ease-out duration-300" enterFrom="opacity-0" enterTo="opacity-100" leave="ease-in duration-200" leaveFrom="opacity-100" leaveTo="opacity-0" > <Dialog.Overlay className="fixed inset-0 transition-opacity bg-opacity-75 bg-black-500" /> </Transition.Child> {/* This element is to trick the browser into centering the modal contents. */} <span className="hidden sm:inline-block sm:align-middle sm:h-screen" aria-hidden="true" > &#8203; </span> <Transition.Child as={Fragment} enter="ease-out duration-300" enterFrom="opacity-0 translate-y-4 sm:translate-y-0 sm:scale-95" enterTo="opacity-100 translate-y-0 sm:scale-100" leave="ease-in duration-200" leaveFrom="opacity-100 translate-y-0 sm:scale-100" leaveTo="opacity-0 translate-y-4 sm:translate-y-0 sm:scale-95" > <div className="inline-block p-4 overflow-x-hidden overflow-y-scroll text-left align-bottom transition-all transform bg-white rounded shadow-xl dark:bg-black-700 sm:my-8 sm:align-middle sm:max-w-2xl sm:w-full" style={{ maxHeight: "35rem", }} > {data && !loading ? ( <> <h1 className="pb-1 mb-1 text-base font-medium text-gray-800 border-b border-gray-300 dark:text-gray-200 dark:border-gray-600"> Account </h1> <p className="mt-3 text-sm text-gray-800 dark:text-gray-400"> Photo </p> <img src={data.me?.imgUrl} alt={data.me?.name} className="w-20 h-20 mt-2 rounded-full" /> <div> <input type="file" hidden={true} ref={fileInputRef} onChange={uploadImage} /> <button onClick={() => { ( fileInputRef as any ).current.click(); }} className="px-2 py-1 mt-2 text-sm border border-gray-300 rounded-sm focus:outline-none hover:bg-gray-100 dark:text-gray-300 dark:hover:bg-gray-600 dark:border-gray-400" > Upload photo </button> </div> <hr className="my-3 border-t border-gray-300 dark:border-gray-600" /> <p className="mb-3 text-sm text-gray-800 dark:text-gray-300"> Personal Info </p> <p className="text-xs text-gray-500 dark:text-gray-400"> Email </p> <p className="text-sm text-gray-800 menlo dark:text-gray-200"> {data.me?.email} </p> <p className="mt-3 text-xs text-gray-500 dark:text-gray-300"> Name </p> <input className="w-full p-1 px-2 mt-2 text-sm bg-gray-100 border border-gray-300 rounded-sm dark:bg-black-700 focus:outline-none focus:ring focus:border-blue-100 dark:border-gray-600 dark:text-gray-200" value={name as any} onChange={(e) => setName(e.target.value) } /> {data && !loading && name != data.me?.name && ( <> <button onClick={updateName} className="px-2 py-1 mt-3 text-sm border border-gray-300 rounded-sm hover:bg-gray-100 dark:text-gray-300 dark:hover:bg-gray-600 dark:border-gray-400" > Update </button> </> )} <hr className="my-3 mt-5 border-t border-gray-300 dark:border-gray-600" /> <p className="mb-1 text-sm text-gray-800 dark:text-gray-300"> Password </p> <p className="text-xs text-gray-500 dark:text-gray-400"> Log out after reseting the password, to use it </p> <div className="flex items-center my-2 mt-4"> <button onClick={forgotPassword} className="px-2 py-1 text-sm border border-gray-300 rounded-sm hover:bg-gray-100 dark:text-gray-300 dark:hover:bg-gray-600 dark:border-gray-400" > Change password </button> </div> {sentEmailLink && ( <p className="mt-1 text-sm font-medium text-green-500"> We{"'"}ve sent an email with a link to change your password! </p> )} <hr className="my-3 mt-5 border-t border-gray-300 dark:border-gray-600" /> <p className="mb-1 text-sm text-gray-800 dark:text-gray-300"> Log out of all devices </p> <p className="text-xs text-gray-500 dark:text-gr"> You will be logged out of all other active sessions besides this one and will have to log back in. </p> <button onClick={logUserOut} className="px-3 py-1.5 mt-2 text-sm text-red-600 border border-red-300 rounded-sm hover:bg-red-50 dark:text-red-400 dark:border-red-400 dark:hover:bg-btn-dark" > Log out </button> <hr className="my-3 mt-5 border-t border-gray-300 dark:border-gray-600" /> <p className="mb-3 text-sm text-gray-800 dark:text-gray-300"> Danger zone Info </p> <button className="px-3 py-1.5 text-sm text-red-600 border border-red-300 rounded-sm hover:bg-red-50 dark:text-red-400 dark:border-red-400 dark:hover:bg-btn-dark"> Delete account </button> </> ) : ( <div className="flex flex-col items-center justify-center max-w-full min-h-screen dark:bg-gray-800"> <Spinner /> </div> )} </div> </Transition.Child> </div> </Dialog> </Transition.Root> ); };
the_stack
* Empty interface from which all entities inherit. */ export interface Entity { [k: string]: unknown; } /** * Cover some cases of objects with `rendered` property. */ interface Rendered { /** * Property of the object, transformed for display. */ rendered?: string; [k: string]: unknown; } /** * Base interface for all post type entities. * * Interfaces that extends from this one are: * - {@link PostEntity}. * - {@link PageEntity}. * - {@link AttachmentEntity}. * - {@link RevisionEntity}. */ export interface PostTypeEntity extends Entity { /** * The date the object was published, in the site's timezone. */ date?: string; /** * The date the object was published, as GMT. */ date_gmt?: string; /** * The globally unique identifier for the object. */ guid?: Rendered; /** * The date the object was last modified, in the site's timezone. */ modified?: string; /** * The date the object was last modified, as GMT. */ modified_gmt?: string; /** * Unique identifier for the object. */ id: number; /** * URL to the object. */ link: string; /** * An alphanumeric identifier for the object unique to its type. */ slug: string; /** * A named status for the object. */ status?: "publish" | "future" | "draft" | "pending" | "private"; /** * Type of Post for the object. */ type?: string; /** * The title for the object. */ title?: Rendered; /** * The ID for the author of the object. */ author?: number; /** * Whether or not comments are open on the object. */ comment_status?: "open" | "closed"; /** * Whether or not the object can be pinged. */ ping_status?: "open" | "closed"; } /** * Interface for entities from the /wp/v2/posts endpoint. */ export interface PostEntity extends PostTypeEntity { /** * Type of Post for the object. */ type: "post"; /** * The content for the object. */ content?: Rendered; /** * The excerpt for the object. */ excerpt?: Rendered; /** * The format for the object. */ format?: | "standard" | "aside" | "chat" | "gallery" | "link" | "image" | "quote" | "status" | "video" | "audio"; /** * Meta fields. */ meta?: Record<string, unknown>; /** * Whether or not the object should be treated as sticky. */ sticky?: boolean; /** * The theme file to use to display the object. */ template?: string; /** * The terms assigned to the object in the category taxonomy. */ categories?: number[]; /** * The terms assigned to the object in the post_tag taxonomy. */ tags?: number[]; /** * The ID of the featured media for the object. */ featured_media?: number; } /** * Interface for entities from the /wp/v2/posts/1/revisions endpoint. */ export interface RevisionEntity extends PostTypeEntity { /** * The ID for the author of the object. */ author?: number; /** * The ID for the parent of the object. */ parent?: number; /** * The content for the object. */ content?: Rendered; /** * The excerpt for the object. */ excerpt?: Rendered; } /** * Interface for entities from the /wp/v2/pages endpoint. */ export interface PageEntity extends PostTypeEntity { /** * Type of Post for the object. */ type: "page"; /** * The ID for the parent of the object. */ parent?: number; /** * The content for the object. */ content?: Rendered; /** * The excerpt for the object. */ excerpt?: Rendered; /** * The order of the object in relation to other object of its type. */ menu_order?: number; /** * Meta fields. */ meta?: Record<string, unknown>; /** * The theme file to use to display the object. */ template?: string; /** * The ID of the featured media for the object. */ featured_media?: number; } /** * Interface for entities from the /wp/v2/media endpoint. */ export interface AttachmentEntity extends PostTypeEntity { /** * Type of Post for the object. */ type: "attachment"; /** * Meta fields. */ meta?: Record<string, unknown>; /** * The theme file to use to display the object. */ template?: string; /** * Alternative text to display when attachment is not displayed. */ alt_text?: string; /** * The attachment caption. */ caption?: Rendered; /** * The attachment description. */ description?: Rendered; /** * Attachment type. */ media_type?: "image" | "file"; /** * The attachment MIME type. */ mime_type?: string; /** * Details about the media file, specific to its type. */ media_details?: { /** * The width of the attachment. */ width: number; /** * The height of the attachment. */ height: number; /** * The file path relative to `wp-content/uploads`. */ file: string; /** * The metadata of the attachment. */ image_meta: Record<string, unknown>; /** * The different sizes that WordPress created for this attachment. */ sizes: Record< string, { /** * The filename of this size. */ file: string; /** * The width of this size. */ width: number; /** * The height of this size. */ height: number; /** * The mime-type of this size. */ mime_type: string; /** * The complete URL of this size. */ source_url: string; } >; }; /** * The ID for the associated post of the attachment. */ post?: number; /** * URL to the original attachment file. */ source_url?: string; /** * List of the missing image sizes of the attachment. */ missing_image_sizes?: string[]; } /** * Interface for entities from the /wp/v2/types endpoint. */ export interface TypeEntity extends Entity { /** * A human-readable description of the post type. */ description?: string; /** * Whether or not the post type should have children. */ hierarchical?: boolean; /** * The title for the post type. */ name?: string; /** * An alphanumeric identifier for the post type. */ slug?: string; /** * REST base route for the post type. */ rest_base: string; /** * Taxonomies associated with post type. */ taxonomies: string[]; } /** * Interface for entities from the /wp/v2/taxonomy endpoint. */ export interface TaxonomyEntity extends Entity { /** * A human-readable description of the taxonomy. */ description?: string; /** * Whether or not the taxonomy should have children. */ hierarchical?: boolean; /** * The title for the taxonomy. */ name?: string; /** * An alphanumeric identifier for the taxonomy. */ slug?: string; /** * REST base route for the taxonomy. */ rest_base: string; /** * Types associated with the taxonomy. */ types: string[]; } /** * Interface for entities that belong to a taxonomy. * * For example: * - entities from the /wp/v2/categories endpoint. * - entities from the /wp/v2/tags endpoint. */ export interface TermEntity extends Entity { /** * Unique identifier for the term. */ id: number; /** * Number of published posts for the term. */ count?: number; /** * HTML description of the term. */ description?: string; /** * URL of the term. */ link: string; /** * HTML title for the term. */ name?: string; /** * An alphanumeric identifier for the term unique to its type. */ slug?: string; /** * Type attribution for the term. */ taxonomy: string; /** * The parent term ID. */ parent?: number; /** * Meta fields. */ meta?: Record<string, unknown>; } /** * Map of avatar URLs by their size. */ export interface AvatarUrls { /** * Avatar URL with image size of 24 pixels. */ "24"?: string; /** * Avatar URL with image size of 48 pixels. */ "48"?: string; /** * Avatar URL with image size of 96 pixels. */ "96"?: string; [k: string]: unknown; } /** * Interface for entities from the /wp/v2/users endpoint. */ export interface AuthorEntity extends Entity { /** * Unique identifier for the user. */ id: number; /** * Display name for the user. */ name?: string; /** * URL of the user. */ url?: string; /** * Description of the user. */ description?: string; /** * Author URL of the user. */ link: string; /** * An alphanumeric identifier for the user. */ slug?: string; /** * Avatar URLs for the user. */ avatar_urls?: AvatarUrls; /** * Meta fields. */ meta?: Record<string, unknown>; } /** * Interface for entities from the /wp/v2/comments endpoint. */ export interface CommentEntity extends Entity { /** * Unique identifier for the object. */ id?: number; /** * The ID of the user object, if author was a user. */ author?: number; /** * Email address for the object author. */ author_email?: string; /** * Display name for the object author. */ author_name?: string; /** * URL for the object author. */ author_url?: string; /** * The content for the object. */ content?: Rendered; /** * The date the object was published, in the site's timezone. */ date?: string; /** * The date the object was published, as GMT. */ date_gmt?: string; /** * URL to the object. */ link?: string; /** * The ID for the parent of the object. */ parent?: number; /** * The ID of the associated post object. */ post?: number; /** * State of the object. */ status?: string; /** * Type of Comment for the object. */ type: "comment"; /** * Avatar URLs for the object author. */ author_avatar_urls?: AvatarUrls; /** * Meta fields. */ meta?: Record<string, unknown>; }
the_stack
import { async, ComponentFixture, TestBed } from '@angular/core/testing'; import { By } from '@angular/platform-browser'; import { FormsModule } from '@angular/forms'; import { RouterTestingModule } from '@angular/router/testing'; import { TooltipModule } from 'ngx-bootstrap'; import { VerticalNavigationComponent } from './vertical-navigation.component'; import { VerticalNavigationItem } from './vertical-navigation-item'; import { WindowReference } from '../../utilities/window.reference'; describe('Vertical Navigation component - ', () => { let comp: VerticalNavigationComponent; let fixture: ComponentFixture<VerticalNavigationComponent>; let navigationItems: VerticalNavigationItem[]; let navigateItem, clickItem; beforeEach(() => { clickItem = undefined; navigateItem = undefined; navigationItems = [ { title: 'Dashboard', iconStyleClass: 'fa fa-dashboard', url: '#/dashboard' }, { title: 'Dolor', iconStyleClass: 'fa fa-shield', url: '#/dolor', badges: [ { count: 1283, tooltip: 'Total number of items' } ] }, { title: 'Ipsum', iconStyleClass: 'fa fa-space-shuttle', activeOnLoad: true, children: [ { title: 'Intellegam', activeOnLoad: true, children: [ { title: 'Recteque', url: '#/ipsum/intellegam/recteque', badges: [ { count: 6, tooltip: 'Total number of error items', badgeClass: 'example-error-background' } ] }, { title: 'Suavitate', url: '#/ipsum/intellegam/suavitate', badges: [ { count: 0, tooltip: 'Total number of items', badgeClass: 'example-ok-background' } ] }, { title: 'Vituperatoribus', url: '#/ipsum/intellegam/vituperatoribus', badges: [ { count: 18, tooltip: 'Total number of warning items', badgeClass: 'example-warning-background' } ] } ] }, { title: 'Copiosae', children: [ { title: 'Exerci', url: '#/ipsum/copiosae/exerci' }, { title: 'Quaeque', url: '#/ipsum/copiosae/quaeque' }, { title: 'Utroque', url: '#/ipsum/copiosae/utroque' } ] }, { title: 'Patrioque', children: [ { title: 'Novum', url: '#/ipsum/patrioque/novum' }, { title: 'Pericula', url: '#/ipsum/patrioque/pericula' }, { title: 'Gubergren', url: '#/ipsum/patrioque/gubergren' } ] }, { title: 'Accumsan', url: '#/ipsum/Accumsan' } ] }, { title: 'Amet', iconStyleClass: 'fa fa-paper-plane', children: [ { title: 'Detracto', children: [ { title: 'Delicatissimi', url: '#/amet/detracto/delicatissimi' }, { title: 'Aliquam', url: '#/amet/detracto/aliquam' }, { title: 'Principes', url: '#/amet/detracto/principes' } ] }, { title: 'Mediocrem', children: [ { title: 'Convenire', url: '#/amet/mediocrem/convenire' }, { title: 'Nonumy', url: '#/amet/mediocrem/nonumy' }, { title: 'Deserunt', url: '#/amet/mediocrem/deserunt' } ] }, { title: 'Corrumpit', children: [ { title: 'Aeque', url: '#/amet/corrumpit/aeque' }, { title: 'Delenit', url: '#/amet/corrumpit/delenit' }, { title: 'Qualisque', url: '#/amet/corrumpit/qualisque' } ] }, { title: 'urbanitas', url: '#/amet/urbanitas' } ] }, { title: 'Adipscing', iconStyleClass: 'fa fa-graduation-cap', url: '#/adipscing' }, { title: 'Lorem', iconStyleClass: 'fa fa-gamepad', url: '#/lorem' } ]; }); beforeEach(async(() => { TestBed.configureTestingModule({ imports: [FormsModule, TooltipModule.forRoot(), RouterTestingModule], declarations: [VerticalNavigationComponent], providers: [WindowReference] }) .compileComponents() .then(() => { fixture = TestBed.createComponent(VerticalNavigationComponent); comp = fixture.componentInstance; comp.navigationEvent.subscribe((item: any) => { navigateItem = item.title; }); comp.itemClickEvent.subscribe((item: any) => { clickItem = item.title; }); comp.items = navigationItems; comp.brandAlt = 'PATTERNFLY'; comp.pinnableMenus = true; comp.showBadges = true; comp.updateActiveItemsOnClick = true; comp.ignoreMobile = true; fixture.detectChanges(); }); })); it('should add the vertical navigation menus', () => { let primaryMenu = fixture.debugElement.query(By.css('.nav-pf-vertical')); expect(primaryMenu).not.toBeNull(); let primaryItems = fixture.debugElement.queryAll( By.css('.nav-pf-vertical > .list-group > .list-group-item')); expect(primaryItems.length).toBe(6); let secondaryMenu = primaryItems[2].query(By.css('.nav-pf-secondary-nav')); expect(secondaryMenu).not.toBeNull(); let secondaryItems = secondaryMenu.queryAll( By.css('.nav-pf-secondary-nav > .list-group > .list-group-item')); expect(secondaryItems.length).toBe(4); let tertiaryMenu = secondaryItems[0].query(By.css('.nav-pf-tertiary-nav')); expect(tertiaryMenu).not.toBeNull(); let tertiaryItems = tertiaryMenu.queryAll(By.css('.nav-pf-tertiary-nav > .list-group > .list-group-item')); expect(tertiaryItems.length).toBe(3); }); it('should pin menus when specified', () => { let collased = fixture.debugElement.query(By.css('.collapsed-secondary-nav-pf.nav')); expect(collased).toBeNull(); collased = fixture.debugElement.query(By.css('.collapsed-tertiary-nav-pf')); expect(collased).toBeNull(); let primaryItems = fixture.debugElement.queryAll( By.css('.nav-pf-vertical > .list-group > .list-group-item')); expect(primaryItems.length).toBe(6); // third item is active, use it to check for pin icon let secondaryMenu = primaryItems[2].query(By.css('.nav-pf-secondary-nav')); expect(secondaryMenu).not.toBeNull(); let collapseToggle = secondaryMenu.queryAll(By.css('.secondary-collapse-toggle-pf')); expect(collapseToggle.length).toBe(1); collapseToggle[0].triggerEventHandler('click', {}); fixture.detectChanges(); collased = fixture.debugElement.query(By.css('.collapsed-secondary-nav-pf')); expect(collased).not.toBeNull(); collased = fixture.debugElement.query(By.css('.collapsed-tertiary-nav-pf')); expect(collased).toBeNull(); let secondaryItems = secondaryMenu.queryAll( By.css('.nav-pf-secondary-nav > .list-group > .list-group-item')); expect(secondaryItems.length).toBe(4); let tertiaryMenu = secondaryItems[0].queryAll(By.css('.nav-pf-tertiary-nav')); expect(tertiaryMenu.length).toBe(1); collapseToggle = tertiaryMenu[0].queryAll(By.css('.tertiary-collapse-toggle-pf')); expect(collapseToggle.length).toBe(1); collapseToggle[0].triggerEventHandler('click', {}); fixture.detectChanges(); collased = fixture.debugElement.query(By.css('.collapsed-tertiary-nav-pf')); expect(collased).not.toBeNull(); }); it('should not show icons', () => { comp.showIcons = false; fixture.detectChanges(); let primaryItems = fixture.debugElement.queryAll( By.css('.nav-pf-vertical > .list-group > .list-group-item')); expect(primaryItems.length).toBe(6); let iconSpan = primaryItems[0].query(By.css('.list-group-item > a > span')); expect(iconSpan.classes['hidden']).toBeTruthy(); }); it('should go to collapse mode when collpase toggle is clicked', () => { let menu = fixture.debugElement.query(By.css('.nav-pf-vertical')); expect(menu).not.toBeNull(); let collapsedMenu = fixture.debugElement.query(By.css('.nav-pf-vertical.collapsed')); expect(collapsedMenu).toBeNull(); let navBarToggle = fixture.debugElement.query(By.css('.navbar-header .navbar-toggle')); expect(navBarToggle).not.toBeNull(); navBarToggle.triggerEventHandler('click', {}); fixture.detectChanges(); menu = fixture.debugElement.query(By.css('.nav-pf-vertical')); expect(menu).not.toBeNull(); collapsedMenu = fixture.debugElement.query(By.css('.nav-pf-vertical.collapsed')); expect(collapsedMenu).not.toBeNull(); }); it('should show the alternate text when specified', () => { comp.brandSrc = ''; comp.showIcons = true; fixture.detectChanges(); let brandIcon = fixture.debugElement.queryAll(By.css('.navbar-brand-icon')); expect(brandIcon.length).toBe(0); let brandText = fixture.debugElement.queryAll(By.css('.navbar-brand-txt')); expect(brandText.length).toBe(1); }); it('should invoke the navigateCallback when an item is clicked', () => { expect(navigateItem).toBeUndefined(); let primaryItems = fixture.debugElement.queryAll( By.css('.nav-pf-vertical > .list-group > .list-group-item > a')); expect(primaryItems.length).toBe(6); primaryItems[0].triggerEventHandler('click', {}); fixture.detectChanges(); expect(navigateItem).toBe(navigationItems[0].title); // Clicking a non-final item primaryItems[2].triggerEventHandler('click', {}); fixture.detectChanges(); expect(navigateItem).toBe(navigationItems[2].children[0].children[0].title); }); it('should invoke the itemClickCallback when any item is clicked', () => { expect(clickItem).toBeUndefined(); let primaryItems = fixture.debugElement.queryAll( By.css('.nav-pf-vertical > .list-group > .list-group-item > a')); expect(primaryItems.length).toBe(6); primaryItems[0].triggerEventHandler('click', {}); fixture.detectChanges(); expect(clickItem).toBe(navigationItems[0].title); // Clicking a non-final item primaryItems[2].triggerEventHandler('click', {}); fixture.detectChanges(); expect(clickItem).toBe(navigationItems[2].title); }); it('should set active items on primary item click when updateActiveItemsOnClick is true', () => { let primaryItems = fixture.debugElement.queryAll( By.css('.nav-pf-vertical > .list-group > .list-group-item > a')); expect(primaryItems.length).toBe(6); primaryItems[0].triggerEventHandler('click', {}); fixture.detectChanges(); expect(clickItem).toBe(navigationItems[0].title); let activePrimary = fixture.debugElement.queryAll( By.css('.nav-pf-vertical > .list-group > .list-group-item.active')); expect(activePrimary.length).toBe(1); let activeSecondary = fixture.debugElement.queryAll( By.css('.nav-pf-secondary-nav > .list-group > .list-group-item.active')); expect(activeSecondary.length).toBe(0); let activeTertiary = fixture.debugElement.queryAll( By.css('.nav-pf-tertiary-nav > .list-group > .list-group-item.active')); expect(activeTertiary.length).toBe(0); expect(navigateItem).toBe(navigationItems[0].title); // Clicking a non-final item will set active items on sub menus primaryItems[2].triggerEventHandler('click', {}); fixture.detectChanges(); expect(clickItem).toBe(navigationItems[2].title); activePrimary = fixture.debugElement.queryAll( By.css('.nav-pf-vertical > .list-group > .list-group-item.active')); expect(activePrimary.length).toBe(1); activeSecondary = fixture.debugElement.queryAll( By.css('.nav-pf-secondary-nav > .list-group > .list-group-item.active')); expect(activeSecondary.length).toBe(1); activeTertiary = fixture.debugElement.queryAll( By.css('.nav-pf-tertiary-nav > .list-group > .list-group-item.active')); expect(activeTertiary.length).toBe(1); expect(navigateItem).toBe(navigationItems[2].children[0].children[0].title); }); it('should set active items on secondary item click when updateActiveItemsOnClick is true', () => { let primaryItems = fixture.debugElement.queryAll( By.css('.nav-pf-vertical > .list-group > .list-group-item')); expect(primaryItems.length).toBe(6); let secondaryItems = primaryItems[2].queryAll( By.css('.nav-pf-secondary-nav > .list-group > .list-group-item > a')); expect(secondaryItems.length).toBe(4); // Clicking a non-final item will set active items on self, parent, and first sub item secondaryItems[2].triggerEventHandler('click', {}); fixture.detectChanges(); let activePrimary = fixture.debugElement.queryAll( By.css('.nav-pf-vertical > .list-group > .list-group-item.active')); expect(activePrimary.length).toBe(1); let activeSecondary = fixture.debugElement.queryAll( By.css('.nav-pf-secondary-nav > .list-group > .list-group-item.active')); expect(activeSecondary.length).toBe(1); let activeTertiary = fixture.debugElement.queryAll( By.css('.nav-pf-tertiary-nav > .list-group > .list-group-item.active')); expect(activeTertiary.length).toBe(1); // Clicking a final item will set active items on self and parent secondaryItems[3].triggerEventHandler('click', {}); fixture.detectChanges(); activePrimary = fixture.debugElement.queryAll( By.css('.nav-pf-vertical > .list-group > .list-group-item.active')); expect(activePrimary.length).toBe(1); activeSecondary = fixture.debugElement.queryAll( By.css('.nav-pf-secondary-nav > .list-group > .list-group-item.active')); expect(activeSecondary.length).toBe(1); activeTertiary = fixture.debugElement.queryAll( By.css('.nav-pf-tertiary-nav > .list-group > .list-group-item.active')); expect(activeTertiary.length).toBe(0); expect(navigateItem).toBe(navigationItems[2].children[3].title); }); it('should set active items on tertiary item click when updateActiveItemsOnClick is true', () => { let primaryItems = fixture.debugElement.queryAll( By.css('.nav-pf-vertical > .list-group > .list-group-item')); expect(primaryItems.length).toBe(6); let secondaryItems = primaryItems[2].queryAll( By.css('.nav-pf-secondary-nav > .list-group > .list-group-item')); expect(secondaryItems.length).toBe(4); let tertiaryItems = secondaryItems[2].queryAll( By.css('.nav-pf-tertiary-nav > .list-group > .list-group-item > a')); expect(tertiaryItems.length).toBe(3); // Clicking a non-final item will set active items on self, parent, and first sub item tertiaryItems[1].triggerEventHandler('click', {}); fixture.detectChanges(); let activePrimary = fixture.debugElement.queryAll( By.css('.nav-pf-vertical > .list-group > .list-group-item.active')); expect(activePrimary.length).toBe(1); let activeSecondary = fixture.debugElement.queryAll( By.css('.nav-pf-secondary-nav > .list-group > .list-group-item.active')); expect(activeSecondary.length).toBe(1); let activeTertiary = fixture.debugElement.queryAll( By.css('.nav-pf-tertiary-nav > .list-group > .list-group-item.active')); expect(activeTertiary.length).toBe(1); expect(navigateItem).toBe(navigationItems[2].children[2].children[1].title); // Clicking a final item will set active items on self and parent secondaryItems[3].triggerEventHandler('click', {}); fixture.detectChanges(); }); it('should not update active items when updateActiveItemsOnClick is not true', function() { comp.updateActiveItemsOnClick = false; fixture.detectChanges(); let primaryItems = fixture.debugElement.queryAll( By.css('.nav-pf-vertical > .list-group > .list-group-item > a')); expect(primaryItems.length).toBe(6); primaryItems[0].triggerEventHandler('click', {}); fixture.detectChanges(); expect(clickItem).toBe(navigationItems[0].title); expect(navigateItem).toBe(navigationItems[0].title); primaryItems[2].triggerEventHandler('click', {}); fixture.detectChanges(); expect(clickItem).toBe(navigationItems[2].title); expect(navigateItem).toBe(navigationItems[2].children[0].children[0].title); }); it('should add badges', function() { let primaryMenu = fixture.debugElement.query(By.css('.nav-pf-vertical')); expect(primaryMenu).not.toBeNull(); let primaryItems = primaryMenu.queryAll(By.css('.nav-pf-vertical> .list-group > .list-group-item')); expect(primaryItems.length).toBe(6); let badges = primaryItems[1].queryAll(By.css('.badge')); expect(badges.length).toBe(1); let secondaryMenu = primaryItems[2].query(By.css('.nav-pf-secondary-nav')); expect(secondaryMenu).not.toBeNull(); let secondaryItems = secondaryMenu.queryAll( By.css('.nav-pf-secondary-nav > .list-group > .list-group-item')); expect(secondaryItems.length).toBe(4); let tertiaryMenu = secondaryItems[0].query(By.css('.nav-pf-tertiary-nav')); expect(tertiaryMenu).not.toBeNull(); let tertiaryBadges = tertiaryMenu.queryAll(By.css('.badge')); expect(tertiaryBadges.length).toBe(3); }); it('should set classes on badges', function() { let primaryMenu = fixture.debugElement.query(By.css('.nav-pf-vertical')); expect(primaryMenu).not.toBeNull(); let primaryItems = primaryMenu.queryAll(By.css('.nav-pf-vertical > .list-group > .list-group-item')); expect(primaryItems.length).toBe(6); let secondaryMenu = primaryItems[2].query(By.css('.nav-pf-secondary-nav')); expect(secondaryMenu).not.toBeNull(); let secondaryItems = secondaryMenu.queryAll( By.css('.nav-pf-secondary-nav > .list-group > .list-group-item')); expect(secondaryItems.length).toBe(4); let tertiaryMenu = secondaryItems[0].query(By.css('.nav-pf-tertiary-nav')); expect(tertiaryMenu).not.toBeNull(); let errorBadge = tertiaryMenu.queryAll(By.css('.badge.example-error-background')); expect(errorBadge.length).toBe(1); let warningBadge = tertiaryMenu.queryAll(By.css('.badge.example-warning-background')); expect(warningBadge.length).toBe(1); }); it('should not show badges with a 0 count', function() { let primaryMenu = fixture.debugElement.query(By.css('.nav-pf-vertical')); expect(primaryMenu).not.toBeNull(); let primaryItems = primaryMenu.queryAll(By.css('.nav-pf-vertical > .list-group > .list-group-item')); expect(primaryItems.length).toBe(6); let secondaryMenu = primaryItems[2].query(By.css('.nav-pf-secondary-nav')); expect(secondaryMenu).not.toBeNull(); let secondaryItems = secondaryMenu.queryAll( By.css('.nav-pf-secondary-nav > .list-group > .list-group-item')); expect(secondaryItems.length).toBe(4); let tertiaryMenu = secondaryItems[0].query(By.css('.nav-pf-tertiary-nav')); expect(tertiaryMenu).not.toBeNull(); let errorBadge = tertiaryMenu.queryAll(By.css('.badge.example-error-background > span')); expect(errorBadge.length).toBe(1); let warningBadge = tertiaryMenu.queryAll(By.css('.badge.example-warning-background > span')); expect(warningBadge.length).toBe(1); warningBadge = tertiaryMenu.queryAll(By.css('.example-ok-background > span')); expect(warningBadge.length).toBe(0); }); it('should not show badges when show-badges is not set', function() { let badgesMenu = fixture.debugElement.query(By.css('.nav-pf-vertical.nav-pf-vertical-with-badges')); expect(badgesMenu).not.toBeNull(); let badgesShown = fixture.debugElement.query(By.css('.badge-container-pf')); expect(badgesShown).not.toBeNull(); comp.showBadges = false; fixture.detectChanges(); badgesMenu = fixture.debugElement.query(By.css('.nav-pf-vertical-with-badges')); expect(badgesMenu).toBeNull(); badgesShown = fixture.debugElement.query(By.css('.badge-container-pf')); expect(badgesShown).toBeNull(); }); it('should show initially collapsed menu', function() { let badgesMenu = fixture.debugElement.query(By.css('.nav-pf-vertical.nav-pf-vertical-with-badges.collapsed')); expect(badgesMenu).toBeNull(); comp.showMenuCollapsed = true; fixture.detectChanges(); badgesMenu = fixture.debugElement.query(By.css('.nav-pf-vertical-with-badges.collapsed')); expect(badgesMenu).toBeNull(); }); });
the_stack
import { useFruitManageHandler } from "../utils/useFruitManageHandler"; // @ts-ignore import mdbid from "mdbid"; import { CmsEntry, CmsModel } from "~/types"; import { setupContentModelGroup, setupContentModels } from "../utils/setup"; const NUMBER_OF_FRUITS = 200; jest.setTimeout(100000); const createFruitData = (counter: number): CmsEntry => { const entryId = mdbid(); const id = `${entryId}#${String(counter).padStart(4, "0")}`; return { id, entryId, version: counter, webinyVersion: "version", modelId: "fruit", createdBy: { id: "admin", type: "admin", displayName: "Admin" }, tenant: "root", publishedOn: new Date().toISOString(), locale: "en-US", ownedBy: { id: "admin", displayName: "Admin", type: "admin" }, values: { name: `Fruit ${counter}`, isSomething: false, rating: 450, numbers: [5, 6, 7.2, 10.18, 12.05], email: "john@doe.com", url: `https://fruit.test/${counter}`, lowerCase: `fruit${counter}`, upperCase: `BANANA${counter}`, date: "2020-12-03", dateTime: new Date("2020-12-03T12:12:21").toISOString(), dateTimeZ: "2020-12-03T14:52:41+01:00", time: "11:59:01", description: `fruit ${counter}`, slug: `fruit-${counter}` }, savedOn: new Date().toISOString(), createdOn: new Date().toISOString(), status: "draft", locked: false }; }; describe("entry pagination", () => { const manageOpts = { path: "manage/en-US" }; let fruitContentModel: CmsModel; const manager = useFruitManageHandler(manageOpts); const { storageOperations, until } = manager; /** * We need to create N fruit entries */ beforeEach(async () => { const group = await setupContentModelGroup(manager); await setupContentModels(manager, group, ["fruit"]); fruitContentModel = (await storageOperations.models.get({ locale: "en-US", tenant: "root", modelId: "fruit" })) as CmsModel; for (let i = 1; i <= NUMBER_OF_FRUITS; i++) { const fruit = createFruitData(i); await storageOperations.entries.create(fruitContentModel, { storageEntry: fruit, entry: fruit }); } }); it("should paginate through entries", async () => { await until( () => manager .listFruits({ limit: 1 }) .then(([data]) => data), ({ data }: any) => { return data.listFruits.meta.totalCount === NUMBER_OF_FRUITS; }, { name: "list all fruits", tries: 20, debounce: 2000, wait: 2000 } ); /** * List items from 0-37 */ const [list0x37Response] = await manager.listFruits({ limit: 37, sort: ["createdOn_DESC"] }); expect(list0x37Response).toMatchObject({ data: { listFruits: { data: expect.any(Array), meta: { totalCount: 200, hasMoreItems: true, cursor: expect.any(String) }, error: null } } }); expect(list0x37Response.data.listFruits.data).toHaveLength(37); /** * First item in data array should have version 200 - because we sort by createdOn_DESC */ expect(list0x37Response.data.listFruits.data[0]).toMatchObject({ meta: { version: 200 } }); const cursor0x37 = list0x37Response.data.listFruits.meta.cursor; /** * List items 37 - 109 (limit 72) */ const [limit37x109Response] = await manager.listFruits({ limit: 72, after: cursor0x37, sort: ["createdOn_DESC"] }); expect(limit37x109Response).toMatchObject({ data: { listFruits: { data: expect.any(Array), meta: { totalCount: 200, hasMoreItems: true, cursor: expect.any(String) }, error: null } } }); expect(limit37x109Response.data.listFruits.data).toHaveLength(72); /** * First item in data array should have version 200 - 37 */ expect(limit37x109Response.data.listFruits.data[0]).toMatchObject({ meta: { version: 163 } }); const cursor37x109 = limit37x109Response.data.listFruits.meta.cursor; /** * List items 109 - 211 (limit 102) */ const [limit109x211Response] = await manager.listFruits({ limit: 102, after: cursor37x109, sort: ["createdOn_DESC"] }); expect(limit109x211Response).toMatchObject({ data: { listFruits: { data: expect.any(Array), meta: { totalCount: 200, hasMoreItems: false, cursor: null }, error: null } } }); expect(limit109x211Response.data.listFruits.data).toHaveLength(91); /** * First item in data array should have version 91 */ expect(limit109x211Response.data.listFruits.data[0]).toMatchObject({ meta: { version: 91 } }); /** * Last item in data array should have version 1 */ expect(limit109x211Response.data.listFruits.data.concat([]).pop()).toMatchObject({ meta: { version: 1 } }); /** * Next we will paginate with limit 8 */ const maxLimit8Runs = Math.ceil(NUMBER_OF_FRUITS / 8); let currentLimit8Run = 0; let limit8LastCursor = ""; /** * We limit with max runs because of possible infinite loop. Just in case... */ while (limit8LastCursor !== null && currentLimit8Run < maxLimit8Runs) { const [limit8Response] = await manager.listFruits({ limit: 8, after: limit8LastCursor, sort: ["createdOn_DESC"] }); expect(limit8Response).toMatchObject({ data: { listFruits: { data: expect.any(Array), meta: { hasMoreItems: expect.any(Boolean), totalCount: 200 } } } }); const firstItem = limit8Response.data.listFruits.data.concat([]).shift(); const lastItem = limit8Response.data.listFruits.data.concat([]).pop(); expect(firstItem).toMatchObject({ meta: { version: NUMBER_OF_FRUITS - currentLimit8Run * 8 } }); const lastVersion = NUMBER_OF_FRUITS - (currentLimit8Run + 1) * 8 + 1; expect(lastItem).toMatchObject({ meta: { version: lastVersion < 1 ? 1 : lastVersion } }); limit8LastCursor = limit8Response.data.listFruits.meta.cursor; currentLimit8Run++; } /** * Last run (currentLimit8Run counter) should never be different than max runs. */ expect(currentLimit8Run).toEqual(maxLimit8Runs); /** * Next we will paginate with limit 13 */ const maxLimit13Runs = Math.ceil(NUMBER_OF_FRUITS / 13); let currentLimit13Run = 0; let limit13LastCursor = ""; /** * We limit with max runs because of possible infinite loop. Just in case... */ while (limit13LastCursor !== null && currentLimit13Run < maxLimit13Runs) { const [limit13Response] = await manager.listFruits({ limit: 13, after: limit13LastCursor, sort: ["createdOn_DESC"] }); expect(limit13Response).toMatchObject({ data: { listFruits: { data: expect.any(Array), meta: { hasMoreItems: expect.any(Boolean), totalCount: 200 } } } }); const firstItem = limit13Response.data.listFruits.data.concat([]).shift(); const lastItem = limit13Response.data.listFruits.data.concat([]).pop(); expect(firstItem).toMatchObject({ meta: { version: NUMBER_OF_FRUITS - currentLimit13Run * 13 } }); const lastVersion = NUMBER_OF_FRUITS - (currentLimit13Run + 1) * 13 + 1; expect(lastItem).toMatchObject({ meta: { version: lastVersion < 1 ? 1 : lastVersion } }); limit13LastCursor = limit13Response.data.listFruits.meta.cursor; currentLimit13Run++; } /** * Last run (currentLimit13Run counter) should never be different than max runs. */ expect(currentLimit13Run).toEqual(maxLimit13Runs); }); });
the_stack
import * as assert from 'assert'; import * as grpc from '@grpc/grpc-js'; import * as sinon from 'sinon'; import * as vscode from 'vscode'; import {TestMemento, mocks} from '../mocks/vscode'; import {EventEmitter} from 'stream'; import {ListenResponse} from '../../src/rpc/listen_pb'; import {NoDaemonCommandError} from '../../src/daemon/types'; import {StripeCLIClient} from '../../src/rpc/commands_grpc_pb'; import {StripeClient} from '../../src/stripeClient'; import {StripeDaemon} from '../../src/daemon/stripeDaemon'; import {StripeEvent} from '../../src/rpc/common_pb'; import {StripeEventsViewProvider} from '../../src/stripeEventsView'; suite('stripeEventsView', () => { let sandbox: sinon.SinonSandbox; const workspaceState = new TestMemento(); const extensionContext = {...mocks.extensionContextMock, workspaceState: workspaceState}; const stripeClient = <Partial<StripeClient>>{ getCLIPath: () => Promise.resolve('/path/to/cli'), promptUpdateForDaemon: () => {}, promptLogin: () => {}, }; const stripeDaemon = <Partial<StripeDaemon>>{ setupClient: () => {}, }; let listenStream: grpc.ClientReadableStream<ListenResponse>; let daemonClient: Partial<StripeCLIClient>; setup(() => { sandbox = sinon.createSandbox(); listenStream = <grpc.ClientReadableStream<ListenResponse>>new EventEmitter(); listenStream.cancel = () => {}; listenStream.destroy = () => {}; daemonClient = { listen: () => listenStream, }; }); teardown(() => { sandbox.restore(); }); suite('startStreaming', () => { setup(() => { sandbox.stub(stripeDaemon, 'setupClient').resolves(daemonClient); }); suite('state transitions', () => { test('renders loading state when stream is LOADING', async () => { const stripeEventsView = new StripeEventsViewProvider( <any>stripeClient, <any>stripeDaemon, extensionContext, ); await stripeEventsView.startStreaming(); // Make sure we start in the idle state const doneResponse = new ListenResponse(); doneResponse.setState(ListenResponse.State.STATE_DONE); listenStream.emit('data', doneResponse); const loadingResponse = new ListenResponse(); loadingResponse.setState(ListenResponse.State.STATE_LOADING); listenStream.emit('data', loadingResponse); const treeItems = await stripeEventsView.buildTree(); // Simulate view refresh const labels = treeItems.map(({label}) => label); const expectedLabel = 'Starting streaming events ...'; assert.strictEqual( labels.includes(expectedLabel), true, `Expected [${labels.toString()}] to contain ${expectedLabel}`, ); }); test('renders loading state when stream is RECONNECTING', async () => { const stripeEventsView = new StripeEventsViewProvider( <any>stripeClient, <any>stripeDaemon, extensionContext, ); await stripeEventsView.startStreaming(); // Make sure we start in the idle state const doneResponse = new ListenResponse(); doneResponse.setState(ListenResponse.State.STATE_DONE); listenStream.emit('data', doneResponse); const reconnectingResponse = new ListenResponse(); reconnectingResponse.setState(ListenResponse.State.STATE_RECONNECTING); listenStream.emit('data', reconnectingResponse); const treeItems = await stripeEventsView.buildTree(); // Simulate view refresh const labels = treeItems.map(({label}) => label); const expectedLabel = 'Starting streaming events ...'; assert.strictEqual( labels.includes(expectedLabel), true, `Expected [${labels.toString()}] to contain ${expectedLabel}`, ); }); test('renders ready state when stream is READY', async () => { const stripeEventsView = new StripeEventsViewProvider( <any>stripeClient, <any>stripeDaemon, extensionContext, ); await stripeEventsView.startStreaming(); // Make sure we start in the streaming state const doneResponse = new ListenResponse(); doneResponse.setState(ListenResponse.State.STATE_DONE); listenStream.emit('data', doneResponse); const readyResponse = new ListenResponse(); readyResponse.setState(ListenResponse.State.STATE_READY); listenStream.emit('data', readyResponse); const treeItems = await stripeEventsView.buildTree(); // Simulate view refresh const labels = treeItems.map(({label}) => label); const expectedLabel = 'Stop streaming events'; assert.strictEqual( labels.includes(expectedLabel), true, `Expected [${labels.toString()}] to contain ${expectedLabel}`, ); }); test('renders idle state when stream is DONE', async () => { const stripeEventsView = new StripeEventsViewProvider( <any>stripeClient, <any>stripeDaemon, extensionContext, ); await stripeEventsView.startStreaming(); // Make sure we start in the streaming state const readyResponse = new ListenResponse(); readyResponse.setState(ListenResponse.State.STATE_READY); listenStream.emit('data', readyResponse); const doneResponse = new ListenResponse(); doneResponse.setState(ListenResponse.State.STATE_DONE); listenStream.emit('data', doneResponse); const treeItems = await stripeEventsView.buildTree(); // Simulate view refresh const labels = treeItems.map(({label}) => label); const expectedLabel = 'Start streaming events'; assert.strictEqual( labels.includes(expectedLabel), true, `Expected [${labels.toString()}] to contain ${expectedLabel}`, ); }); test('renders idle state when stream is receives unknown state', async () => { const stripeEventsView = new StripeEventsViewProvider( <any>stripeClient, <any>stripeDaemon, extensionContext, ); await stripeEventsView.startStreaming(); // Make sure we start in the ready state const readyResponse = new ListenResponse(); readyResponse.setState(ListenResponse.State.STATE_READY); listenStream.emit('data', readyResponse); const unknownStateResponse = new ListenResponse(); unknownStateResponse.setState(<any>-1); // This should be impossible listenStream.emit('data', unknownStateResponse); const treeItems = await stripeEventsView.buildTree(); // Simulate view refresh const labels = treeItems.map(({label}) => label); const expectedLabel = 'Start streaming events'; assert.strictEqual( labels.includes(expectedLabel), true, `Expected [${labels.toString()}] to contain ${expectedLabel}`, ); }); }); test('creates tree items from stream', async () => { const stripeEventsView = new StripeEventsViewProvider( <any>stripeClient, <any>stripeDaemon, extensionContext, ); await stripeEventsView.startStreaming(); // Mock ready response const readyResponse = new ListenResponse(); readyResponse.setState(ListenResponse.State.STATE_READY); listenStream.emit('data', readyResponse); // Mock event response const stripeEvent = new StripeEvent(); stripeEvent.setType('customer.created'); stripeEvent.setId('evt_123'); const response = new ListenResponse(); response.setStripeEvent(stripeEvent); listenStream.emit('data', response); const treeItems = await stripeEventsView.buildTree(); // Simulate view refresh const recentEvents = treeItems.find(({label}) => label === 'Recent events'); const labels = recentEvents?.children?.map(({label}) => label); const expectedLabel = 'customer.created'; assert.strictEqual( labels?.includes(expectedLabel), true, `Expected [${labels?.toString()}] to contain ${expectedLabel}`, ); }); }); suite('stopStreaming', () => { setup(() => { sandbox.stub(stripeDaemon, 'setupClient').resolves(daemonClient); }); test('stops streaming', async () => { // Simulate a stream in progress const stripeEventsView = new StripeEventsViewProvider( <any>stripeClient, <any>stripeDaemon, extensionContext, ); await stripeEventsView.startStreaming(); const readyResponse = new ListenResponse(); readyResponse.setState(ListenResponse.State.STATE_READY); listenStream.emit('data', readyResponse); stripeEventsView.stopStreaming(); const treeItems = await stripeEventsView.buildTree(); // Simulate view refresh const labels = treeItems.map(({label}) => label); const expectedLabel = 'Start streaming events'; assert.strictEqual( labels.includes(expectedLabel), true, `Expected [${labels.toString()}] to contain ${expectedLabel}`, ); }); }); suite('error', () => { test('prompts upgrade when no daemon command', async () => { sandbox.stub(stripeDaemon, 'setupClient').throws(new NoDaemonCommandError()); const promptUpdateForDaemonSpy = sandbox.spy(stripeClient, 'promptUpdateForDaemon'); const stripeEventsView = new StripeEventsViewProvider( <any>stripeClient, <any>stripeDaemon, extensionContext, ); await stripeEventsView.startStreaming(); assert.strictEqual(promptUpdateForDaemonSpy.calledOnce, true); }); test('shows gRPC error message', async () => { sandbox.stub(stripeDaemon, 'setupClient').resolves(daemonClient); const showErrorMessageSpy = sandbox.spy(vscode.window, 'showErrorMessage'); const stripeEventsView = new StripeEventsViewProvider( <any>stripeClient, <any>stripeDaemon, extensionContext, ); await stripeEventsView.startStreaming(); listenStream.emit('error', <Partial<grpc.ServiceError>>{ code: grpc.status.UNKNOWN, details: 'unknown error', }); assert.strictEqual(showErrorMessageSpy.callCount, 1); assert.strictEqual(showErrorMessageSpy.args[0][0], 'unknown error'); }); test('prompts login when UNAUTHENTICATED', async () => { sandbox.stub(stripeDaemon, 'setupClient').resolves(daemonClient); const promptLoginSpy = sandbox.spy(stripeClient, 'promptLogin'); const stripeEventsView = new StripeEventsViewProvider( <any>stripeClient, <any>stripeDaemon, extensionContext, ); await stripeEventsView.startStreaming(); listenStream.emit('error', <Partial<grpc.ServiceError>>{code: grpc.status.UNAUTHENTICATED}); assert.strictEqual(promptLoginSpy.callCount, 1); }); test('silently handle CANCELLED error', async () => { sandbox.stub(stripeDaemon, 'setupClient').resolves(daemonClient); const showErrorMessageSpy = sandbox.spy(vscode.window, 'showErrorMessage'); const stripeEventsView = new StripeEventsViewProvider( <any>stripeClient, <any>stripeDaemon, extensionContext, ); await stripeEventsView.startStreaming(); listenStream.emit('error', <Partial<grpc.ServiceError>>{code: grpc.status.CANCELLED}); assert.strictEqual(showErrorMessageSpy.callCount, 0); }); }); });
the_stack
import * as _ from "lodash"; import { IChildLogger } from "@vscode-logging/logger"; import { IRpc } from "@sap-devx/webview-rpc/out.ext/rpc-common"; import { NpmCommand, PackagesData } from "./utils/npm"; import messages from "./exploreGensMessages"; import { Env, GeneratorData } from "./utils/env"; import { vscode } from "./utils/vscodeProxy"; import { Constants } from "./utils/constants"; type Disposable = { dispose(): void; }; export enum GenState { uninstalling = "uninstalling", updating = "updating", installing = "installing", notInstalled = "notInstalled", installed = "installed", outdated = "outdated", } export class ExploreGens { private readonly logger: IChildLogger; private rpc: Partial<IRpc>; private gensBeingHandled: any[]; // eslint-disable-line @typescript-eslint/prefer-readonly private cachedGeneratorsDataPromise: Promise<GeneratorData[]>; private readonly context: any; private readonly GLOBAL_ACCEPT_LEGAL_NOTE = "global.exploreGens.acceptlegalNote"; private readonly LAST_AUTO_UPDATE_DATE = "global.exploreGens.lastAutoUpdateDate"; private readonly SEARCH_QUERY = "ApplicationWizard.searchQuery"; private readonly AUTO_UPDATE = "ApplicationWizard.autoUpdate"; private readonly ONE_DAY = 1000 * 60 * 60 * 24; constructor(logger: IChildLogger, context?: any) { this.context = context; this.logger = logger; this.gensBeingHandled = []; void this.doGeneratorsUpdate(); } public init(rpc: Partial<IRpc>) { this.initRpc(rpc); this.setInstalledGens(); } public setGenFilter(genFullName: string) { return this.rpc.invoke("setGenQuery", [genFullName]); } private getGeneratorsData(): Promise<GeneratorData[]> { return Env.getGeneratorsData(); } private getInstalledGens(): Promise<GeneratorData[]> { return this.cachedGeneratorsDataPromise; } private setInstalledGens() { this.cachedGeneratorsDataPromise = this.getGeneratorsData(); } private isLegalNoteAccepted() { return Constants.IS_IN_BAS ? this.context.globalState.get(this.GLOBAL_ACCEPT_LEGAL_NOTE, false) : true; } private async acceptLegalNote() { await this.context.globalState.update(this.GLOBAL_ACCEPT_LEGAL_NOTE, true); return true; } private async doGeneratorsUpdate() { try { const lastUpdateDate = this.context.globalState.get(this.LAST_AUTO_UPDATE_DATE, 0); const currentDate = Date.now(); if (currentDate - lastUpdateDate > this.ONE_DAY) { this.context.globalState.update(this.LAST_AUTO_UPDATE_DATE, currentDate); const autoUpdateEnabled = this.getWsConfig().get(this.AUTO_UPDATE, true); if (autoUpdateEnabled) { await NpmCommand.checkAccessAndSetGeneratorsPath(); await this.updateAllInstalledGenerators(); } } } catch (error) { this.showAndLogError(messages.failed_to_update_gens(), error); } } private getIsInBAS(): boolean { return Constants.IS_IN_BAS; } private initRpc(rpc: Partial<IRpc>) { this.rpc = rpc; this.rpc.registerMethod({ func: this.getFilteredGenerators, thisArg: this }); this.rpc.registerMethod({ func: this.update, thisArg: this }); this.rpc.registerMethod({ func: this.install, thisArg: this }); this.rpc.registerMethod({ func: this.uninstall, thisArg: this }); this.rpc.registerMethod({ func: this.getRecommendedQuery, thisArg: this }); this.rpc.registerMethod({ func: this.getIsInBAS, thisArg: this }); this.rpc.registerMethod({ func: this.isLegalNoteAccepted, thisArg: this }); this.rpc.registerMethod({ func: this.acceptLegalNote, thisArg: this }); } private async updateAllInstalledGenerators() { const gensToUpdate: string[] = await Env.getGeneratorNamesWithOutdatedVersion(); if (!_.isEmpty(gensToUpdate)) { this.logger.debug(messages.auto_update_started); const statusBarMessage = this.setStatusBarMessage(messages.auto_update_started); const promises = _.map(gensToUpdate, (genName) => this.update(genName, true)); const failedToUpdateGens: any[] = _.compact(await Promise.all(promises)); if (!_.isEmpty(failedToUpdateGens)) { const errMessage = messages.failed_to_update_gens(failedToUpdateGens); this.showAndLogError(errMessage); } this.setInstalledGens(); statusBarMessage.dispose(); this.setStatusBarMessage(messages.auto_update_finished, 10000); } } private getWsConfig() { return vscode.workspace.getConfiguration(); } private async getFilteredGenerators(query?: string, recommended?: string): Promise<PackagesData> { const gensData: GeneratorData[] = await this.getInstalledGens(); const packagesData: PackagesData = await NpmCommand.getPackagesData(query, recommended); const filteredGenerators = _.map(packagesData.packages, (meta) => { const genName = meta.package.name; const installedGenData = gensData.find((genData) => genData.generatorPackageJson.name === genName); meta.state = !!installedGenData ? GenState.installed : GenState.notInstalled; if (meta.state === GenState.installed && meta.package.version !== installedGenData.generatorPackageJson.version) { meta.state = GenState.outdated; } meta.disabledToHandle = false; const handlingState = this.getHandlingState(genName); if (handlingState) { meta.state = handlingState; meta.disabledToHandle = true; } return meta; }); return { packages: filteredGenerators, total: packagesData.total }; } private getErrorMessage(error: Error): string { return _.get(error, "stack", _.get(error, "message", error.toString())); } private showAndLogError(messagePrefix: string, error?: Error) { if (error) { const errorMessage = this.getErrorMessage(error); this.logger.error(errorMessage); } vscode.window.showErrorMessage(`${messagePrefix}`); } private getRecommendedQuery(): string[] { const recommended: string[] = this.getWsConfig().get(this.SEARCH_QUERY, []); return _.uniq(recommended); } private notifyGeneratorsChange() { return vscode.commands.executeCommand("yeomanUI._notifyGeneratorsChange"); } private setStatusBarMessage(message: string, timeout?: number): Disposable { return vscode.window.setStatusBarMessage(message, timeout); } public async install(gen: any) { const genName = gen.package.name; this.addToHandled(genName, GenState.installing); const installingMessage = messages.installing(genName); const statusbarMessage = this.setStatusBarMessage(installingMessage); try { await NpmCommand.checkAccessAndSetGeneratorsPath(); this.logger.debug(installingMessage); this.updateBeingHandledGenerator(genName, GenState.installing); await NpmCommand.install(genName); const successMessage = messages.installed(genName); this.logger.debug(successMessage); vscode.window.showInformationMessage(successMessage); this.updateBeingHandledGenerator(genName, GenState.installed); await this.notifyGeneratorsChange(); } catch (error) { this.showAndLogError(messages.failed_to_install(genName), error); this.updateBeingHandledGenerator(genName, GenState.notInstalled); } finally { this.finalizeGenerator(genName, statusbarMessage); } } private async uninstall(gen: any) { const genName = gen.package.name; this.addToHandled(genName, GenState.uninstalling); const uninstallingMessage = messages.uninstalling(genName); const statusbarMessage = this.setStatusBarMessage(uninstallingMessage); try { this.logger.debug(uninstallingMessage); this.updateBeingHandledGenerator(genName, GenState.uninstalling); await NpmCommand.uninstall(genName); const successMessage = messages.uninstalled(genName); this.logger.debug(successMessage); vscode.window.showInformationMessage(successMessage); this.updateBeingHandledGenerator(genName, GenState.notInstalled); await this.notifyGeneratorsChange(); } catch (error) { this.showAndLogError(messages.failed_to_uninstall(genName), error); this.updateBeingHandledGenerator(genName, GenState.installed); } finally { this.finalizeGenerator(genName, statusbarMessage); } } private async update(gen: any, isAutoUpdate = false): Promise<string | undefined> { const genName = _.get(gen.package, "name", gen); this.addToHandled(genName, GenState.updating); const updatingMessage = messages.updating(genName); const statusbarMessage = isAutoUpdate ? undefined : this.setStatusBarMessage(updatingMessage); try { this.logger.debug(updatingMessage); this.updateBeingHandledGenerator(genName, GenState.updating); await NpmCommand.install(genName); this.logger.debug(messages.updated(genName)); this.updateBeingHandledGenerator(genName, GenState.installed); } catch (error) { this.updateBeingHandledGenerator(genName, GenState.notInstalled); if (isAutoUpdate) { this.logger.error(this.getErrorMessage(error)); return genName; } this.showAndLogError(messages.failed_to_update(genName), error); } finally { this.finalizeGenerator(genName, statusbarMessage); } } private finalizeGenerator(genName: string, statusbarMessage: any) { this.removeFromHandled(genName); this.setInstalledGens(); if (statusbarMessage) { statusbarMessage.dispose(); } } private updateBeingHandledGenerator(genName: string, state: GenState) { try { void this.rpc?.invoke("updateBeingHandledGenerator", [genName, state]); } catch (error) { // error could happen in case that panel was closed by an user but action is still in progress // in this case webview is already disposed this.logger.debug(this.getErrorMessage(error)); } } private addToHandled(genName: string, state: GenState) { this.gensBeingHandled.push({ name: genName, state }); } private removeFromHandled(genName: string) { _.remove(this.gensBeingHandled, (gen) => { return gen.name === genName; }); } private getHandlingState(genName: string) { const gen = _.find(this.gensBeingHandled, (gen) => { return gen.name === genName; }); return _.get(gen, "state"); } }
the_stack
import {Window} from "../Window"; import * as utils from "../utils"; import {GoldenSun} from "../GoldenSun"; import {Button} from "../XGamepad"; import {MainChar} from "../MainChar"; import {CursorManager, PointVariants} from "../utils/CursorManager"; const MAX_PER_LINE = 4; const WIN_X = 0; const WIN_Y = 112; const WIN_WIDTH = 100; const WIN_HEIGHT = 20; const WIN_X2 = 0; const WIN_Y2 = 0; const WIN_WIDTH2 = 100; const WIN_HEIGHT2 = 36; const CHAR_GROUP_X = 16; const CHAR_GROUP_Y = 128; const CHAR_GROUP_X2 = 16; const CHAR_GROUP_Y2 = 28; const GAP_SIZE = 24; const SHIFT_X = 16; const SHIFT_Y = 32; const CURSOR_X = 0; const CURSOR_Y = 118; const CURSOR_X2 = 0; const CURSOR_Y2 = 22; const ARROW_GROUP_X = 96; const ARROW_GROUP_Y = 100; const UP_ARROW_X = 16; const UP_ARROW_Y = 20; const DOWN_ARROW_X = 0; const DOWN_ARROW_Y = 24; const ARROW_Y_DIFF = 8; const ARROW_GROUP_X2 = 92; const ARROW_GROUP_Y2 = -4; const MENU_SELECTED_Y_SHIFT = 4; const SEPARATOR_X = 4; const SEPARATOR_Y = 27; const SEPARATOR_LENGTH = 96; export enum CharsMenuModes { SHOP, MENU, } const ARROW_TWEEN_TIME = Phaser.Timer.QUARTER >> 1; export class CharsMenu { public game: Phaser.Game; public data: GoldenSun; public on_change: Function; public window: Window; public char_group: Phaser.Group; public arrow_group: Phaser.Group; public up_arrow: Phaser.Sprite; public down_arrow: Phaser.Sprite; public arrow_tweens: Phaser.Tween[]; public lines: MainChar[][]; public char_sprites: Phaser.Sprite[]; public current_line: number; public selected_index: number; public is_active: boolean; public is_open: boolean; public mode: CharsMenuModes; constructor(game: Phaser.Game, data: GoldenSun, on_change: Function) { this.game = game; this.data = data; this.on_change = on_change; this.window = new Window(this.game, WIN_X, WIN_Y, WIN_WIDTH, WIN_HEIGHT); this.char_group = this.game.add.group(); this.char_group.x = CHAR_GROUP_X - SHIFT_X; this.char_group.y = CHAR_GROUP_Y - SHIFT_Y; this.char_group.visible = true; this.arrow_group = this.game.add.group(); this.arrow_group.x = ARROW_GROUP_X; this.arrow_group.y = ARROW_GROUP_Y; this.up_arrow = this.arrow_group.create(UP_ARROW_X, UP_ARROW_Y, "menu", "green_arrow"); this.up_arrow.rotation = Math.PI; this.down_arrow = this.arrow_group.create(DOWN_ARROW_X, DOWN_ARROW_Y, "menu", "green_arrow"); this.up_arrow.visible = false; this.down_arrow.visible = false; this.arrow_tweens = []; this.lines = []; this.char_sprites = []; this.current_line = 0; this.selected_index = null; this.is_active = false; this.is_open = false; this.mode = null; } check_mode() { if (this.mode === CharsMenuModes.SHOP) { this.window.update_size({width: WIN_WIDTH, height: WIN_HEIGHT}); this.window.update_position({x: WIN_X, y: WIN_Y}); this.char_group.x = CHAR_GROUP_X - SHIFT_X + this.game.camera.x; this.char_group.y = CHAR_GROUP_Y - SHIFT_Y + this.game.camera.y; this.arrow_group.x = ARROW_GROUP_X + this.game.camera.x; this.arrow_group.y = ARROW_GROUP_Y + this.game.camera.y; } else if (this.mode === CharsMenuModes.MENU) { this.window.update_size({width: WIN_WIDTH2, height: WIN_HEIGHT2}); this.window.update_position({x: WIN_X2, y: WIN_Y2}); this.char_group.x = CHAR_GROUP_X2 - SHIFT_X + this.game.camera.x; this.char_group.y = CHAR_GROUP_Y2 - SHIFT_Y + this.game.camera.y; this.arrow_group.x = ARROW_GROUP_X2 + this.game.camera.x; this.arrow_group.y = ARROW_GROUP_Y2 + this.game.camera.y; this.window.draw_separator(SEPARATOR_X, SEPARATOR_Y, SEPARATOR_X + SEPARATOR_LENGTH, SEPARATOR_Y, false); } } /*Hides or shows specific arrows Input: up, down [boolean] - If true, shows up/down arrow*/ set_arrows(up: boolean = false, down: boolean = false) { this.up_arrow.x = UP_ARROW_X; this.up_arrow.y = UP_ARROW_Y; this.down_arrow.x = DOWN_ARROW_X; this.down_arrow.y = DOWN_ARROW_Y; if (up) this.up_arrow.visible = true; else this.up_arrow.visible = false; if (down) this.down_arrow.visible = true; else this.down_arrow.visible = false; } /*Checks which arrows to show or hide*/ check_arrows() { let up = false; let down = false; if (this.current_line < this.lines.length - 1) down = true; if (this.current_line > 0) up = true; this.set_arrows(up, down); this.init_arrow_tweens(); this.game.world.bringToTop(this.arrow_group); } /*Starts the arrow animations*/ init_arrow_tweens() { let up_tween = this.game.add .tween(this.up_arrow) .to({y: UP_ARROW_Y - ARROW_Y_DIFF}, ARROW_TWEEN_TIME, Phaser.Easing.Linear.None) .to({y: UP_ARROW_Y}, ARROW_TWEEN_TIME, Phaser.Easing.Linear.None) .loop(); this.arrow_tweens.push(up_tween); let down_tween = this.game.add .tween(this.down_arrow) .to({y: DOWN_ARROW_Y + ARROW_Y_DIFF}, ARROW_TWEEN_TIME, Phaser.Easing.Linear.None) .to({y: DOWN_ARROW_Y}, ARROW_TWEEN_TIME, Phaser.Easing.Linear.None) .loop(); this.arrow_tweens.push(down_tween); up_tween.start(); down_tween.start(); } /*Clears the arrow animations*/ clear_arrow_tweens() { for (let i = 0; i < this.arrow_tweens.length; i++) { this.game.tweens.remove(this.arrow_tweens.pop()); } } set_chars() { this.char_sprites = []; for (let i = 0; i < this.lines[this.current_line].length; ++i) { let char = this.lines[this.current_line][i]; let sprite: Phaser.Sprite = null; let dead_idle = this.char_group.children.filter((s: Phaser.Sprite) => { return s.alive === false && s.key === char.sprite_base.getSpriteKey(utils.base_actions.IDLE); }); if (dead_idle.length > 0) sprite = (dead_idle[0] as Phaser.Sprite).reset(i * GAP_SIZE, 0); else sprite = this.char_group.create( i * GAP_SIZE, 0, char.sprite_base.getSpriteKey(utils.base_actions.IDLE) ); char.sprite_base.setAnimation(sprite, utils.base_actions.IDLE); sprite.animations.play( char.sprite_base.getAnimationKey( utils.base_actions.IDLE, utils.reverse_directions[utils.directions.down] ) ); this.char_sprites.push(sprite); } } make_lines() { let party_length = this.data.info.party_data.members.length; let line_number = party_length % MAX_PER_LINE === 0 ? (party_length / MAX_PER_LINE) | 0 : ((party_length / MAX_PER_LINE) | 0) + 1; for (let i = 0; i < line_number; i++) { let chars = []; for (let n = i * MAX_PER_LINE; n < (i + 1) * MAX_PER_LINE; n++) { if (!this.data.info.party_data.members[n]) break; chars.push(this.data.info.party_data.members[n]); } this.lines[i] = chars; } } change_line(line: number, force_index?: number, no_cursor?: boolean) { if (this.data.info.party_data.members.length < MAX_PER_LINE * line) return; this.clear_arrow_tweens(); this.unset_character(this.selected_index); this.current_line = line; if (force_index !== undefined) { this.selected_index = force_index; } else if (this.selected_index !== null && this.selected_index >= this.lines[this.current_line].length) { this.selected_index = this.lines[this.current_line].length - 1; } utils.kill_all_sprites(this.char_group); this.set_chars(); this.check_arrows(); this.select_char(this.selected_index, no_cursor); } next_line(force_index?: number, no_cursor?: boolean) { if (this.lines.length === 1 || this.current_line + 1 === this.lines.length) return; let index = this.current_line + 1; this.change_line(index, force_index, no_cursor); } previous_line(force_index?: number, no_cursor?: boolean) { if (this.lines.length === 1 || this.current_line - 1 < 0) return; let index = this.current_line - 1; this.change_line(index, force_index, no_cursor); } set_character(index: number) { if (this.mode === CharsMenuModes.SHOP) { //set run animation for new character; } else if (this.mode === CharsMenuModes.MENU) { this.char_sprites[index].y = MENU_SELECTED_Y_SHIFT; } } unset_character(index: number) { if (index === undefined || index === null) return; if (this.mode === CharsMenuModes.SHOP) { //unset run animation for new character; } else if (this.mode === CharsMenuModes.MENU) { this.char_sprites[index].y = 0; } } select_char(index?: number, no_cursor?: boolean, silent?: boolean) { if (index === undefined) index = this.selected_index; const on_move = () => { this.unset_character(this.selected_index); this.selected_index = index; this.set_character(this.selected_index); if (this.on_change && !silent) { const char = this.data.info.party_data.members[this.current_line * MAX_PER_LINE + this.selected_index]; this.on_change(char.key_name); } }; if (!no_cursor) this.move_cursor(index, on_move); else on_move(); } next_char(no_cursor?: boolean) { if (this.lines[this.current_line].length === 1 && this.lines.length === 1) return; if (this.selected_index + 1 === this.lines[this.current_line].length) { if (this.current_line + 1 === this.lines.length) { if (this.lines.length === 1) this.select_char(0, no_cursor); else this.change_line(0, 0, no_cursor); } else this.next_line(0, no_cursor); } else { this.select_char(this.selected_index + 1, no_cursor); } } previous_char(no_cursor?: boolean) { if (this.lines[this.current_line].length === 1 && this.lines.length === 1) return; if (this.selected_index - 1 < 0) { if (this.current_line - 1 < 0) { if (this.lines.length === 1) this.select_char(this.lines[this.current_line].length - 1, no_cursor); else this.change_line(this.lines.length - 1, this.lines[this.lines.length - 1].length - 1, no_cursor); } else this.previous_line(this.lines[this.current_line - 1].length - 1, no_cursor); } else { this.select_char(this.selected_index - 1, no_cursor); } } swap_next() { if ( this.selected_index === this.lines[this.current_line].length - 1 && this.current_line === this.lines.length - 1 ) return; const index = this.selected_index + this.current_line * MAX_PER_LINE; const this_char = this.data.info.party_data.members[index]; this.data.info.party_data.members[index] = this.data.info.party_data.members[index + 1]; this.data.info.party_data.members[index + 1] = this_char; const new_index = (this.selected_index + 1) % MAX_PER_LINE; const new_line = this.current_line + (new_index === 0 ? 1 : 0); this.make_lines(); this.change_line(new_line, new_index); } swap_previous() { if (this.selected_index === 0 && this.current_line === 0) return; const index = this.selected_index + this.current_line * MAX_PER_LINE; const this_char = this.data.info.party_data.members[index]; this.data.info.party_data.members[index] = this.data.info.party_data.members[index - 1]; this.data.info.party_data.members[index - 1] = this_char; const new_index = (this.selected_index + MAX_PER_LINE - 1) % MAX_PER_LINE; const new_line = this.current_line - (new_index > this.selected_index ? 1 : 0); this.make_lines(); this.change_line(new_line, new_index); } grant_control(on_cancel?: Function, on_select?: Function, enable_swap?: boolean) { const controls = [ {button: Button.LEFT, on_down: this.previous_char.bind(this), sfx: {down: "menu/move"}}, {button: Button.RIGHT, on_down: this.next_char.bind(this), sfx: {down: "menu/move"}}, {button: Button.UP, on_down: this.previous_line.bind(this), sfx: {down: "menu/move"}}, {button: Button.DOWN, on_down: this.next_line.bind(this), sfx: {down: "menu/move"}}, { button: Button.A, on_down: () => on_select?.(), params: {reset_controls: true}, sfx: {down: "menu/positive"}, }, { button: Button.B, on_down: () => on_cancel?.(), params: {reset_controls: true}, sfx: {down: "menu/negative"}, }, ]; if (enable_swap) { controls.push( {button: Button.L, on_down: this.swap_previous.bind(this), sfx: {down: "menu/positive"}}, {button: Button.R, on_down: this.swap_next.bind(this), sfx: {down: "menu/positive"}} ); } this.data.control_manager.add_controls(controls, {loop_config: {horizontal: true}}); } move_cursor(pos?: number, on_complete?: Function) { if (pos === undefined) pos = this.selected_index; let cursor_x = 0; let cursor_y = 0; let tween_config = {type: null, variant: null}; if (this.mode === CharsMenuModes.SHOP) { cursor_x = CURSOR_X + pos * GAP_SIZE; cursor_y = CURSOR_Y; tween_config.type = CursorManager.CursorTweens.WIGGLE; } else if (this.mode === CharsMenuModes.MENU) { cursor_x = CURSOR_X2 + pos * GAP_SIZE; cursor_y = CURSOR_Y2; tween_config.type = CursorManager.CursorTweens.POINT; tween_config.variant = PointVariants.NORMAL; } this.data.cursor_manager.move_to( {x: cursor_x, y: cursor_y}, {animate: false, tween_config: tween_config}, on_complete ); } activate() { this.move_cursor(); this.is_active = true; } deactivate() { this.data.cursor_manager.clear_tweens(); this.is_active = false; } open( select_index: number = 0, mode: CharsMenuModes = CharsMenuModes.SHOP, open_callback?: () => void, silent?: boolean ) { this.current_line = 0; this.mode = mode; this.make_lines(); this.check_mode(); this.check_arrows(); this.set_chars(); this.select_char(select_index, undefined, silent); this.char_group.visible = true; this.is_open = true; this.activate(); this.window.show(open_callback, false); } close(callback?: () => void, destroy: boolean = false) { this.is_open = false; this.deactivate(); utils.kill_all_sprites(this.char_group, destroy); this.lines = []; this.char_sprites = []; this.current_line = 0; this.selected_index = null; this.is_active = false; this.is_open = false; this.char_group.visible = false; this.mode = null; this.set_arrows(false, false); this.window.clear_separators(); this.window.close(callback, false); } }
the_stack
* @module OrbitGT */ //package orbitgt.pointcloud.model; type int8 = number; type int16 = number; type int32 = number; type float32 = number; type float64 = number; import { AList } from "../../system/collection/AList"; import { ALong } from "../../system/runtime/ALong"; import { ASystem } from "../../system/runtime/ASystem"; import { Strings } from "../../system/runtime/Strings"; import { AttributeTypes } from "./AttributeTypes"; import { AttributeValue } from "./AttributeValue"; /** * Class PointAttribute defines an attribute of a point. * * @version 1.0 August 2013 */ /** @internal */ export class PointAttribute { /** The name of the attribute */ private _name: string; /** The description of the attribute */ private _description: string; /** The type of the attribute */ private _type: int32; /** The default value of the attribute */ private _defaultValue: AttributeValue; /** The optional minimum value of the attribute */ private _minValue: AttributeValue; /** The optional maximum value of the attribute */ private _maxValue: AttributeValue; /** Is this a standard attribute? (color/intensity/weight)? */ private _standardAttribute: boolean; /** * Create a new point attribute. * @param name the name of the attribute. * @param description the description of the attribute. * @param type the type of the attribute. * @param default value the default value of the attribute (use null to create a default value). */ public constructor(name: string, description: string, type: int32, defaultValue: AttributeValue) { if (defaultValue == null) defaultValue = AttributeValue.createDefault(type); ASystem.assert0(defaultValue.getType() == type, "Default value " + defaultValue + " does not match attribute type " + type); this._name = name; this._description = description; this._type = type; this._defaultValue = defaultValue; this._minValue = null; this._maxValue = null; this._standardAttribute = false; } /** * Get the name. * @return the name. */ public getName(): string { return this._name; } /** * Set the name. * @param name the new name. */ public setName(name: string): void { this._name = name; } /** * Check the name. * @param name the name to check. * @return true if equal. */ public hasName(name: string): boolean { if (name == null) return false; if (Strings.equalsIgnoreCase(name, this._name)) return true; return false; } /** * Get the description. * @return the description. */ public getDescription(): string { return this._description; } /** * Get the type. * @return the type. */ public getType(): int32 { return this._type; } /** * Get the byte-size of the type. * @return the byte-size of the type. */ public getTypeByteSize(): int32 { return PointAttribute.getByteSize(this._type, 1); } /** * Get the byte-size of a number of values. * @param attributeCount the number of values. * @return the byte-size. */ public getTypeByteSizeForCount(attributeCount: int32): int32 { return PointAttribute.getByteSize(this._type, attributeCount); } /** * Get the byte-size of a number of values. * @param attributeCount the number of values. * @return the byte-size. */ public getTypeByteSizeForLongCount(attributeCount: ALong): ALong { return PointAttribute.getByteSizeForCount(this._type, attributeCount); } /** * Get the default value. * @return the default value. */ public getDefaultValue(): AttributeValue { return this._defaultValue; } /** * Get the optional minimum value. * @return the optional minimum value. */ public getMinValue(): AttributeValue { return this._minValue; } /** * Set the optional minimum value. * @param value the optional minimum value. */ public setMinValue(value: AttributeValue): void { this._minValue = value; } /** * Get the optional maximum value. * @return the optional maximum value. */ public getMaxValue(): AttributeValue { return this._maxValue; } /** * Set the optional maximum value. * @param value the optional maximum value. */ public setMaxValue(value: AttributeValue): void { this._maxValue = value; } /** * Set the description of a copy. * @param description the new description. * @return the copy. */ public setDescription(description: string): PointAttribute { return new PointAttribute(this._name, description, this._type, this._defaultValue); } /** * Is this a standard attribute (like color/intensity/weight)? * @return true for a standard attribute. */ public isStandardAttribute(): boolean { return this._standardAttribute; } /** * Make this a standard attribute (like color/intensity/weight). * @param standard true if this is a standard attribute. * @return this attribute for convenience. */ public setStandardAttribute(standard: boolean): PointAttribute { this._standardAttribute = standard; return this; } /** * The standard toString method. * @see Object#toString */ public toString(): string { return "[PointAttribute:name='" + this._name + "',type=" + PointAttribute.getTypeName(this._type) + ",default=" + this._defaultValue + "]"; } /** * Get the name of a type. * @param attributeType the type of attributes. * @return the name. */ public static getTypeName(attributeType: int32): string { if (attributeType <= 0) return "none"; if (attributeType == AttributeTypes.TYPE_BOOLEAN) return "boolean"; if (attributeType == AttributeTypes.TYPE_INT1) return "int1"; if (attributeType == AttributeTypes.TYPE_INT2) return "int2"; if (attributeType == AttributeTypes.TYPE_INT4) return "int4"; if (attributeType == AttributeTypes.TYPE_INT8) return "int8"; if (attributeType == AttributeTypes.TYPE_FLOAT4) return "float4"; if (attributeType == AttributeTypes.TYPE_FLOAT8) return "float8"; if (attributeType == AttributeTypes.TYPE_COLOR) return "color"; return "" + attributeType; } /** * Get the bit size for a type. * @param attributeType the type of attributes. * @return the number of bits. */ public static getBitSize(attributeType: int32): int32 { if (attributeType == AttributeTypes.TYPE_BOOLEAN) return 1; if (attributeType == AttributeTypes.TYPE_INT1) return 8; if (attributeType == AttributeTypes.TYPE_INT2) return 16; if (attributeType == AttributeTypes.TYPE_INT4) return 32; if (attributeType == AttributeTypes.TYPE_INT8) return 64; if (attributeType == AttributeTypes.TYPE_FLOAT4) return 32; if (attributeType == AttributeTypes.TYPE_FLOAT8) return 64; if (attributeType == AttributeTypes.TYPE_COLOR) return 24; return 0; } /** * Get the byte size for a number of attributes. * @param attributeType the type of attributes. * @param attributeCount the number of attributes. */ public static getByteSize(attributeType: int32, attributeCount: int32): int32 { if (attributeCount <= 0) return 0; if (attributeType == AttributeTypes.TYPE_BOOLEAN) return ((attributeCount - 1) >> 3) + 1; if (attributeType == AttributeTypes.TYPE_INT1) return (attributeCount); if (attributeType == AttributeTypes.TYPE_INT2) return (attributeCount << 1); if (attributeType == AttributeTypes.TYPE_INT4) return (attributeCount << 2); if (attributeType == AttributeTypes.TYPE_INT8) return (attributeCount << 3); if (attributeType == AttributeTypes.TYPE_FLOAT4) return (attributeCount << 2); if (attributeType == AttributeTypes.TYPE_FLOAT8) return (attributeCount << 3); if (attributeType == AttributeTypes.TYPE_COLOR) return (attributeCount * 3); return 0; } /** * Get the byte size for a number of attributes. * @param attributeType the type of attributes. * @param attributeCount the number of attributes. */ public static getByteSizeForCount(attributeType: int32, attributeCount: ALong): ALong { if (attributeCount.isPositive() == false) return ALong.ZERO; if (attributeType == AttributeTypes.TYPE_BOOLEAN) return attributeCount.subInt(1).divInt(8).addInt(1); if (attributeType == AttributeTypes.TYPE_INT1) return attributeCount.mulInt(1); if (attributeType == AttributeTypes.TYPE_INT2) return attributeCount.mulInt(2); if (attributeType == AttributeTypes.TYPE_INT4) return attributeCount.mulInt(4); if (attributeType == AttributeTypes.TYPE_INT8) return attributeCount.mulInt(8); if (attributeType == AttributeTypes.TYPE_FLOAT4) return attributeCount.mulInt(4); if (attributeType == AttributeTypes.TYPE_FLOAT8) return attributeCount.mulInt(8); if (attributeType == AttributeTypes.TYPE_COLOR) return attributeCount.mulInt(3); return ALong.ZERO; } /** * Find the index of an attribute. * @param attributes the list of attributes. * @param attributeName the name of an attribute. * @return the index (negative if not found). */ public static indexOfName(attributes: Array<PointAttribute>, attributeName: string): int32 { if (attributes == null) return -1; if (attributeName == null) return -1; for (let i: number = 0; i < attributes.length; i++) if (attributes[i].hasName(attributeName)) return i; return -1; } /** * Find the index of an attribute. * @param attributes the list of attributes. * @param attribute the definition of an attribute. * @return the index (negative if not found). */ public static indexOf(attributes: Array<PointAttribute>, attribute: PointAttribute): int32 { if (attributes == null) return -1; if (attribute == null) return -1; for (let i: number = 0; i < attributes.length; i++) if (attributes[i].hasName(attribute.getName())) return i; return -1; } /** * Check if an attribute exists. * @param attributes the list of attributes. * @param attributeName the name of an attribute. * @return true if found. */ public static hasAttributeName(attributes: Array<PointAttribute>, attributeName: string): boolean { return (PointAttribute.indexOfName(attributes, attributeName) >= 0); } /** * Check if an attribute exists. * @param attributes the list of attributes. * @param attribute the definition of an attribute. * @return true if found. */ public static hasAttribute(attributes: Array<PointAttribute>, attribute: PointAttribute): boolean { return (PointAttribute.indexOf(attributes, attribute) >= 0); } /** * Find the index of an attribute. * @param attributes the list of attributes. * @param attributeName the name of an attribute. * @return the index (negative if not found). */ public static listIndexOfName(attributes: AList<PointAttribute>, attributeName: string): int32 { if (attributes == null) return -1; if (attributeName == null) return -1; for (let i: number = 0; i < attributes.size(); i++) if (attributes.get(i).hasName(attributeName)) return i; return -1; } /** * Find the index of an attribute. * @param attributes the list of attributes. * @param attribute the definition of an attribute. * @return the index (negative if not found). */ public static listIndexOf(attributes: AList<PointAttribute>, attribute: PointAttribute): int32 { if (attributes == null) return -1; if (attribute == null) return -1; for (let i: number = 0; i < attributes.size(); i++) if (attributes.get(i).hasName(attribute.getName())) return i; return -1; } /** * Check if an attribute exists. * @param attributes the list of attributes. * @param attributeName the name of an attribute. * @return true if found. */ public static listHasAttributeName(attributes: AList<PointAttribute>, attributeName: string): boolean { return (PointAttribute.listIndexOfName(attributes, attributeName) >= 0); } /** * Check if an attribute exists. * @param attributes the list of attributes. * @param attribute the definition of an attribute. * @return true if found. */ public static listHasAttribute(attributes: AList<PointAttribute>, attribute: PointAttribute): boolean { return (PointAttribute.listIndexOf(attributes, attribute) >= 0); } }
the_stack
module TDev { export module RT { //? Current box element in the page. //@ skill(2) export module Box { var R = HTML; // Start new definition of a box export function push_box(s:IStackFrame) : void { if (!LayoutMgr.RenderExecutionMode()) Util.userError(lf("boxes can only be created in page display code")); var parent = LayoutMgr.getCurrentRenderBox(); Util.assert(parent != null); LayoutMgr.createOrRecycleContainerBoxDelayed(s.rt, parent); // var w:WallBox = WallBox.CreateOrRecycleContainerBox(s.rt, parent); // LayoutMgr.setCurrentRenderBox(w); } // Finish the box definition export function pop_box(s:IStackFrame) : void { Util.assert(LayoutMgr.RenderExecutionMode()); var box = LayoutMgr.getCurrentRenderBox(); //Util.log("pop box " + box.depth + " " + box.id); var parent = box.parent; Util.assert(parent != null); LayoutMgr.setCurrentRenderBox(box.parent); } //? Sets the foreground color of elements. //@ [color].deflExpr('colors->random') export function set_foreground(color:Color, s:IStackFrame) : void { var box = s.rt.getCurrentBox(); box.setForeground(color.toHtml(), s.rt.getTopScriptPc()); } //? Sets the background color. //@ [color].deflExpr('colors->random') export function set_background(color:Color, s:IStackFrame) : void { var box = s.rt.getCurrentBox(); box.setBackground(color.toHtml(), s.rt.getTopScriptPc()); } //? Sets the background picture. The picture must be a resource or from the web. The size of the picture does not impact the size of the box. //@ [position].deflStrings('center center', 'left top', 'left center', 'left bottom', 'right top', 'right center','right bottom','center top','center bottom') //@ [size].deflStrings('cover', 'contain', 'auto') //@ [repeat].deflStrings('no-repeat', 'repeat', 'repeat-x', 'repeat-y') //@ [attachment].deflStrings('scroll', 'fixed', 'local') export function add_background_picture(pic: Picture, position : string, size : string, repeat : string, attachment : string, s: IStackFrame) { var url = pic.getReadonlyUrlSync(); function validate(str: string): string { var r = str.toLowerCase().trim(); if (!/^[a-z %0-9\-]*$/.test(r)) { App.log('invalid box background value: ' + r); return ''; } return r; } if (url) { var box = s.rt.getCurrentBox(); box.addBackgroundImage({ url: url, position:validate(position), size: validate(size), repeat: validate(repeat), attachment:validate(attachment) }, s.rt.getTopScriptPc()); } } //? Arrange boxes inside this box from top to bottom. export function use_vertical_layout(s:IStackFrame): void { var box = s.rt.getCurrentBox(); box.setFlow(WallBox.FLOW_VERTICAL, s.rt.getTopScriptPc()); } //? Arrange boxes inside this box from left to right. export function use_horizontal_layout(s:IStackFrame): void { var box = s.rt.getCurrentBox(); box.setFlow(WallBox.FLOW_HORIZONTAL, s.rt.getTopScriptPc()); } //? Arrange boxes inside this box as layers on top of each other. export function use_overlay_layout(s:IStackFrame): void { var box = s.rt.getCurrentBox(); box.setFlow(WallBox.FLOW_OVERLAY, s.rt.getTopScriptPc()); } //? Set the width of this box. export function set_width(width:number, s:IStackFrame) : void { var box = s.rt.getCurrentBox(); box.setEmWidth(width, s.rt.getTopScriptPc()); } //? Set the height of this box. export function set_height(height:number, s:IStackFrame) : void { var box = s.rt.getCurrentBox(); box.setEmHeight(height, s.rt.getTopScriptPc()); } //? Set lower and upper limits on the width of this box. export function set_width_range(min_width: number, max_width: number, s:IStackFrame): void { var box = s.rt.getCurrentBox(); box.setEmWidthRange(min_width, max_width, s.rt.getTopScriptPc()); } //? Set lower and upper limits on the height of this box. export function set_height_range(min_height: number, max_height: number, s:IStackFrame): void { var box = s.rt.getCurrentBox(); box.setEmHeightRange(min_height, max_height, s.rt.getTopScriptPc()); } //? Specify how to compute box width (0 = shrink to fit content, 1 = stretch to fit frame, , 0.5 = stretch to half width) //@ [elasticity].defl(1) export function set_horizontal_stretch(elasticity: number, s: IStackFrame): void { var n = elasticity; var box = s.rt.getCurrentBox(); if (n < 0 || n > 1) { Util.userError(lf("invalid argument: elasticity must be a number between 0 and 1")); n = 0; } box.setHorizontalStretch(n, s.rt.getTopScriptPc()); } //? Specify how to compute box height (0 = shrink to fit content, 1 = stretch to fit frame, 0.5 = stretch to half height) //@ [elasticity].defl(1) export function set_vertical_stretch(elasticity: number, s: IStackFrame): void { var n = elasticity; var box = s.rt.getCurrentBox(); if (n < 0 || n > 1) { Util.userError(lf("invalid argument: elasticity must be a number between 0 and 1")); n = 0; } box.setVerticalStretch(n, s.rt.getTopScriptPc()); } //? Set the color and width of the border. //@ [color].deflExpr('colors->foreground') [width].defl(0.1) export function set_border(color: Color, width: number, s:IStackFrame): void { var box = s.rt.getCurrentBox(); box.setEmBorder(color.toHtml(), width, s.rt.getTopScriptPc()); } //? Set the width of each border. export function set_border_widths(top:number, right:number, bottom:number, left:number, s:IStackFrame): void { var box = s.rt.getCurrentBox(); box.setEmBorderWidth(top, right, bottom, left, s.rt.getTopScriptPc()); } //? Set the margins of this box (to leave space around the outside of this box). //@ [left].defl(0.5) [top].defl(0.5) export function set_margins(top: number, right: number, bottom: number, left: number, s:IStackFrame): void { var box = s.rt.getCurrentBox(); box.setAllEmMargins(top, right, bottom, left, s.rt.getTopScriptPc()); } //? Set the padding of this box (to leave space around the contents of this box). export function set_padding(top: number, right: number, bottom: number, left: number, s:IStackFrame): void { var box = s.rt.getCurrentBox(); box.setEmPadding(top, right, bottom, left, s.rt.getTopScriptPc()); } // Set the weights for extending the margins of this box. //export function stretch_margins(top:number, right:number, bottom:number, left:number, s:IStackFrame) : void //{ // var box = s.rt.getCurrentBox(); // box.stretchAllMargins(top, right, bottom, left, s.rt.getTopScriptPc()); //} // Set the weight for extending the width of this box. //export function stretch_width(weight:number, s:IStackFrame) : void //{ // var box = s.rt.getCurrentBox(); // box.setWidthStretch(weight, s.rt.getTopScriptPc()); //} // Set the weight for extending the height of this box. //export function stretch_height(weight:number, s:IStackFrame) : void //{ // var box = s.rt.getCurrentBox(); // box.setHeightStretch(weight, s.rt.getTopScriptPc()); //} //? align (0,0)=center (1,0)=left, (0,1)=right, (1,1)=stretch //@ obsolete export function set_horizontal_alignment(left: number, right: number, s: IStackFrame): void { var box = s.rt.getCurrentBox(); box.setHorizontalAlignment(left, right, s.rt.getTopScriptPc()); } //? align (0,0)=center (1,0)=top, (0,1)=bottom, (1,1)=stretch //@ obsolete export function set_vertical_alignment(top:number, bottom:number, s: IStackFrame) : void { var box = s.rt.getCurrentBox(); box.setVerticalAlignment(top, bottom, s.rt.getTopScriptPc()); } //? Specify how to arrange the content of this box //@ [arrange].defl("left") [arrange].deflStrings("center", "left", "right", "justify", "spread") export function set_horizontal_align(arrange:string, s: IStackFrame): void { var box = s.rt.getCurrentBox(); var a = WallBox.ARRANGE_LEFT; var what = arrange; if (what === "left") a = WallBox.ARRANGE_LEFT; else if (what === "right") a = WallBox.ARRANGE_RIGHT; else if (what === "center") a = WallBox.ARRANGE_CENTER; else if (what === "justify") a = WallBox.ARRANGE_JUSTIFY; else if (what === "spread") a = WallBox.ARRANGE_SPREAD; else Util.userError(lf("horizontal align must be one of {left, right, center, justify, spread}")); box.setHorizontalArrangement(a, s.rt.getTopScriptPc()); } //? Specify how to arrange the content of this box //@ [arrange].defl("baseline") [arrange].deflStrings("baseline", "top", "bottom", "center", "justify", "spread") export function set_vertical_align(arrange:string, s: IStackFrame): void { var box = s.rt.getCurrentBox(); var a = WallBox.ARRANGE_TOP; var what = arrange; if (what === "top") a = WallBox.ARRANGE_TOP; else if (what === "bottom") a = WallBox.ARRANGE_BOTTOM; else if (what === "center") a = WallBox.ARRANGE_CENTER; else if (what === "justify") a = WallBox.ARRANGE_JUSTIFY; else if(what === "baseline") a = WallBox.ARRANGE_BASELINE; else if (what === "spread") a = WallBox.ARRANGE_SPREAD; else Util.userError(lf("vertical align must be one of {baseline, top, bottom, center, justify, spread}")); box.setVerticalArrangement(a, s.rt.getTopScriptPc()); } //? Set font size in this box and contained boxes. //@ [font_size].defl(1) export function set_font_size(font_size: number, s:IStackFrame): void { var box = s.rt.getCurrentBox(); box.setEmFontSize(font_size, s.rt.getTopScriptPc()); } //? Set font weight in this box and contained boxes. //@ [font_weight].defl("bold") [font_weight].deflStrings("normal", "bold", "lighter", "bolder") export function set_font_weight(font_weight: string, s: IStackFrame): void { var box = s.rt.getCurrentBox(); box.setFontWeight(font_weight, s.rt.getTopScriptPc()); } //? Set font family in this box and contained boxes. //@ [family].defl("Default") [family].deflStrings("Default", "Arial, Helvetica, sans-serif", "Courier New, Courier, monospace", "Georgia, serif", "Lucida Console, Monaco, monospace", "Lucida Sans Unicode, Lucida Grande, sans - serif", "Palatino Linotype, Book Antiqua, Palatino, serif", "Tahoma, Geneva, sans - serif", "Times New Roman, Times, serif", "Trebuchet MS, sans-serif", "Verdana, Geneva, sans-serif", "Comic Sans MS, cursive") //@ dbgOnly export function set_font_family(family: string, s:IStackFrame): void { var box = s.rt.getCurrentBox(); box.setFontFamily(family, s.rt.getTopScriptPc()); } //? Specify whether to use scrollbars on overflow. //@ [horizontal_scrolling].defl(true) [vertical_scrolling].defl(true) export function set_scrolling(horizontal_scrolling: boolean, vertical_scrolling: boolean, s:IStackFrame): void { var box = s.rt.getCurrentBox(); box.setScrolling(horizontal_scrolling, vertical_scrolling, s.rt.getTopScriptPc()); } //? Set what happens when the box is tapped. export function on_tapped(handler:Action, s:IStackFrame) : void { var box = s.rt.getCurrentBox(); box.attributes.tappedEvent.addHandler(handler); } // //? Set what happens when the box is tapped. // export function on_edit(handler: Action, s: IStackFrame): void { // var box = s.rt.getCurrentBox(); // box.attributes.editEvent.addHandler(handler); // } //? Set what happens whenever the text in the box is being edited. //@ obsolete export function on_text_editing(handler:TextAction, s:IStackFrame) : void { var box = s.rt.getCurrentBox(); box.attributes.textEditingEvent.addHandler(handler); } //? Set what happens when the user has finished editing the text in the box. //@ obsolete export function on_text_edited(handler:TextAction, s:IStackFrame): void { var box = s.rt.getCurrentBox(); box.attributes.textEditedEvent.addHandler(handler); } //? Display editable text. //@ obsolete //@ [text].defl("") [multiline].defl(true) export function edit_text(text: string, multiline: boolean, s: IStackFrame): void { s.rt.postEditableText(multiline ? "textarea" : "textline", text, null, s.rt.getTopScriptPc()); } //? Display editable text, for the given content and change handler. //@ [style].defl("textline") [style].deflStrings("textline", "textarea", "number", "password") export function edit(style: string, value: string, changehandler:TextAction, s: IStackFrame): void { s.rt.postEditableText(style, value, changehandler, s.rt.getTopScriptPc()); } //? Display editable text, bound to the given string reference. //@ [style].defl("textline") [style].deflStrings("textline", "textarea", "number", "password") export function edit_ref(style: string, ref:Ref<string>, s: IStackFrame): void { s.rt.postEditableText(style, ref._get(s), ref, s.rt.getTopScriptPc()); } //? //@ hidden export function is_init(s:IStackFrame): boolean { return s.rt.getCurrentPage().renderCount == 0; } //? Get the total width of the page. export function page_width(s:IStackFrame) : number { // must leave room for scrollbar, otherwise we get double scroll bars return (s.rt.host.fullWallWidth() - LayoutMgr.instance.scrollbarWidth) / SizeMgr.topFontSize; } //? Get the total height of the page. export function page_height(s:IStackFrame) : number { return s.rt.host.userWallHeight() / SizeMgr.topFontSize; } //? Get the number of pixels in an em export function pixels_per_em(): number { return SizeMgr.topFontSize; } //? Set whether to break long lines, and specify what length is too short for breaking //@ [wrap].readsMutable //@ [wrap].defl(true) [minimumwidth].defl(15) export function set_text_wrapping(wrap:boolean, minimumwidth:number, s:IStackFrame) : void { var box = s.rt.getCurrentBox(); box.setWrap(wrap, minimumwidth, s.rt.getTopScriptPc()); } } //? Current html element in the page. //@ betaOnly skill(2) export module Dom { //? Use CSS for layout and import additional CSS stylesheets. Use string art resource to import urls. //@ betaOnly export function use_css(stylesheet: string, s: IStackFrame): void { s.rt.forceNonRender(lf("cannot change css while displaying page")); s.rt.getCurrentPage().csslayout = true; s.rt.applyPageAttributes(true); if (stylesheet) (<any>s.rt.host).importCss(stylesheet) } //? Specify the tagname for this element //@ betaOnly export function set_tag_name(name: string, s: IStackFrame): void { if (!name) return; if (!HTML.allowedTagName(name)) Util.userError(lf("tag not allowed"), s.pc); LayoutMgr.setHtmlTagName(name); } //? Add a CSS class name to the current element. //@ betaOnly export function add_css_class(name: string, s: IStackFrame): void { if (!name) return; var box = s.rt.getCurrentHtmlBox(); box.addClassName(name, s.rt.getTopScriptPc()); } //? Specify an attribute for the current element. //@ betaOnly export function set_attribute(name: string, value: string, s: IStackFrame): void { if (!name) return; if (!HTML.allowedAttribute(name, value)) Util.userError(lf("attribute not allowed"), s.pc); var box = s.rt.getCurrentHtmlBox(); box.setAttribute(name, value, s.rt.getTopScriptPc()); } //? Specify a style attribute for the current element. //@ betaOnly export function set_style(property: string, value: string, s: IStackFrame): void { if (!property) return; var box = s.rt.getCurrentHtmlBox(); box.setStyle(property,value, s.rt.getTopScriptPc()); } //? Bind editable text, by giving current text and change handler. //@ betaOnly export function bind_value_with_handler(value: string, changehandler: TextAction, s: IStackFrame): void { var box = s.rt.getCurrentHtmlBox(); box.bindEditableText(value, changehandler, s.rt.getTopScriptPc()); } //? Bind editable text, using a string reference. //@ betaOnly export function bind_value_to_ref(ref: Ref<string>, s: IStackFrame): void { var box = s.rt.getCurrentHtmlBox(); box.bindEditableText(ref._get(s), ref, s.rt.getTopScriptPc()); } //? Set what happens when this element is clicked. //@ betaOnly export function add_on_click(body: Action, s: IStackFrame): void { var box = s.rt.getCurrentHtmlBox(); box.attributes.tappedEvent.addHandler(body); } } } }
the_stack
import 'chrome://resources/cr_elements/shared_vars_css.m.js'; import './print_preview_vars_css.js'; import '../strings.m.js'; import '../data/document_info.js'; import './sidebar.js'; import {CrDialogElement} from 'chrome://resources/cr_elements/cr_dialog/cr_dialog.m.js'; import {assert} from 'chrome://resources/js/assert.m.js'; import {isMac, isWindows} from 'chrome://resources/js/cr.m.js'; import {FocusOutlineManager} from 'chrome://resources/js/cr/ui/focus_outline_manager.m.js'; import {EventTracker} from 'chrome://resources/js/event_tracker.m.js'; import {hasKeyModifiers} from 'chrome://resources/js/util.m.js'; import {WebUIListenerMixin} from 'chrome://resources/js/web_ui_listener_mixin.js'; import {html, PolymerElement} from 'chrome://resources/polymer/v3_0/polymer/polymer_bundled.min.js'; import {CloudPrintInterface, CloudPrintInterfaceErrorEventDetail, CloudPrintInterfaceEventType} from '../cloud_print_interface.js'; import {CloudPrintInterfaceImpl} from '../cloud_print_interface_impl.js'; import {Destination, DestinationOrigin} from '../data/destination.js'; import {getPrinterTypeForDestination, PrinterType} from '../data/destination_match.js'; import {DocumentSettings, PrintPreviewDocumentInfoElement} from '../data/document_info.js'; import {Margins} from '../data/margins.js'; import {MeasurementSystem} from '../data/measurement_system.js'; import {DuplexMode, PrintPreviewModelElement, whenReady} from '../data/model.js'; import {PrintableArea} from '../data/printable_area.js'; import {Size} from '../data/size.js'; import {Error, PrintPreviewStateElement, State} from '../data/state.js'; import {MetricsContext, PrintPreviewInitializationEvents} from '../metrics.js'; import {NativeInitialSettings, NativeLayer, NativeLayerImpl} from '../native_layer.js'; // <if expr="chromeos_ash or chromeos_lacros"> import {NativeLayerCros, NativeLayerCrosImpl} from '../native_layer_cros.js'; // </if> import {DestinationState} from './destination_settings.js'; import {PreviewAreaState, PrintPreviewPreviewAreaElement} from './preview_area.js'; import {SettingsMixin} from './settings_mixin.js'; import {PrintPreviewSidebarElement} from './sidebar.js'; export interface PrintPreviewAppElement { $: { documentInfo: PrintPreviewDocumentInfoElement, model: PrintPreviewModelElement, previewArea: PrintPreviewPreviewAreaElement, sidebar: PrintPreviewSidebarElement, state: PrintPreviewStateElement, }; } const PrintPreviewAppElementBase = WebUIListenerMixin(SettingsMixin(PolymerElement)); export class PrintPreviewAppElement extends PrintPreviewAppElementBase { static get is() { return 'print-preview-app'; } static get template() { return html`{__html_template__}`; } static get properties() { return { state: { type: Number, observer: 'onStateChanged_', }, cloudPrintErrorMessage_: String, cloudPrintInterface_: Object, controlsManaged_: { type: Boolean, computed: 'computeControlsManaged_(destinationsManaged_, ' + 'settingsManaged_, maxSheets_)', }, destination_: Object, destinationsManaged_: { type: Boolean, value: false, }, destinationState_: { type: Number, observer: 'onDestinationStateChange_', }, documentSettings_: Object, error_: Number, margins_: Object, pageSize_: Object, previewState_: { type: String, observer: 'onPreviewStateChange_', }, printableArea_: Object, settingsManaged_: { type: Boolean, value: false, }, measurementSystem_: { type: Object, value: null, }, maxSheets_: Number, }; } state: State; private cloudPrintErrorMessage_: string; private cloudPrintInterface_: CloudPrintInterface; private controlsManaged_: boolean; private destination_: Destination; private destinationsManaged_: boolean; private destinationState_: DestinationState; private documentSettings_: DocumentSettings; private error_: Error; private margins_: Margins; private pageSize_: Size; private previewState_: PreviewAreaState; private printableArea_: PrintableArea; private settingsManaged_: boolean; private measurementSystem_: MeasurementSystem|null; private maxSheets_: number; private nativeLayer_: NativeLayer|null = null; // <if expr="chromeos_ash or chromeos_lacros"> private nativeLayerCros_: NativeLayerCros|null = null; // </if> private tracker_: EventTracker = new EventTracker(); private cancelled_: boolean = false; private printRequested_: boolean = false; private startPreviewWhenReady_: boolean = false; private showSystemDialogBeforePrint_: boolean = false; private openPdfInPreview_: boolean = false; private isInKioskAutoPrintMode_: boolean = false; private whenReady_: Promise<void>|null = null; private openDialogs_: CrDialogElement[] = []; constructor() { super(); // Regular expression that captures the leading slash, the content and the // trailing slash in three different groups. const CANONICAL_PATH_REGEX = /(^\/)([\/-\w]+)(\/$)/; const path = location.pathname.replace(CANONICAL_PATH_REGEX, '$1$2'); if (path !== '/') { // There are no subpages in Print Preview. window.history.replaceState(undefined /* stateObject */, '', '/'); } } ready() { super.ready(); FocusOutlineManager.forDocument(document); } connectedCallback() { super.connectedCallback(); document.documentElement.classList.remove('loading'); this.nativeLayer_ = NativeLayerImpl.getInstance(); // <if expr="chromeos_ash or chromeos_lacros"> this.nativeLayerCros_ = NativeLayerCrosImpl.getInstance(); // </if> this.addWebUIListener('cr-dialog-open', this.onCrDialogOpen_.bind(this)); this.addWebUIListener('close', this.onCrDialogClose_.bind(this)); this.addWebUIListener('print-failed', this.onPrintFailed_.bind(this)); this.addWebUIListener( 'print-preset-options', this.onPrintPresetOptions_.bind(this)); this.tracker_.add(window, 'keydown', this.onKeyDown_.bind(this)); this.$.previewArea.setPluginKeyEventCallback(this.onKeyDown_.bind(this)); this.whenReady_ = whenReady(); this.nativeLayer_.getInitialSettings().then( this.onInitialSettingsSet_.bind(this)); MetricsContext.getInitialSettings().record( PrintPreviewInitializationEvents.FUNCTION_INITIATED); } disconnectedCallback() { super.disconnectedCallback(); this.tracker_.removeAll(); this.whenReady_ = null; } private onSidebarFocus_() { this.$.previewArea.hideToolbar(); } /** * Consume escape and enter key presses and ctrl + shift + p. Delegate * everything else to the preview area. */ private onKeyDown_(e: KeyboardEvent) { // Escape key closes the topmost dialog that is currently open within // Print Preview. If no such dialog exists, then the Print Preview dialog // itself is closed. if (e.key === 'Escape' && !hasKeyModifiers(e)) { // Don't close the Print Preview dialog if there is a child dialog open. if (this.openDialogs_.length !== 0) { // Manually cancel the dialog, since we call preventDefault() to prevent // views from closing the Print Preview dialog. const dialogToClose = this.openDialogs_[this.openDialogs_.length - 1]; dialogToClose.cancel(); e.preventDefault(); return; } // On non-mac with toolkit-views, ESC key is handled by C++-side instead // of JS-side. if (isMac) { this.close_(); e.preventDefault(); } // <if expr="chromeos_ash or chromeos_lacros"> if (this.destination_ && this.destination_.origin === DestinationOrigin.CROS) { this.nativeLayerCros_!.recordPrinterStatusHistogram( this.destination_.printerStatusReason, false); } // </if> return; } // On Mac, Cmd+Period should close the print dialog. if (isMac && e.key === '.' && e.metaKey) { this.close_(); e.preventDefault(); return; } // Ctrl + Shift + p / Mac equivalent. Doesn't apply on Chrome OS. // <if expr="not chromeos and not lacros"> if (e.key === 'p') { if ((isMac && e.metaKey && e.altKey && !e.shiftKey && !e.ctrlKey) || (!isMac && e.shiftKey && e.ctrlKey && !e.altKey && !e.metaKey)) { // Don't use system dialog if the link isn't available. if (!this.$.sidebar.systemDialogLinkAvailable()) { return; } // Don't try to print with system dialog on Windows if the document is // not ready, because we send the preview document to the printer on // Windows. if (!isWindows || this.state === State.READY) { this.onPrintWithSystemDialog_(); } e.preventDefault(); return; } } // </if> if ((e.key === 'Enter' || e.key === 'NumpadEnter') && this.state === State.READY && this.openDialogs_.length === 0) { const activeElementTag = (e.composedPath()[0] as HTMLElement).tagName; if (['CR-BUTTON', 'BUTTON', 'SELECT', 'A', 'CR-CHECKBOX'].includes( activeElementTag)) { return; } this.onPrintRequested_(); e.preventDefault(); return; } // Pass certain directional keyboard events to the PDF viewer. this.$.previewArea.handleDirectionalKeyEvent(e); } private onCrDialogOpen_(e: Event) { this.openDialogs_.push(e.composedPath()[0] as CrDialogElement); } private onCrDialogClose_(e: Event) { // Note: due to event re-firing in cr_dialog.js, this event will always // appear to be coming from the outermost child dialog. // TODO(rbpotter): Fix event re-firing so that the event comes from the // dialog that has been closed, and add an assertion that the removed // dialog matches e.composedPath()[0]. if ((e.composedPath()[0] as HTMLElement).nodeName === 'CR-DIALOG') { this.openDialogs_.pop(); } } private onInitialSettingsSet_(settings: NativeInitialSettings) { MetricsContext.getInitialSettings().record( PrintPreviewInitializationEvents.FUNCTION_SUCCESSFUL); if (!this.whenReady_) { // This element and its corresponding model were detached while waiting // for the callback. This can happen in tests; return early. return; } this.whenReady_.then(() => { // The cloud print interface should be initialized before initializing the // sidebar, so that cloud printers can be selected automatically. if (settings.cloudPrintURL) { this.initializeCloudPrint_( settings.cloudPrintURL, settings.isInAppKioskMode, settings.uiLocale); } this.$.documentInfo.init( settings.previewModifiable, settings.previewIsFromArc, settings.documentTitle, settings.documentHasSelection); this.$.model.setStickySettings(settings.serializedAppStateStr); this.$.model.setPolicySettings(settings.policies); this.measurementSystem_ = new MeasurementSystem( settings.thousandsDelimiter, settings.decimalDelimiter, settings.unitType); this.setSetting('selectionOnly', settings.shouldPrintSelectionOnly); this.$.sidebar.init( settings.isInAppKioskMode, settings.printerName, settings.serializedDefaultDestinationSelectionRulesStr, settings.pdfPrinterDisabled, settings.isDriveMounted || false); this.destinationsManaged_ = settings.destinationsManaged; this.isInKioskAutoPrintMode_ = settings.isInKioskAutoPrintMode; // This is only visible in the task manager. let title = document.head.querySelector('title'); if (!title) { title = document.createElement('title'); document.head.appendChild(title); } title.textContent = settings.documentTitle; }); } /** * Called when Google Cloud Print integration is enabled. * @param cloudPrintUrl The URL to use for cloud print servers. * @param appKioskMode Whether the browser is in app kiosk mode. * @param uiLocale The UI locale. */ private initializeCloudPrint_( cloudPrintUrl: string, appKioskMode: boolean, uiLocale: string) { assert(!this.cloudPrintInterface_); this.cloudPrintInterface_ = CloudPrintInterfaceImpl.getInstance(); this.cloudPrintInterface_.configure(cloudPrintUrl, appKioskMode, uiLocale); this.tracker_.add( assert(this.cloudPrintInterface_).getEventTarget(), CloudPrintInterfaceEventType.SUBMIT_DONE, this.close_.bind(this)); this.tracker_.add( assert(this.cloudPrintInterface_).getEventTarget(), CloudPrintInterfaceEventType.SUBMIT_FAILED, this.onCloudPrintError_.bind(this, appKioskMode)); } /** * @return Whether any of the print preview settings or destinations * are managed. */ private computeControlsManaged_(): boolean { // If |this.maxSheets_| equals to 0, no sheets limit policy is present. return this.destinationsManaged_ || this.settingsManaged_ || this.maxSheets_ > 0; } private onDestinationStateChange_() { switch (this.destinationState_) { case DestinationState.SELECTED: case DestinationState.SET: if (this.state !== State.NOT_READY && this.state !== State.FATAL_ERROR) { this.$.state.transitTo(State.NOT_READY); } break; case DestinationState.UPDATED: if (!this.$.model.initialized()) { this.$.model.applyStickySettings(); } this.$.model.applyDestinationSpecificPolicies(); this.startPreviewWhenReady_ = true; this.$.state.transitTo(State.READY); break; case DestinationState.ERROR: let newState = State.ERROR; // <if expr="chromeos_ash or chromeos_lacros"> if (this.error_ === Error.NO_DESTINATIONS) { newState = State.FATAL_ERROR; } // </if> this.$.state.transitTo(newState); break; default: break; } } /** * @param e Event containing the new sticky settings. */ private onStickySettingChanged_(e: CustomEvent<string>) { this.nativeLayer_!.saveAppState(e.detail); } private onPreviewSettingChanged_() { if (this.state === State.READY) { this.$.previewArea.startPreview(false); this.startPreviewWhenReady_ = false; } else { this.startPreviewWhenReady_ = true; } } private onStateChanged_() { if (this.state === State.READY) { if (this.startPreviewWhenReady_) { this.$.previewArea.startPreview(false); this.startPreviewWhenReady_ = false; } if (this.isInKioskAutoPrintMode_ || this.printRequested_) { this.onPrintRequested_(); // Reset in case printing fails. this.printRequested_ = false; } } else if (this.state === State.CLOSING) { this.remove(); this.nativeLayer_!.dialogClose(this.cancelled_); } else if (this.state === State.HIDDEN) { if (this.destination_.isLocal && getPrinterTypeForDestination(this.destination_) !== PrinterType.PDF_PRINTER) { // Only hide the preview for local, non PDF destinations. this.nativeLayer_!.hidePreview(); } } else if (this.state === State.PRINTING) { const destination = assert(this.destination_); const whenPrintDone = this.nativeLayer_!.print(this.$.model.createPrintTicket( destination, this.openPdfInPreview_, this.showSystemDialogBeforePrint_)); if (destination.isLocal) { const onError = getPrinterTypeForDestination(destination) === PrinterType.PDF_PRINTER ? this.onFileSelectionCancel_.bind(this) : this.onPrintFailed_.bind(this); whenPrintDone.then(this.close_.bind(this), onError); } else { // Cloud print resolves when print data is returned to submit to cloud // print, or if print ticket cannot be read, no PDF data is found, or // PDF is oversized. whenPrintDone.then( data => this.onPrintToCloud_(data!), this.onPrintFailed_.bind(this)); } } } private onPrintRequested_() { if (this.state === State.NOT_READY) { this.printRequested_ = true; return; } // <if expr="chromeos_ash or chromeos_lacros"> if (this.destination_ && this.destination_.origin === DestinationOrigin.CROS) { this.nativeLayerCros_!.recordPrinterStatusHistogram( this.destination_.printerStatusReason, true); } // </if> this.$.state.transitTo( this.$.previewArea.previewLoaded() ? State.PRINTING : State.HIDDEN); } private onCancelRequested_() { // <if expr="chromeos_ash or chromeos_lacros"> if (this.destination_ && this.destination_.origin === DestinationOrigin.CROS) { this.nativeLayerCros_!.recordPrinterStatusHistogram( this.destination_.printerStatusReason, false); } // </if> this.cancelled_ = true; this.$.state.transitTo(State.CLOSING); } /** * @param e The event containing the new validity. */ private onSettingValidChanged_(e: CustomEvent<boolean>) { if (e.detail) { this.$.state.transitTo(State.READY); } else { this.error_ = Error.INVALID_TICKET; this.$.state.transitTo(State.ERROR); } } private onFileSelectionCancel_() { this.$.state.transitTo(State.READY); } /** * Called when the native layer has retrieved the data to print to Google * Cloud Print. * @param data The body to send in the HTTP request. */ private onPrintToCloud_(data: string) { assert( this.cloudPrintInterface_ !== null, 'Google Cloud Print is not enabled'); const destination = assert(this.destination_); this.cloudPrintInterface_.submit( destination, this.$.model.createCloudJobTicket(destination), this.documentSettings_.title, data); } // <if expr="not chromeos and not lacros"> private onPrintWithSystemDialog_() { // <if expr="is_win"> this.showSystemDialogBeforePrint_ = true; this.onPrintRequested_(); // </if> // <if expr="not is_win"> this.nativeLayer_!.showSystemDialog(); this.$.state.transitTo(State.SYSTEM_DIALOG); // </if> } // </if> // <if expr="is_macosx"> private onOpenPdfInPreview_() { this.openPdfInPreview_ = true; this.$.previewArea.setOpeningPdfInPreview(); this.onPrintRequested_(); } // </if> /** * Called when printing to a cloud, or extension printer fails. * @param httpError The HTTP error code, or -1 or a string describing * the error, if not an HTTP error. */ private onPrintFailed_(httpError: number|string) { console.warn('Printing failed with error code ' + httpError); this.error_ = Error.PRINT_FAILED; this.$.state.transitTo(State.FATAL_ERROR); } private onPreviewStateChange_() { switch (this.previewState_) { case PreviewAreaState.DISPLAY_PREVIEW: case PreviewAreaState.OPEN_IN_PREVIEW_LOADED: if (this.state === State.HIDDEN) { this.$.state.transitTo(State.PRINTING); } break; case PreviewAreaState.ERROR: if (this.state !== State.ERROR && this.state !== State.FATAL_ERROR) { this.$.state.transitTo( this.error_ === Error.INVALID_PRINTER ? State.ERROR : State.FATAL_ERROR); } break; default: break; } } /** * Called when there was an error communicating with Google Cloud print. * Displays an error message in the print header. */ private onCloudPrintError_( appKioskMode: boolean, event: CustomEvent<CloudPrintInterfaceErrorEventDetail>) { if (event.detail.status === 0 || (event.detail.status === 403 && !appKioskMode)) { return; // No internet connectivity or not signed in. } this.cloudPrintErrorMessage_ = event.detail.message; this.error_ = Error.CLOUD_PRINT_ERROR; this.$.state.transitTo(State.FATAL_ERROR); if (event.detail.status === 200) { console.warn( 'Google Cloud Print Error: ' + `(${event.detail.errorCode}) ${event.detail.message}`); } else { console.warn( 'Google Cloud Print Error: ' + `HTTP status ${event.detail.status}`); } } /** * Updates printing options according to source document presets. * @param disableScaling Whether the document disables scaling. * @param copies The default number of copies from the document. * @param duplex The default duplex setting from the document. */ private onPrintPresetOptions_( disableScaling: boolean, copies: number, duplex: DuplexMode) { if (disableScaling) { this.$.documentInfo.updateIsScalingDisabled(true); } if (copies > 0 && this.getSetting('copies').available) { this.setSetting('copies', copies, true); } if (duplex === DuplexMode.UNKNOWN_DUPLEX_MODE) { return; } if (this.getSetting('duplex').available) { this.setSetting( 'duplex', duplex === DuplexMode.LONG_EDGE || duplex === DuplexMode.SHORT_EDGE, true); } if (duplex !== DuplexMode.SIMPLEX && this.getSetting('duplexShortEdge').available) { this.setSetting( 'duplexShortEdge', duplex === DuplexMode.SHORT_EDGE, true); } } /** * @param e Contains the new preview request ID. */ private onPreviewStart_(e: CustomEvent<number>) { this.$.documentInfo.inFlightRequestId = e.detail; } private close_() { this.$.state.transitTo(State.CLOSING); } } declare global { interface HTMLElementTagNameMap { 'print-preview-app': PrintPreviewAppElement; } } customElements.define(PrintPreviewAppElement.is, PrintPreviewAppElement);
the_stack
import BaseFoundation, { DefaultAdapter } from '../base/foundation'; import { numbers } from './constants'; export interface PaginationAdapter<P = Record<string, any>, S = Record<string, any>> extends DefaultAdapter<P, S> { setPageList: (pageListState: AdapterPageList) => void; setDisabled: (prevIsDisabled: boolean, nextIsDisabled: boolean) => void; updateTotal: (total: number) => void; updatePageSize: (pageSize: number) => void; updateQuickJumpPage: (quickJumpPage: string | number) => void; setCurrentPage: (pageIndex: number) => void; registerKeyDownHandler: (handler: KeyDownHandler) => void; unregisterKeyDownHandler: (handler: KeyDownHandler) => void; notifyPageChange: (pageIndex: number) => void; notifyPageSizeChange: (pageSize: number) => void; notifyChange: (pageIndex: number, pageSize: number) => void; } export type PageRenderText = number | '...'; export type PageList = PageRenderText[]; export interface AdapterPageList { pageList: PageRenderText[]; restLeftPageList: number[]; restRightPageList: number[]; } export type KeyDownHandler = any; class PaginationFoundation<P = Record<string, any>, S = Record<string, any>> extends BaseFoundation<PaginationAdapter<P, S>, P, S> { constructor(adapter: PaginationAdapter<P, S>) { super({ ...adapter }); } init() { const { currentPage, total, pageSize } = this.getStates(); // If pageSize is set, pageSizeOpts does not work this._updateDisabled({ currentPage, total, pageSize }); this._updatePageList({ currentPage, total, pageSize }); this._registerEventHandler(); } destroy() { this._unregisterEventHandler(); } _registerEventHandler() { this._adapter.registerKeyDownHandler(this.handleKeyDown); } _unregisterEventHandler() { this._adapter.unregisterKeyDownHandler(this.handleKeyDown); } _updateDisabled(pageInfo: { currentPage: number; total: number; pageSize: number }) { const { currentPage, total, pageSize } = pageInfo; const totalPageNum = this._getTotalPageNumber(total, pageSize); let prevIsDisabled = false; let nextIsDisabled = false; if (currentPage === 1) { prevIsDisabled = true; nextIsDisabled = totalPageNum < 2; } else if (currentPage === totalPageNum) { prevIsDisabled = false; nextIsDisabled = true; } this._adapter.setDisabled(prevIsDisabled, nextIsDisabled); } goPage(targetPageIndex: number | '...') { if (targetPageIndex === '...') { return; } const { pageSize, currentPage } = this.getStates(); const isControlComponent = this._isInProps('currentPage'); if (targetPageIndex === currentPage) { return; } if (!isControlComponent) { this.updatePage(targetPageIndex); this._adapter.notifyPageChange(targetPageIndex); this._adapter.notifyChange(targetPageIndex, pageSize); } else { this._adapter.notifyPageChange(targetPageIndex); this._adapter.notifyChange(targetPageIndex, pageSize); } } updatePage(targetPageIndex = 1, total?: number, pageSize?: number) { // maybe undefined or null if (total === null || typeof total === 'undefined') { total = this.getState('total'); } if (pageSize === null || typeof pageSize === 'undefined') { pageSize = this.getState('pageSize'); } this._updateDisabled({ currentPage: targetPageIndex, total, pageSize }); this._updatePageList({ currentPage: targetPageIndex, total, pageSize }); this._adapter.updateTotal(total); this._adapter.setCurrentPage(targetPageIndex); this._adapter.updatePageSize(pageSize); } goPrev() { const { currentPage } = this.getStates(); if (currentPage > 1) { this.goPage(currentPage - 1); } } goNext() { const { currentPage, total, pageSize } = this.getStates(); const totalPageNum = this._getTotalPageNumber(total, pageSize); if (currentPage <= totalPageNum - 1) { this.goPage(currentPage as number + 1); } } _updatePageList(pageListInfo: { currentPage: number; total: number; pageSize: number }) { const { currentPage, total, pageSize } = pageListInfo; let pageList: PageList = []; let restLeftPageList: number[] = []; // pages before ... let restRightPageList: number[] = []; // pages after ... /** Pager truncation logic (t is the total number of pages, c is the current page): - No need to truncate when t<=7 pages - When t>7 - When c<4, the fourth is a truncation symbol (...) - When c=4, the sixth is the truncation symbol (...) - When 4<c<t-3, the second and sixth are truncation symbols (...) - When t-3<=c<=t, the second is the truncation symbol (...), followed by the 5th from the bottom-the 1st from the bottom Truncation character + number, the total number is 7 分页器截断逻辑(t为总页数,c为当前页): - t<=7 页的时候不需要截断 - 当 t>7 时 - 当 c<4 时,第4个为截断符号(...) - 当 c=4 时,第6个为截断符号(...) - 当 4<c<t-3 时,第2个与第6个为截断符号(...) - 当 t-3<=c<=t 时,第 2 个为截断符号(...),后面为倒数第5个-倒数第1个 截断符+数字 总共个数为7个 */ const totalPageNum = this._getTotalPageNumber(total, pageSize); const { PAGE_SHOW_MAX, REST_PAGE_MAX_SIZE } = numbers; if (totalPageNum <= PAGE_SHOW_MAX) { pageList = Array.from({ length: totalPageNum }, (v, i) => i + 1); restLeftPageList = []; restRightPageList = []; } else { switch (true) { case currentPage < 4: pageList = [1, 2, 3, 4, '...', totalPageNum - 1, totalPageNum]; // length: (totalPageNum - 1) - 4 restRightPageList = Array.from({ length: Math.min(totalPageNum - 6, REST_PAGE_MAX_SIZE) }, (v, i) => i + 5); restLeftPageList = []; break; case currentPage === 4: pageList = [1, 2, 3, 4, 5, '...', totalPageNum]; restRightPageList = Array.from({ length: Math.min(totalPageNum - 6, REST_PAGE_MAX_SIZE) }, (v, i) => i + 6); restLeftPageList = []; break; case 4 < currentPage && currentPage < totalPageNum - 3: const middle = Array.from({ length: 3 }, (v, i) => currentPage + (i - 1)); pageList = ([1] as PageList).concat('...', middle, '...', totalPageNum); // length: total-(currentPage+1)-1 restRightPageList = Array.from( { length: Math.min(totalPageNum - currentPage - 2, REST_PAGE_MAX_SIZE) }, (v, i) => currentPage + i + 2 ); restLeftPageList = Array.from({ length: Math.min(currentPage - 3, REST_PAGE_MAX_SIZE) }, (v, i) => i + 2); break; case currentPage - 3 <= currentPage && currentPage <= totalPageNum: const right = Array.from({ length: 5 }, (v, i) => totalPageNum - (4 - i)); pageList = [1, '...' as const].concat(right); restRightPageList = []; restLeftPageList = Array.from({ length: Math.min(right[0] - 2, REST_PAGE_MAX_SIZE) }, (v, i) => i + 2); break; default: break; } } this._adapter.setPageList({ pageList, restLeftPageList, restRightPageList }); // this._adapter.setRestLeftPageList(restLeftPageList); // this._adapter.setRestRightPageList(restRightPageList); } changePageSize(newPageSize: number) { const { pageSize } = this.getStates(); this._adapter.updatePageSize(newPageSize); this._adapter.notifyPageSizeChange(newPageSize); const { total, currentPage } = this.getStates(); // After converting the switching page capacity, which page is the current page const currentPageFirstItemIndex = (currentPage - 1) * pageSize + 1; const newCurrentPage = Math.ceil(currentPageFirstItemIndex / newPageSize); this.updatePage(newCurrentPage, total, newPageSize); if (currentPage !== newCurrentPage) { this._adapter.notifyPageChange(newCurrentPage); } this._adapter.notifyChange(newCurrentPage, newPageSize); } // TODO handle tab/enter events // eslint-disable-next-line @typescript-eslint/no-empty-function handleKeyDown() { } // If pageSize is not in the Opts array, insert it pageSizeInOpts() { const { pageSizeOpts } = this.getProps(); const { pageSize } = this.getStates(); const newPageSizeOpts = [...pageSizeOpts]; if (newPageSizeOpts.indexOf(pageSize) === -1) { const firstLargerIndex = newPageSizeOpts.findIndex(el => el > pageSize); newPageSizeOpts.splice(firstLargerIndex, 0, pageSize); } return newPageSizeOpts; } handleQuickJumpNumberChange(targetPage: string | number) { this._adapter.updateQuickJumpPage(targetPage); } _handleQuickJump(quickJumpPage: string | number) { let page = Number(quickJumpPage); const { pageSize, total } = this.getStates(); const totalPageNum = this._getTotalPageNumber(total, pageSize); if (Number.isNaN(page)) { return; } // If the user input is greater than totalPage if (page > totalPageNum) { page = totalPageNum; } if (page <= 0) { page = 1; } // clear inputnumber this._adapter.updateQuickJumpPage(''); this.goPage(page); } handleQuickJumpBlur() { const { quickJumpPage } = this.getStates(); // no need to operate when inputnumber blur & quickJumpPage is empty if ((typeof quickJumpPage === 'string' && quickJumpPage) || typeof quickJumpPage === 'number') { this._handleQuickJump(quickJumpPage); } } handleQuickJumpEnterPress(targetPage: any) { this._handleQuickJump(targetPage); } _getTotalPageNumber(total: number, pageSize: number) { const totalPageNum = Math.ceil(total / pageSize); return totalPageNum; } } export default PaginationFoundation;
the_stack
import * as Common from '../../core/common/common.js'; import * as Host from '../../core/host/host.js'; import type * as SDK from '../../core/sdk/sdk.js'; import * as PerfUI from '../../ui/legacy/components/perf_ui/perf_ui.js'; import * as UI from '../../ui/legacy/legacy.js'; import * as ThemeSupport from '../../ui/legacy/theme_support/theme_support.js'; import {Bounds, formatMillisecondsToSeconds} from './TickingFlameChartHelpers.js'; const defaultFont = '11px ' + Host.Platform.fontFamily(); const defaultColor = ThemeSupport.ThemeSupport.instance().patchColorText('#444', ThemeSupport.ThemeSupport.ColorUsage.Foreground); const DefaultStyle = { height: 20, padding: 2, collapsible: false, font: defaultFont, color: defaultColor, backgroundColor: 'rgba(100 0 0 / 10%)', nestingLevel: 0, itemsHeight: 20, shareHeaderLine: false, useFirstLineForOverview: false, useDecoratorsForOverview: false, }; export const HotColorScheme = ['#ffba08', '#faa307', '#f48c06', '#e85d04', '#dc2f02', '#d00000', '#9d0208']; export const ColdColorScheme = ['#7400b8', '#6930c3', '#5e60ce', '#5390d9', '#4ea8de', '#48bfe3', '#56cfe1', '#64dfdf']; function calculateFontColor(backgroundColor: string): string { const parsedColor = Common.Color.Color.parse(backgroundColor); // Dark background needs a light font. if (parsedColor && parsedColor.hsla()[2] < 0.5) { return '#eee'; } return '#444'; } interface EventHandlers { setLive: (arg0: number) => number; setComplete: (arg0: number) => void; updateMaxTime: (arg0: number) => void; } export interface EventProperties { level: number; startTime: number; duration?: number; name: string; color?: string; hoverData?: Object|null; } /** * Wrapper class for each event displayed on the timeline. */ export class Event { private timelineData: PerfUI.FlameChart.TimelineData; private setLive: (arg0: number) => number; private readonly setComplete: (arg0: number) => void; private readonly updateMaxTime: (arg0: number) => void; private selfIndex: number; private liveInternal: boolean; title: string; private colorInternal: string; private fontColorInternal: string; private readonly hoverData: Object; constructor( timelineData: PerfUI.FlameChart.TimelineData, eventHandlers: EventHandlers, eventProperties: EventProperties| undefined = {color: undefined, duration: undefined, hoverData: {}, level: 0, name: '', startTime: 0}) { // These allow the event to privately change it's own data in the timeline. this.timelineData = timelineData; this.setLive = eventHandlers.setLive; this.setComplete = eventHandlers.setComplete; this.updateMaxTime = eventHandlers.updateMaxTime; // This is the index in the timelineData arrays we should be writing to. this.selfIndex = this.timelineData.entryLevels.length; this.liveInternal = false; // Can't use the dict||or||default syntax, since NaN is a valid expected duration. const duration = eventProperties['duration'] === undefined ? 0 : eventProperties['duration']; (this.timelineData.entryLevels as number[]).push(eventProperties['level'] || 0); (this.timelineData.entryStartTimes as number[]).push(eventProperties['startTime'] || 0); (this.timelineData.entryTotalTimes as number[]).push(duration); // May initially push -1 // If -1 was pushed, we need to update it. The set end time method helps with this. if (duration === -1) { this.endTime = -1; } this.title = eventProperties['name'] || ''; this.colorInternal = eventProperties['color'] || HotColorScheme[0]; this.fontColorInternal = calculateFontColor(this.colorInternal); this.hoverData = eventProperties['hoverData'] || {}; } /** * Render hovertext into the |htmlElement| */ decorate(htmlElement: HTMLElement): void { htmlElement.createChild('span').textContent = `Name: ${this.title}`; htmlElement.createChild('br'); const startTimeReadable = formatMillisecondsToSeconds(this.startTime, 2); if (this.liveInternal) { htmlElement.createChild('span').textContent = `Duration: ${startTimeReadable} - LIVE!`; } else if (!isNaN(this.duration)) { const durationReadable = formatMillisecondsToSeconds(this.duration + this.startTime, 2); htmlElement.createChild('span').textContent = `Duration: ${startTimeReadable} - ${durationReadable}`; } else { htmlElement.createChild('span').textContent = `Time: ${startTimeReadable}`; } } /** * set an event to be "live" where it's ended time is always the chart maximum * or to be a fixed time. * @param {number} time */ set endTime(time: number) { // Setting end time to -1 signals that an event becomes live if (time === -1) { this.timelineData.entryTotalTimes[this.selfIndex] = this.setLive(this.selfIndex); this.liveInternal = true; } else { this.liveInternal = false; const duration = time - this.timelineData.entryStartTimes[this.selfIndex]; this.timelineData.entryTotalTimes[this.selfIndex] = duration; this.setComplete(this.selfIndex); this.updateMaxTime(time); } } get id(): number { return this.selfIndex; } set level(level: number) { this.timelineData.entryLevels[this.selfIndex] = level; } set color(color: string) { this.colorInternal = color; this.fontColorInternal = calculateFontColor(this.colorInternal); } get color(): string { return this.colorInternal; } get fontColor(): string { return this.fontColorInternal; } get startTime(): number { // Round it return this.timelineData.entryStartTimes[this.selfIndex]; } get duration(): number { return this.timelineData.entryTotalTimes[this.selfIndex]; } get live(): boolean { return this.liveInternal; } } export class TickingFlameChart extends UI.Widget.VBox { private intervalTimer: number; private lastTimestamp: number; private canTickInternal: boolean; private ticking: boolean; private isShown: boolean; private readonly bounds: Bounds; private readonly dataProvider: TickingFlameChartDataProvider; private readonly delegate: TickingFlameChartDelegate; private readonly chartGroupExpansionSetting: Common.Settings.Setting<Object>; private readonly chart: PerfUI.FlameChart.FlameChart; private stoppedPermanently?: boolean; constructor() { super(); // set to update once per second _while the tab is active_ this.intervalTimer = 0; this.lastTimestamp = 0; this.canTickInternal = true; this.ticking = false; this.isShown = false; // The max bounds for scroll-out. this.bounds = new Bounds(0, 1000, 30000, 1000); // Create the data provider with the initial max bounds, // as well as a function to attempt bounds updating everywhere. this.dataProvider = new TickingFlameChartDataProvider(this.bounds, this.updateMaxTime.bind(this)); // Delegate doesn't do much for now. this.delegate = new TickingFlameChartDelegate(); // Chart settings. this.chartGroupExpansionSetting = Common.Settings.Settings.instance().createSetting('mediaFlameChartGroupExpansion', {}); // Create the chart. this.chart = // TODO(crbug.com/1172300) Ignored during the jsdoc to ts migration // @ts-expect-error new PerfUI.FlameChart.FlameChart(this.dataProvider, this.delegate, this.chartGroupExpansionSetting); // TODO: needs to have support in the delegate for supporting this. this.chart.disableRangeSelection(); // Scrolling should change the current bounds, and repaint the chart. this.chart.bindCanvasEvent('wheel', e => { this.onScroll(e as WheelEvent); }); // Add the chart. this.chart.show(this.contentElement); } /** * Add a marker with |properties| at |time|. */ addMarker(properties: EventProperties): void { properties['duration'] = NaN; this.startEvent(properties); } /** * Create an event which will be set to live by default. */ startEvent(properties: EventProperties): Event { // Make sure that an unspecified event gets live duration. // Have to check for undefined, since NaN is allowed but evaluates to false. if (properties['duration'] === undefined) { properties['duration'] = -1; } const time = properties['startTime'] || 0; // Event has to be created before the updateMaxTime call. const event = this.dataProvider.startEvent(properties); this.updateMaxTime(time); return event; } /** * Add a group with |name| that can contain |depth| different tracks. */ addGroup(name: Common.UIString.LocalizedString, depth: number): void { this.dataProvider.addGroup(name, depth); } private updateMaxTime(time: number): void { if (this.bounds.pushMaxAtLeastTo(time)) { this.updateRender(); } } private onScroll(e: WheelEvent): void { // TODO: is this a good divisor? does it account for high presicision scroll wheels? // low precisision scroll wheels? const scrollTickCount = Math.round(e.deltaY / 50); const scrollPositionRatio = e.offsetX / (e.srcElement as HTMLElement).clientWidth; if (scrollTickCount > 0) { this.bounds.zoomOut(scrollTickCount, scrollPositionRatio); } else { this.bounds.zoomIn(-scrollTickCount, scrollPositionRatio); } this.updateRender(); } willHide(): void { this.isShown = false; if (this.ticking) { this.stop(); } } wasShown(): void { this.isShown = true; if (this.canTickInternal && !this.ticking) { this.start(); } } set canTick(allowed: boolean) { this.canTickInternal = allowed; if (this.ticking && !allowed) { this.stop(); } if (!this.ticking && this.isShown && allowed) { this.start(); } } private start(): void { if (this.lastTimestamp === 0) { this.lastTimestamp = Date.now(); } if (this.intervalTimer !== 0 || this.stoppedPermanently) { return; } // 16 ms is roughly 60 fps. this.intervalTimer = window.setInterval(this.updateRender.bind(this), 16); this.ticking = true; } private stop(permanently: boolean = false): void { window.clearInterval(this.intervalTimer); this.intervalTimer = 0; if (permanently) { this.stoppedPermanently = true; } this.ticking = false; } private updateRender(): void { if (this.ticking) { const currentTimestamp = Date.now(); const duration = currentTimestamp - this.lastTimestamp; this.lastTimestamp = currentTimestamp; this.bounds.addMax(duration); } this.dataProvider.updateMaxTime(this.bounds); this.chart.setWindowTimes(this.bounds.low, this.bounds.high, true); this.chart.scheduleUpdate(); } } /** * Doesn't do much right now, but can be used in the future for selecting events. */ class TickingFlameChartDelegate implements PerfUI.FlameChart.FlameChartDelegate { constructor() { } windowChanged(_windowStartTime: number, _windowEndTime: number, _animate: boolean): void { } updateRangeSelection(_startTime: number, _endTime: number): void { } updateSelectedGroup(_flameChart: PerfUI.FlameChart.FlameChart, _group: PerfUI.FlameChart.Group|null): void { } } class TickingFlameChartDataProvider implements PerfUI.FlameChart.FlameChartDataProvider { private readonly updateMaxTimeHandle: (arg0: number) => void; private bounds: Bounds; private readonly liveEvents: Set<number>; private eventMap: Map<number, Event>; private readonly timelineDataInternal: PerfUI.FlameChart.TimelineData; private maxLevel: number; constructor(initialBounds: Bounds, updateMaxTime: (arg0: number) => void) { // do _not_ call this method from within this class - only for passing to events. this.updateMaxTimeHandle = updateMaxTime; this.bounds = initialBounds; // All the events which should have their time updated when the chart ticks. this.liveEvents = new Set(); // All events. // Map<Event> this.eventMap = new Map(); // Contains the numerical indicies. This is passed as a reference to the events // so that they can update it when they change. this.timelineDataInternal = new PerfUI.FlameChart.TimelineData([], [], [], []); // The current sum of all group heights. this.maxLevel = 0; } /** * Add a group with |name| that can contain |depth| different tracks. */ addGroup(name: Common.UIString.LocalizedString, depth: number): void { if (this.timelineDataInternal.groups) { this.timelineDataInternal.groups.push({ name: name, startLevel: this.maxLevel, expanded: true, selectable: false, style: DefaultStyle, track: null, }); } this.maxLevel += depth; } /** * Create an event which will be set to live by default. */ startEvent(properties: EventProperties): Event { properties['level'] = properties['level'] || 0; if (properties['level'] > this.maxLevel) { throw `level ${properties['level']} is above the maximum allowed of ${this.maxLevel}`; } const event = new Event( this.timelineDataInternal, { setLive: this.setLive.bind(this), setComplete: this.setComplete.bind(this), updateMaxTime: this.updateMaxTimeHandle, }, properties); this.eventMap.set(event.id, event); return event; } private setLive(index: number): number { this.liveEvents.add(index); return this.bounds.max; } private setComplete(index: number): void { this.liveEvents.delete(index); } updateMaxTime(bounds: Bounds): void { this.bounds = bounds; for (const eventID of this.liveEvents.entries()) { // force recalculation of all live events. (this.eventMap.get(eventID[0]) as Event).endTime = -1; } } maxStackDepth(): number { return this.maxLevel + 1; } timelineData(): PerfUI.FlameChart.TimelineData { return this.timelineDataInternal; } /** time in milliseconds */ minimumBoundary(): number { return this.bounds.low; } totalTime(): number { return this.bounds.high; } entryColor(index: number): string { return (this.eventMap.get(index) as Event).color; } textColor(index: number): string { return (this.eventMap.get(index) as Event).fontColor; } entryTitle(index: number): string|null { return (this.eventMap.get(index) as Event).title; } entryFont(_index: number): string|null { return defaultFont; } decorateEntry( _index: number, _context: CanvasRenderingContext2D, _text: string|null, _barX: number, _barY: number, _barWidth: number, _barHeight: number, _unclippedBarX: number, _timeToPixelRatio: number): boolean { return false; } forceDecoration(_index: number): boolean { return false; } prepareHighlightedEntryInfo(index: number): Element|null { const element = document.createElement('div'); (this.eventMap.get(index) as Event).decorate(element); return element; } formatValue(value: number, _precision?: number): string { // value is always [0, X] so we need to add lower bound value += Math.round(this.bounds.low); // Magic numbers of pre-calculated logorithms. // we want to show additional decimals at the time when two adjacent labels // would otherwise show the same number. At 3840 pixels wide, that cutoff // happens to be about 30 seconds for one decimal and 2.8 for two decimals. if (this.bounds.range < 2800) { return formatMillisecondsToSeconds(value, 2); } if (this.bounds.range < 30000) { return formatMillisecondsToSeconds(value, 1); } return formatMillisecondsToSeconds(value, 0); } canJumpToEntry(_entryIndex: number): boolean { return false; } navStartTimes(): Map<string, SDK.TracingModel.Event> { return new Map(); } }
the_stack
import React from 'react'; import { Box, Grid, Text, styled, Container, Flex, Heading, Paragraph, Section, Card, darkTheme, } from '@modulz/design-system'; import { MarketingCaption } from './MarketingCaption'; import { CodeDemo } from './CodeDemo'; enum Highlights { Unstyled = '1-18', Composable = '20-36', Customizable = '37-51', Consistent = '52-68', } export const DeveloperExperienceSection = () => { const [activeHighlight, setActiveHighlight] = React.useState<Highlights>(Highlights.Unstyled); return ( <Section css={{ overflow: 'hidden', backgroundColor: '$sky6', background: ` radial-gradient(ellipse at 100% 100%, hsl(254 100% 6% / 0.07), $violetA1, transparent), linear-gradient(to bottom right, $mint2, $indigo2, $pink3, $cyan3) `, [`&.${darkTheme}`]: { background: 'linear-gradient(to bottom right, $sky2, $cyan2, $cyan6)', }, }} > <Container size="3"> <Grid gap={{ '@initial': 5, '@bp3': 8 }} css={{ '@bp2': { gridTemplateColumns: 'auto 1fr' } }} > <Box css={{ '@bp2': { maxWidth: 420 } }}> <MarketingCaption css={{ mb: '$1' }}>Developer experience to love</MarketingCaption> <Heading as="h2" size="3" css={{ mb: '$4' }}> Develop with an open, thought‑out API </Heading> <Paragraph css={{ mb: '$5', maxWidth: 500 }}> One of our main goals is to provide the best possible developer experience. Radix Primitives provides a fully-typed API. All components share a similar API, creating a consistent and predictable experience. </Paragraph> <Box css={{ width: '100vw', pl: '$5', mx: '-$5', // Don't cut off box shadows py: '$1', overflowX: 'scroll', overflowY: 'hidden', WebkitOverflowScrolling: 'touch', MsOverflowStyle: 'none', scrollbarWidth: 'none', '&::-webkit-scrollbar': { display: 'none', }, '@bp2': { display: 'none', }, }} > <Grid gapX={{ '@initial': 3, '@bp1': 5, }} gapY={3} flow="column" css={{ gridTemplateColumns: 'repeat(4, max-content) 1px', gridTemplateRows: '410px auto', }} > <CodeWindow className={darkTheme}> <StyledCodeDemo value={code.unstyled} language="jsx" css={{ p: '$2' }} /> </CodeWindow> <Box> <Text as="h3" size="3" css={{ fontWeight: 500, lineHeight: 1.5 }}> Unstyled </Text> <Text as="p" size="3" css={{ lineHeight: 1.5, color: '$slateA11' }}> No need to override styles, no specificity wars. </Text> </Box> <CodeWindow className={darkTheme}> <StyledCodeDemo value={code.composable} language="jsx" css={{ p: '$2' }} /> </CodeWindow> <Box> <Text as="h3" size="3" css={{ fontWeight: 500, lineHeight: 1.5 }}> Composable </Text> <Text as="p" size="3" css={{ lineHeight: 1.5, color: '$slateA11' }}> Granular access to each component part. </Text> </Box> <CodeWindow className={darkTheme}> <StyledCodeDemo value={code.customizable} language="jsx" css={{ p: '$2' }} /> </CodeWindow> <Box> <Text as="h3" size="3" css={{ fontWeight: 500, lineHeight: 1.5 }}> Customizable </Text> <Text as="p" size="3" css={{ lineHeight: 1.5, color: '$slateA11' }}> Configure behavior, control focus, add event listeners. </Text> </Box> <CodeWindow className={darkTheme}> <StyledCodeDemo value={code.consistent} language="jsx" css={{ p: '$2' }} /> </CodeWindow> <Box> <Text as="h3" size="3" css={{ fontWeight: 500, lineHeight: 1.5 }}> Consistent </Text> <Text as="p" size="3" css={{ lineHeight: 1.5, color: '$slateA11' }}> Components with similar functionality share similar API. </Text> </Box> <Box /> </Grid> </Box> <Flex gap="1" direction="column" css={{ ml: '-$3', display: 'none', '@bp2': { display: 'flex' } }} > <BlendedCard as="button" onMouseDown={() => setActiveHighlight(Highlights.Unstyled)} onClick={() => setActiveHighlight(Highlights.Unstyled)} variant={activeHighlight === Highlights.Unstyled ? 'active' : 'ghost'} > <Box css={{ p: '$3' }}> <Text as="h3" size="3" css={{ fontWeight: 500, lineHeight: 1.5 }}> Unstyled </Text> <Text as="p" size="3" css={{ lineHeight: 1.5, color: '$slateA11' }}> No need to override styles, no specificity wars. </Text> </Box> </BlendedCard> <BlendedCard as="button" onMouseDown={() => setActiveHighlight(Highlights.Composable)} onClick={() => setActiveHighlight(Highlights.Composable)} variant={activeHighlight === Highlights.Composable ? 'active' : 'ghost'} > <Box css={{ p: '$3' }}> <Text as="h3" size="3" css={{ fontWeight: 500, lineHeight: 1.5 }}> Composable </Text> <Text as="p" size="3" css={{ lineHeight: 1.5, color: '$slateA11' }}> Granular access to each component part. </Text> </Box> </BlendedCard> <BlendedCard as="button" onMouseDown={() => setActiveHighlight(Highlights.Customizable)} onClick={() => setActiveHighlight(Highlights.Customizable)} variant={activeHighlight === Highlights.Customizable ? 'active' : 'ghost'} > <Box css={{ p: '$3' }}> <Text as="h3" size="3" css={{ fontWeight: 500, lineHeight: 1.5 }}> Customizable </Text> <Text as="p" size="3" css={{ lineHeight: 1.5, color: '$slateA11' }}> Configure behavior, control focus, add event listeners. </Text> </Box> </BlendedCard> <BlendedCard as="button" onMouseDown={() => setActiveHighlight(Highlights.Consistent)} onClick={() => setActiveHighlight(Highlights.Consistent)} variant={activeHighlight === Highlights.Consistent ? 'active' : 'ghost'} > <Box css={{ p: '$3' }}> <Text as="h3" size="3" css={{ fontWeight: 500, lineHeight: 1.5 }}> Consistent </Text> <Text as="p" size="3" css={{ lineHeight: 1.5, color: '$slateA11' }}> Components with similar functionality share similar API. </Text> </Box> </BlendedCard> </Flex> </Box> <Box css={{ position: 'relative', minWidth: 480, display: 'none', '@bp2': { display: 'block' }, }} > <CodeWindow withChrome className={darkTheme} css={{ position: 'absolute', inset: 0, overflow: 'hidden' }} > <StyledCodeDemo language="jsx" value={allCode} line={activeHighlight} data-invert-line-highlight="false" css={{ padding: 0, height: '100%', userSelect: 'auto', $$background: 'transparent', $$text: '$colors$cyan12', $$outline: 'none', $$syntax1: '$colors$purple11', // $$syntax2: '$colors$cyan11', $$syntax2: '$colors$cyan11', $$syntax3: '$colors$crimson11', $$syntax4: '$$text', $$comment: '$colors$slateA11', $$removed: '$colors$crimson11', $$added: '$colors$teal11', $$fadedLines: '$colors$slateA8', }} /> </CodeWindow> </Box> </Grid> </Container> </Section> ); }; const StyledCodeDemo = React.forwardRef<HTMLPreElement, React.ComponentProps<typeof CodeDemo>>( ({ css, ...props }, forwardedRef) => ( <CodeDemo ref={forwardedRef} data-invert-line-highlight="false" css={{ padding: 0, height: '100%', userSelect: 'auto', $$background: 'transparent', $$text: '$colors$cyan12', $$outline: 'none', $$syntax1: '$colors$purple11', // $$syntax2: '$colors$cyan11', $$syntax2: '$colors$cyan11', $$syntax3: '$colors$crimson11', $$syntax4: '$$text', $$comment: '$colors$slateA11', $$removed: '$colors$crimson11', $$added: '$colors$teal11', $$fadedLines: '$colors$slateA8', ...css, }} {...props} /> ) ); const CodeWindow = styled('div', { $$bgColor: '$colors$sky1', [`&.${darkTheme}`]: { $$bgColor: '$colors$sky2', }, [`.${darkTheme} &.${darkTheme}`]: { $$bgColor: '$colors$violet1', }, position: 'relative', bc: '$$bgColor', br: '$4', variants: { withChrome: { true: { px: '$2', pt: '$6', pb: '$2', boxShadow: '0 50px 100px -50px hsl(254 100% 6% / 0.7)', '&::before': { position: 'absolute', top: 10, left: 10, width: 52, height: 12, content: '""', background: ` radial-gradient(circle closest-side at 6px, $slateA7 90%, #FFFFFF00), radial-gradient(circle closest-side at 24px, $slateA7 90%, #FFFFFF00), radial-gradient(circle closest-side at 42px, $slateA7 90%, #FFFFFF00) `, }, '&::after': { position: 'absolute', top: 8, left: 0, right: 0, fontFamily: '$untitled', fontSize: '$1', textAlign: 'center', color: '$slate9', content: '"DeploymentDetail.jsx"', }, }, }, }, }); const BlendedCard = styled(Card, { $$shadowColor: '$colors$skyA12', $$bgColor: '$colors$plum1', [`.${darkTheme} &`]: { $$shadowColor: '$colors$blackA12', $$bgColor: '$colors$whiteA4', }, cursor: 'default', position: 'relative', zIndex: 1, willChange: 'transform', backgroundColor: '$$bgColor', '&::before': { boxShadow: '0 0 0 1px $colors$blackA3', }, // Fix a bug when hovering at card edges would cause the card to jitter because of transform '@hover': { '&:hover::after': { content: '', inset: -3, position: 'absolute', }, }, variants: { variant: { active: { '&::before': { boxShadow: '0px 4px 16px -12px $$shadowColor', }, '&:active': { transition: 'transform 150ms cubic-bezier(0.22, 1, 0.36, 1)', }, '&:focus:not(:focus-visible)': { boxShadow: 'none', }, }, ghost: { '&::before': { boxShadow: '0px 4px 16px -12px $$shadowColor', }, '@hover': { '&:hover': { backgroundColor: '$$bgColor', }, }, '&:focus:not(:focus-visible)': { boxShadow: 'none', }, }, }, }, }); const code = { unstyled: `// Add styles with your preferred CSS technology const TooltipContent = styled(Tooltip.Content, { backgroundColor: 'black', borderRadius: '3px', padding: '5px' }); const PopoverContent = styled(Popover.Content, { backgroundColor: 'white', boxShadow: '0 2px 10px -3px rgb(0 0 0 / 20%)', borderRadius: '3px', }); const DialogContent = styled(Dialog.Content, { backgroundColor: 'white', boxShadow: '0 3px 15px -4px rgb(0 0 0 / 30%)', borderRadius: '5px', });`, composable: `// Compose a custom Tooltip component export const StatusTooltip = ({ state, label }) => { return ( <Tooltip.Root> <Tooltip.Trigger asChild> <Text> <Status variant={state} /> </Text> </Tooltip.Trigger> <TooltipContent> <Tooltip.Arrow /> {label} </TooltipContent> </Tooltip.Root> ); };`, customizable: `// Compose a Popover with custom focus and positioning export const DeploymentPopover = ({ children }) => { const popoverCloseButton = React.useRef(null); return ( <Popover.Root> <Popover.Trigger>View deployment</Popover.Trigger> <PopoverContent align="start" collisionTolerance={10} portalled={false} onOpenAutoFocus={(event) => { // Focus the close button when popover opens event.preventDefault(); popoverCloseButton.current?.focus(); }} > {children} <Popover.Close ref={popoverCloseButton}> Close </Popover.Close> </PopoverContent> </Popover.Root> ); };`, consistent: `// Compose a Dialog with custom focus management export const InfoDialog = ({ children }) => { const dialogCloseButton = React.useRef(null); return ( <Dialog.Root> <Dialog.Trigger>View details</Dialog.Trigger> <Dialog.Overlay /> <DialogContent onOpenAutoFocus={(event) => { // Focus the close button when dialog opens event.preventDefault(); dialogCloseButton.current?.focus(); }} > {children} <Dialog.Close ref={dialogCloseButton}> Close </Dialog.Close> </DialogContent> </Dialog.Root> ); };`, }; const allCode = [code.unstyled, code.composable, code.customizable, code.consistent].join('\n\n');
the_stack
// clang-format off import 'chrome://settings/settings.js'; import {loadTimeData} from 'chrome://resources/js/load_time_data.m.js'; import {flush} from 'chrome://resources/polymer/v3_0/polymer/polymer_bundled.min.js'; import {AutofillManagerImpl, CountryDetailManager, CountryDetailManagerImpl, CrInputElement, SettingsAddressEditDialogElement, SettingsAddressRemoveConfirmationDialogElement, SettingsAutofillSectionElement, SettingsTextareaElement} from 'chrome://settings/lazy_load.js'; import {assertEquals, assertFalse, assertTrue} from 'chrome://webui-test/chai_assert.js'; import {eventToPromise, whenAttributeIs} from 'chrome://webui-test/test_util.js'; import {AutofillManagerExpectations, createAddressEntry, createEmptyAddressEntry, TestAutofillManager} from './passwords_and_autofill_fake_data.js'; // clang-format on /** * Test implementation. */ class CountryDetailManagerTestImpl implements CountryDetailManager { getCountryList() { return new Promise<chrome.autofillPrivate.CountryEntry[]>(function( resolve) { resolve([ {name: 'United States', countryCode: 'US'}, // Default test country. {name: 'Israel', countryCode: 'IL'}, {name: 'United Kingdom', countryCode: 'GB'}, ]); }); } getAddressFormat(countryCode: string) { return new Promise<chrome.autofillPrivate.AddressComponents>(function( resolve) { chrome.autofillPrivate.getAddressComponents(countryCode, resolve); }); } } /** * Resolves the promise after the element fires the expected event. |causeEvent| * is called after adding a listener to make sure that the event is captured. */ function expectEvent( element: Element, eventName: string, causeEvent: () => void) { const promise = eventToPromise(eventName, element); causeEvent(); return promise; } /** * Creates the autofill section for the given list. */ function createAutofillSection( addresses: chrome.autofillPrivate.AddressEntry[], prefValues: any): SettingsAutofillSectionElement { // Override the AutofillManagerImpl for testing. const autofillManager = new TestAutofillManager(); autofillManager.data.addresses = addresses; AutofillManagerImpl.setInstance(autofillManager); const section = document.createElement('settings-autofill-section'); section.prefs = {autofill: prefValues}; document.body.appendChild(section); flush(); return section; } /** * Creates the Edit Address dialog and fulfills the promise when the dialog * has actually opened. */ function createAddressDialog(address: chrome.autofillPrivate.AddressEntry): Promise<SettingsAddressEditDialogElement> { return new Promise(function(resolve) { const section = document.createElement('settings-address-edit-dialog'); section.address = address; document.body.appendChild(section); eventToPromise('on-update-address-wrapper', section).then(function() { resolve(section); }); }); } /** * Creates the remove address dialog. Simulate clicking "Remove" button in * autofill section. */ function createRemoveAddressDialog(autofillManager: TestAutofillManager): SettingsAddressRemoveConfirmationDialogElement { const address = createAddressEntry(); // Override the AutofillManagerImpl for testing. autofillManager.data.addresses = [address]; AutofillManagerImpl.setInstance(autofillManager); document.body.innerHTML = ''; const section = document.createElement('settings-autofill-section'); document.body.appendChild(section); flush(); const addressList = section.$.addressList; const row = addressList.children[0]; assertTrue(!!row); // Simulate clicking the 'Remove' button in the menu. row!.querySelector<HTMLElement>('#addressMenu')!.click(); flush(); assertFalse(!!section.shadowRoot!.querySelector( 'settings-address-remove-confirmation-dialog')); section.$.menuRemoveAddress.click(); flush(); const removeAddressDialog = section.shadowRoot!.querySelector( 'settings-address-remove-confirmation-dialog'); assertTrue(!!removeAddressDialog); return removeAddressDialog!; } suite('AutofillSectionUiTest', function() { test('testAutofillExtensionIndicator', function() { // Initializing with fake prefs const section = document.createElement('settings-autofill-section'); section.prefs = {autofill: {profile_enabled: {}}}; document.body.appendChild(section); assertFalse( !!section.shadowRoot!.querySelector('#autofillExtensionIndicator')); section.set('prefs.autofill.profile_enabled.extensionId', 'test-id'); flush(); assertTrue( !!section.shadowRoot!.querySelector('#autofillExtensionIndicator')); }); }); suite('AutofillSectionAddressTests', function() { suiteSetup(function() { CountryDetailManagerImpl.setInstance(new CountryDetailManagerTestImpl()); }); setup(function() { document.body.innerHTML = ''; }); test('verifyNoAddresses', function() { const section = createAutofillSection([], {profile_enabled: {value: true}}); const addressList = section.$.addressList; assertTrue(!!addressList); // 1 for the template element. assertEquals(1, addressList.children.length); assertFalse(section.$.noAddressesLabel.hidden); assertFalse(section.$.addAddress.disabled); assertFalse(section.$.autofillProfileToggle.disabled); }); test('verifyAddressCount', function() { const addresses = [ createAddressEntry(), createAddressEntry(), createAddressEntry(), createAddressEntry(), createAddressEntry(), ]; const section = createAutofillSection(addresses, {profile_enabled: {value: true}}); const addressList = section.$.addressList; assertTrue(!!addressList); assertEquals( addresses.length, addressList.querySelectorAll('.list-item').length); assertTrue(section.$.noAddressesLabel.hidden); assertFalse(section.$.autofillProfileToggle.disabled); assertFalse(section.$.addAddress.disabled); }); test('verifyAddressDisabled', function() { const section = createAutofillSection([], {profile_enabled: {value: false}}); assertFalse(section.$.autofillProfileToggle.disabled); assertTrue(section.$.addAddress.hidden); }); test('verifyAddressFields', function() { const address = createAddressEntry(); const section = createAutofillSection([address], {}); const addressList = section.$.addressList; const row = addressList.children[0]; assertTrue(!!row); const addressSummary = address.metadata!.summaryLabel + address.metadata!.summarySublabel; let actualSummary = ''; // Eliminate white space between nodes! const addressPieces = row!.querySelector('#addressSummary')!.children; for (const addressPiece of addressPieces) { actualSummary += addressPiece.textContent!.trim(); } assertEquals(addressSummary, actualSummary); }); test('verifyAddressRowButtonTriggersDropdown', function() { const address = createAddressEntry(); const section = createAutofillSection([address], {}); const addressList = section.$.addressList; const row = addressList.children[0]; assertTrue(!!row); const menuButton = row!.querySelector<HTMLElement>('#addressMenu'); assertTrue(!!menuButton); menuButton!.click(); flush(); assertTrue(!!section.shadowRoot!.querySelector('#menuEditAddress')); assertTrue(!!section.$.menuRemoveAddress); }); test('verifyAddAddressDialog', function() { const address = createEmptyAddressEntry(); return createAddressDialog(address).then(function(dialog) { const title = dialog.shadowRoot!.querySelector('[slot=title]')!; assertEquals( loadTimeData.getString('addAddressTitle'), title.textContent); // A country is preselected. assertTrue(!!address.countryCode); }); }); test('verifyEditAddressDialog', function() { return createAddressDialog(createAddressEntry()).then(function(dialog) { const title = dialog.shadowRoot!.querySelector('[slot=title]')!; assertEquals( loadTimeData.getString('editAddressTitle'), title.textContent); // Should be possible to save when editing because fields are // populated. assertFalse(dialog.$.saveButton.disabled); }); }); // The first editable element should be focused by default. test('verifyFirstFieldFocused', async function() { const dialog = await createAddressDialog(createEmptyAddressEntry()); const currentFocus = dialog.shadowRoot!.activeElement; const editableElements = dialog.$.dialog.querySelectorAll('cr-input, select'); assertEquals(editableElements[0], currentFocus); }); test('verifyRemoveAddressDialogConfirmed', async function() { const autofillManager = new TestAutofillManager(); const removeAddressDialog = createRemoveAddressDialog(autofillManager); // Wait for the dialog to open. await whenAttributeIs(removeAddressDialog.$.dialog, 'open', ''); removeAddressDialog.$.remove.click(); // Wait for the dialog to close. await eventToPromise('close', removeAddressDialog); assertTrue(removeAddressDialog.wasConfirmed()); const expected = new AutofillManagerExpectations(); expected.requestedAddresses = 1; expected.listeningAddresses = 1; expected.removeAddress = 1; autofillManager.assertExpectations(expected); }); test('verifyRemoveAddressDialogCanceled', async function() { const autofillManager = new TestAutofillManager(); const removeAddressDialog = createRemoveAddressDialog(autofillManager); // Wait for the dialog to open. await whenAttributeIs(removeAddressDialog.$.dialog, 'open', ''); removeAddressDialog.$.cancel.click(); // Wait for the dialog to close. await eventToPromise('close', removeAddressDialog); assertFalse(removeAddressDialog.wasConfirmed()); const expected = new AutofillManagerExpectations(); expected.requestedAddresses = 1; expected.listeningAddresses = 1; expected.removeAddress = 0; autofillManager.assertExpectations(expected); }); test('verifyCountryIsSaved', function() { const address = createEmptyAddressEntry(); return createAddressDialog(address).then(function(dialog) { const countrySelect = dialog.shadowRoot!.querySelector('select')!; // The country should be pre-selected. assertEquals('US', countrySelect.value); assertEquals('US', address.countryCode); countrySelect.value = 'GB'; countrySelect.dispatchEvent(new CustomEvent('change')); flush(); assertEquals('GB', countrySelect.value); assertEquals('GB', address.countryCode); }); }); test('verifyPhoneAndEmailAreSaved', function() { const address = createEmptyAddressEntry(); return createAddressDialog(address).then(function(dialog) { assertEquals('', dialog.$.phoneInput.value); assertFalse(!!(address.phoneNumbers && address.phoneNumbers[0])); assertEquals('', dialog.$.emailInput.value); assertFalse(!!(address.emailAddresses && address.emailAddresses[0])); const phoneNumber = '(555) 555-5555'; const emailAddress = 'no-reply@chromium.org'; dialog.$.phoneInput.value = phoneNumber; dialog.$.emailInput.value = emailAddress; return expectEvent(dialog, 'save-address', function() { dialog.$.saveButton.click(); }).then(function() { assertEquals(phoneNumber, dialog.$.phoneInput.value); assertEquals(phoneNumber, address.phoneNumbers![0]); assertEquals(emailAddress, dialog.$.emailInput.value); assertEquals(emailAddress, address.emailAddresses![0]); }); }); }); test('verifyHonorificIsSaved', async function() { loadTimeData.overrideValues({showHonorific: true}); const address = createEmptyAddressEntry(); const dialog = await createAddressDialog(address); const honorificElement = dialog.$.dialog .querySelectorAll<SettingsTextareaElement|CrInputElement>( 'settings-textarea, cr-input')[0]!; assertEquals(undefined, honorificElement.value); assertFalse(!!address.honorific); const honorific = 'Lord'; honorificElement.value = honorific; await expectEvent( dialog, 'save-address', () => dialog.$.saveButton.click()); assertEquals(honorific, honorificElement.value); assertEquals(honorific, address.honorific); }); test('verifyPhoneAndEmailAreRemoved', function() { const address = createEmptyAddressEntry(); const phoneNumber = '(555) 555-5555'; const emailAddress = 'no-reply@chromium.org'; address.countryCode = 'US'; // Set to allow save to be active. address.phoneNumbers = [phoneNumber]; address.emailAddresses = [emailAddress]; return createAddressDialog(address).then(function(dialog) { assertEquals(phoneNumber, dialog.$.phoneInput.value); assertEquals(emailAddress, dialog.$.emailInput.value); dialog.$.phoneInput.value = ''; dialog.$.emailInput.value = ''; return expectEvent(dialog, 'save-address', function() { dialog.$.saveButton.click(); }).then(function() { assertEquals(0, address.phoneNumbers!.length); assertEquals(0, address.emailAddresses!.length); }); }); }); // Test will set a value of 'foo' in each text field and verify that the // save button is enabled, then it will clear the field and verify that the // save button is disabled. Test passes after all elements have been tested. test('verifySaveIsNotClickableIfAllInputFieldsAreEmpty', async function() { const dialog = await createAddressDialog(createEmptyAddressEntry()); const saveButton = dialog.$.saveButton; const testElements = dialog.$.dialog .querySelectorAll<SettingsTextareaElement|CrInputElement>( 'settings-textarea, cr-input'); // The country can be preselected. Clear it to ensure the form is empty. await expectEvent(dialog, 'on-update-can-save', function() { const countrySelect = dialog.shadowRoot!.querySelector('select')!; countrySelect.value = ''; countrySelect.dispatchEvent(new CustomEvent('change')); }); // Default country is 'US' expecting: Honorific, Name, Organization, // Street address, City, State, ZIP code, Phone, and Email. // Unless Company name or honorific is disabled. const company_enabled = loadTimeData.getBoolean('EnableCompanyName'); const honorific_enabled = loadTimeData.getBoolean('showHonorific'); assertEquals( 7 + (company_enabled ? 1 : 0) + (honorific_enabled ? 1 : 0), testElements.length); assertTrue(saveButton.disabled); for (const element of testElements) { await expectEvent(dialog, 'on-update-can-save', function() { element.value = 'foo'; }); assertFalse(saveButton.disabled); await expectEvent(dialog, 'on-update-can-save', function() { element.value = ''; }); assertTrue(saveButton.disabled); } }); // Setting the country should allow the address to be saved. test('verifySaveIsNotClickableIfCountryNotSet', async function() { function simulateCountryChange(countryCode: string) { const countrySelect = dialog.shadowRoot!.querySelector('select')!; countrySelect.value = countryCode; countrySelect.dispatchEvent(new CustomEvent('change')); } const dialog = await createAddressDialog(createEmptyAddressEntry()); // A country code is preselected. assertFalse(dialog.$.saveButton.disabled); assertEquals(dialog.address.countryCode, 'US'); await expectEvent( dialog, 'on-update-can-save', simulateCountryChange.bind(null, 'GB')); assertFalse(dialog.$.saveButton.disabled); await expectEvent( dialog, 'on-update-can-save', simulateCountryChange.bind(null, '')); assertTrue(dialog.$.saveButton.disabled); }); // Test will timeout if save-address event is not fired. test('verifyDefaultCountryIsAppliedWhenSaving', function() { const address = createEmptyAddressEntry(); address.fullNames = ['Name']; return createAddressDialog(address).then(function(dialog) { return expectEvent(dialog, 'save-address', function() { // Verify |countryCode| is not set. assertEquals(undefined, address.countryCode); dialog.$.saveButton.click(); }).then(function(event) { // 'US' is the default country for these tests. assertEquals('US', event.detail.countryCode); }); }); }); test('verifyCancelDoesNotSaveAddress', function(done) { createAddressDialog(createAddressEntry()).then(function(dialog) { eventToPromise('save-address', dialog).then(function() { // Fail the test because the save event should not be called when // cancel is clicked. assertTrue(false); }); eventToPromise('close', dialog).then(function() { // Test is |done| in a timeout in order to ensure that // 'save-address' is NOT fired after this test. window.setTimeout(done, 100); }); dialog.$.cancelButton.click(); }); }); }); suite('AutofillSectionAddressLocaleTests', function() { suiteSetup(function() { CountryDetailManagerImpl.setInstance(new CountryDetailManagerTestImpl()); }); setup(function() { document.body.innerHTML = ''; }); // US address has 3 fields on the same line. test('verifyEditingUSAddress', function() { const address = createEmptyAddressEntry(); const company_enabled = loadTimeData.getBoolean('EnableCompanyName'); const honorific_enabled = loadTimeData.getBoolean('showHonorific'); address.honorific = 'Honorific'; address.fullNames = ['Name']; address.companyName = 'Organization'; address.addressLines = 'Street address'; address.addressLevel2 = 'City'; address.addressLevel1 = 'State'; address.postalCode = 'ZIP code'; address.countryCode = 'US'; address.phoneNumbers = ['Phone']; address.emailAddresses = ['Email']; return createAddressDialog(address).then(function(dialog) { const rows = dialog.$.dialog.querySelectorAll('.address-row'); assertEquals( 5 + (company_enabled ? 1 : 0) + (honorific_enabled ? 1 : 0), rows.length); let index = 0; // Country let row = rows[index]!; const countrySelect = row.querySelector('select'); assertTrue(!!countrySelect); assertEquals( 'United States', countrySelect!.selectedOptions[0]!.textContent!.trim()); index++; // Honorific if (honorific_enabled) { row = rows[index]!; const cols = row.querySelectorAll<SettingsTextareaElement|CrInputElement>( '.address-column'); assertEquals(1, cols.length); assertEquals(address.honorific, cols[0]!.value); index++; } // Name row = rows[index]!; let cols = row.querySelectorAll<SettingsTextareaElement|CrInputElement>( '.address-column'); assertEquals(1, cols.length); assertEquals(address.fullNames![0], cols[0]!.value); index++; // Organization if (company_enabled) { row = rows[index]!; cols = row.querySelectorAll<SettingsTextareaElement|CrInputElement>( '.address-column'); assertEquals(1, cols.length); assertEquals(address.companyName, cols[0]!.value); index++; } // Street address row = rows[index]!; cols = row.querySelectorAll<SettingsTextareaElement|CrInputElement>( '.address-column'); assertEquals(1, cols.length); assertEquals(address.addressLines, cols[0]!.value); index++; // City, State, ZIP code row = rows[index]!; cols = row.querySelectorAll<SettingsTextareaElement|CrInputElement>( '.address-column'); assertEquals(3, cols.length); assertEquals(address.addressLevel2, cols[0]!.value); assertEquals(address.addressLevel1, cols[1]!.value); assertEquals(address.postalCode, cols[2]!.value); index++; // Phone, Email row = rows[index]!; cols = row.querySelectorAll<SettingsTextareaElement|CrInputElement>( '.address-column'); assertEquals(2, cols.length); assertEquals(address.phoneNumbers![0], cols[0]!.value); assertEquals(address.emailAddresses![0], cols[1]!.value); }); }); // GB address has 1 field per line for all lines that change. test('verifyEditingGBAddress', function() { const address = createEmptyAddressEntry(); const company_enabled = loadTimeData.getBoolean('EnableCompanyName'); const honorific_enabled = loadTimeData.getBoolean('showHonorific'); address.honorific = 'Lord'; address.fullNames = ['Name']; address.companyName = 'Organization'; address.addressLines = 'Street address'; address.addressLevel2 = 'Post town'; address.postalCode = 'Postal code'; address.countryCode = 'GB'; address.phoneNumbers = ['Phone']; address.emailAddresses = ['Email']; return createAddressDialog(address).then(function(dialog) { const rows = dialog.$.dialog.querySelectorAll('.address-row'); assertEquals( 6 + (company_enabled ? 1 : 0) + (honorific_enabled ? 1 : 0), rows.length); let index = 0; // Country let row = rows[index]!; const countrySelect = row.querySelector('select'); assertTrue(!!countrySelect); assertEquals( 'United Kingdom', countrySelect!.selectedOptions[0]!.textContent!.trim()); index++; // Honorific if (honorific_enabled) { row = rows[index]!; const cols = row.querySelectorAll<SettingsTextareaElement|CrInputElement>( '.address-column'); assertEquals(1, cols.length); assertEquals(address.honorific, cols[0]!.value); index++; } // Name row = rows[index]!; let cols = row.querySelectorAll<SettingsTextareaElement|CrInputElement>( '.address-column'); assertEquals(1, cols.length); assertEquals(address.fullNames![0], cols[0]!.value); index++; // Organization if (company_enabled) { row = rows[index]!; cols = row.querySelectorAll<SettingsTextareaElement|CrInputElement>( '.address-column'); assertEquals(1, cols.length); assertEquals(address.companyName, cols[0]!.value); index++; } // Street address row = rows[index]!; cols = row.querySelectorAll<SettingsTextareaElement|CrInputElement>( '.address-column'); assertEquals(1, cols.length); assertEquals(address.addressLines, cols[0]!.value); index++; // Post Town row = rows[index]!; cols = row.querySelectorAll<SettingsTextareaElement|CrInputElement>( '.address-column'); assertEquals(1, cols.length); assertEquals(address.addressLevel2, cols[0]!.value); index++; // Postal code row = rows[index]!; cols = row.querySelectorAll<SettingsTextareaElement|CrInputElement>( '.address-column'); assertEquals(1, cols.length); assertEquals(address.postalCode, cols[0]!.value); index++; // Phone, Email row = rows[index]!; cols = row.querySelectorAll<SettingsTextareaElement|CrInputElement>( '.address-column'); assertEquals(2, cols.length); assertEquals(address.phoneNumbers![0], cols[0]!.value); assertEquals(address.emailAddresses![0], cols[1]!.value); }); }); // IL address has 2 fields on the same line and is an RTL locale. // RTL locale shouldn't affect this test. test('verifyEditingILAddress', function() { const address = createEmptyAddressEntry(); const company_enabled = loadTimeData.getBoolean('EnableCompanyName'); const honorific_enabled = loadTimeData.getBoolean('showHonorific'); address.honorific = 'Honorific'; address.fullNames = ['Name']; address.companyName = 'Organization'; address.addressLines = 'Street address'; address.addressLevel2 = 'City'; address.postalCode = 'Postal code'; address.countryCode = 'IL'; address.phoneNumbers = ['Phone']; address.emailAddresses = ['Email']; return createAddressDialog(address).then(function(dialog) { const rows = dialog.$.dialog.querySelectorAll('.address-row'); assertEquals( 5 + (company_enabled ? 1 : 0) + (honorific_enabled ? 1 : 0), rows.length); let index = 0; // Country let row = rows[index]!; const countrySelect = row.querySelector('select'); assertTrue(!!countrySelect); assertEquals( 'Israel', countrySelect!.selectedOptions[0]!.textContent!.trim()); index++; // Honorific if (honorific_enabled) { row = rows[index]!; const cols = row.querySelectorAll<SettingsTextareaElement|CrInputElement>( '.address-column'); assertEquals(1, cols.length); assertEquals(address.honorific, cols[0]!.value); index++; } // Name row = rows[index]!; let cols = row.querySelectorAll<SettingsTextareaElement|CrInputElement>( '.address-column'); assertEquals(1, cols.length); assertEquals(address.fullNames![0], cols[0]!.value); index++; // Organization if (company_enabled) { row = rows[index]!; cols = row.querySelectorAll<SettingsTextareaElement|CrInputElement>( '.address-column'); assertEquals(1, cols.length); assertEquals(address.companyName, cols[0]!.value); index++; } // Street address row = rows[index]!; cols = row.querySelectorAll<SettingsTextareaElement|CrInputElement>( '.address-column'); assertEquals(1, cols.length); assertEquals(address.addressLines, cols[0]!.value); index++; // City, Postal code row = rows[index]!; cols = row.querySelectorAll<SettingsTextareaElement|CrInputElement>( '.address-column'); assertEquals(2, cols.length); assertEquals(address.addressLevel2, cols[0]!.value); assertEquals(address.postalCode, cols[1]!.value); index++; // Phone, Email row = rows[index]!; cols = row.querySelectorAll<SettingsTextareaElement|CrInputElement>( '.address-column'); assertEquals(2, cols.length); assertEquals(address.phoneNumbers![0], cols[0]!.value); assertEquals(address.emailAddresses![0], cols[1]!.value); }); }); // US has an extra field 'State'. Validate that this field is // persisted when switching to IL then back to US. test('verifyAddressPersistanceWhenSwitchingCountries', function() { const address = createEmptyAddressEntry(); const company_enabled = loadTimeData.getBoolean('EnableCompanyName'); const honorific_enabled = loadTimeData.getBoolean('showHonorific'); const experimental_fields_count = (company_enabled ? 1 : 0) + (honorific_enabled ? 1 : 0); address.countryCode = 'US'; return createAddressDialog(address).then(function(dialog) { const city = 'Los Angeles'; const state = 'CA'; const zip = '90291'; const countrySelect = dialog.shadowRoot!.querySelector('select')!; return expectEvent( dialog, 'on-update-address-wrapper', function() { // US: const rows = dialog.$.dialog.querySelectorAll('.address-row'); assertEquals(5 + experimental_fields_count, rows.length); // City, State, ZIP code const row = rows[3 + experimental_fields_count]!; const cols = row.querySelectorAll<SettingsTextareaElement| CrInputElement>('.address-column'); assertEquals(3, cols.length); cols[0]!.value = city; cols[1]!.value = state; cols[2]!.value = zip; countrySelect.value = 'IL'; countrySelect.dispatchEvent(new CustomEvent('change')); }) .then(function() { return expectEvent(dialog, 'on-update-address-wrapper', function() { // IL: const rows = dialog.$.dialog.querySelectorAll('.address-row'); assertEquals(5 + experimental_fields_count, rows.length); // City, Postal code const row = rows[3 + experimental_fields_count]!; const cols = row.querySelectorAll<SettingsTextareaElement|CrInputElement>( '.address-column'); assertEquals(2, cols.length); assertEquals(city, cols[0]!.value); assertEquals(zip, cols[1]!.value); countrySelect.value = 'US'; countrySelect.dispatchEvent(new CustomEvent('change')); }); }) .then(function() { // US: const rows = dialog.$.dialog.querySelectorAll('.address-row'); assertEquals(5 + experimental_fields_count, rows.length); // City, State, ZIP code const row = rows[3 + experimental_fields_count]!; const cols = row.querySelectorAll<SettingsTextareaElement|CrInputElement>( '.address-column'); assertEquals(3, cols.length); assertEquals(city, cols[0]!.value); assertEquals(state, cols[1]!.value); assertEquals(zip, cols[2]!.value); }); }); }); });
the_stack
import { GLSLContext, IAttribute, IAttributeInitializationOptions, IBuffer, IBufferInitializationOptions, IClearOptions, IElements, IElementsInitializationOptions, IFramebuffer, IFramebufferInitializationOptions, IModel, IModelInitializationOptions, IReadPixelsOptions, IRendererConfig, IRendererService, isSafari, ITexture2D, ITexture2DInitializationOptions, IViewport, } from '@antv/g-webgpu-core'; // import { Glslang } from '@webgpu/glslang/dist/web-devel/glslang.onefile'; import * as WebGPUConstants from '@webgpu/types/dist/constants'; import { vec4 } from 'gl-matrix'; import { injectable } from 'inversify'; import glslang from './glslang'; import WebGPUAttribute from './WebGPUAttribute'; import WebGPUBuffer from './WebGPUBuffer'; import WebGPUComputeModel from './WebGPUComputeModel'; import WebGPUElements from './WebGPUElements'; import WebGPUFramebuffer from './WebGPUFramebuffer'; import WebGPUModel from './WebGPUModel'; import WebGPUTexture2D from './WebGPUTexture2D'; type Omit<T, K extends keyof T> = Pick<T, Exclude<keyof T, K>>; type WithOptional<T, K extends keyof T> = Omit<T, K> & Partial<Pick<T, K>>; /** * regl renderer */ @injectable() export class WebGPUEngine implements IRendererService { public supportWebGPU = true; public useWGSL = false; public options: IRendererConfig; public canvas: HTMLCanvasElement; public context: GPUCanvasContext; public glslang: any; public adapter: GPUAdapter; public device: GPUDevice; public swapChain: GPUSwapChain; public mainPassSampleCount: number; public mainTexture: GPUTexture; public depthTexture: GPUTexture; public mainColorAttachments: GPURenderPassColorAttachmentDescriptor[]; public mainTextureExtends: GPUExtent3D; public mainDepthAttachment: GPURenderPassDepthStencilAttachmentDescriptor; // Frame Life Cycle (recreated each frame) public uploadEncoder: GPUCommandEncoder; public renderEncoder: GPUCommandEncoder; public computeEncoder: GPUCommandEncoder; public renderTargetEncoder: GPUCommandEncoder; public commandBuffers: GPUCommandBuffer[] = new Array(4).fill(undefined); // Frame Buffer Life Cycle (recreated for each render target pass) public currentRenderPass: GPURenderPassEncoder | null = null; public mainRenderPass: GPURenderPassEncoder | null = null; public currentRenderTargetViewDescriptor: GPUTextureViewDescriptor; public currentComputePass: GPUComputePassEncoder | null = null; public bundleEncoder: GPURenderBundleEncoder | null; public tempBuffers: GPUBuffer[] = []; public currentRenderTarget: WebGPUFramebuffer | null = null; public readonly uploadEncoderDescriptor = { label: 'upload' }; public readonly renderEncoderDescriptor = { label: 'render' }; public readonly renderTargetEncoderDescriptor = { label: 'renderTarget' }; public readonly computeEncoderDescriptor = { label: 'compute' }; /** * 通过名称访问 */ private pipelines: { [pipelineName: string]: GPURenderPipeline; } = {}; private computePipelines: { [pipelineName: string]: GPUComputePipeline; } = {}; private readonly defaultSampleCount = 4; private readonly clearDepthValue = 1; private readonly clearStencilValue = 0; private transientViewport: IViewport = { x: Infinity, y: 0, width: 0, height: 0, }; private cachedViewport: IViewport = { x: 0, y: 0, width: 0, height: 0, }; public isFloatSupported() { return true; } public async init(config: IRendererConfig): Promise<void> { this.canvas = config.canvas; this.options = config; this.useWGSL = !!config.useWGSL; this.mainPassSampleCount = config.antialiasing ? this.defaultSampleCount : 1; await this.initGlslang(); this.initContextAndSwapChain(); this.initMainAttachments(); } public clear = (options: IClearOptions): void => { const { framebuffer, color, depth, stencil } = options; if (this.options.supportCompute) { this.startComputePass(); } // We need to recreate the render pass so that the new parameters for clear color / depth / stencil are taken into account if (this.currentRenderTarget) { if (this.currentRenderPass) { this.endRenderTargetRenderPass(); } this.startRenderTargetRenderPass( this.currentRenderTarget!, color ? color : null, !!depth, !!stencil, ); } else { // if (this.useReverseDepthBuffer) { // this._depthCullingState.depthFunc = Constants.GREATER; // } this.mainColorAttachments[0].loadValue = color ? color : WebGPUConstants.LoadOp.Load; this.mainDepthAttachment.depthLoadValue = depth ? depth : WebGPUConstants.LoadOp.Load; this.mainDepthAttachment.stencilLoadValue = stencil ? this.clearStencilValue : WebGPUConstants.LoadOp.Load; if (this.mainRenderPass) { this.endMainRenderPass(); } this.startMainRenderPass(); } }; public createModel = async ( options: IModelInitializationOptions, ): Promise<IModel> => { const model = new WebGPUModel(this, options); await model.init(); return model; }; public createAttribute = ( options: IAttributeInitializationOptions, ): IAttribute => { return new WebGPUAttribute(this, options); }; public createBuffer = (options: IBufferInitializationOptions): IBuffer => { return new WebGPUBuffer(this, options); }; public createElements = ( options: IElementsInitializationOptions, ): IElements => { return new WebGPUElements(this, options); }; public createTexture2D = ( options: ITexture2DInitializationOptions, ): ITexture2D => { return new WebGPUTexture2D(this, options); }; public createFramebuffer = ( options: IFramebufferInitializationOptions, ): IFramebuffer => { return new WebGPUFramebuffer(this, options); }; public useFramebuffer = ( framebuffer: IFramebuffer | null, drawCommands: () => void, ): void => { // bind if (this.currentRenderTarget) { this.unbindFramebuffer(this.currentRenderTarget); } this.currentRenderTarget = framebuffer as WebGPUFramebuffer; // TODO: use mipmap options in framebuffer this.currentRenderTargetViewDescriptor = { dimension: WebGPUConstants.TextureViewDimension.E2d, // mipLevelCount: bindWithMipMaps ? WebGPUTextureHelper.computeNumMipmapLevels(texture.width, texture.height) - lodLevel : 1, // baseArrayLayer: faceIndex, // baseMipLevel: lodLevel, arrayLayerCount: 1, aspect: WebGPUConstants.TextureAspect.All, }; this.currentRenderPass = null; drawCommands(); }; public createComputeModel = async (context: GLSLContext) => { const model = new WebGPUComputeModel(this, context); await model.init(); return model; }; public getCanvas = (): HTMLCanvasElement => { return this.canvas; }; public getGLContext = (): WebGLRenderingContext => { throw new Error('Method not implemented.'); }; public viewport = ({ x, y, width, height, }: { x: number; y: number; width: number; height: number; }): void => { if (!this.currentRenderPass) { // call viewport() before current render pass created this.transientViewport = { x, y, width, height }; } else if (this.transientViewport.x !== Infinity) { const renderPass = this.getCurrentRenderPass(); // @see https://gpuweb.github.io/gpuweb/#dom-gpurenderpassencoder-setviewport renderPass.setViewport( this.transientViewport.x, this.transientViewport.y, this.transientViewport.width, this.transientViewport.height, 0, 1, ); } else if ( x !== this.cachedViewport.x || y !== this.cachedViewport.y || width !== this.cachedViewport.width || height !== this.cachedViewport.height ) { this.cachedViewport = { x, y, width, height }; const renderPass = this.getCurrentRenderPass(); renderPass.setViewport(x, y, width, height, 0, 1); } }; public readPixels = (options: IReadPixelsOptions): Uint8Array => { throw new Error('Method not implemented.'); }; public destroy(): void { if (this.mainTexture) { this.mainTexture.destroy(); } if (this.depthTexture) { this.depthTexture.destroy(); } this.tempBuffers.forEach((buffer) => buffer.destroy()); this.tempBuffers = []; } public beginFrame() { this.uploadEncoder = this.device.createCommandEncoder( this.uploadEncoderDescriptor, ); this.renderEncoder = this.device.createCommandEncoder( this.renderEncoderDescriptor, ); this.renderTargetEncoder = this.device.createCommandEncoder( this.renderTargetEncoderDescriptor, ); if (this.options.supportCompute) { this.computeEncoder = this.device.createCommandEncoder( this.computeEncoderDescriptor, ); } } public endFrame() { if (this.options.supportCompute) { this.endComputePass(); } this.endMainRenderPass(); this.commandBuffers[0] = this.uploadEncoder.finish(); this.commandBuffers[1] = this.renderEncoder.finish(); if (this.options.supportCompute) { this.commandBuffers[2] = this.computeEncoder.finish(); } this.commandBuffers[3] = this.renderTargetEncoder.finish(); if (isSafari) { this.device // @ts-ignore .getQueue() .submit(this.commandBuffers.filter((buffer) => buffer)); } else { this.device.defaultQueue.submit( this.commandBuffers.filter((buffer) => buffer), ); } } public getCurrentRenderPass(): GPURenderPassEncoder { if (this.currentRenderTarget && !this.currentRenderPass) { this.startRenderTargetRenderPass( this.currentRenderTarget, null, false, false, ); } else if (!this.currentRenderPass) { this.startMainRenderPass(); } return this.currentRenderPass!; } private async initGlslang() { this.glslang = await glslang(); this.adapter = (await navigator?.gpu?.requestAdapter()) as GPUAdapter; this.device = (await this.adapter.requestDevice()) as GPUDevice; } private initContextAndSwapChain() { this.context = (this.canvas.getContext( isSafari ? 'gpu' : 'gpupresent', ) as unknown) as GPUCanvasContext; this.swapChain = this.context.configureSwapChain({ device: this.device, format: this.options.swapChainFormat!, usage: WebGPUConstants.TextureUsage.OutputAttachment | WebGPUConstants.TextureUsage.CopySrc, }); } private initMainAttachments() { this.mainTextureExtends = { width: this.canvas.width, height: this.canvas.height, depth: 1, }; if (this.options.antialiasing) { const mainTextureDescriptor = { size: this.mainTextureExtends, // TODO: arrayLayerCount is deprecated: use size.depth // arrayLayerCount: 1, mipLevelCount: 1, sampleCount: this.mainPassSampleCount, dimension: WebGPUConstants.TextureDimension.E2d, format: WebGPUConstants.TextureFormat.BGRA8Unorm, usage: WebGPUConstants.TextureUsage.OutputAttachment, }; if (this.mainTexture) { this.mainTexture.destroy(); } this.mainTexture = this.device.createTexture(mainTextureDescriptor); this.mainColorAttachments = [ { attachment: isSafari ? // @ts-ignore this.mainTexture.createDefaultView() : this.mainTexture.createView(), loadValue: [0, 0, 0, 1], storeOp: WebGPUConstants.StoreOp.Store, }, ]; } else { this.mainColorAttachments = [ { attachment: isSafari ? // @ts-ignore this.swapChain.getCurrentTexture().createDefaultView() : this.swapChain.getCurrentTexture().createView(), loadValue: [0, 0, 0, 1], storeOp: WebGPUConstants.StoreOp.Store, }, ]; } const depthTextureDescriptor = { size: this.mainTextureExtends, // arrayLayerCount: 1, mipLevelCount: 1, sampleCount: this.mainPassSampleCount, dimension: WebGPUConstants.TextureDimension.E2d, format: isSafari ? 'depth32float-stencil8' : WebGPUConstants.TextureFormat.Depth24PlusStencil8, usage: WebGPUConstants.TextureUsage.OutputAttachment, }; if (this.depthTexture) { this.depthTexture.destroy(); } this.depthTexture = this.device.createTexture( // @ts-ignore depthTextureDescriptor, ); this.mainDepthAttachment = { attachment: isSafari ? // @ts-ignore this.depthTexture.createDefaultView() : this.depthTexture.createView(), depthLoadValue: this.clearDepthValue, depthStoreOp: WebGPUConstants.StoreOp.Store, stencilLoadValue: this.clearStencilValue, stencilStoreOp: WebGPUConstants.StoreOp.Store, }; } private startComputePass() { if (this.currentComputePass) { this.endComputePass(); } this.currentComputePass = this.computeEncoder.beginComputePass(); } private startMainRenderPass() { if (this.currentRenderPass && !this.currentRenderTarget) { this.endMainRenderPass(); } // Resolve in case of MSAA if (this.options.antialiasing) { this.mainColorAttachments[0].resolveTarget = isSafari ? // @ts-ignore this.swapChain.getCurrentTexture().createDefaultView() : this.swapChain.getCurrentTexture().createView(); } else { this.mainColorAttachments[0].attachment = isSafari ? // @ts-ignore this.swapChain.getCurrentTexture().createDefaultView() : this.swapChain.getCurrentTexture().createView(); } this.currentRenderPass = this.renderEncoder.beginRenderPass({ colorAttachments: this.mainColorAttachments, depthStencilAttachment: this.mainDepthAttachment, // TODO: use framebuffer's depth & stencil }); this.mainRenderPass = this.currentRenderPass; if (this.cachedViewport) { this.viewport(this.cachedViewport); } } private startRenderTargetRenderPass( renderTarget: WebGPUFramebuffer, clearColor: [number, number, number, number] | null, clearDepth: boolean, clearStencil: boolean = false, ) { const gpuTexture = renderTarget.get().color?.texture; let colorTextureView: GPUTextureView; if (gpuTexture) { colorTextureView = gpuTexture.createView( this.currentRenderTargetViewDescriptor, ); } const depthStencilTexture = renderTarget.get().depth?.texture; let depthStencilTextureView; if (depthStencilTexture) { depthStencilTextureView = depthStencilTexture.createView(); } const renderPass = this.renderTargetEncoder.beginRenderPass({ colorAttachments: [ { attachment: colorTextureView!, loadValue: clearColor !== null ? clearColor : WebGPUConstants.LoadOp.Load, storeOp: WebGPUConstants.StoreOp.Store, }, ], depthStencilAttachment: depthStencilTexture && depthStencilTextureView ? { attachment: depthStencilTextureView, depthLoadValue: clearDepth ? this.clearDepthValue : WebGPUConstants.LoadOp.Load, depthStoreOp: WebGPUConstants.StoreOp.Store, stencilLoadValue: clearStencil ? this.clearStencilValue : WebGPUConstants.LoadOp.Load, stencilStoreOp: WebGPUConstants.StoreOp.Store, } : undefined, }); this.currentRenderPass = renderPass; if (this.cachedViewport) { this.viewport(this.cachedViewport); } // TODO WEBGPU set the scissor rect and the stencil reference value } private endMainRenderPass() { if ( this.currentRenderPass === this.mainRenderPass && this.currentRenderPass !== null ) { this.currentRenderPass.endPass(); this.resetCachedViewport(); this.currentRenderPass = null; this.mainRenderPass = null; } } private endComputePass() { if (this.currentComputePass) { this.currentComputePass.endPass(); this.currentComputePass = null; } } private endRenderTargetRenderPass() { if (this.currentRenderPass) { this.currentRenderPass.endPass(); this.resetCachedViewport(); } } private resetCachedViewport() { this.cachedViewport = { x: 0, y: 0, width: 0, height: 0, }; } private unbindFramebuffer(framebuffer: WebGPUFramebuffer) { // unbind if ( this.currentRenderPass && this.currentRenderPass !== this.mainRenderPass ) { this.endRenderTargetRenderPass(); } this.transientViewport.x = Infinity; this.currentRenderTarget = null; // if (texture.generateMipMaps && !disableGenerateMipMaps && !texture.isCube) { // this._generateMipmaps(texture); // } this.currentRenderPass = this.mainRenderPass; } }
the_stack
import React from 'react' import { expect, mount, within, wait } from '@instructure/ui-test-utils' import { ScreenReaderFocusRegion } from '../ScreenReaderFocusRegion' describe('ScreenReaderFocusRegion', async () => { const element = ( <div data-test-parent role="main" aria-label="test app" id="test-parent3"> <div data-test-ignore role="alert"> <span>test alert</span> </div> <div data-test-child> <div data-test-descendant>foo</div> <div data-test-descendant> <div data-test-descendant>bar</div> </div> </div> <div data-test-parent aria-hidden="true" id="test-parent2"> <div data-test-child></div> <div role="dialog" aria-label="some content" data-test-parent id="test-parent1" > <div data-test-content> <div>Hello world</div> <button>click me</button> <button>or click me</button> </div> <span data-test-child> <ul data-test-descendant> <li data-test-descendant>item 1</li> <li data-test-descendant>item 2</li> <li data-test-descendant>item 3</li> </ul> </span> </div> </div> <div data-test-child aria-hidden="true"> <div data-test-descendant>foo</div> <div data-test-descendant>bar</div> </div> </div> ) it('should accept a function for liveRegion', async () => { const subject = await mount(element) const main = within(subject.getDOMNode()) const ignore = (await main.find('[data-test-ignore]')).getDOMNode() const content = (await main.find('[data-test-content]')).getDOMNode() const screenReaderFocusRegion = new ScreenReaderFocusRegion(content, { liveRegion: () => ignore, shouldContainFocus: true }) screenReaderFocusRegion.activate() expect(ignore.getAttribute('aria-hidden')).to.not.exist() }) it("should apply aria-hidden to all children of content's parent nodes unless they are live regions", async () => { const subject = await mount(element) const main = within(subject.getDOMNode()) const ignore = (await main.find('[data-test-ignore]')).getDOMNode() const content = (await main.find('[data-test-content]')).getDOMNode() const children = await main.findAll('[data-test-child]') const screenReaderFocusRegion = new ScreenReaderFocusRegion(content, { liveRegion: ignore, shouldContainFocus: true }) screenReaderFocusRegion.activate() children.forEach((node) => { expect(node.getAttribute('aria-hidden')).to.exist() }) expect(ignore.getAttribute('aria-hidden')).to.not.exist() }) it("should mute designated attributes for content's parent nodes", async () => { const subject = await mount(element) const main = within(subject.getDOMNode()) const content = (await main.find('[data-test-content]')).getDOMNode() const parents = await main.findAll('[data-test-parent]') const screenReaderFocusRegion = new ScreenReaderFocusRegion(content) screenReaderFocusRegion.activate() parents.forEach((node) => { expect(node.getAttribute('aria-hidden')).to.not.exist() expect(node.getAttribute('aria-label')).to.not.exist() expect(node.getAttribute('role')).to.not.exist() }) }) it('should not apply aria-hidden to descendants', async () => { const subject = await mount(element) const main = within(subject.getDOMNode()) const content = (await main.find('[data-test-content]')).getDOMNode() const descendants = await main.findAll('[data-test-descendant]') const screenReaderFocusRegion = new ScreenReaderFocusRegion(content) screenReaderFocusRegion.activate() descendants.forEach((node) => { expect(node.getAttribute('aria-hidden')).to.not.exist() }) }) it('should not apply aria-hidden to dynamically added descendants of content', async () => { const subject = await mount(element) const main = within(subject.getDOMNode()) const content = (await main.find('[data-test-content]')).getDOMNode() const screenReaderFocusRegion = new ScreenReaderFocusRegion(content) screenReaderFocusRegion.activate() const desc = document.createElement('div') content.appendChild(desc) screenReaderFocusRegion.handleDOMMutation([ ({ addedNodes: [desc], removedNodes: [] } as unknown) as MutationRecord ]) Array.from(content.childNodes).forEach((node) => { // @ts-expect-error ts-migrate(2571) FIXME: Object is of type 'unknown'. expect(node.getAttribute('aria-hidden')).to.not.exist() }) }) it('should remove aria-hidden from children unless they had aria-hidden before', async () => { const subject = await mount(element) const main = within(subject.getDOMNode()) const content = (await main.find('[data-test-content]')).getDOMNode() const screenReaderFocusRegion = new ScreenReaderFocusRegion(content) const childNodes = await main.findAll( '[data-test-child]:not([aria-hidden="true"])' ) const exception = await main.find('[data-test-child][aria-hidden="true"]') screenReaderFocusRegion.activate() screenReaderFocusRegion.deactivate() await wait(() => { childNodes.forEach((node) => { expect(node.getAttribute('aria-hidden')).to.not.exist() }) }) expect(exception.getAttribute('aria-hidden')).to.exist() }) it('should properly restore and unmute parent attributes', async () => { const subject = await mount(element) const main = within(subject.getDOMNode()) const content = (await main.find('[data-test-content]')).getDOMNode() const screenReaderFocusRegion = new ScreenReaderFocusRegion(content) const attrsMap = {} const parentNodes = await main.findAll('[data-test-parent]') parentNodes.forEach((node) => { // @ts-expect-error ts-migrate(7053) FIXME: Element implicitly has an 'any' type because expre... Remove this comment to see the full error message attrsMap[node.getAttribute('id')] = [...node.getDOMNode().attributes] }) screenReaderFocusRegion.activate() screenReaderFocusRegion.deactivate() parentNodes.forEach((node) => { // @ts-expect-error ts-migrate(7053) FIXME: Element implicitly has an 'any' type because expre... Remove this comment to see the full error message const preNodeAttrs = attrsMap[node.getAttribute('id')] const postNodeAttrs = [...node.getDOMNode().attributes] expect(preNodeAttrs.length).to.equal(postNodeAttrs.length) // both should have same number of attributes // @ts-expect-error ts-migrate(7006) FIXME: Parameter 'preNodeAttribute' implicitly has an 'an... Remove this comment to see the full error message preNodeAttrs.forEach((preNodeAttribute) => { const matchingAttribute = postNodeAttrs.filter( (postNodeAttribute) => preNodeAttribute.name === postNodeAttribute.name )[0] expect(matchingAttribute.value).to.equal(preNodeAttribute.value) }) }) }) it('should not apply aria-hidden to elements that have aria-live attributes', async () => { const subject = await mount( <div data-test-main role="main" aria-label="test app"> <div data-test-live aria-live="assertive"></div> <div data-test-regular></div> <div data-test-content></div> </div> ) const main = within(subject.getDOMNode()) const content = (await main.find('[data-test-content]')).getDOMNode() const screenReaderFocusRegion = new ScreenReaderFocusRegion(content) screenReaderFocusRegion.activate() const liveRegion = (await main.find('[data-test-live]')).getDOMNode() const regularRegion = (await main.find('[data-test-regular]')).getDOMNode() expect(liveRegion.getAttribute('aria-hidden')).to.not.exist() expect(regularRegion.getAttribute('aria-hidden')).to.exist() }) it('should hide the body element of any iframes present on the page', async () => { const subject = await mount( <div> <div data-test-ignore> <iframe title="unhidden" width="100%" height="100px" /> </div> <iframe title="hidden" width="100%" height="100px" /> <div> <iframe title="hidden" width="100%" height="100px" /> <div data-test-content> <span> <iframe title="unhidden" width="100%" height="100px" /> </span> <div>Hello world</div> <button>click me</button> <button>or click me</button> <iframe title="unhidden" width="100%" height="100px" /> </div> <div> <span> <iframe title="hidden" width="100%" height="100px" /> <iframe title="hidden" width="100%" height="100px" /> </span> </div> <iframe title="always-hidden" width="100%" height="100px" /> </div> </div> ) const main = within(subject.getDOMNode()) const content = (await main.find('[data-test-content]')).getDOMNode() const ignore = (await main.find('[data-test-ignore]')).getDOMNode() // @ts-expect-error ts-migrate(7006) FIXME: Parameter 'iframe' implicitly has an 'any' type. const getIframeBody = (iframe) => iframe.getDOMNode().contentDocument.body const alwaysHidden = getIframeBody( await main.find('iframe[title="always-hidden"]') ) alwaysHidden.setAttribute('aria-hidden', 'true') const screenReaderFocusRegion = new ScreenReaderFocusRegion(content, { liveRegion: ignore, shouldContainFocus: true }) // verify no iframe bodies are hidden unless they were hidden initially const iframes = await main.findAll('iframe:not([title="always-hidden"])') iframes.forEach((iframe) => { expect(getIframeBody(iframe).getAttribute('aria-hidden')).to.not.exist() }) expect(alwaysHidden.getAttribute('aria-hidden')).to.equal('true') screenReaderFocusRegion.activate() // once activated, all iframe bodies should be hidden except for iframes that // are contained in the defined content element or live region const hiddenIframes = await main.findAll('iframe[title="hidden"]') hiddenIframes.forEach((iframe) => { expect(getIframeBody(iframe).getAttribute('aria-hidden')).to.equal('true') }) const unhiddenIframes = await main.findAll('iframe[title="unhidden"]') unhiddenIframes.forEach((iframe) => { expect(getIframeBody(iframe).getAttribute('aria-hidden')).to.not.exist() }) expect(alwaysHidden.getAttribute('aria-hidden')).to.equal('true') screenReaderFocusRegion.deactivate() // should restore all iframe bodies iframes.forEach((iframe) => { expect(getIframeBody(iframe).getAttribute('aria-hidden')).to.not.exist() }) expect(alwaysHidden.getAttribute('aria-hidden')).to.equal('true') }) })
the_stack
import { Component, OnInit, AfterViewInit, AfterViewChecked, ApplicationRef } from '@angular/core'; import { Chart, registerShape } from '@antv/g2'; import { DashboardService } from 'src/app/business/dashboard.service'; import { UriConfig } from 'src/app/configs/uri-config'; const signalR = require("@microsoft/signalr"); @Component({ selector: 'app-dashboard', templateUrl: './dashboard.component.html', styleUrls: ['./dashboard.component.less'], providers: [ApplicationRef] }) export class DashboardComponent implements OnInit, AfterViewInit { data = { userCount: 0, roleCount: 0, departmentCount: 0, positionCount: 0 }; chartArray = []; // 仪表盘图对象 cpuChart; // 内存折线图 memoryChart; // 内存折线图数据 memoryChartData = [ ]; // 垃圾回收区域大小饼图 garbageChart; // 垃圾回收区域大小饼图数据 garbageChartData = [ { item: '第0代', count: 0, percent: 0 }, { item: '第1代', count: 0, percent: 0 }, { item: '第2代', count: 0, percent: 0 }, ]; // 应用内存 workingSet = 0; // 垃圾回收堆内存 gcHeapSize = 0; // 垃圾回收代数 gen0Count = 0; gen1Count = 0; gen2Count = 0; // 线程池相关 handelThreadPoolThreadCount = 0; handelMonitorLockContentionCount = 0; threadPoolQueueLength = 0; threadPoolCompletedWorkItemCount = 0; // 垃圾回收代数空间 gen0Size = 0; gen1Size = 0; gen2Size = 0; lohSize = 0; pohSize = 0; constructor( private _uriConstant: UriConfig, private _dashboardService: DashboardService, private appref: ApplicationRef) { } ngOnInit() { const connection = new signalR.HubConnectionBuilder() .withUrl(`${this._uriConstant._baseUri}/appState`) .configureLogging(signalR.LogLevel.Warning) .build(); async function start() { try { await connection.start(); } catch (err) { console.log(err); setTimeout(start, 5000); } }; connection.onclose(start); connection.on("HandleCpuUsage", data => { if (this.cpuChart) { const data = []; data.push({ value: +Number(data) }); this.drawCpuChart(this.cpuChart, data); } }); connection.on("HandleWorkingSet", data => { this.workingSet = data; if (this.memoryChart) { if (this.memoryChartData.length > 10) { this.memoryChartData.shift(); } var myDate = new Date(); let hh = myDate.getHours() let mf = myDate.getMinutes() < 10 ? '0' + myDate.getMinutes() : myDate.getMinutes() let ss = myDate.getSeconds() < 10 ? '0' + myDate.getSeconds() : myDate.getSeconds() this.memoryChartData.push({ 'time': `${hh}:${mf}:${ss}`, type: '内存', size: Number(data) }); this.memoryChart.render(); } }); connection.on("HandleGCHeapSize", data => { this.gcHeapSize = data; }); connection.on("HandelGCCount", (gen, count) => { switch (gen) { case 0: this.gen0Count = count; break; case 1: this.gen1Count = count; break; case 2: this.gen2Count = count; break; } }); connection.on("HandelThreadPoolThreadCount", data => { this.handelThreadPoolThreadCount = data; }); connection.on("HandelMonitorLockContentionCount", data => { this.handelMonitorLockContentionCount = data; }); connection.on("ThreadPoolQueueLength", data => { this.threadPoolQueueLength = data; }); connection.on("ThreadPoolCompletedWorkItemCount", data => { this.threadPoolCompletedWorkItemCount = data; }); connection.on("HandelGcSize", (gen, count) => { switch (gen) { case 0: this.gen0Size = count; this.garbageChartData[0].count = count; break; case 1: this.gen1Size = count; this.garbageChartData[1].count = count; break; case 2: this.gen2Size = count; this.garbageChartData[2].count = count; break; } let fun = (num: number) => { let numStr = num.toString() let index = numStr.indexOf('.') let result = numStr.slice(0, index + 3); return Number(result); } let total = this.garbageChartData[0].count + this.garbageChartData[1].count + this.garbageChartData[2].count; this.garbageChartData[0].percent = fun(this.garbageChartData[0].count / total); this.garbageChartData[1].percent = fun(this.garbageChartData[1].count / total); this.garbageChartData[2].percent = fun(this.garbageChartData[2].count / total); this.garbageChart.changeData(this.garbageChartData); }); connection.on("HandeLohSize", data => { this.lohSize = data; }); connection.on("HandelPohSize", data => { this.pohSize = data; }); // Start the connection. start(); this._dashboardService.get().subscribe((result: any) => this.data = result); } ngAfterViewInit(): void { this.initGarbageChart(); this.initCpuChart(); this.initMemoryChart(); this.initGraph1(); this.initGraph3(); this.initGraph5(); // 初始图像宽度会溢出,通过resize事件触发图标重绘 setTimeout(() => { var myEvent = new Event('resize'); window.dispatchEvent(myEvent); }, 10); } //#region cpu使用率 initCpuChart() { function creatData() { const data = []; data.push({ value: +0 }); return data; } // 自定义Shape 部分 registerShape('point', 'pointer', { draw(cfg, container) { const group = container.addGroup({}); // 获取极坐标系下画布中心点 const center = this.parsePoint({ x: 0, y: 0 }); // 绘制指针 group.addShape('line', { attrs: { x1: center.x, y1: center.y, x2: cfg.x, y2: cfg.y, stroke: cfg.color, lineWidth: 5, lineCap: 'round', }, }); group.addShape('circle', { attrs: { x: center.x, y: center.y, r: 9.75, stroke: cfg.color, lineWidth: 4.5, fill: '#fff', }, }); return group; }, }); const color = ['#0086FA', '#FFBF00', '#F5222D']; const chart = new Chart({ container: 'c4', autoFit: true, height: 400, }); chart.data(creatData()); chart.animate(false); chart.coordinate('polar', { startAngle: (-9 / 8) * Math.PI, endAngle: (1 / 8) * Math.PI, radius: 0.75, }); chart.scale('value', { min: 0, max: 100, tickInterval: 5, }); chart.axis('1', false); chart.axis('value', { line: null, label: { offset: -40, style: { fontSize: 18, fill: '#CBCBCB', textAlign: 'center', textBaseline: 'middle', }, }, tickLine: { length: -24, }, grid: null, }); chart.legend(false); chart.tooltip(false); chart .point() .position('value*1') .shape('pointer') .color('value', (val) => { if (val < 40) { return color[0]; } else if (val <= 80) { return color[1]; } else if (val <= 100) { return color[2]; } }); this.drawCpuChart(chart, creatData()); this.chartArray.push(chart); this.cpuChart = chart; } drawCpuChart(chart, data) { const color = ['#0086FA', '#FFBF00', '#F5222D']; const val = data[0].value; const lineWidth = 25; chart.annotation().clear(true); // 绘制仪表盘背景 chart.annotation().arc({ top: false, start: [0, 1], end: [100, 1], style: { stroke: '#CBCBCB', lineWidth, lineDash: null, }, }); if (val < 40) { chart.annotation().arc({ start: [0, 1], end: [val, 1], style: { stroke: color[0], lineWidth, lineDash: null, }, }); } if (val > 40 && val <= 80) { chart.annotation().arc({ start: [0, 1], end: [40, 1], style: { stroke: color[0], lineWidth, lineDash: null, }, }); chart.annotation().arc({ start: [40, 1], end: [val, 1], style: { stroke: color[1], lineWidth, lineDash: null, }, }); } if (val >= 80) { chart.annotation().arc({ start: [0, 1], end: [40, 1], style: { stroke: color[0], lineWidth, lineDash: null, }, }); chart.annotation().arc({ start: [40, 1], end: [80, 1], style: { stroke: color[1], lineWidth, lineDash: null, }, }); chart.annotation().arc({ start: [80, 1], end: [val, 1], style: { stroke: color[2], lineWidth, lineDash: null, }, }); } // 绘制指标数字 chart.annotation().text({ position: ['50%', '85%'], content: '应用CPU使用率', style: { fontSize: 20, fill: '#545454', textAlign: 'center', }, }); chart.annotation().text({ position: ['50%', '90%'], content: `${data[0].value} %`, style: { fontSize: 36, fill: '#545454', textAlign: 'center', }, offsetY: 15, }); chart.changeData(data); } //#endregion //#region 内存图表 initMemoryChart() { const chart = new Chart({ container: 'c6', autoFit: true, height: 400, }); chart.data(this.memoryChartData); chart.scale({ time: { range: [0, 1], }, size: { nice: true, min: 0, }, }); chart.tooltip({ showCrosshairs: true, shared: true, }); chart.axis('size', { label: { formatter: (val) => { return val + ' MB'; }, }, }); // 线 chart.line().position('time*size').color('type').shape('smooth'); // 点 chart.point().position('time*size').color('type').shape('circle'); chart.render(); this.chartArray.push(chart); this.memoryChart = chart; } //#endregion //#region 垃圾回收区域饼图 initGarbageChart() { const chart = new Chart({ container: 'c2', autoFit: true, height: 400, }); chart.data(this.garbageChartData); chart.scale('percent', { formatter: (val) => { val = val * 100 + '%'; return val; }, }); chart.coordinate('theta', { radius: 0.75, innerRadius: 0.6, }); chart.tooltip({ showTitle: false, showMarkers: false, itemTpl: '<li class="g2-tooltip-list-item"><span style="background-color:{color};" class="g2-tooltip-marker"></span>{name}: {value}</li>', }); // 辅助文本 chart .annotation() .text({ position: ['50%', '50%'], content: '存储', style: { fontSize: 14, fill: '#8c8c8c', textAlign: 'center', }, offsetY: -20, }); chart .interval().adjust('stack').position(['percent']).color('item') .label('percent', (percent) => { return { content: (data) => { return `${data.item}: ${(percent * 100).toFixed(2)}% ${data.count}B`; }, }; }) .tooltip('item*percent', (item, percent) => { percent = percent * 100 + '%'; return { name: item, value: percent, }; }); chart.interaction('element-active'); chart.render(); this.chartArray.push(chart); this.garbageChart = chart; } //#endregion initGraph1() { const data = [ { type: '收纳', value: 340, cat: '办公用品' }, { type: '笔', value: 20760, cat: '办公用品' }, { type: '纸张', value: 28750, cat: '办公用品' }, { type: '配件', value: 4090, cat: '技术' }, { type: '电话', value: 9880, cat: '技术' }, { type: '复印机', value: 40988, cat: '技术' }, { type: '桌子', value: 14870, cat: '家具' }, { type: '椅子', value: 37098, cat: '家具' }, { type: '书架', value: 49099, cat: '家具' }, ]; const chart = new Chart({ container: 'c1', autoFit: true, height: 400, syncViewPadding: true, }); chart.data(data); chart.scale({ value: { max: 55000, min: 0, alias: '金额(元)', }, }); chart.axis('type', { tickLine: null, line: null, }); chart.axis('value', { label: null, title: { offset: 30, style: { fontWeight: 300, }, }, grid: null, }); chart.legend(false); chart.coordinate('rect').transpose(); chart .interval() .position('type*value') .color('cat', ['#face1d', '#37c461', '#2194ff']) .size(26) .label('value', { style: { fill: '#8d8d8d', }, offset: 10, content: (originData) => { return (originData.value + '').replace(/(\d)(?=(?:\d{3})+$)/g, '$1,'); }, }); chart.annotation().text({ top: true, position: ['椅子', 'min'], content: '家具', style: { fill: '#c0c0c0', fontSize: 12, fontWeight: 300, textAlign: 'center', }, offsetX: -70, rotate: Math.PI * -0.5 }); chart.annotation().text({ top: true, position: ['电话', 'min'], content: '技术', style: { fill: '#c0c0c0', fontSize: 12, fontWeight: 300, textAlign: 'center', }, offsetX: -70, rotate: Math.PI * -0.5 }); chart.annotation().text({ top: true, position: ['笔', 'min'], content: '办公用品', style: { fill: '#c0c0c0', fontSize: 12, fontWeight: 300, textAlign: 'center', }, offsetX: -70, rotate: Math.PI * -0.5 }); chart.annotation().line({ start: ['-20%', '33.2%'], end: ['100%', '33.2%'], style: { stroke: '#c0c0c0', lineDash: [2, 2], }, }); chart.annotation().line({ start: ['-20%', '66.8%'], end: ['100%', '66.8%'], style: { stroke: '#c0c0c0', lineDash: [2, 2], }, }); chart.interaction('element-active'); chart.theme('dark'); chart.render(); } initGraph3() { function getFillAttrs(cfg) { return { ...cfg.defaultStyle, ...cfg.style, fill: cfg.color, fillOpacity: cfg.opacity, }; } function getRectPath(points) { const path = []; for (let i = 0; i < points.length; i++) { const point = points[i]; if (point) { const action = i === 0 ? 'M' : 'L'; path.push([action, point.x, point.y]); } } const first = points[0]; path.push(['L', first.x, first.y]); path.push(['z']); return path; } // 顶边带圆角 registerShape('interval', 'top', { draw(cfg, container) { const attrs = getFillAttrs(cfg); let path = getRectPath(cfg.points); path = this.parsePath(path); // 将 0 - 1 的值转换为画布坐标 const radius = (path[2][1] - path[1][1]) / 2; const temp = []; temp.push(['M', path[0][1], path[0][2]]); temp.push(['L', path[1][1], path[1][2] + radius]); temp.push(['A', radius, radius, 90, 0, 1, path[1][1] + radius, path[1][2]]); temp.push(['L', path[2][1] - radius, path[2][2]]); temp.push(['A', radius, radius, 90, 0, 1, path[2][1], path[2][2] + radius]); temp.push(['L', path[3][1], path[3][2]]); temp.push(['Z']); const group = container.addGroup(); group.addShape('path', { attrs: { ...attrs, path: temp, }, }); return group; }, }); // 底边带圆角 registerShape('interval', 'bottom', { draw(cfg, container) { const attrs = getFillAttrs(cfg); let path = getRectPath(cfg.points); path = this.parsePath(path); const radius = (path[2][1] - path[1][1]) / 2; const temp = []; temp.push(['M', path[0][1] + radius, path[0][2]]); temp.push(['A', radius, radius, 90, 0, 1, path[0][1], path[0][2] - radius]); temp.push(['L', path[1][1], path[1][2]]); temp.push(['L', path[2][1], path[2][2]]); temp.push(['L', path[3][1], path[3][2] - radius]); temp.push(['A', radius, radius, 90, 0, 1, path[3][1] - radius, path[3][2]]); temp.push(['Z']); const group = container.addGroup(); group.addShape('path', { attrs: { ...attrs, path: temp, }, }); return group; }, }); const data = [ { year: '2014', type: 'Sales', sales: 1000 }, { year: '2015', type: 'Sales', sales: 1170 }, { year: '2016', type: 'Sales', sales: 660 }, { year: '2017', type: 'Sales', sales: 1030 }, { year: '2014', type: 'Expenses', sales: 400 }, { year: '2015', type: 'Expenses', sales: 460 }, { year: '2016', type: 'Expenses', sales: 1120 }, { year: '2017', type: 'Expenses', sales: 540 }, { year: '2014', type: 'Profit', sales: 300 }, { year: '2015', type: 'Profit', sales: 300 }, { year: '2016', type: 'Profit', sales: 300 }, { year: '2017', type: 'Profit', sales: 350 }, ]; const chart = new Chart({ container: 'c3', autoFit: true, height: 400, }); chart.data(data); chart.scale({ sales: { max: 2400, tickInterval: 600, nice: true, }, }); const axisCfg = { title: null, label: { style: { fontFamily: 'Monospace', fontWeight: 700, fontSize: 14, fill: '#545454', }, }, grid: { line: { style: { lineDash: null, stroke: '#545454', }, }, }, line: { style: { lineDash: null, stroke: '#545454', }, }, }; chart.axis('year', axisCfg); chart.axis('sales', { ...axisCfg, line: null }); chart.tooltip({ showMarkers: false }); chart .interval() .position('year*sales') .color('type') .size(35) .shape('type', (val) => { if (val === 'Profit') { // 顶部圆角 return 'bottom'; } else if (val === 'Sales') { // 底部圆角 return 'top'; } }) .style({ stroke: '#545454', lineWidth: 2, }) .adjust('stack'); chart.interaction('element-highlight-by-color'); chart.render(); this.chartArray.push(chart); } initGraph5() { const data = [ [0, 0, 10], [0, 1, 19], [0, 2, 8], [0, 3, 24], [0, 4, 67], [1, 0, 92], [1, 1, 58], [1, 2, 78], [1, 3, 117], [1, 4, 48], [2, 0, 35], [2, 1, 15], [2, 2, 123], [2, 3, 64], [2, 4, 52], [3, 0, 72], [3, 1, 132], [3, 2, 114], [3, 3, 19], [3, 4, 16], [4, 0, 38], [4, 1, 5], [4, 2, 8], [4, 3, 117], [4, 4, 115], [5, 0, 88], [5, 1, 32], [5, 2, 12], [5, 3, 6], [5, 4, 120], [6, 0, 13], [6, 1, 44], [6, 2, 88], [6, 3, 98], [6, 4, 96], [7, 0, 31], [7, 1, 1], [7, 2, 82], [7, 3, 32], [7, 4, 30], [8, 0, 85], [8, 1, 97], [8, 2, 123], [8, 3, 64], [8, 4, 84], [9, 0, 47], [9, 1, 114], [9, 2, 31], [9, 3, 48], [9, 4, 91], ]; const source = data.map((arr) => { return { name: arr[0], day: arr[1], sales: arr[2], }; }); const chart = new Chart({ container: 'c5', autoFit: true, height: 400, }); chart.data(source); chart.scale('name', { type: 'cat', values: ['Alexander', 'Marie', 'Maximilian', 'Sophia', 'Lukas', 'Maria', 'Leon', 'Anna', 'Tim', 'Laura'], }); chart.scale('day', { type: 'cat', values: ['Monday', 'Tuesday', 'Wednesday', 'Thursday', 'Friday'], }); chart.scale('sales', { nice: true, }); chart.axis('name', { tickLine: null, grid: { alignTick: false, line: { style: { lineWidth: 1, lineDash: null, stroke: '#f0f0f0', }, }, }, }); chart.axis('day', { title: null, grid: { alignTick: false, line: { style: { lineWidth: 1, lineDash: null, stroke: '#f0f0f0', }, }, }, }); chart.tooltip(false); chart.interaction('brush-visible'); chart .polygon() .position('name*day') .color('sales', '#BAE7FF-#1890FF-#0050B3') .label('sales', { offset: -2, style: { fill: '#fff', shadowBlur: 2, shadowColor: 'rgba(0, 0, 0, .45)', }, }) .style({ lineWidth: 1, stroke: '#fff', }).state({ active: { style: { fillOpacity: 0.9 }, }, inactive: { style: { fillOpacity: 0.4 }, } });; chart.render(); this.chartArray.push(chart); } }
the_stack
import _ from 'lodash' import timecodes from 'node-timecodes' import { Clip, Effect, Project } from '../Entity' import EffectPluginBase from '../PluginSupport/PostEffectBase' import { ParameterValueTypes } from '../PluginSupport/TypeDescriptor' import { IRenderingStreamObserver, RenderingStatus } from './IRenderingStreamObserver' import { IRenderer } from './Renderer/RendererBase' import PluginRegistry from '../PluginSupport/PluginRegistry' import { EffectPluginMissingException, RenderingAbortedException, RenderingFailedException } from '../Exceptions' import { mergeInto as mergeAudioBufferInto } from '../helper/Audio' import defaults from '../helper/defaults' import FPSCounter from '../helper/FPSCounter' import ProgressPromise from '../helper/progress-promise' import { proxyDeepFreeze } from '../helper/proxyFreeze' import DependencyResolver from './DependencyResolver' import * as ExpressionContext from './ExpressionSupport/ExpressionContext' import { ClipRenderContext } from './RenderContext/ClipRenderContext' import { RenderContextBase } from './RenderContext/RenderContextBase' import ClipRenderTask from './Task/ClipRenderTask' import EffectRenderTask from './Task/EffectRenderTask' import { LayerRenderTask } from './Task/LayerRenderTask' import WebGLContext from './WebGL/WebGLContext' // import WebGLContext from './WebGL/WebGLContext' export interface ExpressionExecuters { [paramName: string]: (exposes: ExpressionContext.ContextSource) => ParameterValueTypes } interface RenderingOption { beginFrame: number endFrame: number loop: boolean ignoreMissingEffect: boolean realtime: boolean audioBufferSizeSecond: number enableAlpha: boolean } interface RenderProgression { state: string isAudioBuffered: boolean audioBuffers: Float32Array[] currentFrame: number rangeEndFrame: number playbackRate: number } type TaskGroup = { context: ClipRenderContext<any> task: ClipRenderTask }[] export default class Engine { private _fpsCounter: FPSCounter = new FPSCounter() private _seqRenderPromise: ProgressPromise<void> | null = null private _project: Project private _pluginRegistry: PluginRegistry = new PluginRegistry() private _destinationAudioNode: AudioNode private _clipRendererCache: WeakMap<Clip, IRenderer<any>> = new WeakMap() private _effectCache: WeakMap<Effect, EffectPluginBase> = new WeakMap() private _streamObserver: IRenderingStreamObserver | null = null private glContext: WebGLContext = new WebGLContext(1, 1) // private _gl: WebGL2RenderingContext get pluginRegistry() { return this._pluginRegistry } set pluginRegistry(pluginRegistry: PluginRegistry) { this._pluginRegistry = pluginRegistry } // get destinationAudioNode() { return this._destinationAudioNode } // set destinationAudioNode(destinationAudioNode: AudioNode) { this._destinationAudioNode = destinationAudioNode } public setProject(project: Project) { this._project = project this._clipRendererCache = new WeakMap() this._effectCache = new WeakMap() } public setStreamObserver(observer: IRenderingStreamObserver) { this._streamObserver = observer } public removeStreamObserver(observer: IRenderingStreamObserver) { this._streamObserver = null } public stopCurrentRendering() { if (this._seqRenderPromise) { this._seqRenderPromise.abort() } } public clearCache() { this._clipRendererCache = new WeakMap() this._effectCache = new WeakMap() } public renderFrame( compositionId: string, beginFrame: number, options: Partial<RenderingOption> = {}, ): ProgressPromise<void> { return new ProgressPromise<void>(async (resolve, reject, onAbort, notifier) => { let aborted = false onAbort(() => (aborted = true)) const renderingOption: RenderingOption = { beginFrame, endFrame: beginFrame, ignoreMissingEffect: false, loop: false, realtime: false, audioBufferSizeSecond: 1, enableAlpha: false, ...options, } const request = this._initStage(compositionId, renderingOption) try { const renderTasks = await this._taskingStage(request, renderingOption) await this._renderStage(request, renderTasks) } catch (e) { reject(e) return } if (this._streamObserver) { if (this._streamObserver.onFrame) { this._streamObserver.onFrame(request.destCanvas, { frame: request.frame, time: request.time, durationFrame: request.durationFrames, samplingRate: request.samplingRate, }) } } resolve() }) } public renderSequencial( compositionId: string, options: Partial<RenderingOption> = {}, ): ProgressPromise<void, RenderProgression> { const renderingOption: RenderingOption = defaults(options, { beginFrame: 0, loop: false, endFrame: -1, ignoreMissingEffect: false, realtime: false, audioBufferSizeSecond: 1, enableAlpha: false, }) this.stopCurrentRendering() this._seqRenderPromise = new ProgressPromise<void, RenderProgression>( async (resolve, reject, onAbort, notifier) => { let aborted = false onAbort(() => { aborted = true this._seqRenderPromise = null }) let context = this._initStage(compositionId, renderingOption) let renderTasks: LayerRenderTask[] try { renderTasks = await this._taskingStage(context, renderingOption) } catch (e) { reject(e) return } this._fpsCounter.reset() const reqDestCanvasCtx = context.destCanvas.getContext('2d')! const framerate = context.rootComposition.framerate const lastFrame = context.rootComposition.durationFrames let animationFrameId: number let renderedFrames = 0 let lastAudioBufferTime = -1 * renderingOption.audioBufferSizeSecond const throttle = options.realtime ? (fn: () => void) => _.throttle(fn, 1000 / context.framerate) : (fn: () => void) => fn const animationFrame = options.realtime ? requestAnimationFrame : (fn: () => void) => (fn() as unknown) as number const cancelFrame = options.realtime ? cancelAnimationFrame : clearTimeout const render = throttle(async () => { const currentFrame = renderingOption.beginFrame + renderedFrames const currentTime = currentFrame / framerate // 最後のバッファリングからバッファサイズ分経過 & 次のフレームがレンダリングの終わりでなければバッファリング const isAudioBufferingNeeded = lastAudioBufferTime === -1 || (currentTime - lastAudioBufferTime >= renderingOption.audioBufferSizeSecond && renderedFrames + 1 <= context.durationFrames) if (isAudioBufferingNeeded) { lastAudioBufferTime = currentTime | 0 for (const buffer of context.destAudioBuffer) { buffer.fill(0) } } context = context.clone({ frame: currentFrame, time: currentTime, frameOnComposition: currentFrame, timeOnComposition: currentTime, isAudioBufferingNeeded, }) reqDestCanvasCtx.clearRect(0, 0, context.width, context.height) try { await this._renderStage(context, renderTasks) } catch (e) { reject(e) return } if (!aborted) { const status: RenderingStatus = { frame: context.frame, time: context.time, durationFrame: context.durationFrames, samplingRate: context.samplingRate, } if (this._streamObserver) { if (this._streamObserver.onStateChanged) this._streamObserver.onStateChanged(status) if (this._streamObserver.onFrame) this._streamObserver.onFrame(context.destCanvas, status) if (isAudioBufferingNeeded) { if (this._streamObserver.onAudioBuffered) { this._streamObserver.onAudioBuffered(context.destAudioBuffer, status) } } } } if (renderingOption.beginFrame + renderedFrames >= lastFrame) { if (renderingOption.loop) { renderedFrames = 0 lastAudioBufferTime = -1 } else { cancelFrame(animationFrameId) resolve() return } } else { renderedFrames++ } if (aborted) { cancelFrame(animationFrameId) reject(new RenderingAbortedException('Rendering aborted.')) return } const timecode = timecodes.fromSeconds(context.time, { frameRate: context.framerate, }) notifier({ state: `time: ${timecode.slice(0, -3)} (${this._fpsCounter.latestFPS()} / ${context.framerate} fps)`, currentFrame: context.frame, rangeEndFrame: renderingOption.endFrame, isAudioBuffered: isAudioBufferingNeeded, audioBuffers: context.destAudioBuffer, playbackRate: this._fpsCounter.latestFPS() / context.framerate, }) this._fpsCounter.increase() animationFrameId = animationFrame(render) }) animationFrameId = animationFrame(render) }, ) return this._seqRenderPromise } private _initStage(compositionId: string, option: RenderingOption): RenderContextBase { if (!this._project) throw new RenderingFailedException('Project must be set before rendering') if (!this._pluginRegistry) throw new RenderingFailedException('Plugin registry not set') const rootComposition = this._project.findComposition(compositionId) if (!rootComposition) throw new RenderingFailedException('Specified composition not found') const resolver = new DependencyResolver(this._project, this._pluginRegistry) const canvas = document.createElement('canvas') as HTMLCanvasElement canvas.width = rootComposition.width canvas.height = rootComposition.height const compositionDurationTime = rootComposition.durationFrames / rootComposition.framerate const audioBufferSizeByte = rootComposition.samplingRate * option.audioBufferSizeSecond * 4 const audioContext = new OfflineAudioContext( rootComposition.audioChannels, Math.ceil(audioBufferSizeByte * compositionDurationTime), rootComposition.samplingRate, ) const audioBuffers = _.times( rootComposition.audioChannels, () => new Float32Array(new ArrayBuffer(audioBufferSizeByte)), ) const currentFrame = option.beginFrame const currentTime = currentFrame / rootComposition.framerate this.glContext.setSize(rootComposition.width, rootComposition.height) return new RenderContextBase({ time: currentTime, timeOnComposition: currentTime, frame: currentFrame, frameOnComposition: currentFrame, destCanvas: canvas, width: rootComposition.width, height: rootComposition.height, framerate: rootComposition.framerate, durationFrames: rootComposition.durationFrames, destAudioBuffer: audioBuffers, audioContext, samplingRate: rootComposition.samplingRate, neededSamples: rootComposition.samplingRate * option.audioBufferSizeSecond, audioChannels: rootComposition.audioChannels, isAudioBufferingNeeded: false, transparentBackground: !!option.enableAlpha, rootComposition, resolver, gl: this.glContext, }) } private async _taskingStage(baseContext: RenderContextBase, option: RenderingOption): Promise<LayerRenderTask[]> { const layerTasks: LayerRenderTask[] = [] const renderOrderLayers = baseContext.rootComposition.layers.slice(0).reverse() for (const layer of renderOrderLayers) { const layerRenderTask = LayerRenderTask.build(layer) const clips: ClipRenderTask[] = [] for (const clip of layer.clips) { // Initialize clip const clipRenderTask = ClipRenderTask.build({ clip, clipRendererCache: this._clipRendererCache, context: baseContext, }) await clipRenderTask.initialize(baseContext) // Initialize effects const effects: EffectRenderTask[] = [] for (const effect of clip.effects) { try { const effectRenderTask = EffectRenderTask.build({ effect, clip, context: baseContext, effectCache: this._effectCache, resolver: baseContext.resolver, }) effects.push(effectRenderTask) } catch (e) { if (e instanceof EffectPluginMissingException && option.ignoreMissingEffect) { continue } else { throw e } } } // Lookup before apply expression referenceable effect params expression const referenceableEffectParams: ExpressionContext.ReferenceableEffectsParams = Object.create(null) _.each(clipRenderTask.effectRenderTasks, task => { if (task.effectEntity.referenceName == null) return referenceableEffectParams[task.effectEntity.referenceName] = task.keyframeTable.getParametersAt( baseContext.frame, ) }) for (const effectRenderTask of effects) { await effectRenderTask.initialize(baseContext, referenceableEffectParams) } clipRenderTask.effectRenderTasks = effects clips.push(clipRenderTask) } layerRenderTask.clipRenderTasks = clips layerTasks.push(layerRenderTask) } return layerTasks } private async _renderStage(baseContext: RenderContextBase, layerRenderTasks: LayerRenderTask[]): Promise<void> { const destBufferCanvas = baseContext.destCanvas const destBufferCtx = destBufferCanvas.getContext('2d')! if (baseContext.transparentBackground) { destBufferCtx.clearRect(0, 0, baseContext.width, baseContext.height) } else { destBufferCtx.fillStyle = baseContext.rootComposition.backgroundColor.toString() destBufferCtx.fillRect(0, 0, baseContext.width, baseContext.height) } const taskGroupChunks: TaskGroup[] = [] const audioTaskGroup: TaskGroup = [] let latestGroup: TaskGroup = [] for (const layerTask of layerRenderTasks) { const renderTargetClips = layerTask.findRenderTargetClipTasks(baseContext) for (const clipTask of renderTargetClips) { if (clipTask.rendererType === 'adjustment') { taskGroupChunks.push(latestGroup) latestGroup = [] } const clipBufferCanvas = document.createElement('canvas') as HTMLCanvasElement clipBufferCanvas.width = baseContext.width clipBufferCanvas.height = baseContext.height // Fix context type clipBufferCanvas.getContext('2d')! const timeOnClip = baseContext.time - clipTask.clipPlacedFrame / baseContext.framerate const frameOnClip = baseContext.frame - clipTask.clipPlacedFrame // Lookup before apply expression referenceable effect params expression const referenceableEffectParams: ExpressionContext.ReferenceableEffectsParams = Object.create(null) _.each(clipTask.effectRenderTasks, task => { if (task.effectEntity.referenceName == null) return referenceableEffectParams[task.effectEntity.referenceName] = task.keyframeTable.getParametersAt( baseContext.frame, ) }) const beforeClipExpressionParams = clipTask.keyframeTable.getParametersAt(baseContext.frame) const clipRenderContext = baseContext.toClipRenderContext({ clip: clipTask.clipEntity, timeOnClip, frameOnClip, beforeExpressionParameters: beforeClipExpressionParams, parameters: {}, clipEffectParams: referenceableEffectParams, srcCanvas: null, destCanvas: clipBufferCanvas, srcAudioBuffer: null, destAudioBuffer: clipTask.audioBuffer, }) clipRenderContext.parameters = clipTask.keyframeTable.getParameterWithExpressionAt(baseContext.frame, { context: clipRenderContext, clipParams: beforeClipExpressionParams, referenceableEffectParams, }) if (clipTask.rendererType === 'audio') { audioTaskGroup.push({ context: clipRenderContext, task: clipTask }) } else { latestGroup.push({ context: clipRenderContext, task: clipTask }) } } } taskGroupChunks.push(latestGroup) const processTaskGroup = (group: TaskGroup, srcAudioBuffer: Float32Array[] | null) => { return Promise.all( group.map(async ({ context: clipContext, task }) => { if (task.rendererType === 'adjustment') { clipContext.srcCanvas = destBufferCanvas } clipContext.srcAudioBuffer = srcAudioBuffer const clipBufferCtx = clipContext.destCanvas.getContext('2d')! await task.clipRenderer.render(clipContext) clipBufferCtx.globalAlpha = 1 clipBufferCtx.setTransform(1, 0, 0, 1, 0, 0) // Post process effects for (const effectTask of task.effectRenderTasks) { const effectRenderContext = baseContext.toEffectRenderContext({ effect: effectTask.effectEntity, timeOnClip: clipContext.timeOnClip, frameOnClip: clipContext.frameOnClip, srcCanvas: clipContext.destCanvas, destCanvas: clipContext.destCanvas, parameters: {}, clipEffectParams: clipContext.clipEffectParams, }) effectRenderContext.parameters = effectTask.keyframeTable.getParameterWithExpressionAt(baseContext.frame, { context: effectRenderContext, clipParams: clipContext.beforeExpressionParameters, referenceableEffectParams: clipContext.clipEffectParams, }) await effectTask.effectRenderer.render(effectRenderContext) clipBufferCtx.globalAlpha = 1 clipBufferCtx.setTransform(1, 0, 0, 1, 0, 0) } }), ) } await processTaskGroup(audioTaskGroup, null) if (baseContext.isAudioBufferingNeeded) { for (const task of audioTaskGroup) { await mergeAudioBufferInto( baseContext.destAudioBuffer, task.context.destAudioBuffer, baseContext.audioChannels, baseContext.samplingRate, ) for (const chBuffer of task.context.destAudioBuffer) { chBuffer.fill(0) } } } const freezedAudioBuffer = proxyDeepFreeze(baseContext.destAudioBuffer) for (const group of taskGroupChunks) { await processTaskGroup(group, freezedAudioBuffer as Float32Array[]) for (const clipTask of group) { // Render clip rendering result to merger canvas if (clipTask.task.rendererType === 'adjustment') { // Merge adjustment clip result to last destination canvas // SPEC: Through prevent painting if adjustment clip renders transparent(opacity: 0). // SPEC: Behavior when two or more clips exist on same layer at the same time is not defined. destBufferCtx.globalAlpha = _.clamp(clipTask.context.parameters.opacity as number, 0, 100) / 100 destBufferCtx.drawImage(clipTask.context.destCanvas, 0, 0) destBufferCtx.globalAlpha = 1 } else { destBufferCtx.drawImage(clipTask.context.destCanvas, 0, 0) } } } } }
the_stack
import * as express from 'express'; import DocBuilder from 'tiny-attribution-generator'; import TextRenderer from 'tiny-attribution-generator/lib/outputs/text'; import * as winston from 'winston'; import auth from '../../../auth'; import { isAdmin } from '../../../auth/util'; import * as documentdb from '../../../db/attribution_documents'; import * as db from '../../../db/projects'; import { DbPackageUsage } from '../../../db/projects'; import { getProjectAuditLog } from '../../../db/projects_audit'; import { AccessError } from '../../../errors/index'; import { asyncApi } from '../../../util/middleware'; import { storePackage } from '../packages'; import { addProjectPackages, applyCopyrightTransforms, applyTextTransforms, getWarnings, OverlayLicenseDictionary, } from './attribution'; import { assertProjectAccess, effectivePermission, requireProjectAccess, } from './auth'; import { AccessLevel, AccessLevelStrength, RefInfo, WebProject, } from './interfaces'; import * as projectValidators from './validators'; export const router = express.Router(); export default router; type ProjectIdPromise = Promise<Pick<WebProject, 'projectId'>>; /** * List all projects filtered by access. */ router.get('/', asyncApi(searchProjects)); export async function searchProjects( req: express.Request, res: express.Response ): Promise<Array<Partial<WebProject>>> { const user = auth.extractRequestUser(req); const groups = await auth.getGroups(user); // all projects if (req.query.all) { if (!isAdmin(req, groups)) { throw new AccessError('Cannot access all projects'); } const projects = await db.searchProjects(); return projects.map(mapProjectShortInfo); } // "my" projects const ownProjects = await db.searchOwnProjects(groups); return ownProjects.map(mapProjectShortInfo); } function mapProjectShortInfo(dbData): Partial<WebProject> { return { projectId: dbData.project_id, title: dbData.title, createdOn: dbData.created_on, version: dbData.version, }; } /** * Create a new project. */ router.post('/new', projectValidators.createProject, asyncApi(createProject)); export async function createProject( req: express.Request, res: express.Response ): ProjectIdPromise { const body: WebProject = req.body; const user = auth.extractRequestUser(req); const projectId = await db.createProject( { title: body.title, version: body.version, description: body.description, planned_release: body.plannedRelease, contacts: body.contacts, acl: body.acl, metadata: body.metadata, // do *not* accept raw user input for refs! // refs can implicitly grant access to other projects' contents. // allowing users to refer to other projects would be a security issue. refs: {}, }, user ); winston.info(`Project ${projectId} created by ${user}`); return { projectId }; } /** * Get a particular project. */ router.get('/:projectId', requireProjectAccess('viewer'), asyncApi(getProject)); export async function getProject( req: express.Request, res: express.Response ): Promise<WebProject> { const project: db.DbProject = res.locals.project; const accessLevel = (await effectivePermission(req, project)) as AccessLevel; // map DB types to a public API return { projectId: project.project_id, title: project.title, version: project.version, description: project.description || '', createdOn: project.created_on, plannedRelease: project.planned_release, contacts: project.contacts, acl: project.acl, packagesUsed: project.packages_used.map((usage) => ({ ...usage, package_id: undefined, packageId: usage.package_id, })), refs: project.refs, metadata: project.metadata || {}, access: { level: accessLevel, canEdit: AccessLevelStrength[accessLevel] >= AccessLevelStrength.editor, }, }; } /** * Edit a project's basic details. */ router.patch( '/:projectId', requireProjectAccess('editor'), projectValidators.patchProject, asyncApi(patchProject) ); export async function patchProject( req: express.Request, res: express.Response ): ProjectIdPromise { const { params: { projectId }, body, } = req; const user = auth.extractRequestUser(req); const project: db.DbProject = res.locals.project; // map API names to DB columns const internalMap = { title: 'title', version: 'version', description: 'description', plannedRelease: 'planned_release', contacts: 'contacts', acl: 'acl', metadata: 'metadata', }; const mappedChanges = {}; for (const k of Object.keys(body)) { // validate that requester is an owner for ACL changes if (k === 'acl') { await assertProjectAccess(req, project, 'owner'); } mappedChanges[internalMap[k]] = body[k]; } await db.patchProject(projectId, mappedChanges, user); winston.info(`Project ${projectId} modified by ${user}`); return { projectId }; } /** * Attach a package to a project, optionally creating or updating the package. */ router.post( '/:projectId/attach', requireProjectAccess('editor'), projectValidators.attachPackage, asyncApi(attachPackage) ); export async function attachPackage( req: express.Request, res: express.Response ): Promise<{ packageId: number }> { const { params: { projectId }, body: { packageId, name, version, website, copyright, usage, license, licenseText, }, } = req; // access check const user = auth.extractRequestUser(req); const project: db.DbProject = res.locals.project; // see if we need to edit the existing package const newId = await storePackage(req, packageId, { name, version, website, copyright, license, licenseText, }); // update usage info to store on project const usageInfo: DbPackageUsage = { ...usage, package_id: newId, }; // filter out any existing packages with the current/previous ID. // no sense in having more than one instance, so assume that // re-submitting means "edit". note that if the package details // were changed (instead of just usage info) then a new package // ID will have been created, and the old one won't get removed. const used = project.packages_used.filter((u) => u.package_id !== packageId); // *not* newId used.push(usageInfo); // submit the update await db.updatePackagesUsed(projectId, used, user); // finally, return the updated/inserted package ID const addedPackageId = usageInfo.package_id; winston.info(`Attached package ${addedPackageId} to project ${projectId}`); return { packageId: addedPackageId }; } /** * Detach a package from a project. */ router.post( '/:projectId/detach', requireProjectAccess('editor'), asyncApi(detachPackage) ); export async function detachPackage( req: express.Request, res: express.Response ): ProjectIdPromise { const { params: { projectId }, body: { packageId }, } = req; const user = auth.extractRequestUser(req); const project: db.DbProject = res.locals.project; const newUsage = project.packages_used.filter((item) => { return item.package_id !== packageId; }); await db.updatePackagesUsed(projectId, newUsage, user); winston.info(`Detached package ${packageId} from project ${projectId}`); return { projectId }; } /** * Replace a package instance with another, without changing the usage. */ router.post( '/:projectId/replace', requireProjectAccess('editor'), projectValidators.replacePackage, asyncApi(replacePackage) ); export async function replacePackage( req: express.Request, res: express.Response ): ProjectIdPromise { const { params: { projectId }, body: { oldId, newId }, } = req; const user = auth.extractRequestUser(req); const project: db.DbProject = res.locals.project; const usage = project.packages_used; for (const u of usage) { if (u.package_id === oldId) { u.package_id = newId; } } await db.updatePackagesUsed(projectId, usage, user); winston.info(`Replaced package ${oldId} -> ${newId} on project ${projectId}`); return { projectId }; } /** * Preview an attribution document. Return the document along * with any warnings. */ router.get( '/:projectId/build', requireProjectAccess('viewer'), asyncApi(async (req, res) => generateAttributionDocument(req, res, false)) ); /** * Building a document using POST will trigger a store & download. */ router.post( '/:projectId/build', requireProjectAccess('viewer'), asyncApi(async (req, res) => generateAttributionDocument(req, res, true)) ); export async function generateAttributionDocument( req: express.Request, res: express.Response, store = false ) { const { params: { projectId }, } = req; const user = auth.extractRequestUser(req); const project: db.DbProject = res.locals.project; const renderer = new TextRenderer({ wrap: 79 }); const overlayLicenses = new OverlayLicenseDictionary(); const builder = new DocBuilder(renderer, overlayLicenses); builder.addTextTransform(applyTextTransforms); builder.addTextTransform(applyCopyrightTransforms); // add our own packages await addProjectPackages(project, builder); // and then referenced projects of type "include", if any for (const [targetProjectId, meta] of Object.entries(project.refs)) { if (meta.type !== 'includes') { continue; } const targetProject = (await db.getProject( targetProjectId )) as db.DbProject; await addProjectPackages(targetProject, builder); } // do it! const text: string = builder.build(); const warnings = getWarnings(builder); const annotations = renderer.annotations; const summary = builder.summary; // save a copy if requested if (store) { const documentId = await documentdb.storeAttributionDocument( projectId, project.version, text, user ); winston.info(`Document for project ${projectId} was stored by ${user}`); return { text, documentId }; } return { text, annotations, warnings, summary }; } /** * List stored attribution documents for a project. */ router.get( '/:projectId/docs', requireProjectAccess('viewer'), asyncApi(listRenderedDocuments) ); export async function listRenderedDocuments( req: express.Request, res: express.Response ) { const docs = await documentdb.findDocumentsForProject(req.params.projectId); return { documents: docs.map((d) => ({ id: d.doc_id, projectVersion: d.project_version, createdOn: d.created_on, createdBy: d.created_by, })), }; } /** * Retrieve a rendered document for a project. */ router.get( '/:projectId/docs/:documentId.text', requireProjectAccess('viewer'), asyncApi(async (req, res) => getRenderedDocument(req, res, true)) ); router.get( '/:projectId/docs/:documentId', requireProjectAccess('viewer'), asyncApi(async (req, res) => getRenderedDocument(req, res, false)) ); export async function getRenderedDocument( req: express.Request, res: express.Response, textOnly: boolean ) { const { params: { projectId, documentId }, } = req; const doc = await documentdb.getAttributionDocument(projectId, parseInt(documentId)); if (doc == undefined) { return; } if (textOnly) { res.type('text/plain'); return doc.content; } return { id: doc.doc_id, projectId: doc.project_id, projectVersion: doc.project_version, createdOn: doc.created_on, createdBy: doc.created_by, content: doc.content, }; } /** * Clone a project. */ router.post( '/:projectId/clone', requireProjectAccess('viewer'), projectValidators.cloneProject, asyncApi(cloneProject) ); export async function cloneProject( req: express.Request, res: express.Response ): ProjectIdPromise { const originalProjectId = req.params.projectId; const user = auth.extractRequestUser(req); const originalProject: db.DbProject = res.locals.project; const body = req.body; const projectId = await db.createProject( { title: body.title, version: body.version, description: originalProject.description, planned_release: originalProject.planned_release, contacts: originalProject.contacts, acl: body.acl, refs: { [originalProjectId]: { type: 'cloned_from' }, }, metadata: originalProject.metadata, }, user ); // copy over packages_used too! await db.updatePackagesUsed(projectId, originalProject.packages_used, user); winston.info( `Project ${projectId} cloned from ${originalProjectId} by ${user}` ); return { projectId }; } router.post( '/:projectId/refs', requireProjectAccess('editor'), projectValidators.createRef, asyncApi(createRef) ); export async function createRef( req: express.Request, res: express.Response ): ProjectIdPromise { const { params: { projectId }, body: { targetProjectId, type, comment }, } = req; const project: db.DbProject = res.locals.project; const user = auth.extractRequestUser(req); // ensure the user has permission to see the target project as well const targetProject = await db.getProject(targetProjectId); try { await assertProjectAccess(req, targetProject, 'viewer'); } catch (err) { // give a nicer error for this one if (err instanceof AccessError) { throw new AccessError( "You don't have viewer access on the project you're linking to, or it doesn't exist." ); } throw err; } const refs: { [id: string]: db.DbProjectRef } = { ...project.refs, [targetProjectId]: { type, // validated in projectValidators comment, }, }; await db.patchProject(projectId, { refs }, user); return { projectId }; } router.get( '/:projectId/refs', requireProjectAccess('viewer'), asyncApi(getRefInfo) ); export async function getRefInfo( req: express.Request, res: express.Response ): Promise<{ refs: RefInfo[]; reverseRefs: any }> { const { params: { projectId }, } = req; // first, fetch all projects from our refs const project: db.DbProject = res.locals.project; const refs = (await db.getProjectRefs(Object.keys(project.refs))).map( (p) => ({ projectId: p.project_id, title: p.title, version: p.version, packageIds: p.packages_used.map((usage) => usage.package_id), }) ); // then, figure out which projects reference us const reverseRefs = (await db.getProjectsRefReverse(projectId)).map((p) => ({ projectId: p.project_id, title: p.title, version: p.version, })); return { refs, reverseRefs, }; } router.delete( '/:projectId/refs/:targetProjectId', requireProjectAccess('editor'), asyncApi(deleteRef) ); export async function deleteRef( req: express.Request, res: express.Response ): ProjectIdPromise { const { params: { projectId, targetProjectId }, } = req; const project: db.DbProject = res.locals.project; const user = auth.extractRequestUser(req); // no permission on a target project needed to *remove* a ref; that's fine. const refs = { ...project.refs, }; delete refs[targetProjectId]; await db.patchProject(projectId, { refs }, user); return { projectId }; } /** * Fetch the project's audit log. */ router.get( '/:projectId/changes', requireProjectAccess('viewer'), asyncApi(listProjectChanges) ); export async function listProjectChanges( req: express.Request, res: express.Response ) { const changes = await getProjectAuditLog(req.params.projectId); return { changes: changes.map((c) => ({ id: c.id, projectId: c.project_id, who: c.who, changedOn: c.changed_on, changedTo: c.changed_to, })), }; }
the_stack
import test from 'ava' import * as React from 'react' import { Simulate } from 'react-dom/test-utils' import { debounceTime, distinctUntilChanged, filter, map, pairwise } from 'rxjs/operators' import { Effects, Store } from '../../src' import { createConnectedStore } from '../../src/react/createConnectedStore' import { withElement } from '../testUtils' test('it should render', t => { let { Container, withStore } = createConnectedStore({ a: 1 }) let B = withStore(({ store }) => ( <button onClick={() => store.set('a')(store.get('a') + 1)}> {store.get('a')} </button> )) let A = () => ( <Container> <B /> </Container> ) withElement(A, a => { t.is(a.querySelector('button')!.innerHTML, '1') Simulate.click(a.querySelector('button')!) t.is(a.querySelector('button')!.innerHTML, '2') }) }) test('it should update (with extra props)', t => { let { Container, withStore } = createConnectedStore({ a: 1 }) type Props = { extra: string onChange(): void store: Store<{ a: number }> } let B = withStore((props: Props) => ( <> <button onClick={() => props.onChange()}>{props.extra}</button> {props.store.get('a')} </> )) class A extends React.Component { state = { extra: 'a' } onChange = () => this.setState({ extra: 'b' }) render() { return ( <Container> <B extra={this.state.extra} onChange={this.onChange} /> </Container> ) } } withElement(A, a => { t.is(a.querySelector('button')!.innerHTML, 'a') Simulate.click(a.querySelector('button')!) t.is(a.querySelector('button')!.innerHTML, 'b') }) }) test('it should support effects', t => { t.plan(1) type State = { a: number } let withEffects: Effects<State> = store => { store.on('a').subscribe(a => { t.is(a, 2) }) return store } let { Container, withStore } = createConnectedStore({ a: 1 }, withEffects) let C = withStore(({ store }) => ( <button onClick={() => store.set('a')(store.get('a') + 1)}> {store.get('a')} </button> )) let A = () => ( <Container> <C /> </Container> ) withElement(A, _ => Simulate.click(_.querySelector('button')!)) }) test.cb('it should support effects with rx opererators', t => { t.plan(2) type State = { a: number b: number } let store: Store<{ a: number; b: number }> let withEffects: Effects<State> = s => { store = s s.on('a') .pipe( distinctUntilChanged(), filter(_ => _ > 2), pairwise(), map(([a]) => a * 6), debounceTime(0) ) .subscribe(store.set('b')) return s } let { Container, withStore } = createConnectedStore( { a: 1, b: 1 }, withEffects ) let C = withStore(({ store }) => ( <button onClick={() => store.set('a')(store.get('a') + 1)}> {store.get('a')} </button> )) let A = () => ( <Container> <C /> </Container> ) withElement(A, _ => { Simulate.click(_.querySelector('button')!) t.is(store.get('b'), 1) Simulate.click(_.querySelector('button')!) Simulate.click(_.querySelector('button')!) setTimeout(() => { t.is(store.get('b'), 18) t.end() }, 0) }) }) test('it should support multiple instances of a store', t => { let { Container, withStore } = createConnectedStore({ a: 1 }) let C = withStore(({ store }) => ( <button onClick={() => store.set('a')(store.get('a') + 1)}> {store.get('a')} </button> )) let A = () => ( <Container> <C /> </Container> ) let B = () => ( <Container> <C /> </Container> ) withElement(A, a => withElement(B, b => { t.is(a.querySelector('button')!.innerHTML, '1') t.is(b.querySelector('button')!.innerHTML, '1') Simulate.click(a.querySelector('button')!) t.is(a.querySelector('button')!.innerHTML, '2') t.is(b.querySelector('button')!.innerHTML, '1') Simulate.click(b.querySelector('button')!) t.is(a.querySelector('button')!.innerHTML, '2') t.is(b.querySelector('button')!.innerHTML, '2') }) ) }) test('it should support multiple instances of a store, with disjoint lifecycles', t => { let { Container, withStore } = createConnectedStore({ a: 1 }) let C = withStore(({ store }) => ( <button onClick={() => store.set('a')(store.get('a') + 1)}> {store.get('a')} </button> )) let A = () => ( <Container> <C /> </Container> ) let B = () => ( <Container> <C /> </Container> ) withElement(A, a => { t.is(a.querySelector('button')!.innerHTML, '1') Simulate.click(a.querySelector('button')!) t.is(a.querySelector('button')!.innerHTML, '2') }) withElement(B, b => { t.is(b.querySelector('button')!.innerHTML, '1') Simulate.click(b.querySelector('button')!) t.is(b.querySelector('button')!.innerHTML, '2') }) }) test('it should support multiple instances of a store in one tree, with disjoint lifecycles', t => { let Test = createConnectedStore({ isA: true }) let { Container, withStore } = createConnectedStore({ a: 1 }) let C = withStore(({ store }) => ( <button id="C" onClick={() => store.set('a')(store.get('a') + 1)}> {store.get('a')} </button> )) let A = () => ( <Container> <C /> </Container> ) let B = () => ( <Container> <C /> </Container> ) let D = Test.withStore(({ store }) => ( <> {store.get('isA') ? <A /> : <B />} <button id="D" onClick={() => store.set('isA')(!store.get('isA'))} /> </> )) let E = () => ( <Test.Container> <D /> </Test.Container> ) withElement(E, e => { t.is(e.querySelector('#C')!.innerHTML, '1') Simulate.click(e.querySelector('#C')!) t.is(e.querySelector('#C')!.innerHTML, '2') // Swap subtree Simulate.click(e.querySelector('#D')!) t.is(e.querySelector('#C')!.innerHTML, '1') Simulate.click(e.querySelector('#C')!) t.is(e.querySelector('#C')!.innerHTML, '2') // Swap subtree Simulate.click(e.querySelector('#D')!) t.is(e.querySelector('#C')!.innerHTML, '1') Simulate.click(e.querySelector('#C')!) t.is(e.querySelector('#C')!.innerHTML, '2') }) }) test('it should support interleaved stores', t => { let A = createConnectedStore({ a: 1 }) let B = createConnectedStore({ b: 1 }) let C = A.withStore(({ store }) => ( <button onClick={() => store.set('a')(store.get('a') + 1)}> {store.get('a')} </button> )) let D = B.withStore(({ store }) => ( <button onClick={() => store.set('b')(store.get('b') + 1)}> {store.get('b')} </button> )) let X = () => ( <A.Container> <C /> <B.Container> <D /> <C /> </B.Container> </A.Container> ) withElement(X, x => { assertButtons(x, 1, 1, 1) Simulate.click(x.querySelectorAll('button')[0]) assertButtons(x, 2, 1, 2) Simulate.click(x.querySelectorAll('button')[1]) assertButtons(x, 2, 2, 2) Simulate.click(x.querySelectorAll('button')[2]) assertButtons(x, 3, 2, 3) }) function assertButtons(x: Element, one: number, two: number, three: number) { t.is(x.querySelectorAll('button')[0].innerHTML, one.toString()) t.is(x.querySelectorAll('button')[1].innerHTML, two.toString()) t.is(x.querySelectorAll('button')[2].innerHTML, three.toString()) } }) test('it should support custom initialState', t => { let { Container, withStore } = createConnectedStore({ a: 1 }) let C = withStore(({ store }) => ( <button onClick={() => store.set('a')(store.get('a') + 1)}> {store.get('a')} </button> )) let A = () => ( <Container initialState={{ a: 101 }}> <C /> </Container> ) let B = () => ( <Container> <C /> </Container> ) withElement(A, a => withElement(B, b => { t.is(a.querySelector('button')!.innerHTML, '101') t.is(b.querySelector('button')!.innerHTML, '1') Simulate.click(a.querySelector('button')!) t.is(a.querySelector('button')!.innerHTML, '102') t.is(b.querySelector('button')!.innerHTML, '1') Simulate.click(b.querySelector('button')!) t.is(a.querySelector('button')!.innerHTML, '102') t.is(b.querySelector('button')!.innerHTML, '2') }) ) }) test('it should support custom effects', t => { t.plan(1) type State = { a: number } let { Container, withStore } = createConnectedStore({ a: 1 }) let withEffects: Effects<State> = store => { store.on('a').subscribe(a => { t.is(a, 2) }) return store } let C = withStore(({ store }) => ( <button onClick={() => store.set('a')(store.get('a') + 1)}> {store.get('a')} </button> )) let A = () => ( <Container effects={withEffects}> <C /> </Container> ) withElement(A, _ => Simulate.click(_.querySelector('button')!)) }) test('it should eagerly throw at runtime when using a consumer without a container (createConnectedStore)', t => { let { withStore } = createConnectedStore({ a: 1 }) let A = withStore(() => <div />) t.throws(() => withElement(A, _ => {}), { message: /does not seem to be nested/ }) }) test('it should re-render if a used model property changed', t => { let renderCount = 0 let store: Store<{ a: number; b: number }> let S = createConnectedStore( { a: 1, b: 1 }, s => { store = s return s } ) let A = S.withStore(({ store }) => { renderCount++ return <>{store.get('a')}</> }) let B = () => ( <S.Container> <A /> </S.Container> ) withElement(B, _ => { store.set('a')(2) store.set('a')(3) t.is(renderCount, 3) }) }) test('it should re-render if an unused model property changed', t => { let renderCount = 0 let store: Store<{ a: number; b: number }> let S = createConnectedStore( { a: 1, b: 1 }, s => { store = s return s } ) let A = S.withStore(({ store }) => { renderCount++ return <>{store.get('a')}</> }) let B = () => ( <S.Container> <A /> </S.Container> ) withElement(B, _ => { store.set('b')(2) store.set('b')(3) t.is(renderCount, 3) }) }) test('it should update even when unused fields change (get)', t => { let store: Store<{ a: number; b: string }> let S = createConnectedStore( { a: 0, b: 'foo' }, s => { store = s return s } ) let renderCount = 0 type Props = { store: Store<{ a: number; b: string }> } let A = S.withStore( class Test extends React.Component<Props> { render() { renderCount++ return ( <> {this.props.store.get('a')} <button id="a" onClick={() => this.props.store.set('a')(this.props.store.get('a') + 1) } /> <button id="b" onClick={() => this.props.store.set('a')(this.props.store.get('a') - 1) } /> {this.props.store.get('a') > 0 ? ( <div>{this.props.store.get('b')}</div> ) : ( <span /> )} </> ) } } ) let B = () => ( <S.Container> <A /> </S.Container> ) withElement(B, _ => { store.set('b')('bar') // No render t.is( _.innerHTML, '0<button id="a"></button><button id="b"></button><span></span>' ) Simulate.click(_.querySelector('#a')!) // Render t.is( _.innerHTML, '1<button id="a"></button><button id="b"></button><div>bar</div>' ) Simulate.click(_.querySelector('#b')!) // Render t.is( _.innerHTML, '0<button id="a"></button><button id="b"></button><span></span>' ) store.set('b')('baz') // Render t.is( _.innerHTML, '0<button id="a"></button><button id="b"></button><span></span>' ) t.is(renderCount, 5) }) }) test('it should update even when unused fields change (get in lifecycle)', t => { let store: Store<{ a: number; b: string }> let S = createConnectedStore( { a: 0, b: 'foo' }, s => { store = s return s } ) let renderCount = 0 type Props = { store: Store<{ a: number; b: string }> } let A = S.withStore( class Test extends React.Component<Props> { shouldComponentUpdate(p: Props) { return p.store.get('b') !== this.props.store.get('b') || true } render() { renderCount++ return ( <> {this.props.store.get('a')} {this.props.store.get('a') > 0 ? ( <div>{this.props.store.get('b')}</div> ) : ( <span /> )} </> ) } } ) let B = () => ( <S.Container> <A /> </S.Container> ) withElement(B, _ => { store.set('b')('bar') // No render t.is(_.innerHTML, '0<span></span>') store.set('a')(1) // Render, and trigger shouldComponentUpdate store.set('b')('a') // Render store.set('b')('b') // Render t.is(renderCount, 5) }) }) test('it should update even when unused fields change (getState in lifecycle 1)', t => { let store: Store<{ a: number; b: string }> let S = createConnectedStore( { a: 0, b: 'foo' }, s => { store = s return s } ) let renderCount = 0 type Props = { store: Store<{ a: number; b: string }> } let A = S.withStore( class Test extends React.Component<Props> { shouldComponentUpdate(p: Props) { return p.store.getState().b !== this.props.store.get('b') || true } render() { renderCount++ return this.props.store.get('a') } } ) let B = () => ( <S.Container> <A /> </S.Container> ) withElement(B, _ => { store.set('b')('bar') // No render t.is(_.innerHTML, '0') store.set('a')(1) // Render, and trigger shouldComponentUpdate store.set('b')('a') // Render store.set('b')('b') // Render t.is(renderCount, 5) }) }) test('[stateful] it should update even when unused fields change (getState in lifecycle 2)', t => { let store: Store<{ a: number; b: string }> let S = createConnectedStore( { a: 0, b: 'foo' }, s => { store = s return s } ) let renderCount = 0 type Props = { store: Store<{ a: number; b: string }> } let A = S.withStore( class Test extends React.Component<Props> { shouldComponentUpdate(p: Props) { return p.store.get('b') !== this.props.store.getState().b || true } render() { renderCount++ return this.props.store.get('a') } } ) let B = () => ( <S.Container> <A /> </S.Container> ) withElement(B, _ => { store.set('b')('bar') // No render t.is(_.innerHTML, '0') store.set('a')(1) // Render, and trigger shouldComponentUpdate store.set('b')('a') // Render store.set('b')('b') // Render t.is(renderCount, 5) }) }) test('[stateful] it should update only when subscribed fields change (get in constructor)', t => { let store: Store<{ a: number; b: string }> let S = createConnectedStore( { a: 0, b: 'foo' }, s => { store = s return s } ) let renderCount = 0 type Props = { store: Store<{ a: number; b: string }> } let A = S.withStore( class Test extends React.Component<Props> { constructor(p: Props) { super(p) let _ = this.props.store.get('b') // Trigger read } render() { renderCount++ return ( <> {this.props.store.get('a')} {this.props.store.get('a') > 0 ? ( <div>{this.props.store.get('b')}</div> ) : ( <span /> )} </> ) } } ) let B = () => ( <S.Container> <A /> </S.Container> ) withElement(B, _ => { store.set('b')('bar') // Render t.is(_.innerHTML, '0<span></span>') store.set('a')(1) // Render store.set('b')('a') // Render store.set('b')('b') // Render t.is(renderCount, 5) }) }) test('it should update when subscribed fields change (set in constructor)', t => { let S = createConnectedStore({ a: 0 }) let renderCount = 0 type Props = { store: Store<{ a: number }> } let A = S.withStore( class Test extends React.Component<Props> { constructor(p: Props) { super(p) this.props.store.set('a')(1) } render() { renderCount++ return <>{this.props.store.get('a')}</> } } ) let B = () => ( <S.Container> <A /> </S.Container> ) withElement(B, _ => { t.is(_.innerHTML, '1') t.is(renderCount, 2) }) }) test('[stateful] it should update when any field changes (getState)', t => { let store: Store<{ a: number; b: string }> let S = createConnectedStore( { a: 0, b: 'foo' }, s => { store = s return s } ) let renderCount = 0 type Props = { store: Store<{ a: number; b: string }> } let A = S.withStore( class Test extends React.Component<Props> { render() { renderCount++ return ( <> {this.props.store.getState().a} <button id="a" onClick={() => this.props.store.set('a')(this.props.store.get('a') + 1) } /> <button id="b" onClick={() => this.props.store.set('a')(this.props.store.get('a') - 1) } /> {this.props.store.get('a') > 0 ? ( <div>{this.props.store.get('b')}</div> ) : ( <span /> )} </> ) } } ) let B = () => ( <S.Container> <A /> </S.Container> ) withElement(B, _ => { store.set('b')('bar') // Render (this is the deoptimization when you use .getState) t.is( _.innerHTML, '0<button id="a"></button><button id="b"></button><span></span>' ) Simulate.click(_.querySelector('#a')!) // Render t.is( _.innerHTML, '1<button id="a"></button><button id="b"></button><div>bar</div>' ) Simulate.click(_.querySelector('#b')!) // Render t.is( _.innerHTML, '0<button id="a"></button><button id="b"></button><span></span>' ) store.set('b')('baz') // Render t.is( _.innerHTML, '0<button id="a"></button><button id="b"></button><span></span>' ) t.is(renderCount, 5) }) }) test("it should get the most up-to-date version of a field, even if Undux doesn't know the component depends on it", t => { t.plan(2) let S = createConnectedStore({ a: 0 }) type Props = { store: Store<{ a: number }> } let A = S.withStore( class Test extends React.Component<Props> { constructor(p: Props) { super(p) this.props.store.set('a')(1) } render() { return <>{this.props.store.get('a')}</> } } ) let B = S.withStore( class Test extends React.Component<Props & { onClick(a: number): void }> { onClick = () => this.props.onClick(this.props.store.get('a')) render() { return ( <> <button onClick={this.onClick} /> <A /> </> ) } } ) let C = () => ( <S.Container> <B onClick={a => t.is(a, 1)} /> </S.Container> ) withElement(C, _ => { t.is(_.innerHTML, '<button></button>1') Simulate.click(_.querySelector('button')!) }) }) test('it should return the same value when call .get multiple times for one snapshot', t => { t.plan(4) let S = createConnectedStore({ a: 0 }) type Props = { store: Store<{ a: number }> } let A = S.withStore( class Test extends React.Component<Props> { constructor(p: Props) { super(p) this.props.store.set('a')(1) } render() { return <>{this.props.store.get('a')}</> } } ) let B = S.withStore( class Test extends React.Component<Props & { onClick(a: number): void }> { onClick = () => { this.props.onClick(this.props.store.get('a')) this.props.onClick(this.props.store.get('a')) this.props.onClick(this.props.store.get('a')) } render() { return ( <> <button onClick={this.onClick} /> <A /> </> ) } } ) let call = 0 let C = () => ( <S.Container> <B onClick={a => { switch (call) { case 0: return t.is(a, 1) case 1: return t.is(a, 1) case 2: return t.is(a, 1) } call++ }} /> </S.Container> ) withElement(C, _ => { t.is(_.innerHTML, '<button></button>1') Simulate.click(_.querySelector('button')!) }) }) test('it should return the same value when call .get multiple times for one snapshot, even when using shouldComponentUpdate', t => { let S = createConnectedStore({ a: 'a' }) let X = S.withStore(props => ( <button onClick={() => props.store.set('a')('x')}> {props.store.get('a')} </button> )) let Y = S.withStore(props => ( <button onClick={() => props.store.set('a')('y')}> {props.store.get('a')} </button> )) let Z = S.withStore(props => ( <button onClick={() => props.store.set('a')('z')}> {props.store.get('a')} </button> )) let A = S.withStore( class Test extends React.Component<{ store: Store<{ a: string }> }> { shouldComponentUpdate(props: { store: Store<{ a: string }> }) { return props.store.get('a') !== this.props.store.get('a') } render() { switch (this.props.store.get('a')) { case 'a': return <X /> case 'x': return <Y /> case 'y': return <Z /> default: return <>{this.props.store.get('a')}</> } } } ) let store: Store<{ a: string }> let Leak = S.withStore(props => { store = (props as any).store.storeDefinition return null }) let C = () => ( <S.Container> <Leak /> <A /> </S.Container> ) withElement(C, _ => { t.is(_.innerHTML, '<button>a</button>') t.is(store.get('a'), 'a') Simulate.click(_.querySelector('button')!) t.is(store.get('a'), 'x') t.is(_.innerHTML, '<button>x</button>') Simulate.click(_.querySelector('button')!) t.is(store.get('a'), 'y') t.is(_.innerHTML, '<button>y</button>') Simulate.click(_.querySelector('button')!) t.is(store.get('a'), 'z') t.is(_.innerHTML, 'z') }) }) test('it should fail for async updates by default', t => { type State = { as: number[] } let S = createConnectedStore<State>({ as: [] }) let index = 0 type Props = { store: Store<State> } class A extends React.Component<Props> { componentDidMount() { const as = this.props.store.get('as') this.props.store.set('as')([...as, index++]) } render() { return <div /> } } let A1 = S.withStore(A) function B() { return ( <> <A1 /> <A1 /> <A1 /> </> ) } let store: Store<State> let Leak = S.withStore(props => { store = (props as any).store.storeDefinition return null }) function C() { return ( <S.Container> <Leak /> <B /> </S.Container> ) } withElement(C, _ => { t.deepEqual(store.get('as'), [2]) }) }) test('it should work for async updates using setFrom_EXPERIMENTAL', t => { type State = { as: number[] } let S = createConnectedStore<State>({ as: [] }) let index = 0 type Props = { store: Store<State> } class A extends React.Component<Props> { componentDidMount() { this.props.store.setFrom_EXPERIMENTAL(store => { let as = store.get('as') store.set('as')([...as, index++]) }) } render() { return <div /> } } let A1 = S.withStore(A) function B() { return ( <> <A1 /> <A1 /> <A1 /> </> ) } let store: Store<State> let Leak = S.withStore(props => { store = (props as any).store.storeDefinition return null }) function C() { return ( <S.Container> <Leak /> <B /> </S.Container> ) } withElement(C, _ => { t.deepEqual(store.get('as'), [0, 1, 2]) }) }) test('setFrom_EXPERIMENTAL should compose', t => { type State = { as: number[] } let S = createConnectedStore<State>({ as: [] }) let index = 0 type Props = { store: Store<State> } class A extends React.Component<Props> { componentDidMount() { this.props.store.setFrom_EXPERIMENTAL(store => { let as = store.get('as') store.set('as')([...as, index++]) // One more time store.setFrom_EXPERIMENTAL(store => { let as = store.get('as') store.set('as')([...as, index++]) }) }) } render() { return <div /> } } let A1 = S.withStore(A) function B() { return ( <> <A1 /> <A1 /> <A1 /> </> ) } let store: Store<State> let Leak = S.withStore(props => { store = (props as any).store.storeDefinition return null }) function C() { return ( <S.Container> <Leak /> <B /> </S.Container> ) } withElement(C, _ => { t.deepEqual(store.get('as'), [0, 1, 2, 3, 4, 5]) }) }) test('setFrom_EXPERIMENTAL should chain', t => { type State = { as: number } let S = createConnectedStore<State>({ as: 0 }) type Props = { store: Store<State> } class A extends React.Component<Props> { componentDidMount() { this.props.store.setFrom_EXPERIMENTAL(store => store.set('as')(store.get('as') + 1) ) this.props.store.setFrom_EXPERIMENTAL(store => store.set('as')(store.get('as') + 1) ) this.props.store.setFrom_EXPERIMENTAL(store => store.set('as')(store.get('as') + 1) ) } render() { return <div /> } } let A1 = S.withStore(A) let store: Store<State> let Leak = S.withStore(props => { store = (props as any).store.storeDefinition return null }) function C() { return ( <S.Container> <Leak /> <A1 /> </S.Container> ) } withElement(C, _ => { t.deepEqual(store.get('as'), 3) }) })
the_stack
// ------------------------------------------------------------------------------------------------- // Copyright (c) Microsoft Corporation. All rights reserved. // Licensed under the MIT License (MIT). See LICENSE in the repo root for license information. // ------------------------------------------------------------------------------------------------- import * as React from 'react'; import { FormGroup, Label, Input, Card, CardBody, CardTitle } from 'reactstrap'; import { DeviceValueSet, DeviceMapping } from '../../store/Mapping'; import * as Constants from '../Constants'; import { DeleteIcon } from '../Icons'; import * as Utility from './Utility'; const TypeMatchExpression = (props: { data: string; onUpdate: Function }) => { return ( <FormGroup> <Label for="deviceMetaTypeMatch">{Constants.Text.LabelTypeMatchExpression}</Label> <Input type="text" name="deviceMetaTypeMatch" id="deviceMetaTypeMatch" defaultValue={props.data} onChange={(e) => props.onUpdate(e.target.value)} /> </FormGroup> ); } const DeviceIdExpression = (props: { data: string; onUpdate: Function }) => { return ( <FormGroup> <Label for="deviceMetaDeviceId">{Constants.Text.LabelDeviceIdExpression}</Label> <Input type="text" name="deviceMetaDeviceId" id="deviceMetaDeviceId" defaultValue={props.data} onChange={(e) => props.onUpdate(e.target.value)} /> </FormGroup> ); } const TimestampExpression = (props: { data: string; onUpdate: Function }) => { return ( <FormGroup> <Label for="deviceMetaTimestamp">{Constants.Text.LabelTimeStampExpression}</Label> <Input type="text" name="deviceMetaTimestamp" id="deviceMetaTimestamp" defaultValue={props.data} onChange={(e) => props.onUpdate(e.target.value)} /> </FormGroup> ); } const PatientIdExpression = (props: { data: string; onUpdate: Function }) => { return ( <FormGroup> <Label for="deviceMetaPatientId">{Constants.Text.LabelPatientIdExpression}</Label> <Input type="text" name="deviceMetaPatientId" id="deviceMetaPatientId" defaultValue={props.data} onChange={(e) => props.onUpdate(e.target.value)} /> </FormGroup> ); } const EncounterIdExpression = (props: { data: string; onUpdate: Function }) => { return ( <FormGroup> <Label for="deviceMetaEncounterId">{Constants.Text.LabelEncounterIdExpression}</Label> <Input type="text" name="deviceMetaEncounterId" id="deviceMetaEncounterId" defaultValue={props.data} onChange={(e) => props.onUpdate(e.target.value)} /> </FormGroup> ); } const CorrelationIdExpression = (props: { data: string; onUpdate: Function }) => { return ( <FormGroup> <Label for="deviceMetaCorrelationId">{Constants.Text.LabelCorrelationIdExpression}</Label> <Input type="text" name="deviceMetaCorrelationId" id="deviceMetaCorrelationId" defaultValue={props.data} onChange={(e) => props.onUpdate(e.target.value)} /> </FormGroup> ); } const DeviceValueName = (props: { data: DeviceValueSet; onUpdate: Function; modifier?: string }) => { return ( <FormGroup> <Label for={`deviceValueName-${props.modifier}`}>{Constants.Text.LabelDeviceValueName}</Label> <Input type="text" name={`deviceValueName-${props.modifier}`} id={`deviceValueName-${props.modifier}`} value={props.data.valueName} onChange={e => props.onUpdate(e.target.value)} /> </FormGroup> ); } const DeviceValueExpression = (props: { data: DeviceValueSet; onUpdate: Function; modifier?: string }) => { return ( <FormGroup> <Label for={`deviceValueExpression-${props.modifier}`}>{Constants.Text.LabelDeviceValueExpression}</Label> <Input type="text" name={`deviceValueExpression-${props.modifier}`} id={`deviceValueExpression-${props.modifier}`} value={props.data.valueExpression} onChange={e => props.onUpdate(e.target.value)} /> </FormGroup> ); } const DeviceValueRequired = (props: { data: DeviceValueSet; onUpdate: Function; modifier?: string }) => { return ( <FormGroup> <Label for={`deviceValueRequired-${props.modifier}`}>{Constants.Text.LabelDeviceValueRequired}</Label> <Input type="checkbox" name={`deviceValueRequired-${props.modifier}`} id={`deviceValueRequired-${props.modifier}`} style={{ left: "40%" }} checked={props.data.required} onChange={e => props.onUpdate(e.target.checked)} /> </FormGroup> ); } const DeviceValuesForm = (props: { data: DeviceValueSet[]; onUpdate: Function; }) => { // Fix the display of input array. const [keyModifier, refreshKeyModifier] = React.useState(Utility.getRandomString()); const appendDeviceValueSet = () => { const updatedDeviceValueSets = [...props.data, {} as DeviceValueSet]; refreshKeyModifier(Utility.getRandomString()); props.onUpdate(updatedDeviceValueSets); } const removeDeviceValueSet = (removeIndex: number) => { const updatedDeviceValueSets = [...props.data.filter((_, index) => index !== removeIndex)]; refreshKeyModifier(Utility.getRandomString()); props.onUpdate(updatedDeviceValueSets); } const updateDeviceValueSet = (index: number, name: string, value: any) => { const updatedDeviceValueSets = props.data; switch (name) { case 'required': updatedDeviceValueSets[index].required = value; break; case 'valueExpression': updatedDeviceValueSets[index].valueExpression = value; break; case 'valueName': updatedDeviceValueSets[index].valueName = value; break; default: } props.onUpdate(updatedDeviceValueSets); } const renderDeviceValueSet = (valueSet: DeviceValueSet, index: number) => { const keySuffix = `-${index}-${keyModifier}`; return ( <Card className="mb-3" key={`deviceValue-${keySuffix}`}> <CardTitle className="p-2 border-bottom"> Value <button className="btn iomt-cm-btn-link iomt-cm-right p-0" onClick={() => removeDeviceValueSet(index)}> <DeleteIcon /> </button> </CardTitle> <CardBody> <DeviceValueName data={valueSet} onUpdate={(val: string) => updateDeviceValueSet(index, 'valueName', val)} modifier={`deviceValueName-${keySuffix}`} /> <DeviceValueExpression data={valueSet} onUpdate={(val: string) => updateDeviceValueSet(index, 'valueExpression', val)} modifier={`deviceValueExpression-${keySuffix}`} /> <DeviceValueRequired data={valueSet} onUpdate={(val: string) => updateDeviceValueSet(index, 'required', val)} modifier={`deviceValueRequired-${keySuffix}`} /> </CardBody> </Card> ) } return ( <React.Fragment> <div className="position-relative"> <Label>{Constants.Text.LabelDeviceValues}</Label> <button className="btn iomt-cm-btn-link" onClick={appendDeviceValueSet}> + Value </button> </div> {props.data.map(renderDeviceValueSet)} </React.Fragment> ); } const DeviceEditForm = (props: { data: DeviceMapping; onUpdate: Function }) => { return ( <React.Fragment> <TypeMatchExpression data={props.data.typeMatchExpression} onUpdate={(updatedTypeMatchExpression: string) => { const updatedDeviceMapping = { ...props.data, typeMatchExpression: updatedTypeMatchExpression } as DeviceMapping; props.onUpdate(updatedDeviceMapping); }} /> <DeviceIdExpression data={props.data.deviceIdExpression} onUpdate={(updatedDeviceIdExpression: string) => { const updatedDeviceMapping = { ...props.data, deviceIdExpression: updatedDeviceIdExpression } as DeviceMapping; props.onUpdate(updatedDeviceMapping); }} /> <TimestampExpression data={props.data.timestampExpression} onUpdate={(updatedTimestampExpression: string) => { const updatedDeviceMapping = { ...props.data, timestampExpression: updatedTimestampExpression } as DeviceMapping; props.onUpdate(updatedDeviceMapping); }} /> <PatientIdExpression data={props.data.patientIdExpression} onUpdate={(updatedPatientIdExpression: string) => { const updatedDeviceMapping = { ...props.data, patientIdExpression: updatedPatientIdExpression } as DeviceMapping; props.onUpdate(updatedDeviceMapping); }} /> <EncounterIdExpression data={props.data.encounterIdExpression} onUpdate={(updatedEncounterIdExpression: string) => { const updatedDeviceMapping = { ...props.data, encounterIdExpression: updatedEncounterIdExpression } as DeviceMapping; props.onUpdate(updatedDeviceMapping); }} /> <CorrelationIdExpression data={props.data.correlationIdExpression} onUpdate={(updatedCorrelationIdExpression: string) => { const updatedDeviceMapping = { ...props.data, correlationIdExpression: updatedCorrelationIdExpression } as DeviceMapping; props.onUpdate(updatedDeviceMapping); }} /> <DeviceValuesForm data={props.data.values || [] as DeviceValueSet[]} onUpdate={(updatedDeviceValueSets: DeviceValueSet[]) => { const updatedDeviceMapping = { ...props.data, values: updatedDeviceValueSets } as DeviceMapping; props.onUpdate(updatedDeviceMapping); }} /> </React.Fragment> ); } export default DeviceEditForm;
the_stack
import * as fs from 'fs'; import { AsynchronousLocalStorage } from '../AsynchronousLocalStorage'; const cls: AsynchronousLocalStorage<Number> = new AsynchronousLocalStorage<Number>(); const DODEBUG = 0; function debugId(prefix: string): void { if (!DODEBUG) { return; } console.log('TEST: ' + prefix); } // ####################################################################################################################### describe('test asynchronous:', () => { it('calling process.nextTick should preserve continuation local storage', (done) => { debugId('process.nextTick: START BEGIN'); const startValue = 211; expect(cls.setContext(startValue)) .withContext(`start value (${startValue}) not set`) .toBe(startValue); debugId('process.nextTick: START END '); process.nextTick(() => { debugId('process.nextTick: OUTER BEGIN'); expect(cls.getContext()) .withContext(`outer value is not the expected start value (${startValue})`) .toBe(startValue); const outerValue = startValue + 1; expect(cls.setContext(outerValue)) .withContext(`outer value (${outerValue}) not set`) .toBe(outerValue); debugId('process.nextTick: OUTER END '); process.nextTick(() => { debugId('process.nextTick: INNER BEGIN'); expect(cls.getContext()) .withContext(`inner value is not the expected outer value (${outerValue})`) .toBe(outerValue); const innerValue = outerValue + 1; expect(cls.setContext(innerValue)) .withContext(`inner value (${innerValue}) not set`) .toBe(innerValue); debugId('process.nextTick: INNER END '); done(); }); }); }); it('calling setImmediate should preserve continuation local storage', (done) => { debugId('setImmediate: START BEGIN'); const startValue = 221; expect(cls.setContext(startValue)) .withContext(`start value (${startValue}) not set`) .toBe(startValue); debugId('setImmediate: START END '); setImmediate(() => { debugId('setImmediate: OUTER BEGIN'); expect(cls.getContext()) .withContext(`outer value is not the expected start value (${startValue})`) .toBe(startValue); const outerValue = startValue + 1; expect(cls.setContext(outerValue)) .withContext(`outer value (${outerValue}) not set`) .toBe(outerValue); debugId('setImmediate: OUTER END '); setImmediate(() => { debugId('setImmediate: INNER BEGIN'); expect(cls.getContext()) .withContext(`inner value is not the expected outer value (${outerValue})`) .toBe(outerValue); const innerValue = outerValue + 1; expect(cls.setContext(innerValue)) .withContext(`inner value (${innerValue}) not set`) .toBe(innerValue); debugId('setImmediate: INNER END '); done(); }); }); }); it('calling setTimeout should preserve continuation local storage', (done) => { debugId('setTimeout: START BEGIN'); const startValue = 231; expect(cls.setContext(startValue)) .withContext(`start value (${startValue}) not set`) .toBe(startValue); debugId('setTimeout: START END '); setTimeout(() => { debugId('setTimeout: OUTER BEGIN'); expect(cls.getContext()) .withContext(`outer value is not the expected start value (${startValue})`) .toBe(startValue); const outerValue = startValue + 1; expect(cls.setContext(outerValue)) .withContext(`outer value (${outerValue}) not set`) .toBe(outerValue); debugId('setTimeout: OUTER END '); setTimeout(() => { debugId('setTimeout: INNER BEGIN'); expect(cls.getContext()) .withContext(`inner value is not the expected outer value (${outerValue})`) .toBe(outerValue); const innerValue = outerValue + 1; expect(cls.setContext(innerValue)) .withContext(`inner value (${innerValue}) not set`) .toBe(innerValue); debugId('setTimeout: INNER END '); done(); }, 0); }, 0); }); it('calling setInterval should preserve continuation local storage', (done) => { debugId('setInterval: START BEGIN'); const startValue = 241; expect(cls.setContext(startValue)) .withContext(`start value (${startValue}) not set`) .toBe(startValue); debugId('setInterval: START END '); const timer1 = setInterval(() => { debugId('setInterval: OUTER BEGIN'); expect(cls.getContext()) .withContext(`outer value is not the expected start value (${startValue})`) .toBe(startValue); const outerValue = startValue + 1; expect(cls.setContext(outerValue)) .withContext(`outer value (${outerValue}) not set`) .toBe(outerValue); debugId('setInterval: OUTER END '); clearInterval(timer1); const timer2 = setInterval(() => { debugId('setInterval: INNER BEGIN'); expect(cls.getContext()) .withContext(`inner value is not the expected outer value (${outerValue})`) .toBe(outerValue); const innerValue = outerValue + 1; expect(cls.setContext(innerValue)) .withContext(`inner value (${innerValue}) not set`) .toBe(innerValue); debugId('setInterval: INNER END '); clearInterval(timer2); done(); }, 100); }, 100); }); it('calling fs should preserve continuation local storage', (done) => { debugId('fs: START BEGIN'); const startValue = 251; expect(cls.setContext(startValue)) .withContext(`start value (${startValue}) not set`) .toBe(startValue); debugId('fs: START END '); fs.access(__filename, () => { debugId('fs: OUTER BEGIN'); expect(cls.getContext()) .withContext(`outer value is not the expected start value (${startValue})`) .toBe(startValue); const outerValue = startValue + 1; expect(cls.setContext(outerValue)) .withContext(`outer value (${outerValue}) not set`) .toBe(outerValue); debugId('fs: OUTER END '); fs.access(__filename, () => { debugId('fs: INNER BEGIN'); expect(cls.getContext()) .withContext(`inner value is not the expected outer value (${outerValue})`) .toBe(outerValue); const innerValue = outerValue + 1; expect(cls.setContext(innerValue)) .withContext(`inner value (${innerValue}) not set`) .toBe(innerValue); debugId('fs: INNER END '); done(); }); }); }); // NOTES: // the executor function of the top most Promise is running synchronously // see: https://github.com/nodejs/node-eps/pull/18 // so the cls-context inside this executor function is the same as the // cls-context of the caller it('chained promises should preserve continuation local storage', () => { debugId('promise: START BEGIN'); const startValue = 261; let outerValue: number; let innerValue: number; let innermostValue: number; expect(cls.setContext(startValue)) .withContext(`start value (${startValue}) not set`) .toBe(startValue); debugId('promise: START END '); return new Promise<number>((resolve, reject) => { debugId('promise: OUTER BEGIN'); expect(cls.getContext()) .withContext(`outer value is not the expected start value (${startValue})`) .toBe(startValue); expect(cls.getContext()) .withContext(`outer value is not the expected start value (${startValue})`) .toBe(startValue); outerValue = startValue; debugId('promise: OUTER END '); resolve(outerValue); }) .then((val) => { debugId('promise: OUTER THEN'); return new Promise<number>((resolve, reject) => { debugId('promise: INNER BEGIN'); expect(cls.getContext()) .withContext(`inner value is not the expected outer value (${outerValue})`) .toBe(outerValue); innerValue = outerValue + 1; expect(cls.setContext(innerValue)) .withContext(`inner value (${innerValue}) not set`) .toBe(innerValue); debugId('promise: INNER END '); resolve(innerValue); }).then((val2) => { debugId('promise: INNER THEN'); return new Promise<number>((resolve, reject) => { debugId('promise: INNERMOST BEGIN'); expect(cls.getContext()) .withContext(`innermost value is not the expected inner value (${innerValue})`) .toBe(innerValue); innermostValue = innerValue + 1; expect(cls.setContext(innermostValue)) .withContext(`innermost value (${innermostValue}) not set`) .toBe(innermostValue); debugId('promise: INNERMOST END '); resolve(innermostValue); }); }); }) .then((val) => { return val; }) .catch((err) => { fail(err); }); }); it('promise returned from promise executor function should preserve continuation local storage', async () => { debugId('promise: START'); debugId('promise: START BEGIN'); const startValue = 271; let outerValue = 0; let innerValue = 0; cls.setContext(startValue); expect(cls.getContext()) .withContext(`start value (${startValue}) not set`) .toBe(startValue); await new Promise<number>((resolve1, reject1) => { debugId('promise: OUTER BEGIN'); expect(cls.getContext()) .withContext(`outer value is not the expected start value (${startValue})`) .toBe(startValue); cls.setContext(startValue + 1); outerValue = cls.getContext() as number; return new Promise<number>((resolve2, reject2) => { debugId('promise: INNER BEGIN'); expect(cls.getContext()) .withContext(`outer value is not the expected start value (${outerValue})`) .toBe(outerValue); cls.setContext(outerValue + 1); innerValue = cls.getContext() as number; resolve2(42); }).then(() => { resolve1(24); }); // <= resolving is requried }) .catch((err) => { fail(err); }) .then((val) => { return val; }); expect(cls.getContext()) .withContext(`start context value is not updated to inner value (${innerValue})`) .toBe(innerValue); }); });
the_stack
import { createHash } from 'crypto'; import * as Debug from 'debug'; import * as _ from 'lodash'; import * as redis from 'redis'; import * as traverse from 'traverse'; import { v4 as uuid } from 'uuid'; import { INohmPrefixes, NohmClass } from '.'; import { LinkError } from './errors/LinkError'; import { ValidationError } from './errors/ValidationError'; import * as messageComposers from './eventComposers'; import { callbackError, checkEqual } from './helpers'; import { idGenerators } from './idGenerators'; import { IChangeEventPayload, IDefaultEventPayload, IDictionary, ILinkOptions, ILinkSaveResult, IModelOptions, IModelPropertyDefinition, IModelPropertyDefinitions, IProperty, IPropertyDiff, IRelationChange, IRelationChangeEventPayload, ISaveOptions, ISearchOption, ISortOptions, IStructuredSearch, IUnlinkKeyMapItem, IValidationObject, IValidationResult, TLinkCallback, TValidationDefinition, ILinkOptionsWithName, } from './model.header'; import { del, exec, exists, get, hgetall, mset, sadd, scard, set, setnx, sinter, sismember, smembers, } from './typed-redis-helper'; import { validators } from './validators'; export { IDictionary, ILinkOptions, IModelPropertyDefinition, IModelPropertyDefinitions, IModelOptions, ISortOptions, TLinkCallback, }; export { NohmModel }; const debug = Debug('nohm:model'); const debugPubSub = Debug('nohm:pubSub'); /* * The property types that get indexed in a sorted set. * This should not be changed since it can invalidate already existing data. */ const indexNumberTypes = ['integer', 'float', 'timestamp']; export type TAllowedEventNames = | 'create' | 'save' | 'update' | 'remove' | 'link' | 'unlink'; const eventActions: Array<TAllowedEventNames> = [ 'create', 'update', 'save', 'remove', 'unlink', 'link', ]; const metaUpdating: Array<string> = []; /** * Redis client for this model * * @type {redis.RedisClient} * @name client * @memberof NohmModel# */ /** * Validation errors that were set during the last call to {@link NohmModel#validate}. (so also during save()) * * The type is an object with property names as keys and then an array with validation * names of the validations that failed * * @type { Object.<string, Array<string>> } * @name errors * @memberof NohmModel# */ /** * Name of the model, used for database keys and relation values * * @type {string} * @name modelName * @memberof NohmModel# */ /** * A nohm model class. * * @abstract * @class NohmModel */ abstract class NohmModel<TProps extends IDictionary = IDictionary> { /** * Redis client for this model * * @type {redis.RedisClient} */ public client: redis.RedisClient; public errors: { [key in keyof TProps]: Array<string> }; public meta: { inDb: boolean; properties: IModelPropertyDefinitions; version: string; }; public readonly modelName: string; protected properties: Map<keyof TProps, IProperty>; protected options: IModelOptions; protected publish: null | boolean = null; protected static readonly definitions: IModelPropertyDefinitions = {}; protected abstract nohmClass: NohmClass; private _id: null | string; private _isLoaded: boolean; private _isDirty: boolean; private allPropertiesCache: { [key in keyof TProps]: any } & { id: any }; private inDb: boolean; private tmpUniqueKeys: Array<string>; private relationChanges: Array<IRelationChange>; constructor() { this._initOptions(); if (!this.client) { throw new Error('No redis client defined before initializing models.'); } if (!this.meta.inDb) { this.updateMeta(this.options.metaCallback); } this.properties = new Map(); this.allPropertiesCache = { id: null, } as any; this.errors = {} as any; const definitions = this.getDefinitions(); const propKeys = Object.keys(definitions); debug(`Constructing model with these properties: %j`, propKeys); propKeys.forEach((key: keyof TProps) => { const definition = this.getDefinitions()[key]; let defaultValue = definition.defaultValue || 0; if (typeof defaultValue === 'function') { defaultValue = defaultValue(); } this.properties.set(key, { __numericIndex: false, __oldValue: null, __updated: false, value: undefined, }); if (typeof definition.type === 'function') { // behaviors should not be called on initialization - thus leaving it at defaultValue this.setProperty(key, defaultValue, true); } else { this.property(key, defaultValue); // this ensures typecasting } this.__resetProp(key); this.errors[key] = []; }); if (this.options.methods) { this.addMethods(this.options.methods); } if (this.options.publish) { this.publish = this.options.publish; } if (!this.options.idGenerator) { this.options.idGenerator = 'default'; } this.relationChanges = []; this.tmpUniqueKeys = []; this._id = null; this._isLoaded = false; this._isDirty = false; this.inDb = false; } private __resetProp(property: keyof TProps) { const tmp = this.getProperty(property); tmp.__updated = false; tmp.__oldValue = tmp.value; type genericFunction = (...args: Array<any>) => any; let type: string | genericFunction = this.getDefinitions()[property].type; if (typeof type !== 'string') { type = '__notIndexed__'; } tmp.__numericIndex = indexNumberTypes.indexOf(type) > -1; } private addMethods(methods?: { [name: string]: () => any }) { if (methods) { _.each(methods, (method, name) => { if (typeof (this as any)[name] !== 'undefined') { const errorForStack = new Error('Deprecation warning'); setTimeout(() => { // Timeout to make sure we have this.modelName. this function is called in constructor and thus // doesn't always have modelName yet console.warn( '\x1b[31m%s\x1b[0m', `WARNING: Overwriting existing property/method '${name}' in '${this.modelName}' because of method definition.`, ); console.warn( '\x1b[31m%s\x1b[0m', // tslint:disable-next-line:max-line-length `DEPRECATED: Overwriting built-in methods is deprecated. Please migrate them to a different name. Here's a stack to help identify the problem:`, errorForStack.stack, ); }, 1); (this as any)['_super_' + name] = (this as any)[name].bind(this); } debug(`Adding method to model: %s`, method); (this as any)[name] = method; }); } } private updateMeta(callback?: IModelOptions['metaCallback']) { // Check if we're already updating the meta version before setting the timeout. // Doing it multiple times is costly. This has the downside of potentially not updating the meta version // sometimes when the same model is registered in several nohm instances with different redis databases. // However that is a trade-off that seems okay for now. Statistically each redis database should receive the correct // meta version over some time. // TODO: investigate whether acquiring a lock in the db has enough merit in this case if (metaUpdating.includes(this.meta.version)) { return; } process.nextTick(async () => { // Defer execution to the next process tick. // Since we don't have the modelName in some cases in immediate execution this is required. // However it also has the added benefit of making meta updates decoupled from the calling operation. // Check if we're already updating the meta version again to make sure it didn't happen in the meantime if (metaUpdating.includes(this.meta.version)) { return; } metaUpdating.push(this.meta.version); const versionKey = this.rawPrefix().meta.version + this.modelName; const idGeneratorKey = this.rawPrefix().meta.idGenerator + this.modelName; const propertiesKey = this.rawPrefix().meta.properties + this.modelName; try { const dbVersion = await get(this.client, versionKey); if (this.meta.version !== dbVersion) { const properties = traverse(this.meta.properties).map((x) => { if (typeof x === 'function') { return String(x); } else { return x; } }); const generator = this.options.idGenerator || 'default'; debug( `Setting meta for model '%s' with version '%s' and idGenerator '%s' to %j.`, this.modelName, this.meta.version, generator, properties, ); await Promise.all([ set(this.client, idGeneratorKey, generator.toString()), set(this.client, propertiesKey, JSON.stringify(properties)), set(this.client, versionKey, this.meta.version), ]); } this.meta.inDb = true; const updatingIndex = metaUpdating.indexOf(this.meta.version); if (updatingIndex !== -1) { metaUpdating.splice(updatingIndex, 1); } if (typeof callback === 'function') { callback(null, this.meta.version); } } catch (err) { this.nohmClass.logError(err); if (typeof callback === 'function') { callback(err, this.meta.version); } } }); } /** * DO NOT OVERWRITE THIS; USED INTERNALLY * * @protected */ protected abstract _initOptions(): any; /** * Returns the a redis key prefix string (including the modelName but without trailing ':'!) * DO NOT OVERWRITE THIS; USED INTERNALLY * * @protected */ protected abstract prefix(prefix: keyof INohmPrefixes): string; /** * Returns an object with the redis key prefix strings (including the trailing ':') * DO NOT OVERWRITE THIS; USED INTERNALLY * * @protected */ protected abstract rawPrefix(): INohmPrefixes; protected generateMetaVersion(): string { const hash = createHash('sha1'); const idGenerator = this.options.idGenerator || 'default'; // '' + to make sure that when no definition is set, it doesn't cause an exception here. hash.update('' + JSON.stringify(this.getDefinitions())); hash.update('' + JSON.stringify(this.modelName)); hash.update(idGenerator.toString()); return hash.digest('hex'); } public p(keyOrValues: any, value?: any): any { console.warn( '\x1b[31m%s\x1b[0m', 'DEPRECATED: Usage of NohmModel.p() is deprecated, use NohmModel.property() instead.', ); return this.property(keyOrValues, value); } public prop(keyOrValues: any, value?: any): any { console.warn( '\x1b[31m%s\x1b[0m', 'DEPRECATED: Usage of NohmModel.prop() is deprecated, use NohmModel.property() instead.', ); return this.property(keyOrValues, value); } /** * Checks if key is a string, nothing else. Used as a type guard * * @private * @param {*} key * @returns {string} Name of a property */ private isPropertyKey(key: any): key is keyof TProps { return typeof key === 'string'; } public property<TProp extends keyof TProps>(key: TProp): TProps[TProp]; public property<TProp extends keyof TProps>( key: TProp, value: any, // tslint:disable-line:unified-signatures ): TProps[TProp]; public property( valuesObject: Partial<{ [key in keyof TProps]: any }>, ): Partial<{ [key in keyof TProps]: TProps[key] }>; /** * Read and write properties to the instance. * * @param {(string | PropertyObject)} keyOrValues Name of the property as string or an object where * the keys are the names and the values the new values * @param {*} [value] If changing a property and using the .property('string', value) call signature this is the value * @returns {(any)} Returns the property as set after type casting */ public property<TProp extends keyof TProps>( keyOrValues: keyof TProps | Partial<{ [key in keyof TProps]: any }>, value?: any, ): TProps[TProp] | Partial<{ [key in keyof TProps]: any }> { if (!this.isPropertyKey(keyOrValues)) { const obj: Partial<{ [key in keyof TProps]: any }> = {}; Object.keys(keyOrValues).forEach((key) => { obj[key] = this.property(key, keyOrValues[key]); }); return obj; } if (typeof value !== 'undefined') { debug(`Setting property '%s' to value %o`, keyOrValues, value); this.setProperty(keyOrValues, value); this.allPropertiesCache[keyOrValues] = this.property(keyOrValues); } const prop = this.getProperty(keyOrValues); let returnValue = prop.value; if (this.getDefinitions()[keyOrValues].type === 'json') { returnValue = JSON.parse(returnValue); } debug(`Returning property '%s' with value %o`, keyOrValues, returnValue); return returnValue; } private getProperty(key: keyof TProps) { const prop = this.properties.get(key); if (!prop) { throw new Error(`Invalid property key '${key}'.`); } return prop; } private setProperty(key: keyof TProps, value: any, skipCast = false): void { const prop = this.getProperty(key); if (prop.value !== value) { if (skipCast) { prop.value = value; this.allPropertiesCache[key] = value; } else { prop.value = this.castProperty(key, prop, value); } prop.__updated = prop.value !== prop.__oldValue; this.properties.set(key, prop); } } private castProperty(key: keyof TProps, prop: IProperty, newValue: any): any { const type = this.getDefinitions()[key].type; if (typeof type === 'undefined') { return newValue; } debug(`Casting property '%s' with type %o`, key, type); if (typeof type === 'function') { return type.call(this, String(newValue), key, String(prop.__oldValue)); } switch (type.toLowerCase()) { case 'boolean': case 'bool': return newValue === 'false' ? false : !!newValue; case 'string': return (!(newValue instanceof String) || newValue.toString() === '') && typeof newValue !== 'string' ? '' : newValue; case 'integer': case 'int': return isNaN(parseInt(newValue, 10)) ? 0 : parseInt(newValue, 10); case 'float': case 'number': return isNaN(parseFloat(newValue)) ? 0 : parseFloat(newValue); case 'date': case 'time': case 'timestamp': let castTimestamp: number; // make it a timestamp aka. milliseconds from 1970 if (isNaN(newValue) && typeof newValue === 'string') { let timezoneOffset: number; // see if there is a timezone specified in the string if (newValue.match(/Z$/)) { // UTC timezone in an ISO string (hopefully) timezoneOffset = 0; } else { const matches = newValue.match(/(\+|\-)([\d]{1,2})\:([\d]{2})$/); if (matches) { // +/- hours:minutes specified. // calculating offsets in minutes and removing the offset from the string since new Date() // can't handle those. const hours = parseInt(matches[2], 10); const minutes = parseInt(matches[3], 10); timezoneOffset = hours * 60 + minutes; if (matches[1] === '-') { timezoneOffset *= -1; } // make sure it is set in UTC here newValue = newValue.substring(0, newValue.length - matches[0].length) + 'Z'; } else { timezoneOffset = new Date(newValue).getTimezoneOffset(); } } castTimestamp = new Date(newValue).getTime() - timezoneOffset * 60 * 1000; } else { castTimestamp = parseInt(newValue, 10); } return castTimestamp.toString(); case 'json': if (typeof newValue === 'object') { return JSON.stringify(newValue); } else { try { // already is json, do nothing JSON.parse(newValue); return newValue; } catch (e) { return JSON.stringify(newValue); } } default: return newValue; } } /** * Returns an array of all the properties that have been changed since init/load/save. * * @example * user.propertyDiff('country') === * [{ * key: 'country', * before: 'GB', * after: 'AB' * }] */ public propertyDiff( key?: keyof TProps, ): Array<void | IPropertyDiff<keyof TProps>> { // TODO: determine if returning an array is really the best option if (key) { return [this.onePropertyDiff(key)]; } else { const diffResult: Array<IPropertyDiff<keyof TProps>> = []; for (const [iterationKey] of this.properties) { const diff = this.onePropertyDiff(iterationKey); if (diff) { diffResult.push(diff); } } return diffResult; } } private onePropertyDiff(key: keyof TProps): IPropertyDiff | void { const prop = this.getProperty(key); if (prop.__updated) { return { after: prop.value, before: prop.__oldValue, key, }; } } /** * Resets a property to its state as it was at last init/load/save. * * @param {string} [key] If given only this key is reset */ public propertyReset(key?: keyof TProps): void { if (key && !this.properties.has(key)) { throw new Error('Invalid key specified for propertyReset'); } debug(`Resetting property '%s' (all if empty).`, key); this.properties.forEach((prop: IProperty, innerKey: keyof TProps) => { if (!key || innerKey === key) { prop.__updated = false; prop.value = prop.__oldValue; this.properties.set(innerKey, prop); this.allPropertiesCache[innerKey] = prop.__oldValue; } }); } /** * Get all properties with values either as an array or as json (param true). */ public allProperties(): TProps & { id: any } { // tslint:disable-next-line:prefer-object-spread // ts complains when using spread method here return Object.assign({}, this.allPropertiesCache); } /** * Save an instance to the database. Updating or Creating as needed depending on if the instance already has an id. * * @param {ISaveOptions} [options={ * silent: false, * skip_validation_and_unique_indexes: false, * }] * @returns {Promise<void>} */ public async save(options?: ISaveOptions): Promise<void> { // TODO for v2.1: instead of the old continue_on_link_error behavior, we should // add a way to deepValidate before saving. Meaning all relationChanges (only link) // get validated and if one of them is not valid, we abort before starting the save callbackError(...arguments); options = { silent: false, skip_validation_and_unique_indexes: false, ...options, }; let action: 'update' | 'create' = 'update'; if (!this.id) { action = 'create'; // create and set a unique temporary id // TODO: determine if this is still needed or can be solved more elegantly. // for example just ditching manual id creation and use uuid everywhere. // that would also make clustered/sharded storage much more straight forward // and remove a bit of code here. this.id = uuid(); } debug( `Saving instance '%s.%s' with action '%s'.`, this.modelName, this.id, action, ); let isValid = true; if (options.skip_validation_and_unique_indexes === false) { isValid = await this.validate(undefined, true); if (!isValid) { if (action === 'create') { // remove temp id this.id = null; } throw new ValidationError(this.errors, this.modelName); } } let numIdExisting: number = 0; if (action !== 'create') { numIdExisting = await sismember( this.client, this.prefix('idsets'), this.id, ); } if (action === 'create' && numIdExisting === 0) { debug( `Creating new instance '%s.%s' because action was '%s' and numIdExisting was %d.`, this.modelName, this.id, action, numIdExisting, ); await this.create(); this.inDb = false; } else { this.inDb = true; // allows for some optimizations during .update() } await this.update(options); // TODO: maybe implement some kind of locking mechanism so that an object is not being changed during save. this.inDb = true; this._isDirty = false; this._isLoaded = true; } private async create() { const id = await this.generateId(); await sadd(this.client, this.prefix('idsets'), id); await this.setUniqueIds(id); this.id = id; } private async generateId(): Promise<string> { let id: null | string = null; let generator = this.options.idGenerator; if (typeof generator === 'function') { id = await generator.call(this); } else { if (!generator || !idGenerators[generator]) { generator = 'default'; } id = await idGenerators[generator].call( idGenerators, this.client, this.prefix('incrementalIds'), ); } if (typeof id !== 'string') { id = String(id); } if (id.includes(':')) { // we need to do stuff with redis keys and we separate parts of the redis key by : // thus the id cannot contain that character. throw new Error( 'Nohm IDs cannot contain the character ":". Please change your idGenerator!', ); } return id; } /** * Sets the unique ids of all unique property values in this instance to the given id. * Warning: Only use this during create() when overwriting temporary ids! */ private async setUniqueIds(id: string): Promise<void> { const mSetArguments: Array<string> = []; for (const [key, prop] of this.properties) { const isUnique = !!this.getDefinitions()[key].unique; const isEmptyString = prop.value === ''; // marking an empty string as unique is probably never wanted const isDirty = prop.__updated || !this.inDb; if (isUnique && !isEmptyString && isDirty) { let value = this.property(key); if (this.getDefinitions()[key].type === 'string') { value = value.toLowerCase(); } const prefix = this.prefix('unique'); mSetArguments.push(`${prefix}:${key}:${value}`, id); } } if (mSetArguments.length !== 0) { debug( `Setting all unique indices of model '%s.%s' to new id '%s'.`, this.modelName, this.id, id, ); return mset(this.client, mSetArguments); } } private async update( options: ISaveOptions, ): Promise<Array<ILinkSaveResult> | LinkError> { if (!this.id) { throw new Error('Update was called without having an id set.'); } const hmSetArguments: Array<string> = []; const client = this.client.multi(); const isCreate = !this.inDb; hmSetArguments.push(`${this.prefix('hash')}:${this.id}`); for (const [key, prop] of this.properties) { if (isCreate || prop.__updated) { hmSetArguments.push(key, prop.value); } } if (hmSetArguments.length > 1) { hmSetArguments.push('__meta_version', this.meta.version); client.hmset.apply(client, hmSetArguments); } await this.setIndices(client); await exec(client); const linkResults = await this.storeLinks(options); this.relationChanges = []; const linkFailures = linkResults.filter( (linkResult) => !linkResult.success, ); if (linkFailures.length > 0) { throw new LinkError(linkFailures); } let diff; if (this.getPublish()) { // don't need the diff otherwise diff = this.propertyDiff(); } for (const [key] of this.properties) { this.__resetProp(key); } if (!options.silent) { if (isCreate) { this.fireEvent('create'); } else { this.fireEvent('update', diff); } this.fireEvent('save', diff); } return linkResults; } private async storeLinks( options: ISaveOptions, ): Promise<Array<ILinkSaveResult>> { const changeFns = this.relationChanges.map((change) => { return async () => { // TODO: decide whether silent should actually be overwritten for all cases change.options.silent = options.silent; let returnArray: Array<ILinkSaveResult> = []; const saveResult: ILinkSaveResult = { child: change.object, error: null, parent: this, success: true, }; try { if (!change.object.id) { debug( `Saving %sed '%s' instance from '%s.%s' with relation '%s' because it had no id.`, change.action, change.object.modelName, this.modelName, this.id, change.options.name, ); await change.object.save(options); } await this.saveLinkRedis(change); try { if (typeof change.callback === 'function') { change.callback.call( this, change.action, this.modelName, change.options.name, change.object, ); } } catch (e) { // ignore errors thrown by link callback } } catch (err) { const isSubLinkError = err instanceof LinkError; if (!isSubLinkError && typeof change.options.error === 'function') { try { change.options.error(err, change.object); } catch (e) { // ignore errors thrown by link callback } } if (isSubLinkError) { returnArray = returnArray.concat(err.errors); } else { saveResult.success = false; saveResult.error = err; } } returnArray.push(saveResult); return returnArray; }; }); let saveResults: Array<ILinkSaveResult> = []; // Sequentially go through all the changes and store them instead of parallel. // The reason for this behavior is that it makes saving other objects when they don't have an id yet // easier and cannot cause race-conditions as easily. for (const [, fn] of changeFns.entries()) { saveResults = saveResults.concat(await fn()); } return saveResults; } private getRelationKey(otherName: string, relationName: string) { return `${this.prefix('relations')}:${relationName}:${otherName}:${ this.id }`; } private async saveLinkRedis(change: IRelationChange): Promise<void> { const foreignName = `${change.options.name}Foreign`; const command = change.action === 'link' ? 'sadd' : 'srem'; const relationKeyPrefix = this.rawPrefix().relationKeys; const multi = this.client.multi(); // relation to other const toKey = this.getRelationKey( change.object.modelName, change.options.name, ); // first store the information to which other model names the instance has a relation to multi[command](`${relationKeyPrefix}${this.modelName}:${this.id}`, toKey); // second store the information which specific other model id that relation is referring to multi[command](toKey, change.object.stringId()); // relation from other - same thing in reverse const fromKey = change.object.getRelationKey(this.modelName, foreignName); multi[command]( `${relationKeyPrefix}${change.object.modelName}:${change.object.id}`, fromKey, ); multi[command](fromKey, this.stringId()); try { debug(`Linking in redis.`, this.modelName, change.options.name, command); await exec(multi); if (!change.options.silent) { this.fireEvent(change.action, change.object, change.options.name); } } catch (err) { if (change.options.error) { change.options.error(err, change.object); } throw err; } } private async setIndices( multi: redis.Multi | redis.RedisClient, ): Promise<void> { let oldValues: Partial<TProps> = {}; try { if (this.inDb) { oldValues = await this.getHashAll(this.id); } } catch (e) { if (e.message !== 'not found') { throw e; } // else { not found just means no old values and it stays {} } } for (const [key, prop] of this.properties) { const isUnique = !!this.getDefinitions()[key].unique; const isIndex = !!this.getDefinitions()[key].index; const isInDb = oldValues[key] !== undefined; const isDirty = prop.value !== oldValues[key]; const oldValue = oldValues[key]; // free old uniques if (isUnique && isDirty && isInDb) { let oldUniqueValue = oldValue; if (this.getDefinitions()[key].type === 'string') { oldUniqueValue = oldUniqueValue.toLowerCase(); } debug( `Removing old unique '%s' from '%s.%s' because propUpdated: %o && this.inDb %o.`, key, this.modelName, this.id, prop.__updated, this.inDb, ); multi.del( `${this.prefix('unique')}:${key}:${oldUniqueValue}`, this.nohmClass.logError, ); } // set new normal index if (isIndex && isDirty) { if (prop.__numericIndex) { debug( `Adding numeric index '%s' to '%s.%s'.`, key, this.modelName, this.id, prop.__updated, ); // we use scored sets for things like "get all users older than 5" const scoredPrefix = this.prefix('scoredindex'); multi.zadd( `${scoredPrefix}:${key}`, prop.value, this.stringId(), this.nohmClass.logError, ); } debug( `Adding index '%s' to '%s.%s'; isInDb: '%s'; newValue: '%s'; oldValue: '%s'.`, key, this.modelName, this.stringId(), isInDb, prop.value, oldValue, ); const prefix = this.prefix('index'); if (isInDb) { multi.srem( `${prefix}:${key}:${oldValue}`, this.stringId(), this.nohmClass.logError, ); } multi.sadd( `${prefix}:${key}:${prop.value}`, this.stringId(), this.nohmClass.logError, ); } } } public valid(property?: keyof TProps, setDirectly = false): Promise<boolean> { console.warn( '\x1b[31m%s\x1b[0m', 'DEPRECATED: Usage of NohmModel.valid() is deprecated, use NohmModel.validate() instead.', ); return this.validate(property, setDirectly); } /** * Check if one or all properties are valid and optionally set the unique indices immediately. * If a property is invalid the {@link NohmModel#errors} object will be populated with error messages. * * @param {string} [property] Property name if you only want to check one property for validity or * null for all properties * @param {boolean} [setDirectly=false] Set to true to immediately set the unique indices while checking. * This prevents race conditions but should probably only be used internally * @returns {Promise<boolean>} Promise resolves to true if checked properties are valid. */ public async validate( property?: keyof TProps, setDirectly = false, ): Promise<boolean> { callbackError(...arguments); const nonUniqueValidations: Array<Promise<IValidationResult>> = []; for (const [key, prop] of this.properties) { if (!property || property === key) { this.errors[key] = []; nonUniqueValidations.push(this.validateProperty(key, prop)); } } let validationResults: Array<IValidationResult> = await Promise.all< IValidationResult >(nonUniqueValidations); let valid = validationResults.some((result) => result.valid); if (!valid) { // if nonUniqueValidations failed, we don't want to set uniques while checking them setDirectly = false; } const uniqueValidations: Array<Promise<IValidationResult>> = []; for (const [key, prop] of this.properties) { if (!property || property === key) { uniqueValidations.push(this.checkUniques(setDirectly, key, prop)); } } const uniqueValidationResults = await Promise.all<IValidationResult>( uniqueValidations, ); validationResults = validationResults.concat(uniqueValidationResults); validationResults.forEach((result) => { if (!this.errors[result.key]) { this.errors[result.key] = []; } if (!result.valid) { valid = false; if (!result.errors || result.errors.length === 0) { throw new Error( `Validation failed but didn't provide an error message. Property name: ${result.key}.`, ); } this.errors[result.key] = this.errors[result.key].concat(result.errors); } }); if (setDirectly && valid === false) { await this.clearTemporaryUniques(); } return valid; } private async validateProperty( key: string, property: IProperty, ): Promise<IValidationResult> { const result: IValidationResult = { key, valid: true, }; const validations = this.getDefinitions()[key].validations; if (validations) { const validatorOptions = { old: property.__oldValue, optional: false, trim: true, }; const validationObjects = validations.map((validator) => this.getValidationObject(validator, key), ); const validationPromises: Array<Promise<void>> = validationObjects.map( async (validationObject) => { if (validationObject.options.optional && !property.value) { return; } const valid = await validationObject.validator.call( this, property.value, { ...validatorOptions, ...validationObject.options, }, ); if (!valid) { result.valid = false; if (!result.errors) { result.errors = []; } result.errors.push(validationObject.name); } }, ); await Promise.all(validationPromises); } return result; } private getValidationObject( validator: TValidationDefinition, key: keyof TProps, ): IValidationObject { if (typeof validator === 'function') { const funcName = validator.name || key; return { name: `custom_${funcName}`, options: {}, validator, }; } else { if (typeof validator === 'string') { // predefined validator method return { name: validator, options: {}, validator: validators[validator], }; } else if (validator && validator.name) { // predefined validator method with options return { name: validator.name, options: validator.options, validator: validators[validator.name], }; } else { throw new Error( `Bad validation definition for model '${this.modelName}' for validator '${validator}'.`, ); } } } private isUpdatedUnique(key: keyof TProps, property: IProperty): boolean { const definition = this.getDefinitions()[key]; if (!definition || !definition.unique) { return false; } if (property.value === '') { return false; // empty string is not valid unique value } if (!property.__updated && this.inDb) { // neither updated nor new return false; } return true; } private async isUniqueKeyFree( key: string, setDirectly: boolean, ): Promise<boolean> { let dbValue: number; if (setDirectly) { /* * We lock the unique value here if it's not locked yet, then later remove the old unique lock * when really saving it. (or we free the unique slot if we're not saving) */ dbValue = await setnx(this.client, key, this.stringId()); } else { dbValue = await exists(this.client, key); } let isFreeUnique = false; if (setDirectly && dbValue === 1) { // setDirectly === true means using setnx which returns 1 if the value did *not* exist isFreeUnique = true; this.tmpUniqueKeys.push(key); } else if (!setDirectly && dbValue === 0) { // setDirectly === false means using exists which returns 0 if the value did *not* exist isFreeUnique = true; } else if (setDirectly && dbValue === 0) { // setDirectly === true means using setnx which returns 1 if the value did *not* exist // if it did exist, we check if the unique is the same as the one on this model. // see https://github.com/maritz/nohm/issues/82 for use-case const dbId = await get(this.client, key); if (dbId === this.stringId()) { isFreeUnique = true; } } debug( `Checked unique '%s' for '%s.%s'. Result: '%s' because setDirectly: '%o' && dbValue: '%d'.`, key, this.modelName, this.id, isFreeUnique, setDirectly, dbValue, ); return isFreeUnique; } private getUniqueKey(key: keyof TProps, property: IProperty): string { let uniqueValue = property.value; if (this.getDefinitions()[key].type === 'string') { uniqueValue = String.prototype.toLowerCase.call(property.value); } return `${this.prefix('unique')}:${key}:${uniqueValue}`; } private async checkUniques( setDirectly: boolean, key: keyof TProps, property: IProperty, ): Promise<IValidationResult> { const successReturn = { key, valid: true, }; const isUpdatedUnique = this.isUpdatedUnique(key, property); if (!isUpdatedUnique) { return successReturn; } const uniqueKey = this.getUniqueKey(key, property); debug( `Checking unique '%s' for '%s.%s' at '%s'.`, key, this.modelName, this.id, uniqueKey, ); const isFree = await this.isUniqueKeyFree(uniqueKey, setDirectly); if (!isFree) { return { errors: ['notUnique'], key, valid: false, }; } return successReturn; } /** * Used after a failed validation with setDirectly=true to remove the temporary unique keys * * @private * @param {string} key * @param {IProperty} property * @returns {Promise<void>} */ private async clearTemporaryUniques(): Promise<void> { if (this.tmpUniqueKeys.length > 0) { debug( `Clearing temp uniques '%o' for '%s.%s'.`, this.tmpUniqueKeys, this.modelName, this.id, ); const deletes: Array<Promise<void>> = this.tmpUniqueKeys.map((key) => { return del(this.client, key); }); await Promise.all(deletes); } } /** * Remove an object from the database. * Note: Does not destroy the js object or its properties itself! * * @param {boolean} [silent=false] Fire PubSub events or not * @returns {Promise<void>} */ public async remove(silent = false): Promise<void> { callbackError(...arguments); if (!this.id) { throw new Error('The instance you are trying to delete has no id.'); } if (!this.inDb) { // make sure we have the db uniques/indices await this.load(this.id); } debug(`Removing '%s.%s'.`, this.modelName, this.id); await this.deleteDbCall(); const oldId = this.id; this.id = null; if (!silent) { this.fireEvent('remove', oldId); } } private async deleteDbCall(): Promise<void> { // TODO: write test for removal of relationKeys - purgeDb kinda tests it already, but not enough const multi = this.client.multi(); multi.del(`${this.prefix('hash')}:${this.stringId()}`); multi.srem(this.prefix('idsets'), this.stringId()); this.properties.forEach((prop, key) => { if (this.getDefinitions()[key].unique) { let value = prop.__oldValue; if (this.getDefinitions()[key].type === 'string') { value = String(value).toLowerCase(); } multi.del(`${this.prefix('unique')}:${key}:${value}`); } if (this.getDefinitions()[key].index === true) { multi.srem( `${this.prefix('index')}:${key}:${prop.__oldValue}`, this.stringId(), ); } if (prop.__numericIndex === true) { multi.zrem(`${this.prefix('scoredindex')}:${key}`, this.stringId()); } }); await this.unlinkAll(multi); await exec(multi); } /** * Returns a Promise that resolves to true if the given id exists for this model. * * @param {*} id * @returns {Promise<boolean>} */ public async exists(id: any): Promise<boolean> { callbackError(...arguments); return !!(await sismember(this.client, this.prefix('idsets'), id)); } private async getHashAll(id: any): Promise<Partial<TProps>> { const props: Partial<TProps> = {}; const values = await hgetall(this.client, `${this.prefix('hash')}:${id}`); if (values === null || Object.keys(values).length === 0) { throw new Error('not found'); } Object.keys(values).forEach((key) => { if (key === '__meta_version') { return; } if (!this.getDefinitions()[key]) { this.nohmClass.logError( // tslint:disable-next-line:max-line-length `A hash in the DB contained a key '${key}' that is not in the model definition. This might be because of model changes or database corruption/intrusion.`, ); return; } props[key] = values[key]; }); return props; } /** * Loads the record from the database. * * @param {*} id * @returns {Object} Resolves with the return of {@link NohmModel.allProperties} * of {@link NohmModel.allProperties} after loading * @throws {Error('not found')} If no record exists of the given id, * an error is thrown with the message 'not found' * @memberof NohmModel */ public async load(id: any): Promise<TProps & { id: any }> { callbackError(...arguments); if (!id) { throw new Error('No id passed to .load().'); } debug(`Loading '%s.%s' at '%s'.`, this.modelName, id); const dbProps = await this.getHashAll(id); const definitions = this.getDefinitions(); Object.keys(dbProps).forEach((key) => { if (definitions[key].load_pure) { // prevents type casting/behavior. especially useful for create-only properties like a createdAt timestamp debug( `Loading property '%s' from '%s.%s' as pure (no type casting).`, key, this.modelName, id, ); this.setProperty(key, dbProps[key], true); } else { this.property(key, dbProps[key]); } this.__resetProp(key); }); this.id = id; this.inDb = true; this._isDirty = false; this._isLoaded = true; return this.allProperties(); } public link<T extends NohmModel>(other: T, callback?: TLinkCallback<T>): void; public link<T extends NohmModel>( other: NohmModel, optionsOrNameOrCallback: string | ILinkOptions, callback?: TLinkCallback<T>, ): void; /** * Links one object to another. * Does not save the link directly but marks it for the next .save() call. * When linking an instance that has not been saved that instance will then be saved during the .save() call * on this instance. * * Note: link names should not end with 'Foreign' as that is an internally used identifier. * * @example * const user = new UserModel(); * const comment = new CommentModel(); * await user.load(123); * user.linK(comment, 'author'); * await user.save(); // this will save the link to the database and also call .save() on comment * * @example * // options object typing: * { * error?: (err: Error | string, otherName: string, otherObject: NohmModel) => any; * name: string; * silent?: boolean; * } * * @param {NohmModel} other The other instance that is being linked * @param {(string | ILinkOptions | function)} [optionsOrNameOrCallback] Either a string for the * relation name (default: 'default') or an options object (see example above) or the callback * @param {function} [callback] Function that is called when the link is saved. */ public link<T extends NohmModel>( other: NohmModel, optionsOrNameOrCallback?: string | ILinkOptions | TLinkCallback<T>, callback?: TLinkCallback<T>, ): void { if (typeof optionsOrNameOrCallback === 'function') { callback = optionsOrNameOrCallback; optionsOrNameOrCallback = 'default'; } else if (typeof optionsOrNameOrCallback === 'undefined') { optionsOrNameOrCallback = 'default'; } const options = this.getLinkOptions(optionsOrNameOrCallback); this.relationChanges.push({ action: 'link', callback, object: other, options, }); debug( `Set link for '%s.%s': %o`, this.modelName, this.id, this.relationChanges[this.relationChanges.length - 1], ); } public unlink<T extends NohmModel>( other: T, callback?: TLinkCallback<T>, ): void; public unlink<T extends NohmModel>( other: NohmModel, optionsOrNameOrCallback: string | ILinkOptions, callback?: TLinkCallback<T>, ): void; /** * Unlinks one object to another. * Does not remove the link directly but marks it for the next .save() call. * * @example * // options object typing: * { * error?: (err: Error | string, otherName: string, otherObject: NohmModel) => any; * name: string; * silent?: boolean; * } * * @param {NohmModel} other The other instance that is being unlinked (needs to have an id) * @param {(string | ILinkOptions | function)} [optionsOrNameOrCallback] Either a string for the * relation name (default: 'default') or an options object (see example above) or the callback * @param {function} [callback] */ public unlink<T extends NohmModel>( other: NohmModel, optionsOrNameOrCallback?: string | ILinkOptions | TLinkCallback<T>, callback?: TLinkCallback<T>, ): void { if (typeof optionsOrNameOrCallback === 'function') { callback = optionsOrNameOrCallback; optionsOrNameOrCallback = 'default'; } else if (typeof optionsOrNameOrCallback === 'undefined') { optionsOrNameOrCallback = 'default'; } const options = this.getLinkOptions(optionsOrNameOrCallback); this.relationChanges.forEach((change, key) => { const sameRelationChange = change.options.name === options.name && checkEqual(change.object, other); if (sameRelationChange) { this.relationChanges.splice(key, 1); } }); this.relationChanges.push({ action: 'unlink', callback, object: other, options, }); debug( `Set unlink for '%s.%s': %o`, this.modelName, this.id, this.relationChanges[this.relationChanges.length - 1], ); } private getLinkOptions( optionsOrName: string | ILinkOptions, ): ILinkOptionsWithName { if (typeof optionsOrName === 'string') { return { name: optionsOrName, }; } else { return { name: 'default', ...optionsOrName, }; } } private isMultiClient(client: any): client is redis.Multi { return client && typeof client.exec === 'function'; } /** * Unlinks all relations a record has to all other models. * * @param {(redis.RedisClient | redis.Multi)} [givenClient] * @returns {Promise<void>} * @memberof NohmModel */ public async unlinkAll( givenClient?: redis.RedisClient | redis.Multi, ): Promise<void> { callbackError(...arguments); let multi: redis.Multi; if (this.isMultiClient(givenClient)) { multi = givenClient; } else if (givenClient) { multi = givenClient.multi(); } else { multi = this.client.multi(); } // remove outstanding relation changes this.relationChanges = []; const relationKeysKey = `${this.rawPrefix().relationKeys}${ this.modelName }:${this.id}`; const keys = await smembers(this.client, relationKeysKey); debug(`Removing links for '%s.%s': %o.`, this.modelName, this.id, keys); const others: Array<IUnlinkKeyMapItem> = keys.map((key) => { const matches = key.match(/:([\w]*):([\w]*):[^:]+$/i); if (!matches) { throw new Error('Malformed relation key found in the database! ' + key); } // selfName is the name of the relation as it is on this instance const selfRelationName = matches[1]; const otherModelName = matches[2]; const namedMatches = matches[1].match(/^([\w]*)Foreign$/); const otherRelationName = namedMatches ? namedMatches[1] : matches[1] + 'Foreign'; return { otherIdsKey: `${ this.rawPrefix().relations }${otherModelName}:${otherRelationName}:${this.modelName}:`, ownIdsKey: `${this.prefix( 'relations', )}:${selfRelationName}:${otherModelName}:${this.id}`, }; }); const otherRelationIdsPromises = others.map((item) => this.removeIdFromOtherRelations(multi, item), ); await Promise.all(otherRelationIdsPromises); // add multi'ed delete commands for other keys others.forEach((item) => multi.del(item.ownIdsKey)); multi.del(relationKeysKey); // if we didn't get a multi client from the callee we have to exec() ourselves if (!this.isMultiClient(givenClient)) { await exec(multi); } } /* This method is doubly asynchronous: First it returns a promise that gets resolved when the ids have been fetched that need to be used as keys for removing this.id from relations to others. Secondly it adds an SREM to the multi redis client. */ private async removeIdFromOtherRelations( multi: redis.Multi, item: IUnlinkKeyMapItem, ): Promise<void> { const ids = await smembers(this.client, item.ownIdsKey); ids.forEach((id) => { multi.srem(`${item.otherIdsKey}${id}`, this.stringId()); }); } /** * Resolves with true if the given object has a relation (optionally with the given relation name) to this. * * @param {NohmModel} obj * @param {string} [relationName='default'] * @returns {Promise<boolean>} */ public async belongsTo( obj: NohmModel, relationName = 'default', ): Promise<boolean> { callbackError(...arguments); if (!this.id || !obj.id) { throw new Error( 'Calling belongsTo() even though either the object itself or the relation does not have an id.', ); } return !!(await sismember( this.client, this.getRelationKey(obj.modelName, relationName), obj.id, )); } /** * Returns an array of the ids of all objects that are linked with the given relation. * * @param {string} otherModelName * @param {string} [relationName='default'] * @returns {Promise<Array<any>>} */ public async getAll( otherModelName: string, relationName = 'default', ): Promise<Array<any>> { if (!this.id) { throw new Error( `Calling getAll() even though this ${this.modelName} has no id. Please load or save it first.`, ); } const relationKey = this.getRelationKey(otherModelName, relationName); const ids = await smembers(this.client, relationKey); if (!Array.isArray(ids)) { return []; } else { return ids; } } /** * Returns the number of links of a specified relation (or the default) an instance has to * models of a given modelName. * * @param {string} otherModelName Name of the model on the other end of the relation. * @param {string} [relationName='default'] Name of the relation * @returns {Promise<number>} */ public async numLinks( otherModelName: string, relationName = 'default', ): Promise<number> { callbackError(...arguments); if (!this.id) { throw new Error( `Calling numLinks() even though this ${this.modelName} has no id. Please load or save it first.`, ); } const relationKey = this.getRelationKey(otherModelName, relationName); return scard(this.client, relationKey); } /** * Finds ids of objects by search arguments * * @see https://maritz.github.io/nohm/#finding * @param {ISearchOptions} searches * @returns {Promise<Array<any>>} */ public async find( searches: Partial< { [key in keyof TProps]: | string | number | boolean | Partial<ISearchOption>; } > = {}, ): Promise<Array<string>> { const structuredSearches = this.createStructuredSearchOptions(searches); const uniqueSearch = structuredSearches.find( (search) => search.type === 'unique', ); if (uniqueSearch) { debug( `Finding '%s's with uniques:\n%o.`, this.modelName, this.id, uniqueSearch, ); return this.uniqueSearch(uniqueSearch); } const onlySets = structuredSearches.filter( (search) => search.type === 'set', ); const onlyZSets = structuredSearches.filter( (search) => search.type === 'zset', ); if (onlySets.length === 0 && onlyZSets.length === 0) { // no valid searches - return all ids return smembers(this.client, `${this.prefix('idsets')}`); } debug( `Finding '%s's with these searches (sets, zsets):\n%o,\n%o.`, this.modelName, this.id, onlySets, onlyZSets, ); const setPromises = this.setSearch(onlySets); const zSetPromises = this.zSetSearch(onlyZSets); const searchResults = await Promise.all([setPromises, zSetPromises]); if (onlySets.length !== 0 && onlyZSets.length !== 0) { // both searches - form intersection of them const intersection = _.intersection(searchResults[0], searchResults[1]); return intersection; } else { // only one form of search if (onlySets.length !== 0) { return searchResults[0]; } else { return searchResults[1]; } } } private createStructuredSearchOptions( searches: Partial< { [key in keyof TProps]: | string | number | boolean | Partial<ISearchOption>; } >, ): Array<IStructuredSearch<TProps>> { return Object.keys(searches).map((key) => { const search = searches[key]; if (typeof search === 'undefined') { throw new Error('Invalid find() options.'); // this shouldn't occur } const prop = this.getProperty(key); const definition = this.getDefinitions()[key]; const structuredSearch: IStructuredSearch<TProps> = { key, options: {}, type: 'undefined', value: search, }; if (definition.unique) { if (definition.type === 'string') { if (typeof search !== 'string') { throw new Error( // tslint:disable-next-line:max-line-length 'Invalid search parameters: Searching for a unique (type "string") with a non-string value is not supported.', ); } structuredSearch.value = search.toLowerCase(); } structuredSearch.type = 'unique'; } else { if (!prop.__numericIndex && !definition.index) { throw new Error( `Trying to search for non-indexed and non-unique property '${key}' is not supported.`, ); } const isDirectNumericSearch = !isNaN(parseInt(search as string, 10)); const isSimpleIndexSearch = !prop.__numericIndex || isDirectNumericSearch; if (!isSimpleIndexSearch && prop.__numericIndex) { structuredSearch.type = 'zset'; structuredSearch.options = search as Partial<ISearchOption>; } else if (definition.index === true) { structuredSearch.type = 'set'; } } return structuredSearch; }); } private async uniqueSearch( options: IStructuredSearch<TProps>, ): Promise<Array<string>> { const key = `${this.prefix('unique')}:${options.key}:${options.value}`; const id = await get(this.client, key); if (id) { return [id]; } else { return []; } } private async setSearch( searches: Array<IStructuredSearch<TProps>>, ): Promise<Array<string>> { const keys = searches.map((search) => { return `${this.prefix('index')}:${search.key}:${search.value}`; }); if (keys.length === 0) { // shortcut return []; } return sinter(this.client, keys); } private async zSetSearch( searches: Array<IStructuredSearch<TProps>>, ): Promise<Array<string>> { const singleSearches = await Promise.all( searches.map((search) => this.singleZSetSearch(search)), ); return _.intersection(...singleSearches); } private singleZSetSearch( search: IStructuredSearch<TProps>, ): Promise<Array<string>> { return new Promise((resolve, reject) => { const key = `${this.prefix('scoredindex')}:${search.key}`; let command: 'zrangebyscore' | 'zrevrangebyscore' = 'zrangebyscore'; const options: ISearchOption = { endpoints: '[]', limit: -1, max: '+inf', min: '-inf', offset: 0, ...search.options, }; if ( (options.min === '+inf' && options.max !== '+inf') || (options.max === '-inf' && options.min !== '-inf') || parseFloat('' + options.min) > parseFloat('' + options.max) ) { command = 'zrevrangebyscore'; } if (options.endpoints === ')') { options.endpoints = '[)'; } const endpoints = [ options.endpoints[0] === '(' ? '(' : '', options.endpoints[1] === ')' ? '(' : '', ]; const callback = (err: Error | null, ids: Array<string>) => { if (err) { reject(err); } else { resolve(ids); } }; if (options.limit) { this.client[command]( key, endpoints[0] + options.min, endpoints[1] + options.max, 'LIMIT', options.offset, options.limit, callback, ); } else { this.client[command]( key, endpoints[0] + options.min, endpoints[1] + options.max, callback, ); } }); } /** * Sort records by some criteria and return the sorted ids. * * @see https://maritz.github.io/nohm/#sorting * @param {Object} [options={}] * @param {(Array<string> | false)} [ids=false] * @returns {Promise<Array<string>>} */ public async sort( options: ISortOptions<TProps> = {}, ids: Array<string | number> | false = false, ): Promise<Array<string>> { callbackError(...arguments); if (!Array.isArray(ids)) { ids = false; } if (ids && ids.length === 0) { return []; } if (Array.isArray(ids) && options === {}) { return ids.map((id) => String(id)).sort(); } if (!options.field || !this.properties.has(options.field)) { throw new Error( `Invalid field in ${this.modelName}.sort() options: '${options.field}'`, ); } const fieldType = this.getDefinitions()[options.field].type; const isIndexed = this.getDefinitions()[options.field].index; const alpha = options.alpha || (fieldType === 'string' ? 'ALPHA' : undefined); const direction = options.direction ? options.direction : 'ASC'; const scored = typeof fieldType === 'string' && isIndexed ? indexNumberTypes.includes(fieldType) : false; let start = 0; let stop = 100; if (Array.isArray(options.limit) && options.limit.length > 0) { start = options.limit[0]; if (scored) { // the limit arguments for sets and sorted sets work differently // stop is a 0-based index from the start of all zset members stop = options.limit[1] ? start + options.limit[1] : start + stop; stop--; } else { // stop is a 1-based index from the defined start limit (the wanted behavior) stop = options.limit[1] || stop; } } let idsetKey = this.prefix('idsets'); let zsetKey = `${this.prefix('scoredindex')}:${options.field}`; const client: redis.Multi = this.client.multi(); let tmpKey: string = ''; debug( `Sorting '%s's with these options (this.id, alpha, direction, scored, start, stop, ids):`, this.modelName, this.id, alpha, direction, scored, start, stop, ids, ); if (ids) { // to get the intersection of the given ids and all ids on the server we first // temporarily store the given ids either in a set or sorted set and then return the intersection if (scored) { tmpKey = zsetKey + ':tmp_sort:' + +new Date() + Math.ceil(Math.random() * 1000); const tempZaddArgs = [tmpKey]; ids.forEach((id) => { tempZaddArgs.push('0', id as string); }); // typecast because redis doesn't care about numbers/string client.zadd.apply(client, tempZaddArgs); client.zinterstore([tmpKey, 2, tmpKey, zsetKey]); zsetKey = tmpKey; } else { tmpKey = idsetKey + ':tmp_sort:' + +new Date() + Math.ceil(Math.random() * 1000); ids.unshift(tmpKey); client.sadd.apply(client, ids as Array<string>); // typecast because redis doesn't care about numbers/string client.sinterstore([tmpKey, tmpKey, idsetKey]); idsetKey = tmpKey; } } if (scored) { const method = direction && direction === 'DESC' ? 'zrevrange' : 'zrange'; client[method](zsetKey, start, stop); } else { const args = [ idsetKey, 'BY', `${this.prefix('hash')}:*->${options.field}`, 'LIMIT', String(start), String(stop), direction, ]; if (alpha) { // due to the way ioredis handles input parameters, we have to do this weird apply and append thing. // when just passing in an undefined value it throws syntax errors because it attempts to add that as an actual // parameter args.push(alpha); } client.sort.apply(client, args); } if (ids) { client.del(tmpKey); } const replies = await exec<any>(client); let reply: Array<Error | any>; if (ids) { // 2 redis commands to create the temp keys, then the query reply = replies.splice(2, 1)[0]; } else { reply = replies.splice(0, 1)[0]; } replies.forEach((otherReply) => { if (otherReply instanceof Error) { const errorMessage = otherReply.stack ? otherReply.stack : otherReply.message; this.nohmClass.logError( `Error during ${this.modelName}.sort() multi.exec(): ${errorMessage}`, ); } }); if (reply instanceof Error) { // multi responses are returned as arrays and each item can be an error // if the reply of the sort command that gives us our ids fails, we want to throw throw reply; } else { return reply; } } /** * Returns the property definitions of this model. * * @returns {Object} */ public getDefinitions(): { [key in keyof TProps]: IModelPropertyDefinition } { const definitions = Object.getPrototypeOf(this).definitions; if (!definitions) { throw new Error( `Model was not defined with proper static definitions: '${this.modelName}'`, ); } return definitions; } private fireEvent(event: TAllowedEventNames, ...args: Array<any>) { if (!this.getPublish()) { // global or model specific setting for publishing events is false. return; } if (eventActions.indexOf(event) < 0) { const supported = eventActions.join(', '); this.nohmClass.logError( 'Cannot fire an unsupported action. Was "' + event + '" ' + 'and must be one of ' + supported, ); return; } const composer = messageComposers[event] || messageComposers.defaultComposer; const payload = composer.apply(this, args); const message = JSON.stringify(payload); debugPubSub( `Firing event '%s' for '%s': %j.`, event, this.modelName, payload, ); this.client.publish(`${this.prefix('channel')}:${event}`, message); } private getPublish(): boolean { if (this.publish !== null) { return this.publish; } else { return this.nohmClass.getPublish(); } } public async subscribe<TPayloadProps extends TProps>( eventName: 'create' | 'remove', callback: (payload: IDefaultEventPayload<TPayloadProps>) => void, ): Promise<void>; public async subscribe<TPayloadProps extends TProps>( eventName: 'save' | 'update', callback: (payload: IChangeEventPayload<TPayloadProps>) => void, ): Promise<void>; public async subscribe<TPayloadProps extends TProps>( eventName: 'link' | 'unlink', callback: (payload: IRelationChangeEventPayload<TPayloadProps>) => void, ): Promise<void>; /** * Subscribe to nohm events for this model. * * @param {string} eventName One of 'create', 'update', 'save', 'remove', 'unlink', 'link' * @param {function} callback * @returns {Promise<void>} Resolves after the subscription has been set up. * @memberof NohmModel */ public async subscribe<TPayloadProps extends TProps>( eventName: TAllowedEventNames, callback: | ((payload: IDefaultEventPayload<TPayloadProps>) => void) | ((payload: IChangeEventPayload<TPayloadProps>) => void) | ((payload: IRelationChangeEventPayload<TPayloadProps>) => void), ): Promise<void> { debugPubSub( `Subscribing to event '%s' for '%s'.`, eventName, this.modelName, ); await this.nohmClass.subscribeEvent( `${this.modelName}:${eventName}`, callback, ); } /** * Subscribe to only the next occurrence of an event for this model. * * @param {string} eventName One of 'create', 'update', 'save', 'remove', 'unlink', 'link' * @param {function} callback * @returns {Promise<void>} Resolves after the subscription has been set up. * @memberof NohmModel */ public async subscribeOnce( eventName: TAllowedEventNames, callback: (payload: any) => void, ): Promise<void> { debugPubSub( `Subscribing once to event '%s' for '%s'.`, eventName, this.modelName, ); await this.nohmClass.subscribeEventOnce( `${this.modelName}:${eventName}`, callback, ); } /** * Unsubscribe from an event. * * @param {string} eventName One of 'create', 'update', 'save', 'remove', 'unlink', 'link' * @param {function} [fn] If a function is given, only that function is removed as a listener. * @memberof NohmModel */ public unsubscribeEvent(eventName: string, fn?: any): void { debugPubSub( `Unsubscribing from event '%s' for '%s' with fn?: %s.`, eventName, this.modelName, fn, ); this.nohmClass.unsubscribeEvent(eventName, fn); } get id(): null | string { return this._id; } /** * ID of the record. * You can manually set it, but that doesn't automatically load it. * * @memberof NohmModel */ set id(id: null | string) { if (id === null) { this._id = null; this._isLoaded = false; this._isDirty = false; this.allPropertiesCache.id = null; return; } const stringifiedId = String(id); if (this._id !== stringifiedId) { this._id = stringifiedId; this._isLoaded = false; this._isDirty = true; this.allPropertiesCache.id = this._id; } } private stringId(): string { return typeof this._id === 'string' ? this._id : ''; } /** * Returns true if the model has been loaded from the database. * * @readonly * @type {boolean} * @memberof NohmModel */ get isLoaded(): boolean { return this._isLoaded; } /** * True if there are any unsaved changes. This is triggered by changing the id manually, * using .link()/.unlink() and changing properties from their stored state. */ get isDirty(): boolean { if (this._isDirty) { return true; } if (this.relationChanges.length > 0) { return true; } const propDiffs = this.propertyDiff(); if (propDiffs.length > 0) { return true; } return false; } } export default NohmModel;
the_stack
import * as argparse from 'argparse'; import * as fs from 'fs'; import Stream from 'stream'; import * as readline from 'readline'; import * as Tp from 'thingpedia'; import * as ThingTalk from 'thingtalk'; import util from 'util'; import { SentenceExample, DatasetParser, DatasetStringifier } from '../lib/dataset-tools/parsers'; import { maybeCreateReadStream, readAllLines } from './lib/argutils'; import * as StreamUtils from '../lib/utils/stream-utils'; import * as Utils from '../lib/utils/misc-utils'; import { EntityMap } from '../lib/utils/entity-utils'; import * as ThingTalkUtils from '../lib/utils/thingtalk'; interface CacheEntry { from : string; to : string; } class CacheParser extends Stream.Transform { constructor() { super({ objectMode: true }); } _transform(line : string, encoding : BufferEncoding, callback : (err ?: Error|null, res ?: CacheEntry) => void) { const [from, to] = line.split('\t'); callback(null, { from, to }); } _flush(callback : () => void) { callback(); } } class CacheSerializer extends Stream.Transform { constructor() { super({ writableObjectMode: true }); } _transform(entry : CacheEntry, encoding : BufferEncoding, callback : (err ?: Error|null, res ?: string|Buffer) => void) { callback(null, `${entry.from}\t${entry.to}\n`); } _flush(callback : () => void) { callback(); } } class TypecheckStream extends Stream.Transform { private _locale : string; private _timezone : string; private _includeEntityValue : boolean; private _tpClient : Tp.BaseClient; private _schemas : ThingTalk.SchemaRetriever; private _cache : Map<string, CacheEntry>; private _cacheOut : Stream.Writable|undefined; private _droppedOut : Stream.Writable; private _interactive : boolean; private _strict : boolean; private _rl ?: readline.Interface; private _current : SentenceExample|undefined; private _entities : EntityMap|undefined; private _resolve : ((res : boolean) => void)|undefined; constructor(tpClient : Tp.BaseClient, schemas : ThingTalk.SchemaRetriever, cache : Map<string, CacheEntry>, cacheOut : Stream.Writable|undefined, droppedOut : Stream.Writable, args : { interactive : boolean, strict : boolean, locale : string, timezone : string, include_entity_value : boolean }) { super({ objectMode: true }); this._locale = args.locale; this._timezone = args.timezone; this._includeEntityValue = args.include_entity_value; this._tpClient = tpClient; this._schemas = schemas; this._cache = cache; this._cacheOut = cacheOut; this._droppedOut = droppedOut; this._interactive = args.interactive; if (args.interactive) { this._rl = readline.createInterface({ input: process.stdin, output: process.stdout }); this._rl.setPrompt('$ '); this._rl.on('line', (line) => this._onLine(line)); } this._strict = args.strict; this._current = undefined; this._entities = undefined; this._resolve = undefined; } private _onLine(line : string) { line = line.trim(); if (!line) { this._rl!.prompt(); return; } if (line === 'h' || line === '?') { this._help(); this._rl!.prompt(); return; } if (line === 'q') { this._quit(); return; } if (line === 'd') { this._resolve!(false); return; } this._learn(line).catch((e) => this.emit('error', e)); } private _help() { console.log('Available commands:'); console.log('q: quit (switch to non-interactive mode)'); console.log('d: drop'); console.log('? or h: this help'); console.log('Any other input is interpreted as a ThingTalk program'); } private _cacheable(from : string, to : string) { if (to === 'null') return true; // if the number of quotes changed in from/to, then the mapping depends on // the sentence as well, so the program is not cacheable const fromqcount = from.split(' ').filter((t) => t === '"').length; const toqcount = to.split(' ').filter((t) => t === '"').length; return fromqcount === toqcount; } private _doCache(to : string) { const targetCode = String(this._current!.target_code); if (!this._cacheable(targetCode, to)) return; const cacheEntry = { from: targetCode, to }; this._cache.set(targetCode, cacheEntry); if (this._cacheOut) this._cacheOut.write(cacheEntry); } async _learn(line : string) { try { const program = await ThingTalkUtils.parse(line, this._schemas); const code = ThingTalkUtils.serializePrediction(program, this._current!.preprocessed, this._entities!, { locale: this._locale, timezone: this._timezone, includeEntityValue: this._includeEntityValue }).join(' '); this._doCache(code); this._current!.target_code = code; this._resolve!(true); } catch(e) { console.log(e.name + ': ' + e.message); this._rl!.prompt(); } } private _quit() { if (this._resolve) this._resolve(false); this._rl!.close(); this._interactive = false; } private async _process(ex : SentenceExample) { this._current = ex; this._entities = Utils.makeDummyEntities(ex.preprocessed); let program : ThingTalk.Ast.Input|undefined; try { program = await ThingTalkUtils.parsePrediction(String(ex.target_code).split(' '), this._entities, { timezone: this._timezone, thingpediaClient: this._tpClient, schemaRetriever: this._schemas, }, true); ex.target_code = ThingTalkUtils.serializePrediction(program!, this._current!.preprocessed, this._entities, { locale: this._locale, timezone: this._timezone, includeEntityValue: this._includeEntityValue }).join(' '); this.push(ex); return; } catch(e) { if (this._strict) throw e; if (this._cache.has(String(ex.target_code))) { const cached = this._cache.get(String(ex.target_code))!; if (cached.to === 'null') { this._droppedOut.write(this._current); return; } ex.target_code = cached.to; this.push(ex); return; } let ok = false; if (this._interactive) { console.log(`${ex.id}: ${e.name}: ${e.message}`); console.log(ex.preprocessed); if (program) console.log(program.prettyprint()); else console.log(ex.target_code); ok = await new Promise((resolve, reject) => { this._resolve = resolve; if (program) this._rl!.write(program.prettyprint().replace(/\n/g, ' ')); this._rl!.prompt(); }); } if (ok) { this.push(this._current); } else { this._doCache('null'); this._droppedOut.write(this._current); } } } _transform(ex : SentenceExample, encoding : BufferEncoding, callback : (err ?: Error) => void) { this._process(ex).then(() => callback(), callback); } _flush(callback : () => void) { if (this._interactive) this._rl!.close(); this._droppedOut.end(); if (this._cacheOut) this._cacheOut.end(); callback(); } } export function initArgparse(subparsers : argparse.SubParser) { const parser = subparsers.add_parser('typecheck', { add_help: true, description: "Typecheck a dataset, optionally applying transformations to ensure the types are correct." }); parser.add_argument('-o', '--output', { required: true, type: fs.createWriteStream }); parser.add_argument('--dropped', { required: true, help: "Location where to save sentences that were dropped", type: fs.createWriteStream }); parser.add_argument('-l', '--locale', { required: false, default: 'en-US', help: `BGP 47 locale tag of the language to evaluate (defaults to 'en-US', English)` }); parser.add_argument('--timezone', { required: false, default: undefined, help: `Timezone to use to interpret dates and times (defaults to the current timezone).` }); parser.add_argument('--thingpedia', { required: true, help: 'Path to ThingTalk file containing class definitions.' }); parser.add_argument('--cache', { help: "Cache file with previously applied transformations." }); parser.add_argument('--contextual', { action: 'store_true', help: 'Process a contextual dataset.', default: false }); parser.add_argument('--interactive', { action: 'store_true', help: 'Fix problems interactively.', default: false }); parser.add_argument('--no-interactive', { action: 'store_false', dest: 'interactive', help: 'Fix problems automatically with no interaction.', }); parser.add_argument('--strict', { action: 'store_true', help: 'Abort on any error.', default: false }); parser.add_argument('--no-strict', { action: 'store_false', dest: 'strict', help: 'Silently ignore errors.', }); parser.add_argument('input_file', { nargs: '+', type: maybeCreateReadStream, help: 'Input datasets to typecheck (in TSV format); use - for standard input' }); parser.add_argument('--debug', { action: 'store_true', help: 'Enable debugging.', default: false }); parser.add_argument('--no-debug', { action: 'store_false', dest: 'debug', help: 'Disable debugging.', }); parser.add_argument('--random-seed', { default: 'almond is awesome', help: 'Random seed' }); parser.add_argument('--include-entity-value', { action: 'store_true', help: "Include entity value in thingtalk", default: false }); } export async function execute(args : any) { const tpClient = new Tp.FileClient(args); const schemas = new ThingTalk.SchemaRetriever(tpClient, null, !args.debug); let cache : Map<string, CacheEntry>, cacheOut; if (args.cache) { if (await util.promisify(fs.exists)(args.cache)) { cache = await readAllLines([fs.createReadStream(args.cache)]) .pipe(new CacheParser()) .pipe(new StreamUtils.MapAccumulator<CacheEntry, 'from'>('from')) .read(); } else { cache = new Map; } cacheOut = new CacheSerializer(); cacheOut.pipe(fs.createWriteStream(args.cache, { flags: 'a' })); } else { cache = new Map; cacheOut = undefined; } const droppedOut = new DatasetStringifier(); droppedOut.pipe(args.dropped); readAllLines(args.input_file) .pipe(new DatasetParser({ contextual: args.contextual })) .pipe(new TypecheckStream(tpClient, schemas, cache, cacheOut, droppedOut, args)) .pipe(new DatasetStringifier()) .pipe(args.output); await Promise.all([ StreamUtils.waitFinish(args.output), StreamUtils.waitFinish(args.dropped) ]); }
the_stack
import Ajv from 'ajv' import flatten from 'lodash/flatten' import range from 'lodash/range' import round from 'lodash/round' import labwareSchema from '../../labware/schemas/2.json' import { toWellName, sortWells, splitWellsOnColumn, getDisplayVolume, getAsciiVolumeUnits, ensureVolumeUnits, } from '../helpers/index' import type { LabwareDefinition2 as Definition, LabwareMetadata as Metadata, LabwareDimensions as Dimensions, LabwareBrand as Brand, LabwareParameters as Params, LabwareWell as Well, LabwareWellProperties as InputWell, LabwareWellMap as WellMap, LabwareWellGroup as WellGroup, LabwareOffset as Offset, LabwareVolumeUnits as VolumeUnits, } from '../types' // NOTE: leaving this 'beta' to reduce conflicts with future labware cloud namespaces export const DEFAULT_CUSTOM_NAMESPACE = 'custom_beta' const SCHEMA_VERSION = 2 const DEFAULT_BRAND_NAME = 'generic' interface Cell { row: number column: number } // This represents creating a "range" of well names with step intervals included // For example, starting at well "A1" with a column stride of 2 would result in // the grid name being ordered as: "A1", "B1"..."A3", "B3"..etc interface GridStart { rowStart: string colStart: string rowStride: number colStride: number } type InputParams = Omit<Params, 'loadName'> type InputWellGroup = Omit<WellGroup, 'wells'> export interface BaseLabwareProps { metadata: Metadata parameters: InputParams dimensions: Dimensions brand?: Brand version?: number namespace?: string loadNamePostfix?: string[] strict?: boolean | null // If true, throws error on failed validation } export interface RegularLabwareProps extends BaseLabwareProps { offset: Offset grid: Cell spacing: Cell well: InputWell group?: InputWellGroup } export interface IrregularLabwareProps extends BaseLabwareProps { offset: Offset[] grid: Cell[] spacing: Cell[] well: InputWell[] gridStart: GridStart[] group?: InputWellGroup[] } const ajv = new Ajv({ allErrors: true, jsonPointers: true }) const validate = ajv.compile(labwareSchema) function validateDefinition( definition: Definition, strict: boolean | null | undefined = true ): Definition { const valid = validate(definition) if (!valid) { console.error('Definition:', definition) console.error('Validation Errors:', validate.errors) if (strict) { throw new Error( 'Generated labware failed to validate, please check your inputs' ) } } return definition } export function _irregularWellName( rowIdx: number, colIdx: number, gridStart: GridStart ): string { const rowNum = rowIdx * gridStart.rowStride + gridStart.rowStart.charCodeAt(0) - 65 const colNum = colIdx * gridStart.colStride + parseInt(gridStart.colStart) - 1 return toWellName({ rowNum, colNum, }) } export function _calculateWellCoord( rowIdx: number, colIdx: number, spacing: Cell, offset: Offset, well: InputWell ): Well { const coords = { x: round(colIdx * spacing.column + offset.x, 2), y: round(rowIdx * spacing.row + offset.y, 2), z: round(offset.z - well.depth, 2), } // NOTE: Ian 2019-04-16 this silly "if circular" is to make Flow happy if (well.shape === 'circular') return { ...well, ...coords } return { ...well, ...coords } } interface Layout { wells: WellMap groups: WellGroup[] } function determineIrregularLayout( grids: Cell[], spacing: Cell[], offset: Offset[], gridStart: GridStart[], wells: InputWell[], group: InputWellGroup[] = [] ): Layout { return grids.reduce<Layout>( (result, gridObj, gridIdx) => { const reverseRowIdx = range(gridObj.row - 1, -1) const inputGroup = group[gridIdx] || { metadata: {}, } const currentGroup: WellGroup = { ...inputGroup, wells: [] } range(gridObj.column).forEach(colIdx => { range(gridObj.row).forEach(rowIdx => { const wellName = _irregularWellName( rowIdx, colIdx, gridStart[gridIdx] ) currentGroup.wells.push(wellName) result.wells[wellName] = _calculateWellCoord( reverseRowIdx[rowIdx], colIdx, spacing[gridIdx], offset[gridIdx], wells[gridIdx] ) }) }) return { wells: result.wells, groups: [...result.groups, currentGroup], } }, { wells: {}, groups: [], } ) } export function _generateIrregularLoadName(args: { grid: Cell[] well: InputWell[] totalWellCount: number units: VolumeUnits brand: string displayCategory: string loadNamePostfix?: string[] }): string { const { grid, well, totalWellCount, units, brand, displayCategory, loadNamePostfix = [], } = args const loadNameUnits = getAsciiVolumeUnits(units) const wellComboArray = grid.map((gridObj, gridIdx) => { const numWells = gridObj.row * gridObj.column const wellVolume = getDisplayVolume(well[gridIdx].totalLiquidVolume, units) return `${numWells}x${wellVolume}${loadNameUnits}` }) return joinLoadName([ brand, totalWellCount, displayCategory, wellComboArray, ...loadNamePostfix, ]) } // Decide order of wells for single grid containers function determineOrdering(grid: Cell): string[][] { const ordering = range(grid.column).map(colNum => range(grid.row).map(rowNum => toWellName({ rowNum, colNum, }) ) ) return ordering } // Decide order of wells for multi-grid containers export function determineIrregularOrdering(wellsArray: string[]): string[][] { const sortedArray = wellsArray.sort(sortWells) const ordering = splitWellsOnColumn(sortedArray) return ordering } // Private helper functions to calculate the XYZ coordinates of a give well // Will return a nested object of all well objects for a labware function calculateCoordinates( wellProps: InputWell, ordering: string[][], spacing: Cell, offset: Offset, dimensions: Dimensions ): WellMap { const { yDimension } = dimensions return ordering.reduce<WellMap>((wellMap, column, cIndex) => { return column.reduce<WellMap>( (colWellMap, wellName, rIndex) => ({ ...colWellMap, [wellName]: { ...wellProps, x: round(cIndex * spacing.column + offset.x, 2), y: round(yDimension - offset.y - rIndex * spacing.row, 2), z: round(offset.z - wellProps.depth, 2), }, }), wellMap ) }, {}) } function ensureBrand(brand?: Brand): Brand { return ( brand || { brand: DEFAULT_BRAND_NAME, } ) } // joins the input array with _ to create a name, making sure to lowercase the // result and remove all invalid characters (allowed characters: [a-z0-9_.]) function joinLoadName( fragments: Array<string | number | Array<string | number>> ): string { return flatten(fragments) .map(s => String(s).replace(/_/g, '')) .join('_') .toLowerCase() .replace(/[^a-z0-9_.]/g, '') } export interface RegularNameProps { displayCategory: string displayVolumeUnits: VolumeUnits gridRows: number gridColumns: number totalLiquidVolume: number brandName?: string loadNamePostfix?: string[] } export function createRegularLoadName(args: RegularNameProps): string { const { gridRows, gridColumns, displayCategory, totalLiquidVolume, displayVolumeUnits, brandName = DEFAULT_BRAND_NAME, loadNamePostfix = [], } = args const numWells = gridRows * gridColumns return joinLoadName([ brandName, numWells, displayCategory, `${getDisplayVolume( totalLiquidVolume, displayVolumeUnits )}${getAsciiVolumeUnits(displayVolumeUnits)}`, ...loadNamePostfix, ]) } const capitalize = (_s: string): string => { const s = _s.trim() return `${s.slice(0, 1).toUpperCase()}${s.slice(1)}` } // TODO: Ian 2019-08-23 consider using this in the labware creation functions instead of manually entering displayName export function createDefaultDisplayName(args: RegularNameProps): string { const { gridRows, gridColumns, displayCategory, totalLiquidVolume, displayVolumeUnits, brandName = DEFAULT_BRAND_NAME, loadNamePostfix = [], } = args const numWells = gridRows * gridColumns return [ ...brandName.split(' ').map(capitalize), numWells, capitalize(displayCategory.replace(/([a-z])([A-Z])/g, '$1 $2')), getDisplayVolume(totalLiquidVolume, displayVolumeUnits), displayVolumeUnits, ...loadNamePostfix.map(capitalize), ] .filter(s => s !== '') .join(' ') .replace(/\s+/g, ' ') .trim() } // Generator function for labware definitions within a regular grid format // e.g. well plates, regular tuberacks (NOT 15_50ml) etc. // For further info on these parameters look at labware examples in __tests__ // or the labware definition schema in labware/schemas/ export function createRegularLabware(args: RegularLabwareProps): Definition { const { offset, dimensions, grid, spacing, well, loadNamePostfix } = args const strict = args.strict const version = args.version || 1 const namespace = args.namespace || DEFAULT_CUSTOM_NAMESPACE const ordering = determineOrdering(grid) const brand = ensureBrand(args.brand) const groupBase = args.group || { metadata: {}, } const metadata = { ...args.metadata, displayVolumeUnits: ensureVolumeUnits(args.metadata.displayVolumeUnits), } const loadName = createRegularLoadName({ gridColumns: grid.column, gridRows: grid.row, displayCategory: metadata.displayCategory, displayVolumeUnits: metadata.displayVolumeUnits, totalLiquidVolume: well.totalLiquidVolume, brandName: brand.brand, loadNamePostfix, }) return validateDefinition( { ordering, brand, metadata, dimensions, wells: calculateCoordinates(well, ordering, spacing, offset, dimensions), groups: [{ ...groupBase, wells: flatten(ordering) }], parameters: { ...args.parameters, loadName }, namespace, version, schemaVersion: SCHEMA_VERSION, cornerOffsetFromSlot: { x: 0, y: 0, z: 0, }, }, strict ) } // Generator function for labware definitions within an irregular grid format // e.g. crystallization plates, 15_50ml tuberacks and anything with multiple "grids" export function createIrregularLabware( args: IrregularLabwareProps ): Definition { const { offset, dimensions, grid, spacing, well, gridStart, group } = args const strict = args.strict const namespace = args.namespace || DEFAULT_CUSTOM_NAMESPACE const version = args.version || 1 const { wells, groups } = determineIrregularLayout( grid, spacing, offset, gridStart, well, group ) const brand = ensureBrand(args.brand) const metadata = { ...args.metadata, displayVolumeUnits: ensureVolumeUnits(args.metadata.displayVolumeUnits), } const loadName = _generateIrregularLoadName({ grid, well, totalWellCount: Object.keys(wells).length, units: metadata.displayVolumeUnits, displayCategory: metadata.displayCategory, brand: brand.brand, }) return validateDefinition( { wells, groups, brand, metadata, dimensions, parameters: { ...args.parameters, loadName, format: 'irregular' }, ordering: determineIrregularOrdering(Object.keys(wells)), namespace, version, schemaVersion: SCHEMA_VERSION, cornerOffsetFromSlot: { x: 0, y: 0, z: 0, }, }, strict ) }
the_stack
import { HierarchyProvider } from "./provider"; import { Index } from "@esfx/interval"; type HasPreviousSibling<T> = Pick<Required<HierarchyProvider<T>>, "previousSibling">; type HasNextSibling<T> = Pick<Required<HierarchyProvider<T>>, "nextSibling">; type HasFirstChild<T> = Pick<Required<HierarchyProvider<T>>, "firstChild">; type HasLastChild<T> = Pick<Required<HierarchyProvider<T>>, "lastChild">; function hasPreviousSibling<T>(provider: HierarchyProvider<T>): provider is HierarchyProvider<T> & HasPreviousSibling<T> { return provider.previousSibling !== undefined; } function hasNextSibling<T>(provider: HierarchyProvider<T>): provider is HierarchyProvider<T> & HasNextSibling<T> { return provider.nextSibling !== undefined; } function hasFirstChild<T>(provider: HierarchyProvider<T>): provider is HierarchyProvider<T> & HasFirstChild<T> { return provider.firstChild !== undefined; } function hasLastChild<T>(provider: HierarchyProvider<T>): provider is HierarchyProvider<T> & HasLastChild<T> { return provider.lastChild !== undefined; } /** * Axis traversal helpers. */ export namespace Axis { export function * self<T>(provider: HierarchyProvider<T>, element: T) { yield element; } export function * parents<T>(provider: HierarchyProvider<T>, element: T) { const parent = provider.parent(element); if (parent !== undefined) { yield parent; } } function * reverseChildrenUsingPreviousSiblingAndLastChild<T>(provider: HierarchyProvider<T> & HasPreviousSibling<T> & HasLastChild<T>, element: T) { for (let child = provider.lastChild(element); child !== undefined; child = provider.previousSibling(child)) { yield child; } } function * reverseChildrenFallback<T>(provider: HierarchyProvider<T>, element: T) { const childrenArray = [...children(provider, element)]; for (let i = childrenArray.length - 1; i >= 0; i--) { yield childrenArray[i]; } } export function * children<T>(provider: HierarchyProvider<T>, element: T) { const children = provider.children(element); if (children === undefined) { return; } for (const child of children) { if (child !== undefined) { yield child; } } } function * firstChildUsingFirstChild<T>(provider: HierarchyProvider<T> & HasFirstChild<T>, element: T) { const child = provider.firstChild(element); if (child !== undefined) { yield child; } } function * firstChildFallback<T>(provider: HierarchyProvider<T>, element: T) { for (const child of children(provider, element)) { yield child; break; } } export function * firstChild<T>(provider: HierarchyProvider<T>, element: T) { yield* hasFirstChild(provider) ? firstChildUsingFirstChild(provider, element) : firstChildFallback(provider, element); } function * lastChildUsingLastChild<T>(provider: HierarchyProvider<T> & HasLastChild<T>, element: T) { const child = provider.lastChild(element); if (child !== undefined) { yield child; } } function * lastChildFallback<T>(provider: HierarchyProvider<T>, element: T) { let last!: T; let hasChild = false; for (const child of children(provider, element)) { last = child; hasChild = true; } if (hasChild) { yield last; } } export function * lastChild<T>(provider: HierarchyProvider<T>, element: T) { yield* hasLastChild(provider) ? lastChildUsingLastChild(provider, element) : lastChildFallback(provider, element); } function nth<T>(source: Iterable<T>, offset: number | Index): T | undefined { let isFromEnd = false; if (typeof offset === "number") { isFromEnd = offset < 0; if (isFromEnd) offset = -offset; } else { isFromEnd = offset.isFromEnd; offset = offset.value; } if (isFromEnd) { if (offset === 0) { return undefined; } if (offset === 1) { let last: T | undefined; for (const element of source) { last = element; } return last; } const array: T[] = []; for (const element of source) { if (array.length >= offset) { array.shift(); } array.push(element); } return array.length === offset ? array[0] : undefined; } for (const element of source) { if (offset === 0) { return element; } offset--; } return undefined; } export function * nthChild<T>(provider: HierarchyProvider<T>, element: T, offset: number | Index) { if (typeof offset !== "number" && !offset.isFromEnd) { offset = offset.value; } if (offset === 0) { yield* firstChild(provider, element); } else { const child = nth(children(provider, element), offset); if (child !== undefined) { yield child; } } } export function * root<T>(provider: HierarchyProvider<T>, element: T) { if (provider.root !== undefined) { yield provider.root(element); } else { let hasRoot = false; let root!: T; for (const ancestor of ancestorsAndSelf(provider, element)) { hasRoot = true; root = ancestor; } if (hasRoot) { yield root; } } } function * ancestorsWorker<T>(provider: HierarchyProvider<T>, element: T, self: boolean) { let ancestor = self ? element : provider.parent(element); while (ancestor !== undefined) { yield ancestor; ancestor = provider.parent(ancestor); } } export function * ancestors<T>(provider: HierarchyProvider<T>, element: T) { yield* ancestorsWorker(provider, element, /*self*/ false); } export function * ancestorsAndSelf<T>(provider: HierarchyProvider<T>, element: T) { yield* ancestorsWorker(provider, element, /*self*/ true); } function * descendantsUsingNextSiblingAndFirstChild<T>(provider: HierarchyProvider<T> & HasNextSibling<T> & HasFirstChild<T>, element: T, self: boolean, after: boolean): IterableIterator<T> { if (self && !after) { yield element; } for (let child = provider.firstChild(element); child !== undefined; child = provider.nextSibling(child)) { yield* descendantsUsingNextSiblingAndFirstChild(provider, child, /*self*/ true, after); } if (self && after) { yield element; } } function * descendantsFallback<T>(provider: HierarchyProvider<T>, element: T, self: boolean, after: boolean): IterableIterator<T> { if (self && !after) { yield element; } for (const child of children(provider, element)) { yield* descendantsFallback(provider, child, /*self*/ true, after); } if (self && after) { yield element; } } function * reverseDescendantsUsingPreviousSiblingAndLastChild<T>(provider: HierarchyProvider<T> & HasPreviousSibling<T> & HasLastChild<T>, element: T, self: boolean): IterableIterator<T> { for (const child of reverseChildrenUsingPreviousSiblingAndLastChild(provider, element)) { yield* reverseDescendantsUsingPreviousSiblingAndLastChild(provider, child, /*self*/ true); } if (self) { yield element; } } function * reverseDescendantsFallback<T>(provider: HierarchyProvider<T>, element: T, self: boolean): IterableIterator<T> { for (const child of reverseChildrenFallback(provider, element)) { yield* reverseDescendantsFallback(provider, child, /*self*/ true); } if (self) { yield element; } } export function * descendants<T>(provider: HierarchyProvider<T>, element: T) { yield* hasNextSibling(provider) && hasFirstChild(provider) ? descendantsUsingNextSiblingAndFirstChild(provider, element, /*self*/ false, /*after*/ false) : descendantsFallback(provider, element, /*self*/ false, /*after*/ false); } export function * descendantsAndSelf<T>(provider: HierarchyProvider<T>, element: T) { yield* hasNextSibling(provider) && hasFirstChild(provider) ? descendantsUsingNextSiblingAndFirstChild(provider, element, /*self*/ true, /*after*/ false) : descendantsFallback(provider, element, /*self*/ true, /*after*/ false); } function * siblingsUsingPreviousAndNextSibling<T>(provider: HierarchyProvider<T> & HasPreviousSibling<T> & HasNextSibling<T>, element: T, self: boolean) { const precedingSiblings = [...precedingSiblingUsingPreviousSibling(provider, element)]; for (let i = precedingSiblings.length - 1; i >= 0; i--) { yield precedingSiblings[i]; } if (self) { yield element; } yield* followingSiblingsUsingNextSibling(provider, element); } function * siblingsFallback<T>(provider: HierarchyProvider<T>, element: T, self: boolean) { const parent = provider.parent(element); if (parent !== undefined) { for (const child of children(provider, parent)) { if (self || child !== element) { yield child; } } } } export function * siblings<T>(provider: HierarchyProvider<T>, element: T) { yield* hasPreviousSibling(provider) && hasNextSibling(provider) ? siblingsUsingPreviousAndNextSibling(provider, element, /*self*/ false) : siblingsFallback(provider, element, /*self*/ false); } export function * siblingsAndSelf<T>(provider: HierarchyProvider<T>, element: T) { yield* hasPreviousSibling(provider) && hasNextSibling(provider) ? siblingsUsingPreviousAndNextSibling(provider, element, /*self*/ true) : siblingsFallback(provider, element, /*self*/ true); } function * precedingSiblingUsingPreviousSibling<T>(provider: HierarchyProvider<T> & HasPreviousSibling<T>, element: T) { for (let node = provider.previousSibling(element); node !== undefined; node = provider.previousSibling(node)) { yield node; } } function * precedingSiblingsFallback<T>(provider: HierarchyProvider<T>, element: T) { let precedingSiblings: T[] | undefined; for (const sibling of siblingsFallback(provider, element, /*self*/ true)) { if (sibling === element) { break; } if (precedingSiblings === undefined) { precedingSiblings = [sibling]; } else { precedingSiblings.push(sibling); } } if (precedingSiblings) { for (let i = precedingSiblings.length - 1; i >= 0; i--) { yield precedingSiblings[i]; } } } export function * precedingSiblings<T>(provider: HierarchyProvider<T>, element: T) { yield* hasPreviousSibling(provider) ? precedingSiblingUsingPreviousSibling(provider, element) : precedingSiblingsFallback(provider, element); } function * followingSiblingsUsingNextSibling<T>(provider: HierarchyProvider<T> & HasNextSibling<T>, element: T) { for (let node = provider.nextSibling(element); node !== undefined; node = provider.nextSibling(node)) { yield node; } } function * followingSiblingsFallback<T>(provider: HierarchyProvider<T>, element: T) { let hasSeenSelf = false; for (const sibling of siblingsFallback(provider, element, /*self*/ true)) { if (hasSeenSelf) { yield sibling; } else if (sibling === element) { hasSeenSelf = true; } } } export function * followingSiblings<T>(provider: HierarchyProvider<T>, element: T) { yield* hasNextSibling(provider) ? followingSiblingsUsingNextSibling(provider, element) : followingSiblingsFallback(provider, element); } function * precedingUsingPreviousSiblingAndLastChild<T>(provider: HierarchyProvider<T> & HasPreviousSibling<T> & HasLastChild<T>, element: T) { for (const ancestor of ancestorsWorker(provider, element, /*self*/ true)) { for (const sibling of precedingSiblingUsingPreviousSibling(provider, ancestor)) { yield* reverseDescendantsUsingPreviousSiblingAndLastChild(provider, sibling, /*self*/ true); } } } function * precedingFallback<T>(provider: HierarchyProvider<T>, element: T) { for (const ancestor of ancestorsWorker(provider, element, /*self*/ true)) { for (const sibling of precedingSiblingsFallback(provider, ancestor)) { yield* reverseDescendantsFallback(provider, sibling, /*self*/ true); } } } export function * preceding<T>(provider: HierarchyProvider<T>, element: T) { yield* hasPreviousSibling(provider) && hasLastChild(provider) ? precedingUsingPreviousSiblingAndLastChild(provider, element) : precedingFallback(provider, element); } function * followingUsingNextSiblingAndFirstChild<T>(provider: HierarchyProvider<T> & HasNextSibling<T> & HasFirstChild<T>, element: T) { for (const ancestor of ancestorsWorker(provider, element, /*self*/ true)) { for (const sibling of followingSiblingsUsingNextSibling(provider, ancestor)) { yield* descendantsUsingNextSiblingAndFirstChild(provider, sibling, /*self*/ true, /*after*/ true); } } } function * followingFallback<T>(provider: HierarchyProvider<T>, element: T) { for (const ancestor of ancestorsWorker(provider, element, /*self*/ true)) { for (const sibling of followingSiblingsFallback(provider, ancestor)) { yield* descendantsFallback(provider, sibling, /*self*/ true, /*after*/ true); } } } export function * following<T>(provider: HierarchyProvider<T>, element: T) { yield* hasNextSibling(provider) && hasFirstChild(provider) ? followingUsingNextSiblingAndFirstChild(provider, element) : followingFallback(provider, element); } }
the_stack
import { routing } from "../../example/routing"; import { z, OpenAPI, defaultEndpointsFactory, withMeta, createConfig, } from "../../src"; import { expectType } from "tsd"; describe("Open API generator", () => { const config = createConfig({ cors: true, logger: { level: "debug", color: true }, server: { listen: 8090, }, }); describe("generateOpenApi()", () => { test("should generate the correct schema of example routing", () => { const spec = new OpenAPI({ routing, config, version: "1.2.3", title: "Example API", serverUrl: "http://example.com", }).getSpecAsYaml(); expect(spec).toMatchSnapshot(); }); test("should generate the correct schema for complex types", () => { const literalValue = "something" as const; const spec = new OpenAPI({ config, routing: { v1: { getSomething: defaultEndpointsFactory.build({ methods: ["get"], input: z.object({ array: z.array(z.number().int().positive()).min(1).max(3), unlimited: z.array(z.boolean()), transformer: z.string().transform((str) => str.length), }), output: z.object({ literal: z.literal(literalValue), transformation: z.number(), }), handler: async ({ input }) => ({ literal: literalValue, transformation: input.transformer, }), }), }, }, version: "3.4.5", title: "Testing Complex Types", serverUrl: "http://example.com", }).getSpecAsYaml(); expect(spec).toMatchSnapshot(); }); test("should generate the correct schema for nullable and optional types", () => { const spec = new OpenAPI({ config, routing: { v1: { getSomething: defaultEndpointsFactory.build({ methods: ["get"], input: z.object({ optional: z.string().optional(), optDefault: z.string().optional().default("test"), nullish: z.boolean().nullish(), nuDefault: z.number().int().positive().nullish().default(123), }), output: z.object({ nullable: z.string().nullable(), }), handler: async () => ({ nullable: null, }), }), }, }, version: "3.4.5", title: "Testing Nullable and Optional Types", serverUrl: "http://example.com", }).getSpecAsYaml(); expect(spec).toMatchSnapshot(); }); test("should generate the correct schema for intersection type", () => { const spec = new OpenAPI({ config, routing: { v1: { getSomething: defaultEndpointsFactory.build({ methods: ["post"], input: z.object({ intersection: z.intersection( z.object({ one: z.string(), }), z.object({ two: z.string(), }) ), }), output: z.object({ and: z .object({ five: z.number().int().gte(0), }) .and( z.object({ six: z.string(), }) ), }), handler: async () => ({ and: { five: 5, six: "six", }, }), }), }, }, version: "3.4.5", title: "Testing Intersection and And types", serverUrl: "http://example.com", }).getSpecAsYaml(); expect(spec).toMatchSnapshot(); }); test("should generate the correct schema for union type", () => { const spec = new OpenAPI({ config, routing: { v1: { getSomething: defaultEndpointsFactory.build({ methods: ["post"], input: z.object({ union: z.union([ z.object({ one: z.string(), two: z.number().int().positive(), }), z.object({ two: z.number().int().negative(), three: z.string(), }), ]), }), output: z.object({ or: z.string().or(z.number().int().positive()), }), handler: async () => ({ or: 554, }), }), }, }, version: "3.4.5", title: "Testing Union and Or Types", serverUrl: "http://example.com", }).getSpecAsYaml(); expect(spec).toMatchSnapshot(); }); test("should handle transformation schema in output", () => { const spec = new OpenAPI({ config, routing: { v1: { getSomething: defaultEndpointsFactory.build({ methods: ["post"], input: z.object({ one: z.string(), two: z.number().int().positive(), }), output: z.object({ transform: z.string().transform((str) => str.length), }), handler: async () => ({ transform: "test", }), }), }, }, version: "3.4.5", title: "Testing Transformation in response schema", serverUrl: "http://example.com", }).getSpecAsYaml(); expect(spec).toMatchSnapshot(); }); test("should handle bigint, boolean, date and null", () => { const spec = new OpenAPI({ config, routing: { v1: { getSomething: defaultEndpointsFactory.build({ method: "post", input: z.object({ bigint: z.bigint(), boolean: z.boolean(), date: z.date(), }), output: z.object({ null: z.null(), }), handler: async () => ({ null: null, }), }), }, }, version: "3.4.5", title: "Testing additional types", serverUrl: "http://example.com", }).getSpecAsYaml(); expect(spec).toMatchSnapshot(); }); test("should handle record", () => { const spec = new OpenAPI({ config, routing: { v1: { getSomething: defaultEndpointsFactory.build({ method: "post", input: z.object({}), output: z.object({ simple: z.record(z.number().int()), stringy: z.record(z.string().regex(/[A-Z]+/), z.boolean()), numeric: z.record(z.number().int(), z.boolean()), literal: z.record(z.literal("only"), z.boolean()), union: z.record( z.literal("option1").or(z.literal("option2")), z.boolean() ), enum: z.record(z.enum(["option1", "option2"]), z.boolean()), }), handler: jest.fn(), }), }, }, version: "3.4.5", title: "Testing record", serverUrl: "http://example.com", }).getSpecAsYaml(); expect(spec).toMatchSnapshot(); }); test("should handle type any", () => { const spec = new OpenAPI({ config, routing: { v1: { getSomething: defaultEndpointsFactory.build({ method: "get", input: z.object({ any: z.any(), }), output: z.object({ any: z.any(), }), handler: jest.fn(), }), }, }, version: "3.4.5", title: "Testing type any", serverUrl: "http://example.com", }).getSpecAsYaml(); expect(spec).toMatchSnapshot(); }); test("should handle different number types", () => { const spec = new OpenAPI({ config, routing: { v1: { getSomething: defaultEndpointsFactory.build({ method: "post", input: z.object({ double: z.number(), doublePositive: z.number().positive(), doubleNegative: z.number().negative(), doubleLimited: z.number().min(-0.5).max(0.5), int: z.number().int(), intPositive: z.number().int().positive(), intNegative: z.number().int().negative(), intLimited: z.number().int().min(-100).max(100), zero: z.number().int().nonnegative().nonpositive().optional(), }), output: z.object({ bigint: z.bigint(), }), handler: jest.fn(), }), }, }, version: "3.4.5", title: "Testing numbers", serverUrl: "http://example.com", }).getSpecAsYaml(); expect(spec).toMatchSnapshot(); }); test("should handle different string types", () => { const spec = new OpenAPI({ config, routing: { v1: { getSomething: defaultEndpointsFactory.build({ method: "post", input: z.object({ regular: z.string(), min: z.string().min(1), max: z.string().max(15), range: z.string().min(2).max(3), email: z.string().email(), uuid: z.string().uuid(), cuid: z.string().cuid(), url: z.string().url(), numeric: z.string().regex(/\d+/), combined: z .string() .nonempty() .email() .regex(/.*@example\.com/is) .max(90), }), output: z.object({ nonempty: z.string().nonempty(), }), handler: jest.fn(), }), }, }, version: "3.4.5", title: "Testing strings", serverUrl: "http://example.com", }).getSpecAsYaml(); expect(spec).toMatchSnapshot(); }); test("should handle tuples", () => { const spec = new OpenAPI({ config, routing: { v1: { getSomething: defaultEndpointsFactory.build({ method: "post", input: z.object({ ofOne: z.tuple([z.boolean()]), ofStrings: z.tuple([z.string(), z.string().nullable()]), complex: z.tuple([ z.boolean(), z.string(), z.number().int().positive(), ]), }), output: z.object({ empty: z.tuple([]), }), handler: jest.fn(), }), }, }, version: "3.4.5", title: "Testing tuples", serverUrl: "http://example.com", }).getSpecAsYaml(); expect(spec).toMatchSnapshot(); }); test("should handle enum types", () => { const spec = new OpenAPI({ config, routing: { v1: { getSomething: defaultEndpointsFactory.build({ method: "post", input: z.object({ regularEnum: z.enum(["ABC", "DEF"]), }), output: z.object({ nativeEnum: z.nativeEnum({ FEG: 1, XYZ: 2 }), }), handler: async () => ({ nativeEnum: 1, }), }), }, }, version: "3.4.5", title: "Testing enums", serverUrl: "http://example.com", }).getSpecAsYaml(); expect(spec).toMatchSnapshot(); }); test("should handle z.preprocess()", () => { const string = z.preprocess((arg) => String(arg), z.string()); const number = z.preprocess( (arg) => parseInt(String(arg), 16), z.number().int().nonnegative() ); const boolean = z.preprocess((arg) => !!arg, z.boolean()); const spec = new OpenAPI({ config, routing: { v1: { getSomething: defaultEndpointsFactory.build({ method: "get", input: z.object({ string, number }), output: z.object({ boolean }), handler: async () => ({ boolean: [] as unknown as boolean, // @todo check this out without type forcing in future Zod versions }), }), }, }, version: "3.4.5", title: "Testing z.preprocess()", serverUrl: "http://example.com", }).getSpecAsYaml(); expect(spec).toMatchSnapshot(); expect(string.parse(123)).toBe("123"); expect(number.parse("0xFF")).toBe(255); expect(boolean.parse([])).toBe(true); expect(boolean.parse("")).toBe(false); expect(boolean.parse(null)).toBe(false); }); test("should throw on unsupported types", () => { [ z.undefined(), z.map(z.any(), z.any()), z.function(), z.lazy(() => z.any()), z.promise(z.any()), z.unknown(), z.never(), z.void(), ].forEach((zodType) => { expect( () => new OpenAPI({ config, routing: { v1: { getSomething: defaultEndpointsFactory.build({ method: "post", input: z.object({ property: zodType, }), output: z.object({}), handler: async () => ({}), }), }, }, version: "3.4.5", title: "Testing unsupported types", serverUrl: "http://example.com", }) ).toThrowError(/Zod type Zod\w+ is unsupported/); }); }); }); describe("Issue #98", () => { test("Should describe non-empty array", () => { // There is no such class as ZodNonEmptyArray in Zod v3.7.0+ // It existed though in Zod v3.6.x: // @see https://github.com/colinhacks/zod/blob/v3.6.1/src/types.ts#L1204 const spec = new OpenAPI({ config, routing: { v1: { getSomething: defaultEndpointsFactory.build({ methods: ["get", "post"], input: z.object({ arr: z.array(z.string()).nonempty(), }), output: z.object({ arr: z.array(z.string()).nonempty(), }), handler: async ({ input }) => ({ arr: input.arr, }), }), }, }, version: "3.4.5", title: "Testing issue #98", serverUrl: "http://example.com", }).getSpecAsYaml(); expect(spec).toMatchSnapshot(); }); test("should union schemas", () => { const baseSchema = z.object({ id: z.string() }); const subType1 = baseSchema.extend({ field1: z.string() }); const subType2 = baseSchema.extend({ field2: z.string() }); const unionSchema = z.union([subType1, subType2]); type TestingType = z.infer<typeof unionSchema>; expectType<TestingType>({ id: "string", field1: "string" }); expectType<TestingType>({ id: "string", field2: "string" }); const spec = new OpenAPI({ config, routing: { v1: { getSomething: defaultEndpointsFactory.build({ method: "post", input: unionSchema, output: unionSchema, handler: async ({ input }) => { if ("field1" in input) { return { id: `test, ${input.id}`, field1: input.field1, }; } return { id: "other test", field2: input.field2, }; }, }), }, }, version: "3.4.5", title: "Testing issue #98", serverUrl: "http://example.com", }).getSpecAsYaml(); expect(spec).toMatchSnapshot(); }); }); describe("Route Path Params", () => { test("should handle route path params for POST request", () => { const spec = new OpenAPI({ config, routing: { v1: { ":name": defaultEndpointsFactory.build({ method: "post", input: z.object({ name: z.literal("John").or(z.literal("Jane")), other: z.boolean(), }), output: z.object({}), handler: jest.fn(), }), }, }, version: "3.4.5", title: "Testing route path params", serverUrl: "http://example.com", }).getSpecAsYaml(); expect(spec).toMatchSnapshot(); }); test("should handle route path params for GET request", () => { const spec = new OpenAPI({ config, routing: { v1: { ":name": defaultEndpointsFactory.build({ method: "get", input: z.object({ name: z.literal("John").or(z.literal("Jane")), other: z.boolean(), }), output: z.object({}), handler: jest.fn(), }), }, }, version: "3.4.5", title: "Testing route path params", serverUrl: "http://example.com", }).getSpecAsYaml(); expect(spec).toMatchSnapshot(); }); }); describe("Metadata", () => { test("should pass over the schema description", () => { const spec = new OpenAPI({ config, routing: { v1: { getSomething: defaultEndpointsFactory.build({ method: "get", input: z.object({ str: z.string().describe("here is the test"), }), output: z.object({ result: z .number() .int() .positive() .describe("some positive integer"), }), handler: async () => ({ result: 123 }), }), }, }, version: "3.4.5", title: "Testing Metadata:description", serverUrl: "http://example.com", }).getSpecAsYaml(); expect(spec).toMatchSnapshot(); }); test("should pass over the example of an individual parameter", () => { const spec = new OpenAPI({ config, routing: { v1: { getSomething: defaultEndpointsFactory.build({ method: "get", input: z.object({ strNum: withMeta( z.string().transform((v) => parseInt(v, 10)) ).example("123"), // example is for input side of the transformation }), output: z.object({ numericStr: withMeta( z.number().transform((v) => `${v}`) ).example(123), // example is for input side of the transformation }), handler: async () => ({ numericStr: 123 }), }), }, }, version: "3.4.5", title: "Testing Metadata:example on IO parameter", serverUrl: "http://example.com", }).getSpecAsYaml(); expect(spec).toMatchSnapshot(); }); test("should pass over examples of each param from the whole IO schema examples (GET)", () => { const spec = new OpenAPI({ config, routing: { v1: { getSomething: defaultEndpointsFactory.build({ method: "get", input: withMeta( z.object({ strNum: z.string().transform((v) => parseInt(v, 10)), }) ).example({ strNum: "123", // example is for input side of the transformation }), output: withMeta( z.object({ numericStr: z.number().transform((v) => `${v}`), }) ).example({ numericStr: 123, // example is for input side of the transformation }), handler: async () => ({ numericStr: 123 }), }), }, }, version: "3.4.5", title: "Testing Metadata:example on IO schema", serverUrl: "http://example.com", }).getSpecAsYaml(); expect(spec).toMatchSnapshot(); }); test("should pass over examples of the whole IO schema (POST)", () => { const spec = new OpenAPI({ config, routing: { v1: { getSomething: defaultEndpointsFactory.build({ method: "post", input: withMeta( z.object({ strNum: z.string().transform((v) => parseInt(v, 10)), }) ).example({ strNum: "123", // example is for input side of the transformation }), output: withMeta( z.object({ numericStr: z.number().transform((v) => `${v}`), }) ).example({ numericStr: 123, // example is for input side of the transformation }), handler: async () => ({ numericStr: 123 }), }), }, }, version: "3.4.5", title: "Testing Metadata:example on IO schema", serverUrl: "http://example.com", }).getSpecAsYaml(); expect(spec).toMatchSnapshot(); }); test("should merge endpoint handler examples with its middleware examples", () => { const spec = new OpenAPI({ config, routing: { v1: { getSomething: defaultEndpointsFactory .addMiddleware({ input: withMeta( z.object({ key: z.string(), }) ).example({ key: "1234-56789-01", }), middleware: jest.fn(), }) .build({ method: "post", input: withMeta( z.object({ str: z.string(), }) ).example({ str: "test", }), output: withMeta( z.object({ num: z.number(), }) ).example({ num: 123, }), handler: async () => ({ num: 123 }), }), }, }, version: "3.4.5", title: "Testing Metadata:example on IO schema + middleware", serverUrl: "http://example.com", }).getSpecAsYaml(); expect(spec).toMatchSnapshot(); }); }); });
the_stack
import * as React from 'react'; import { ICrop } from '../ImageManipulation.types'; import { nodePoition } from './Enums'; import styles from './ImageCrop.module.scss'; import { ICropData, IMousePosition } from './Interfaces'; function clamp(num: number, min: number, max: number): number { return Math.min(Math.max(num, min), max); } export interface IImageCropProps { crop: ICrop; sourceHeight: number; sourceWidth: number; showRuler?: boolean; onDragStart?: (e: MouseEvent) => void; onComplete?: (crop: ICrop) => void; onChange?: (crop: ICrop) => void; // tslint:disable-next-line: no-any onDragEnd?: (e: any) => void; } export interface IImageCropState { cropIsActive: boolean; newCropIsBeingDrawn: boolean; reloadtimestamp: string; } // Feature detection // tslint:disable-next-line: max-line-length // https://developer.mozilla.org/en-US/docs/Web/API/EventTarget/addEventListener#Improving_scrolling_performance_with_passive_listeners export default class ImageCrop extends React.Component<IImageCropProps, IImageCropState> { private controlRef: HTMLDivElement = undefined; private dragStarted: boolean = false; private mouseDownOnCrop: boolean = false; private evData: ICropData; constructor(props: IImageCropProps) { super(props); this.state = { cropIsActive: false, newCropIsBeingDrawn: false, reloadtimestamp: '' }; this.onDocMouseTouchMove = this.onDocMouseTouchMove.bind(this); this.onDocMouseTouchEnd = this.onDocMouseTouchEnd.bind(this); this.onCropMouseTouchDown = this.onCropMouseTouchDown.bind(this); this.setControlRef = this.setControlRef.bind(this); this.onMouseTouchDown = this.onMouseTouchDown.bind(this); } public componentDidMount(): void { const { crop } = this.props; if (crop && this.isValid(crop) && (crop.sx !== 0 || crop.sy !== 0 || crop.width !== 0 && crop.height !== 0) ) { this.setState({ cropIsActive: true }); } else { // Requireed because first renderer has no ref this.setState({ reloadtimestamp: new Date().getTime().toString() }); } } public render(): React.ReactElement<IImageCropProps> { const { crop } = this.props; const cropSelection: JSX.Element = this.isValid(crop) && this.controlRef ? this.createSelectionGrid() : undefined; // tslint:disable:react-a11y-event-has-role return ( <div ref={this.setControlRef} className={styles.ImgGridShadowOverlay} onMouseMove={this.onDocMouseTouchMove} onTouchMove={this.onDocMouseTouchMove} onMouseUp={this.onDocMouseTouchEnd} onTouchCancel={this.onDocMouseTouchEnd} onTouchEnd={this.onDocMouseTouchEnd} onMouseDown={this.onMouseTouchDown} onTouchStart={this.onMouseTouchDown} > <div className={styles.ImgGridVisible} style={ { left: 0, top: 0, right: 0, bottom: 0 } }> {cropSelection} </div> </div> ); // tslint: } private createSelectionGrid(): JSX.Element { const { showRuler } = this.props; const style: { top: string, left: string, width: string, height: string } = this.getCropStyle(); // tslint:disable:react-a11y-event-has-role return ( <div style={style} className={styles.CropContrainer} onMouseDown={this.onCropMouseTouchDown} onTouchStart={this.onCropMouseTouchDown} > <div className={styles.dragBar_n} data-ord={nodePoition.N} /> <div className={styles.dragBar_e} data-ord={nodePoition.E} /> <div className={styles.dragBar_s} data-ord={nodePoition.S} /> <div className={styles.dragBar_w} data-ord={nodePoition.W} /> <div className={[styles.dragHandle, styles.nw].join(' ')} data-ord={nodePoition.NW} /> <div className={[styles.dragHandle, styles.n].join(' ')} data-ord={nodePoition.N} /> <div className={[styles.dragHandle, styles.ne].join(' ')} data-ord={nodePoition.NE} /> <div className={[styles.dragHandle, styles.e].join(' ')} data-ord={nodePoition.E} /> <div className={[styles.dragHandle, styles.se].join(' ')} data-ord={nodePoition.SE} /> <div className={[styles.dragHandle, styles.s].join(' ')} data-ord={nodePoition.S} /> <div className={[styles.dragHandle, styles.sw].join(' ')} data-ord={nodePoition.SW} /> <div className={[styles.dragHandle, styles.w].join(' ')} data-ord={nodePoition.W} /> {showRuler && ( <div> <div className={styles.ruleOfThirdsHZ} /> <div className={styles.ruleOfThirdsVT} /> </div> )} </div> ); // tslint:enable } private makeNewCrop(): ICrop { const crop: ICrop = { ...{ sx: 0, sy: 0, height: 0, width: 0 }, ...this.props.crop }; return crop; } private getCropStyle(): { top: string, left: string, width: string, height: string } { const crop: ICrop = this.makeNewCrop(); const unit: string = 'px'; return { top: `${crop.sy}${unit}`, left: `${crop.sx}${unit}`, width: `${crop.width}${unit}`, height: `${crop.height}${unit}` }; } // tslint:disable-next-line: no-any private onDocMouseTouchMove(e: React.MouseEvent<HTMLDivElement> | any): void { const { crop, onChange, onDragStart } = this.props; if (!this.mouseDownOnCrop) { return; } e.preventDefault(); if (!this.dragStarted) { this.dragStarted = true; if (onDragStart) { // tslint:disable-next-line: no-any onDragStart(e as any); } } const clientPos: IMousePosition = this.getClientPos(e); /* if (this.evData.isResize && this.props.aspect && this.evData.cropOffset) { clientPos.y = this.straightenYPath(clientPos.x); } */ this.evData.xDiff = clientPos.x - this.evData.clientStartX; this.evData.yDiff = clientPos.y - this.evData.clientStartY; let nextCrop: ICrop; if (this.evData.isResize) { nextCrop = this.resizeCrop(); } else { nextCrop = this.dragCrop(); } if (nextCrop !== crop) { if (onChange) { onChange(nextCrop); } } } private dragCrop(): ICrop { const { evData } = this; const nextCrop: ICrop = this.makeNewCrop(); const width: number = this.controlRef.clientWidth; const height: number = this.controlRef.clientHeight; nextCrop.sx = clamp(evData.cropStartX + evData.xDiff, 0, width - nextCrop.width); nextCrop.sy = clamp(evData.cropStartY + evData.yDiff, 0, height - nextCrop.height); return nextCrop; } private resizeCrop(): ICrop { const { evData } = this; const nextCrop: ICrop = this.makeNewCrop(); const { pos } = evData; if (evData.xInversed) { evData.xDiff -= evData.cropStartWidth * 2; } if (evData.yInversed) { evData.yDiff -= evData.cropStartHeight * 2; } const newSize: { width: number, height: number } = this.getNewSize(); let newX: number = evData.cropStartX; let newY: number = evData.cropStartY; if (evData.xInversed) { newX = nextCrop.sx + (nextCrop.width - newSize.width); } if (evData.yInversed) { newY = nextCrop.sy + (nextCrop.height - newSize.height); } const containedCrop: ICrop = { sx: newX, sy: newY, width: newSize.width, height: newSize.height, aspect: this.props.crop.aspect }; if (this.props.crop.aspect || (pos === nodePoition.NW || pos === nodePoition.SE || pos === nodePoition.SW || pos === nodePoition.NE)) { nextCrop.sx = containedCrop.sx; nextCrop.sy = containedCrop.sy; nextCrop.width = containedCrop.width; nextCrop.height = containedCrop.height; } else if (pos === nodePoition.E || pos === nodePoition.W) { nextCrop.sx = containedCrop.sx; nextCrop.width = containedCrop.width; } else if (pos === nodePoition.N || pos === nodePoition.S) { nextCrop.sy = containedCrop.sy; nextCrop.height = containedCrop.height; } return nextCrop; } private getNewSize(): { width: number, height: number } { const { crop, sourceWidth, sourceHeight } = this.props; const { evData } = this; let newWidth: number = evData.cropStartWidth + evData.xDiff; if (evData.xInversed) { newWidth = Math.abs(newWidth); } newWidth = clamp(newWidth, 0, sourceWidth); // New height. let newHeight: number; if (crop.aspect) { newHeight = newWidth / crop.aspect; } else { newHeight = evData.cropStartHeight + evData.yDiff; } if (evData.yInversed) { // Cap if polarity is inversed and the height fills the y space. newHeight = Math.min(Math.abs(newHeight), evData.cropStartY); } newHeight = clamp(newHeight, 0, sourceHeight); if (crop.aspect) { newWidth = clamp(newHeight * crop.aspect, 0, sourceWidth); } return { width: newWidth, height: newHeight }; } // tslint:disable-next-line: no-any private onDocMouseTouchEnd(e: MouseEvent | any): void { const { crop, onDragEnd, onComplete } = this.props; if (this.mouseDownOnCrop) { this.mouseDownOnCrop = false; this.dragStarted = false; if (onDragEnd) { onDragEnd(e); } if (onComplete) { onComplete(crop); } this.setState({ cropIsActive: false, newCropIsBeingDrawn: false }); } } // tslint:disable-next-line: no-any private onCropMouseTouchDown(e: MouseEvent | any): void { const { crop } = this.props; e.preventDefault(); // Stop drag selection. const mousepos: IMousePosition = this.getClientPos(e); const { ord } = e.target.dataset; let xInversed: boolean = false; let yInversed: boolean = false; let pos: nodePoition = undefined; if (ord && !isNaN(+ord)) { pos = +ord; xInversed = pos === nodePoition.NW || pos === nodePoition.W || pos === nodePoition.SW; yInversed = pos === nodePoition.NW || pos === nodePoition.N || pos === nodePoition.NE; } this.evData = { clientStartX: mousepos.x, clientStartY: mousepos.y, cropStartWidth: crop.width, cropStartHeight: crop.height, cropStartX: xInversed ? crop.sx + crop.width : crop.sx, cropStartY: yInversed ? crop.sy + crop.height : crop.sy, xInversed: xInversed, yInversed: yInversed, isResize: (ord && !isNaN(ord)), pos: pos, xDiff: 0, yDiff: 0 }; this.mouseDownOnCrop = true; this.setState({ cropIsActive: true }); } private setControlRef(element: HTMLDivElement): void { this.controlRef = element; } // tslint:disable-next-line: no-any private getClientPos(e: MouseEvent | any): IMousePosition { let pageX: number; let pageY: number; if (e.touches) { [{ pageX, pageY }] = e.touches; } else { ({ pageX, pageY } = e); } return { x: pageX, y: pageY }; } private isValid(crop: ICrop): boolean { return crop && !isNaN(crop.width) && !isNaN(crop.height); } // tslint:disable-next-line: no-any private onMouseTouchDown(e: MouseEvent | any): void { const { crop, onChange } = this.props; e.preventDefault(); // Stop drag selection. const mousepos: IMousePosition = this.getClientPos(e); // tslint:disable-next-line: no-any const refpos: any = this.controlRef.getBoundingClientRect(); const startx: number = mousepos.x - refpos.left; const starty: number = mousepos.y - refpos.top; // is mousePos in current pos if (crop) { if (crop.sx - 5 <= startx && crop.sx + crop.width + 5 >= startx && crop.sy - 5 <= starty && crop.sy + crop.height + 5 >= starty ) { // Position in current crop do Nothing return; } } const nextCrop: ICrop = { sx: startx, sy: starty, width: 0, height: 0, aspect: crop.aspect }; this.evData = { clientStartX: mousepos.x, clientStartY: mousepos.y, cropStartWidth: nextCrop.width, cropStartHeight: nextCrop.height, cropStartX: nextCrop.sx, cropStartY: nextCrop.sy, xInversed: false, yInversed: false, isResize: true, xDiff: 0, yDiff: 0, pos: nodePoition.NW }; this.mouseDownOnCrop = true; onChange(nextCrop); this.setState({ cropIsActive: true, newCropIsBeingDrawn: true }); } }
the_stack
import { injectable } from 'inversify'; import * as ts from 'typescript'; import { getCommentAtPosition, WrappedAst, getWrappedNodeAtPosition } from 'tsutils'; import { FindingFilterFactory, FindingFilter, Finding, FindingFilterContext, LineSwitchParser, LineSwitchParserContext, RawLineSwitch, RawLineSwitchRule, FindingPosition, Severity, Replacement, } from '@fimbul/ymir'; export const LINE_SWITCH_REGEX = /^ *wotan-(enable|disable)((?:-next)?-line)?( +(?:(?:[\w-]+\/)*[\w-]+ *, *)*(?:[\w-]+\/)*[\w-]+)? *$/; const enum SwitchState { NoMatch, NoChange, Redundant, Unused, Used, } interface RuleSwitch { state: SwitchState; location?: ts.TextRange; fixLocation?: ts.TextRange; } interface Switch { location: ts.TextRange; enable: boolean; rules: RuleSwitch[]; outOfRange: boolean; } @injectable() export class LineSwitchFilterFactory implements FindingFilterFactory { constructor(private parser: LineSwitchParser) {} public create(context: FindingFilterContext): FindingFilter { const {disables, switches} = this.parseLineSwitches(context); return new Filter(disables, switches, context.sourceFile); } public getDisabledRanges(context: FindingFilterContext) { // remove internal `switch` property from ranges return new Map(Array.from(this.parseLineSwitches(context).disables, (entry): [string, ts.TextRange[]] => [ entry[0], entry[1].map((range) => ({pos: range.pos, end: range.end})), ])); } private parseLineSwitches(context: FindingFilterContext) { const {sourceFile, ruleNames} = context; let wrappedAst: WrappedAst | undefined; const raw = this.parser.parse({ sourceFile, getCommentAtPosition(pos) { const wrap = getWrappedNodeAtPosition(wrappedAst ??= context.getWrappedAst(), pos); if (wrap === undefined) return; return getCommentAtPosition(sourceFile, pos, wrap.node); }, }); const lineSwitches = []; const result: DisableMap = new Map(); for (const rawLineSwitch of raw) { const lineSwitch: Switch = { location: rawLineSwitch.location, enable: rawLineSwitch.enable, rules: [], outOfRange: rawLineSwitch.end! <= 0 || rawLineSwitch.pos > sourceFile.end, }; lineSwitches.push(lineSwitch); if (lineSwitch.outOfRange) continue; const rulesToSwitch = new Map<string, RuleSwitch>(); for (const rawRuleSwitch of rawLineSwitch.rules) { const ruleSwitch: RuleSwitch = { location: rawRuleSwitch.location, fixLocation: rawRuleSwitch.fixLocation || rawRuleSwitch.location, state: SwitchState.NoMatch, }; lineSwitch.rules.push(ruleSwitch); if (typeof rawRuleSwitch.predicate === 'string') { if (ruleNames.includes(rawRuleSwitch.predicate)) { if (rulesToSwitch.has(rawRuleSwitch.predicate)) { ruleSwitch.state = SwitchState.Redundant; } else { rulesToSwitch.set(rawRuleSwitch.predicate, ruleSwitch); ruleSwitch.state = SwitchState.NoChange; } } } else { const matchingNames = ruleNames.filter(makeFilterPredicate(rawRuleSwitch.predicate)); if (matchingNames.length !== 0) { ruleSwitch.state = SwitchState.Redundant; for (const rule of matchingNames) { if (!rulesToSwitch.has(rule)) { rulesToSwitch.set(rule, ruleSwitch); ruleSwitch.state = SwitchState.NoChange; } } } } } for (const [rule, ruleSwitch] of rulesToSwitch) { const ranges = result.get(rule); if (ranges === undefined) { if (rawLineSwitch.enable) continue; // rule is already enabled result.set( rule, [{pos: rawLineSwitch.pos, end: rawLineSwitch.end ?? Infinity, switch: ruleSwitch}], ); } else { const last = ranges[ranges.length - 1]; if (last.end === Infinity) { if (!rawLineSwitch.enable) continue; // rule is already disabled last.end = rawLineSwitch.pos; if (rawLineSwitch.end !== undefined) ranges.push({pos: rawLineSwitch.end, end: Infinity, switch: ruleSwitch}); } else if (rawLineSwitch.enable || rawLineSwitch.pos < last.end) { // rule is already enabled // or disabled range is nested inside the previous range continue; } else { ranges.push({ pos: rawLineSwitch.pos, end: rawLineSwitch.end ?? Infinity, switch: ruleSwitch, }); } } ruleSwitch.state = SwitchState.Unused; } } return {switches: lineSwitches, disables: result}; } } interface DisabledRange extends ts.TextRange { switch: RuleSwitch; } type DisableMap = Map<string, DisabledRange[]>; const stateText: Record<Exclude<SwitchState, SwitchState.Used>, (singular: boolean, mode: 'enable' | 'disable') => string> = { [SwitchState.NoChange](singular, mode) { return `${singular ? 'is' : 'are'} already ${mode}d`; }, [SwitchState.NoMatch](singular) { return `do${singular ? 'es' : ''}n't match any rules enabled for this file`; }, [SwitchState.Unused](singular) { return `${singular ? 'has' : 'have'} no failures to disable`; }, [SwitchState.Redundant](singular, mode) { return singular ? `was already specified in this ${mode} switch` : 'are redundant'; }, }; class Filter implements FindingFilter { constructor(private disables: DisableMap, private switches: Switch[], private sourceFile: ts.SourceFile) {} public filter(finding: Finding) { const ruleDisables = this.disables.get(finding.ruleName); if (ruleDisables !== undefined) { const {start: {position: pos}, end: {position: end}} = finding; for (const disabledRange of ruleDisables) { if (end > disabledRange.pos && pos < disabledRange.end) { disabledRange.switch.state = SwitchState.Used; return false; } } } return true; } public reportUseless(severity: Severity) { const result: Finding[] = []; for (const current of this.switches) { const mode = current.enable ? 'enable' : 'disable'; if (current.rules.length === 0) { result.push( this.createFinding( current.outOfRange ? `${titlecase(mode)} switch has no effect. The specified range doesn't exits.` : `${titlecase(mode)} switch doesn't specify any rule names.`, severity, current.location, ), ); continue; } const counts = new Array<number>(SwitchState.Used + 1).fill(0); for (const rule of current.rules) ++counts[rule.state]; if (counts[SwitchState.Used] === 0 && (!current.enable || counts[SwitchState.Unused] === 0)) { const errorStates = []; for (let state = SwitchState.NoMatch; state !== SwitchState.Used; ++state) if (counts[state] !== 0) errorStates.push(stateText[state](false, mode)); result.push( this.createFinding( `${titlecase(mode)} switch has no effect. All specified rules ${join(errorStates)}.`, severity, current.location, ), ); continue; } for (const ruleSwitch of current.rules) if ( ruleSwitch.location !== undefined && ruleSwitch.state !== SwitchState.Used && (!current.enable || ruleSwitch.state !== SwitchState.Unused) ) result.push( this.createFinding( `This rule ${stateText[ruleSwitch.state](true, mode)}.`, severity, ruleSwitch.location, ruleSwitch.fixLocation, ), ); } return result; } private createPosition(pos: number): FindingPosition { return { position: pos, ...ts.getLineAndCharacterOfPosition(this.sourceFile, pos), }; } private createFinding(message: string, severity: Severity, location: ts.TextRange, fixLocation = location): Finding { return { ruleName: 'useless-line-switch', severity, // tslint:disable-line:object-shorthand-properties-first message, // tslint:disable-line:object-shorthand-properties-first start: this.createPosition(location.pos), end: this.createPosition(location.end), fix: {replacements: [Replacement.delete(fixLocation.pos, fixLocation.end)]}, }; } } function titlecase(str: string) { return str.charAt(0).toUpperCase() + str.substr(1); } function join(parts: string[]): string { if (parts.length === 1) return parts[0]; return parts.slice(0, -1).join(', ') + ' or ' + parts[parts.length - 1]; } function makeFilterPredicate( predicate: Exclude<RawLineSwitchRule['predicate'], string>, ): Extract<RawLineSwitchRule['predicate'], Function> { return typeof predicate === 'function' ? predicate : (ruleName) => predicate.test(ruleName); } @injectable() export class DefaultLineSwitchParser implements LineSwitchParser { public parse(context: LineSwitchParserContext) { const {sourceFile} = context; const result: RawLineSwitch[] = []; const commentRegex = /(\/[/*] *wotan-(enable|disable)((?:-next)?-line)?)( +(?:(?:[\w-]+\/)*[\w-]+ *, *)*(?:[\w-]+\/)*[\w-]+)? *(?:$|\*\/)/mg; for (let match = commentRegex.exec(sourceFile.text); match !== null; match = commentRegex.exec(sourceFile.text)) { const comment = context.getCommentAtPosition(match.index); if (comment === undefined || comment.pos !== match.index || comment.end !== match.index + match[0].length) continue; const rules = match[4] === undefined ? [{predicate: /^/}] : parseRules(match[4], match.index + match[1].length); const enable = match[2] === 'enable'; switch (match[3]) { case '-line': { const lineStarts = sourceFile.getLineStarts(); const {line} = ts.getLineAndCharacterOfPosition(sourceFile, comment.pos); result.push({ rules, enable, pos: lineStarts[line], // no need to switch back if there is no next line end: lineStarts.length === line + 1 ? undefined : lineStarts[line + 1], location: {pos: comment.pos, end: comment.end}, }); break; } case '-next-line': { const lineStarts = sourceFile.getLineStarts(); const line = ts.getLineAndCharacterOfPosition(sourceFile, comment.pos).line + 1; if (lineStarts.length === line) { // there is no next line, return an out-of-range switch that can be reported result.push({ rules, enable, pos: sourceFile.end + 1, end: undefined, location: {pos: comment.pos, end: comment.end}, }); } else { result.push({ rules, enable, pos: lineStarts[line], // no need to switch back if there is no next line end: lineStarts.length === line + 1 ? undefined : lineStarts[line + 1], location: {pos: comment.pos, end: comment.end}, }); } break; } default: result.push({rules, enable, pos: comment.pos, end: undefined, location: {pos: comment.pos, end: comment.end}}); } } return result; } } function parseRules(raw: string, offset: number) { const result: RawLineSwitchRule[] = []; const re = /(?: *, *|$)/g; let pos = raw.search(/[^ ]/); let fixPos = pos; for (let match = re.exec(raw)!; ; match = re.exec(raw)!) { result.push({ predicate: raw.slice(pos, match.index), location: {pos: pos + offset, end: match.index + offset}, // fix of first rule needs to remove the comma after it, all other rule fixes need to remove the comma before it fixLocation: {pos: fixPos + offset, end: (result.length === 0 ? re.lastIndex : match.index) + offset}, }); if (match[0].length === 0) break; pos = re.lastIndex; fixPos = match.index; // fix always removes the preceeding comma } return result; }
the_stack
import { ethers, bridge } from 'hardhat'; const { BridgeMessageTypes } = bridge; import { BytesLike } from 'ethers'; import { expect } from 'chai'; import { toBytes32 } from '../../lib/utils'; import { formatTokenId } from '../../lib/bridge'; import * as types from '../../lib/types'; import { TestBridgeMessage__factory, TestBridgeMessage, } from '@optics-xyz/ts-interface/dist/optics-xapps'; import { TokenIdentifier } from '@optics-xyz/multi-provider/dist/optics'; const stringToBytes32 = (s: string): string => { const str = Buffer.from(s.slice(0, 32), 'utf-8'); const result = Buffer.alloc(32); str.copy(result); return '0x' + result.toString('hex'); }; describe('BridgeMessage', async () => { let bridgeMessage: TestBridgeMessage; const [deployer] = await ethers.getSigners(); const deployerAddress = await deployer.getAddress(); const deployerId = toBytes32(deployerAddress).toLowerCase(); const TOKEN_VALUE = 0xffff; // tokenId const testTokenId: TokenIdentifier = { domain: 1, id: '0x' + '11'.repeat(32), }; const tokenIdBytes = formatTokenId( testTokenId.domain as number, testTokenId.id as string, ); // transfer action/message const transferAction: types.TransferAction = { type: BridgeMessageTypes.TRANSFER, recipient: deployerId, amount: TOKEN_VALUE, }; const transferBytes = bridge.serializeTransferAction(transferAction); const transferMessage: types.Message = { tokenId: testTokenId, action: transferAction, }; const transferMessageBytes = bridge.serializeMessage(transferMessage); // details action/message const detailsAction: types.DetailsAction = { type: BridgeMessageTypes.DETAILS, name: stringToBytes32('TEST TOKEN'), symbol: stringToBytes32('TEST'), decimals: 8, }; const detailsBytes = bridge.serializeDetailsAction(detailsAction); const detailsMessage: types.Message = { tokenId: testTokenId, action: detailsAction, }; const detailsMessageBytes = bridge.serializeMessage(detailsMessage); // requestDetails action/message const requestDetailsAction: types.RequestDetailsAction = { type: BridgeMessageTypes.REQUEST_DETAILS, }; const requestDetailsBytes = bridge.serializeRequestDetailsAction(requestDetailsAction); const requestDetailsMessage: types.Message = { tokenId: testTokenId, action: { type: BridgeMessageTypes.REQUEST_DETAILS, }, }; const requestDetailsMessageBytes = bridge.serializeMessage( requestDetailsMessage, ); before(async () => { const [signer] = await ethers.getSigners(); const bridgeMessageFactory = new TestBridgeMessage__factory(signer); bridgeMessage = await bridgeMessageFactory.deploy(); }); it('validates actions', async () => { const invalidAction = '0x00'; // transfer message is valid let isAction = await bridgeMessage.testIsValidAction( transferBytes, BridgeMessageTypes.TRANSFER, ); expect(isAction).to.be.true; // details message is valid isAction = await bridgeMessage.testIsValidAction( detailsBytes, BridgeMessageTypes.DETAILS, ); expect(isAction).to.be.true; // request details message is valid isAction = await bridgeMessage.testIsValidAction( requestDetailsBytes, BridgeMessageTypes.REQUEST_DETAILS, ); expect(isAction).to.be.true; // not a valid message type isAction = await bridgeMessage.testIsValidAction( transferBytes, BridgeMessageTypes.INVALID, ); expect(isAction).to.be.false; // not a valid action type isAction = await bridgeMessage.testIsValidAction( invalidAction, BridgeMessageTypes.TRANSFER, ); expect(isAction).to.be.false; }); it('validates message length', async () => { const invalidMessageLen = '0x' + '03'.repeat(38); // valid transfer message let isValidLen = await bridgeMessage.testIsValidMessageLength( transferMessageBytes, ); expect(isValidLen).to.be.true; // valid details message isValidLen = await bridgeMessage.testIsValidMessageLength( detailsMessageBytes, ); expect(isValidLen).to.be.true; // valid requestDetails message isValidLen = await bridgeMessage.testIsValidMessageLength( requestDetailsMessageBytes, ); expect(isValidLen).to.be.true; // invalid message length isValidLen = await bridgeMessage.testIsValidMessageLength( invalidMessageLen, ); expect(isValidLen).to.be.false; // TODO: check that message length matches type? }); it('formats message', async () => { // formats message const newMessage = await bridgeMessage.testFormatMessage( tokenIdBytes, transferBytes, BridgeMessageTypes.TOKEN_ID, BridgeMessageTypes.TRANSFER, ); expect(newMessage).to.equal(transferMessageBytes); // reverts with bad tokenId await expect( bridgeMessage.testFormatMessage( tokenIdBytes, transferBytes, BridgeMessageTypes.INVALID, BridgeMessageTypes.TRANSFER, ), ).to.be.reverted; // reverts with bad action await expect( bridgeMessage.testFormatMessage( tokenIdBytes, transferBytes, BridgeMessageTypes.TOKEN_ID, BridgeMessageTypes.INVALID, ), ).to.be.revertedWith('!action'); }); it('returns correct message type', async () => { // transfer message let type = await bridgeMessage.testMessageType(transferMessageBytes); expect(type).to.equal(BridgeMessageTypes.TRANSFER); // details message type = await bridgeMessage.testMessageType(detailsMessageBytes); expect(type).to.equal(BridgeMessageTypes.DETAILS); // request details message type = await bridgeMessage.testMessageType(requestDetailsMessageBytes); expect(type).to.equal(BridgeMessageTypes.REQUEST_DETAILS); }); it('checks message type', async () => { // transfer message let isTransfer = await bridgeMessage.testIsTransfer(transferBytes); expect(isTransfer).to.be.true; isTransfer = await bridgeMessage.testIsTransfer(detailsBytes); expect(isTransfer).to.be.false; isTransfer = await bridgeMessage.testIsTransfer(requestDetailsBytes); expect(isTransfer).to.be.false; let isDetails = await bridgeMessage.testIsDetails(detailsBytes); expect(isDetails).to.be.true; isDetails = await bridgeMessage.testIsDetails(transferBytes); expect(isDetails).to.be.false; isDetails = await bridgeMessage.testIsDetails(requestDetailsBytes); expect(isDetails).to.be.false; let isRequestDetails = await bridgeMessage.testIsRequestDetails( requestDetailsBytes, ); expect(isRequestDetails).to.be.true; isRequestDetails = await bridgeMessage.testIsRequestDetails(detailsBytes); expect(isRequestDetails).to.be.false; isRequestDetails = await bridgeMessage.testIsRequestDetails(transferBytes); expect(isRequestDetails).to.be.false; }); it('fails for wrong action type', async () => { const invalidType = '0x00'; const badTransfer: BytesLike = invalidType + transferBytes.slice(4); const badDetails: BytesLike = invalidType + detailsBytes.slice(4); const badRequest: BytesLike = invalidType + requestDetailsBytes.slice(4); const isTransfer = await bridgeMessage.testIsTransfer(badTransfer); expect(isTransfer).to.be.false; const isDetails = await bridgeMessage.testIsDetails(badDetails); expect(isDetails).to.be.false; const isRequest = await bridgeMessage.testIsRequestDetails(badRequest); expect(isRequest).to.be.false; }); it('formats transfer action', async () => { const { recipient, amount } = transferAction; const newTransfer = await bridgeMessage.testFormatTransfer( recipient, amount, ); expect(newTransfer).to.equal(transferBytes); }); it('formats details action', async () => { const { name, symbol, decimals } = detailsAction; const newDetails = await bridgeMessage.testFormatDetails( name, symbol, decimals, ); expect(newDetails).to.equal(detailsBytes); }); it('formats request details action', async () => { const newDetails = await bridgeMessage.testFormatRequestDetails(); expect(newDetails).to.equal(requestDetailsBytes); }); it('formats token id', async () => { const newTokenId = await bridgeMessage.testFormatTokenId( testTokenId.domain, testTokenId.id, ); expect(newTokenId).to.equal(tokenIdBytes); }); it('returns elements of a token id', async () => { const evmId = '0x' + (testTokenId.id as string).slice(26); const [domain, id, newEvmId] = await bridgeMessage.testSplitTokenId( tokenIdBytes, ); expect(domain).to.equal(testTokenId.domain); expect(id).to.equal(testTokenId.id); expect(newEvmId).to.equal(evmId); await bridgeMessage.testSplitTokenId(transferMessageBytes); }); it('returns elements of a transfer action', async () => { const evmRecipient = deployerAddress; const [type, recipient, newEvmRecipient, amount] = await bridgeMessage.testSplitTransfer(transferBytes); expect(type).to.equal(BridgeMessageTypes.TRANSFER); expect(recipient).to.equal(transferAction.recipient); expect(newEvmRecipient).to.equal(evmRecipient); expect(amount).to.equal(transferAction.amount); }); it('returns elements of a details action', async () => { const [type, name, symbol, decimals] = await bridgeMessage.testSplitDetails( detailsBytes, ); expect(type).to.equal(BridgeMessageTypes.DETAILS); expect(name).to.equal(detailsAction.name); expect(symbol).to.equal(detailsAction.symbol); expect(decimals).to.equal(detailsAction.decimals); }); it('returns elements of a message', async () => { const [newTokenId, action] = await bridgeMessage.testSplitMessage( transferMessageBytes, ); expect(newTokenId).to.equal(tokenIdBytes); expect(action).to.equal(transferBytes); }); it('fails if message type is not valid', async () => { const revertMsg = 'Validity assertion failed'; await expect( bridgeMessage.testMustBeTransfer(detailsBytes), ).to.be.revertedWith(revertMsg); await expect( bridgeMessage.testMustBeDetails(transferBytes), ).to.be.revertedWith(revertMsg); await expect( bridgeMessage.testMustBeRequestDetails(transferBytes), ).to.be.revertedWith(revertMsg); await expect( bridgeMessage.testMustBeTokenId(transferBytes), ).to.be.revertedWith(revertMsg); await expect( bridgeMessage.testMustBeMessage(transferBytes), ).to.be.revertedWith(revertMsg); }); });
the_stack
import { now, timeFrom } from 'hrtime-now'; import * as sts from 'ts-simple-ast'; import SimpleProjectConstructor, { Node } from 'ts-simple-ast'; import * as ts from 'typescript'; import * as ts_module from 'typescript/lib/tsserverlibrary'; import { EvalContextUtil, EvalContextUtilImpl } from './evalCodeContextUtil'; // import { matchGlobalRegexWithGroupIndex } from './regex-groups-index'; // import { basename } from 'path'; // export const EVAL_CODE_IN_COMMENTS_REFACTOR_ACTION_NAME = `plugin-ast-inspector-eval-code-in-comments` export const EVAL_SELECTION_REFACTOR_ACTION_NAME = `plugin-ast-inspector-eval-selection` export const EVAL_CURRENT_FUNCTION_BODY_REFACTOR_ACTION_NAME = `plugin-ast-inspector-eval-current-function-body` /** context of evaluated code available in `c` variable */ export interface EvalContext { /** this is the whole typescript namespace as imported with `"import * as ts from 'typescript'` */ ts: typeof ts /** this is the whole ts-simple-ast namespace as imported with `import * as sts from 'ts-simple-ast'`. We are providing it as an utility because is much more high level than native typescript - you choose if you want ot work with it or not. */ tsa: typeof sts SimpleProjectConstructor: typeof SimpleProjectConstructor /** The user selected or where his cursor is when he activated this refactor. It will be never undefined - at least it will be the SourceFile. The type is ts-simple-ast Node. */ node: Node /** use it like console log to put debug strings that then will be printed back in the document */ print(s): void /** log messages back to tsserver (so host plugin and tsserver can see them). Is like a console.log() */ log: (msg: string) => void util: EvalContextUtil /** * Entry point for the plugin execution context. from here you have access to the Project, the Program, current sourcefile, language service, plugin configuration and everything else regarding the context on where the host plugin is being executed. Take into account that everything obtained via `info` will be native typescript objects not ts-simple-ast. For example: * * ``` * const sourceFile = c.config.info.project.getSourceFile(c.fileName) * const definition = c.info.languageService.getDefinitionAtPosition(toPosition(c.positionOrRange)) * ``` */ info: ts_module.server.PluginCreateInfo /** current file name as provided in plugin's `getEditsForRefactor`*/ fileName: string, formatOptions: ts.FormatCodeSettings /** cursor position or range from where the refactor suggestion was activated as provided in plugin's `getEditsForRefactor`*/ positionOrRange: number | ts.TextRange, /** name of the activated refactor as provided in plugin's `getEditsForRefactor` */ refactorName: string /** name of the activated refactor's action as provided in plugin's `getEditsForRefactor` */ actionName: string project: sts.Project } interface EvalResult { output?: string[] error?: Error errorOuter?: Error } let _printed = [] class EvalContextImpl implements EvalContext { ts = ts tsa = sts SimpleProjectConstructor = SimpleProjectConstructor info: ts_module.server.PluginCreateInfo fileName: string formatOptions: ts.FormatCodeSettings positionOrRange: number | ts.TextRange refactorName: string actionName: string node: Node util: EvalContextUtil = new EvalContextUtilImpl() project: sts.Project log: (msg: string) => void constructor(config: EvalContextConfig) { this.info = config.info this.fileName = config.fileName this.formatOptions = config.formatOptions this.positionOrRange = config.positionOrRange this.refactorName = config.refactorName this.actionName = config.actionName this.log = config.log this.node = config.node _printed = [] this.project = config.project } print(s): void { _printed.push(s + '') } } function doEval(code, __context__: EvalContextImpl): EvalResult { // heads up - we are type/catch inside eval. If we let eval code throw exceptions this will impact not only this extension but all other plugins in the tsserver instance const __result__: EvalResult = {}; const codeToEval = ` try { (function(c){ ${code} })(__context__); }catch(ex){ __result__.error = ex; } ` try {// TODO: get how much time it took and print it back in the output eval(codeToEval) // TODO: eval code safely using node vm so security people dont complain } catch (ex) { __context__.log('executeEvalCode, eval error (outer): ' + ex + ' - ' + JSON.stringify(ex)) __result__.errorOuter = ex } __result__.output = _printed return __result__ } const stackTrace = require('stack-trace') function prettyPrintEvalResult(evalResult) { let output = '' if (evalResult.output) { output += `Output:\n${evalResult.output.join('\n')}\n` } let error = ''; if (evalResult.error) { var trace = stackTrace.parse(evalResult.error); error += `Error: (in)\n${evalResult.error}\nTrace: \n${stackTrace.parse(evalResult.error).map(i=>`file:/${i.fileName||'unknown.ts'}#${i.lineNumber},${i.columnNumber}) function ${i.functionName}`).join('\n')}\nOriginal Stack:\n ${evalResult.error.stack}\n` } if (evalResult.errorOuter) { error += `Error: (out) \n${evalResult.errorOuter}\nStack:\n ${evalResult.errorOuter.stack}\n` } return `\nvar __output = \`\n${error + output}\n\``//TODO: escape ` ? } export interface EvalContextConfig { log: (str: string) => void node: Node info: ts_module.server.PluginCreateInfo fileName: string positionOrRange: number | ts.TextRange formatOptions: ts.FormatCodeSettings refactorName: string actionName: string project: sts.Project } export function executeEvalCode(config: EvalContextConfig): void { const t0 = now() const sourceFile = config.node.getSourceFile() const originalSourceFile = config.info.project.getSourceFile(sourceFile.getFilePath() as any) // handle eval function body if (config.actionName === EVAL_CURRENT_FUNCTION_BODY_REFACTOR_ACTION_NAME) { let targetFunction = (config.node.getKind() === ts.SyntaxKind.FunctionDeclaration ? config.node : undefined) || config.node.getFirstAncestorByKind(ts.SyntaxKind.FunctionDeclaration) if (!targetFunction) { // if we are not inside a function declaration we evaluate the body of the first function declaration in this file targetFunction = sourceFile.getFirstDescendantByKind(ts.SyntaxKind.FunctionDeclaration) } if (!targetFunction || !sts.TypeGuards.isFunctionDeclaration(targetFunction) || !targetFunction.getName()) { return } // transpile the source file to js (so user is not restricted to js) and get the body text of the transpiled function */ let codeToEval = targetFunction.getBody().getText() let configToEval = config let transpiledSourceFile: sts.SourceFile try { const jsCode = sourceFile.getEmitOutput().getOutputFiles().find(f => f.getFilePath().endsWith('.js')).getText() const fileName = 'evaluated_' + new Date().getTime() + '.ts' transpiledSourceFile = config.project.createSourceFile(fileName, jsCode) const body = transpiledSourceFile.getFunction(targetFunction.getName()).getBody().getText() if (body) { codeToEval = transpiledSourceFile.getText() + ';\n' + targetFunction.getName() + '();' configToEval = Object.assign({}, config, { sourceFile: transpiledSourceFile }) } } catch (ex) { config.log(' log failed to transpile - we continue evaluating original function though. Error: '+ex+' - '+ex.stack) //TODO: log failed to transpile - we continue evaluating original function though } const text = evalCodeAndPrintResult(configToEval, codeToEval) sourceFile.insertText(targetFunction.getEnd(), text) if (transpiledSourceFile) { transpiledSourceFile.deleteImmediatelySync() } } // handle eval selected code else if (config.actionName === EVAL_SELECTION_REFACTOR_ACTION_NAME && typeof (config.positionOrRange as ts.TextRange).pos === 'number') { const range = config.positionOrRange as ts.TextRange const text = evalCodeAndPrintResult(config, originalSourceFile.getFullText().substring(range.pos, range.end)) sourceFile.insertText(range.end, text) return } // // handle eval code in comments // else { // const regex = /\/\*\*\*@\s*([^@]+)\s*(@\*\*\*\/)/gim // const result = matchGlobalRegexWithGroupIndex(regex, originalSourceFile.getFullText()) // config.log('executeEvalCode apply matchGlobalRegexWithGroupIndex result ' + JSON.stringify(result, null, 2)) // const toPrint = result && result.length && result.map(match => { // return { text: evalCodeAndPrintResult(config, match[0].value), printPosition: match[1].end } // }) // config.log('executeEvalCode apply return true and toPrint == ' + toPrint ? JSON.stringify(toPrint, null, 2) : 'undefined') // if (!toPrint) { // sourceFile.insertText(config.node.getSourceFile().getEnd(), evalHelpText) // } // else { // toPrint.forEach(content => { // sourceFile.insertText(content.printPosition, content.text) // }) // config.log('executeEvalCode took ' + timeFrom(t0)) // } // } } function evalCodeAndPrintResult(config: EvalContextConfig, code: string): string { const context = new EvalContextImpl(config) config.log('executeEvalCode evaluating selected code: ' + code) const result = doEval(code, context) //TODO: not logging time & error const text = prettyPrintEvalResult(result) config.log('executeEvalCode after evaluating selected code result is: ' + JSON.stringify(result, null, 2)) return text } // const evalHelpText = ` // /***@ // // For evaluating code you can use a comment with a format like this one, (see how starts with "/*** followed // // by "at") You could have many of these comments as this one as long they contain VALID JAVASCRIPT (this is // // why we use line comments inside for this internal comments) IMPORTANT: make sure you save the file before // // evaluating code - if not the content in editor buffer will be different (older) than filesystem (most // // editors handle this OK but be advised) // //You have a "c" variable with a context object with useful utilities, among others:TODO: IEvalContext apidocs) // // ts: typeof ts whole typescript namespace available // // sts: typeof tsa whole ts-simple-ast namespace available // // node: Node node selected by user when activated this refactor // // print(s): void print text back here a analog to console.log // // printAst (node:Node|ts.Node): string pretty prints AST structure of given node to understand it // // This is the code will be executed here : // c.print(\` // Hello from editor. Using typescript version: \${c.ts.version} // Selected node by user is a \${c.node.getKindName()} and its parent's text is "\${c.node.getParent().getText()}" // The AST structure of this file: // \${c.printAst(c.node.getSourceFile())} // \`) // @***/ // `
the_stack
import { MarshallingError } from './MarshallingError'; import * as Assert from './assert'; import * as Util from './utils'; type Processor<T, R = T> = (value: T) => R; type CustomProcessor<T, R = T> = (value: T, path: string) => R; export enum MiddlewareStep { Before, After, } /** * Predicate over serialization/deserialization target and metadata * @param value The value being processed * @param typeName The name of the type of the value being processed * @param isRequired Is the value required * @param isBuiltInType Is the type a built-in type (versus a custom, user-defined type) */ type TestPredicate<T> = (value: T, typeName: string, isRequired: boolean, isBuiltInType: boolean) => boolean; export type Serialized<DomObj> = { [K in keyof DomObj]: DomObj[K] extends Set<infer T> ? T[] : DomObj[K] extends Map<any, infer B> // currently limited to string ? ({ [key: string]: B } | Map<any, B>) : DomObj[K] extends IObjectAny ? Serialized<DomObj[K]> : DomObj[K] }; interface IMiddleware<T, R = T> { process: Processor<T, R>; test?: TestPredicate<T>; when?: MiddlewareStep; } type ProcessorLookup<T, R = T> = Map<string, Processor<T, R>>; const identity = <T>(value: T): T => value; interface IMarshaller { /** * Restart the marshaller configuration. * This will restart all middleware and serializer/deserializer configuration. * * Primarily meant for usage in tests. */ clear: () => this; /** * Register a serializer for the type name. * The type name is case-insensitive. * This function will be used when calling `serialize` with the same type name. * * Serializers are allowed to (and encouraged to) throw errors if they encounter invalid data * * @param typeName Type name for which the serializer is being registered * @param serializer Function to be called during serialization */ registerSerializer: <T, R = T>(typeName: string, serializer: Processor<T, R>) => this; /** * Register a deserializer for the type name. * The type name is case-insensitive. * This function will be used when calling `deserialize` with the same type name. * * Deserializers are allowed to (and encouraged to) throw errors if they encounter invalid data * * @param typeName Type name for which the deserializer is being registered * @param deserializer Function to be called during deserialization */ registerDeserializer: <T, R = T>(typeName: string, serializer: Processor<T, R>) => this; /** * Register a middleware function that will be called during serialization. * Any number of functions may be registered as middleware, and will be called in the order they were specified in. * Middleware will be invoked _before_ any `serialize` function. * Middleware will be invoked every time `serialize` is called, but the execution of the processor function can be guarded: * - If the `test` function _is not_ specified, `process` will be invoked on every serialization attempt * - If the `test` function _is_ specified, `process` will be called only when `test` returns `true` * * @param process Function to be invoked to transform values _before_ serialization. It receives only the value. * @param test Optional function to guard against applying the middleware. When not specified, it behaves as though it always returned `true`. It receives the value, the type name, and a boolean indicating whether the value is required. */ registerSerializerMiddleware: <T, R = T>(process: Processor<T, R>, test?: TestPredicate<T>, when?: MiddlewareStep) => this; /** * Register a middleware function that will be called during deserialization. * Any number of functions may be registered as middleware, and will be called in the order they were specified in. * Middleware will be invoked _before_ or _after_ any `deserialize` function, depending on the configuration * Middleware will be invoked every time `deserialize` is called, but the execution of the processor function can be guarded: * - If the `test` function _is not_ specified, `process` will be invoked on every deserialization attempt * - If the `test` function _is_ specified, `process` will be called only when `test` returns `true` * * @param process Function to be invoked to transform values _before_ deserialization. It receives only the value. * @param test Optional function to guard against applying the middleware. When not specified, it behaves as though it always returned `true`. It receives the value, the type name, and a boolean indicating whether the value is required. */ registerDeserializerMiddleware: <T, R = T>(process: Processor<T, R>, test?: TestPredicate<T>, when?: MiddlewareStep) => this; /** * Serializes a value for sending it via some communication channel. * The serializer will be resolved via `typeName`, in a case-insensitive manner, as defined through `registerSerializer`. * If no serializer was registered, an identity function will be used. * Before or after serialization, depending on the flag, all serialization middleware are invoked, unless their guard indicates that they should not be. * * If `value` is undefined/null and `isRequired` is `true`, an error will be thrown. * If `value` is undefined/null and `isRequired` is `false`, `undefined` will be returned. * Otherwise, the serializer will be executed. * If an error occurs, an error with additional details and `path` will be thrown. * * @param value The value to serialize * @param typeName The name of the type being serializer, and for which to resolve a serializer * @param isRequired Is the value required * @param path The JSON path of the value in the root object, for error reporting * @param isBuiltInType Is the type a built-in type (versus custom, user-defined) */ serialize: <T, R = T>(value: T | undefined | null, typeName: string, isRequired: boolean, path: string, isBuiltInType: boolean) => R | undefined; /** * Serializes a value for sending it via some communication channel. * The serializer is passed explicitly. * Before serialization, all serialization middleware are invoked, unless their guard indicates that they should not be. * * If `value` is undefined/null and `isRequired` is `true`, an error will be thrown. * If `value` is undefined/null and `isRequired` is `false`, `undefined` will be returned. * Otherwise, the serializer will be executed. * If an error occurs, an error with additional details and `path` will be thrown. * * @param value The value to serialize * @param typeName The name of the type being serializer, used in guards only * @param formatter The function used as a serializer * @param isRequired Is the value required * @param path The JSON path of the value in the root object, for error reporting * @param isBuiltInType Is the type a built-in type (versus custom, user-defined) */ serializeWith: <T, R = T>(value: T | undefined | null, typeName: string, formatter: CustomProcessor<T, R>, isRequired: boolean, path: string, isBuiltInType: boolean) => R | undefined; /** * Deserializes a value for receiving via some communication channel. * The deserializer will be resolved via `typeName`, in a case-insensitive manner, as defined through `registerDeserializer`. * If no deserializer was registered, an identity function will be used. * Before deserialization, all deserialization middleware are invoked, unless their guard indicates that they should not be. * * If `value` is undefined/null and `isRequired` is `true`, an error will be thrown. * If `value` is undefined/null and `isRequired` is `false`, `undefined` will be returned. * Otherwise, the deserializer will be executed. * If an error occurs, an error with additional details and `path` will be thrown. * * @param value The value to deserialize * @param typeName The name of the type being deserializer, and for which to resolve a deserializer * @param isRequired Is the value required * @param path The JSON path of the value in the root object, for error reporting * @param isBuiltInType Is the type a built-in type (versus custom, user-defined) */ deserialize: <T, R = T>(value: T | undefined | null, typeName: string, isRequired: boolean, path: string, isBuiltInType: boolean) => R | undefined; /** * Deserializes a value for receiving via some communication channel. * The deserializer is passed explicitly. * Before deserialization, all deserialization middleware are invoked, unless their guard indicates that they should not be. * * If `value` is undefined/null and `isRequired` is `true`, an error will be thrown. * If `value` is undefined/null and `isRequired` is `false`, `undefined` will be returned. * Otherwise, the deserializer will be executed. * If an error occurs, an error with additional details and `path` will be thrown. * * @param value The value to deserialize * @param typeName The name of the type being deserializer, used in guards only * @param formatter The function used as a deserializer * @param isRequired Is the value required * @param path The JSON path of the value in the root object, for error reporting * @param isBuiltInType Is the type a built-in type (versus custom, user-defined) */ deserializeWith: <T, R = T>(value: T | undefined | null, typeName: string, formatter: CustomProcessor<T, R>, isRequired: boolean, path: string, isBuiltInType: boolean) => R | undefined; } export class Marshaller implements IMarshaller { /** * Serialization utilities, re-exported for easier access in generated code */ public static Util = Util; // Re-export as a namespace for utility public static Assert = Assert; /** * Get an instance of the marshaller. * The marshaller is a singleton. */ public static getInstance() { if (this.instance == null) { return this.instance = new Marshaller(); } return this.instance; } private static instance: Marshaller; private serializeMiddleware: Array<IMiddleware<any, any>> = []; private deserializeMiddleware: Array<IMiddleware<any, any>> = []; private serializerLookup: ProcessorLookup<any, any> = new Map(); private deserializerLookup: ProcessorLookup<any, any> = new Map(); /** * Marshaller is a singleton, ergo private constructor */ private constructor() {} public registerSerializer<T, R = T>(typeName: string, serializer: Processor<T, R>) { this.serializerLookup.set(typeName.toLocaleLowerCase(), serializer); return this; } public registerDeserializer<T, R = T>(typeName: string, deserializer: Processor<T, R>) { this.deserializerLookup.set(typeName.toLocaleLowerCase(), deserializer); return this; } /** * Shorthand for registering both the serializer and deserializer * @param typeName Case-insensitive type name * @param formatter Function for formatting and validating the input */ public registerFormatter<T, R = T>(typeName: string, formatter: Processor<T, R>) { this.registerSerializer<T, R>(typeName, formatter); this.registerDeserializer<T, R>(typeName, formatter); return this; } public registerSerializerMiddleware<T, R = T>(process: Processor<T, R>, test?: TestPredicate<T>, when?: MiddlewareStep) { this.serializeMiddleware.push({ process, test, when, }); return this; } public registerDeserializerMiddleware<T, R = T>(process: Processor<T, R>, test?: TestPredicate<T>, when?: MiddlewareStep) { this.deserializeMiddleware.push({ process, test, when, }); return this; } public clear() { this.serializeMiddleware = []; this.deserializeMiddleware = []; this.serializerLookup = new Map(); this.deserializerLookup = new Map(); return this; } public serializeWith<T, R = T>(value: T | undefined | null, typeName: string, formatter: CustomProcessor<T, R>, isRequired: boolean, path: string, isBuiltInType: boolean = false): R | undefined { try { const result = this.serializeMiddleware.filter((it) => it.when !== MiddlewareStep.After).reduce((value, { process, test }) => { return (test == null || test(value, typeName, isRequired, isBuiltInType)) ? process(value) : value; }, value); if (Assert.assertPresence(result, isRequired) == null && !isRequired) { return; } const formatted = formatter(result as T, path); return this.serializeMiddleware.filter((it) => it.when === MiddlewareStep.After).reduce((value, { process, test }) => { return (test == null || test(value, typeName, isRequired, isBuiltInType)) ? process(value) : value; }, formatted); } catch (error) { if (error instanceof MarshallingError) { throw error; } const message = error instanceof Error ? error.message : String(error); throw new MarshallingError(`Serializing failed on field "${path}" of type ${typeName}${isRequired ? '' : '?'}: ${message}`); } } public deserializeWith<T, R = T>(value: T | undefined | null, typeName: string, formatter: CustomProcessor<T, R>, isRequired: boolean, path: string, isBuiltInType: boolean = false): R | undefined { try { const result = this.deserializeMiddleware.filter((it) => it.when !== MiddlewareStep.After).reduce((value, { process, test }) => { return (test == null || test(value, typeName, isRequired, isBuiltInType)) ? process(value) : value; }, value); if (Assert.assertPresence(result, isRequired) == null && !isRequired) { return; } const formatted = formatter(result as T, path); return this.deserializeMiddleware.filter((it) => it.when === MiddlewareStep.After).reduce((value, { process, test }) => { return (test == null || test(value, typeName, isRequired, isBuiltInType)) ? process(value) : value; }, formatted); } catch (error) { if (error instanceof MarshallingError) { throw error; } const message = error instanceof Error ? error.message : String(error); throw new MarshallingError(`Deserializing failed on field "${path}" of type ${typeName}${isRequired ? '' : '?'}: ${message}`); } } public serialize<T, R = T>(value: T | undefined | null, typeName: string, isRequired: boolean, path: string, isBuiltInType: boolean = true): R | undefined { const formatter = (value: T) => this.resolveSerializer<T, R>(typeName)(value); return this.serializeWith(value, typeName, formatter, isRequired, path, isBuiltInType); } public deserialize<T, R = T>(value: T | undefined | null, typeName: string, isRequired: boolean, path: string, isBuiltInType: boolean = true): R | undefined { const formatter = (value: T) => this.resolveDeserializer<T, R>(typeName)(value); return this.deserializeWith(value, typeName, formatter, isRequired, path, isBuiltInType); } protected resolveSerializer<T, R = T>(typeName: string): Processor<T, R> { const standardName = typeName.toLocaleLowerCase(); return this.serializerLookup.has(standardName) ? this.serializerLookup.get(standardName)! : identity; } protected resolveDeserializer<T, R = T>(typeName: string): Processor<T, R> { const standardName = typeName.toLocaleLowerCase(); return this.deserializerLookup.has(standardName) ? this.deserializerLookup.get(standardName)! : identity; } }
the_stack
import type Pose from '../../armature/Pose'; import type { IKChain, IKLink } from "../rigs/IKChain"; import type { ISolver } from './support/ISolver'; import type Bone from '../../armature/Bone'; import { QuatUtil, Transform, Vec3Util } from '../../maths'; import { vec3, quat } from 'gl-matrix'; //#endregion // Forward And Backward Reaching Inverse Kinematics class FabrikSolver implements ISolver{ //#region MAIN maxIteration = 15; // Max Attempts to reach the end effector effectorPos : vec3 = [0,0,0]; // IK Target can be a Position or... effectorFwd : vec3 = [0,0,0]; _inWorldSpace = false; // Use & Apply changes to pose, else will use bindpose for initial data & updating pose _threshold = 0.0001 ** 2; _bonePos !: Array< vec3 >; // Use to keep track of the position of each bone _radLimit = 45 * Math.PI / 180; _dotLimit = Math.cos( this._radLimit ); _radLimit2 = 10 * Math.PI / 180; _dotLimit2 = Math.cos( this._radLimit2 ); // eslint-disable-next-line @typescript-eslint/no-unused-vars initData( pose ?: Pose, chain ?: IKChain ): this{ return this; } setTargetPos( v: vec3 ): this{ //this._isTarPosition = true; this.effectorPos[ 0 ] = v[ 0 ]; this.effectorPos[ 1 ] = v[ 1 ]; this.effectorPos[ 2 ] = v[ 2 ]; return this; } setTargetFwd( v: vec3 ): this{ this.effectorFwd[ 0 ] = v[ 0 ]; this.effectorFwd[ 1 ] = v[ 1 ]; this.effectorFwd[ 2 ] = v[ 2 ]; return this; } inWorldSpace(): this{ this._inWorldSpace = true; return this; } //#endregion resolve( chain: IKChain, pose: Pose, debug?:any ): void{ this._preProcess( chain, pose, debug ); let i:number = 0; let good: number = 0; for( i; i < this.maxIteration; i++ ){ this._iterateBackward( chain, debug ); this._iterateForward( chain, debug ); if( Vec3Util.lenSqr( this.effectorPos, this._bonePos[ chain.count ] ) <= this._threshold ){ good++; if( good >= 3 ) break; } } // console.log( 'Total Iter', i ); if( this._inWorldSpace ) this._update_fromWorldPose( chain, pose, debug ); // Apply Changes to Pose thats passed in. else this._update_fromBindPose( chain, pose, debug ); // Apply to BindPose then save results to pose. } // #region DATA _preProcess( chain: IKChain, pose: Pose, debug ?: any ): void{ //~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~ // JIT Array if( !this._bonePos ){ this._bonePos = []; for( let i=0; i < chain.count; i++ ) this._bonePos.push( [0,0,0] ); this._bonePos.push( [0,0,0] ); // One more to store tail } //~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~ // Compute all the Starting Positions for the Chain let lnk: IKLink; if( this._inWorldSpace ){ for( let i=0; i < chain.count; i++ ){ lnk = chain.links[ i ]; vec3.copy( this._bonePos[ i ], pose.bones[ lnk.idx ].world.pos ); } }else{ const pt = new Transform(); const ct = new Transform(); lnk = chain.first(); // Start in Bind Space pose.getWorldTransform( lnk.pidx, pt ); // Get the Starting Transform for the chain. ct.fromMul( pt, lnk.bind ); // Shift Bind to World Space vec3.copy( this._bonePos[0], ct.pos ); // Save First Position for( let i=1; i < chain.count; i++ ){ ct.mul( chain.links[ i ].bind ); // Add Next Bone to transform chain vec3.copy( this._bonePos[i], ct.pos ); // Save its position } } } _update_fromWorldPose( chain: IKChain, pose: Pose, debug ?: any ): void{ const pt = new Transform(); const ct = new Transform(); let lnk = chain.first(); const tail : vec3 = [0,0,0]; const from : vec3 = [0,0,0]; const to : vec3 = [0,0,0]; const q : quat = [0,0,0,1]; let b : Bone; pose.getWorldTransform( lnk.pidx, pt ); // Get the Starting Transform for the chain. for( let i=0; i < chain.count; i++ ){ lnk = chain.links[ i ]; b = pose.bones[ lnk.idx ]; ct.fromMul( pt, b.local ); // Get Bone's World Space Transform tail[0] = 0; tail[1] = lnk.len; tail[2] = 0; ct.transformVec3( tail ); // Get its Tail Position vec3.sub( from, tail, ct.pos ); // From Direction, WS Bone to WS Bind Tail vec3.normalize( from, from ); vec3.sub( to, this._bonePos[i+1], ct.pos ); // To Direction, WS Bone to Fabrik Pos vec3.normalize( to, to ); quat.rotationTo( q, from, to ); // Create Swing Rotation quat.mul( q, q, ct.rot ); // Apply it to world space bind QuatUtil.pmulInvert( q, q, pt.rot ); // To Local pose.setLocalRot( lnk.idx, q ); // Save pt.mul( q, lnk.bind.pos, lnk.bind.scl ); // Set WorldSpace Transform for next bone } } _update_fromBindPose( chain: IKChain, pose: Pose, debug ?: any ): void{ const tail : vec3 = [0,0,0]; const from : vec3 = [0,0,0]; const to : vec3 = [0,0,0]; const q : quat = [0,0,0,1]; const pt = new Transform(); const ct = new Transform(); let lnk = chain.first(); pose.getWorldTransform( lnk.pidx, pt ); // Get the Starting Transform for the chain. for( let i=0; i < chain.count; i++ ){ lnk = chain.links[ i ]; ct.fromMul( pt, lnk.bind ); tail[0] = 0; tail[1] = lnk.len; tail[2] = 0; ct.transformVec3( tail ); vec3.sub( from, tail, ct.pos ); // From Direction, Bone to Bind Tail vec3.normalize( from, from ); vec3.sub( to, this._bonePos[i+1], ct.pos ); // To Direction, Bone to Fabrik Pos vec3.normalize( to, to ); quat.rotationTo( q, from, to ); // Create Swing Rotation quat.mul( q, q, ct.rot ); // Apply it to world space bind QuatUtil.pmulInvert( q, q, pt.rot ); // To Local pose.setLocalRot( lnk.idx, q ); // Save pt.mul( q, lnk.bind.pos, lnk.bind.scl ); // Set WorldSpace Transform for next bone } } // #endregion // #region ITERATIONS _applyAngleConstraint( fromDir: vec3, toDir: vec3, t: number ){ //~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~ const dLmt = lerp( this._dotLimit, this._dotLimit2, t ); const dot = Math.max( Math.min( vec3.dot( fromDir, toDir ) , 1 ), -1 ) ; if( dot > dLmt ) return; //~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~ const rad = Math.acos( dot ); const axis : vec3 = vec3.cross( [0,0,0], fromDir, toDir ); vec3.normalize( axis, axis ); const radLmt = lerp( this._radLimit, this._radLimit2, t ); const q : quat = quat.setAxisAngle( [0,0,0,0], axis, -( rad - radLmt ) ); vec3.transformQuat( toDir, toDir, q ); } _iterateBackward( chain: IKChain, debug ?: any ): void{ // debug.pnt.reset(); // debug.ln.reset(); const endIdx = chain.count - 1; const apos = this._bonePos; const lnks = chain.links; const dir : vec3 = [0,0,0]; const prevDir : vec3 = [0,0,0]; const prevPos : vec3 = vec3.copy( [0,0,0], this.effectorPos ); // Start Pointing to Effector // Skip root point since we can consider it pinned let i, t; for( i=endIdx; i > 0; i-- ){ //------------------------------------ vec3.sub( dir, apos[i], prevPos ); // Direction from pos toward prev vec3.normalize( dir, dir ); if( this._radLimit && i != endIdx ){ t = 1 - ( i / endIdx); t = 1 - Math.abs( 2 * t - 1 ); // 0-1 to 0-1-0 t = sigmoid( t, -0.5 ); // Apply controllable curve on T this._applyAngleConstraint( prevDir, dir, t ); } //------------------------------------ // Scale direction by bone's legth, move bone so its tail touches prev pos vec3.scaleAndAdd( apos[i], prevPos, dir, lnks[i].len ); vec3.copy( prevPos, apos[i] ); // Save for next bone as target pos vec3.copy( prevDir, dir ); // Save for next bone for Angle Constraint Testing //debug.pnt.add( apos[i], 0xffff00, 1.5 ); } } _iterateForward( chain: IKChain, debug ?: any ): void{ const apos = this._bonePos; const lnks = chain.links; const dir : vec3 = [0,0,0] ; const prevPos : vec3 = vec3.copy( [0,0,0], apos[0] ) ; let prevLen : number = lnks[0].len; //~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~ // Move all the points back towards the root position for( let i=1; i < chain.count; i++ ){ vec3.sub( dir, apos[i], prevPos ); // Direction from Bone pos to prev pos vec3.normalize( dir, dir ); // Normalize it // Scale Direction by Prev Bone's Length then Move it so its touches prev bone's vec3.scaleAndAdd( apos[i], prevPos, dir, prevLen ); vec3.copy( prevPos, apos[i] ); // Save for next bone prevLen = lnks[ i ].len; // Save Previous Bone Length to compute tail position } //~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~ // Figure out the tail position after iteration const ilast = chain.count - 1; vec3.sub( prevPos, this.effectorPos, apos[ ilast ] ); vec3.normalize( prevPos, prevPos ); vec3.scaleAndAdd( apos[ chain.count ], apos[ ilast ], prevPos, lnks[ ilast ].len ); } // #endregion } function lerp( a: number, b: number, t: number ): number{ return a * (1-t) + b * t; } function sigmoid( t: number, k=0 ){ // Over 0, Eases in the middle, under eases in-out // this uses the -1 to 1 value of sigmoid which allows to create easing at // start and finish. Can pass in range 0:1 and it'll return that range. // https://dhemery.github.io/DHE-Modules/technical/sigmoid/ // https://www.desmos.com/calculator/q6ukniiqwn return ( t - k*t ) / ( k - 2*k*Math.abs(t) + 1 ); } export default FabrikSolver;
the_stack
import { Nodehun } from 'nodehun' const fs = require('fs') const path = require('path') // @ts-ignore const { performance } = require('perf_hooks') const ChartjsNode = require('chartjs-node'); const Nodehun3: typeof Nodehun = require('bindings')('Nodehun') const Nodehun2 = require('nodehun') ///////////////////////////////////////////////////// // CONFIGURATION ///////////////////////////////////////////////////// const samples_spell = 10 const iterations_spell = 100 const samples_suggest = 10 const iterations_suggest = 100 const correct = 'color' const incorrect = 'colour' const dictionaryType = 'en_US' const d = { affix: fs.readFileSync(path.resolve(__dirname, '../dictionaries/en_us.aff')), dictionary: fs.readFileSync(path.resolve(__dirname, '../dictionaries/en_us.dic')) } ///////////////////////////////////////////////////// interface Nodehun2 { isCorrect: Function isCorrectSync: Function spellSuggestions: Function spellSuggestionsSync: Function } const nodehun3: Nodehun = new Nodehun3(d.affix, d.dictionary) const nodehun2: Nodehun2 = new Nodehun2(d.affix, d.dictionary) const suggestSync3Test = (word: string): number => { let start = performance.now() nodehun3.suggestSync(word) let end = performance.now() return end - start } const suggestSync2Test = (word: string): number => { let start = performance.now() nodehun2.spellSuggestionsSync(word) let end = performance.now() return end - start } const suggest3Test = async (word: string) => { let start = performance.now() await nodehun3.suggest(word) let end = performance.now() return end - start }; const suggest2Test = async (word: string) => { let start = performance.now() await new Promise(resolve => nodehun2.spellSuggestions(word, resolve)) let end = performance.now() return end - start } const spellSync3Test = (word: string): number => { let start = performance.now() nodehun3.spellSync(word) let end = performance.now() return end - start } const spellSync2Test = (word: string): number => { let start = performance.now() nodehun2.isCorrectSync(word) let end = performance.now() return end - start } const spell3Test = async (word: string) => { let start = performance.now() await nodehun3.spell(word) let end = performance.now() return end - start }; const spell2Test = async (word: string) => { let start = performance.now() await new Promise(resolve => nodehun2.isCorrect(word, resolve)) let end = performance.now() return end - start } const suggestSyncTest = (iterations: number) => { let time2_correct = 0 , time3_correct = 0 , time2_incorrect = 0 , time3_incorrect = 0 for (let i = 0; i < iterations; i++) { time2_correct += suggestSync2Test(correct) time2_incorrect += suggestSync2Test(incorrect) time3_correct += suggestSync3Test(correct) time3_incorrect += suggestSync3Test(incorrect) } return { time2_correct, time2_incorrect, time3_correct, time3_incorrect } } const suggestTest = async (iterations: number) => { let time2_correct = 0 , time3_correct = 0 , time2_incorrect = 0 , time3_incorrect = 0 for (let i = 0; i < iterations; i++) { time2_correct += await suggest2Test(correct) time2_incorrect += await suggest2Test(incorrect) time3_correct += await suggest3Test(correct) time3_incorrect += await suggest3Test(incorrect) } return { time2_correct, time2_incorrect, time3_correct, time3_incorrect } } const spellSyncTest = (iterations: number) => { let time2_correct = 0 , time3_correct = 0 , time2_incorrect = 0 , time3_incorrect = 0 for (let i = 0; i < iterations; i++) { time2_correct += spellSync2Test(correct) time2_incorrect += spellSync2Test(incorrect) time3_correct += spellSync3Test(correct) time3_incorrect += spellSync3Test(incorrect) } return { time2_correct, time2_incorrect, time3_correct, time3_incorrect } } const spellTest = async (iterations: number) => { let time2_correct = 0 , time3_correct = 0 , time2_incorrect = 0 , time3_incorrect = 0 for (let i = 0; i < iterations; i++) { time2_correct += await spell2Test(correct) time2_incorrect += await spell2Test(incorrect) time3_correct += await spell3Test(correct) time3_incorrect += await spell3Test(incorrect) } return { time2_correct, time2_incorrect, time3_correct, time3_incorrect } } const standardDeviation = (values: number[]) => { var avg = average(values) var squareDiffs = values.map(function (value) { var diff = value - avg var sqrDiff = diff * diff return sqrDiff }) var avgSquareDiff = average(squareDiffs) var stdDev = Math.sqrt(avgSquareDiff) return stdDev } const average = (data: number[]) => { var sum = data.reduce(function (sum, value) { return sum + value }, 0) var avg = sum / data.length return avg } /** * Takes an array of objects and returns the average and standard deviation * for each numeric key * @param results */ const analyzeResults = (results: Array<Record<string, number>>): Record<string, { average: number, standardDeviation: number }> => { if (!results || results.length == 0) throw 'empty results' const obj = results[0] const analysis: Record<string, { average: number, standardDeviation: number }> = {} Object.keys(obj).forEach(key => { if (typeof obj[key] == 'number') { const data = results.map(r => r[key]) const avg = average(data) const std = standardDeviation(data) analysis[key] = { average: avg, standardDeviation: std } } }) return analysis } const exportGraph = async ( title: string, legendLabels: string[], yAxisLabel: string, nodehun2_xAxisLabel: string, nodehun3_xAxisLabel: string, nodehun2Times: number[], nodehun3Times: number[], writeToFile: string ) => { return new Promise(resolve => { const chartNode = new ChartjsNode(600, 400); chartNode.drawChart({ type: 'bar', options: { title: { display: true, text: title }, scales: { yAxes: [{ ticks: { beginAtZero: true }, scaleLabel: { display: true, labelString: yAxisLabel } }], xAxes: [{ afterFit: (scale) => { scale.height = 40; } }] } }, data: { labels: legendLabels, datasets: [{ backgroundColor: '#d9e4aa', label: nodehun2_xAxisLabel, data: nodehun2Times, barThickness: 50, }, { backgroundColor: '#7ac36a', label: nodehun3_xAxisLabel, data: nodehun3Times, barThickness: 50, }] } }) .then(() => chartNode.getImageBuffer('image/png')) .then(() => chartNode.getImageStream('image/png')) .then(() => chartNode.writeImageToFile('image/png', writeToFile)) .then(resolve) }) } const performanceTest = async () => { console.log(`Running performance test`) console.log(`...correct word '${correct}'`) console.log(`...incorrect word '${incorrect}'`) console.log(`...spelling\n`, `......iterations ${iterations_spell}\n`, `......samples ${samples_spell}`) console.log(`...suggesting\n`, `......iterations ${iterations_suggest}\n`, `......samples ${samples_suggest}`) const results_spellSync = [] const results_spell = [] const results_suggestSync = [] const results_suggest = [] for (let i = 0; i < samples_spell; i++) { results_spellSync.push(spellSyncTest(iterations_spell)) results_spell.push(await spellTest(iterations_spell)) } for (let i = 0; i < samples_suggest; i++) { results_suggestSync.push(suggestSyncTest(iterations_suggest)) results_suggest.push(await suggestTest(iterations_suggest)) } const analysis_spellSync = analyzeResults(results_spellSync) const analysis_spell = analyzeResults(results_spell) const analysis_suggestSync = analyzeResults(results_suggestSync) const analysis_suggest = analyzeResults(results_suggest) console.log('Nodehun3#spellSync vs Nodehun2#isCorrectSync') console.log(analysis_spellSync) console.log('Nodehun3#spell vs Nodehun2#isCorrect') console.log(analysis_spell) console.log('Nodehun3#suggestSync vs Nodehun2#spellSuggestionsSync') console.log(analysis_suggestSync) console.log('Nodehun3#suggest vs Nodehun2#spellSuggestions') console.log(analysis_suggest) await exportGraph( `Nodehun3#spell[Sync] vs Nodehun2#isCorrect[Sync] (${samples_spell} samples, ${dictionaryType})`, [ ` correct word\n"${correct}" (sync)`, ` correct word\n"${correct}" (async)`, ` incorrect word\n"${incorrect}" (sync)`, ` incorrect word\n"${incorrect}" (async)` ], `average milliseconds for ${iterations_spell} operations`, 'Nodehun2 (w/ promise wrapper for async)', 'Nodehun3', [ analysis_spellSync.time2_correct.average, analysis_spell.time2_correct.average, analysis_spellSync.time2_incorrect.average, analysis_spell.time2_incorrect.average ], [ analysis_spellSync.time3_correct.average, analysis_spell.time3_correct.average, analysis_spellSync.time3_incorrect.average, analysis_spell.time3_incorrect.average ], './test/performance/spell.png' ) await exportGraph( `Nodehun3#suggest[Sync] vs Nodehun2#spellSuggestions[Sync] (${samples_suggest} samples, ${dictionaryType})`, [ ` correct word\n"${correct}" (sync)`, ` correct word\n"${correct}" (async)`, ` incorrect word\n"${incorrect}" (sync)`, ` incorrect word\n"${incorrect}" (async)` ], `average milliseconds for ${iterations_suggest} operations`, 'Nodehun2 (w/ promise wrapper for async)', 'Nodehun3', [ analysis_suggestSync.time2_correct.average, analysis_suggest.time2_correct.average, analysis_suggestSync.time2_incorrect.average, analysis_suggest.time2_incorrect.average ], [ analysis_suggestSync.time3_correct.average, analysis_suggest.time3_correct.average, analysis_suggestSync.time3_incorrect.average, analysis_suggest.time3_incorrect.average ], './test/performance/suggest.png' ) } performanceTest()
the_stack
import * as path from "path"; import * as fs from "fs"; import * as yazl from "yazl"; import * as yauzl from "yauzl"; import { ArchiveCommon } from "./ArchiveCommon"; import { File, FileLink } from "../../common/File"; import { ProgressFunc, ProgressResult } from "../../common/Reader"; import { Logger } from "../../common/Logger"; import { Transform, Readable } from "stream"; const log = Logger("archivetar"); export class ArchiveZip extends ArchiveCommon { isSupportType( file: File ): string { return file.name.match(/\.(zip|jar)$/) ? "zip" : null; } async getArchivedFiles(progress?: ProgressFunc): Promise<File[]> { return new Promise( (resolve, reject) => { const resultFiles = []; yauzl.open( this.originalFile.fullname, { lazyEntries: true, autoClose: false, decodeStrings: false }, (err, zipfile: yauzl.ZipFile) =>{ if ( err ) { reject( err ); return; } zipfile.on("entry", (entry: yauzl.Entry) => { progress && progress( this.originalFile, (zipfile as any).readEntryCursor, this.originalFile.size, 0 ); resultFiles.push( this.convertZipToFile(entry) ); zipfile.readEntry(); }); zipfile.once("end", () => { progress && progress( this.originalFile, this.originalFile.size, this.originalFile.size, 0 ); zipfile.close(); resolve( this.subDirectoryCheck(resultFiles) ); }); zipfile.readEntry(); }); }); } uncompress( extractDir: File, uncompressFiles?: File[], progress?: ProgressFunc ): Promise<void> { return new Promise((resolve, reject) => { if ( !extractDir || (uncompressFiles && uncompressFiles.length === 0) ) { reject( "Uncompress files empty !!!" ); return; } const filesBaseDir = uncompressFiles && uncompressFiles.length > 0 ? uncompressFiles[0].dirname : ""; yauzl.open( this.originalFile.fullname, { lazyEntries: true, autoClose: false, decodeStrings: false }, (err, zipfile: yauzl.ZipFile) =>{ if ( err ) { reject( err ); return; } zipfile.on("entry", (entry: yauzl.Entry) => { const zipFileInfo = this.convertZipToFile(entry); if ( uncompressFiles ) { if ( !uncompressFiles.find( item => zipFileInfo.fullname.startsWith(item.fullname) ) ) { zipfile.readEntry(); return; } } if ( zipFileInfo.dir || zipFileInfo.link ) { this.fileStreamWrite( extractDir, filesBaseDir, zipFileInfo, null, null, (status: string, err) => { // log.debug( "Uncompress: [%s] - [%s]", zipFileInfo.fullname, err || "SUCCESS" ); if ( err ) { zipfile.close(); reject( err ); return; } zipfile.readEntry(); }); return; } zipfile.openReadStream( entry, (err, readStream) => { if ( err ) { // log.error( "zipfile.openReadStream: [%s]", err.message ); reject( err ); return; } let chunkCopyLength = 0; const reportProgress = new Transform({ transform(chunk: Buffer, encoding, callback) { chunkCopyLength += chunk.length; if ( progress ) { const result = progress( zipFileInfo, chunkCopyLength, zipFileInfo.size, chunk.length ); // log.debug( "Uncompress: %s => %s (%d / %d)", zipFileInfo.fullname, extractDir.fullname, chunkCopyLength, zipFileInfo.size ); if ( result === ProgressResult.USER_CANCELED ) { zipfile.close(); log.debug( "ZIP Uncompress - CANCEL" ); reject( "USER_CANCEL" ); return; } } callback( null, chunk ); } }); reportProgress._flush = (cb) => { cb(); zipfile.readEntry(); }; this.fileStreamWrite( extractDir, filesBaseDir, zipFileInfo, readStream, reportProgress, (status: string, err) => { // log.debug( "Uncompress: [%s] - [%s]", zipFileInfo.fullname, err || "SUCCESS" ); if ( err ) { zipfile.close(); reject( err ); return; } }); }); }); zipfile.on("error", (err) => { log.error( err ); zipfile.close(); reject( err ); }); zipfile.once("end", () => { zipfile.close(); resolve(); }); zipfile.readEntry(); }); }); } protected commonCompress( writeTarStream: fs.WriteStream, packFunc: (zip: yazl.ZipFile) => Promise<void>, _progress?: ProgressFunc ): Promise<void> { const zip = new yazl.ZipFile(); return new Promise( async (resolve, reject) => { try { writeTarStream.on("error", (error) => { log.error( "ERROR [%s]", error ); reject(error); }); const outstream = zip.outputStream.pipe(writeTarStream); outstream.on("error", (error) => { log.error( "ERROR [%s]", error ); reject(error); }).on("finish", () => { writeTarStream.close(); log.info( "Compress Finish !!!" ); resolve(); }); await packFunc( zip ); (zip as any).end(); } catch ( err ) { log.error( err ); reject( err ); } }); } protected originalPacking( pack: yazl.ZipFile, filterEntryFunc: (packFileInfo: File, header) => boolean, progress?: ProgressFunc ): Promise<void> { return new Promise( (resolve, reject) => { yauzl.open( this.originalFile.fullname, { lazyEntries: true, autoClose: false, decodeStrings: false }, (err, zipfile: yauzl.ZipFile) =>{ if ( err ) { reject( err ); return; } zipfile.on("entry", (entry: yauzl.Entry) => { try { const zipFileInfo = this.convertZipToFile(entry); const header = this.convertFileToHeader(zipFileInfo, null, null); if ( filterEntryFunc && !filterEntryFunc( zipFileInfo, header ) ) { zipfile.readEntry(); return; } if ( zipFileInfo.link ) { reject( `Unsupport link file ${zipFileInfo.name}` ); return; } if ( zipFileInfo.dir ) { pack.addEmptyDirectory( header.name, header.option ); zipfile.readEntry(); return; } zipfile.openReadStream( entry, (err, readStream) => { if ( err ) { log.error( "zipfile.openReadStream: [%s]", err.message ); reject( err ); return; } let chunkCopyLength = 0; const reportProgress = new Transform({ transform(chunk: Buffer, encoding, callback) { chunkCopyLength += chunk.length; if ( progress ) { const result = progress( zipFileInfo, chunkCopyLength, zipFileInfo.size, chunk.length ); // log.debug( "Uncompress: %s => %d (%d / %d)", zipFileInfo.fullname, chunk.length, chunkCopyLength, zipFileInfo.size ); if ( result === ProgressResult.USER_CANCELED ) { zipfile.close(); log.debug( "ZIP Uncompress - CANCEL" ); reject( "USER_CANCEL" ); return; } } callback( null, chunk ); } }); reportProgress._flush = (cb) => { cb(); zipfile.readEntry(); }; readStream.on( "error", (err) => { log.error( err ); reject( err ); }); pack.addReadStream( readStream.pipe(reportProgress), header.name, header.option ); }); } catch ( e ) { log.error( e ); reject( e ); } }); zipfile.on("error", (err) => { log.error( err ); zipfile.close(); reject( err ); }); zipfile.once("end", () => { zipfile.close(); resolve(); }); zipfile.readEntry(); }); }); } protected packEntry(file: File, header, stream: Readable, pack: yazl.ZipFile, reportProgress?: Transform): Promise<void> { return new Promise( (resolve, reject) => { if ( file.link ) { reject( `Unsupport link file - ${file.fullname}` ); return; } if ( file.dir ) { pack.addEmptyDirectory( header.name, header.option ); resolve(); } else { stream.on( "error", (err) => { log.error( err ); reject( err ); }); stream.on( "end", () => { resolve(); }); if ( reportProgress ) { stream = stream.pipe(reportProgress); } pack.addReadStream( stream, header.name, header.option ); } }); } protected convertFileToHeader( file: File, srcBaseDir: File, targetDir: string ) { const header: any = { name: file.orgname, option: { mtime: file.mtime, // mode: 0o100000 | convertAttrToStatMode(file) } }; if ( file.fstype === "file" ) { let orgFilename = file.fullname.substr(srcBaseDir.fullname.length); orgFilename = orgFilename.split(path.sep).join(path.posix.sep); header.name = path.posix.normalize(targetDir + orgFilename).replace( /^\//, ""); } return header; } private convertZipToFile(zipHeader: yauzl.Entry): File { const file = new File(); file.fstype = "archive"; const filename = this.decodeString(zipHeader.fileName); file.fullname = filename[0] !== "/" ? "/" + filename : filename; file.orgname = filename; file.name = path.basename(file.fullname); file.owner = ""; file.group = ""; file.uid = 0; file.gid = 0; file.mtime = zipHeader.getLastModDate(); file.ctime = zipHeader.getLastModDate(); file.root = this.originalFile.fullname; file.attr = filename[filename.length - 1] === "/" ? "drwxr-xr-x" : "-rw-r--r--"; file.dir = file.attr[0] === "d"; file.size = zipHeader.uncompressedSize; if ( zipHeader.extraFields ) { // .ZIP File Format Specification) // - https://pkware.cachefly.net/webdocs/casestudies/APPNOTE.TXT // - https://opensource.apple.com/source/zip/zip-6/unzip/unzip/proginfo/extra.fld zipHeader.extraFields.map( item => { if ( item.id === 0x7875 ) { // Info-ZIP New Unix Extra Field let offset = 0; const extraVer = item.data.readInt8(0); offset += 1; if (extraVer === 1) { const uidSize = item.data.readUInt8(offset); offset += 1; if (uidSize <= 6) { file.uid = item.data.readUIntLE(offset, uidSize); } offset += uidSize; const gidSize = item.data.readUInt8(offset); offset += 1; if (gidSize <= 6) { file.gid = item.data.readUIntLE(offset, gidSize); } } } else if ( item.id === 0x5455 ) { // extended timestamp let offset = 0; const timestampFields = item.data.readInt8(0); offset += 1; if (item.data.byteLength >= 5 && timestampFields & 1) { file.mtime = new Date(item.data.readUInt32LE(offset) * 1000); offset += 4; } if (item.data.byteLength >= 9 && timestampFields & 2) { file.atime = new Date(item.data.readUInt32LE(offset) * 1000); offset += 4; } if (item.data.byteLength >= 13 && timestampFields & 4) { file.ctime = new Date(item.data.readUInt32LE(offset) * 1000); } } else if ( item.id === 0x5855 || item.id === 0x000d ) { // "Info-ZIP UNIX (type 1)", "PKWARE Unix" let offset = 0; if (item.data.byteLength >= 8) { const atime = new Date(item.data.readUInt32LE(offset) * 1000); offset += 4; const mtime = new Date(item.data.readUInt32LE(offset) * 1000); offset += 4; file.atime = atime; file.mtime = mtime; if (item.data.byteLength >= 12) { file.uid = item.data.readUInt16LE(offset); offset += 2; file.gid = item.data.readUInt16LE(offset); offset += 2; } } } else if ( item.id === 0x7855 ) { // Info-ZIP Unix Extra Field (type 2) let offset = 0; if (item.data.byteLength >= 4) { file.uid = item.data.readUInt16LE(offset); offset += 2; file.gid = item.data.readUInt16LE(offset); } } else if ( item.id === 0x756e ) { // ASi Unix Extra Field let offset = 0; if (item.data.byteLength >= 14) { // eslint-disable-next-line prefer-const let crc = item.data.readUInt32LE(offset); offset += 4; const mode = item.data.readUInt16LE(offset); offset += 2; // eslint-disable-next-line prefer-const let sizdev = item.data.readUInt32LE(offset); offset += 4; file.uid = item.data.readUInt16LE(offset); offset += 2; file.gid = item.data.readUInt16LE(offset); offset += 2; this.convertUnixPermission(file, mode); if (item.data.byteLength > 14) { const start = offset; const end = item.data.byteLength - 14; const symlinkName = this.decodeString(item.data.slice(start, end)); if ( symlinkName ) { file.link = new FileLink( symlinkName, null ); } } } } else if ( item.id === 0x000a ) { // NTFS (Win9x/WinNT FileTimes) let offset = 4; if ( item.data.byteLength >= 24 + 4 + 4 ) { // eslint-disable-next-line prefer-const let tag1 = item.data.readUInt16LE(offset); offset += 2; // eslint-disable-next-line prefer-const let size1 = item.data.readUInt16LE(offset); offset += 2; const mtime = item.data.readBigInt64LE(offset); offset += 8; const atime = item.data.readBigInt64LE(offset); offset += 8; const ctime = item.data.readBigInt64LE(offset); try { // eslint-disable-next-line @typescript-eslint/ban-ts-comment // @ts-ignore const EPOCH_OFFSET = -116444736000000000n; const convertWin32Time = (time) => { // eslint-disable-next-line @typescript-eslint/ban-ts-comment // @ts-ignore return new Date(Number((time + EPOCH_OFFSET) / 10000n)); }; file.mtime = convertWin32Time(mtime); file.atime = convertWin32Time(atime); file.ctime = convertWin32Time(ctime); // eslint-disable-next-line no-empty } catch( e ) {} } } }); } log.debug( "File [%s] - ORG [%s]", file.fullname, filename); return file; } private convertUnixPermission( file: File, mode: number ) { const fileMode: string[] = file.attr ? file.attr.split("") : "----------".split(""); fileMode[1] = mode & fs.constants.S_IRUSR ? "r" : "-"; fileMode[2] = mode & fs.constants.S_IWUSR ? "w" : "-"; fileMode[3] = mode & fs.constants.S_IXUSR ? "x" : "-"; fileMode[4] = mode & fs.constants.S_IRGRP ? "r" : "-"; fileMode[5] = mode & fs.constants.S_IWGRP ? "w" : "-"; fileMode[6] = mode & fs.constants.S_IXGRP ? "x" : "-"; fileMode[7] = mode & fs.constants.S_IROTH ? "r" : "-"; fileMode[8] = mode & fs.constants.S_IWOTH ? "w" : "-"; fileMode[9] = mode & fs.constants.S_IXOTH ? "x" : "-"; file.attr = fileMode.join(""); } }
the_stack
import { camelCase, cloneDeep, maxBy, max, compact, sampleSize, round, sample, startCase } from "lodash-es"; import { randomNormalDistribution, strSimilarity } from "./util"; import { base62, debase62 } from "./lib/base62"; import { Polarity, RivenProperty, RivenDatabase, RivenPropertyDataBase, NormalMod, MainTag, WeaponDatabase, RivenTypes, Weapon } from "./codex"; import { HH } from "@/var"; import { i18n } from "@/i18n"; /** * 紫卡属性数值 */ export class ValuedRivenProperty { /** 属性原型 */ prop: RivenProperty; /** 基础值 */ baseValue: number; /** 偏差值 大约取值 0.89 ~ 1.11 -0.8 后 * 5000 精度为 -20.05 ~ +20.05 */ deviation: number; /** 位置值 */ upLevel: number; constructor(prop: RivenProperty, deviation: number, baseValue?: number, upLevel?: number, isValue?: boolean) { this.prop = prop; this.baseValue = baseValue; this.upLevel = upLevel; if (isValue) this.value = deviation; else this.deviation = deviation; } /** 获取属性id */ get id() { return this.prop.id; } /** 获取属性名称 */ get name() { return this.prop.name; } /** 获取属性显示数据 */ get displayValue() { let val = this.prop.nopercent ? this.value.toFixed(1) : this.value.toFixed(1) + "%"; if (val[0] != "-") return "+" + val; else return val; } /** 根据属性基础值计算属性偏差值 */ get value() { return this.deviation * this.baseValue * this.upLevel; } set value(val) { this.deviation = val / (this.baseValue * this.upLevel); } /** 数值范围 [下限, 上限] */ get range() { let val = this.baseValue * this.upLevel; return [+(val * 0.9).toFixed(1), +(val * 1.1).toFixed(1)]; } /** 获取偏差值显示数据 */ get displayDeviation() { let val = this.deviation * 100 - 100, tex = val.toFixed(1) + "%"; if (Math.abs(val) < 0.2) return ""; if (tex[0] != "-") return "+" + tex; return tex; } } export class RivenMod { /** 武器ID */ name: string; /** 等级 */ level: number = 8; /** 极性 */ polarity: Polarity; /** 根据卡面所带来的位置值 一共4种 0.755 | 1 | 0.942 | 1.243 分别代表 3+; 2+; 3+1-; 2+1- */ upLevel = 1; /** 负面位置值 */ negativeUpLevel = -0.755; /** 属性列表 */ properties: ValuedRivenProperty[] = []; /** 是否有负面属性 */ hasNegativeProp: boolean; /** 循环次数 */ recycleTimes = 0; /** 段位 */ rank: number; /** 类型 */ mod: RivenTypes; /** 后缀 */ private _subfix: string; get subfix(): string { if (this._subfix) return this._subfix; else { let props = this.properties.map(v => v.prop.id); if (this.hasNegativeProp) props.pop(); this.shortSubfix = props.join(""); return this._subfix; } } set subfix(value: string) { this._subfix = value; } get readableSubfix() { return this.properties.map(v => (v.upLevel < 0 ? "-" : "") + i18n.t(`prop.shortName.${v.id}`)).join(""); } /** 本地化ID */ get id() { return `messages.${camelCase(this.name)}`; } /** 本地化名称 */ get locName() { return i18n.te(this.id) ? i18n.t(this.id) : this.name; } /** 全名 如: 西诺斯 Critacan*/ get fullLocName() { return this.locName + " " + this.subfix; } /** 英文全名 如: Cernos Critacan*/ get fullName() { return this.name + " " + this.subfix; } set fullName(value) { let v = value.split(" "); this.name = v[0]; this.subfix = v[1]; } get weapon() { return WeaponDatabase.getWeaponByName(this.name); } get weapons() { return WeaponDatabase.getWeaponsByBase(this.name); } get ratio() { return this.weapon.disposition; } get star() { return this.weapon.star; } get starText() { return this.weapon.starText; } constructor(parm?: string | RivenMod, base64 = false) { if (typeof parm === "string") { if (parm.indexOf("|") >= 0) this.qrCode = parm; else if (base64) this.qrCodeBase64 = parm; else this.parseString(parm); } else if (parm) { this.name = parm.name; this.subfix = parm.subfix; this.level = parm.level; this.polarity = parm.polarity; this.upLevel = parm.upLevel; this.negativeUpLevel = parm.negativeUpLevel; this.properties = cloneDeep(parm.properties); this.hasNegativeProp = parm.hasNegativeProp; this.recycleTimes = parm.recycleTimes; this.rank = parm.rank; this.mod = MainTag[parm.weapon.mod] as RivenTypes; } } /** * 读取OCR识别的MOD文本 * @param modText MOD文本 */ parseString(modText: string) { /* 示例输入: 多克拉姆 Pleci-loctitis +78.6%暴击伤害 滑行攻击有+89.2%的几率 造成暴击。 +106.6%攻击范围 -34.9%对Infested伤害 A段位12023 */ this.name = ""; this.hasNegativeProp = false; this.rank = this.recycleTimes = 0; let lines = modText .replace(/\n([A-Za-z\u4e00-\u9fa5。]+)\n/g, (m, r1) => r1 + "\n") .replace(/((\S*?)\s(\S*?))|(\(\S*?)\s(\S*?\))/g, "$1$2$3$4") .replace("·", "-") .replace(/lgni/g, "Igni") .split(/\r?\n+|\b \b/g) .reduce((r, v) => { console.log(JSON.stringify(v), /^\w+$/.test(v)); if (r.length && /^\w+$/.test(v)) { r[r.length - 1] = r[r.length - 1] + " " + v; return r; } return [...r, v]; }, []); let subfixIndex = lines.findIndex(v => v.match(RivenDatabase.PrefixAll) != null); if (subfixIndex < 0) return new Error("紫卡属性识别错误: 找不到后缀"); else { let idt = lines[subfixIndex].match(RivenDatabase.PrefixAll).index; if (idt > 0) { let subfix = lines[subfixIndex].substr(idt).trim(); lines[subfixIndex] = lines[subfixIndex].substr(0, idt).trim(); lines.splice(++subfixIndex, 0, subfix); } } console.log("lines=>", lines, lines[subfixIndex]); let rawName = lines[(subfixIndex || 1) - 1]; // 查询名称最接近的武器 let weapon = WeaponDatabase.findMostSimRivenWeapon(rawName); this.mod = MainTag[weapon.mod] as RivenTypes; this.subfix = lines[subfixIndex]; // 识别到的名字是否正确, 否则模糊匹配 this.name = weapon.name; // 获取后缀属性 let rivenProps = this.parseSubfix(this.subfix, this.mod); let propRegExp = /([+\-]?\d+(?:\.\d+)?)%? *.*?([A-Zc\u4e00-\u9fa5]\D+)/; let properties: [RivenProperty, number][] = []; for (let i = subfixIndex + 1; i < lines.length; i++) { let propLine = lines[i].match(propRegExp); if (properties.length < 4 && !this.hasNegativeProp && propLine) { // 如果后缀已识别则优先使用(只识别一定次数) let prop = (i <= subfixIndex + ((rivenProps && rivenProps.length) || 0) && rivenProps && maxBy(rivenProps, v => { let s = max([strSimilarity(v[0].name, propLine[2]), strSimilarity(v[0].eName, propLine[2])]); // console.log("strSimilarity: ", v[0].name, propLine[2], "s=", s); return s; })[0]) || // 识别到的属性是否正确, 否则模糊匹配 RivenDatabase.findMostSimProp(propLine[2]); // 判断前缀不是+或者-就加上- let propValue = +(v => (v[0] != "-" && v[0] != "+" ? -v : v))(propLine[1]); // console.log(propLine[0], "prop=", prop, "propValue=", propValue); // 对于只有正面的属性去除负号 if (prop.onlyPositive && propValue < 0) propValue = -propValue; // 检测负属性 if ((prop.negative ? -propValue : propValue) < 0) this.hasNegativeProp = true; // 如果有4条则最后一个一定是负 else if (properties.length === 3) { propValue = -propValue; this.hasNegativeProp = true; } if (properties.length > 3) { console.log("[ERR]more than 4 properties found", [prop.name, prop, propValue]); continue; } // 将属性值加入 properties.push([prop, propValue]); } else { // 识别段位和重roll次数 let extra = compact(lines[i].split(/\D+/g)); this.rank = (extra[0] && +extra[0]) || 0; this.recycleTimes = (extra[1] && +extra[1]) || 0; if (this.recycleTimes == 0 && this.rank > 100) { // 1003变成10 3 let str = this.rank.toFixed(); // 万一紫卡就出到20段了呢 if (str.startsWith("1") || str.startsWith("2")) { this.rank = +str.substr(0, 2); this.recycleTimes = +str.substr(3); } else { this.rank = +str.substr(0, 1); this.recycleTimes = +str.substr(2); } } } } // console.log(lines); // console.log(this.hasNegativeProp, properties); if (properties.length > (this.hasNegativeProp ? 4 : 3)) return new Error("紫卡属性识别错误: 正面属性过多"); // 计算upLevel // 3+1- = [4-3]>> 1 // 3+ = [3-1]>>2 // 2+ = [2-1]>>1 // 2+1- = [3-3]>>0 this.upLevel = toUpLevel(properties.length, this.hasNegativeProp); this.negativeUpLevel = -toNegaUpLevel(properties.length, this.hasNegativeProp); // 写入属性 this.parseProps(properties.map(v => [v[0].id, v[1]] as [string, number])); return; } /** * 识别后缀 * @param subfix 后缀 * @param stype MOD类型 */ parseSubfix(subfix: string, stype: string): [RivenProperty, string][] { if (!subfix) return; let rst = subfix.toLowerCase().match(RivenDatabase.PropRegExps[stype]); if (rst) { let fixs = rst.slice(rst[1] ? 1 : 2, 4); return fixs.map((v, i): [RivenProperty, string] => [RivenPropertyDataBase[stype].find(p => v == p[i < fixs.length - 1 ? "prefix" : "subfix"]), v]); } return; } /** * 识别普通MOD格式的属性 */ parseProps(props: [string, number][], weapon = this.weapon) { this.hasNegativeProp = props.reduce((r, v, i) => { let prop = RivenDatabase.getPropByName(v[0]); const isNegative = i >= 3 || !prop.negative == v[1] < 0; if (isNegative) return true; return r; }, false); this.upLevel = toUpLevel(props.length, this.hasNegativeProp); this.negativeUpLevel = -toNegaUpLevel(props.length, this.hasNegativeProp); this.properties = props.map((v, i) => { let prop = RivenDatabase.getPropByName(v[0]); const isNegative = i >= 3 || !prop.negative === v[1] < 0; const base = weapon.getPropBaseValue(prop.name); const up = isNegative ? this.negativeUpLevel : this.upLevel; return new ValuedRivenProperty(prop, v[1], base, up, true); }); } /** * 识别偏差值数据 */ parseDevis(props: [string, number][]) { const weapon = this.weapon; this.hasNegativeProp = props.length > this.shortSubfix.length; this.upLevel = toUpLevel(props.length, this.hasNegativeProp); this.negativeUpLevel = -toNegaUpLevel(props.length, this.hasNegativeProp); this.properties = props.map((v, i) => { let prop = RivenDatabase.getPropByName(v[0]); const base = weapon.getPropBaseValue(prop.name); const up = this.hasNegativeProp && i === props.length - 1 ? this.negativeUpLevel : this.upLevel; return new ValuedRivenProperty(prop, v[1], base, up); }); } /** * 随机化所有 */ random(stype: string = "") { let db = WeaponDatabase.protos.filter(v => v.disposition > 0); let data = stype ? db.filter(v => v.mod === MainTag[stype]) : db; let { name, mod } = data[~~(Math.random() * data.length)]; let rank = ~~(Math.random() * 8) + 9; [this.name, this.mod, this.rank, this.recycleTimes] = [name, MainTag[mod] as RivenTypes, rank, 0]; this.randomProp(); } /** * 只随机化属性 */ randomProp() { this.subfix = ""; let count = ~~(Math.random() * 2) + 2; this.hasNegativeProp = ~~(Math.random() * 2) > 0; let totalCount = count + (this.hasNegativeProp ? 1 : 0); this.upLevel = toUpLevel(totalCount, this.hasNegativeProp); this.negativeUpLevel = -toNegaUpLevel(totalCount, this.hasNegativeProp); // 偏差值 正态分布 标准差=5 let devi = () => (100 + 5 * randomNormalDistribution()) / 100; const weapon = this.weapon; // console.log(weapon, RivenPropertyDataBase[this.mod]); let props = sampleSize( RivenPropertyDataBase[this.mod].filter(v => !v.onlyNegative), count ).map(v => [v.id, round(devi() * this.upLevel * weapon.getPropBaseValue(v.id), 1)]) as [string, number][]; if (this.hasNegativeProp) { let neProp = sample(RivenPropertyDataBase[this.mod].filter(v => !v.onlyPositive && props.every(k => k[0] !== v.id))); props.push([neProp.id, round(devi() * this.negativeUpLevel * weapon.getPropBaseValue(neProp.id), 1)]); } this.parseProps(props); } /** * 模拟洗卡 * @return newMod RivenMod */ reroll() { ++this.recycleTimes; let newMod = new RivenMod(this); newMod.randomProp(); return newMod; } /** 返回一个标准MOD对象 */ normalMod(weapon: Weapon): NormalMod { const ratio = weapon.disposition && this.weapon.disposition ? weapon.disposition / this.weapon.disposition : 1; return new NormalMod({ key: "01", id: this.fullName, name: this.fullLocName, type: this.name, polarity: this.polarity || "r", cost: 10, level: 8, rarity: "x", props: this.properties.map(v => [v.prop.id, (ratio * v.value) / 9] as [string, number]), riven: this.qrCode, }); } /** 短后缀 */ get shortSubfix() { let subs = this.parseSubfix(this.subfix, this.mod); if (subs) return subs.map(v => v[0].id).join(""); return ""; } set shortSubfix(value) { let props = value.split("").map(v => RivenDatabase.getPropByName(v)); if (props.length === 3) this.subfix = startCase(props[0].prefix) + "-" + props[1].prefix + props[2].subfix; else if (props.length === 2) this.subfix = startCase(props[0].prefix) + props[1].subfix; } /** 返回二维码使用的序列化字符串 */ get qrCode() { return [ this.name, this.shortSubfix, base62(this.rank) + base62(this.recycleTimes), this.properties.map(v => v.prop.id + base62(+(v.deviation * 5000 - 4000).toFixed(0))).join("."), ].join("|"); } /** 读取二维码识别后的序列化字符串 */ set qrCode(value) { let d = value.split("|"); if (!d[0]) return; this.name = d[0]; if (d[1]) this.shortSubfix = d[1]; let weapon = WeaponDatabase.getWeaponByName(this.name); this.name = weapon.name; this.mod = MainTag[weapon.mod] as RivenTypes; this.rank = debase62(d[2][0]); this.recycleTimes = debase62(d[2].substr(1)); let props = d[3].split(".").map(v => { let vv = (debase62(v.substr(1)) + 4000) / 5000; return [RivenDatabase.getPropByName(v[0]), vv]; }) as [RivenProperty, number][]; let lastProp = props[props.length - 1]; this.hasNegativeProp = props.length === 4 || !lastProp[0].negative === lastProp[1] < 0; this.upLevel = toUpLevel(props.length, this.hasNegativeProp); this.negativeUpLevel = -toNegaUpLevel(props.length, this.hasNegativeProp); this.parseDevis(props.map(([n, v]) => [n.id, v] as [string, number])); } get qrCodeV1() { return [ this.name, this.shortSubfix, base62(this.rank) + base62(this.recycleTimes), this.properties.map(v => v.prop.id + base62(+(v.deviation * 10).toFixed(0))).join("."), ].join("|"); } /** 读取二维码识别后的序列化字符串 */ set qrCodeV1(value) { let d = value.split("|"); if (!d[0]) return; this.name = d[0]; if (d[1]) this.shortSubfix = d[1]; let weapon = WeaponDatabase.getWeaponByName(this.name); this.name = weapon.name; this.mod = MainTag[weapon.mod] as RivenTypes; this.rank = debase62(d[2][0]); this.recycleTimes = debase62(d[2].substr(1)); let props = d[3].split(".").map(v => { let vv = debase62(v.substr(1)) / 10; return [RivenDatabase.getPropByName(v[0]), vv]; }) as [RivenProperty, number][]; let lastProp = props[props.length - 1]; this.hasNegativeProp = props.length === 4 || !lastProp[0].negative == lastProp[1] < 0; this.upLevel = toUpLevel(props.length, this.hasNegativeProp); this.parseProps(props.map(([n, v]) => [n.id, v] as [string, number])); } /** Base64形式的二维码 */ get qrCodeBase64() { return btoa(this.qrCode); } set qrCodeBase64(value) { this.qrCode = atob(value); } get qrCodeBase64V1() { return btoa(this.qrCodeV1); } set qrCodeBase64V1(value) { this.qrCodeV1 = atob(value); } /** 网址形式的二维码 */ get qrCodeURL() { return `https://${HH}/riven/` + this.qrCodeBase64; } set qrCodeURL(value) { this.qrCodeBase64 = value.replace(`https://${HH}/riven/`, ""); } /** 返回完整的modText */ get modText() { return [this.fullLocName, ...this.properties.map(v => v.displayValue + v.name), this.rank + "O" + this.recycleTimes].join("\n"); } set modText(value) { this.parseString(value); } } export function toUpLevel(len: number, nega: boolean) { return [1.243, 0.942, 1, 0.755][len - (nega ? 3 : 0)]; } export function toNegaUpLevel(len: number, nega: boolean) { return [0.5, 0.755, 1, 1][len - (nega ? 3 : 0)]; }
the_stack
import { BoardType, Space, SpaceSubtype, EventExecutionType, GameVersion, EventCodeLanguage, EditorEventActivationType, CostumeType } from "./types"; import { copyObject } from "./utils/obj"; import { ICustomEvent } from "./events/customevents"; import { getEvent, IEventParameter, EventParameterValues } from "./events/events"; import { getAdapter, getROMAdapter } from "./adapter/adapters"; import { boardsChanged, clearUndoHistory, currentBoardChanged, getAppInstance } from "./app/appControl"; import { IDecisionTreeNode } from "./ai/aitrees"; import defaultThemeBoardSelect from "./img/themes/default/boardselect.png"; import defaultThemeBoardSelectIcon from "./img/themes/default/boardselecticon.png"; import defaultThemeBoardLogo from "./img/themes/default/boardlogo.png"; import defaultThemeBoardLogoText from "./img/themes/default/boardlogotext.png"; import defaultThemeLargeScene from "./img/themes/default/largescene.png"; import defaultThemeConversation from "./img/themes/default/conversation.png"; import defaultThemeSplashscreen from "./img/themes/default/splashscreen.png"; import defaultThemeBg from "./img/themes/default/bg.png"; import defaultThemeBg2 from "./img/themes/default/bg2.png"; import { store } from "./app/store"; import { addAdditionalBackgroundAction, addAnimationBackgroundAction, addBoardAction, addConnectionAction, addEventToBoardAction, addEventToSpaceAction, addSpaceAction, clearBoardsFromROMAction, copyCurrentBoardAction, deleteBoardAction, EventMap, excludeEventFromBoardAction, includeEventInBoardAction, removeAdditionalBackgroundAction, removeAnimationBackgroundAction, removeEventFromBoardAction, removeEventFromSpaceAction, removeSpaceAction, selectBoards, selectCurrentBoard, selectCurrentBoardIndex, selectCurrentBoardIsROM, selectData, selectROMBoards, setAdditionalBackgroundCodeAction, setAudioSelectCodeAction, setBackgroundAction, setBoardAudioAction, setBoardCostumeTypeIndexAction, setBoardDescriptionAction, setBoardDifficultyAction, setBoardNameAction, setBoardOtherBgAction, setCurrentBoardAction, setSpaceHostsStarAction, setSpaceRotationAction, } from "./app/boardState"; import { assert } from "./utils/debug"; import { getEventsInLibrary } from "./events/EventLibrary"; const _themes = { default: { boardselect: defaultThemeBoardSelect, boardselecticon: defaultThemeBoardSelectIcon, boardlogo: defaultThemeBoardLogo, boardlogotext: defaultThemeBoardLogoText, largescene: defaultThemeLargeScene, conversation: defaultThemeConversation, splashscreen: defaultThemeSplashscreen, bg: defaultThemeBg, bg2: defaultThemeBg2 }, }; export interface IBoard { name: string; description: string; game: GameVersion; type: BoardType; difficulty: number; spaces: ISpace[]; links: { [startingSpaceIndex: number]: (number | number[]) }; events: { [name: string]: IBoardEvent | string }; boardevents?: IEventInstance[]; bg: IBoardBgDetails; otherbg: { boardselect?: string, boardselecticon?: string, boardlogo?: string, boardlogotext?: string, largescene?: string, conversation?: string, splashscreen?: string, }; animbg?: string[]; additionalbg?: string[]; additionalbgcode?: IBoardEvent | string; audioType?: BoardAudioType; audioIndex?: number; audioData?: IBoardAudioData[]; audioSelectCode?: IBoardEvent; costumeTypeIndex?: CostumeType; _rom?: boolean; _deadSpace?: number; } /** Type of board audio. */ export enum BoardAudioType { /** Song from the original game. */ InGame = 0, /** Song provided by the user. */ Custom = 1, } export interface IBoardAudioData { name: string; data: string; soundbankIndex: number; } export interface IBoardEvent { language: EventCodeLanguage; code: string; } interface IBoardImage { width: number; height: number; src: string; // sometimes boolean inside this file. } interface IBoardBgDetails extends IBoardImage { fov: number; scaleFactor: number; cameraEyePosX: number; cameraEyePosY: number; cameraEyePosZ: number; lookatPointX: number; lookatPointY: number; lookatPointZ: number; } export interface ISpace { x: number; y: number; z: number; rotation?: number; type: Space; subtype?: SpaceSubtype; events?: IEventInstance[]; star?: boolean; aiTree?: IDecisionTreeNode[]; } /** The subset of an IEvent that is kept on a space in the board. */ export interface IEventInstance { id: string; activationType: EditorEventActivationType; executionType: EventExecutionType; parameterValues?: EventParameterValues; custom?: boolean; } export function _makeDefaultBoard(gameVersion: 1 | 2 | 3 = 1, type: BoardType = BoardType.NORMAL): IBoard { const board: any = { name: "Untitled", description: "Use your Star Power to finish\nthis board.", game: gameVersion, type: type, difficulty: 3, spaces: [], links: {}, events: {}, audioType: BoardAudioType.InGame, }; switch (gameVersion) { case 1: board.bg = { "width": 960, "height": 720, "src": true, // Replaced with theme url later. fov: 17, scaleFactor: 1, cameraEyePosX: 0, cameraEyePosY: 1355, cameraEyePosZ: 1780, lookatPointX: 0, lookatPointY: 0, lookatPointZ: 0, }; board.otherbg = { boardselect: true, // Replaced with theme url later. boardlogo: true, largescene: true, conversation: true, splashscreen: true, }; board.audioIndex = 0x18; // Mambo! break; case 2: board.bg = { width: 1152, height: 864, src: true, fov: 3, scaleFactor: 0.1, cameraEyePosX: 0, cameraEyePosY: 1570, cameraEyePosZ: 1577, lookatPointX: 0, lookatPointY: 0, lookatPointZ: 0, }; board.animbg = []; board.otherbg = { boardselect: true, boardselecticon: true, boardlogo: true, largescene: true, }; board.audioIndex = 0x36; // Mini-Game Stadium board.costumeTypeIndex = CostumeType.NORMAL; break; case 3: switch (type) { case BoardType.NORMAL: board.bg = { width: 1152, height: 864, src: true, fov: 15, scaleFactor: 0.1, cameraEyePosX: 0, cameraEyePosY: 300, cameraEyePosZ: 300, lookatPointX: 0, lookatPointY: 0, lookatPointZ: 0, }; board.audioIndex = 0x29; // VS Millenium Star! break; case BoardType.DUEL: board.bg = { width: 896, height: 672, src: true, fov: 15, scaleFactor: 0.1, cameraEyePosX: 0, cameraEyePosY: 210, cameraEyePosZ: 210, lookatPointX: 0, lookatPointY: 0, lookatPointZ: 0, }; board.audioIndex = 0; // TODO break; } board.otherbg = { boardselect: true, boardlogo: true, boardlogotext: true, largescene: true, }; break; } if (type === BoardType.DUEL) { board.spaces.push({ x: 200, y: 200, type: Space.DUEL_START_BLUE }); board.spaces.push({ x: board.bg.width - 200, y: board.bg.height - 200, type: Space.DUEL_START_RED }); } else { board.spaces.push({ x: board.bg.width - 200, y: board.bg.height - 200, type: Space.START }); } applyTheme(board); return board; } function applyTheme(board: IBoard, name: "default" = "default") { const themeImages = _themes[name]; if (board.otherbg.boardselect) board.otherbg.boardselect = themeImages.boardselect; if (board.otherbg.boardselecticon) board.otherbg.boardselecticon = themeImages.boardselecticon; if (board.otherbg.boardlogo) board.otherbg.boardlogo = themeImages.boardlogo; if (board.otherbg.boardlogotext) board.otherbg.boardlogotext = themeImages.boardlogotext; if (board.otherbg.largescene) board.otherbg.largescene = themeImages.largescene; if (board.otherbg.conversation) board.otherbg.conversation = themeImages.conversation; if (board.otherbg.splashscreen) board.otherbg.splashscreen = themeImages.splashscreen; switch (board.game) { case 1: board.bg.src = themeImages.bg; break; case 2: case 3: board.bg.src = themeImages.bg2; break; } } /** * Adds a board to the board collection. * @param board The board to add. If not passed, a default board is generated. * @param opts.rom The board is from the ROM * @param opts.type Board type to use * @param opts.game Game version for the board * @returns The index of the inserted board. */ export function addBoard(board?: IBoard | null, opts: { rom?: boolean, game?: 1 | 2 | 3, type?: BoardType } = {}) { if (!board) board = _makeDefaultBoard(opts.game || 1, opts.type || BoardType.NORMAL); if (opts.rom) { board._rom = true; } _fixPotentiallyOldBoard(board); store.dispatch(addBoardAction({ board, rom: opts.rom })); const app = getAppInstance(); if (app) boardsChanged(); const storeData = selectData(store.getState()); const collection = opts.rom ? storeData.romBoards : storeData.boards; return collection.length - 1; } export function getCurrentBoard(): IBoard { let board = selectCurrentBoard(store.getState()); return board; } export function indexOfBoard(board: IBoard) { return selectBoards(store.getState()).indexOf(board); } export function setCurrentBoard(index: number, isRom?: boolean) { store.dispatch(setCurrentBoardAction({ index, rom: !!isRom })) currentBoardChanged(); } export function boardIsROM(board: IBoard) { return !!board._rom; } /** * Tests if there is a connection from startIdx to endIdx. * If endIdx is "*"" or not passed, test if any connection is outbound from startIdx. */ export function hasConnection(startIdx: number, endIdx: number | "*", board: IBoard = getCurrentBoard()) { if (Array.isArray(board.links[startIdx])) { if (endIdx === "*" || endIdx === undefined) return true; // Asking if any connections exist out of startIdx return (board.links[startIdx] as number[]).indexOf(endIdx) >= 0; } if (board.links[startIdx] !== undefined && board.links[startIdx] !== null) { if (endIdx === "*" || endIdx === undefined) return true; return board.links[startIdx] === endIdx; } return false; } interface ForEachEventCallback { (event: IEventInstance, eventIndex: number, space?: ISpace, spaceIndex?: number): void; } export function forEachEvent(board: IBoard, fn: ForEachEventCallback) { if (board.boardevents) { // Reverse to allow deletion in callback. for (let i = board.boardevents.length - 1; i >= 0; i--) { const event = board.boardevents[i]; fn(event, i); } } const spaces = board.spaces; if (spaces && spaces.length) { for (let s = 0; s < spaces.length; s++) { const space = spaces[s]; if (space.events && space.events.length) { for (let i = space.events.length - 1; i >= 0; i--) { const event = space.events[i]; fn(event, i, space, s); } } } } } interface ForEachEventParameterCallback { (param: IEventParameter, event: IEventInstance, eventIndex: number, space?: ISpace, spaceIndex?: number): void; } export function forEachEventParameter(board: IBoard, eventLibrary: EventMap, fn: ForEachEventParameterCallback) { forEachEvent(board, (eventInstance, eventIndex, space, spaceIndex) => { const event = getEvent(eventInstance.id, board, eventLibrary); assert(!!event); if (event.parameters) { for (let p = 0; p < event.parameters.length; p++) { const parameter = event.parameters[p]; fn(parameter, eventInstance, eventIndex, space, spaceIndex); } } }); } /** Adds an event to be executed during specific moments. */ export function addEventToBoard(event: IEventInstance) { store.dispatch(addEventToBoardAction({ event })); } /** Removes an event from `boardevents`. */ export function removeEventFromBoard(eventIndex: number) { store.dispatch(removeEventFromBoardAction({ eventIndex })); } export function addEventToSpace(event: IEventInstance, toStart?: boolean) { store.dispatch(addEventToSpaceAction({ event, toStart })); } export function addEventToSpaceInternal( board: IBoard, space: ISpace, event: IEventInstance, toStart: boolean, eventLibrary: EventMap ) { space.events = space.events || []; if (event) { if (toStart) space.events.unshift(event); else space.events.push(event); if (event.custom) { const customEvent = getEvent(event.id, board, eventLibrary) as ICustomEvent; includeEventInBoardInternal(board, customEvent); } } } export function removeEventFromSpace(eventIndex: number) { store.dispatch(removeEventFromSpaceAction({ eventIndex })); } export function getBoardEvent(board: IBoard, eventId: string): IBoardEvent | null { if (board.events) { const boardEvent = board.events[eventId]; if (typeof boardEvent === "string") { return { language: EventCodeLanguage.MIPS, code: boardEvent }; } return boardEvent || null; } return null; } /** Includes an event in the collection of events kept within the board file. */ export function includeEventInBoard(event: ICustomEvent) { store.dispatch(includeEventInBoardAction({ event })); } export function includeEventInBoardInternal(board: IBoard, event: ICustomEvent) { if (!event.asm) throw new Error(`Attempting to add event ${event.name} but it doesn't have code`); board.events[event.name] = { language: event.language!, code: event.asm, }; } /** Removes an event from the collection of events stored in the board file. */ export function excludeEventFromBoard(eventId: string): void { store.dispatch(excludeEventFromBoardAction({ eventId })); } export function getAdditionalBackgroundCode(board: IBoard): IBoardEvent | null { if (board.additionalbgcode) { let additionalBgCode = board.additionalbgcode; if (typeof additionalBgCode === "string") { return { language: EventCodeLanguage.MIPS, code: additionalBgCode }; } return additionalBgCode || null; } return null; } export function setAdditionalBackgroundCode(code: string, language: EventCodeLanguage): void { store.dispatch(setAdditionalBackgroundCodeAction({ code, language })); } export function getAudioSelectCode(board: IBoard): IBoardEvent | null { return board.audioSelectCode || null; } export function setAudioSelectCode(code: string, language: EventCodeLanguage): void { store.dispatch(setAudioSelectCodeAction({ code, language })); } export function getDeadEnds(board: IBoard) { const deadEnds: number[] = []; let spaces = _getSpacesCopy(board); function _getSpacesCopy(board: IBoard) { return copyObject(board.spaces); } function _checkDeadEnd(spaceIndex: number): boolean | undefined { if (spaces[spaceIndex]._seen) return false; // We have reached a previous space - no dead end. if (!board.links.hasOwnProperty(spaceIndex)) { deadEnds.push(spaceIndex); return true; } spaces[spaceIndex]._seen = true; let nextSpaces = board.links[spaceIndex]; let result; if (Array.isArray(nextSpaces)) { for (var i = 0; i < nextSpaces.length; i++) { result = _checkDeadEnd(nextSpaces[i]); if (result) return result; } } else { result = _checkDeadEnd(nextSpaces); if (result) return result; } } // Build a reverse lookup of space to _pointing_ spaces. var pointingMap: { [index: number]: number[] } = {}; for (let s = 0; s < spaces.length; s++) { if (spaces[s]) pointingMap[s] = []; } for (let startIdx in board.links) { let ends = getConnections(parseInt(startIdx), board)!; ends.forEach(end => { pointingMap[end].push(Number(startIdx)); }); } // Returns true if the given space is linked to from another space besides // the previous space. function spaceIsLinkedFromByAnother(spaceIdx: number, prevIdx?: number) { // If no previous index passed, just see if anything points. if (prevIdx === undefined) return !!pointingMap[spaceIdx].length; if (!pointingMap[spaceIdx].length) return false; if (pointingMap[spaceIdx].indexOf(Number(prevIdx)) === -1) return true; if (pointingMap[spaceIdx].length > 1) return true; // Assumes prevIdx is not duplicated return false; // length === 1 && only entry is prevIdx } let startIdx = getStartSpaceIndex(board); if (startIdx >= 0) _checkDeadEnd(startIdx); for (let s = 0; s < spaces.length; s++) { if (!spaces[s]) continue; if (spaces[s]._seen) continue; // Don't even need to check, we already visited it. // The latter condition is not totally necessary, but I don't know that // we want to or can handle single-space chains. if (!spaceIsLinkedFromByAnother(s) && hasConnection(s, null as any, board)) { // FIXME: passing null? _checkDeadEnd(s); } } return deadEnds; } export function _fixPotentiallyOldBoard(board: IBoard): IBoard { if (!("game" in board)) { board.game = 1; } if (!("type" in board)) { board.type = BoardType.NORMAL; } if (!("events" in board)) { board.events = {}; } for (const eventId in board.events) { const eventData = board.events[eventId]; if (typeof eventData === "string") { board.events[eventId] = { code: eventData, language: EventCodeLanguage.MIPS, }; } } if (typeof board.audioType === "undefined") { board.audioType = BoardAudioType.InGame; } if (board.audioData && !Array.isArray(board.audioData)) { board.audioData = [(board as any).audioData]; } if (board.game === 2 && typeof board.costumeTypeIndex !== "number") { board.costumeTypeIndex = CostumeType.NORMAL; } _migrateOldCustomEvents(board); if (!("fov" in board.bg)) { switch (board.game) { case 3: if (board.type === BoardType.DUEL) { Object.assign(board.bg, { fov: 15, scaleFactor: 0.1, cameraEyePosX: 0, cameraEyePosY: 210, cameraEyePosZ: 210, lookatPointX: 0, lookatPointY: 0, lookatPointZ: 0, }); } else { Object.assign(board.bg, { fov: 15, scaleFactor: 0.1, cameraEyePosX: 0, cameraEyePosY: 300, cameraEyePosZ: 300, lookatPointX: 0, lookatPointY: 0, lookatPointZ: 0, }); } break; case 2: Object.assign(board.bg, { fov: 3, scaleFactor: 0.1, cameraEyePosX: 0, cameraEyePosY: 1570, cameraEyePosZ: 1577, lookatPointX: 0, lookatPointY: 0, lookatPointZ: 0, }); break; case 1: Object.assign(board.bg, { fov: 17, scaleFactor: 1, cameraEyePosX: 0, cameraEyePosY: 1355, cameraEyePosZ: 1780, lookatPointX: 0, lookatPointY: 0, lookatPointZ: 0, }); break; } } return board; } function _migrateOldCustomEvents(board: IBoard) { forEachEvent(board, (spaceEvent: IEventInstance) => { // Unnecessary properties of space events. if ("parameters" in spaceEvent) { delete (spaceEvent as any).parameters; } if ("supportedGames" in spaceEvent) { delete (spaceEvent as any).supportedGames; } // Move any asm into the single collection. if ((spaceEvent as ICustomEvent).asm) { spaceEvent.id = (spaceEvent as any).name; if (board.events[spaceEvent.id] && (board.events[spaceEvent.id] !== (spaceEvent as ICustomEvent).asm)) { console.warn(`When updating the format of ${board.name}, event ${spaceEvent.id} had multiple versions. Only one will be kept.`); } board.events[spaceEvent.id] = (spaceEvent as ICustomEvent).asm; delete (spaceEvent as any).asm; } }); } export function getCurrentBoardIndex() { return selectCurrentBoardIndex(store.getState()); } export function currentBoardIsROM() { return selectCurrentBoardIsROM(store.getState()); } export function getBoardCount() { return selectBoards(store.getState()).length; } export function getBoards() { return selectBoards(store.getState()); } export function getROMBoards() { return selectROMBoards(store.getState()); } export function setBG(bg: string) { store.dispatch(setBackgroundAction({ bg })); } export function addAnimBG(bg: string) { store.dispatch(addAnimationBackgroundAction({ bg })); } export function removeAnimBG(index: number) { store.dispatch(removeAnimationBackgroundAction({ index })); } export function supportsAnimationBackgrounds(board: IBoard): boolean { return board.game === 2; } export function addAdditionalBG(bg: string) { store.dispatch(addAdditionalBackgroundAction({ bg })); } export function removeAdditionalBG(index: number) { store.dispatch(removeAdditionalBackgroundAction({ index })); } export function supportsAdditionalBackgrounds(board: IBoard): boolean { return board.game !== 2; } export function addDecisionTree(board: IBoard, spaceIndex: number, tree: IDecisionTreeNode[]): void { // board.spaces[spaceIndex].aiTree = tree; } export function deleteBoard(boardIndex: number) { store.dispatch(deleteBoardAction({ boardIndex })); boardsChanged(); currentBoardChanged(); } export function copyCurrentBoard(makeCurrent?: boolean): void { store.dispatch(copyCurrentBoardAction({ makeCurrent })); boardsChanged(); } export function setBoardName(name: string): void { store.dispatch(setBoardNameAction({ name })); } export function setBoardDescription(description: string): void { store.dispatch(setBoardDescriptionAction({ description })); } export function setBoardDifficulty(difficulty: number): void { store.dispatch(setBoardDifficultyAction({ difficulty })); } export function setBoardCostumeTypeIndex(costumeType: CostumeType): void { store.dispatch(setBoardCostumeTypeIndexAction({ costumeType })); } export function setBoardOtherBackground(name: keyof IBoard["otherbg"], value: string): void { store.dispatch(setBoardOtherBgAction({ name, value })); } export function setHostsStar(spaceIndices: number[], hostsStar: boolean): void { store.dispatch(setSpaceHostsStarAction({ spaceIndices, hostsStar })); } export interface IBoardAudioChanges { audioType?: BoardAudioType; gameAudioIndex?: number; customAudioIndex?: number; midiName?: string; midiData?: string; soundbankIndex?: number; delete?: boolean; } export function setBoardAudio(audioChanges: IBoardAudioChanges): void { store.dispatch(setBoardAudioAction({ audioChanges })); } export function addSpace(x: number, y: number, type: Space, subtype?: SpaceSubtype, board?: IBoard): number { // Hack for callers not editing redux state. if (board) { return addSpaceInternal(x, y, type, subtype, board, getEventsInLibrary()); } else { const newIndex = getCurrentBoard().spaces.length; store.dispatch(addSpaceAction({ x, y, type, subtype })); return newIndex; } } export function addSpaceInternal(x: number, y: number, type: Space, subtype: SpaceSubtype | undefined, board: IBoard, eventLibrary: EventMap): number { let newSpace: any = { x, y, z: 0, type: type }; if (subtype !== undefined) newSpace.subtype = subtype; let adapter = getAdapter(board.game || 1); if (adapter) adapter.hydrateSpace(newSpace, board, eventLibrary); board.spaces.push(newSpace); return board.spaces.length - 1; } export function removeSpace(index: number) { store.dispatch(removeSpaceAction({ index })); } export function getSpaceIndex(space: ISpace, board = getCurrentBoard()) { return board.spaces.indexOf(space); } export function getStartSpaceIndex(board: IBoard) { let spaces = board.spaces; for (let i = 0; i < spaces.length; i++) { if (!spaces[i]) continue; if (spaces[i].type === Space.START) return i; } return -1; } export function getSpacesOfType(type: Space, board: IBoard = getCurrentBoard()): number[] { let spaces = board.spaces; let typeSpaces = []; for (let i = 0; i < spaces.length; i++) { if (!spaces[i]) continue; if (spaces[i].type === type) typeSpaces.push(i); } return typeSpaces; } export function getSpacesOfSubType(subtype: SpaceSubtype, board: IBoard = getCurrentBoard()): number[] { let spaces = board.spaces; let subtypeSpaces = []; for (let i = 0; i < spaces.length; i++) { if (!spaces[i]) continue; if (spaces[i].subtype === subtype) subtypeSpaces.push(i); } return subtypeSpaces; } /** Returns array of space indices of spaces with a given event. */ export function getSpacesWithEvent(eventName: string, board: IBoard = getCurrentBoard()): number[] { const eventSpaces: number[] = []; forEachEvent(board, (event, eventIndex, space, spaceIndex) => { if (space && event.id === eventName) { eventSpaces.push(spaceIndex!); } }); return eventSpaces; } /** Gets the index of the "dead space." The space is created if it hasn't been already. */ export function getDeadSpaceIndex(board: IBoard): number { if (typeof board._deadSpace === "number") { return board._deadSpace; } let deadSpaceIndex = addSpace(board.bg.width + 150, board.bg.height + 100, Space.OTHER, undefined, board); board._deadSpace = deadSpaceIndex; return deadSpaceIndex; } /** Gets the "dead space." The space is created if it hasn't been already. */ export function getDeadSpace(board: IBoard): ISpace { return board.spaces[getDeadSpaceIndex(board)]; } // Returns array of space indices connected to from a space. export function getConnections(spaceIndex: number, board: IBoard = getCurrentBoard()) { if (spaceIndex < 0) return null; if (!board.links) { return []; }; if (Array.isArray(board.links[spaceIndex])) return (board.links[spaceIndex] as number[]).slice(0); if (typeof board.links[spaceIndex] === "number") return [board.links[spaceIndex] as number]; return []; } export function addConnectionInternal(startSpaceIndex: number, endSpaceIndex: number, board: IBoard): void { if (startSpaceIndex === endSpaceIndex || hasConnection(startSpaceIndex, endSpaceIndex, board)) return; board.links = board.links || {}; if (Array.isArray(board.links[startSpaceIndex])) (board.links[startSpaceIndex] as number[]).push(endSpaceIndex); else if (typeof board.links[startSpaceIndex] === "number") board.links[startSpaceIndex] = [board.links[startSpaceIndex] as number, endSpaceIndex]; else if (endSpaceIndex >= 0) board.links[startSpaceIndex] = endSpaceIndex; } export function addConnection(startSpaceIndex: number, endSpaceIndex: number, board?: IBoard) { if (board) { // Hack: the places that do pass a board aren't modifying the redux store. addConnectionInternal(startSpaceIndex, endSpaceIndex, board); } else { store.dispatch(addConnectionAction({ startSpaceIndex, endSpaceIndex })); } } export function setSpaceRotation(spaceIndex: number, angleYAxisDeg: number) { store.dispatch(setSpaceRotationAction({ spaceIndex, angleYAxisDeg })); } export function addEventByIndex(board: IBoard, spaceIdx: number, event: any, toStart: boolean, eventLibrary: EventMap) { const space = board.spaces[spaceIdx]; addEventToSpaceInternal(board, space, event, toStart, eventLibrary); } export function loadBoardsFromROM() { let adapter = getROMAdapter(); if (!adapter) return; let gameBoards = adapter.loadBoards(); for (const gameBoard of gameBoards) { gameBoard._rom = true; store.dispatch(addBoardAction({ board: gameBoard, rom: true })); } boardsChanged(); clearUndoHistory(); } export function clearBoardsFromROM() { store.dispatch(clearBoardsFromROMAction()); }
the_stack
import {EventAggregator, Subscription} from 'aurelia-event-aggregator'; import {NewInstance, bindable, computedFrom, inject, observable} from 'aurelia-framework'; import {Router} from 'aurelia-router'; import {ControllerValidateResult, ValidateResult, ValidationController, ValidationRules} from 'aurelia-validation'; import {BindingSignaler} from 'aurelia-templating-resources'; import {join} from 'path'; import {ForbiddenError, UnauthorizedError, isError} from '@essential-projects/errors_ts'; import {IDiagram, ISolution} from '@process-engine/solutionexplorer.contracts'; import {ISolutionExplorerService} from '@process-engine/solutionexplorer.service.contracts'; import {IIdentity} from '@essential-projects/iam_contracts'; import {IResponse} from '@essential-projects/http_contracts'; import { AuthenticationStateEvent, IDiagramCreationService, IDiagramState, IDiagramStateList, IDiagramStateListEntry, ISolutionEntry, ISolutionService, NotificationType, } from '../../../contracts/index'; import environment from '../../../environment'; import {NotificationService} from '../../../services/notification-service/notification.service'; import {OpenDiagramsSolutionExplorerService} from '../../../services/solution-explorer-services/open-diagrams-solution-explorer.service'; import {OpenDiagramStateService} from '../../../services/solution-explorer-services/open-diagram-state.service'; import {DeleteDiagramModal} from './delete-diagram-modal/delete-diagram-modal'; import {DeployDiagramService} from '../../../services/deploy-diagram-service/deploy-diagram.service'; import {SaveDiagramService} from '../../../services/save-diagram-service/save-diagram.service'; import {HttpFetchClient} from '../../fetch-http-client/http-fetch-client'; import {solutionIsRemoteSolution} from '../../../services/solution-is-remote-solution-module/solution-is-remote-solution.module'; import {isRunningInElectron} from '../../../services/is-running-in-electron-module/is-running-in-electron.module'; import {getInvalidCharacters} from '../../../services/xml-id-validation-module/xml-id-validation-module'; const ENTER_KEY: string = 'Enter'; const ESCAPE_KEY: string = 'Escape'; type DiagramSorter = (firstElement: IDiagram, secondElement: IDiagram) => number; enum CloseModalResult { Cancel = 0, Save = 1, Delete = 2, } interface IDiagramNameInputState { currentDiagramInputValue: string; } interface IDiagramCreationState extends IDiagramNameInputState { isCreateDiagramInputShown: boolean; } @inject( Router, EventAggregator, NewInstance.of(ValidationController), 'DiagramCreationService', 'NotificationService', 'SolutionService', 'OpenDiagramStateService', DeployDiagramService, SaveDiagramService, BindingSignaler, 'HttpFetchClient', ) export class SolutionExplorerSolution { public solutionExplorerSolution = this; public activeDiagram: IDiagram; public showCloseModal: boolean = false; @bindable public renameDiagramInput: HTMLInputElement; // Fields below are bound from the html view. @bindable public solutionService: ISolutionExplorerService; @bindable public openDiagramService: OpenDiagramsSolutionExplorerService; @bindable @observable public displayedSolutionEntry: ISolutionEntry; @bindable public cssIconClass: string; @bindable public isConnected: boolean; @bindable public tooltipText: string; @bindable public peHasStarted: boolean = false; public createNewDiagramInput: HTMLInputElement; public diagramContextMenu: HTMLElement; public showContextMenu: boolean = false; public deleteDiagramModal: DeleteDiagramModal; public processEngineRunning: boolean = false; public isSavingDiagrams: boolean = false; public currentlySavingDiagramName: string = ''; public processEngineStartupError: boolean = false; public processEngineErrorLog: string; public errorLogArea: HTMLTextAreaElement; public authorisationError: boolean; public authenticationError: boolean; @bindable public login: Function; private router: Router; private eventAggregator: EventAggregator; private validationController: ValidationController; private diagramCreationService: IDiagramCreationService; private notificationService: NotificationService; private openDiagramStateService: OpenDiagramStateService; private deployDiagramService: DeployDiagramService; private saveDiagramService: SaveDiagramService; private diagramRoute: string = 'design'; private inspectView: string; private designView: string = 'detail'; private subscriptions: Array<Subscription>; private openedSolution: ISolution; private diagramCreationState: IDiagramCreationState = { currentDiagramInputValue: undefined, isCreateDiagramInputShown: false, }; private solutionEventListenerId: string; private diagramStateList: Array<IDiagramStateListEntry>; private diagramRenamingState: IDiagramNameInputState = { currentDiagramInputValue: undefined, }; private refreshTimeoutTask: NodeJS.Timer; private currentlyRenamingDiagram: IDiagram | null = null; private isAttached: boolean = false; private originalIconClass: string; private globalSolutionService: ISolutionService; private diagramInContextMenu: IDiagram; private ipcRenderer: any; private sortedDiagramsOfSolutions: Array<IDiagram> = []; private diagramStatesChangedCallbackId: string; private signaler: BindingSignaler; private httpFetchClient: HttpFetchClient; private isPolling: boolean = false; private shouldRefreshOnTokenRefresh: boolean = false; private saveFunction: EventListenerOrEventListenerObject; private dontSaveFunction: EventListenerOrEventListenerObject; private cancelFunction: EventListenerOrEventListenerObject; constructor( router: Router, eventAggregator: EventAggregator, validationController: ValidationController, diagramCreationService: IDiagramCreationService, notificationService: NotificationService, solutionService: ISolutionService, openDiagramStateService: OpenDiagramStateService, deployDiagramService: DeployDiagramService, saveDiagramService: SaveDiagramService, bindingSignaler: BindingSignaler, httpFetchClient: HttpFetchClient, ) { this.router = router; this.eventAggregator = eventAggregator; this.validationController = validationController; this.diagramCreationService = diagramCreationService; this.notificationService = notificationService; this.globalSolutionService = solutionService; this.openDiagramStateService = openDiagramStateService; this.deployDiagramService = deployDiagramService; this.saveDiagramService = saveDiagramService; this.signaler = bindingSignaler; this.httpFetchClient = httpFetchClient; this.updateDiagramStateList(); this.diagramStatesChangedCallbackId = this.openDiagramStateService.onDiagramStatesChanged(() => { this.updateDiagramStateList(); }); } public async attached(): Promise<void> { const solutionIsInternalProcessEngine: boolean = this.displayedSolutionEntry.uri === window.localStorage.getItem('InternalProcessEngineRoute'); this.isAttached = true; if (isRunningInElectron()) { this.ipcRenderer = (window as any).nodeRequire('electron').ipcRenderer; if (solutionIsInternalProcessEngine) { this.ipcRenderer.send('add_internal_processengine_status_listener'); // wait for status to be reported this.ipcRenderer.on('internal_processengine_status', async (event: any, status: string, errorLog: string) => { if (status === 'success') { this.processEngineRunning = true; this.peHasStarted = true; await this.updateSolution(); this.solutionEventListenerId = this.displayedSolutionEntry.service.watchSolution(() => { this.updateSolution(); }); } else { this.processEngineErrorLog = errorLog; this.processEngineStartupError = true; this.processEngineRunning = false; this.isConnected = false; this.cssIconClass = 'fa fa-bolt'; console.error(errorLog); } }); } } this.originalIconClass = this.cssIconClass; this.updateSolutionExplorer(); this.subscriptions = [ this.eventAggregator.subscribe('router:navigation:success', () => { this.updateSolutionExplorer(); }), this.eventAggregator.subscribe(AuthenticationStateEvent.LOGIN, async () => { await this.updateSolution(); if (this.solutionEventListenerId !== undefined) { this.displayedSolutionEntry.service.unwatchSolution(this.solutionEventListenerId); } if (!this.displayedSolutionEntry.isOpenDiagram) { this.solutionEventListenerId = this.displayedSolutionEntry.service.watchSolution(() => { this.updateSolution(); }); } }), this.eventAggregator.subscribe( `${AuthenticationStateEvent.REFRESH}-${this.displayedSolutionEntry.uri}`, async () => { if (this.shouldRefreshOnTokenRefresh) { await this.updateSolution(); this.shouldRefreshOnTokenRefresh = false; } }, ), this.eventAggregator.subscribe( environment.events.solutionExplorer.closeAllOpenDiagrams, this.closeAllDiagramsEventFunction, ), this.eventAggregator.subscribe(environment.events.solutionExplorer.closeDiagram, () => { this.closeDiagram(this.activeDiagram); }), ]; if (this.displayedSolutionEntry.isOpenDiagram) { const updateSubscription: Subscription = this.eventAggregator.subscribe( environment.events.solutionExplorer.updateOpenDiagrams, (): void => { this.updateSolution(); }, ); this.subscriptions.push(updateSubscription); if (isRunningInElectron()) { this.ipcRenderer.on('menubar__start_close_all_diagrams', this.closeAllDiagramsEventFunction); this.ipcRenderer.on('menubar__start_save_all_diagrams', this.saveAllDiagramsEventFunction); } } if (solutionIsRemoteSolution(this.displayedSolutionEntry.uri)) { if (solutionIsInternalProcessEngine) { return; } await this.waitForProcessEngine(); } else { this.setValidationRules(); setTimeout(async () => { await this.updateSolution(); }, 0); if (!this.displayedSolutionEntry.isOpenDiagram) { this.solutionEventListenerId = this.displayedSolutionEntry.service.watchSolution(() => { this.updateSolution(); }); } } } public waitForProcessEngine(): Promise<void> { return new Promise((resolve: Function, reject: Function): void => { const makeRequest: Function = (): void => { setTimeout(async () => { try { try { await this.httpFetchClient.get(`${this.displayedSolutionEntry.uri}/process_engine`); } catch (error) { const errorIsNotFoundError: boolean = error.code === 404; if (errorIsNotFoundError) { await this.httpFetchClient.get(`${this.displayedSolutionEntry.uri}`); } else { throw error; } } await this.updateSolution(); this.solutionEventListenerId = this.displayedSolutionEntry.service.watchSolution(() => { this.updateSolution(); }); resolve(); } catch (error) { setTimeout(() => { makeRequest(); }, 1000); } // tslint:disable-next-line: no-magic-numbers }, 10); }; makeRequest(); }); } public detached(): void { this.isAttached = false; clearTimeout(this.refreshTimeoutTask as NodeJS.Timer); this.disposeSubscriptions(); if (this.diagramCreationState.isCreateDiagramInputShown) { this.resetDiagramCreation(); } if (this.isCurrentlyRenamingDiagram) { this.resetDiagramRenaming(); } if (this.displayedSolutionEntry.isOpenDiagram) { this.ipcRenderer.removeListener('menubar__start_close_all_diagrams', this.closeAllDiagramsEventFunction); this.ipcRenderer.removeListener('menubar__start_save_all_diagrams', this.saveAllDiagramsEventFunction); } this.openDiagramStateService.removeOnDiagramStatesChangedListener(this.diagramStatesChangedCallbackId); if (this.solutionEventListenerId !== undefined) { this.displayedSolutionEntry.service.unwatchSolution(this.solutionEventListenerId); } } public async showDeleteDiagramModal(diagram: IDiagram, event: Event): Promise<void> { /** * We are stopping the event propagation here, because we don't want * the event to be called on the list element, since this would lead to a * navigation to the diagram we want to delete. */ event.stopPropagation(); const diagramWasDeleted: boolean = await this.deleteDiagramModal.show(diagram, this.solutionService); if (diagramWasDeleted) { await this.updateSolution(); this.refreshDisplayedDiagrams(); } } public copyToClipboard(): void { this.errorLogArea.select(); document.execCommand('copy'); } /** * Called by aurelia, if the value of the solutionService binding changes. */ public solutionServiceChanged(newValue: ISolutionExplorerService, oldValue: ISolutionExplorerService): Promise<void> { if (!this.processEngineRunning) { return undefined; } return this.updateSolution(); } /** * Reload the solution by requesting it from the solution service. */ public async updateSolution(): Promise<void> { try { this.openedSolution = await this.solutionService.loadSolution(); await this.updateSolutionEntry(); const updatedDiagramList: Array<IDiagram> = this.displayedSolutionEntry.isOpenDiagram ? this.openedSolution.diagrams : this.openedSolution.diagrams.sort(this.diagramSorter); const diagramsOfSolutionChanged: boolean = JSON.stringify(this.sortedDiagramsOfSolutions) !== JSON.stringify(updatedDiagramList); if (diagramsOfSolutionChanged) { this.refreshDisplayedDiagrams(); } this.isConnected = true; this.cssIconClass = this.originalIconClass; this.tooltipText = ''; this.processEngineRunning = true; this.authorisationError = false; this.authenticationError = false; } catch (error) { // In the future we can maybe display a small icon indicating the error. if (isError(error, UnauthorizedError)) { this.shouldRefreshOnTokenRefresh = true; this.authorisationError = true; this.sortedDiagramsOfSolutions = []; this.openedSolution = undefined; } else if (isError(error, ForbiddenError)) { if (this.displayedSolutionEntry.isLoggedIn) { this.shouldRefreshOnTokenRefresh = true; this.authorisationError = true; this.authenticationError = false; } else { this.authenticationError = true; this.authorisationError = false; } this.sortedDiagramsOfSolutions = []; this.openedSolution = undefined; } else { this.openedSolution.diagrams = undefined; this.sortedDiagramsOfSolutions = []; this.cssIconClass = 'fa fa-bolt'; this.isConnected = false; if (solutionIsRemoteSolution(this.displayedSolutionEntry.uri)) { this.tooltipText = 'ProcessEngine is disconnected!'; } else { this.tooltipText = 'Solution was removed!'; } this.processEngineRunning = false; } } } private async updateSolutionEntry(): Promise<void> { const solutionIsNotRemote: boolean = !solutionIsRemoteSolution(this.displayedSolutionEntry.uri); if (solutionIsNotRemote) { return; } let response: IResponse<JSON & {version: string}>; try { response = await this.httpFetchClient.get(`${this.displayedSolutionEntry.uri}/process_engine`); } catch (error) { const errorIsNotFoundError: boolean = error.code === 404; if (errorIsNotFoundError) { response = await this.httpFetchClient.get(`${this.displayedSolutionEntry.uri}`); } else { throw error; } } let authority; try { const fetchResponse: any = await this.httpFetchClient.get( `${this.displayedSolutionEntry.uri}/process_engine/security/authority`, ); authority = fetchResponse.result.authority; } catch (error) { const errorIsNotFoundError: boolean = error.code === 404; if (errorIsNotFoundError) { const fetchResponse: any = await this.httpFetchClient.get( `${this.displayedSolutionEntry.uri}/security/authority`, ); authority = fetchResponse.result.authority; } else { throw error; } } this.displayedSolutionEntry.authority = authority; this.displayedSolutionEntry.processEngineVersion = response.result.version; this.globalSolutionService.addSolutionEntry(this.displayedSolutionEntry); this.signaler.signal('update-version-icon'); } /* * Used when this is a open diagram solution explorer service. */ public async closeDiagram(diagram: IDiagram, event?: Event): Promise<void> { const eventSet: boolean = event !== undefined; if (eventSet) { event.stopPropagation(); } if (diagram == null) { return undefined; } if (!this.displayedSolutionEntry.isOpenDiagram) { return undefined; } const diagramState: IDiagramState = this.openDiagramStateService.loadDiagramState(diagram.uri); const diagramHasUnsavedChanges: boolean = diagramState !== null && diagramState.metadata.isChanged; if (diagramHasUnsavedChanges) { const cancelClosing: boolean = (await this.showCloseDiagramModal(diagram)) === CloseModalResult.Cancel; if (cancelClosing) { return undefined; } } const closedDiagramWasActiveDiagram: boolean = this.activeDiagramUri === diagram.uri; if (closedDiagramWasActiveDiagram) { return new Promise<void>((resolve: Function): void => { const subscription: Subscription = this.eventAggregator.subscribe('router:navigation:success', () => { this.closeOpenDiagram(diagram); subscription.dispose(); resolve(); }); this.router.navigateToRoute('start-page'); }); } this.closeOpenDiagram(diagram); return undefined; } public async startRenamingOfDiagram(diagram: IDiagram, event: Event): Promise<void> { event.stopPropagation(); if (this.isCurrentlyRenamingDiagram) { return; } // Dont allow renaming diagram, if already creating another. if (this.diagramCreationState.isCreateDiagramInputShown) { return; } // This shows the input field. this.currentlyRenamingDiagram = diagram; // The templating update must happen before we can set the focus. window.setTimeout(() => { this.renameDiagramInput.focus(); this.diagramRenamingState.currentDiagramInputValue = diagram.name; this.setValidationRules(); this.validationController.validate(); }, 0); document.addEventListener('click', this.onRenameDiagramClickEvent); document.addEventListener('keyup', this.onRenameDiagramKeyupEvent); } public activateContextMenu(event: MouseEvent, diagram: IDiagram): void { this.diagramInContextMenu = diagram; this.diagramContextMenu.style.top = `${event.y}px`; this.diagramContextMenu.style.left = `${event.x}px`; this.showContextMenu = true; const documentEventListener: EventListenerOrEventListenerObject = (): void => { this.showContextMenu = false; this.diagramInContextMenu = undefined; document.removeEventListener('click', documentEventListener); }; document.addEventListener('click', documentEventListener); } public async duplicateDiagram(): Promise<void> { const noDiagramInContextMenu: boolean = this.diagramInContextMenu === undefined; if (noDiagramInContextMenu) { return; } let newNameFound: boolean = false; let newName: string; let diagramNumber: number = 1; const isDiagramNameNotEqualToNewName: (diagram: IDiagram) => boolean = (diagram: IDiagram) => { return diagram.name !== newName; }; const invalidCharacters = getInvalidCharacters(this.diagramInContextMenu.name); let currentDiagramName = this.diagramInContextMenu.name; for (const invalidCharacter of invalidCharacters) { currentDiagramName = currentDiagramName.replace(invalidCharacter, '_'); } while (newNameFound === false) { newName = `${currentDiagramName}_${diagramNumber}`; newNameFound = this.openedDiagrams.every(isDiagramNameNotEqualToNewName); diagramNumber++; } const duplicatedDiagram: IDiagram = await this.diagramCreationService.createNewDiagram( this.displayedSolutionEntry.uri, newName, this.diagramInContextMenu.xml, ); await this.solutionService.saveDiagram(duplicatedDiagram, duplicatedDiagram.uri); await this.updateSolution(); } public async deployDiagram(): Promise<void> { const noDiagramInContextMenu: boolean = this.diagramInContextMenu === undefined; if (noDiagramInContextMenu) { return; } const diagramState: IDiagramState | null = this.openDiagramStateService.loadDiagramState( this.diagramInContextMenu.uri, ); const diagramHasState: boolean = diagramState !== null; const xml: string | undefined = diagramHasState ? diagramState.data.xml : undefined; await this.deployDiagramService.deployDiagram(this.displayedSolutionEntry, this.diagramInContextMenu, xml); } /* * Called by the parent component to start the creation dialog of a new * diagram. */ public async startCreationOfNewDiagram(): Promise<void> { if (this.diagramCreationState.isCreateDiagramInputShown) { return; } // Dont allow new diagram creation, if already renaming another diagram. if (this.isCurrentlyRenamingDiagram) { return; } if (this.displayedSolutionEntry.isOpenDiagram) { this.openNewDiagram(); return; } this.diagramCreationState.isCreateDiagramInputShown = true; // The templating update must happen before we can set the focus. window.setTimeout(() => { this.createNewDiagramInput.focus(); this.setValidationRules(); }, 0); document.addEventListener('click', this.onCreateNewDiagramClickEvent); document.addEventListener('keyup', this.onCreateNewDiagramKeyupEvent); } @computedFrom('validationController.errors.length') public get diagramValidationErrors(): Array<ValidateResult> { const validationErrorPresent: boolean = this.validationController.errors.length >= 1; if (validationErrorPresent) { this.setInvalidCharacterMessage(this.validationController.errors); } return this.validationController.errors; } @computedFrom('validationController.errors.length') public get hasValidationErrors(): boolean { return this.validationController.errors && this.validationController.errors.length > 0; } @computedFrom('currentlyRenamingDiagram') public get currentlyRenamingDiagramUri(): string { return this.currentlyRenamingDiagram === null ? null : this.currentlyRenamingDiagram.uri; } public shouldFileIconBeShown(): boolean { return false; } @computedFrom('displayedSolutionEntry.isOpenDiagram', 'openedSolution') public get canRenameDiagram(): boolean { return ( !this.displayedSolutionEntry.isOpenDiagram && this.openedSolution && !solutionIsRemoteSolution(this.openedSolution.uri) ); } @computedFrom('diagramStateList') public get diagramChangedStateMap(): Map<string, boolean> { const isChangedMap: Map<string, boolean> = new Map<string, boolean>(); this.diagramStateList.forEach((diagramStateListEntry: IDiagramStateListEntry): void => { const isChanged: boolean = diagramStateListEntry !== null && diagramStateListEntry.diagramState.metadata.isChanged; isChangedMap.set(diagramStateListEntry.uri, isChanged); }); return isChangedMap; } public canDeleteDiagram(): boolean { return !this.displayedSolutionEntry.isOpenDiagram && this.openedSolution !== undefined; } public get solutionIsNotLoaded(): boolean { return ( solutionIsRemoteSolution(this.displayedSolutionEntry.uri) && (this.openedSolution === null || this.openedSolution === undefined || !this.processEngineRunning) ); } public get openedDiagrams(): Array<IDiagram> { return this.sortedDiagramsOfSolutions; } public getDiagramLocation(diagramUri: string): string { const lastIndexOfSlash: number = diagramUri.lastIndexOf('/'); const lastIndexOfBackSlash: number = diagramUri.lastIndexOf('\\'); const indexBeforeFilename: number = Math.max(lastIndexOfSlash, lastIndexOfBackSlash); const diagramLocationWithoutFileName: string = diagramUri.slice(0, indexBeforeFilename); return diagramLocationWithoutFileName; } public getDiagramFolder(diagramUri: string): string { const diagramLocation: string = this.getDiagramLocation(diagramUri); const lastIndexOfSlash: number = diagramLocation.lastIndexOf('/'); const lastIndexOfBackSlash: number = diagramLocation.lastIndexOf('\\'); const indexBeforeFoldername: number = Math.max(lastIndexOfSlash, lastIndexOfBackSlash); const indexIsInvalid: boolean = indexBeforeFoldername < 0; if (indexIsInvalid) { return ''; } const diagramFolder: string = diagramLocation.slice(indexBeforeFoldername, diagramLocation.length); return diagramFolder; } @computedFrom('activeDiagram.uri') public get activeDiagramUri(): string { const activeDiagramIsNotSet: boolean = this.activeDiagram === undefined; if (activeDiagramIsNotSet) { return undefined; } const solutionUri: string = this.router.currentInstruction.queryParams.solutionUri; const solutionUriUnspecified: boolean = solutionUri === undefined; if (solutionUriUnspecified) { return undefined; } return this.activeDiagram.uri; } public async openDiagram(diagram: IDiagram): Promise<void> { const diagramIsFromLocalSolution: boolean = !solutionIsRemoteSolution(diagram.uri); if (diagramIsFromLocalSolution) { const diagramIsNotYetOpened: boolean = !this.openDiagramService .getOpenedDiagrams() .some((openedDiagram: IDiagram): boolean => { return openedDiagram.uri === diagram.uri; }); if (diagramIsNotYetOpened) { await this.openDiagramService.openDiagramFromSolution(diagram.uri, this.createIdentityForSolutionExplorer()); } } this.navigateToDetailView(diagram); } public isUriFromRemoteSolution(uri: string): boolean { return solutionIsRemoteSolution(uri); } private updateDiagramStateList(): void { this.diagramStateList = this.openDiagramStateService.loadDiagramStateForAllDiagrams(); } private closeAllDiagramsEventFunction: Function = async (): Promise<void> => { if (this.displayedSolutionEntry.isOpenDiagram === false) { return; } const currentlyOpenDiagrams: Array<IDiagram> = [...this.openedDiagrams]; await this.closeMultipleDiagrams(currentlyOpenDiagrams); }; private async closeMultipleDiagrams(diagrams: Array<IDiagram>): Promise<void> { const diagramsIsEmpty: boolean = diagrams === undefined || diagrams.length === 0; if (diagramsIsEmpty) { return; } const amountOfDiagrams: number = diagrams.length; this.navigateToDiagram(diagrams[0]); for (let index: number = 0; index < amountOfDiagrams; index++) { const nextDiagramIndex: number = index + 1; const isLastDiagram: boolean = nextDiagramIndex === amountOfDiagrams; const currentDiagram: IDiagram = diagrams[index]; const nextDiagram: IDiagram = isLastDiagram ? undefined : diagrams[nextDiagramIndex]; const diagramState: IDiagramState = this.openDiagramStateService.loadDiagramState(currentDiagram.uri); const diagramHasUnsavedChanges: boolean = diagramState !== null && diagramState.metadata.isChanged; let closeDiagram: boolean = true; if (diagramHasUnsavedChanges) { const closeModalResult: CloseModalResult = await this.showCloseDiagramModal(currentDiagram, false); closeDiagram = closeModalResult !== CloseModalResult.Cancel; } if (isLastDiagram) { await this.navigateToStartPage(); } else { await this.navigateToDiagram(nextDiagram); } if (closeDiagram) { await this.closeOpenDiagram(currentDiagram); } } } private get isCurrentlyRenamingDiagram(): boolean { return this.currentlyRenamingDiagram !== null; } private navigateToStartPage(): Promise<void> { return new Promise((resolve: Function): void => { this.eventAggregator.subscribeOnce('router:navigation:success', () => { resolve(); }); this.router.navigateToRoute('start-page'); }); } private async navigateToDiagram(diagram: IDiagram): Promise<void> { return new Promise((resolve: Function): void => { this.eventAggregator.subscribeOnce('router:navigation:success', () => { resolve(); }); this.router.navigateToRoute('design', { view: this.designView, diagramName: diagram.name, diagramUri: diagram.uri, solutionUri: this.displayedSolutionEntry.uri, }); }); } private async navigateBack(): Promise<void> { return new Promise<void>((resolve: Function): void => { this.eventAggregator.subscribeOnce('router:navigation:success', () => { resolve(); }); this.router.navigateBack(); }); } private saveAllDiagramsEventFunction: Function = (): void => { this.saveAllUnsavedDiagrams(); }; // TODO: This method is copied all over the place. private async navigateToDetailView(diagram: IDiagram): Promise<void> { await this.router.navigateToRoute(this.diagramRoute, { view: this.inspectView ? this.inspectView : this.designView, diagramName: diagram.name, diagramUri: diagram.uri, solutionUri: this.displayedSolutionEntry.uri, }); } private createIdentityForSolutionExplorer(): IIdentity { const accessToken: string = this.createDummyAccessToken(); // TODO: Get the identity from the IdentityService of `@process-engine/iam` const identity: IIdentity = { token: accessToken, userId: '', // Provided by the IdentityService. }; return identity; } private createDummyAccessToken(): string { const dummyAccessTokenString: string = 'dummy_token'; const base64EncodedString: string = btoa(dummyAccessTokenString); return base64EncodedString; } private get diagramSorter(): DiagramSorter { const sortOptions: Intl.CollatorOptions = { caseFirst: 'lower', }; const sorter: DiagramSorter = (firstElement: IDiagram, secondElement: IDiagram): number => { return firstElement.name.localeCompare(secondElement.name, undefined, sortOptions); }; return sorter; } private async saveAllUnsavedDiagrams(): Promise<void> { if (this.isSavingDiagrams) { return; } this.isSavingDiagrams = true; const diagramStateList: IDiagramStateList = this.openDiagramStateService .loadDiagramStateForAllDiagrams() .filter((diagramStateListEntry: IDiagramStateListEntry) => { return diagramStateListEntry.diagramState.metadata.isChanged; }); for (const diagramStateListEntry of diagramStateList) { const isActiveDiagram: boolean = this.activeDiagram !== undefined && this.activeDiagram.uri === diagramStateListEntry.uri; if (isActiveDiagram) { this.currentlySavingDiagramName = this.activeDiagram.name; await this.saveActiveDiagram(); await this.waitForSaving(); continue; } const diagramToSave: IDiagram = this.openedDiagrams.find((diagram: IDiagram) => { return diagram.uri === diagramStateListEntry.uri; }); const diagramNotFound: boolean = diagramToSave === undefined; if (diagramNotFound) { continue; } this.currentlySavingDiagramName = diagramToSave.name; diagramToSave.xml = diagramStateListEntry.diagramState.data.xml; await this.saveDiagramService.saveDiagram(this.displayedSolutionEntry, diagramToSave, diagramToSave.xml); const diagramState: IDiagramState = this.openDiagramStateService.loadDiagramState(diagramToSave.uri); diagramState.metadata.isChanged = false; this.openDiagramStateService.updateDiagramState(diagramStateListEntry.uri, diagramState); await this.waitForSaving(); } this.isSavingDiagrams = false; this.currentlySavingDiagramName = ''; } private saveActiveDiagram(): Promise<void> { return new Promise((resolve: Function): void => { this.eventAggregator.subscribeOnce(environment.events.diagramDetail.saveDiagramDone, () => { resolve(); }); this.eventAggregator.publish(environment.events.diagramDetail.saveDiagram); }); } private waitForSaving(): Promise<void> { return new Promise((resolve: Function): void => { setTimeout(() => { resolve(); }, 550); }); } private refreshDisplayedDiagrams(): void { this.sortedDiagramsOfSolutions = this.displayedSolutionEntry.isOpenDiagram ? this.openedSolution.diagrams : this.openedSolution.diagrams.sort(this.diagramSorter); } private async closeOpenDiagram(diagramToClose: IDiagram): Promise<void> { if (!this.displayedSolutionEntry.isOpenDiagram) { return; } const openDiagramService: OpenDiagramsSolutionExplorerService = this .solutionService as OpenDiagramsSolutionExplorerService; await openDiagramService.closeDiagram(diagramToClose); this.globalSolutionService.removeOpenDiagramByUri(diagramToClose.uri); } private async showCloseDiagramModal( diagramToSave: IDiagram, shouldNavigate: boolean = true, ): Promise<CloseModalResult> { const diagramToSaveIsNotActiveDiagram: boolean = diagramToSave.uri !== this.activeDiagramUri; if (diagramToSaveIsNotActiveDiagram && shouldNavigate) { await this.navigateToDiagram(diagramToSave); } const modalResult: Promise<CloseModalResult> = new Promise((resolve: Function): CloseModalResult | void => { this.dontSaveFunction = async (): Promise<void> => { if (diagramToSaveIsNotActiveDiagram && shouldNavigate) { await this.navigateBack(); } resolve(CloseModalResult.Delete); this.showCloseModal = false; }; this.saveFunction = async (): Promise<void> => { this.eventAggregator.subscribeOnce(environment.events.diagramWasSaved, async () => { if (shouldNavigate) { await this.navigateBack(); } resolve(CloseModalResult.Save); }); this.eventAggregator.publish(environment.events.diagramDetail.saveDiagram); this.showCloseModal = false; }; this.cancelFunction = async (): Promise<void> => { if (diagramToSaveIsNotActiveDiagram && shouldNavigate) { await this.navigateBack(); } resolve(CloseModalResult.Cancel); this.showCloseModal = false; }; this.showCloseModal = true; }); return modalResult; } private async isDiagramDetailViewOfDiagramOpen(diagramUriToCheck: string): Promise<boolean> { const activeDiagramIsUndefined: boolean = this.activeDiagram === undefined; if (activeDiagramIsUndefined) { return false; } const diagramIsOpened: boolean = diagramUriToCheck === this.activeDiagramUri; return diagramIsOpened; } /** * Looks in the given Array of validation errors for an invalid character * error message and replace the messages content with the acutal * message and returns a reference to a new array with the mod * * TODO: This method should create a deep copy of an arra< that contains * errors and return it instead of just modifying the reference. * */ private setInvalidCharacterMessage(errors: Array<ValidateResult>): void { const defaultErrorText = 'The diagram name contains the following illegal characters: '; for (const currentError of errors) { const validationErrorIsQname = currentError.message === defaultErrorText; if (validationErrorIsQname) { const inputToValidate: string = currentError.object.currentDiagramInputValue; const invalidCharacters = getInvalidCharacters(inputToValidate); const filteredInvalidCharacters: Array<string> = invalidCharacters.filter( (current: string, index: number): boolean => { return invalidCharacters.indexOf(current) === index; }, ); // Replaces the commas between the invalid characters by a space to increase readability. const invalidCharacterString: string = `${filteredInvalidCharacters}`.replace(/(.)./g, '$1 '); const invalidWhitespace = filteredInvalidCharacters.some((character) => character.match(/\s/i) != null); const invalidFirstCharacterRegex: RegExp = /^[\d-.:]/i; const invalidFirstCharacter = inputToValidate.match(invalidFirstCharacterRegex); if (invalidWhitespace) { currentError.message = 'The diagram name contains at least one illegal whitespace character.'; } else if (invalidFirstCharacter) { currentError.message = `Illegal first character in diagram name: ${inputToValidate.substr(0, 1)}`; } else { currentError.message = `${defaultErrorText} ${invalidCharacterString}`; } } } } private async openNewDiagram(): Promise<void> { const unsavedDiagrams: Array<IDiagram> = this.openedDiagrams.filter((diagram: IDiagram): boolean => { const diagramIsUnsavedDiagram: boolean = diagram.name.startsWith('Untitled-'); if (!diagramIsUnsavedDiagram) { return false; } const diagramIndex: number = parseInt(diagram.name.replace('Untitled-', '')); // eslint-disable-next-line no-restricted-globals return !isNaN(diagramIndex); }); const unsavedDiagramIndexes: Array<number> = unsavedDiagrams.map((diagram: IDiagram) => { const diagramIndex: number = parseInt(diagram.name.replace('Untitled-', '')); return diagramIndex; }); const anotherUnsavedDiagramExists: boolean = unsavedDiagrams.length > 0; const newDiagramIndex: number = anotherUnsavedDiagramExists ? Math.max(...unsavedDiagramIndexes) + 1 : 1; const solutionIsNotFullyOpen: boolean = this.openedSolution === undefined; if (solutionIsNotFullyOpen) { await this.updateSolution(); } const createdDiagram: IDiagram = await this.diagramCreationService.createNewDiagram( this.openedSolution.uri, `Untitled-${newDiagramIndex}`, ); this.openDiagramStateService.saveDiagramState(createdDiagram.uri, createdDiagram.xml, undefined, undefined, true); this.openDiagramService.openDiagramFromSolution(createdDiagram.uri, this.createIdentityForSolutionExplorer()); await this.updateSolution(); this.navigateToDetailView(createdDiagram); } /** * The event listener used to handle mouse clicks during the diagram * creation. * * The listener will try to finish the diagram creation if the user clicks * on another element then the input. */ private onCreateNewDiagramClickEvent = async (event: MouseEvent): Promise<void> => { const inputWasClicked: boolean = event.target === this.createNewDiagramInput; if (inputWasClicked) { return; } const emptyDiagram: IDiagram = await this.finishDiagramCreation(); if (emptyDiagram === undefined) { return; } await this.openDiagramAndUpdateSolution(emptyDiagram); }; private async openDiagramAndUpdateSolution(createdDiagram: IDiagram): Promise<void> { await this.openDiagramService.openDiagramFromSolution(createdDiagram.uri, this.createIdentityForSolutionExplorer()); this.openDiagramStateService.setDiagramChange(createdDiagram.uri, {change: 'create'}); await this.updateSolution(); this.resetDiagramCreation(); this.activeDiagram = createdDiagram; this.navigateToDetailView(createdDiagram); } /** * The event listener used to handle keyboard events during the diagram * creation. * * The listener will try to finish the diagram creation if the user presses * the enter key. It will abort the creation if the escape key is pressed. */ private onCreateNewDiagramKeyupEvent = async (event: KeyboardEvent): Promise<void> => { const pressedKey: string = event.key; if (pressedKey === ENTER_KEY) { const emptyDiagram: IDiagram = await this.finishDiagramCreation(); if (emptyDiagram === undefined) { return; } await this.openDiagramAndUpdateSolution(emptyDiagram); } else if (pressedKey === ESCAPE_KEY) { this.resetDiagramCreation(); } }; /** * The event listener used to handle mouse clicks during the diagram * renaming. * * The listener will try to finish the diagram renaming if the user clicks * on another element then the input. It will abort if there are any * validation errors. */ private onRenameDiagramClickEvent = async (event: MouseEvent): Promise<void> => { const inputWasClicked: boolean = event.target === this.renameDiagramInput; if (inputWasClicked) { return; } const inputWasNotValid: boolean = !(await this.finishDiagramRenaming(true)); if (inputWasNotValid) { this.resetDiagramRenaming(); return; } this.updateSolution().then(() => { this.refreshDisplayedDiagrams(); }); this.resetDiagramRenaming(); }; /** * The event listener used to handle keyboard events during the diagram * renaming. * * The listener will try to finish the diagram creation if the user presses * the enter key. It will abort the creation if the escape key is pressed. It * will not abort the diagram renaming, if there are validation errors. */ private onRenameDiagramKeyupEvent = async (event: KeyboardEvent): Promise<void> => { const pressedKey: string = event.key; const enterWasPressed: boolean = pressedKey === ENTER_KEY; const escapeWasPressed: boolean = pressedKey === ESCAPE_KEY; if (enterWasPressed) { const inputWasNotValid: boolean = !(await this.finishDiagramRenaming(false)); if (inputWasNotValid) { return; } this.updateSolution().then(() => { this.refreshDisplayedDiagrams(); }); this.resetDiagramRenaming(); } else if (escapeWasPressed) { this.resetDiagramRenaming(); } }; /** * Checks, if the input contains any non empty values. * * @return true, if the input has some non empty value. */ private hasNonEmptyValue(input: HTMLInputElement): boolean { const inputValue: string = input.value; const inputHasValue: boolean = inputValue !== undefined && inputValue !== null && inputValue !== ''; return inputHasValue; } /** * Finishes the diagram renaming process. This method will again run the * validation and ensures that all input is correct. Otherwise an error is * displayed to the user. * * If the validation passes, the diagram will be created and returned. * * @param silent if a notification should be shown on validation failure. * @returns true if the diagram was renamed, false otherwise. */ private async finishDiagramRenaming(silent: boolean): Promise<boolean> { const validationResult: ControllerValidateResult = await this.validationController.validate(); const inputWasNotValid: boolean = !validationResult.valid || (this.validationController.errors && this.validationController.errors.length > 0); if (inputWasNotValid) { if (!silent) { const message: string = 'Please resolve all errors first.'; this.notificationService.showNotification(NotificationType.INFO, message); } return false; } const filenameWasNotChanged: boolean = this.currentlyRenamingDiagram.name === this.diagramRenamingState.currentDiagramInputValue; if (filenameWasNotChanged) { return true; } try { const diagramState: IDiagramState = this.openDiagramStateService.loadDiagramState( this.currentlyRenamingDiagram.uri, ); if (diagramState != null) { this.openDiagramStateService.setDiagramChange(this.currentlyRenamingDiagram.uri, {change: 'rename'}); } await this.solutionService.renameDiagram( this.currentlyRenamingDiagram, this.diagramRenamingState.currentDiagramInputValue, ); const newDiagram = await this.openDiagramService.renameDiagram( this.currentlyRenamingDiagram, this.diagramRenamingState.currentDiagramInputValue, ); if (newDiagram) { this.globalSolutionService.removeOpenDiagramByUri(this.currentlyRenamingDiagram.uri); this.globalSolutionService.addOpenDiagram(newDiagram); } const showRenamedDiagram = this.router.currentInstruction.params.diagramName === this.currentlyRenamingDiagram.name && this.router.currentInstruction.config.name === 'design'; if (showRenamedDiagram) { await this.router.navigateToRoute('design', { diagramName: newDiagram.name, diagramUri: newDiagram.uri, solutionUri: this.displayedSolutionEntry.uri, }); } } catch (error) { this.notificationService.showNotification(NotificationType.WARNING, error.message); return false; } return true; } /** * Finishes the diagram creation. This method will again run the validation * and ensures that all input is correct. Otherwise an error is displayed to * the user. * * If no input element was empty, the diagram creation will be aborted. * If the validation passes, the diagram will be created and returned. */ private async finishDiagramCreation(): Promise<IDiagram> { const inputHasNoValue: boolean = !this.hasNonEmptyValue(this.createNewDiagramInput); if (inputHasNoValue) { this.resetDiagramCreation(); return undefined; } const validationResult: ControllerValidateResult = await this.validationController.validate(); const inputWasNotValid: boolean = !validationResult.valid || (this.validationController.errors && this.validationController.errors.length > 0); if (inputWasNotValid) { const message: string = 'Please resolve all errors first.'; this.notificationService.showNotification(NotificationType.INFO, message); return undefined; } const emptyDiagram: IDiagram = await this.diagramCreationService.createNewDiagram( this.openedSolution.uri, this.diagramCreationState.currentDiagramInputValue, ); try { await this.solutionService.saveDiagram(emptyDiagram, emptyDiagram.uri); } catch (error) { this.notificationService.showNotification(NotificationType.ERROR, error.message); return undefined; } return emptyDiagram; } /** * Resets the diagram renaming state to its default. Any listeners will be * removed and input values will be cleared. */ private resetDiagramRenaming(): void { // Remove all used event listeners. document.removeEventListener('click', this.onRenameDiagramClickEvent); document.removeEventListener('keyup', this.onRenameDiagramKeyupEvent); // Reset input field. this.diagramRenamingState.currentDiagramInputValue = ''; this.renameDiagramInput.value = ''; // Hide input field. this.currentlyRenamingDiagram = null; ValidationRules.off(this.diagramRenamingState); } /** * Resets the diagram creation state to its default. Any listeners will be * removed and input values will be cleared. */ private resetDiagramCreation(): void { // Remove all used event listeners. document.removeEventListener('click', this.onCreateNewDiagramClickEvent); document.removeEventListener('keyup', this.onCreateNewDiagramKeyupEvent); // Reset input field. this.diagramCreationState.currentDiagramInputValue = ''; this.createNewDiagramInput.value = ''; // Hide input field. this.diagramCreationState.isCreateDiagramInputShown = false; ValidationRules.off(this.diagramCreationState); } private findURIObject<TType extends {uri: string}>(objects: Array<TType>, targetURI: string): TType { const foundObject: TType = objects.find((object: TType): boolean => { return object.uri.toLowerCase() === targetURI.toLowerCase(); }); return foundObject; } private disposeSubscriptions(): void { for (const subscription of this.subscriptions) { subscription.dispose(); } } private async updateSolutionExplorer(): Promise<void> { const solutionUri: string = this.router.currentInstruction.queryParams.solutionUri; const solutionUriSpecified: boolean = solutionUri !== undefined; const diagramName: string = this.router.currentInstruction.params.diagramName; const diagramNameIsSpecified: boolean = diagramName !== undefined; const diagramUri: string = this.router.currentInstruction.queryParams.diagramUri; const routeName: string = this.router.currentInstruction.config.name; const routeNameNeedsUpdate: boolean = routeName === 'design' || routeName === 'inspect' || routeName === 'think'; if (routeNameNeedsUpdate) { this.diagramRoute = routeName; this.inspectView = this.router.currentInstruction.params.view; } const currentRoute: string = this.router.currentInstruction.config.name; if (currentRoute === 'preferences' || currentRoute === 'settings') { return; } if (solutionUriSpecified && diagramNameIsSpecified) { try { const activeSolution: ISolution = await this.solutionService.loadSolution(); this.activeDiagram = activeSolution.diagrams.find((diagram: IDiagram) => { const currentDiagramIsGivenDiagram: boolean = diagram.uri === diagramUri; const diagramIsInGivenSolution: boolean = solutionIsRemoteSolution(solutionUri) ? diagram.uri.includes(solutionUri) : diagram.uri.includes(`${solutionUri}/${diagram.name}.bpmn`) || diagram.uri.endsWith(`${diagram.name}.bpmn`); return diagram.name === diagramName && (currentDiagramIsGivenDiagram || diagramIsInGivenSolution); }); } catch { // Do nothing } } else { this.activeDiagram = undefined; } } private setValidationRules(): void { ValidationRules.ensure((state: IDiagramNameInputState) => state.currentDiagramInputValue) .required() .withMessage('Diagram name cannot be blank.') .satisfies((input) => { const qNameRegex: RegExp = /^([a-z][\w-.]*:)?[a-z_][\w-.]*$/i; return qNameRegex.test(input); }) .withMessage('The diagram name contains the following illegal characters: ') .then() .satisfies(async (input: string) => { const diagramNameIsUnchanged: boolean = this.isCurrentlyRenamingDiagram && this.currentlyRenamingDiagram.name.toLowerCase() === input.toLowerCase(); if (diagramNameIsUnchanged) { return true; } // The solution may have changed on the file system. await this.updateSolution(); const isRemoteSolution: boolean = solutionIsRemoteSolution(this.openedSolution.uri); let expectedDiagramUri: string; if (isRemoteSolution) { expectedDiagramUri = `${this.openedSolution.uri}/${input}.bpmn`; } else if (isRunningInElectron()) { expectedDiagramUri = join(this.openedSolution.uri, `${input}.bpmn`); } const diagramWithUriDoesNotExist: boolean = this.findURIObject(this.openedSolution.diagrams, expectedDiagramUri) === undefined; return diagramWithUriDoesNotExist; }) .withMessage('A diagram with that name already exists.') .on(this.diagramRenamingState) .on(this.diagramCreationState); } }
the_stack
import {PipeTransform} from '@angular/core'; import * as angular from 'angular'; import * as _ from "underscore"; import {DomainType, DomainTypesService} from "../../../services/DomainTypesService"; import {TableColumnDefinition} from "../../../model/TableColumnDefinition"; import {TableFieldPartition} from "../../../model/TableFieldPartition"; import {TableFieldPolicy} from "../../../model/TableFieldPolicy"; import {TableCreateMethod, TableForm} from "../../../model/feed/feed-table"; import {ObjectUtils} from "../../../../../lib/common/utils/object-utils"; import {StringUtils} from "../../../../common/utils/StringUtils"; const moduleName = require('../module-name'); export class ExpansionPanelHelper { constructor(private $mdExpansionPanel: any) { } /* Collapse the file picker section */ collapseMethodPanel() { this.$mdExpansionPanel().waitFor('panelOne').then((instance: any) => { instance.collapse(); }); }; /* Expand the schema panel */ expandSchemaPanel() { this.$mdExpansionPanel().waitFor('panelTwo').then((instance: any) => { instance.expand(); }); }; collapseMethodAndExpandSchemaPanel() { this.collapseMethodPanel(); this.expandSchemaPanel(); } expandChooseMethodPanel() { this.$mdExpansionPanel().waitFor('panelOne').then((instance: any) => { instance.expand(); }); }; } export class DefineFeedTableController { /** * The 1 based index step number */ stepNumber: number; /** * The feed stepper controller */ stepperController: any; /** * The FeedMetadata model boject */ model: any; /** * flag to check if the form is valid or not */ isValid: boolean = false; /** * The html File object for the sample */ sampleFile: any = null; tableCreateMethods: TableCreateMethod[] = [{type: 'MANUAL', name: 'Manual'}, {type: 'SAMPLE_FILE', name: 'Sample File'}]; availableDefinitionDataTypes: string[] = []; /** * The parser selected for the sample file */ schemaParser: any = null; /** * replace the <space> with underscore in field names * @type {boolean} */ useUnderscoreInsteadOfSpaces: boolean = true; /** * the selected field */ selectedColumn: TableColumnDefinition = null; fieldNamesUniqueRetryAmount: number = 0; /** * Should we show the method panel ? * this will be false for Data Transform feeds * @type {boolean} */ showMethodPanel: boolean = true; /** * is the upload button disabled * @type {boolean} */ uploadBtnDisabled: boolean = false; /** * Array of partition formulas */ partitionFormulas: string[] = []; /** * The feed format */ feedFormat: string; /** * Metadata for the selected column tag. * @type {{searchText: null, selectedItem: null}} */ tagChips: any = {searchText: null, selectedItem: null}; /** * List of available domain types. * @type {DomainType[]} */ availableDomainTypes: DomainType[] = []; /** * the 0 based string index */ stepIndex: string; expansionPanelHelper: ExpansionPanelHelper; tableLocked: boolean; dataTypeLocked: boolean; canRemoveFields: boolean; tableForm: TableForm; static readonly $inject = ["$rootScope", "$scope", "$http", "$timeout", "$mdToast", "$filter", "$mdDialog", "$mdExpansionPanel", "RestUrlService", "FeedService", "FileUpload", "BroadcastService", "Utils", "FeedTagService", "DomainTypesService"] constructor(private $rootScope: any, private $scope: any, private $http: any, private $timeout: any, private $mdToast: any, private $filter: any, private $mdDialog: any , private $mdExpansionPanel: any, private restUrlService: any, private feedService: any, private fileUpload: any, private broadcastService: any, private utils: any, private feedTagService: any, private domainTypesService: any) { this.expansionPanelHelper = new ExpansionPanelHelper((this.$mdExpansionPanel)); this.model = feedService.createFeedModel; this.addComplexDataTypes() this.tableForm = new TableForm(this.model); domainTypesService.findAll().then((domainTypes: DomainType[]) => { this.availableDomainTypes = domainTypes; }); this.ensurePartitionData(); broadcastService.subscribe($scope, 'DATA_TRANSFORM_SCHEMA_LOADED', this.onDataTransformSchemaLoaded.bind(this)); var invalidColumnsWatch = $scope.$watch(() => { return this.tableForm.defineFeedTableForm.invalidColumns }, (newVal: any) => { // console.log("watching this.defineFeedTableForm.invalidColumns"); this.isValid = this.tableForm.validate(undefined); }, true); var tableMethodWatch = $scope.$watch(() => { return this.model.table.method; }, (newVal: any) => { // console.log("watching model.table.method"); this.model.table.method = newVal; this.calcTableState(); }); //Set the Table Name to be the System Feed Name var systemFeedNameWatch = $scope.$watch(() => { return this.model.systemFeedName; }, (newVal: any) => { this.model.table.tableSchema.name = newVal; }); /** * Ensure the form is valid * @type {*|function()} */ var formValidWatch = $scope.$watch(() => { return this.tableForm.defineFeedTableForm.$valid; }, (newVal: any) => { if (newVal === true) { this.isValid = this.tableForm.validate(newVal); } else { this.isValid = false; } }); var sampleFileWatch = $scope.$watch(() => { return this.sampleFile; }, (newVal: any) => { if (newVal == null) { angular.element('#upload-sample-file-btn').removeClass('md-primary'); } else { angular.element('#upload-sample-file-btn').addClass('md-primary'); } }); $scope.$on('$destroy', () => { systemFeedNameWatch(); invalidColumnsWatch(); formValidWatch(); tableMethodWatch(); sampleFileWatch(); }); } $onInit() { this.ngOnInit(); } ngOnInit() { this.stepNumber = parseInt(this.stepIndex) + 1; if (this.model.sampleFile) { this.sampleFile = this.model.sampleFile; } //attach the schema parser options if theey were saved on the model if (this.model.schemaParser) { this.schemaParser = this.model.schemaParser; } // this.$scope.$evalAsync(() => { this.calcTableState(); if (this.model.table.tableSchema.fields && this.model.table.tableSchema.fields.length > 0) { if (this.model.dataTransformationFeed) { this.addComplexDataTypes(); } this.syncFeedsColumns(); this.expansionPanelHelper.expandSchemaPanel(); }else { if (!this.model.dataTransformationFeed) { this.expansionPanelHelper.expandChooseMethodPanel(); } } // Retrieve partition formulas this.feedService.getPartitionFunctions() .then((functions: any) => { this.partitionFormulas = functions; }); this.isValid = this.tableForm.validate(undefined); } /** * Called when the Method radio option is changed */ updateSelectedMethod(method: string) { if (method == 'MANUAL') { this.model.allowSkipHeaderOption = true; } } /** * Adding a new Column to the schema * This is called both when the user clicks the "Add Field" button or when the sample file is uploaded * If adding from the UI the {@code columnDef} will be null, otherwise it will be the parsed ColumnDef from the sample file * @param columnDef */ addColumn(columnDef: TableColumnDefinition, syncFieldPolicies?: boolean) { // console.log("addColumn"); if (columnDef == null) { columnDef = this.feedService.newTableFieldDefinition(); } // when adding a new column this is also called to synchronize the field policies array with the columns let policy = this.feedService.newTableFieldPolicy(); if (columnDef.sampleValues != null && columnDef.sampleValues.length > 0) { columnDef.selectedSampleValue = columnDef.sampleValues[0]; } else { columnDef.selectedSampleValue = null; } if (this.useUnderscoreInsteadOfSpaces) { columnDef.name = StringUtils.replaceSpaces(columnDef.name, '_'); } columnDef.initFeedColumn(); //add the column to both the source and destination tables as well as the fieldPolicies array this.model.table.tableSchema.fields.push(columnDef); this.model.table.fieldPolicies.push(policy); this.model.table.sourceTableSchema.fields.push(this.feedService.newTableFieldDefinition()); this.tableForm.validateColumn(columnDef); if (syncFieldPolicies == undefined || syncFieldPolicies == true) { this.feedService.syncTableFieldPolicyNames(); } }; undoColumn(index: number) { var columnDef = <TableColumnDefinition> this.model.table.tableSchema.fields[index]; columnDef.history.pop(); let prevValue = columnDef.history[columnDef.history.length - 1]; columnDef.undo(prevValue); this.tableForm.validateColumn(columnDef); this.tableForm.partitionNamesUnique(); this.feedService.syncTableFieldPolicyNames(); this.isValid = this.tableForm.validate(undefined); }; /** * Remove a column from the schema * @param index */ removeColumn(index: number) { var columnDef = <TableColumnDefinition> this.model.table.tableSchema.fields[index]; columnDef.deleteColumn(); //remove any partitions using this field this.model.table.partitions .filter((partition: any) => { return partition.columnDef.name === columnDef.name; }) .map((partition: any) => { return partition._id; }) .forEach((id: any) => { var index = this.model.table.partitions.findIndex((partition: any) => { return partition._id === id; }); if (index > -1) { this.removePartitionField(index); } }); //ensure the field names on the columns are unique again as removing a column might fix a "notUnique" error this.tableForm.validateColumn(columnDef); this.tableForm.partitionNamesUnique(); this.isValid = this.tableForm.validate(undefined); }; /** * Removes the column matching the passed in {@code columnDef} with the array of columns * @param columnDef */ removeColumnUsingReference(columnDef: TableColumnDefinition) { var idx = _.indexOf(this.model.table.tableSchema.fields, columnDef) if (idx >= 0) { this.removeColumn(idx); } }; /** * Add a partition to the schema * This is called from the UI when the user clicks "Add Partition" */ addPartitionField() { var partitionLength = this.model.table.partitions.length; var partition = TableFieldPartition.atPosition(partitionLength); this.model.table.partitions.push(partition); }; /** * Remove the partition from the schecma * @param index */ removePartitionField(index: number) { this.model.table.partitions.splice(index, 1); this.tableForm.partitionNamesUnique(); }; onSelectedColumn(selectedColumn: TableColumnDefinition) { var firstSelection = this.selectedColumn == null; this.selectedColumn = selectedColumn; // Show an item in dropdown if (this.selectedColumn.selectedSampleValue == null && this.selectedColumn.sampleValues.length > 0) { this.selectedColumn.selectedSampleValue = this.selectedColumn.sampleValues[0]; } if (firstSelection) { //trigger scroll to stick the selection to the screen this.utils.waitForDomElementReady('#selectedColumnPanel', () => { angular.element('#selectedColumnPanel').triggerHandler('stickIt'); }) } // Ensure tags is an array if (angular.isUndefined(selectedColumn.tags) ) { selectedColumn.tags = []; } }; onPrecisionChange(columnDef: TableColumnDefinition) { this.tableForm.validateColumn(columnDef); this.onFieldChange(columnDef); }; /** * When the schema field changes it needs to * - ensure the names are unique * - update the respective partition names if there is a partition on the field with the 'val' formula * - ensure that partition names are unique since the new field name could clash with an existing partition * @param columnDef */ onNameFieldChange(columnDef: TableColumnDefinition, index: number) { columnDef.replaceNameSpaces(); this.onFieldChange(columnDef); //update the partitions with "val" on this column so the name matches _.each(this.model.table.partitions, (partition: TableFieldPartition) => { if (partition.columnDef == columnDef) { partition.syncSource(); partition.updateFieldName(); } }); this.tableForm.validateColumn(columnDef); this.tableForm.partitionNamesUnique(); this.feedService.syncTableFieldPolicyNames(); // Check if column data type matches domain data type var policy = <TableFieldPolicy>this.model.table.fieldPolicies[index]; var domainType = policy.$currentDomainType; if (policy.domainTypeId && domainType.field && columnDef.$allowDomainTypeConflict !== true) { var nameChanged = (domainType.field.name && columnDef.name !== domainType.field.name); var dataTypeChanged = (domainType.field.derivedDataType && columnDef.derivedDataType !== domainType.field.derivedDataType); if (nameChanged || dataTypeChanged) { this.$mdDialog.show({ controller: "DomainTypeConflictDialog", escapeToClose: false, fullscreen: true, parent: angular.element(document.body), templateUrl: "../../../shared/apply-domain-type/domain-type-conflict.component.html", locals: { data: { columnDef: columnDef, domainType: domainType } } }) .then((keep: any) => { if (keep) { columnDef.$allowDomainTypeConflict = true; } else { delete policy.$currentDomainType; delete policy.domainTypeId; } }, () => { this.undoColumn(index); }); } } } /** * When a partition Source field changes it needs to * - auto select the formula if there is only 1 in the drop down (i.e. fields other than dates/timestamps will only have the 'val' formula * - ensure the partition data mapping to this source field is correct * - attempt to prefill in the name with some default name. if its a val formula it will default the partition name to the source field name and leave it disabled * @param partition */ onPartitionSourceFieldChange(partition: TableFieldPartition) { //set the partition data to match the selected sourceField partition.syncSource(); //if there is only 1 option in the formula list then auto select it var formulas = this.$filter('filterPartitionFormula')(this.partitionFormulas, partition); if (formulas.length == 1) { partition.formula = formulas[0]; } partition.updateFieldName(); this.tableForm.partitionNamesUnique(); } /** * When a partition formula changes it needs to * - attempt to prefill in the name with some default name. if its a val formula it will default the partition name to the source field name and leave it disabled * @param partition */ onPartitionFormulaChange(partition: TableFieldPartition) { partition.updateFieldName(); this.tableForm.partitionNamesUnique(); } /** * when the partition name changes it needs to * - ensure the names are unique * - ensure no dups (cannot have more than 1 partitoin on the same col/formula * @param partition */ onPartitionNameChange(partition: any) { partition.replaceSpaces(); this.tableForm.partitionNamesUnique(); }; /** * User uploads a sample file. * resets the columns, applys fields to the table */ uploadSampleFile() { this.uploadBtnDisabled = true; this.showProgress(); var file = this.sampleFile; var params = {}; if (this.schemaParser) { params = {parser: JSON.stringify(this.schemaParser)}; } //Store the Schema Parser option on the model so they can be loaded when returning back to this step this.model.schemaParser = this.schemaParser; var uploadUrl = this.restUrlService.UPLOAD_SAMPLE_TABLE_FILE; var successFn = (response: any) => { var responseData = response.data; this.resetColumns(); this.availableDefinitionDataTypes = this.feedService.columnDefinitionDataTypes.slice(); angular.forEach(responseData.fields, (field) => { var col = this.feedService.newTableFieldDefinition(); col = angular.extend(col, field) // add exotic data type to available columns if needed if ($.inArray(col.derivedDataType, this.availableDefinitionDataTypes) == -1) { this.availableDefinitionDataTypes.push(col.derivedDataType); } this.addColumn(col, false); }); this.feedService.syncTableFieldPolicyNames(); this.applyDomainTypes(); //set the feedFormat property this.model.table.feedFormat = responseData.hiveFormat; this.model.table.structured = responseData.structured; this.model.table.feedTblProperties = responseData.serdeTableProperties; if (this.schemaParser.allowSkipHeader) { this.model.allowSkipHeaderOption = true; this.model.options.skipHeader = true; } else { this.model.allowSkipHeaderOption = false; this.model.options.skipHeader = false; } this.hideProgress(); this.uploadBtnDisabled = false; this.syncFeedsColumns(); this.calcTableState(); this.expansionPanelHelper.collapseMethodAndExpandSchemaPanel(); this.isValid = this.tableForm.validate(undefined); angular.element('#upload-sample-file-btn').removeClass('md-primary'); this.$timeout(() => this.tableForm.touchErrorFields(), 2000); }; var errorFn = (data: any) => { //clear the schemaParser options this.model.schemaParser = undefined; this.hideProgress(); this.uploadBtnDisabled = false; angular.element('#upload-sample-file-btn').removeClass('md-primary'); angular.element('#uploadButton').addClass('md-primary'); }; //clear partitions while (this.model.table.partitions.length) { this.model.table.partitions.pop(); } this.fileUpload.uploadFileToUrl(file, uploadUrl, successFn, errorFn, params); } private onFieldChange(columnDef: TableColumnDefinition) { this.selectedColumn = columnDef; columnDef.changeColumn(); } /** * Transforms the specified chip into a tag. * @param {string} chip the chip * @returns {Object} the tag */ transformTagChip(chip: any) { return angular.isObject(chip) ? chip : {name: chip}; }; private showProgress() { if (this.stepperController) { this.stepperController.showProgress = true; } } private hideProgress() { if (this.stepperController) { this.stepperController.showProgress = false; } } private resetColumns() { this.model.table.tableSchema.fields = []; this.model.table.fieldPolicies = []; this.tableForm.defineFeedTableForm.invalidColumns = []; } /** * Ensure that for the partitions the sourceField and sourceDataTypes match the respective schema field data */ private ensurePartitionData() { _.each(this.model.table.partitions, (partition: TableFieldPartition) => { if (partition.columnDef == undefined) { var columnDef = this.feedService.getColumnDefinitionByName(partition.sourceField); if (columnDef != null) { partition.columnDef = columnDef; } } partition.syncSource(); }); } private addComplexDataTypes() { this.availableDefinitionDataTypes = this.feedService.columnDefinitionDataTypes.slice(); angular.forEach(this.model.table.tableSchema.fields, (field) => { // add exotic data type to available columns if needed if ($.inArray(field.derivedDataType, this.availableDefinitionDataTypes) == -1) { this.availableDefinitionDataTypes.push(field.derivedDataType); } }); } /** * Detects and applies domain types to all columns. */ private applyDomainTypes() { // Detect domain types var data: any = {domainTypes: [], fields: []}; this.model.table.tableSchema.fields.forEach((field: TableColumnDefinition, index: number) => { var domainType = this.domainTypesService.detectDomainType(field, this.availableDomainTypes); if (domainType !== null) { if (this.domainTypesService.matchesField(domainType, field)) { // Domain type can be applied immediately this.feedService.setDomainTypeForField(field, this.model.table.fieldPolicies[index], domainType); field.history = []; field.addHistoryItem(); } else { // Domain type needs user confirmation data.domainTypes.push(domainType); data.fields.push(field); } } }); // Get user confirmation for domain type changes to field data types if (data.fields.length > 0) { this.$mdDialog.show({ controller: "ApplyTableDomainTypesDialog", escapeToClose: false, fullscreen: true, parent: angular.element(document.body), templateUrl: "../../../shared/apply-domain-type/apply-table-domain-types.component.html", locals: { data: data } }) .then((selected: any) => { selected.forEach((selection: any) => { var fieldIndex = data.fields.findIndex((element: any) => { return element.name === selection.name; }); var policyIndex = this.model.table.tableSchema.fields.findIndex((element: any) => { return element.name === selection.name; }); this.feedService.setDomainTypeForField(data.fields[fieldIndex], this.model.table.fieldPolicies[policyIndex], data.domainTypes[fieldIndex]); data.fields[fieldIndex].history = []; let columnDef = <TableColumnDefinition> data.fields[fieldIndex]; columnDef.addHistoryItem(); }); }, () => { // ignore cancel }); } } /** * Called when a user transitions from the Wrangler to this step */ private onDataTransformSchemaLoaded() { this.syncFeedsColumns(); this.isValid = this.tableForm.validate(undefined); if (angular.isDefined(this.model.schemaChanged) && this.model.schemaChanged == true) { this.isValid = false; this.$mdDialog.show( this.$mdDialog.alert() .parent(angular.element(document.body)) .clickOutsideToClose(true) .title('Table Schema Changed') .htmlContent('The table schema no longer matches the schema previously defined. <br/><br/> This is invalid. If you wish to modify the underlying schema <br/> (i.e. change some column names and/or types) please clone<br/> the feed as a new feed instead.') .ariaLabel('Table Schema Changed ') .ok('Got it!') ); } this.addComplexDataTypes(); this.calcTableState(); this.expansionPanelHelper.expandSchemaPanel(); this.isValid = this.tableForm.validate(undefined); } /** * Set the table states for locks */ private calcTableState() { this.tableLocked = angular.isDefined(this.tableLocked) && (this.tableLocked == true ); this.dataTypeLocked = angular.isDefined(this.dataTypeLocked) && (this.dataTypeLocked == true ); this.canRemoveFields = angular.isUndefined(this.canRemoveFields) || this.canRemoveFields === true ; this.showMethodPanel = (this.model.table.method != 'EXISTING_TABLE'); } /* Create columns for tracking changes between original source and the target table schema */ private syncFeedsColumns() { let convertFieldsToObjects = false; if(this.model.table.tableSchema.fields.length >0){ convertFieldsToObjects = !ObjectUtils.isType(this.model.table.tableSchema.fields[0],TableColumnDefinition.OBJECT_TYPE); } if(convertFieldsToObjects){ let convertedFields:TableColumnDefinition[] = this.model.table.tableSchema.fields.map((columnDef:any) => ObjectUtils.getAs(columnDef,TableColumnDefinition)); this.model.table.tableSchema.fields = convertedFields; } _.each(this.model.table.tableSchema.fields, (columnDef: TableColumnDefinition) => { columnDef.initFeedColumn() }); } } class FilterPartitionFormulaPipe implements PipeTransform{ constructor(private FeedService:any){ } transform(formulas:any, partition:any){ // Find column definition var columnDef = (partition && partition.sourceField) ? this.FeedService.getColumnDefinitionByName(partition.sourceField) : null; if (columnDef == null) { return formulas; } // Filter formulas based on column type if (columnDef.derivedDataType !== "date" && columnDef.derivedDataType !== "timestamp") { return _.without(formulas, "to_date", "year", "month", "day", "hour", "minute"); } else { return formulas; } } } angular.module(moduleName).filter("filterPartitionFormula", ["FeedService", (FeedService:any) => { const pipe = new FilterPartitionFormulaPipe(FeedService); return pipe.transform.bind(pipe); }]); angular.module(moduleName). component("thinkbigDefineFeedTable", { bindings: { canRemoveFields: "<?", stepIndex: '@', tableLocked: "<?", dataTypeLocked: "<?typeLocked" }, require: { stepperController: "^thinkbigStepper" }, controllerAs: 'vm', controller: DefineFeedTableController, templateUrl: './define-feed-table.html', });
the_stack
import _ from 'lodash'; import {TailwindConfigParser} from './TailwindConfigParser'; import {nonConfigurableClassNames} from '../lib/non-configurable'; // prettier-ignore import { TAllClassnames, Backgrounds, Layout, Borders, Tables, Effects, Interactivity, TransitionsAndAnimations, Transforms, Accessibility, SVG, FlexBox, Grid, Spacing, Sizing, Typography, Filters } from '../types/classes'; import {TConfigTheme, TConfigDarkMode} from '../types/config'; import {tailwindLabsPlugins} from '../lib/tailwindlabs-plugins'; import {regularClassGroupKeys} from './constants/regularClassGroupKeys'; /** * Responsible for generating the types from a parsed config by ConfigScanner. */ export class ClassnamesGenerator { private readonly _prefix: string; private readonly _separator: string; private readonly _darkMode: TConfigDarkMode; private readonly _theme: Omit<TConfigTheme, 'extend'>; private readonly _configParser: TailwindConfigParser; private readonly _generatedRegularClassnames: TAllClassnames; private readonly _generatedPseudoClassnames: string[]; /** * Initializes a new instance of the `ClassesGenerator` class. * @param tailwindConfig The _parsed_ TailwindCSS Config. */ constructor(parser: TailwindConfigParser) { this._configParser = parser; this._prefix = this._configParser.getPrefix(); this._separator = this._configParser.getSeparator(); this._darkMode = this._configParser.getDarkMode(); this._theme = this._configParser.getTheme(); this._generatedRegularClassnames = { Accessibility: this.accessibility(), Backgrounds: this.backgrounds(), Borders: this.borders(), Tables: this.tables(), Effects: this.effects(), TransitionsAndAnimations: this.transitionsAndAnimations(), Filters: this.filters(), FlexBox: this.flexBox(), Grid: this.grid(), Spacing: this.spacing(), Interactivity: this.interactivity(), Layout: this.layout(), Sizing: this.sizing(), SVG: this.SVG(), Transforms: this.transforms(), Typography: this.typography(), }; const configPlugins = this._configParser.getPlugins(); if (configPlugins !== null) { this._generatedRegularClassnames.TailwindLabsPlugins = {}; const {pluginCustomForms, pluginTypography} = tailwindLabsPlugins; if (!!configPlugins.pluginCustomForms) this._generatedRegularClassnames.TailwindLabsPlugins.pluginCustomForms = pluginCustomForms; if (!!configPlugins.pluginTypography) this._generatedRegularClassnames.TailwindLabsPlugins.pluginTypography = pluginTypography; } this._generatedPseudoClassnames = this.pseudoClasses(); } /** * Get the generated classnames. */ public generate = (): TAllClassnames => { return this._generatedRegularClassnames; }; private layout = (): Layout => { return { ...nonConfigurableClassNames.layout, objectPosition: Object.keys(this._theme.objectPosition).map(x => 'object-' + x), inset: Object.keys(this._theme.inset).flatMap(insetValue => { return ['inset', 'inset-x', 'inset-y', 'top', 'right', 'bottom', 'left'].map(side => insetValue.startsWith('-') ? `-${side}-${insetValue.substring(1)}` : `${side}-${insetValue}`, ); }), zIndex: Object.keys(this._theme.zIndex).flatMap(zIndexValue => zIndexValue.startsWith('-') ? `-z-${zIndexValue.substring(1)}` : `z-${zIndexValue}`, ), aspectRatio: Object.keys(this._theme.aspectRatio).map(x => 'aspect-' + x), columns: Object.keys(this._theme.columns).map(x => 'columns-' + x), }; }; private backgrounds = (): Backgrounds => { return { ...nonConfigurableClassNames.backgrounds, backgroundOpacity: this.getGeneratedClassesWithOpacities().backgroundOpacities, backgroundColor: this.generateClassesWithColors('backgroundColor'), backgroundPosition: Object.keys(this._theme.backgroundPosition).map(x => 'bg-' + x), backgroundSize: Object.keys(this._theme.backgroundSize).map(x => 'bg-' + x), backgroundImage: Object.keys(this._theme.backgroundImage).map(x => 'bg-' + x), gradientColorStops: this.generateClassesWithColors('gradientColorStops').flatMap(val => ['from', 'via', 'to'].map(x => x + val.replace('gradient', '')), ), }; }; private borders = (): Borders => { return { // Add all non configurable classes in `borders` plugin. // These are utilities that their names never change e.g. border styles (dashed, solid etc.) ...nonConfigurableClassNames.borders, /* Dynamic border utils */ borderColor: this.generateClassesWithColors('borderColor'), borderOpacity: this.getGeneratedClassesWithOpacities().borderOpacities, borderRadius: Object.keys(this._theme.borderRadius).flatMap(radius => { const sides = ['t', 'r', 'b', 'l', 'tr', 'tl', 'br', 'bl']; return sides.map(side => `rounded-${side}-${radius}`).concat(`rounded-${radius}`); }), borderWidth: Object.keys(this._theme.borderWidth).flatMap(width => { const sides = ['t', 'r', 'b', 'l', 'x', 'y']; return sides.map(side => `border-${side}-${width}`).concat(`border-${width}`); }), /* Dynamic divide utilities */ divideColor: this.generateClassesWithColors('divideColor'), divideOpacity: this.getGeneratedClassesWithOpacities().divideOpacities, // divide width inherits its values from theme.borderWidth by default // but theme.divideWidth overrides it. divideWidth: Object.keys( _.isEmpty(this._theme.divideWidth) ? this._theme.borderWidth : this._theme.divideWidth, ) .concat('reverse') .flatMap(width => ['x', 'y'].map(axis => `divide-${axis}-${width}`)), /* Dynamic ring utilities */ ringColor: this.generateClassesWithColors('ringColor'), ringWidth: Object.keys(this._theme.ringWidth) .map(x => 'ring-' + x) .concat('ring-inset'), ringOpacity: this.getGeneratedClassesWithOpacities().ringOpacities, ringOffsetColor: this.generateClassesWithColors('ringOffsetColor'), ringOffsetWidth: Object.keys(this._theme.ringOffsetWidth).map(x => 'ring-offset-' + x), outlineOffset: Object.keys(this._theme.outlineOffset).map(x => 'outline-' + x), outlineWidth: Object.keys(this._theme.outlineWidth).map(x => 'outline-' + x), outlineColor: this.generateClassesWithColors('outlineColor'), }; }; private tables = (): Tables => { return nonConfigurableClassNames.tables; }; private effects = (): Effects => { return { ...nonConfigurableClassNames.effects, boxShadow: Object.keys(this._theme.boxShadow).map(key => `shadow-${key}`), boxShadowColor: this.generateClassesWithColors('boxShadowColor'), opacity: this.getGeneratedClassesWithOpacities().opacities, }; }; private transitionsAndAnimations = (): TransitionsAndAnimations => { return { ...nonConfigurableClassNames.transitionsAndAnimations, transitionProperty: Object.keys(this._theme.transitionProperty).map( property => 'transition-' + property, ), transitionDuration: Object.keys(this._theme.transitionDuration).map( value => 'duration-' + value, ), transitionTimingFunction: Object.keys(this._theme.transitionTimingFunction) .filter(k => k !== 'DEFAULT') // The `DEFAULT` key does not correspond to a classname .map(value => 'ease-' + value), transitionDelay: Object.keys(this._theme.transitionDelay).map(value => 'delay-' + value), animation: Object.keys(this._theme.animation).map(val => 'animate-' + val), }; }; private transforms = (): Transforms => { return { ...nonConfigurableClassNames.transforms, scale: ['', 'x-', 'y-'].flatMap(x => Object.keys(this._theme.scale).map(value => 'scale-' + x + value), ), rotate: Object.keys(this._theme.rotate).map(value => value.startsWith('-') ? '-rotate-' + value.slice(1) : `rotate-${value}`, ), // translate gets values from theme.spacing in addition to 50% and 100% variations // by default and theme.translate overrides this behaviour. translate: ['x', 'y'].flatMap(side => { return Object.keys( _.isEmpty(this._theme.translate) ? this._theme.spacing : this._theme.translate, ).map(value => value.startsWith('-') ? `-translate-${side}-${value.slice(1)}` : `translate-${side}-${value}`, ); }), skew: ['x', 'y'].flatMap(side => Object.keys(this._theme.skew).map(value => value.startsWith('-') ? `-skew-${side}-${value.substring(1)}` : `skew-${side}-${value}`, ), ), transformOrigin: Object.keys(this._theme.transformOrigin).map(value => 'origin-' + value), }; }; private interactivity = (): Interactivity => { const sides = ['', 'y', 'x', 't', 'r', 'b', 'l']; return { ...nonConfigurableClassNames.interactivity, cursor: Object.keys(this._theme.cursor).map(x => 'cursor-' + x), caretColor: this.generateClassesWithColors('caretColor'), willChange: Object.keys(this._theme.willChange).map(x => 'will-change-' + x), accentColor: this.generateClassesWithColors('accentColor'), scrollPadding: sides.flatMap(side => { return Object.keys(this._theme.scrollPadding).map(value => `scroll-p${side}-${value}`); }), scrollMargin: sides.flatMap(side => { return Object.keys(this._theme.scrollMargin).map(value => `scroll-m${side}-${value}`); }), }; }; private SVG = (): SVG => { return { ...nonConfigurableClassNames.svg, fill: Object.keys(this._theme.fill).map(value => 'fill-' + value), stroke: Object.keys(this._theme.stroke).map(value => 'stroke-' + value), strokeWidth: Object.keys(this._theme.strokeWidth).map(value => 'stroke-' + value), }; }; private accessibility = (): Accessibility => { return { ...nonConfigurableClassNames.accessibility, }; }; private filters = (): Filters => { return { ...nonConfigurableClassNames.filters, blur: Object.keys(this._theme.blur).map(x => 'blur-' + x), brightness: Object.keys(this._theme.brightness).map(x => 'brightness-' + x), contrast: Object.keys(this._theme.contrast).map(x => 'contrast-' + x), dropShadow: Object.keys(this._theme.dropShadow).map(x => 'drop-shadow-' + x), grayscale: Object.keys(this._theme.grayscale).map(x => 'grayscale-' + x), hueRotate: Object.keys(this._theme.hueRotate).map(x => x.startsWith('-') ? '-hue-rotate-' + x.slice(1) : 'hue-rotate-' + x, ), invert: Object.keys(this._theme.invert).map(x => 'invert-' + x), saturate: Object.keys(this._theme.saturate).map(x => 'saturate-' + x), sepia: Object.keys(this._theme.sepia).map(x => 'sepia-' + x), backdropBlur: Object.keys(this._theme.backdropBlur).map(x => 'backdrop-blur-' + x), backdropBrightness: Object.keys(this._theme.backdropBrightness).map( x => 'backdrop-brightness-' + x, ), backdropContrast: Object.keys(this._theme.backdropContrast).map( x => 'backdrop-contrast-' + x, ), backdropGrayscale: Object.keys(this._theme.backdropGrayscale).map( x => 'backdrop-grayscale-' + x, ), backdropHueRotate: Object.keys(this._theme.backdropHueRotate).map(x => x.startsWith('-') ? '-backdrop-hue-rotate-' + x.slice(1) : 'backdrop-hue-rotate-' + x, ), backdropInvert: Object.keys(this._theme.backdropInvert).map(x => 'backdrop-invert-' + x), backdropOpacity: Object.keys(this._theme.backdropOpacity).map(x => 'backdrop-opacity-' + x), backdropSaturate: Object.keys(this._theme.backdropSaturate).map( x => 'backdrop-saturate-' + x, ), backdropSepia: Object.keys(this._theme.backdropSepia).map(x => 'backdrop-sepia-' + x), }; }; private flexBox = (): FlexBox => { return { ...nonConfigurableClassNames.flexBox, flexBasis: Object.keys(this._theme.flexBasis).map(x => `basis-${x}`), flexGrow: Object.keys(this._theme.flexGrow).map(x => `grow-${x}`), flexShrink: Object.keys(this._theme.flexShrink).map(x => `shrink-${x}`), order: Object.keys(this._theme.order).map(x => `order-${x}`), }; }; private grid = (): Grid => { return { ...nonConfigurableClassNames.grid, gridTemplateColumns: Object.keys(this._theme.gridTemplateColumns).map( key => `grid-cols-${key}`, ), gridAutoColumns: Object.keys(this._theme.gridAutoColumns).map(key => `auto-cols-${key}`), gridColumn: Object.keys(this._theme.gridColumn).map(key => `col-${key}`), gridColumnStart: Object.keys(this._theme.gridColumnStart).map(key => `col-start-${key}`), gridColumnEnd: Object.keys(this._theme.gridColumnEnd).map(key => `col-end-${key}`), gridTemplateRows: Object.keys(this._theme.gridTemplateRows).map(key => `grid-rows-${key}`), gridAutoRows: Object.keys(this._theme.gridAutoRows).map(key => `auto-rows-${key}`), gridRow: Object.keys(this._theme.gridRow).map(key => `row-${key}`), gridRowStart: Object.keys(this._theme.gridRowStart).map(key => `row-start-${key}`), gridRowEnd: Object.keys(this._theme.gridRowEnd).map(key => `row-end-${key}`), gap: ['gap-', 'gap-y-', 'gap-x-'].flatMap(x => { // grid gap inherits its values from theme.spacing by default, but theme.gap overrides it. return Object.keys(_.isEmpty(this._theme.gap) ? this._theme.spacing : this._theme.gap).map( gapValue => x + gapValue, ); }), }; }; private spacing = (): Spacing => { const sides = ['', 'y', 'x', 't', 'r', 'b', 'l']; return { padding: sides.flatMap(side => { return Object.keys( _.isEmpty(this._theme.padding) ? this._theme.spacing : this._theme.padding, ).map(value => value.startsWith('-') ? `-p${side}-${value.slice(1)}` : `p${side}-${value}`, ); }), margin: sides.flatMap(side => { return Object.keys( _.isEmpty(this._theme.margin) ? this._theme.spacing : this._theme.margin, ).map(value => value.startsWith('-') ? `-m${side}-${value.slice(1)}` : `m${side}-${value}`, ); }), space: ['x', 'y'].flatMap(axis => { return Object.keys(_.isEmpty(this._theme.space) ? this._theme.spacing : this._theme.space) .concat('reverse') .map(key => { if (key.startsWith('-')) { key = key.slice(1); return '-space-' + axis + `-${key}`; } else { return `space-${axis}-${key}`; } }); }), }; }; private sizing = (): Sizing => { // prettier-ignore const extraWidthSizing = ['full', 'screen', 'auto', '1/2', '1/3', '2/3', '1/4', '2/4', '3/4', '1/5', '2/5', '3/5', '4/5', '1/6', '2/6', '3/6', '4/6', '5/6', '1/12', '2/12', '3/12', '4/12', '5/12', '6/12', '7/12', '8/12', '9/12', '10/12', '11/12']; const extraHeightSizing = ['full', 'screen']; return { ...nonConfigurableClassNames.sizing, // width values come from theme.spacing + `extraWidthSizing` by default // and theme.width overrides this default behaviour. // prettier-ignore width: (_.isEmpty(this._theme.width) ? Object.keys(this._theme.spacing).concat(extraWidthSizing) : Object.keys(this._theme.width)).map(x => 'w-' + x), minWidth: Object.keys(this._theme.minWidth).map(x => 'min-w-' + x), maxWidth: Object.keys(this._theme.maxWidth).map(x => 'max-w-' + x), // height values come from theme.spacing + `extraHeightSizing` by default // and overridden by theme.height. // prettier-ignore height: (_.isEmpty(this._theme.height) ? Object.keys(this._theme.spacing).concat(extraHeightSizing) : Object.keys(this._theme.height)).map(x => 'h-' + x), minHeight: Object.keys(this._theme.minHeight).map(x => 'min-h-' + x), maxHeight: Object.keys(this._theme.maxHeight).map(x => 'max-h-' + x), }; }; private typography = (): Typography => { return { ...nonConfigurableClassNames.typography, fontFamily: Object.keys(this._theme.fontFamily).map(value => 'font-' + value), fontSize: Object.keys(this._theme.fontSize).map(size => 'text-' + size), fontWeight: Object.keys(this._theme.fontWeight).map(weight => 'font-' + weight), letterSpacing: Object.keys(this._theme.letterSpacing).map(value => 'tracking-' + value), lineHeight: Object.keys(this._theme.lineHeight).map(value => 'leading-' + value), listStyleType: Object.keys(this._theme.listStyleType).map(value => 'list-' + value), placeholderColor: this.generateClassesWithColors('placeholderColor'), placeholderOpacity: this.getGeneratedClassesWithOpacities().placeholderOpacities, textColor: this.generateClassesWithColors('textColor'), textOpacity: this.getGeneratedClassesWithOpacities().textOpacities, content: Object.keys(this._theme.content).map(x => 'content-' + x), textIndent: Object.keys(this._theme.textIndent).map(x => 'indent-' + x), textDecorationColor: this.generateClassesWithColors('textDecorationColor'), textDecorationThickness: Object.keys(this._theme.textDecorationThickness).map( x => 'decoration-' + x, ), textUnderlineOffset: Object.keys(this._theme.textUnderlineOffset).map( x => 'underline-offset-' + x, ), }; }; // Generate the types for pseudo classes as hover:, focus: etc. // and return them in a string array to be parsed and converted into a template string that // will be a part of the final generated file. See `FileContentGenerator` class. private pseudoClasses = (): string[] => { // Initialise a pseudoClasses array with base values. const pseudoClasses: string[] = ['peer', 'group']; if (this._darkMode === 'class') pseudoClasses.push('dark'); // Get the variants from config const variants = this._configParser.getVariants(); for (const regularClassGroupKey of regularClassGroupKeys) { Object.keys(this._generatedRegularClassnames).map(key => { // If the current key is found to be a member of the generated regular classes group... if ( _.has(this._generatedRegularClassnames[key as keyof TAllClassnames], regularClassGroupKey) ) { // Get the value of the found generated class group let generatedClassGroup = _.get( this._generatedRegularClassnames, `${key}.${regularClassGroupKey}`, ) as string[]; // Duplicate classnames with an important (!) prefix const generatedClassGroupWithImportantPrefix = generatedClassGroup.map(cls => '!' + cls); // Append the classnames with important prefix to the regular classnames generatedClassGroup = generatedClassGroup.concat(generatedClassGroupWithImportantPrefix); // Append the classnames with important prefix to the pseudo classes array generatedClassGroupWithImportantPrefix.map(cls => pseudoClasses.push(cls)); // For every member of the found regular classes group... generatedClassGroup.map(classname => { // Generate the classname of each variant... variants.map(variant => { // Append the variant to the classname and push to the pseudoClasses array. pseudoClasses.push(variant + this._separator + this._prefix + classname); }); }); } }); } // After all is done, return the generated pseudo classes types array return pseudoClasses; }; private generateClassesWithColors = (property: ClassesWithColors): string[] => { // Get the key-value pairs of the passed property const [propertyKeys, propertyValues] = this._configParser.getThemeProperty(property); // Convert the config property names into utility class names const utilName = property .replace('Color', '') // gradientColorStops -> gradientStops, borderColor -> border etc. .replace('Stops', '') // gradientStops -> gradient .replace('ringOffset', 'ring-offset') .replace('boxShadow', 'shadow') .replace('textDecoration', 'decoration') .replace('background', 'bg'); const classnamesWithColors = propertyKeys // For every key of the property... .flatMap((colorName, i) => { // Exclude `DEFAULT` keys from the keys collection as they do not correspond to any classname. if (propertyKeys[i] === 'DEFAULT') return null; // Get the value that corresponds to that key. NOTE: It can be `string` or an `object` of shades. const colorValue = propertyValues[i]; // If the value is a nested object of color shades... if (typeof colorValue === 'object' && colorValue !== null) { // Loop over the deep objects and return the result for each key of the object. return Object.keys(colorValue).flatMap(shade => { if (utilName === 'border') { return ['', 't', 'r', 'b', 'l', 'x', 'y'].map( side => `${utilName}-${side.length > 0 ? side + '-' : ''}${colorName}-${shade}`, ); } else { return `${utilName}-${colorName}-${shade}`; } }); } // Otherwise... else { // Return the result of merging the utility name with color value if (utilName === 'border') { return ['', 't', 'r', 'b', 'l'].map( side => `${utilName}-${side.length > 0 ? side + '-' : ''}${colorName}`, ); } else { return `${utilName}-${colorName}`; } } }) .filter(Boolean) as string[]; // // Add the opacities short hand suffix `/{opacity}`: "bg-red-100/50" // const classnamesWithColorsAndOpacitySuffix = Object.keys( // this._configParser.getTheme().opacity, // ).flatMap(op => classnamesWithColors.map(cls => cls + '/' + op)); return classnamesWithColors; }; private getGeneratedClassesWithOpacities = (): ClassesWithOpacities => { const allOpacities = this._configParser.getTheme().opacity; // prettier-ignore type TOpacityProp = | 'divideOpacity' | 'textOpacity' | 'backgroundOpacity' | 'borderOpacity' | 'placeholderOpacity' | 'ringOpacity' const getOpacity = (themePropertyName: TOpacityProp, outputNamePrefix: string): string[] => { const generatedOpacities = generateOpacities(allOpacities, this._theme, themePropertyName); return Object.keys(generatedOpacities).map( opacity => `${outputNamePrefix}-opacity-${opacity}`, ); }; function generateOpacities( defaultOpacities: Record<string, string>, theme: TConfigTheme, property: keyof Omit<TConfigTheme, 'extend'>, ): Record<string, string> { const themeOpacities = _.isEmpty(theme[property]) ? defaultOpacities : theme[property]; const extendedThemeOpacities = theme.extend?.[property]; const result = extendedThemeOpacities ? {...themeOpacities, ...extendedThemeOpacities} : themeOpacities; return result as Record<string, string>; } return { opacities: Object.keys(allOpacities).map(opacity => `opacity-${opacity}`), textOpacities: getOpacity('textOpacity', 'text'), backgroundOpacities: getOpacity('backgroundOpacity', 'bg'), borderOpacities: getOpacity('borderOpacity', 'border'), divideOpacities: getOpacity('divideOpacity', 'divide'), placeholderOpacities: getOpacity('placeholderOpacity', 'placeholder'), ringOpacities: getOpacity('ringOpacity', 'ring'), }; }; } type ClassesWithColors = | 'caretColor' | 'backgroundColor' | 'divideColor' | 'placeholderColor' | 'textColor' | 'borderColor' | 'ringColor' | 'ringOffsetColor' | 'gradientColorStops' | 'boxShadowColor' | 'outlineColor' | 'textDecorationColor' | 'accentColor'; type ClassesWithOpacities = { opacities: string[]; textOpacities: string[]; backgroundOpacities: string[]; borderOpacities: string[]; divideOpacities: string[]; placeholderOpacities: string[]; ringOpacities: string[]; };
the_stack
import { FileManager } from '../../../src/file-manager/base/file-manager'; import { NavigationPane } from '../../../src/file-manager/layout/navigation-pane'; import { DetailsView } from '../../../src/file-manager/layout/details-view'; import { Toolbar } from '../../../src/file-manager/actions/toolbar'; import { createElement, Browser, EventHandler, isNullOrUndefined, select } from '@syncfusion/ej2-base'; import { toolbarItems, toolbarItems1, data1, data2, folderRename, dataSortbySize, singleSelectionDetails, rename, data3, data4, data5, dataDelete, data6, data7, data8, data9, data12, data14, UploadData, data15, data11, accessData1, accessDetails1, accessDetails2, accessData2, data18, accessSearchData, data14Rename } from '../data'; import { FileOpenEventArgs } from '../../../src/file-manager/base/interface'; import { MenuOpenEventArgs, MenuClickEventArgs } from '../../../src'; FileManager.Inject(Toolbar, NavigationPane, DetailsView); describe('FileManager control LargeIcons view', () => { describe('Navigation pane right click testing', () =>{ let i: number = 0; let mouseEventArgs: any, tapEvent: any; let feObj: any; let ele: HTMLElement; let originalTimeout: any; beforeEach((done: Function): void => { jasmine.Ajax.install(); feObj = undefined; ele = createElement('div', { id: 'file' }); document.body.appendChild(ele); feObj = new FileManager({ view: 'LargeIcons', ajaxSettings: { url: '/FileOperations', uploadUrl: '/Upload', downloadUrl: '/Download', getImageUrl: '/GetImage' }, fileOpen: (args: FileOpenEventArgs) => { i++ }, showThumbnail: false }); feObj.appendTo('#file'); this.request = jasmine.Ajax.requests.mostRecent(); this.request.respondWith({ status: 200, responseText: JSON.stringify(data1) }); originalTimeout = jasmine.DEFAULT_TIMEOUT_INTERVAL; jasmine.DEFAULT_TIMEOUT_INTERVAL = 50000; mouseEventArgs = { preventDefault: (): void => { }, stopImmediatePropagation: (): void => { }, target: null, type: null, shiftKey: false, ctrlKey: false, originalEvent: { target: null } }; tapEvent = { originalEvent: mouseEventArgs, tapCount: 1 }; setTimeout(function () { let menuObj: any = (document.getElementById(feObj.element.id + '_contextmenu') as any).ej2_instances[0]; menuObj.animationSettings = { effect: 'None' }; menuObj.dataBind(); done(); }, 500); }); afterEach((): void => { i = 0; jasmine.Ajax.uninstall(); if (feObj) feObj.destroy(); ele.remove(); jasmine.DEFAULT_TIMEOUT_INTERVAL = originalTimeout; }); it('Navigation pane right clik folder navigation testing', (done: Function) => { let li: any = document.getElementById('file_tree').querySelectorAll('li'); mouseEventArgs.originalEvent.target = li[1].querySelector('.e-fullrow'); mouseEventArgs.originalEvent.which = 3; feObj.navigationpaneModule.treeObj.clickHandler(mouseEventArgs); feObj.navigationpaneModule.treeObj.dataBind(); setTimeout(() => { expect(feObj.path).toBe('/Documents/'); done(); }, 500); }) it('Navigation pane right clik folder navigation cancel testing', (done: Function) => { let restrict: any = true; feObj.fileOpen = function(args: FileOpenEventArgs){ args.cancel = restrict; } let li = document.getElementById('file_tree').querySelectorAll('li'); mouseEventArgs.originalEvent.target = li[1].querySelector('.e-fullrow'); mouseEventArgs.originalEvent.which = 3; feObj.navigationpaneModule.treeObj.clickHandler(mouseEventArgs); let evt = document.createEvent('MouseEvents'); evt.initEvent('contextmenu', true, true); li[1].dispatchEvent(evt); feObj.contextmenuModule.contextMenu.dataBind(); feObj.navigationpaneModule.treeObj.dataBind(); let el: any = document.getElementById(feObj.element.id + '_contextmenu'); let sourceElement: any = el.ej2_instances[0]; expect(sourceElement.element.querySelectorAll('li')[0].innerText).toBe('Open'); expect(sourceElement.element.querySelectorAll('li')[0].classList.contains('e-disabled')).toBe(false); expect(feObj.path).toBe('/'); restrict = false; sourceElement.element.querySelectorAll('li')[0].click(); setTimeout(() => { expect(feObj.path).toBe('/Documents/'); done(); }, 500); }) }) describe('context menu testing', () => { let i: number = 0; let mouseEventArgs: any, tapEvent: any; let feObj: any; let ele: HTMLElement; let originalTimeout: any; beforeEach((done: Function): void => { jasmine.Ajax.install(); feObj = undefined; ele = createElement('div', { id: 'file' }); document.body.appendChild(ele); feObj = new FileManager({ view: 'LargeIcons', ajaxSettings: { url: '/FileOperations', uploadUrl: '/Upload', downloadUrl: '/Download', getImageUrl: '/GetImage' }, fileOpen: (args: FileOpenEventArgs) => { i++ }, showThumbnail: false }); feObj.appendTo('#file'); this.request = jasmine.Ajax.requests.mostRecent(); this.request.respondWith({ status: 200, responseText: JSON.stringify(data1) }); originalTimeout = jasmine.DEFAULT_TIMEOUT_INTERVAL; jasmine.DEFAULT_TIMEOUT_INTERVAL = 50000; mouseEventArgs = { preventDefault: (): void => { }, stopImmediatePropagation: (): void => { }, target: null, type: null, shiftKey: false, ctrlKey: false, originalEvent: { target: null } }; tapEvent = { originalEvent: mouseEventArgs, tapCount: 1 }; setTimeout(function () { let menuObj: any = (document.getElementById(feObj.element.id + '_contextmenu') as any).ej2_instances[0]; menuObj.animationSettings = { effect: 'None' }; menuObj.dataBind(); done(); }, 500); }); afterEach((): void => { i = 0; jasmine.Ajax.uninstall(); if (feObj) feObj.destroy(); ele.remove(); jasmine.DEFAULT_TIMEOUT_INTERVAL = originalTimeout; }); // it('folder context menu open process testing', (done: Function) => { // let el: any = document.getElementById(feObj.element.id + '_contextmenu'); // let li: any = document.getElementById('file_largeicons').querySelectorAll('li'); // expect(li.length).toBe(5); // mouseEventArgs.target = li[0]; // tapEvent.tapCount = 1; // feObj.largeiconsviewModule.clickObj.tap(tapEvent); // expect(li[0].textContent).toBe('Documents'); // let sourceElement: any = el.ej2_instances[0]; // let evt = document.createEvent('MouseEvents') // evt.initEvent('contextmenu', true, true); // li[0].dispatchEvent(evt); // setTimeout(function () { // sourceElement.element.querySelectorAll('li')[0].click(); // this.request = jasmine.Ajax.requests.mostRecent(); // this.request.respondWith({ // status: 200, // responseText: JSON.stringify(data1) // }); // jasmine.DEFAULT_TIMEOUT_INTERVAL = 1000; // setTimeout(function () { // let li1: any = document.getElementById('file_largeicons').querySelectorAll('li'); // expect(li1.length).toBe(5); // let li2: Element[] = <Element[] & NodeListOf<HTMLLIElement>>document.getElementById('file_tree').querySelectorAll('li'); // expect((li2[0] as Element).classList.contains('e-active')).toBe(false); // expect((li2[1] as Element).classList.contains('e-active')).toBe(true); // expect((li2[1] as HTMLElement).innerText.trim()).toBe('Documents'); // done(); // }, 500); // }, 500); // }); it('folder context menu open process testing with (right and left click testing) mouse double click', (done: Function) => { let el: any = document.getElementById(feObj.element.id + '_contextmenu'); let li: any = document.getElementById('file_largeicons').querySelectorAll('li'); expect(li.length).toBe(5); mouseEventArgs.target = li[0]; mouseEventArgs.which = 3; tapEvent.tapCount = 2; feObj.largeiconsviewModule.clickObj.tap(tapEvent); expect(li[0].textContent).toBe('Documents'); let sourceElement: any = el.ej2_instances[0]; let evt = document.createEvent('MouseEvents') evt.initEvent('contextmenu', true, true); li[0].dispatchEvent(evt); sourceElement.element.querySelectorAll('li')[0].click(); this.request = jasmine.Ajax.requests.mostRecent(); this.request.respondWith({ status: 200, responseText: JSON.stringify(data1) }); setTimeout(function () { let li1: any = document.getElementById('file_largeicons').querySelectorAll('li'); expect(li1.length).toBe(5); let li2: Element[] = <Element[] & NodeListOf<HTMLLIElement>>document.getElementById('file_tree').querySelectorAll('li'); expect((li2[0] as Element).classList.contains('e-active')).toBe(false); expect((li2[1] as Element).classList.contains('e-active')).toBe(true); expect((li2[1] as HTMLElement).innerText.trim()).toBe('Documents'); done(); }, 500); }); // it('mouse click on refresh button', (done: Function) => { // let ele: any = document.getElementById(feObj.element.id + '_contextmenu'); // let menuObj: any = ele.ej2_instances[0]; // let lgli: any = document.getElementById('file_largeicons').querySelectorAll('li'); // mouseEventArgs.target = lgli[1]; // feObj.largeiconsviewModule.clickObj.tap(tapEvent); // mouseEventArgs.ctrlKey = true; // mouseEventArgs.target = lgli[2]; // feObj.largeiconsviewModule.clickObj.tap(tapEvent); // document.getElementById('file_tree').querySelectorAll('li')[1].remove(); // lgli[0].remove(); // document.getElementsByClassName('e-addressbar-ul')[0].querySelector('li').remove(); // let li: any = document.getElementById('file_tree').querySelectorAll('li'); // let tr: any = document.getElementById('file_largeicons').querySelectorAll('li'); // let ar: any = document.getElementsByClassName('e-addressbar-ul')[0].querySelectorAll('li'); // expect(li.length).toEqual(4); // expect(tr.length).toEqual(4); // expect(ar.length).toEqual(0); // expect(tr[0].classList.contains('e-active')).toBe(true); // expect(tr[0].querySelector('.e-frame').classList.contains('e-check')).toBe(true); // expect(tr[1].classList.contains('e-active')).toBe(true); // expect(tr[1].querySelector('.e-frame').classList.contains('e-check')).toBe(true); // let largeWrap: Element = feObj.largeiconsviewModule.element.children[0]; // let evt = document.createEvent('MouseEvents'); // evt.initEvent('contextmenu', true, true); // largeWrap.dispatchEvent(evt); // setTimeout(function () { // // menuObj.element.querySelector('.e-fe-refresh').click(); // this.request = jasmine.Ajax.requests.mostRecent(); // this.request.respondWith({ // status: 200, // responseText: JSON.stringify(data1) // }); // jasmine.DEFAULT_TIMEOUT_INTERVAL = 10000; // setTimeout(function () { // let nli: any = document.getElementById('file_tree').querySelectorAll('li'); // let ntr: any = document.getElementById('file_largeicons').querySelectorAll('li'); // let nar: any = document.getElementsByClassName('e-addressbar-ul')[0].querySelectorAll('li'); // expect(nli.length).toEqual(5); // expect(ntr.length).toEqual(5); // expect(nar.length).toEqual(1); // expect(ntr[1].classList.contains('e-active')).toBe(true); // expect(ntr[1].querySelector('.e-frame').classList.contains('e-check')).toBe(true); // expect(ntr[2].classList.contains('e-active')).toBe(true); // expect(ntr[2].querySelector('.e-frame').classList.contains('e-check')).toBe(true); // done(); // }, 500); // }, 100); // }); it('non-image file context menu open process testing', (done) => { let el: any = document.getElementById(feObj.element.id + '_contextmenu'); let li: any = document.getElementById('file_largeicons').querySelectorAll('li'); expect(li.length).toBe(5); mouseEventArgs.target = li[0]; tapEvent.tapCount = 1; feObj.largeiconsviewModule.clickObj.tap(tapEvent); expect(li[0].textContent).toBe('Documents'); let sourceElement: any = el.ej2_instances[0]; let evt = document.createEvent('MouseEvents') evt.initEvent('contextmenu', true, true); li[0].dispatchEvent(evt); expect(sourceElement.element.querySelectorAll('li')[0].innerText).toBe('Open'); expect(sourceElement.element.querySelectorAll('li')[0].classList.contains('e-disabled')).toBe(false); sourceElement.element.querySelectorAll('li')[0].click(); this.request = jasmine.Ajax.requests.mostRecent(); this.request.respondWith({ status: 200, responseText: JSON.stringify(data11) }); setTimeout(function () { li = document.getElementById('file_largeicons').querySelectorAll('li'); mouseEventArgs.target = li[1]; tapEvent.tapCount = 1; feObj.largeiconsviewModule.clickObj.tap(tapEvent); expect(li[1].textContent).toBe('music.mp3'); let evt = document.createEvent('MouseEvents') evt.initEvent('contextmenu', true, true); li[1].dispatchEvent(evt); expect(sourceElement.element.querySelectorAll('li')[0].innerText).toBe('Open'); expect(sourceElement.element.querySelectorAll('li')[0].classList.contains('e-disabled')).toBe(false); sourceElement.element.querySelectorAll('li')[0].click(); expect(i > 1).toBe(true); done(); }, 500); }); it('setmodel context menu testing', () => { feObj.contextMenuSettings.visible = false; feObj.dataBind(); let el: any = document.getElementById(feObj.element.id + '_contextmenu'); expect(el !== null).toBe(true); expect(isNullOrUndefined((feObj as FileManager).contextmenuModule)).toBe(true); feObj.contextMenuSettings.visible = true; feObj.dataBind(); el = document.getElementById(feObj.element.id + '_contextmenu'); expect(el !== null).toBe(true); expect(isNullOrUndefined((feObj as FileManager).contextmenuModule)).toBe(false); }); it('folder context menu in tree view open item testing', () => { let el: any = document.getElementById(feObj.element.id + '_contextmenu'); let Li: Element = feObj.navigationpaneModule.treeObj.element.querySelectorAll("li")[2]; let sourceElement: any = el.ej2_instances[0]; let evt = document.createEvent('MouseEvents') evt.initEvent('contextmenu', true, true); Li.dispatchEvent(evt); expect(sourceElement.element.querySelectorAll('li')[0].innerText).toBe('Open'); expect(sourceElement.element.querySelectorAll('li')[0].classList.contains('e-disabled')).toBe(true); }); }); describe('for LargeIcons View context menu', () => { let mouseEventArgs: any, tapEvent: any; let feObj: any; let ele: HTMLElement; let originalTimeout: any; let type: string = ""; let count: number = 0; function menuopened(eventArgs: MenuOpenEventArgs) { count++; type = eventArgs.menuType; } function addCustomItems(args: MenuOpenEventArgs) { for (var item = 0; item < args.items.length; item++) { if ((args.items[item].text == "Custom1") && (args.items[item].items.length === 0)) { args.items[item].items = [{ text: 'Google', iconCss: "e-fe-tick e-icons", id: 'item1' }, { text: 'Gmail', id: 'item2' }]; } } menuopened(args); } beforeEach((done: Function): void => { jasmine.Ajax.install(); feObj = undefined; ele = createElement('div', { id: 'file' }); document.body.appendChild(ele); feObj = new FileManager({ view: 'LargeIcons', ajaxSettings: { url: '/FileOperations', uploadUrl: '/Upload', downloadUrl: '/Download', getImageUrl: '/GetImage' }, showThumbnail: false }); feObj.appendTo('#file'); this.request = jasmine.Ajax.requests.mostRecent(); this.request.respondWith({ status: 200, responseText: JSON.stringify(data14) }); originalTimeout = jasmine.DEFAULT_TIMEOUT_INTERVAL; jasmine.DEFAULT_TIMEOUT_INTERVAL = 50000; mouseEventArgs = { preventDefault: (): void => { }, stopImmediatePropagation: (): void => { }, target: null, type: null, shiftKey: false, ctrlKey: false, originalEvent: { target: null } }; tapEvent = { originalEvent: mouseEventArgs, tapCount: 1 }; setTimeout(function () { let menuObj: any = (document.getElementById(feObj.element.id + '_contextmenu') as any).ej2_instances[0]; menuObj.animationSettings = { effect: 'None' }; menuObj.dataBind(); done(); }, 500); }); afterEach((): void => { count = 0; jasmine.Ajax.uninstall(); if (feObj) feObj.destroy(); ele.remove(); jasmine.DEFAULT_TIMEOUT_INTERVAL = originalTimeout; }); it('upload process testing', (done) => { let el: any = document.getElementById(feObj.element.id + '_contextmenu'); let li: any = document.getElementById('file_largeicons'); mouseEventArgs.target = li; tapEvent.tapCount = 1; feObj.largeiconsviewModule.clickObj.tap(tapEvent); let sourceElement: any = el.ej2_instances[0]; let evt = document.createEvent('MouseEvents') evt.initEvent('contextmenu', true, true); li.dispatchEvent(evt); sourceElement.element.querySelectorAll('#file_cm_upload')[0].click(); let fileObj: File = new File(["Nice One"], "sample.txt", { lastModified: 0, type: "overide/mimetype" }) let eventArgs: any = { type: 'click', target: { files: [fileObj] }, preventDefault: (): void => { } }; let uploadObj: any = document.querySelector('#' + feObj.element.id + '_upload'); uploadObj.ej2_instances[0].onSelectFiles(eventArgs); this.request = jasmine.Ajax.requests.mostRecent(); this.request.respondWith({ status: 200, responseText: JSON.stringify(UploadData) }); setTimeout(function () { let li1: any = document.getElementById('file_largeicons').querySelectorAll('li')[0]; mouseEventArgs.target = li1.querySelector(".e-text-content"); done(); }, 500); }); it('folder context menu with open', (done: Function) => { let el: any = document.getElementById(feObj.element.id + '_contextmenu'); let li: any = document.getElementById('file_largeicons').querySelectorAll('li'); expect(li.length).toBe(3); mouseEventArgs.target = li[0]; tapEvent.tapCount = 1; feObj.largeiconsviewModule.clickObj.tap(tapEvent); expect(li[0].textContent).toBe('Documents'); let sourceElement: any = el.ej2_instances[0]; let evt = document.createEvent('MouseEvents') evt.initEvent('contextmenu', true, true); li[0].dispatchEvent(evt); expect(sourceElement.element.querySelectorAll('li')[0].innerText).toBe('Open'); expect(sourceElement.element.querySelectorAll('li')[0].classList.contains('e-disabled')).toBe(false); sourceElement.element.querySelectorAll('li')[0].click(); this.request = jasmine.Ajax.requests.mostRecent(); this.request.respondWith({ status: 200, responseText: JSON.stringify(data1) }); setTimeout(function () { let nar: any = document.getElementsByClassName('e-addressbar-ul')[0].querySelectorAll('li'); let li1: any = document.getElementById('file_largeicons').querySelectorAll('li'); expect(li1.length).toBe(5); expect(document.getElementsByClassName('e-addressbar-ul')[0].querySelectorAll('li')[1].textContent).toBe("Documents"); let li2: Element[] = <Element[] & NodeListOf<HTMLLIElement>>document.getElementById('file_tree').querySelectorAll('li'); expect((li2[0] as Element).classList.contains('e-active')).toBe(false); expect((li2[1] as Element).classList.contains('e-active')).toBe(true); expect((li2[1] as HTMLElement).innerText.trim()).toBe('Documents'); done(); }, 500); }); it('folder context menu with delete', (done: Function) => { let el: any = document.getElementById(feObj.element.id + '_contextmenu'); let li: any = document.getElementById('file_tree').querySelectorAll('li'); let ntr: any = document.getElementById('file_largeicons').querySelectorAll('li'); expect(li.length).toEqual(4); expect(ntr.length).toEqual(3); mouseEventArgs.target = ntr[0]; tapEvent.tapCount = 1; feObj.largeiconsviewModule.clickObj.tap(tapEvent); expect(ntr[0].textContent).toBe('Documents'); let sourceElement: any = el.ej2_instances[0]; let evt = document.createEvent('MouseEvents') evt.initEvent('contextmenu', true, true); ntr[0].dispatchEvent(evt); sourceElement.element.querySelectorAll('#file_cm_delete')[0].click(); (document.getElementById('file_dialog').querySelectorAll('.e-btn')[1] as HTMLElement).click(); this.request = jasmine.Ajax.requests.mostRecent(); this.request.respondWith({ status: 200, responseText: JSON.stringify(data1) }); this.request = jasmine.Ajax.requests.mostRecent(); this.request.respondWith({ status: 200, responseText: JSON.stringify(dataDelete) }); setTimeout(function () { let nli: any = document.getElementById('file_tree').querySelectorAll('li'); let ntr: any = document.getElementById('file_largeicons').querySelectorAll('li'); let nar: any = document.getElementsByClassName('e-addressbar-ul')[0].querySelectorAll('li'); expect(nli.length).toEqual(4); expect(ntr.length).toEqual(4); done(); }, 500); }); it('folder context menu with rename', (done: Function) => { let el: any = document.getElementById(feObj.element.id + '_contextmenu'); let li: any = document.getElementById('file_tree').querySelectorAll('li'); let ntr: any = document.getElementById('file_largeicons').querySelectorAll('li'); expect(li.length).toEqual(4); expect(ntr.length).toEqual(3); mouseEventArgs.target = ntr[0]; tapEvent.tapCount = 1; feObj.largeiconsviewModule.clickObj.tap(tapEvent); expect(ntr[0].textContent).toBe('Documents'); let sourceElement: any = el.ej2_instances[0]; let evt = document.createEvent('MouseEvents') evt.initEvent('contextmenu', true, true); ntr[0].dispatchEvent(evt); sourceElement.element.querySelectorAll('#file_cm_rename')[0].click(); expect(ntr[0].textContent).toBe("Documents"); (<HTMLInputElement>document.getElementById('rename')).value = "My Folder"; (<HTMLElement>document.getElementById('file_dialog').querySelectorAll('.e-btn')[1]).click(); this.request = jasmine.Ajax.requests.mostRecent(); this.request.respondWith({ status: 200, responseText: JSON.stringify(folderRename) }); this.request = jasmine.Ajax.requests.mostRecent(); this.request.respondWith({ status: 200, responseText: JSON.stringify(data14Rename) }); setTimeout(function () { let nli: any = document.getElementById('file_tree').querySelectorAll('li'); let ntr: any = document.getElementById('file_largeicons').querySelectorAll('li'); let nar: any = document.getElementsByClassName('e-addressbar-ul')[0].querySelectorAll('li'); expect(nli.length).toEqual(4); expect(ntr.length).toEqual(3); expect(nar.length).toEqual(1); expect(ntr[2].textContent).toBe("My Folder"); expect(nli[1].textContent).toBe("My Folder"); done(); }, 500); }); it('folder context menu with details', (done: Function) => { let el: any = document.getElementById(feObj.element.id + '_contextmenu'); let li: any = document.getElementById('file_tree').querySelectorAll('li'); let ntr: any = document.getElementById('file_largeicons').querySelectorAll('li'); expect(li.length).toEqual(4); expect(ntr.length).toEqual(3); mouseEventArgs.target = ntr[0]; tapEvent.tapCount = 1; feObj.largeiconsviewModule.clickObj.tap(tapEvent); expect(ntr[0].textContent).toBe('Documents'); let sourceElement: any = el.ej2_instances[0]; let evt = document.createEvent('MouseEvents') evt.initEvent('contextmenu', true, true); ntr[0].dispatchEvent(evt); sourceElement.element.querySelectorAll('#file_cm_details')[0].click(); expect(ntr[0].textContent).toBe("Documents"); this.request = jasmine.Ajax.requests.mostRecent(); this.request.respondWith({ status: 200, responseText: JSON.stringify(singleSelectionDetails) }); setTimeout(function () { let nli: any = document.getElementById('file_tree').querySelectorAll('li'); let ntr: any = document.getElementById('file_largeicons').querySelectorAll('li'); let nar: any = document.getElementsByClassName('e-addressbar-ul')[0].querySelectorAll('li'); expect(nli.length).toEqual(4); expect(ntr.length).toEqual(3); expect(nar.length).toEqual(1); expect(document.getElementById('file_dialog_title').textContent).toBe('Documents') expect(document.querySelectorAll('.e-fe-value').length).toBe(4) expect((<any>document.querySelectorAll('.e-fe-value')[0]).textContent).toBe('Folder') // expect((<any>document.querySelectorAll('.e-fe-value')[1]).textContent).toBe('0') expect((<any>document.querySelectorAll('.e-fe-value')[2]).textContent).toBe('/Documents') expect((<any>document.querySelectorAll('.e-fe-value')[3]).textContent).toBe('October 16, 2018 19:43:17') done(); }, 500); }); it('file context menu open process testing', (done) => { let el: any = document.getElementById(feObj.element.id + '_contextmenu'); let li: any = document.getElementById('file_largeicons').querySelectorAll('li'); expect(li.length).toBe(3); mouseEventArgs.target = li[2]; tapEvent.tapCount = 1; feObj.largeiconsviewModule.clickObj.tap(tapEvent); expect(li[2].textContent).toBe('Food'); let sourceElement: any = el.ej2_instances[0]; let evt = document.createEvent('MouseEvents') evt.initEvent('contextmenu', true, true); li[2].dispatchEvent(evt); expect(sourceElement.element.querySelectorAll('li')[0].innerText).toBe('Open'); expect(sourceElement.element.querySelectorAll('li')[0].classList.contains('e-disabled')).toBe(false); sourceElement.element.querySelectorAll('li')[0].click(); this.request = jasmine.Ajax.requests.mostRecent(); this.request.respondWith({ status: 200, responseText: JSON.stringify(data15) }); setTimeout(function () { li = document.getElementById('file_largeicons').querySelectorAll('li'); mouseEventArgs.target = li[0]; tapEvent.tapCount = 1; feObj.largeiconsviewModule.clickObj.tap(tapEvent); expect(li[0].textContent).toBe('Bread.png'); let evt = document.createEvent('MouseEvents') evt.initEvent('contextmenu', true, true); li[0].dispatchEvent(evt); expect(sourceElement.element.querySelectorAll('li')[0].innerText).toBe('Open'); expect(sourceElement.element.querySelectorAll('li')[0].classList.contains('e-disabled')).toBe(false); sourceElement.element.querySelectorAll('li')[0].click(); done(); }, 500); }); it('layout context menu with details', (done: Function) => { let el: any = document.getElementById(feObj.element.id + '_contextmenu'); let li: any = document.getElementById('file_largeicons'); mouseEventArgs.target = li; tapEvent.tapCount = 1; feObj.largeiconsviewModule.clickObj.tap(tapEvent); let sourceElement: any = el.ej2_instances[0]; let evt = document.createEvent('MouseEvents') evt.initEvent('contextmenu', true, true); li.dispatchEvent(evt); sourceElement.element.querySelectorAll('#file_cm_details')[0].click(); this.request = jasmine.Ajax.requests.mostRecent(); this.request.respondWith({ status: 200, responseText: JSON.stringify(singleSelectionDetails) }); setTimeout(function () { let nli: any = document.getElementById('file_tree').querySelectorAll('li'); let ntr: any = document.getElementById('file_largeicons').querySelectorAll('li'); let nar: any = document.getElementsByClassName('e-addressbar-ul')[0].querySelectorAll('li'); expect(nli.length).toEqual(4); expect(ntr.length).toEqual(3); expect(nar.length).toEqual(1); expect(document.getElementById('file_dialog_title').textContent).toBe('Documents') expect(document.querySelectorAll('.e-fe-value').length).toBe(4) expect((<any>document.querySelectorAll('.e-fe-value')[0]).textContent).toBe('Folder') // expect((<any>document.querySelectorAll('.e-fe-value')[1]).textContent).toBe('0') expect((<any>document.querySelectorAll('.e-fe-value')[2]).textContent).toBe('/Documents') expect((<any>document.querySelectorAll('.e-fe-value')[3]).textContent).toBe('October 16, 2018 19:43:17') done(); }, 500); }); it('layout context menu with new folder', (done: Function) => { let el: any = document.getElementById(feObj.element.id + '_contextmenu'); let li: any = document.getElementById('file_largeicons'); mouseEventArgs.target = li; tapEvent.tapCount = 1; feObj.largeiconsviewModule.clickObj.tap(tapEvent); let sourceElement: any = el.ej2_instances[0]; let evt = document.createEvent('MouseEvents') evt.initEvent('contextmenu', true, true); li.dispatchEvent(evt); let nli: any = document.getElementById('file_tree').querySelectorAll('li'); let ntr: any = document.getElementById('file_largeicons').querySelectorAll('li'); let nar: any = document.getElementsByClassName('e-addressbar-ul')[0].querySelectorAll('li'); expect(nli.length).toEqual(4); expect(ntr.length).toEqual(3); expect(nar.length).toEqual(1); sourceElement.element.querySelectorAll('#file_cm_newfolder')[0].click(); let items: any = document.getElementsByClassName('e-fe-newfolder'); items[0].click(); (<HTMLInputElement>document.getElementById('newname')).value = "New Folder"; (<HTMLElement>document.getElementById('file_dialog').querySelectorAll('.e-btn')[1]).click(); this.request = jasmine.Ajax.requests.mostRecent(); this.request.respondWith({ status: 200, responseText: JSON.stringify(data1) }); this.request = jasmine.Ajax.requests.mostRecent(); this.request.respondWith({ status: 200, responseText: JSON.stringify(data5) }); setTimeout(function () { let nli: any = document.getElementById('file_tree').querySelectorAll('li'); let ntr: any = document.getElementById('file_largeicons').querySelectorAll('li'); let nar: any = document.getElementsByClassName('e-addressbar-ul')[0].querySelectorAll('li'); expect(nli.length).toEqual(6); expect(ntr.length).toEqual(6); expect(nar.length).toEqual(1); expect(ntr[1].classList.contains('e-active')).toBe(false); expect(ntr[1].querySelector('.e-frame').classList.contains('e-check')).toBe(false); expect(ntr[2].classList.contains('e-active')).toBe(false); expect(ntr[2].querySelector('.e-frame').classList.contains('e-check')).toBe(false); done(); }, 500); }); it('layout context menu with refresh', (done: Function) => { let el: any = document.getElementById(feObj.element.id + '_contextmenu'); let li: any = document.getElementById('file_largeicons'); mouseEventArgs.target = li; tapEvent.tapCount = 1; feObj.largeiconsviewModule.clickObj.tap(tapEvent); let sourceElement: any = el.ej2_instances[0]; let evt = document.createEvent('MouseEvents') evt.initEvent('contextmenu', true, true); li.dispatchEvent(evt); let nli: any = document.getElementById('file_tree').querySelectorAll('li'); let ntr: any = document.getElementById('file_largeicons').querySelectorAll('li'); let nar: any = document.getElementsByClassName('e-addressbar-ul')[0].querySelectorAll('li'); expect(nli.length).toEqual(4); expect(ntr.length).toEqual(3); expect(nar.length).toEqual(1); sourceElement.element.querySelectorAll('#file_cm_refresh')[0].click(); let lgli: any = document.getElementById('file_largeicons').querySelectorAll('li'); mouseEventArgs.target = lgli[1]; feObj.largeiconsviewModule.clickObj.tap(tapEvent); mouseEventArgs.ctrlKey = true; mouseEventArgs.target = lgli[2]; feObj.largeiconsviewModule.clickObj.tap(tapEvent); document.getElementById('file_tree').querySelectorAll('li')[1].remove(); lgli[0].remove(); document.getElementsByClassName('e-addressbar-ul')[0].querySelector('li').remove(); li = document.getElementById('file_tree').querySelectorAll('li'); let tr: any = document.getElementById('file_largeicons').querySelectorAll('li'); let ar: any = document.getElementsByClassName('e-addressbar-ul')[0].querySelectorAll('li'); expect(li.length).toEqual(3); expect(tr.length).toEqual(2); expect(ar.length).toEqual(0); expect(tr[0].classList.contains('e-active')).toBe(true); expect(tr[0].querySelector('.e-frame').classList.contains('e-check')).toBe(true); expect(tr[1].classList.contains('e-active')).toBe(true); expect(tr[1].querySelector('.e-frame').classList.contains('e-check')).toBe(true); let largeWrap: Element = feObj.largeiconsviewModule.element.children[0]; evt = document.createEvent('MouseEvents'); evt.initEvent('contextmenu', true, true); largeWrap.dispatchEvent(evt); sourceElement.element.querySelectorAll('#file_cm_refresh')[0].click(); this.request = jasmine.Ajax.requests.mostRecent(); this.request.respondWith({ status: 200, responseText: JSON.stringify(data1) }); setTimeout(function () { let nli: any = document.getElementById('file_tree').querySelectorAll('li'); let ntr: any = document.getElementById('file_largeicons').querySelectorAll('li'); let nar: any = document.getElementsByClassName('e-addressbar-ul')[0].querySelectorAll('li'); expect(nli.length).toEqual(5); expect(ntr.length).toEqual(5); expect(nar.length).toEqual(1); expect(ntr[1].classList.contains('e-active')).toBe(true); expect(ntr[1].querySelector('.e-frame').classList.contains('e-check')).toBe(true); expect(ntr[2].classList.contains('e-active')).toBe(true); expect(ntr[2].querySelector('.e-frame').classList.contains('e-check')).toBe(true); done(); }, 500); }); it('layout context menu with selectAll', () => { let el: any = document.getElementById(feObj.element.id + '_contextmenu'); let li: any = document.getElementById('file_largeicons'); mouseEventArgs.target = li; tapEvent.tapCount = 1; feObj.largeiconsviewModule.clickObj.tap(tapEvent); let sourceElement: any = el.ej2_instances[0]; let evt = document.createEvent('MouseEvents') evt.initEvent('contextmenu', true, true); li.dispatchEvent(evt); let nli: any = document.getElementById('file_tree').querySelectorAll('li'); let ntr: any = document.getElementById('file_largeicons').querySelectorAll('li'); let nar: any = document.getElementsByClassName('e-addressbar-ul')[0].querySelectorAll('li'); expect(nli.length).toEqual(4); expect(ntr.length).toEqual(3); expect(nar.length).toEqual(1); sourceElement.element.querySelectorAll('#file_cm_selectall')[0].click(); nli = document.getElementById('file_tree').querySelectorAll('li'); ntr = document.getElementById('file_largeicons').querySelectorAll('li'); nar = document.getElementsByClassName('e-addressbar-ul')[0].querySelectorAll('li'); expect(nli.length).toEqual(4); expect(ntr.length).toEqual(3); expect(nar.length).toEqual(1); // expect(ntr[0].classList.contains('e-active')).toBe(true); // expect(ntr[1].classList.contains('e-active')).toBe(true); // expect(ntr[2].classList.contains('e-active')).toBe(true); // expect(feObj.selectedItems.length).toBe(3); }); it('layout context menu with view', (done: Function) => { let el: any = document.getElementById(feObj.element.id + '_contextmenu'); let li: any = document.getElementById('file_largeicons'); mouseEventArgs.target = li; tapEvent.tapCount = 1; feObj.largeiconsviewModule.clickObj.tap(tapEvent); let sourceElement: any = el.ej2_instances[0]; let evt = document.createEvent('MouseEvents') evt.initEvent('contextmenu', true, true); li.dispatchEvent(evt); let nli: any = document.getElementById('file_tree').querySelectorAll('li'); let ntr: any = document.getElementById('file_largeicons').querySelectorAll('li'); let nar: any = document.getElementsByClassName('e-addressbar-ul')[0].querySelectorAll('li'); expect(nli.length).toEqual(4); expect(ntr.length).toEqual(3); expect(nar.length).toEqual(1); sourceElement.element.querySelectorAll('#file_cm_view')[0].click(); mouseEventArgs.target = sourceElement.element.querySelectorAll('li')[1]; mouseEventArgs.type = 'mouseover'; feObj.contextmenuModule.contextMenu.moverHandler(mouseEventArgs); // expect(document.getElementById('file_grid').offsetWidth == 0).toEqual(true); expect(document.getElementById('file_largeicons').offsetWidth != 0).toEqual(true); expect(document.getElementById('file_grid').offsetHeight == 0).toEqual(true); expect(document.getElementById('file_largeicons').offsetHeight != 0).toEqual(true); (<any>document.querySelector('#file_cm_detailsview')).click(); this.request = jasmine.Ajax.requests.mostRecent(); this.request.respondWith({ status: 200, responseText: JSON.stringify(data1) }); setTimeout(function () { expect(document.getElementById('file_grid').offsetWidth != 0).toEqual(true); expect(document.getElementById('file_largeicons').offsetWidth == 0).toEqual(true); expect(document.getElementById('file_grid').offsetHeight != 0).toEqual(true); expect(document.getElementById('file_largeicons').offsetHeight == 0).toEqual(true); let nli: any = document.getElementById('file_tree').querySelectorAll('li'); let ntr: any = document.getElementById('file_largeicons').querySelectorAll('li'); let nar: any = document.getElementsByClassName('e-addressbar-ul')[0].querySelectorAll('li'); expect(nli.length).toEqual(4); expect(ntr.length).toEqual(3); expect(nar.length).toEqual(1); done(); }, 500); }); it('layout context menu with sortby', (done: Function) => { jasmine.Ajax.uninstall(); if (feObj) feObj.destroy(); ele.remove(); jasmine.DEFAULT_TIMEOUT_INTERVAL = originalTimeout; jasmine.Ajax.install(); feObj = undefined; ele = createElement('div', { id: 'file' }); document.body.appendChild(ele); feObj = new FileManager({ view: 'LargeIcons', ajaxSettings: { url: '/FileOperations', uploadUrl: '/Upload', downloadUrl: '/Download', getImageUrl: '/GetImage' }, showThumbnail: false }); feObj.appendTo('#file'); this.request = jasmine.Ajax.requests.mostRecent(); this.request.respondWith({ status: 200, responseText: JSON.stringify(dataSortbySize) }); let el: any = document.getElementById(feObj.element.id + '_contextmenu'); let li: any = document.getElementById('file_largeicons'); mouseEventArgs.target = li; tapEvent.tapCount = 1; feObj.largeiconsviewModule.clickObj.tap(tapEvent); let sourceElement: any = el.ej2_instances[0]; let evt = document.createEvent('MouseEvents') evt.initEvent('contextmenu', true, true); li.dispatchEvent(evt); let nli: any = document.getElementById('file_tree').querySelectorAll('li'); let ntr: any = document.getElementById('file_largeicons').querySelectorAll('li'); let nar: any = document.getElementsByClassName('e-addressbar-ul')[0].querySelectorAll('li'); expect(nli.length).toEqual(5); // expect(ntr.length).toEqual(3); expect(nar.length).toEqual(1); sourceElement.element.querySelectorAll('li')[0].click(); mouseEventArgs.target = sourceElement.element.querySelectorAll('li')[0]; mouseEventArgs.type = 'mouseover'; feObj.contextmenuModule.contextMenu.moverHandler(mouseEventArgs); (<any>document.querySelector('#file_cm_size')).click(); this.request = jasmine.Ajax.requests.mostRecent(); this.request.respondWith({ status: 200, responseText: JSON.stringify(dataSortbySize) }); setTimeout(function () { let nli: any = document.getElementById('file_tree').querySelectorAll('li'); let ntr: any = document.getElementById('file_largeicons').querySelectorAll('li'); let nar: any = document.getElementsByClassName('e-addressbar-ul')[0].querySelectorAll('li'); expect(nli.length).toEqual(5); // expect(ntr.length).toEqual(3); expect(nar.length).toEqual(1); expect(ntr[0].textContent).toBe("Food"); expect(ntr[1].textContent).toBe("Nature"); expect(ntr[1].querySelector('.e-frame').classList.contains('e-check')).toBe(false); expect(ntr[2].classList.contains('e-active')).toBe(false); expect(ntr[2].querySelector('.e-frame').classList.contains('e-check')).toBe(false); done(); }, 500); }); it('folder context menu - menuType', () => { feObj.menuOpen = menuopened; feObj.dataBind(); var li = document.getElementById('file_largeicons').querySelectorAll('li'); mouseEventArgs.target = li[0]; tapEvent.tapCount = 1; feObj.largeiconsviewModule.clickObj.tap(tapEvent); var evt = document.createEvent('MouseEvents'); evt.initEvent('contextmenu', true, true); li[0].dispatchEvent(evt); expect(count).toBe(1); expect(type).toBe("folder"); }); it('file context menu - menuType', (done: Function) => { feObj.menuOpen = menuopened; feObj.dataBind(); document.getElementById('file_tb_refresh').click(); this.request = jasmine.Ajax.requests.mostRecent(); this.request.respondWith({ status: 200, responseText: JSON.stringify(data1) }); setTimeout(function () { let li_file: any = document.getElementById('file_largeicons').querySelectorAll('li'); mouseEventArgs.target = li_file[4]; tapEvent.tapCount = 1; feObj.largeiconsviewModule.clickObj.tap(tapEvent); let evt = document.createEvent('MouseEvents') evt.initEvent('contextmenu', true, true); li_file[4].dispatchEvent(evt); expect(count).toBe(1); expect(type).toBe("file"); done(); }, 500); }); it('treeView - contextmenu menuType', () => { feObj.menuOpen = menuopened; feObj.dataBind(); var li = document.getElementById('file_tree').querySelectorAll('li'); mouseEventArgs.target = li[0]; var evt = document.createEvent('MouseEvents'); evt.initEvent('contextmenu', true, true); li[0].dispatchEvent(evt); expect(count).toBe(1); expect(type).toBe('folder'); }) it('layout - contextmenu menuType', () => { feObj.menuOpen = menuopened; feObj.dataBind(); var layout = document.querySelector('#file_largeicons'); mouseEventArgs.target = layout; tapEvent.tapCount = 1; feObj.largeiconsviewModule.clickObj.tap(tapEvent); var evt = document.createEvent('MouseEvents'); evt.initEvent('contextmenu', true, true); layout.dispatchEvent(evt); expect(count).toBe(1); expect(type).toBe('layout'); }) it("Contextmenu - custom menu items in folder", () => { feObj.contextMenuSettings = { file: ['Open', '|', 'Delete', 'Download', 'Rename', '|', 'Details', "Openinnewwindow", "OpeninVS", "|", "Giveaccessto"], folder: ['Open', '|', 'Delete', 'Rename', 'Download', '|', 'Details', "Custom1", "Custom2", "Custom3"], layout: ['SortBy', 'View', 'Refresh', '|', 'NewFolder', 'Upload', '|', 'Details', '|', 'SelectAll', "Custom1", "Custom2", "Custom3"] }; feObj.menuOpen = menuopened; feObj.dataBind(); var Li = document.querySelectorAll("#file_largeicons .e-large-icon")[2]; mouseEventArgs.target = Li; tapEvent.tapCount = 1; feObj.largeiconsviewModule.clickObj.tap(tapEvent); var evt = document.createEvent('MouseEvents'); evt.initEvent('contextmenu', true, true); Li.dispatchEvent(evt); var menuItems = document.querySelectorAll("#file_contextmenu .e-menu-item").length; expect(menuItems).toBe(10); expect(count).toBe(1); expect(type).toBe('folder'); }); it("Contextmenu items trimmed testing", () => { feObj.contextMenuSettings = { file: [' Open ', '|', ' Delete '], folder: ['Open ', '|', ' Delete '], layout: [' SortBy ', ' View ', ' Refresh '] }; feObj.menuOpen = menuopened; feObj.dataBind(); let Li: Element = document.querySelectorAll("#file_largeicons .e-large-icon")[1]; let evt = document.createEvent('MouseEvents') evt.initEvent('contextmenu', true, true); Li.dispatchEvent(evt); expect(isNullOrUndefined(document.getElementById('file_cm_open'))).toBe(false); expect(isNullOrUndefined(document.getElementById('file_cm_delete'))).toBe(false); let nLi: Element = document.querySelectorAll("#file_largeicons")[0]; let evts = document.createEvent('MouseEvents') evts.initEvent('contextmenu', true, true); nLi.dispatchEvent(evts); expect(isNullOrUndefined(document.getElementById('file_cm_sortby'))).toBe(false); expect(isNullOrUndefined(document.getElementById('file_cm_view'))).toBe(false); expect(isNullOrUndefined(document.getElementById('file_cm_refresh'))).toBe(false); }); it("Contextmenu - custom menu items in file", (done: Function) => { feObj.contextMenuSettings = { file: ['Open', '|', 'Delete', 'Download', 'Rename', '|', 'Details', "Openinnewwindow", "OpeninVS", "|", "Giveaccessto"], folder: ['Open', '|', 'Delete', 'Rename', 'Download', '|', 'Details', "Custom1", "Custom2", "Custom3"], layout: ['SortBy', 'View', 'Refresh', '|', 'NewFolder', 'Upload', '|', 'Details', '|', 'SelectAll', "Custom1", "Custom2", "Custom3"] }; feObj.menuOpen = menuopened; feObj.dataBind(); document.getElementById('file_tb_refresh').click(); this.request = jasmine.Ajax.requests.mostRecent(); this.request.respondWith({ status: 200, responseText: JSON.stringify(data1) }); setTimeout(function () { let li_file: any = document.getElementById('file_largeicons').querySelectorAll('li'); mouseEventArgs.target = li_file[4]; tapEvent.tapCount = 1; feObj.largeiconsviewModule.clickObj.tap(tapEvent); let evt = document.createEvent('MouseEvents') evt.initEvent('contextmenu', true, true); li_file[4].dispatchEvent(evt); var menuItems = document.querySelectorAll("#file_contextmenu .e-menu-item").length; expect(menuItems).toBe(11); expect(count).toBe(1); expect(type).toBe("file"); done(); }, 500); }); it("Contextmenu - custom menu items in layout", () => { feObj.contextMenuSettings = { file: ['Open', '|', 'Delete', 'Download', 'Rename', '|', 'Details', "Openinnewwindow", "OpeninVS", "|", "Giveaccessto"], folder: ['Open', '|', 'Delete', 'Rename', 'Download', '|', 'Details', "Custom1", "Custom2", "Custom3"], layout: ['SortBy', 'View', 'Refresh', '|', 'NewFolder', 'Upload', '|', 'Details', '|', 'SelectAll', "Custom1", "Custom2", "Custom3"] }; feObj.menuOpen = menuopened; feObj.dataBind(); var layout = document.querySelector('#file_largeicons'); mouseEventArgs.target = layout; tapEvent.tapCount = 1; feObj.largeiconsviewModule.clickObj.tap(tapEvent); var evt = document.createEvent('MouseEvents'); evt.initEvent('contextmenu', true, true); layout.dispatchEvent(evt); var menuItems = document.querySelectorAll("#file_contextmenu .e-menu-item").length; expect(menuItems).toBe(13); expect(count).toBe(1); expect(type).toBe("layout"); }); it("layout Contextmenu - custom menu items - testing submenu", () => { let click: boolean = false; feObj.menuOpen = addCustomItems; feObj.menuClick = function () { click = true; } feObj.contextMenuSettings = { file: ['Open', '|', 'Delete', 'Download', 'Rename', '|', 'Details', "Openinnewwindow", "OpeninVS", "|", "Giveaccessto"], folder: ['Open', '|', 'Delete', 'Rename', 'Download', '|', 'Details', "Custom1", "Custom2", "Custom3"], layout: ['SortBy', 'View', 'Refresh', '|', 'NewFolder', 'Upload', '|', 'Details', '|', 'SelectAll', "Custom1", "Custom2", "Custom3"] }; feObj.dataBind(); let el: any = document.getElementById(feObj.element.id + '_contextmenu'); let sourceElement: any = el.ej2_instances[0]; let Li: Element = document.querySelector('#file_largeicons'); let evt = document.createEvent('MouseEvents') mouseEventArgs.target = Li; tapEvent.tapCount = 1; feObj.largeiconsviewModule.clickObj.tap(tapEvent); evt.initEvent('contextmenu', true, true); Li.dispatchEvent(evt); expect(count).toBe(1); let menuItems = document.querySelectorAll("#file_contextmenu .e-menu-item").length; expect(menuItems).toBe(13); let menuItem: HTMLElement = <HTMLElement>document.querySelectorAll("#file_contextmenu .e-menu-item")[10]; mouseEventArgs.target = menuItem; mouseEventArgs.type = 'mouseover'; sourceElement.moverHandler(mouseEventArgs); document.getElementById('item1').click(); expect(click).toBe(true); expect(count).toBe(2); expect(type).toBe('layout'); }); it("file Contextmenu - custom menu items - testing submenu", (done) => { let click: boolean = false; feObj.menuOpen = addCustomItems; feObj.menuClick = function () { click = true; } feObj.contextMenuSettings = { file: ["Custom1", 'Open', '|', 'Delete', 'Download', 'Rename', '|', 'Details', "Openinnewwindow", "OpeninVS", "|", "Giveaccessto"], folder: ["Custom1", 'Open', '|', 'Delete', 'Rename', 'Download', '|', 'Details', "Custom4", "Custom2", "Custom3"], layout: ['SortBy', 'View', 'Refresh', '|', 'NewFolder', 'Upload', '|', 'Details', '|', 'SelectAll', "Custom1", "Custom2", "Custom3"] }; feObj.dataBind(); document.getElementById('file_tb_refresh').click(); this.request = jasmine.Ajax.requests.mostRecent(); this.request.respondWith({ status: 200, responseText: JSON.stringify(data1) }); setTimeout(function () { let el: any = document.getElementById(feObj.element.id + '_contextmenu'); let sourceElement: any = el.ej2_instances[0]; let Li: Element = document.getElementById('file_largeicons').querySelectorAll('li')[4]; let evt = document.createEvent('MouseEvents'); mouseEventArgs.target = Li; tapEvent.tapCount = 1; feObj.largeiconsviewModule.clickObj.tap(tapEvent); evt.initEvent('contextmenu', true, true); Li.dispatchEvent(evt); expect(count).toBe(1); let menuItems = document.querySelectorAll("#file_contextmenu .e-menu-item").length; expect(menuItems).toBe(12); let menuItem: HTMLElement = <HTMLElement>document.querySelectorAll("#file_contextmenu .e-menu-item")[0]; mouseEventArgs.target = menuItem; mouseEventArgs.type = 'mouseover'; sourceElement.moverHandler(mouseEventArgs); document.getElementById('item1').click(); expect(click).toBe(true); expect(count).toBe(2); expect(type).toBe('file'); done(); }, 500); }); it("folder Contextmenu - custom menu items - testing submenu", () => { let click: boolean = false; feObj.menuOpen = addCustomItems; feObj.menuClick = function () { click = true; } feObj.contextMenuSettings = { file: ["Custom1", 'Open', '|', 'Delete', 'Download', 'Rename', '|', 'Details', "Openinnewwindow", "OpeninVS", "|", "Giveaccessto"], folder: ["Custom1", 'Open', '|', 'Delete', 'Rename', 'Download', '|', 'Details', "Custom4", "Custom2", "Custom3"], layout: ['SortBy', 'View', 'Refresh', '|', 'NewFolder', 'Upload', '|', 'Details', '|', 'SelectAll', "Custom1", "Custom2", "Custom3"] }; feObj.dataBind(); let el: any = document.getElementById(feObj.element.id + '_contextmenu'); let sourceElement: any = el.ej2_instances[0]; let Li: Element = document.getElementById('file_largeicons').querySelectorAll('li')[2]; let evt = document.createEvent('MouseEvents'); mouseEventArgs.target = Li; tapEvent.tapCount = 1; feObj.largeiconsviewModule.clickObj.tap(tapEvent); evt.initEvent('contextmenu', true, true); Li.dispatchEvent(evt); expect(count).toBe(1); let menuItems = document.querySelectorAll("#file_contextmenu .e-menu-item").length; expect(menuItems).toBe(11); let menuItem: HTMLElement = <HTMLElement>document.querySelectorAll("#file_contextmenu .e-menu-item")[0]; mouseEventArgs.target = menuItem; mouseEventArgs.type = 'mouseover'; sourceElement.moverHandler(mouseEventArgs); document.getElementById('item1').click(); expect(click).toBe(true); expect(count).toBe(2); expect(type).toBe('folder'); }); }); describe('access control context menu testing', () => { let feObj: any; let ele: HTMLElement; let originalTimeout: any; let mouseEventArgs: any, tapEvent: any; beforeEach((): void => { jasmine.Ajax.install(); feObj = undefined; ele = createElement('div', { id: 'file' }); document.body.appendChild(ele); originalTimeout = jasmine.DEFAULT_TIMEOUT_INTERVAL; jasmine.DEFAULT_TIMEOUT_INTERVAL = 50000; mouseEventArgs = { preventDefault: (): void => { }, stopImmediatePropagation: (): void => { }, target: null, type: null, shiftKey: false, ctrlKey: false, originalEvent: { target: null } }; tapEvent = { originalEvent: mouseEventArgs, tapCount: 1 }; }); afterEach((): void => { jasmine.Ajax.uninstall(); if (feObj) feObj.destroy(); ele.remove(); jasmine.DEFAULT_TIMEOUT_INTERVAL = originalTimeout; }); it('Search context menu testing', (done: Function) => { let i: number = 0; feObj = new FileManager({ view: 'LargeIcons', ajaxSettings: { url: '/FileAccessOperations', uploadUrl: '/Upload', downloadUrl: '/Download', getImageUrl: '/GetImage' }, fileOpen: (args: FileOpenEventArgs) => { i++ }, showThumbnail: false }); feObj.appendTo('#file'); this.request = jasmine.Ajax.requests.mostRecent(); this.request.respondWith({ status: 200, responseText: JSON.stringify(accessData1) }); setTimeout(function () { let treeObj: any = (document.getElementById("file_tree") as any).ej2_instances[0]; let treeLi: any = treeObj.element.querySelectorAll('li'); let el: any = document.getElementById(feObj.element.id + '_contextmenu'); let li: any = document.getElementById('file_largeicons').querySelectorAll('li'); expect(treeObj.selectedNodes[0]).toEqual("fe_tree"); expect(treeLi.length).toEqual(5); expect(li.length).toEqual(9); let searchEle: any = feObj.element.querySelector("#file_search"); let searchObj: any = searchEle.ej2_instances[0]; searchEle.value = 'doc'; searchObj.value = 'doc'; let eventArgs: any = { value: 'doc', container: searchEle }; searchObj.input(eventArgs); setTimeout(function () { this.request = jasmine.Ajax.requests.filter('/FileAccessOperations'); this.request[this.request.length - 1].respondWith({ status: 200, responseText: JSON.stringify(accessSearchData) }); setTimeout(function () { li = document.getElementById('file_largeicons').querySelectorAll('li'); expect(li.length).toEqual(3); feObj.menuClick = (args: MenuClickEventArgs) => { i++; expect((<any>args.fileDetails[0]).name === 'EJ2 File Manager.docx').toBe(true); } mouseEventArgs.target = li[2]; tapEvent.tapCount = 1; feObj.largeiconsviewModule.clickObj.tap(tapEvent); let sourceElement: any = el.ej2_instances[0]; let evt = document.createEvent('MouseEvents') evt.initEvent('contextmenu', true, true); li[2].dispatchEvent(evt); expect(sourceElement.element.querySelectorAll('li')[0].innerText).toBe('Open'); expect(sourceElement.element.querySelectorAll('li')[0].classList.contains('e-disabled')).toBe(false); sourceElement.element.querySelectorAll('li')[0].click(); expect(i === 2).toBe(true); done(); }, 500); }, 400); }, 500); }); it('mouse click on new folder button', (done: Function) => { feObj = new FileManager({ view: 'LargeIcons', ajaxSettings: { url: '/FileAccessOperations', uploadUrl: '/Upload', downloadUrl: '/Download', getImageUrl: '/GetImage' }, showThumbnail: false }); feObj.appendTo('#file'); this.request = jasmine.Ajax.requests.mostRecent(); this.request.respondWith({ status: 200, responseText: JSON.stringify(accessData1) }); setTimeout(function () { let menuObj: any = (document.getElementById(feObj.element.id + '_contextmenu') as any).ej2_instances[0]; menuObj.animationSettings = { effect: 'None' }; menuObj.dataBind(); let treeObj: any = (document.getElementById("file_tree") as any).ej2_instances[0]; let treeLi: any = treeObj.element.querySelectorAll('li'); let largeLi: any = document.getElementById('file_largeicons').querySelectorAll('.e-list-item'); expect(treeLi.length).toEqual(5); expect(largeLi.length).toEqual(9); let aTreeLi: any = treeObj.element.querySelectorAll('li.e-fe-hidden'); let aLargeLi: any = document.getElementById('file_largeicons').querySelectorAll('.e-list-item.e-fe-hidden'); expect(aTreeLi.length).toEqual(2); expect(aLargeLi.length).toEqual(4); expect(treeLi[2].classList.contains('e-fe-hidden')).toBe(true); expect(largeLi[1].classList.contains('e-fe-hidden')).toBe(true); let evt = document.createEvent('MouseEvents'); evt.initEvent('contextmenu', true, true); document.getElementById('file_largeicons').dispatchEvent(evt); document.getElementById('file_cm_newfolder').click(); let dialogObj: any = (document.getElementById("file_dialog") as any).ej2_instances[0]; expect(dialogObj.element.querySelector('.e-dlg-header').innerText).toEqual("Access Denied"); let treeLi1: any = treeObj.element.querySelectorAll('li'); let largeLi1: any = document.getElementById('file_largeicons').querySelectorAll('.e-list-item'); expect(treeLi1.length).toEqual(5); expect(largeLi1.length).toEqual(9); let aTreeLi1: any = treeObj.element.querySelectorAll('li.e-fe-hidden'); let aLargeLi1: any = document.getElementById('file_largeicons').querySelectorAll('.e-list-item.e-fe-hidden'); expect(aTreeLi1.length).toEqual(2); expect(aLargeLi1.length).toEqual(4); expect(treeLi1[2].classList.contains('e-fe-hidden')).toBe(true); expect(largeLi1[1].classList.contains('e-fe-hidden')).toBe(true); done(); }, 500); }); it('mouse click on upload button', (done: Function) => { feObj = new FileManager({ view: 'LargeIcons', ajaxSettings: { url: '/FileAccessOperations', uploadUrl: '/Upload', downloadUrl: '/Download', getImageUrl: '/GetImage' }, showThumbnail: false }); feObj.appendTo('#file'); this.request = jasmine.Ajax.requests.mostRecent(); this.request.respondWith({ status: 200, responseText: JSON.stringify(accessData1) }); setTimeout(function () { let menuObj: any = (document.getElementById(feObj.element.id + '_contextmenu') as any).ej2_instances[0]; menuObj.animationSettings = { effect: 'None' }; let treeObj: any = (document.getElementById("file_tree") as any).ej2_instances[0]; let treeLi: any = treeObj.element.querySelectorAll('li'); let largeLi: any = document.getElementById('file_largeicons').querySelectorAll('.e-list-item'); expect(treeLi.length).toEqual(5); expect(largeLi.length).toEqual(9); let aTreeLi: any = treeObj.element.querySelectorAll('li.e-fe-hidden'); let aLargeLi: any = document.getElementById('file_largeicons').querySelectorAll('.e-list-item.e-fe-hidden'); expect(aTreeLi.length).toEqual(2); expect(aLargeLi.length).toEqual(4); expect(treeLi[2].classList.contains('e-fe-hidden')).toBe(true); expect(largeLi[1].classList.contains('e-fe-hidden')).toBe(true); let evt = document.createEvent('MouseEvents'); evt.initEvent('contextmenu', true, true); document.getElementById('file_largeicons').dispatchEvent(evt); document.getElementById('file_cm_upload').click(); let dialogObj: any = (document.getElementById("file_dialog") as any).ej2_instances[0]; expect(dialogObj.element.querySelector('.e-dlg-header').innerText).toEqual("Access Denied"); let treeLi1: any = treeObj.element.querySelectorAll('li'); let largeLi1: any = document.getElementById('file_largeicons').querySelectorAll('.e-list-item'); expect(treeLi1.length).toEqual(5); expect(largeLi1.length).toEqual(9); let aTreeLi1: any = treeObj.element.querySelectorAll('li.e-fe-hidden'); let aLargeLi1: any = document.getElementById('file_largeicons').querySelectorAll('.e-list-item.e-fe-hidden'); expect(aTreeLi1.length).toEqual(2); expect(aLargeLi1.length).toEqual(4); expect(treeLi1[2].classList.contains('e-fe-hidden')).toBe(true); expect(largeLi1[1].classList.contains('e-fe-hidden')).toBe(true); done(); }, 500); }); it('mouse click on refresh button', (done: Function) => { feObj = new FileManager({ view: 'LargeIcons', ajaxSettings: { url: '/FileAccessOperations', uploadUrl: '/Upload', downloadUrl: '/Download', getImageUrl: '/GetImage' }, showThumbnail: false }); feObj.appendTo('#file'); this.request = jasmine.Ajax.requests.mostRecent(); this.request.respondWith({ status: 200, responseText: JSON.stringify(accessData1) }); setTimeout(function () { let menuObj: any = (document.getElementById(feObj.element.id + '_contextmenu') as any).ej2_instances[0]; menuObj.animationSettings = { effect: 'None' }; menuObj.dataBind(); let treeObj: any = (document.getElementById("file_tree") as any).ej2_instances[0]; let treeLi: any = treeObj.element.querySelectorAll('li'); let largeLi: any = document.getElementById('file_largeicons').querySelectorAll('.e-list-item'); expect(treeLi.length).toEqual(5); expect(largeLi.length).toEqual(9); let aTreeLi: any = treeObj.element.querySelectorAll('li.e-fe-hidden'); let aLargeLi: any = document.getElementById('file_largeicons').querySelectorAll('.e-list-item.e-fe-hidden'); expect(aTreeLi.length).toEqual(2); expect(aLargeLi.length).toEqual(4); expect(treeLi[2].classList.contains('e-fe-hidden')).toBe(true); expect(largeLi[1].classList.contains('e-fe-hidden')).toBe(true); let evt = document.createEvent('MouseEvents'); evt.initEvent('contextmenu', true, true); document.getElementById('file_largeicons').dispatchEvent(evt); document.getElementById('file_cm_refresh').click(); this.request = jasmine.Ajax.requests.mostRecent(); this.request.respondWith({ status: 200, responseText: JSON.stringify(accessData1) }); setTimeout(function () { let treeLi1: any = treeObj.element.querySelectorAll('li'); let largeLi1: any = document.getElementById('file_largeicons').querySelectorAll('.e-list-item'); expect(treeLi1.length).toEqual(5); expect(largeLi1.length).toEqual(9); let aTreeLi1: any = treeObj.element.querySelectorAll('li.e-fe-hidden'); let aLargeLi1: any = document.getElementById('file_largeicons').querySelectorAll('.e-list-item.e-fe-hidden'); expect(aTreeLi1.length).toEqual(2); expect(aLargeLi1.length).toEqual(4); expect(treeLi1[2].classList.contains('e-fe-hidden')).toBe(true); expect(largeLi1[1].classList.contains('e-fe-hidden')).toBe(true); done(); }, 500); }, 500); }); it('mouse click on rename button', (done: Function) => { feObj = new FileManager({ view: 'LargeIcons', ajaxSettings: { url: '/FileAccessOperations', uploadUrl: '/Upload', downloadUrl: '/Download', getImageUrl: '/GetImage' }, showThumbnail: false }); feObj.appendTo('#file'); this.request = jasmine.Ajax.requests.mostRecent(); this.request.respondWith({ status: 200, responseText: JSON.stringify(accessData1) }); setTimeout(function () { let menuObj: any = (document.getElementById(feObj.element.id + '_contextmenu') as any).ej2_instances[0]; menuObj.animationSettings = { effect: 'None' }; menuObj.dataBind(); let treeObj: any = (document.getElementById("file_tree") as any).ej2_instances[0]; let treeLi: any = treeObj.element.querySelectorAll('li'); let largeLi: any = document.getElementById('file_largeicons').querySelectorAll('.e-list-item'); expect(treeLi.length).toEqual(5); expect(largeLi.length).toEqual(9); let aTreeLi: any = treeObj.element.querySelectorAll('li.e-fe-hidden'); let aLargeLi: any = document.getElementById('file_largeicons').querySelectorAll('.e-list-item.e-fe-hidden'); expect(aTreeLi.length).toEqual(2); expect(aLargeLi.length).toEqual(4); expect(treeLi[2].classList.contains('e-fe-hidden')).toBe(true); expect(largeLi[1].classList.contains('e-fe-hidden')).toBe(true); mouseEventArgs.target = largeLi[1]; feObj.largeiconsviewModule.clickObj.tap(tapEvent); let evt = document.createEvent('MouseEvents'); evt.initEvent('contextmenu', true, true); largeLi[1].dispatchEvent(evt); document.getElementById('file_cm_rename').click(); let dialogObj: any = (document.getElementById("file_dialog") as any).ej2_instances[0]; expect(dialogObj.element.querySelector('.e-dlg-header').innerText).toEqual("Access Denied"); done(); }, 500); }); it('mouse click on delete button', (done: Function) => { feObj = new FileManager({ view: 'LargeIcons', ajaxSettings: { url: '/FileAccessOperations', uploadUrl: '/Upload', downloadUrl: '/Download', getImageUrl: '/GetImage' }, showThumbnail: false }); feObj.appendTo('#file'); this.request = jasmine.Ajax.requests.mostRecent(); this.request.respondWith({ status: 200, responseText: JSON.stringify(accessData1) }); setTimeout(function () { let menuObj: any = (document.getElementById(feObj.element.id + '_contextmenu') as any).ej2_instances[0]; menuObj.animationSettings = { effect: 'None' }; menuObj.dataBind(); let treeObj: any = (document.getElementById("file_tree") as any).ej2_instances[0]; let treeLi: any = treeObj.element.querySelectorAll('li'); let largeLi: any = document.getElementById('file_largeicons').querySelectorAll('.e-list-item'); expect(treeLi.length).toEqual(5); expect(largeLi.length).toEqual(9); let aTreeLi: any = treeObj.element.querySelectorAll('li.e-fe-hidden'); let aLargeLi: any = document.getElementById('file_largeicons').querySelectorAll('.e-list-item.e-fe-hidden'); expect(aTreeLi.length).toEqual(2); expect(aLargeLi.length).toEqual(4); expect(treeLi[2].classList.contains('e-fe-hidden')).toBe(true); expect(largeLi[1].classList.contains('e-fe-hidden')).toBe(true); mouseEventArgs.target = largeLi[1]; feObj.largeiconsviewModule.clickObj.tap(tapEvent); let evt = document.createEvent('MouseEvents'); evt.initEvent('contextmenu', true, true); largeLi[1].dispatchEvent(evt); document.getElementById('file_cm_delete').click(); let dialogObj: any = (document.getElementById("file_dialog") as any).ej2_instances[0]; expect(dialogObj.element.querySelector('.e-dlg-header').innerText).toEqual("Access Denied"); let treeLi1: any = treeObj.element.querySelectorAll('li'); let largeLi1: any = document.getElementById('file_largeicons').querySelectorAll('.e-list-item'); expect(treeLi1.length).toEqual(5); expect(largeLi1.length).toEqual(9); let aTreeLi1: any = treeObj.element.querySelectorAll('li.e-fe-hidden'); let aLargeLi1: any = document.getElementById('file_largeicons').querySelectorAll('.e-list-item.e-fe-hidden'); expect(aTreeLi1.length).toEqual(2); expect(aLargeLi1.length).toEqual(4); expect(treeLi1[2].classList.contains('e-fe-hidden')).toBe(true); expect(largeLi1[1].classList.contains('e-fe-hidden')).toBe(true); done(); }, 500); }); it('mouse click on download button', (done: Function) => { feObj = new FileManager({ view: 'LargeIcons', ajaxSettings: { url: '/FileAccessOperations', uploadUrl: '/Upload', downloadUrl: '/Download', getImageUrl: '/GetImage' }, showThumbnail: false }); feObj.appendTo('#file'); this.request = jasmine.Ajax.requests.mostRecent(); this.request.respondWith({ status: 200, responseText: JSON.stringify(accessData1) }); setTimeout(function () { let menuObj: any = (document.getElementById(feObj.element.id + '_contextmenu') as any).ej2_instances[0]; menuObj.animationSettings = { effect: 'None' }; menuObj.dataBind(); let treeObj: any = (document.getElementById("file_tree") as any).ej2_instances[0]; let treeLi: any = treeObj.element.querySelectorAll('li'); let largeLi: any = document.getElementById('file_largeicons').querySelectorAll('.e-list-item'); expect(treeLi.length).toEqual(5); expect(largeLi.length).toEqual(9); let aTreeLi: any = treeObj.element.querySelectorAll('li.e-fe-hidden'); let aLargeLi: any = document.getElementById('file_largeicons').querySelectorAll('.e-list-item.e-fe-hidden'); expect(aTreeLi.length).toEqual(2); expect(aLargeLi.length).toEqual(4); expect(treeLi[2].classList.contains('e-fe-hidden')).toBe(true); expect(largeLi[1].classList.contains('e-fe-hidden')).toBe(true); mouseEventArgs.target = largeLi[1]; feObj.largeiconsviewModule.clickObj.tap(tapEvent); let evt = document.createEvent('MouseEvents'); evt.initEvent('contextmenu', true, true); largeLi[1].dispatchEvent(evt); document.getElementById('file_cm_download').click(); let dialogObj: any = (document.getElementById("file_dialog") as any).ej2_instances[0]; expect(dialogObj.element.querySelector('.e-dlg-header').innerText).toEqual("Access Denied"); done(); }, 500); }); it('mouse click on details button', (done: Function) => { feObj = new FileManager({ view: 'LargeIcons', ajaxSettings: { url: '/FileAccessOperations', uploadUrl: '/Upload', downloadUrl: '/Download', getImageUrl: '/GetImage' }, showThumbnail: false }); feObj.appendTo('#file'); this.request = jasmine.Ajax.requests.mostRecent(); this.request.respondWith({ status: 200, responseText: JSON.stringify(accessData1) }); setTimeout(function () { let menuObj: any = (document.getElementById(feObj.element.id + '_contextmenu') as any).ej2_instances[0]; menuObj.animationSettings = { effect: 'None' }; menuObj.dataBind(); let treeObj: any = (document.getElementById("file_tree") as any).ej2_instances[0]; let treeLi: any = treeObj.element.querySelectorAll('li'); let largeLi: any = document.getElementById('file_largeicons').querySelectorAll('.e-list-item'); expect(treeLi.length).toEqual(5); expect(largeLi.length).toEqual(9); let aTreeLi: any = treeObj.element.querySelectorAll('li.e-fe-hidden'); let aLargeLi: any = document.getElementById('file_largeicons').querySelectorAll('.e-list-item.e-fe-hidden'); expect(aTreeLi.length).toEqual(2); expect(aLargeLi.length).toEqual(4); expect(treeLi[2].classList.contains('e-fe-hidden')).toBe(true); expect(largeLi[1].classList.contains('e-fe-hidden')).toBe(true); mouseEventArgs.target = largeLi[1]; feObj.largeiconsviewModule.clickObj.tap(tapEvent); let evt = document.createEvent('MouseEvents') evt.initEvent('contextmenu', true, true); largeLi[1].dispatchEvent(evt); document.getElementById('file_cm_details').click(); this.request = jasmine.Ajax.requests.mostRecent(); this.request.respondWith({ status: 200, responseText: JSON.stringify(accessDetails1) }); setTimeout(function () { let dialogObj: any = (document.getElementById("file_dialog") as any).ej2_instances[0]; expect(dialogObj.element.querySelector('.e-dlg-header').innerHTML).toEqual("Downloads"); expect(dialogObj.element.querySelectorAll('td')[8].innerHTML).toEqual("Permission"); done(); }, 500); }, 500); }); it('mouse click on delete button with two items selected', (done: Function) => { feObj = new FileManager({ view: 'LargeIcons', ajaxSettings: { url: '/FileAccessOperations', uploadUrl: '/Upload', downloadUrl: '/Download', getImageUrl: '/GetImage' }, showThumbnail: false }); feObj.appendTo('#file'); this.request = jasmine.Ajax.requests.mostRecent(); this.request.respondWith({ status: 200, responseText: JSON.stringify(accessData1) }); setTimeout(function () { let menuObj: any = (document.getElementById(feObj.element.id + '_contextmenu') as any).ej2_instances[0]; menuObj.animationSettings = { effect: 'None' }; menuObj.dataBind(); let treeObj: any = (document.getElementById("file_tree") as any).ej2_instances[0]; let treeLi: any = treeObj.element.querySelectorAll('li'); let largeLi: any = document.getElementById('file_largeicons').querySelectorAll('.e-list-item'); expect(treeLi.length).toEqual(5); expect(largeLi.length).toEqual(9); let aTreeLi: any = treeObj.element.querySelectorAll('li.e-fe-hidden'); let aLargeLi: any = document.getElementById('file_largeicons').querySelectorAll('.e-list-item.e-fe-hidden'); expect(aTreeLi.length).toEqual(2); expect(aLargeLi.length).toEqual(4); expect(treeLi[2].classList.contains('e-fe-hidden')).toBe(true); expect(largeLi[1].classList.contains('e-fe-hidden')).toBe(true); mouseEventArgs.target = largeLi[1]; mouseEventArgs.ctrlKey = true; feObj.largeiconsviewModule.clickObj.tap(tapEvent); mouseEventArgs.target = largeLi[2]; mouseEventArgs.ctrlKey = true; feObj.largeiconsviewModule.clickObj.tap(tapEvent); let evt = document.createEvent('MouseEvents'); evt.initEvent('contextmenu', true, true); largeLi[2].dispatchEvent(evt); document.getElementById('file_cm_delete').click(); let dialogObj: any = (document.getElementById("file_dialog") as any).ej2_instances[0]; expect(dialogObj.element.querySelector('.e-dlg-header').innerText).toEqual("Access Denied"); let treeLi1: any = treeObj.element.querySelectorAll('li'); let largeLi1: any = document.getElementById('file_largeicons').querySelectorAll('.e-list-item'); expect(treeLi1.length).toEqual(5); expect(largeLi1.length).toEqual(9); let aTreeLi1: any = treeObj.element.querySelectorAll('li.e-fe-hidden'); let aLargeLi1: any = document.getElementById('file_largeicons').querySelectorAll('.e-list-item.e-fe-hidden'); expect(aTreeLi1.length).toEqual(2); expect(aLargeLi1.length).toEqual(4); expect(treeLi1[2].classList.contains('e-fe-hidden')).toBe(true); expect(largeLi1[1].classList.contains('e-fe-hidden')).toBe(true); done(); }, 500); }); it('mouse click on download button with two items selected', (done: Function) => { feObj = new FileManager({ view: 'LargeIcons', ajaxSettings: { url: '/FileAccessOperations', uploadUrl: '/Upload', downloadUrl: '/Download', getImageUrl: '/GetImage' }, showThumbnail: false }); feObj.appendTo('#file'); this.request = jasmine.Ajax.requests.mostRecent(); this.request.respondWith({ status: 200, responseText: JSON.stringify(accessData1) }); setTimeout(function () { let menuObj: any = (document.getElementById(feObj.element.id + '_contextmenu') as any).ej2_instances[0]; menuObj.animationSettings = { effect: 'None' }; menuObj.dataBind(); let treeObj: any = (document.getElementById("file_tree") as any).ej2_instances[0]; let treeLi: any = treeObj.element.querySelectorAll('li'); let largeLi: any = document.getElementById('file_largeicons').querySelectorAll('.e-list-item'); expect(treeLi.length).toEqual(5); expect(largeLi.length).toEqual(9); let aTreeLi: any = treeObj.element.querySelectorAll('li.e-fe-hidden'); let aLargeLi: any = document.getElementById('file_largeicons').querySelectorAll('.e-list-item.e-fe-hidden'); expect(aTreeLi.length).toEqual(2); expect(aLargeLi.length).toEqual(4); expect(treeLi[2].classList.contains('e-fe-hidden')).toBe(true); expect(largeLi[1].classList.contains('e-fe-hidden')).toBe(true); mouseEventArgs.target = largeLi[1]; mouseEventArgs.ctrlKey = true; feObj.largeiconsviewModule.clickObj.tap(tapEvent); mouseEventArgs.target = largeLi[2]; mouseEventArgs.ctrlKey = true; feObj.largeiconsviewModule.clickObj.tap(tapEvent); let evt = document.createEvent('MouseEvents'); evt.initEvent('contextmenu', true, true); largeLi[2].dispatchEvent(evt); document.getElementById('file_cm_download').click(); let dialogObj: any = (document.getElementById("file_dialog") as any).ej2_instances[0]; expect(dialogObj.element.querySelector('.e-dlg-header').innerText).toEqual("Access Denied"); done(); }, 500); }); it('mouse click on details button with two items selected', (done: Function) => { feObj = new FileManager({ view: 'LargeIcons', ajaxSettings: { url: '/FileAccessOperations', uploadUrl: '/Upload', downloadUrl: '/Download', getImageUrl: '/GetImage' }, showThumbnail: false }); feObj.appendTo('#file'); this.request = jasmine.Ajax.requests.mostRecent(); this.request.respondWith({ status: 200, responseText: JSON.stringify(accessData1) }); setTimeout(function () { let menuObj: any = (document.getElementById(feObj.element.id + '_contextmenu') as any).ej2_instances[0]; menuObj.animationSettings = { effect: 'None' }; menuObj.dataBind(); let treeObj: any = (document.getElementById("file_tree") as any).ej2_instances[0]; let treeLi: any = treeObj.element.querySelectorAll('li'); let largeLi: any = document.getElementById('file_largeicons').querySelectorAll('.e-list-item'); expect(treeLi.length).toEqual(5); expect(largeLi.length).toEqual(9); let aTreeLi: any = treeObj.element.querySelectorAll('li.e-fe-hidden'); let aLargeLi: any = document.getElementById('file_largeicons').querySelectorAll('.e-list-item.e-fe-hidden'); expect(aTreeLi.length).toEqual(2); expect(aLargeLi.length).toEqual(4); expect(treeLi[2].classList.contains('e-fe-hidden')).toBe(true); expect(largeLi[1].classList.contains('e-fe-hidden')).toBe(true); mouseEventArgs.target = largeLi[1]; mouseEventArgs.ctrlKey = true; feObj.largeiconsviewModule.clickObj.tap(tapEvent); mouseEventArgs.target = largeLi[2]; mouseEventArgs.ctrlKey = true; feObj.largeiconsviewModule.clickObj.tap(tapEvent); let evt = document.createEvent('MouseEvents'); evt.initEvent('contextmenu', true, true); largeLi[2].dispatchEvent(evt); document.getElementById('file_cm_details').click(); this.request = jasmine.Ajax.requests.mostRecent(); this.request.respondWith({ status: 200, responseText: JSON.stringify(accessDetails2) }); setTimeout(function () { let dialogObj: any = (document.getElementById("file_dialog") as any).ej2_instances[0]; expect(dialogObj.element.querySelector('.e-dlg-header').innerHTML).toEqual("Downloads, Music.png"); done(); }, 500); }, 500); }); it('mouse click on open button with non access folder/files', (done: Function) => { feObj = new FileManager({ view: 'LargeIcons', ajaxSettings: { url: '/FileAccessOperations', uploadUrl: '/Upload', downloadUrl: '/Download', getImageUrl: '/GetImage' }, showThumbnail: false }); feObj.appendTo('#file'); this.request = jasmine.Ajax.requests.mostRecent(); this.request.respondWith({ status: 200, responseText: JSON.stringify(accessData1) }); setTimeout(function () { let menuObj: any = (document.getElementById(feObj.element.id + '_contextmenu') as any).ej2_instances[0]; menuObj.animationSettings = { effect: 'None' }; menuObj.dataBind(); let treeObj: any = (document.getElementById("file_tree") as any).ej2_instances[0]; let treeLi: any = treeObj.element.querySelectorAll('li'); let largeLi: any = document.getElementById('file_largeicons').querySelectorAll('.e-list-item'); expect(treeLi.length).toEqual(5); expect(largeLi.length).toEqual(9); let aTreeLi: any = treeObj.element.querySelectorAll('li.e-fe-hidden'); let aLargeLi: any = document.getElementById('file_largeicons').querySelectorAll('.e-list-item.e-fe-hidden'); expect(aTreeLi.length).toEqual(2); expect(aLargeLi.length).toEqual(4); expect(treeLi[2].classList.contains('e-fe-hidden')).toBe(true); expect(largeLi[1].classList.contains('e-fe-hidden')).toBe(true); mouseEventArgs.target = largeLi[1]; feObj.largeiconsviewModule.clickObj.tap(tapEvent); let evt = document.createEvent('MouseEvents'); evt.initEvent('contextmenu', true, true); largeLi[1].dispatchEvent(evt); document.getElementById('file_cm_open').click(); let dialogObj: any = (document.getElementById("file_dialog") as any).ej2_instances[0]; expect(dialogObj.element.querySelector('.e-dlg-header').innerText).toEqual("Access Denied"); dialogObj.element.querySelector('.e-primary').click(); mouseEventArgs.target = largeLi[7]; feObj.largeiconsviewModule.clickObj.tap(tapEvent); let evt1 = document.createEvent('MouseEvents'); evt1.initEvent('contextmenu', true, true); largeLi[7].dispatchEvent(evt1); document.getElementById('file_cm_open').click(); expect(dialogObj.element.querySelector('.e-dlg-header').innerText).toEqual("Access Denied"); done(); }, 500); }); it('mouse click on open button with access folder/files', (done: Function) => { feObj = new FileManager({ view: 'LargeIcons', ajaxSettings: { url: '/FileAccessOperations', uploadUrl: '/Upload', downloadUrl: '/Download', getImageUrl: '/GetImage' }, showThumbnail: false }); feObj.appendTo('#file'); this.request = jasmine.Ajax.requests.mostRecent(); this.request.respondWith({ status: 200, responseText: JSON.stringify(accessData1) }); setTimeout(function () { let menuObj: any = (document.getElementById(feObj.element.id + '_contextmenu') as any).ej2_instances[0]; menuObj.animationSettings = { effect: 'None' }; menuObj.dataBind(); let treeObj: any = (document.getElementById("file_tree") as any).ej2_instances[0]; let treeLi: any = treeObj.element.querySelectorAll('li'); let largeLi: any = document.getElementById('file_largeicons').querySelectorAll('.e-list-item'); expect(treeLi.length).toEqual(5); expect(largeLi.length).toEqual(9); let aTreeLi: any = treeObj.element.querySelectorAll('li.e-fe-hidden'); let aLargeLi: any = document.getElementById('file_largeicons').querySelectorAll('.e-list-item.e-fe-hidden'); expect(aTreeLi.length).toEqual(2); expect(aLargeLi.length).toEqual(4); expect(treeLi[2].classList.contains('e-fe-hidden')).toBe(true); expect(largeLi[1].classList.contains('e-fe-hidden')).toBe(true); mouseEventArgs.target = largeLi[0]; feObj.largeiconsviewModule.clickObj.tap(tapEvent); let evt = document.createEvent('MouseEvents'); evt.initEvent('contextmenu', true, true); largeLi[0].dispatchEvent(evt); document.getElementById('file_cm_open').click(); this.request = jasmine.Ajax.requests.mostRecent(); this.request.respondWith({ status: 200, responseText: JSON.stringify(accessData2) }); setTimeout(function () { let treeLi1: any = treeObj.element.querySelectorAll('li'); let largeLi1: any = document.getElementById('file_largeicons').querySelectorAll('.e-list-item'); expect(treeLi1.length).toEqual(7); expect(largeLi1.length).toEqual(12); let aTreeLi1: any = treeObj.element.querySelectorAll('li.e-fe-hidden'); let aLargeLi1: any = document.getElementById('file_largeicons').querySelectorAll('.e-list-item.e-fe-hidden'); expect(aTreeLi1.length).toEqual(2); expect(aLargeLi1.length).toEqual(5); expect(treeLi1[2].classList.contains('e-fe-hidden')).toBe(false); expect(largeLi1[2].classList.contains('e-fe-hidden')).toBe(true); let evt1 = document.createEvent('MouseEvents'); evt1.initEvent('contextmenu', true, true); largeLi1[2].dispatchEvent(evt1); document.getElementById('file_cm_open').click(); let dialogObj: any = (document.getElementById("file_dialog") as any).ej2_instances[0]; expect(dialogObj.element.querySelector('.e-dlg-header').innerText).toEqual("Access Denied"); dialogObj.element.querySelector('.e-primary').click(); mouseEventArgs.target = largeLi1[7]; feObj.largeiconsviewModule.clickObj.tap(tapEvent); let evt2 = document.createEvent('MouseEvents'); evt2.initEvent('contextmenu', true, true); largeLi1[7].dispatchEvent(evt2); document.getElementById('file_cm_open').click(); let dialogObj1: any = (document.getElementById("file_img_dialog") as any).ej2_instances[0]; expect(dialogObj1.element.querySelector('.e-dlg-header').innerHTML).toEqual("4.jpg"); done(); }, 500); }, 500); }); }); });
the_stack
import { gql } from "@apollo/client"; import * as Apollo from "@apollo/client"; export type Maybe<T> = T | undefined; export type Exact<T extends { [key: string]: unknown }> = { [K in keyof T]: T[K]; }; /** All built-in and custom scalars, mapped to their actual values */ export type Scalars = { ID: string; String: string; Boolean: boolean; Int: number; Float: number; }; /** expression to compare columns of type Boolean. All fields are combined with logical 'AND'. */ export type BooleanComparisonExp = { _eq?: Maybe<Scalars["Boolean"]>; _gt?: Maybe<Scalars["Boolean"]>; _gte?: Maybe<Scalars["Boolean"]>; _in?: Maybe<Array<Scalars["Boolean"]>>; _is_null?: Maybe<Scalars["Boolean"]>; _lt?: Maybe<Scalars["Boolean"]>; _lte?: Maybe<Scalars["Boolean"]>; _neq?: Maybe<Scalars["Boolean"]>; _nin?: Maybe<Array<Scalars["Boolean"]>>; }; /** expression to compare columns of type Int. All fields are combined with logical 'AND'. */ export type IntComparisonExp = { _eq?: Maybe<Scalars["Int"]>; _gt?: Maybe<Scalars["Int"]>; _gte?: Maybe<Scalars["Int"]>; _in?: Maybe<Array<Scalars["Int"]>>; _is_null?: Maybe<Scalars["Boolean"]>; _lt?: Maybe<Scalars["Int"]>; _lte?: Maybe<Scalars["Int"]>; _neq?: Maybe<Scalars["Int"]>; _nin?: Maybe<Array<Scalars["Int"]>>; }; /** expression to compare columns of type String. All fields are combined with logical 'AND'. */ export type StringComparisonExp = { _eq?: Maybe<Scalars["String"]>; _gt?: Maybe<Scalars["String"]>; _gte?: Maybe<Scalars["String"]>; _ilike?: Maybe<Scalars["String"]>; _in?: Maybe<Array<Scalars["String"]>>; _is_null?: Maybe<Scalars["Boolean"]>; _like?: Maybe<Scalars["String"]>; _lt?: Maybe<Scalars["String"]>; _lte?: Maybe<Scalars["String"]>; _neq?: Maybe<Scalars["String"]>; _nilike?: Maybe<Scalars["String"]>; _nin?: Maybe<Array<Scalars["String"]>>; _nlike?: Maybe<Scalars["String"]>; _nsimilar?: Maybe<Scalars["String"]>; _similar?: Maybe<Scalars["String"]>; }; /** mutation root */ export type MutationRoot = { __typename?: "mutation_root"; /** delete data from the table: "todos" */ delete_todos?: Maybe<TodosMutationResponse>; /** delete single row from the table: "todos" */ delete_todos_by_pk?: Maybe<Todos>; /** insert data into the table: "todos" */ insert_todos?: Maybe<TodosMutationResponse>; /** insert a single row into the table: "todos" */ insert_todos_one?: Maybe<Todos>; /** update data of the table: "todos" */ update_todos?: Maybe<TodosMutationResponse>; /** update single row of the table: "todos" */ update_todos_by_pk?: Maybe<Todos>; }; /** mutation root */ export type MutationRootDeleteTodosArgs = { where: TodosBoolExp; }; /** mutation root */ export type MutationRootDeleteTodosByPkArgs = { id: Scalars["Int"]; }; /** mutation root */ export type MutationRootInsertTodosArgs = { objects: Array<TodosInsertInput>; on_conflict?: Maybe<TodosOnConflict>; }; /** mutation root */ export type MutationRootInsertTodosOneArgs = { object: TodosInsertInput; on_conflict?: Maybe<TodosOnConflict>; }; /** mutation root */ export type MutationRootUpdateTodosArgs = { _inc?: Maybe<TodosIncInput>; _set?: Maybe<TodosSetInput>; where: TodosBoolExp; }; /** mutation root */ export type MutationRootUpdateTodosByPkArgs = { _inc?: Maybe<TodosIncInput>; _set?: Maybe<TodosSetInput>; pk_columns: TodosPkColumnsInput; }; /** column ordering options */ export enum OrderBy { /** in the ascending order, nulls last */ Asc = "asc", /** in the ascending order, nulls first */ AscNullsFirst = "asc_nulls_first", /** in the ascending order, nulls last */ AscNullsLast = "asc_nulls_last", /** in the descending order, nulls first */ Desc = "desc", /** in the descending order, nulls first */ DescNullsFirst = "desc_nulls_first", /** in the descending order, nulls last */ DescNullsLast = "desc_nulls_last", } /** query root */ export type QueryRoot = { __typename?: "query_root"; /** fetch data from the table: "todos" */ todos: Array<Todos>; /** fetch aggregated fields from the table: "todos" */ todos_aggregate: TodosAggregate; /** fetch data from the table: "todos" using primary key columns */ todos_by_pk?: Maybe<Todos>; }; /** query root */ export type QueryRootTodosArgs = { distinct_on?: Maybe<Array<TodosSelectColumn>>; limit?: Maybe<Scalars["Int"]>; offset?: Maybe<Scalars["Int"]>; order_by?: Maybe<Array<TodosOrderBy>>; where?: Maybe<TodosBoolExp>; }; /** query root */ export type QueryRootTodosAggregateArgs = { distinct_on?: Maybe<Array<TodosSelectColumn>>; limit?: Maybe<Scalars["Int"]>; offset?: Maybe<Scalars["Int"]>; order_by?: Maybe<Array<TodosOrderBy>>; where?: Maybe<TodosBoolExp>; }; /** query root */ export type QueryRootTodosByPkArgs = { id: Scalars["Int"]; }; /** subscription root */ export type SubscriptionRoot = { __typename?: "subscription_root"; /** fetch data from the table: "todos" */ todos: Array<Todos>; /** fetch aggregated fields from the table: "todos" */ todos_aggregate: TodosAggregate; /** fetch data from the table: "todos" using primary key columns */ todos_by_pk?: Maybe<Todos>; }; /** subscription root */ export type SubscriptionRootTodosArgs = { distinct_on?: Maybe<Array<TodosSelectColumn>>; limit?: Maybe<Scalars["Int"]>; offset?: Maybe<Scalars["Int"]>; order_by?: Maybe<Array<TodosOrderBy>>; where?: Maybe<TodosBoolExp>; }; /** subscription root */ export type SubscriptionRootTodosAggregateArgs = { distinct_on?: Maybe<Array<TodosSelectColumn>>; limit?: Maybe<Scalars["Int"]>; offset?: Maybe<Scalars["Int"]>; order_by?: Maybe<Array<TodosOrderBy>>; where?: Maybe<TodosBoolExp>; }; /** subscription root */ export type SubscriptionRootTodosByPkArgs = { id: Scalars["Int"]; }; /** columns and relationships of "todos" */ export type Todos = { __typename?: "todos"; complete: Scalars["Boolean"]; id: Scalars["Int"]; name: Scalars["String"]; }; /** aggregated selection of "todos" */ export type TodosAggregate = { __typename?: "todos_aggregate"; aggregate?: Maybe<TodosAggregateFields>; nodes: Array<Todos>; }; /** aggregate fields of "todos" */ export type TodosAggregateFields = { __typename?: "todos_aggregate_fields"; avg?: Maybe<TodosAvgFields>; count?: Maybe<Scalars["Int"]>; max?: Maybe<TodosMaxFields>; min?: Maybe<TodosMinFields>; stddev?: Maybe<TodosStddevFields>; stddev_pop?: Maybe<TodosStddevPopFields>; stddev_samp?: Maybe<TodosStddevSampFields>; sum?: Maybe<TodosSumFields>; var_pop?: Maybe<TodosVarPopFields>; var_samp?: Maybe<TodosVarSampFields>; variance?: Maybe<TodosVarianceFields>; }; /** aggregate fields of "todos" */ export type TodosAggregateFieldsCountArgs = { columns?: Maybe<Array<TodosSelectColumn>>; distinct?: Maybe<Scalars["Boolean"]>; }; /** order by aggregate values of table "todos" */ export type TodosAggregateOrderBy = { avg?: Maybe<TodosAvgOrderBy>; count?: Maybe<OrderBy>; max?: Maybe<TodosMaxOrderBy>; min?: Maybe<TodosMinOrderBy>; stddev?: Maybe<TodosStddevOrderBy>; stddev_pop?: Maybe<TodosStddevPopOrderBy>; stddev_samp?: Maybe<TodosStddevSampOrderBy>; sum?: Maybe<TodosSumOrderBy>; var_pop?: Maybe<TodosVarPopOrderBy>; var_samp?: Maybe<TodosVarSampOrderBy>; variance?: Maybe<TodosVarianceOrderBy>; }; /** input type for inserting array relation for remote table "todos" */ export type TodosArrRelInsertInput = { data: Array<TodosInsertInput>; on_conflict?: Maybe<TodosOnConflict>; }; /** aggregate avg on columns */ export type TodosAvgFields = { __typename?: "todos_avg_fields"; id?: Maybe<Scalars["Float"]>; }; /** order by avg() on columns of table "todos" */ export type TodosAvgOrderBy = { id?: Maybe<OrderBy>; }; /** Boolean expression to filter rows from the table "todos". All fields are combined with a logical 'AND'. */ export type TodosBoolExp = { _and?: Maybe<Array<Maybe<TodosBoolExp>>>; _not?: Maybe<TodosBoolExp>; _or?: Maybe<Array<Maybe<TodosBoolExp>>>; complete?: Maybe<BooleanComparisonExp>; id?: Maybe<IntComparisonExp>; name?: Maybe<StringComparisonExp>; }; /** unique or primary key constraints on table "todos" */ export enum TodosConstraint { /** unique or primary key constraint */ TodosPkey = "todos_pkey", } /** input type for incrementing integer column in table "todos" */ export type TodosIncInput = { id?: Maybe<Scalars["Int"]>; }; /** input type for inserting data into table "todos" */ export type TodosInsertInput = { complete?: Maybe<Scalars["Boolean"]>; id?: Maybe<Scalars["Int"]>; name?: Maybe<Scalars["String"]>; }; /** aggregate max on columns */ export type TodosMaxFields = { __typename?: "todos_max_fields"; id?: Maybe<Scalars["Int"]>; name?: Maybe<Scalars["String"]>; }; /** order by max() on columns of table "todos" */ export type TodosMaxOrderBy = { id?: Maybe<OrderBy>; name?: Maybe<OrderBy>; }; /** aggregate min on columns */ export type TodosMinFields = { __typename?: "todos_min_fields"; id?: Maybe<Scalars["Int"]>; name?: Maybe<Scalars["String"]>; }; /** order by min() on columns of table "todos" */ export type TodosMinOrderBy = { id?: Maybe<OrderBy>; name?: Maybe<OrderBy>; }; /** response of any mutation on the table "todos" */ export type TodosMutationResponse = { __typename?: "todos_mutation_response"; /** number of affected rows by the mutation */ affected_rows: Scalars["Int"]; /** data of the affected rows by the mutation */ returning: Array<Todos>; }; /** input type for inserting object relation for remote table "todos" */ export type TodosObjRelInsertInput = { data: TodosInsertInput; on_conflict?: Maybe<TodosOnConflict>; }; /** on conflict condition type for table "todos" */ export type TodosOnConflict = { constraint: TodosConstraint; update_columns: Array<TodosUpdateColumn>; where?: Maybe<TodosBoolExp>; }; /** ordering options when selecting data from "todos" */ export type TodosOrderBy = { complete?: Maybe<OrderBy>; id?: Maybe<OrderBy>; name?: Maybe<OrderBy>; }; /** primary key columns input for table: "todos" */ export type TodosPkColumnsInput = { id: Scalars["Int"]; }; /** select columns of table "todos" */ export enum TodosSelectColumn { /** column name */ Complete = "complete", /** column name */ Id = "id", /** column name */ Name = "name", } /** input type for updating data in table "todos" */ export type TodosSetInput = { complete?: Maybe<Scalars["Boolean"]>; id?: Maybe<Scalars["Int"]>; name?: Maybe<Scalars["String"]>; }; /** aggregate stddev on columns */ export type TodosStddevFields = { __typename?: "todos_stddev_fields"; id?: Maybe<Scalars["Float"]>; }; /** order by stddev() on columns of table "todos" */ export type TodosStddevOrderBy = { id?: Maybe<OrderBy>; }; /** aggregate stddev_pop on columns */ export type TodosStddevPopFields = { __typename?: "todos_stddev_pop_fields"; id?: Maybe<Scalars["Float"]>; }; /** order by stddev_pop() on columns of table "todos" */ export type TodosStddevPopOrderBy = { id?: Maybe<OrderBy>; }; /** aggregate stddev_samp on columns */ export type TodosStddevSampFields = { __typename?: "todos_stddev_samp_fields"; id?: Maybe<Scalars["Float"]>; }; /** order by stddev_samp() on columns of table "todos" */ export type TodosStddevSampOrderBy = { id?: Maybe<OrderBy>; }; /** aggregate sum on columns */ export type TodosSumFields = { __typename?: "todos_sum_fields"; id?: Maybe<Scalars["Int"]>; }; /** order by sum() on columns of table "todos" */ export type TodosSumOrderBy = { id?: Maybe<OrderBy>; }; /** update columns of table "todos" */ export enum TodosUpdateColumn { /** column name */ Complete = "complete", /** column name */ Id = "id", /** column name */ Name = "name", } /** aggregate var_pop on columns */ export type TodosVarPopFields = { __typename?: "todos_var_pop_fields"; id?: Maybe<Scalars["Float"]>; }; /** order by var_pop() on columns of table "todos" */ export type TodosVarPopOrderBy = { id?: Maybe<OrderBy>; }; /** aggregate var_samp on columns */ export type TodosVarSampFields = { __typename?: "todos_var_samp_fields"; id?: Maybe<Scalars["Float"]>; }; /** order by var_samp() on columns of table "todos" */ export type TodosVarSampOrderBy = { id?: Maybe<OrderBy>; }; /** aggregate variance on columns */ export type TodosVarianceFields = { __typename?: "todos_variance_fields"; id?: Maybe<Scalars["Float"]>; }; /** order by variance() on columns of table "todos" */ export type TodosVarianceOrderBy = { id?: Maybe<OrderBy>; }; export type TodosQueryVariables = Exact<{ [key: string]: never }>; export type TodosQuery = { __typename?: "query_root" } & { todos: Array< { __typename?: "todos" } & Pick<Todos, "id" | "name" | "complete"> >; }; export type CreateTodoMutationVariables = Exact<{ name: Scalars["String"]; }>; export type CreateTodoMutation = { __typename?: "mutation_root" } & { insert_todos?: Maybe< { __typename?: "todos_mutation_response" } & { returning: Array< { __typename?: "todos" } & Pick<Todos, "id" | "name" | "complete"> >; } >; }; export type UpdateTodoMutationVariables = Exact<{ id: Scalars["Int"]; complete: Scalars["Boolean"]; }>; export type UpdateTodoMutation = { __typename?: "mutation_root" } & { update_todos?: Maybe< { __typename?: "todos_mutation_response" } & { returning: Array< { __typename?: "todos" } & Pick<Todos, "id" | "name" | "complete"> >; } >; }; export type DeleteTodoMutationVariables = Exact<{ id: Scalars["Int"]; }>; export type DeleteTodoMutation = { __typename?: "mutation_root" } & { delete_todos?: Maybe< { __typename?: "todos_mutation_response" } & { returning: Array<{ __typename?: "todos" } & Pick<Todos, "id">>; } >; }; export const TodosDocument = gql` query Todos { todos { id name complete } } `; /** * __useTodosQuery__ * * To run a query within a React component, call `useTodosQuery` and pass it any options that fit your needs. * When your component renders, `useTodosQuery` returns an object from Apollo Client that contains loading, error, and data properties * you can use to render your UI. * * @param baseOptions options that will be passed into the query, supported options are listed on: https://www.apollographql.com/docs/react/api/react-hooks/#options; * * @example * const { data, loading, error } = useTodosQuery({ * variables: { * }, * }); */ export function useTodosQuery( baseOptions?: Apollo.QueryHookOptions<TodosQuery, TodosQueryVariables> ) { return Apollo.useQuery<TodosQuery, TodosQueryVariables>( TodosDocument, baseOptions ); } export function useTodosLazyQuery( baseOptions?: Apollo.LazyQueryHookOptions<TodosQuery, TodosQueryVariables> ) { return Apollo.useLazyQuery<TodosQuery, TodosQueryVariables>( TodosDocument, baseOptions ); } export type TodosQueryHookResult = ReturnType<typeof useTodosQuery>; export type TodosLazyQueryHookResult = ReturnType<typeof useTodosLazyQuery>; export type TodosQueryResult = Apollo.QueryResult< TodosQuery, TodosQueryVariables >; export const CreateTodoDocument = gql` mutation CreateTodo($name: String!) { insert_todos(objects: { name: $name }) { returning { id name complete } } } `; export type CreateTodoMutationFn = Apollo.MutationFunction< CreateTodoMutation, CreateTodoMutationVariables >; /** * __useCreateTodoMutation__ * * To run a mutation, you first call `useCreateTodoMutation` within a React component and pass it any options that fit your needs. * When your component renders, `useCreateTodoMutation` returns a tuple that includes: * - A mutate function that you can call at any time to execute the mutation * - An object with fields that represent the current status of the mutation's execution * * @param baseOptions options that will be passed into the mutation, supported options are listed on: https://www.apollographql.com/docs/react/api/react-hooks/#options-2; * * @example * const [createTodoMutation, { data, loading, error }] = useCreateTodoMutation({ * variables: { * name: // value for 'name' * }, * }); */ export function useCreateTodoMutation( baseOptions?: Apollo.MutationHookOptions< CreateTodoMutation, CreateTodoMutationVariables > ) { return Apollo.useMutation<CreateTodoMutation, CreateTodoMutationVariables>( CreateTodoDocument, baseOptions ); } export type CreateTodoMutationHookResult = ReturnType< typeof useCreateTodoMutation >; export type CreateTodoMutationResult = Apollo.MutationResult< CreateTodoMutation >; export type CreateTodoMutationOptions = Apollo.BaseMutationOptions< CreateTodoMutation, CreateTodoMutationVariables >; export const UpdateTodoDocument = gql` mutation UpdateTodo($id: Int!, $complete: Boolean!) { update_todos(where: { id: { _eq: $id } }, _set: { complete: $complete }) { returning { id name complete } } } `; export type UpdateTodoMutationFn = Apollo.MutationFunction< UpdateTodoMutation, UpdateTodoMutationVariables >; /** * __useUpdateTodoMutation__ * * To run a mutation, you first call `useUpdateTodoMutation` within a React component and pass it any options that fit your needs. * When your component renders, `useUpdateTodoMutation` returns a tuple that includes: * - A mutate function that you can call at any time to execute the mutation * - An object with fields that represent the current status of the mutation's execution * * @param baseOptions options that will be passed into the mutation, supported options are listed on: https://www.apollographql.com/docs/react/api/react-hooks/#options-2; * * @example * const [updateTodoMutation, { data, loading, error }] = useUpdateTodoMutation({ * variables: { * id: // value for 'id' * complete: // value for 'complete' * }, * }); */ export function useUpdateTodoMutation( baseOptions?: Apollo.MutationHookOptions< UpdateTodoMutation, UpdateTodoMutationVariables > ) { return Apollo.useMutation<UpdateTodoMutation, UpdateTodoMutationVariables>( UpdateTodoDocument, baseOptions ); } export type UpdateTodoMutationHookResult = ReturnType< typeof useUpdateTodoMutation >; export type UpdateTodoMutationResult = Apollo.MutationResult< UpdateTodoMutation >; export type UpdateTodoMutationOptions = Apollo.BaseMutationOptions< UpdateTodoMutation, UpdateTodoMutationVariables >; export const DeleteTodoDocument = gql` mutation DeleteTodo($id: Int!) { delete_todos(where: { id: { _eq: $id } }) { returning { id } } } `; export type DeleteTodoMutationFn = Apollo.MutationFunction< DeleteTodoMutation, DeleteTodoMutationVariables >; /** * __useDeleteTodoMutation__ * * To run a mutation, you first call `useDeleteTodoMutation` within a React component and pass it any options that fit your needs. * When your component renders, `useDeleteTodoMutation` returns a tuple that includes: * - A mutate function that you can call at any time to execute the mutation * - An object with fields that represent the current status of the mutation's execution * * @param baseOptions options that will be passed into the mutation, supported options are listed on: https://www.apollographql.com/docs/react/api/react-hooks/#options-2; * * @example * const [deleteTodoMutation, { data, loading, error }] = useDeleteTodoMutation({ * variables: { * id: // value for 'id' * }, * }); */ export function useDeleteTodoMutation( baseOptions?: Apollo.MutationHookOptions< DeleteTodoMutation, DeleteTodoMutationVariables > ) { return Apollo.useMutation<DeleteTodoMutation, DeleteTodoMutationVariables>( DeleteTodoDocument, baseOptions ); } export type DeleteTodoMutationHookResult = ReturnType< typeof useDeleteTodoMutation >; export type DeleteTodoMutationResult = Apollo.MutationResult< DeleteTodoMutation >; export type DeleteTodoMutationOptions = Apollo.BaseMutationOptions< DeleteTodoMutation, DeleteTodoMutationVariables >;
the_stack
import InterfacesDefault from "../src/interfaces"; import { runModule } from "../src/module"; import path from "path"; import * as utils from "../src/utils"; import * as cms from "../src/cms"; import * as locales from "../src/locales"; import * as packages from "../src/packages"; import * as theme from "../src/theme"; import chokidar from "chokidar"; import fse from "fs-extra"; import { ShopwarePwaConfigFile } from "@shopware-pwa/commons"; import * as files from "@shopware-pwa/commons/node"; jest.mock("../src/utils"); jest.mock("../src/cms"); jest.mock("../src/locales"); jest.mock("../src/packages"); jest.mock("../src/theme"); jest.mock("chokidar"); jest.mock("fs-extra"); jest.mock("@shopware-pwa/commons/node"); const mockedUtils = utils as jest.Mocked<typeof utils>; const mockedTheme = theme as jest.Mocked<typeof theme>; const mockedFiles = files as jest.Mocked<typeof files>; const consoleErrorSpy = jest.spyOn(console, "error"); const consoleInfoSpy = jest.spyOn(console, "info"); const mockedChokidar = chokidar as jest.Mocked<typeof chokidar>; const mockedFse = fse as jest.Mocked<typeof fse>; describe("nuxt-module - ShopwarePWAModule runModule", () => { let webpackConfig: any = {}; let webpackContext: any = {}; let methods: Function[] = []; const moduleObject: any = { options: { rootDir: __dirname, router: { middleware: [], }, features: { store: null, }, }, addLayout: jest.fn(), extendRoutes: jest.fn(), addPlugin: jest.fn(), nuxt: { hook: jest.fn(), resolver: { resolveModule: jest.fn(), }, }, extendBuild: (method: Function): number => methods.push(method), }; let THEME_SOURCE = path.join("node_modules", "theme-name"); let PROJECT_SOURCE = "src"; let TARGET_SOURCE = path.join(".shopware-pwa", "source"); /** * To resolve extendBuild we need to invoke resolveBuilds after method * invocation to test real impact on webpack configuration */ const resolveBuilds = () => methods.forEach((method) => method(webpackConfig, webpackContext)); beforeEach(() => { jest.resetAllMocks(); //clean shopware config delete moduleObject.options.shopware; mockedUtils.loadConfig.mockResolvedValue({ shopwareEndpoint: "mockedEndpoint", shopwareAccessToken: "mockedToken", theme: "theme-name", }); webpackConfig = { resolve: { alias: {}, }, optimization: { splitChunks: { cacheGroups: { commons: { minChunks: 0, }, }, }, }, }; methods = []; webpackContext = { isClient: true, isDev: false, }; consoleErrorSpy.mockImplementationOnce(() => {}); consoleInfoSpy.mockImplementationOnce(() => {}); mockedTheme.getThemeSourcePath.mockReturnValue(THEME_SOURCE); mockedTheme.getTargetSourcePath.mockReturnValue(TARGET_SOURCE); mockedTheme.getProjectSourcePath.mockReturnValue(PROJECT_SOURCE); mockedChokidar.watch.mockReturnValue({ on: () => {} }); mockedFiles.getAllFiles.mockReturnValue([]); }); it("should invoke config load", async () => { await runModule(moduleObject, {}); expect(mockedUtils.loadConfig).toBeCalledWith(moduleObject); }); it("should display a meesage when default config cannot be fetched", async () => { await runModule(moduleObject, {}); expect(consoleErrorSpy).toBeCalledWith( "Cannot resolve API defaults config", expect.anything() ); }); it("should invoke useThemeAndProjectFiles", async () => { await runModule(moduleObject, {}); expect(mockedTheme.useThemeAndProjectFiles).toBeCalledWith({ THEME_SOURCE, PROJECT_SOURCE, TARGET_SOURCE, }); }); it("should add api-client plugin", async () => { await runModule(moduleObject, {}); const pathForApiClientPlugin = path.join( __dirname, "..", "plugins", "api-client.js" ); expect(moduleObject.addPlugin).toBeCalledWith({ fileName: "api-client.js", options: { shopwareAccessToken: "mockedToken", shopwareEndpoint: "mockedEndpoint", apiDefaults: expect.anything(), }, src: pathForApiClientPlugin, }); }); it("should add entities-parser client plugin", async () => { await runModule(moduleObject, {}); const pathForEntitiesParserClientPlugin = path.join( __dirname, "..", "plugins", "entities-parser", "entities-parser.csr.js" ); expect(moduleObject.addPlugin).toBeCalledWith({ fileName: "entities-parser.csr.js", mode: "client", options: {}, src: pathForEntitiesParserClientPlugin, }); }); it("should add entities-parser server plugin", async () => { await runModule(moduleObject, {}); const pathForEntitiesParserServerPlugin = path.join( __dirname, "..", "plugins", "entities-parser", "entities-parser.ssr.js" ); expect(moduleObject.addPlugin).toBeCalledWith({ fileName: "entities-parser.ssr.js", mode: "server", options: {}, src: pathForEntitiesParserServerPlugin, }); }); it("should show console info, that shopware-pwa.config.js is missing endpoint settings", async () => { mockedUtils.loadConfig.mockResolvedValueOnce({} as ShopwarePwaConfigFile); await runModule(moduleObject, {}); expect(consoleErrorSpy).toBeCalledWith( "shopwareAccessToken in shopware-pwa.config.js is missing" ); expect(consoleErrorSpy).toBeCalledWith( "shopwareEndpoint in shopware-pwa.config.js is missing" ); }); it("should show info which theme is used from config", async () => { mockedUtils.loadConfig.mockResolvedValueOnce({ theme: "my-theme-name", } as ShopwarePwaConfigFile); await runModule(moduleObject, {}); expect(consoleInfoSpy).toBeCalledWith("Using theme: my-theme-name"); }); it("should have extra API client related config", async () => { mockedUtils.loadConfig.mockResolvedValueOnce({ shopwareEndpoint: "https://shopware-pwa.storefrontcloud.io/sales-channel-api/v1", shopwareAccessToken: "mockedToken", theme: "@shopware-pwa/default-theme", shopwareApiClient: { timeout: 5, }, }); const pathForApiClientPlugin = path.join( __dirname, "..", "plugins", "api-client.js" ); await runModule(moduleObject, {}); expect(moduleObject.addPlugin).toBeCalledWith({ fileName: "api-client.js", options: { shopwareAccessToken: "mockedToken", shopwareEndpoint: "https://shopware-pwa.storefrontcloud.io/sales-channel-api/v1", shopwareApiClient: { timeout: 5, }, apiDefaults: expect.anything(), }, src: pathForApiClientPlugin, }); }); it("should add cookies plugin", async () => { await runModule(moduleObject, {}); expect(moduleObject.addPlugin).toBeCalled(); const pathForCookiesPlugin = path.join( __dirname, "..", "plugins", "cookie-universal-nuxt.js" ); expect(moduleObject.addPlugin).toBeCalledWith({ fileName: "cookie-universal-nuxt.js", options: { alias: "cookies", parseJSON: true, }, src: pathForCookiesPlugin, }); }); it("should extend build wirh sw-plugins alias", async () => { await runModule(moduleObject, {}); resolveBuilds(); expect(webpackConfig.resolve.alias["sw-plugins"]).toEqual( path.join(__dirname, ".shopware-pwa", "sw-plugins") ); }); it("should not change webpack chunks config if it's server build", async () => { webpackContext.isClient = false; await runModule(moduleObject, {}); resolveBuilds(); expect( webpackConfig.optimization.splitChunks.cacheGroups.commons.minChunks ).toEqual(0); }); it("should not change webpack chunks config if it's a dev build", async () => { webpackContext.isClient = true; webpackContext.isDev = true; await runModule(moduleObject, {}); resolveBuilds(); expect( webpackConfig.optimization.splitChunks.cacheGroups.commons.minChunks ).toEqual(0); }); it("should change webpack chunks config if it's client prod build", async () => { webpackContext.isClient = true; webpackContext.isDev = false; await runModule(moduleObject, {}); resolveBuilds(); expect( webpackConfig.optimization.splitChunks.cacheGroups.commons.minChunks ).toEqual(2); }); it("should invoke extendCMS", async () => { await runModule(moduleObject, {}); expect(cms.extendCMS).toBeCalledWith(moduleObject, { shopwareAccessToken: "mockedToken", shopwareEndpoint: "mockedEndpoint", theme: THEME_SOURCE, }); }); it("should invoke extendLocales", async () => { await runModule(moduleObject, {}); expect(locales.extendLocales).toBeCalledWith(moduleObject, { shopwareAccessToken: "mockedToken", shopwareEndpoint: "mockedEndpoint", theme: THEME_SOURCE, }); }); it("should invoke useCorePackages", async () => { await runModule(moduleObject, {}); expect(packages.useCorePackages).toBeCalledWith(moduleObject, [ "@shopware-pwa/composables", "@shopware-pwa/commons", "@shopware-pwa/helpers", "@shopware-pwa/shopware-6-client", "@storefront-ui/vue", "@storefront-ui/shared", ]); }); it("should add babel preset to config", async () => { await runModule(moduleObject, {}); expect(moduleObject.options.build.babel.presets).toBeTruthy(); }); it("interfaces should return default empty object", () => { expect(InterfacesDefault).toEqual({}); }); it("should change build chunk names", async () => { await runModule(moduleObject, {}); expect(moduleObject.options.build.filenames.chunk).toBeTruthy(); expect( moduleObject.options.build.filenames.chunk({ isDev: false }) ).toEqual("[id].[contenthash].js"); expect(moduleObject.options.build.filenames.chunk({ isDev: true })).toEqual( "[name].js" ); }); it("should not watch files if not in development mode", async () => { await runModule(moduleObject, {}); expect(mockedChokidar.watch).not.toBeCalled(); }); it("should start watching files on development mode", async () => { moduleObject.options.dev = true; await runModule(moduleObject, {}); expect(mockedChokidar.watch).toBeCalledWith([THEME_SOURCE], { followSymlinks: true, ignoreInitial: true, ignored: path.join(THEME_SOURCE, "node_modules/**/*"), }); expect(mockedChokidar.watch).toBeCalledWith(["src"], { ignoreInitial: true, }); }); it("should invoke onThemeFilesChanged when theme files change", async () => { moduleObject.options.dev = true; const invocationList: any[] = []; const onMock = jest .fn() .mockImplementation((name, fn) => invocationList.push(fn)); mockedChokidar.watch.mockReturnValueOnce({ on: onMock } as any); await runModule(moduleObject, {}); expect(onMock).toBeCalledWith("all", expect.any(Function)); expect(invocationList.length).toEqual(1); invocationList[0]("add", "some/filepath.vue"); expect(mockedTheme.onThemeFilesChanged).toBeCalledWith({ THEME_SOURCE, PROJECT_SOURCE, TARGET_SOURCE, event: "add", filePath: "some/filepath.vue", }); }); it("should invoke onProjectFilesChanged when project files change", async () => { moduleObject.options.dev = true; const invocationList: any[] = []; const onMock = jest .fn() .mockImplementation((name, fn) => invocationList.push(fn)); // first invocation is for onThemeFilesChanged mockedChokidar.watch.mockReturnValueOnce({ on: () => {}, } as any); mockedChokidar.watch.mockReturnValueOnce({ on: onMock, } as any); await runModule(moduleObject, {}); expect(onMock).toBeCalledWith("all", expect.any(Function)); expect(invocationList.length).toEqual(1); invocationList[0]("add", "some/project/filepath.vue"); expect(mockedTheme.onProjectFilesChanged).toBeCalledWith({ THEME_SOURCE, PROJECT_SOURCE, TARGET_SOURCE, event: "add", filePath: "some/project/filepath.vue", }); }); describe("vuex store", () => { it("should enable vuex store", async () => { moduleObject.options.shopware ??= {}; moduleObject.options.shopware.enableVuex = true; await runModule(moduleObject, {}); expect(moduleObject.options.store).toEqual(true); expect(moduleObject.options.features.store).toEqual(true); }); it("should be disabled by default", async () => { await runModule(moduleObject, {}); expect(moduleObject.options.store).toEqual(false); expect(moduleObject.options.features.store).toEqual(false); }); it("should be disabled by default with shopware option", async () => { moduleObject.options.shopware ??= {}; await runModule(moduleObject, {}); expect(moduleObject.options.store).toEqual(false); expect(moduleObject.options.features.store).toEqual(false); }); }); it("should copy target static directory to project root directory after production build", async () => { moduleObject.options.dev = false; const afterBuildMethods: any[] = []; moduleObject.nuxt.hook.mockImplementation( (hookName: string, method: Function) => { hookName === "build:done" && afterBuildMethods.push(method); } ); await runModule(moduleObject, {}); expect(moduleObject.nuxt.hook).toBeCalledWith( "build:done", expect.any(Function) ); expect(afterBuildMethods.length).toEqual(1); await afterBuildMethods[0](moduleObject); const fromPath = path.join(TARGET_SOURCE, "static"); const toPath = path.join(moduleObject.options.rootDir, "static"); expect(mockedFse.copy).toBeCalledWith(fromPath, toPath); expect(consoleInfoSpy).toBeCalledWith( "Moved static files to root directory static folder. Make sure your static files are placed inside `src/static` directory." ); }); it("should add plugins registered in theme - js|ts files only including extracted mode", async () => { mockedFiles.getAllFiles.mockReturnValueOnce([ "/file/path/plugins/notifications.js", "/file/path/plugins/README.md", "/file/path/plugins/custom-plugin.ts", "/file/path/plugins/server-plugin.server.ts", "/file/path/plugins/client-plugin.client.ts", ]); await runModule(moduleObject, {}); expect(moduleObject.addPlugin).toHaveBeenCalledWith({ src: "/file/path/plugins/notifications.js", fileName: "notifications.js", options: expect.anything(), }); expect(moduleObject.addPlugin).toHaveBeenCalledWith({ src: "/file/path/plugins/custom-plugin.ts", fileName: "custom-plugin.ts", options: expect.anything(), }); expect(moduleObject.addPlugin).not.toHaveBeenCalledWith({ src: "/file/path/plugins/README.md", fileName: "README.md", options: expect.anything(), }); expect(moduleObject.addPlugin).toHaveBeenCalledWith({ src: "/file/path/plugins/client-plugin.client.ts", fileName: "client-plugin.client.ts", options: expect.anything(), mode: "client", }); }); });
the_stack
import { SyntheticViewTemplate, Updates } from "@microsoft/fast-element"; import { attr, Observable, observable } from "@microsoft/fast-element"; import { limit, uniqueId } from "@microsoft/fast-web-utilities"; import type { FoundationElementDefinition } from "../foundation-element/foundation-element.js"; import type { ListboxOption } from "../listbox-option/listbox-option.js"; import { DelegatesARIAListbox } from "../listbox/listbox.js"; import type { StartEndOptions } from "../patterns/start-end.js"; import { StartEnd } from "../patterns/start-end.js"; import { SelectPosition } from "../select/select.options.js"; import { applyMixins } from "../utilities/apply-mixins.js"; import { FormAssociatedCombobox } from "./combobox.form-associated.js"; import { ComboboxAutocomplete } from "./combobox.options.js"; /** * Combobox configuration options * @public */ export type ComboboxOptions = FoundationElementDefinition & StartEndOptions & { indicator?: string | SyntheticViewTemplate; }; /** * A Combobox Custom HTML Element. * Implements the {@link https://w3c.github.io/aria-practices/#combobox | ARIA combobox }. * * @slot start - Content which can be provided before the input * @slot end - Content which can be provided after the input * @slot control - Used to replace the input element representing the combobox * @slot indicator - The visual indicator representing the expanded state * @slot - The default slot for the options * @csspart control - The wrapper element containing the input area, including start and end * @csspart selected-value - The input element representing the selected value * @csspart indicator - The element wrapping the indicator slot * @csspart listbox - The wrapper for the listbox slotted options * @fires change - Fires a custom 'change' event when the value updates * * @public */ export class Combobox extends FormAssociatedCombobox { /** * The internal value property. * * @internal */ private _value: string = ""; /** * The autocomplete attribute. * * @public * @remarks * HTML Attribute: autocomplete */ @attr({ attribute: "autocomplete", mode: "fromView" }) autocomplete: ComboboxAutocomplete | undefined; /** * Reference to the internal text input element. * * @internal */ public control: HTMLInputElement; /** * Reference to the internal listbox element. * * @internal */ public listbox: HTMLDivElement; /** * The collection of currently filtered options. * * @public */ public filteredOptions: ListboxOption[] = []; /** * The current filter value. * * @internal */ private filter: string = ""; /** * The initial state of the position attribute. * * @internal */ private forcedPosition: boolean = false; /** * Reset the element to its first selectable option when its parent form is reset. * * @internal */ public formResetCallback(): void { super.formResetCallback(); this.setDefaultSelectedOption(); this.updateValue(); } private get isAutocompleteInline(): boolean { return ( this.autocomplete === ComboboxAutocomplete.inline || this.isAutocompleteBoth ); } private get isAutocompleteList(): boolean { return this.autocomplete === ComboboxAutocomplete.list || this.isAutocompleteBoth; } private get isAutocompleteBoth(): boolean { return this.autocomplete === ComboboxAutocomplete.both; } /** * The unique id for the internal listbox element. * * @internal */ public listboxId: string = uniqueId("listbox-"); /** * The max height for the listbox when opened. * * @internal */ @observable public maxHeight: number = 0; /** * The open attribute. * * @public * @remarks * HTML Attribute: open */ @attr({ attribute: "open", mode: "boolean" }) public open: boolean = false; /** * Sets focus and synchronize ARIA attributes when the open property changes. * * @param prev - the previous open value * @param next - the current open value * * @internal */ protected openChanged() { if (this.open) { this.ariaControls = this.listboxId; this.ariaExpanded = "true"; this.setPositioning(); this.focusAndScrollOptionIntoView(); // focus is directed to the element when `open` is changed programmatically Updates.enqueue(() => this.focus()); return; } this.ariaControls = ""; this.ariaExpanded = "false"; } /** * The list of options. * * @public * @remarks * Overrides `Listbox.options`. */ public get options(): ListboxOption[] { Observable.track(this, "options"); return this.filteredOptions.length ? this.filteredOptions : this._options; } public set options(value: ListboxOption[]) { this._options = value; Observable.notify(this, "options"); } /** * Sets the placeholder value of the element, generally used to provide a hint to the user. * @public * @remarks * HTML Attribute: placeholder * Using this attribute is not a valid substitute for a labeling element. */ @attr public placeholder: string; /** * Updates the placeholder on the proxy element. * @internal */ protected placeholderChanged(): void { if (this.proxy instanceof HTMLInputElement) { this.proxy.placeholder = this.placeholder; } } /** * The placement for the listbox when the combobox is open. * * @public */ @attr({ attribute: "position" }) public positionAttribute?: SelectPosition; /** * The current state of the calculated position of the listbox. * * @public */ @observable public position?: SelectPosition; protected positionChanged( prev: SelectPosition | undefined, next: SelectPosition | undefined ): void { this.positionAttribute = next; this.setPositioning(); } /** * The value property. * * @public */ public get value() { Observable.track(this, "value"); return this._value; } public set value(next: string) { const prev = `${this._value}`; if (this.$fastController.isConnected && this.options) { const selectedIndex = this.options.findIndex( el => el.text.toLowerCase() === next.toLowerCase() ); const prevSelectedValue = this.options[this.selectedIndex]?.text; const nextSelectedValue = this.options[selectedIndex]?.text; this.selectedIndex = prevSelectedValue !== nextSelectedValue ? selectedIndex : this.selectedIndex; next = this.firstSelectedOption?.text || next; } if (prev !== next) { this._value = next; super.valueChanged(prev, next); Observable.notify(this, "value"); } } /** * Handle opening and closing the listbox when the combobox is clicked. * * @param e - the mouse event * @internal */ public clickHandler(e: MouseEvent): boolean | void { if (this.disabled) { return; } if (this.open) { const captured = (e.target as HTMLElement).closest( `option,[role=option]` ) as ListboxOption | null; if (!captured || captured.disabled) { return; } this.selectedOptions = [captured]; this.control.value = captured.text; this.clearSelectionRange(); this.updateValue(true); } this.open = !this.open; if (this.open) { this.control.focus(); } return true; } public connectedCallback() { super.connectedCallback(); this.forcedPosition = !!this.positionAttribute; if (this.value) { this.initialValue = this.value; } } /** * Synchronize the `aria-disabled` property when the `disabled` property changes. * * @param prev - The previous disabled value * @param next - The next disabled value * * @internal */ public disabledChanged(prev: boolean, next: boolean): void { if (super.disabledChanged) { super.disabledChanged(prev, next); } this.ariaDisabled = this.disabled ? "true" : "false"; } /** * Filter available options by text value. * * @public */ public filterOptions(): void { if (!this.autocomplete || this.autocomplete === ComboboxAutocomplete.none) { this.filter = ""; } const filter = this.filter.toLowerCase(); this.filteredOptions = this._options.filter(o => o.text.toLowerCase().startsWith(this.filter.toLowerCase()) ); if (this.isAutocompleteList) { if (!this.filteredOptions.length && !filter) { this.filteredOptions = this._options; } this._options.forEach(o => { o.hidden = !this.filteredOptions.includes(o); }); } } /** * Focus the control and scroll the first selected option into view. * * @internal * @remarks * Overrides: `Listbox.focusAndScrollOptionIntoView` */ protected focusAndScrollOptionIntoView(): void { if (this.contains(document.activeElement)) { this.control.focus(); if (this.firstSelectedOption) { requestAnimationFrame(() => { this.firstSelectedOption?.scrollIntoView({ block: "nearest" }); }); } } } /** * Handle focus state when the element or its children lose focus. * * @param e - The focus event * @internal */ public focusoutHandler(e: FocusEvent): boolean | void { this.updateValue(); if (!this.open) { return true; } const focusTarget = e.relatedTarget as HTMLElement; if (this.isSameNode(focusTarget)) { this.focus(); return; } if (!this.options || !this.options.includes(focusTarget as ListboxOption)) { this.open = false; } } /** * Handle content changes on the control input. * * @param e - the input event * @internal */ public inputHandler(e: InputEvent): boolean | void { this.filter = this.control.value; this.filterOptions(); if (e.inputType === "deleteContentBackward" || !this.filter.length) { return true; } if (this.isAutocompleteList && !this.open) { this.open = true; } if (this.isAutocompleteInline && this.filteredOptions.length) { this.selectedOptions = [this.filteredOptions[0]]; this.selectedIndex = this.options.indexOf(this.firstSelectedOption); this.setInlineSelection(); } return; } /** * Handle keydown actions for listbox navigation. * * @param e - the keyboard event * @internal */ public keydownHandler(e: Event & KeyboardEvent): boolean | void { const key = e.key; if (e.ctrlKey || e.shiftKey) { return true; } switch (key) { case "Enter": { this.updateValue(true); if (this.isAutocompleteInline) { this.filter = this.value; } this.open = false; this.clearSelectionRange(); break; } case "Escape": { if (!this.isAutocompleteInline) { this.selectedIndex = -1; } if (this.open) { this.open = false; break; } this.value = ""; this.control.value = ""; this.filter = ""; this.filterOptions(); break; } case "Tab": { this.updateValue(); if (!this.open) { return true; } e.preventDefault(); this.open = false; break; } case "ArrowUp": case "ArrowDown": { this.filterOptions(); if (!this.open) { this.open = true; break; } if (this.filteredOptions.length > 0) { super.keydownHandler(e); } if (this.isAutocompleteInline) { this.updateValue(); this.setInlineSelection(); } break; } default: { return true; } } } /** * Handle keyup actions for value input and text field manipulations. * * @param e - the keyboard event * @internal */ public keyupHandler(e: KeyboardEvent): boolean | void { const key = e.key; switch (key) { case "ArrowLeft": case "ArrowRight": case "Backspace": case "Delete": case "Home": case "End": { this.filter = this.control.value; this.selectedIndex = -1; this.filterOptions(); break; } } } /** * Ensure that the selectedIndex is within the current allowable filtered range. * * @param prev - the previous selected index value * @param next - the current selected index value * * @internal */ public selectedIndexChanged(prev: number | undefined, next: number): void { if (this.$fastController.isConnected) { next = limit(-1, this.options.length - 1, next); // we only want to call the super method when the selectedIndex is in range if (next !== this.selectedIndex) { this.selectedIndex = next; return; } super.selectedIndexChanged(prev, next); } } /** * Move focus to the previous selectable option. * * @internal * @remarks * Overrides `Listbox.selectPreviousOption` */ public selectPreviousOption(): void { if (!this.disabled && this.selectedIndex >= 0) { this.selectedIndex = this.selectedIndex - 1; } } /** * Set the default selected options at initialization or reset. * * @internal * @remarks * Overrides `Listbox.setDefaultSelectedOption` */ public setDefaultSelectedOption(): void { if (this.$fastController.isConnected && this.options) { const selectedIndex = this.options.findIndex( el => el.getAttribute("selected") !== null || el.selected ); this.selectedIndex = selectedIndex; if (!this.dirtyValue && this.firstSelectedOption) { this.value = this.firstSelectedOption.text; } this.setSelectedOptions(); } } /** * Focus and select the content of the control based on the first selected option. * * @param start - The index for the starting range * @internal */ private setInlineSelection(): void { if (this.firstSelectedOption) { this.control.value = this.firstSelectedOption.text; this.control.focus(); this.control.setSelectionRange( this.filter.length, this.control.value.length, "backward" ); } } /** * Calculate and apply listbox positioning based on available viewport space. * * @param force - direction to force the listbox to display * @public */ public setPositioning(): void { const currentBox = this.getBoundingClientRect(); const viewportHeight = window.innerHeight; const availableBottom = viewportHeight - currentBox.bottom; this.position = this.forcedPosition ? this.positionAttribute : currentBox.top > availableBottom ? SelectPosition.above : SelectPosition.below; this.positionAttribute = this.forcedPosition ? this.positionAttribute : this.position; this.maxHeight = this.position === SelectPosition.above ? ~~currentBox.top : ~~availableBottom; } /** * Ensure that the entire list of options is used when setting the selected property. * * @param prev - the previous list of selected options * @param next - the current list of selected options * * @internal * @remarks * Overrides: `Listbox.selectedOptionsChanged` */ public selectedOptionsChanged( prev: ListboxOption[] | undefined, next: ListboxOption[] ): void { if (this.$fastController.isConnected) { this._options.forEach(o => { o.selected = next.includes(o); }); } } /** * Synchronize the form-associated proxy and update the value property of the element. * * @param prev - the previous collection of slotted option elements * @param next - the next collection of slotted option elements * * @internal */ public slottedOptionsChanged(prev: Element[] | undefined, next: Element[]): void { super.slottedOptionsChanged(prev, next); this.updateValue(); } /** * Sets the value and to match the first selected option. * * @param shouldEmit - if true, the change event will be emitted * * @internal */ private updateValue(shouldEmit?: boolean) { if (this.$fastController.isConnected) { this.value = this.firstSelectedOption?.text || this.control.value; } if (shouldEmit) { this.$emit("change"); } } /** * @internal */ private clearSelectionRange() { const controlValueLength = this.control.value.length; this.control.setSelectionRange(controlValueLength, controlValueLength); } } /** * Includes ARIA states and properties relating to the ARIA combobox role. * * @public */ export class DelegatesARIACombobox { /** * See {@link https://www.w3.org/TR/wai-aria-1.2/#aria-autocomplete} for more information. * * @public * @remarks * HTML Attribute: `aria-autocomplete` */ @observable public ariaAutoComplete: "inline" | "list" | "both" | "none" | string | null; /** * See {@link https://www.w3.org/TR/wai-aria-1.2/#aria-controls} for more information. * * @public * @remarks * HTML Attribute: `aria-controls` */ @observable public ariaControls: string | null; } /** * Mark internal because exporting class and interface of the same name * confuses API documenter. * TODO: https://github.com/microsoft/fast/issues/3317 * @internal */ export interface DelegatesARIACombobox extends DelegatesARIAListbox {} applyMixins(DelegatesARIACombobox, DelegatesARIAListbox); /** * Mark internal because exporting class and interface of the same name * confuses API documenter. * TODO: https://github.com/microsoft/fast/issues/3317 * @internal */ export interface Combobox extends StartEnd, DelegatesARIACombobox {} applyMixins(Combobox, StartEnd, DelegatesARIACombobox);
the_stack
import { assert, MultiMap, InterfaceType, isInterfaceType, isFed1Supergraph, isObjectType, isUnionType, NamedType, ObjectType, Schema, SchemaRootKind, Type, UnionType, baseType, SelectionSet, federationBuiltIns, isFederationSubgraphSchema, CompositeType, extractSubgraphsFromSupergraph, FieldDefinition, isCompositeType, parseFieldSetArgument, AbstractType, isAbstractType, possibleRuntimeTypes, MapWithCachedArrays, mapKeys, firstOf, FEDERATION_RESERVED_SUBGRAPH_NAME, ALL_SUBTYPING_RULES, externalDirectiveName, requiresDirectiveName, } from '@apollo/federation-internals'; import { inspect } from 'util'; import { DownCast, FieldCollection, subgraphEnteringTransition, SubgraphEnteringTransition, Transition, KeyResolution, RootTypeResolution } from './transition'; import { isStructuralFieldSubtype } from './structuralSubtyping'; // We use our federation reserved subgraph name to avoid risk of conflict with other subgraph names (wouldn't be a huge // deal, but safer that way). Using something short like `_` is also on purpose: it makes it stand out in debug messages // without taking space. const FEDERATED_GRAPH_ROOT_SOURCE = FEDERATION_RESERVED_SUBGRAPH_NAME; const FEDERATED_GRAPH_ROOT_SCHEMA = new Schema(); export function federatedGraphRootTypeName(rootKind: SchemaRootKind): string { return `[${rootKind}]`; } export function isFederatedGraphRootType(type: NamedType) { return type.name.startsWith('[') && type.name.endsWith(']'); } /** * A vertex of a query graph, which points to a type (definition) in a particular graphQL schema (the `source` being * an identifier for that schema). * * @see QueryGraph */ export class Vertex { constructor( /** Index used for this vertex in the query graph it is part of. */ readonly index: number, /** The graphQL type the vertex points to. */ readonly type: NamedType, /** * An identifier of the underlying schema containing the `type` this vertex points to. * This is mainly used in "federated" query graphs, where the `source` is a subgraph name. */ readonly source : string ) {} toString(): string { return `${this.type}(${this.source})`; } } /** * A "root" `Vertex`, that is a vertex that one of the root of a query graph. * * @see Vertex * @see QueryGraph.roots */ export class RootVertex extends Vertex { constructor( readonly rootKind: SchemaRootKind, index: number, type: NamedType, source : string ) { super(index, type, source); } toString(): string { return super.toString() + '*'; } } function toRootVertex(vertex: Vertex, rootKind: SchemaRootKind): RootVertex { return new RootVertex(rootKind, vertex.index, vertex.type, vertex.source); } export function isRootVertex(vertex: Vertex): vertex is RootVertex { return vertex instanceof RootVertex; } /** * An edge of a query graph. * * Query graphs are directed and an edge goes from its `head` vertex to its `tail` one. * Edges also have additional metadata: their `transition` and, optionally, `conditions`. */ export class Edge { private _conditions?: SelectionSet; constructor( /** * Index used for this edge in the query graph it is part of (note that this index is "scoped" within * the head vertex, meaning that if 2 different vertices of the same query graph both have a single * out-edge, then both of those edges have index 0, and if a vertex has 3 out-edges, their index will * be 0, 1 and 2). */ public readonly index: number, /** * The vertex from which the edge starts. */ public readonly head: Vertex, /** * The vertex on which the edge ends. */ public readonly tail: Vertex, /** * Indicates what kind of edges this is and what the edges does/represents. * For instance, if the edge represents a field, the `transition` will be a `FieldCollection` transition * and will link to the definition of the field it represents. * * @see Transition */ public readonly transition: Transition, /** * Optional conditions on an edge. * * Conditions are a select of selections (in the graphQL sense) that the traversal of a query graph * needs to "collect" (traverse edges with transitions corresponding to those selections) in order * to be able to collect that edge. * * Conditions are primarily used for edges corresponding to @key, in which case they correspond * to the fields composing the key. In other words, for a key edges, conditions basically represents * the fact that you need the key to be able to use a key edge. * * Outside of keys, @requires also rely on conditions. */ conditions?: SelectionSet, ) { this._conditions = conditions; } get conditions(): SelectionSet | undefined { return this._conditions; } isEdgeForField(name: string): boolean { return this.transition.kind === 'FieldCollection' && this.transition.definition.name === name; } matchesSupergraphTransition(supergraph: Schema, otherTransition: Transition): boolean { const transition = this.transition; switch (transition.kind) { case 'FieldCollection': if (otherTransition.kind === 'FieldCollection') { // isStructuralFieldSubtype relies on being about to check subtypes. And when comparing types, we // want to know if types are subtypes 'in the supergraph'. return isStructuralFieldSubtype( transition.definition, otherTransition.definition, ALL_SUBTYPING_RULES, // We can safely use all rules, even if merge didn't. It just mean some rules will never be needed. (union, maybeMember) => (supergraph.type(union.name)! as UnionType).hasTypeMember(maybeMember.name), (maybeImplementer, itf) => (supergraph.type(maybeImplementer.name)! as (ObjectType | InterfaceType)).implementsInterface(itf) ); } else { return false; } case 'DownCast': return otherTransition.kind === 'DownCast' && transition.castedType.name === otherTransition.castedType.name; default: return transition.kind === otherTransition.kind; } } label(): string { if (this.transition instanceof SubgraphEnteringTransition && !this._conditions) { return ""; } return this._conditions ? `${this._conditions} ⊢ ${this.transition}` : this.transition.toString(); } withNewHead(newHead: Vertex): Edge { return new Edge( this.index, newHead, this.tail, this.transition, this._conditions ); } addToConditions(newConditions: SelectionSet) { if (!this._conditions) { this._conditions = new SelectionSet(this.head.type as CompositeType); } this._conditions.mergeIn(newConditions); } toString(): string { return `${this.head} -> ${this.tail} (${this.label()})`; } } /** * An immutable directed graph data structure (built of vertices and edges) that is layered over one or multiple * graphQL schema, that aims to facilitate reasoning about queries expressed on the underlying schema. * * On top of its set of vertices and edges, a query graph exposes: * - its set of "sources": pointers to the graphQL schema on which the query graph was built. * - a set of distinguished vertices called "root" vertices. A query graph has at most one root * vertex per `SchemaRootKind`, and those vertices are usually entry points for traversals of * a query graph. * * In practice, the code builds 2 "kind" of query graphs: * 1. a supergraph query graph, which is built on top of a supergraph API schema (@see buildGraph()), * and is built to reason about user queries (made on the supergraph API). This supergraph query * graph is used to validate composition. * 2. a "federated" query graph, which is a single graph built on top of a) a number of subgraph * API schema and b) the additional federation directives on those subgraphs (@see buildFederatedQueryGraph()). * This query graph is used both for validating composition and for query planning. * * Note that this class handles both cases, but a "supergraph query graph" will, by construction, have * a few more invariants than a "federated query graph". Including (but not necessarily limited to): * - edges in a super graph query graph will never have `conditions` or 'key' edges (edges with a `KeyResolution` edges). * - supergraph query graphs will have a single value in `sources` (the supergraph schema). * * Also note that as query graphs are about reasoning about queries over schema, they only contain vertices * that points to "reachable" types (reachable from any kind of operations). */ export class QueryGraph { /** * Creates a new query graph. * * This isn't meant to be be called directly outside of `GraphBuilder.build`. */ constructor( /** A name to identify the graph. Mostly for pretty-printing/debugging purpose. */ readonly name: string, /** The vertices of the query graph. The index of each vertex in the array will be the value of its `Vertex.index` value. */ private readonly vertices: Vertex[], /** * For each vertex, the edges that originate from that array. This array has the same length as `vertices` and `adjacencies[i]` * is an array of all the edges starting at vertices[i]. */ private readonly adjacencies: Edge[][], /** * A map that associate type names of the underlying schema on which this query graph was built to each of the vertex * (vertex index) that points to a type of that name. Note that in a "supergraph query graph", each type name will only * map to a single vertex, */ private readonly typesToVertices: MultiMap<string, number>, /** The set of distinguished root vertices (pointers to vertices in `vertices`), keyed by their kind. */ private readonly rootVertices: MapWithCachedArrays<SchemaRootKind, RootVertex>, /** * The sources on which the query graph was built, that is a set (which can be of size 1) of graphQL schema keyed by * the name identifying them. Note that the `source` string in the `Vertex` of a query graph is guaranteed to be * valid key in this map. */ readonly sources: ReadonlyMap<string, Schema> ) { } /** The number of vertices in this query graph. */ verticesCount(): number { return this.vertices.length; } /** The number of edges in this query graph. */ edgesCount(): number { // We could count edges as we add them and pass it to the ctor. For now though, it's not meant to be // on a hot path, so recomputing is probably fine. return this.adjacencies.reduce((acc, v) => acc + v.length, 0); } /** * The set of `SchemaRootKind` for which this query graph has a root vertex (for * which `root(SchemaRootKind)` will _not_ return `undefined`). */ rootKinds(): readonly SchemaRootKind[] { return this.rootVertices.keys(); } /** * The set of root vertices in this query graph. */ roots(): readonly RootVertex[] { return this.rootVertices.values(); } /** * The root vertex corresponding to the provided root kind, if this query graph has one. * * @param kind - the root kind for which to get the root vertex. * @returns the root vertex for `kind` if this query graph has one. */ root(kind: SchemaRootKind): RootVertex | undefined { return this.rootVertices.get(kind); } /** * The edges out of the provided vertex. * * @param vertex - the vertex for which to return out edges. This method _assumes_ that * the provided vertex is a vertex of this query graph (and its behavior is undefined * if it isn't). * @returns the list of all the edges out of this vertex. */ outEdges(vertex: Vertex): readonly Edge[] { return this.adjacencies[vertex.index]; } /** * The edge out of the provided vertex at the provided (edge) index. * * @param vertex - the vertex for which to return the out edge. This method _assumes_ that * the provided vertex is a vertex of this query graph (and its behavior is undefined * if it isn't). * @param edgeIndex - the edge index (relative to `vertex`, see `Edge.index`) to retrieve. * @returns the `edgeIndex`^th edge out of `vertex`, if such edges exists. */ outEdge(vertex: Vertex, edgeIndex: number): Edge | undefined { return this.adjacencies[vertex.index][edgeIndex]; } /** * Whether the provided vertex is a terminal one (has no out edges). * * @param vertex - the vertex to check. * @returns whether the provided vertex is terminal. */ isTerminal(vertex: Vertex): boolean { return this.outEdges(vertex).length == 0; } /** * The set of vertices whose associated type (see `Vertex.type`) is of type `typeName`. */ verticesForType(typeName: string): Vertex[] { const indexes = this.typesToVertices.get(typeName); return indexes == undefined ? [] : indexes.map(i => this.vertices[i]); } } /** * A utility class that allows to associate state to the vertices and/or edges of a query graph. * * @param VertexState - the type of the state associated to vertices. * @param EdgeState - the type of the state associated to edges. Defaults to `undefined`, which * means that state is only associated to vertices. */ export class QueryGraphState<VertexState, EdgeState = undefined> { // Store some "user" state for each vertex (accessed by index) private readonly verticesStates: (VertexState | undefined)[]; private readonly adjacenciesStates: (EdgeState | undefined)[][]; /** * Creates a new `QueryGraphState` to associate state to the vertices and/or edges of `graph`. */ constructor(readonly graph: QueryGraph) { this.verticesStates = new Array(graph.verticesCount()); this.adjacenciesStates = new Array(graph.verticesCount()); } /** * Associates the provided state to the provided vertex. * * @param vertex - the vertex to which state should be associated. This method _assumes_ * that the provided vertex is a vertex of the query graph against which this * `QueryGraphState` was created (and its behavior is undefined if it isn't). * @param state - the state/value to associate to `vertex`. */ setVertexState(vertex: Vertex, state: VertexState) { this.verticesStates[vertex.index] = state; } /** * Removes the state associated to the provided vertex (if any is). * * @param vertex - the vertex for which state should be removed. This method _assumes_ * that the provided vertex is a vertex of the query graph against which this * `QueryGraphState` was created (and its behavior is undefined if it isn't). */ removeVertexState(vertex: Vertex) { this.verticesStates[vertex.index] = undefined; } /** * Retrieves the state associated to the provided vertex (if any is). * * @param vertex - the vertex for which state should be retrieved. This method _assumes_ * that the provided vertex is a vertex of the query graph against which this * `QueryGraphState` was created (and its behavior is undefined if it isn't). * @return the state associated to `vertex`, if any. */ getVertexState(vertex: Vertex): VertexState | undefined { return this.verticesStates[vertex.index]; } /** * Associates the provided state to the provided edge. * * @param edge - the edge to which state should be associated. This method _assumes_ * that the provided edge is an edge of the query graph against which this * `QueryGraphState` was created (and its behavior is undefined if it isn't). * @param state - the state/value to associate to `edge`. */ setEdgeState(edge: Edge, state: EdgeState) { if (!this.adjacenciesStates[edge.head.index]) { this.adjacenciesStates[edge.head.index] = new Array(this.graph.outEdges(edge.head).length); } this.adjacenciesStates[edge.head.index][edge.index] = state; } /** * Removes the state associated to the provided edge (if any is). * * @param edge - the edge for which state should be removed. This method _assumes_ * that the provided edge is an edge of the query graph against which this * `QueryGraphState` was created (and its behavior is undefined if it isn't). */ removeEdgeState(edge: Edge) { this.adjacenciesStates[edge.head.index][edge.index] = undefined; } /** * Retrieves the state associated to the provided edge (if any is). * * @param edge - the edge for which state should be retrieved. This method _assumes_ * that the provided vertex is an edge of the query graph against which this * `QueryGraphState` was created (and its behavior is undefined if it isn't). * @return the state associated to `edge`, if any. */ getEdgeState(edge: Edge): EdgeState | undefined { const forEdge = this.adjacenciesStates[edge.head.index]; return forEdge ? forEdge[edge.index] : undefined; } toDebugString( vertexMapper: (s: VertexState) => string, edgeMapper: (e: EdgeState) => string ): string { const vs = this.verticesStates.map((state, idx) => ` ${idx}: ${!state ? "<null>" : vertexMapper(state)}`).join("\n"); const es = this.adjacenciesStates.map((adj, vIdx) => adj.map((state, eIdx) => ` ${vIdx}[${eIdx}]: ${!state ? "<null>" : edgeMapper(state)}`).join("\n")).join("\n"); return `vertices = {${vs}\n}, edges = {${es}\n}`; } } /** * Builds the query graph corresponding to the provided schema. * * Note that this method and mainly exported for the sake of testing but should rarely, if * ever, be used otherwise. Instead use either `buildSupergraphAPIQueryGraph` or * `buildFederatedQueryGraph` which are more explicit. * * @param name - the name to use for the created graph and as "source" name for the schema. * @param schema - the schema for which to build the query graph. * @returns the query graph corresponding to `schema` "API" (in the sense that no federation * directives are taken into account by this method in the building of the query graph). */ export function buildQueryGraph(name: string, schema: Schema): QueryGraph { return buildGraphInternal(name, schema, false); } function buildGraphInternal(name: string, schema: Schema, addAdditionalAbstractTypeEdges: boolean, supergraphSchema?: Schema): QueryGraph { const builder = new GraphBuilderFromSchema(name, schema, supergraphSchema); for (const rootType of schema.schemaDefinition.roots()) { builder.addRecursivelyFromRoot(rootType.rootKind, rootType.type); } if (addAdditionalAbstractTypeEdges) { builder.addAdditionalAbstractTypeEdges(); } return builder.build(); } /** * Builds a "supergraph API" query graph based on the provided supergraph schema. * * A "supergraph API" query graph is one that is used to reason about queries against said * supergraph API, but @see QueryGraph for more details. * * @param supergraph - the schema of the supergraph for which to build the query graph. * The provided schema should generally be a "supergraph" as generated by composition merging. * Note however that the query graph built by this method is only based on the supergraph * API and doesn't rely on the join spec directives, so it is valid to also directly * pass a schema that directly corresponds to the supergraph API. * @returns the built query graph. */ export function buildSupergraphAPIQueryGraph(supergraph: Schema): QueryGraph { return buildQueryGraph("supergraph", supergraph); } /** * Builds a "federated" query graph based on the provided supergraph schema. * * A "federated" query graph is one that is used to reason about queries made by a * gateway/router against a set of federated subgraph services. * * @see QueryGraph * * @param supergraph - the schema of the supergraph for which to build the query graph. * The provided schema _must_ be a "supergraph" as generated by composition merging, * one that includes join spec directives in particular. * @param forQueryPlanning - whether the build query graph is built for query planning (if * so, it will included some additional edges that don't impact validation but allow * to generate more efficient query plans). * @returns the built federated query graph. */ export function buildFederatedQueryGraph(supergraph: Schema, forQueryPlanning: boolean): QueryGraph { const subgraphs = extractSubgraphsFromSupergraph(supergraph); const graphs = []; for (const subgraph of subgraphs) { graphs.push(buildGraphInternal(subgraph.name, subgraph.schema, forQueryPlanning, supergraph)); } return federateSubgraphs(graphs); } function federatedProperties(subgraphs: QueryGraph[]) : [number, Set<SchemaRootKind>, Schema[]] { let vertices = 0; const rootKinds = new Set<SchemaRootKind>(); const schemas: Schema[] = []; for (const subgraph of subgraphs) { vertices += subgraph.verticesCount(); subgraph.rootKinds().forEach(k => rootKinds.add(k)); assert(subgraph.sources.size === 1, () => `Subgraphs should only have one sources, got ${subgraph.sources.size} ([${mapKeys(subgraph.sources).join(', ')}])`); schemas.push(firstOf(subgraph.sources.values())!); } return [vertices + rootKinds.size, rootKinds, schemas]; } function federateSubgraphs(subgraphs: QueryGraph[]): QueryGraph { const [verticesCount, rootKinds, schemas] = federatedProperties(subgraphs); const builder = new GraphBuilder(verticesCount); rootKinds.forEach(k => builder.createRootVertex( k, new ObjectType(federatedGraphRootTypeName(k)), FEDERATED_GRAPH_ROOT_SOURCE, FEDERATED_GRAPH_ROOT_SCHEMA )); // We first add all the vertices and edges from the subgraphs const copyPointers: SubgraphCopyPointer[] = new Array(subgraphs.length); for (const [i, subgraph] of subgraphs.entries()) { copyPointers[i] = builder.copyGraph(subgraph); } // We then add the edges from supergraph roots to the subgraph ones. // Also, for each root kind, we also add edges from the corresponding root type of each subgraph to the root type of other subgraphs. // This essentially encode the fact that if a field return a root type, we can always query any subgraph from that point. for (const [i, subgraph] of subgraphs.entries()) { const copyPointer = copyPointers[i]; for (const rootKind of subgraph.rootKinds()) { const rootVertex = copyPointer.copiedVertex(subgraph.root(rootKind)!); builder.addEdge(builder.root(rootKind)!, rootVertex, subgraphEnteringTransition) for (const [j, otherSubgraph] of subgraphs.entries()) { if (i === j) { continue; } const otherRootVertex = otherSubgraph.root(rootKind); if (otherRootVertex) { const otherCopyPointer = copyPointers[j]; builder.addEdge(rootVertex, otherCopyPointer.copiedVertex(otherRootVertex), new RootTypeResolution(rootKind)); } } } } // Then we add/update edges for @key and @requires. We do @provides in a second step because its handling requires // copying vertex and their edges, and it's easier to reason about this if we know all keys have already been created. for (const [i, subgraph] of subgraphs.entries()) { const subgraphSchema = schemas[i]; const keyDirective = federationBuiltIns.keyDirective(subgraphSchema); const requireDirective = federationBuiltIns.requiresDirective(subgraphSchema); simpleTraversal( subgraph, v => { const type = v.type; for (const keyApplication of type.appliedDirectivesOf(keyDirective)) { // The @key directive creates an edge from every other subgraphs (having that type) // to the current subgraph. In other words, the fact this subgraph has a @key means // that the service of the current subgraph can be queried for the entity (through // _entities) as long as "the other side" can provide the proper field values. // Note that we only require that "the other side" can gather the key fields (through // the path conditions; note that it's possible those conditions are never satisfiable), // but don't care that it defines the same key, because it's not a technical // requirement (and while we probably don't want to allow in general a type to be an // entity in some subgraphs but not other, this is not the place to impose that // restriction, and this may be useful at least temporarily to allow convert a type to // an entity). assert(isInterfaceType(type) || isObjectType(type), () => `Invalid "@key" application on non Object || Interface type "${type}"`); const conditions = parseFieldSetArgument(type, keyApplication); for (const [j, otherSubgraph] of subgraphs.entries()) { if (i == j) { continue; } const otherVertices = otherSubgraph.verticesForType(type.name); if (otherVertices.length == 0) { continue; } // Note that later, when we've handled @provides, this might not be true anymore a provide may create copy of a // certain type. But for now, it's true. assert( otherVertices.length == 1, () => `Subgraph ${j} should have a single vertex for type ${type.name} but got ${otherVertices.length}: ${inspect(otherVertices)}`); // The edge goes from the otherSubgraph to the current one. const head = copyPointers[j].copiedVertex(otherVertices[0]); const tail = copyPointers[i].copiedVertex(v); builder.addEdge(head, tail, new KeyResolution(), conditions); } } }, e => { // Handling @requires if (e.transition.kind === 'FieldCollection') { const type = e.head.type; const field = e.transition.definition; assert(isCompositeType(type), () => `Non composite type "${type}" should not have field collection edge ${e}`); for (const requiresApplication of field.appliedDirectivesOf(requireDirective)) { const conditions = parseFieldSetArgument(type, requiresApplication); const head = copyPointers[i].copiedVertex(e.head); // We rely on the fact that the edge indexes will be the same in the copied builder. But there is no real reason for // this to not be the case at this point so... const copiedEdge = builder.edge(head, e.index); copiedEdge.addToConditions(conditions); } } return true; // Always traverse edges } ); } // Now we handle @provides for (const [i, subgraph] of subgraphs.entries()) { const subgraphSchema = schemas[i]; const providesDirective = federationBuiltIns.providesDirective(subgraphSchema); simpleTraversal( subgraph, _ => undefined, e => { // Handling @provides if (e.transition.kind === 'FieldCollection') { const type = e.head.type; const field = e.transition.definition; assert(isCompositeType(type), () => `Non composite type "${type}" should not have field collection edge ${e}`); for (const providesApplication of field.appliedDirectivesOf(providesDirective)) { const fieldType = baseType(field.type!); assert(isCompositeType(fieldType), () => `Invalid @provide on field "${field}" whose type "${fieldType}" is not a composite type`) const provided = parseFieldSetArgument(fieldType, providesApplication); const head = copyPointers[i].copiedVertex(e.head); const tail = copyPointers[i].copiedVertex(e.tail); // We rely on the fact that the edge indexes will be the same in the copied builder. But there is no real reason for // this to not be the case at this point so... const copiedEdge = builder.edge(head, e.index); // We make a copy of the `fieldType` vertex (with all the same edges), and we change this particular edge to point to the // new copy. From that, we can add all the provides edges to the copy. const copiedTail = builder.makeCopy(tail); builder.updateEdgeTail(copiedEdge, copiedTail); addProvidesEdges(subgraphSchema, builder, copiedTail, provided); } } return true; // Always traverse edges } ); } return builder.build(FEDERATED_GRAPH_ROOT_SOURCE); } function addProvidesEdges(schema: Schema, builder: GraphBuilder, from: Vertex, provided: SelectionSet) { const stack: [Vertex, SelectionSet][] = [[from, provided]]; const source = from.source; while (stack.length > 0) { const [v, selectionSet] = stack.pop()!; // We reverse the selections to cancel the reversing that the stack does. for (const selection of selectionSet.selections(true)) { const element = selection.element(); if (element.kind == 'Field') { const fieldDef = element.definition; const existingEdge = builder.edges(v).find(e => e.transition.kind === 'FieldCollection' && e.transition.definition.name === fieldDef.name); if (existingEdge) { // If this is a leaf field, then we don't really have anything to do. Otherwise, we need to copy // the tail and continue propagating the provides from there. if (selection.selectionSet) { const copiedTail = builder.makeCopy(existingEdge.tail); builder.updateEdgeTail(existingEdge, copiedTail); stack.push([copiedTail, selection.selectionSet]); } } else { // There is no exisiting edges, which means that it's an edge added by the provide. // We find the existing vertex it leads to, if it exists and create a new one otherwise. const fieldType = baseType(fieldDef.type!); const existingTail = builder.verticesForType(fieldType.name).find(v => v.source === source); const newTail = existingTail ? existingTail : builder.createNewVertex(fieldType, v.source, schema); // If the field is a leaf, then just create the new edge and we're done. Othewise, we // should copy the vertex (unless we just created it), add the edge and continue. if (selection.selectionSet) { const copiedTail = existingTail ? builder.makeCopy(existingTail) : newTail; builder.addEdge(v, copiedTail, new FieldCollection(fieldDef, true)); stack.push([copiedTail, selection.selectionSet]); } else { builder.addEdge(v, newTail, new FieldCollection(fieldDef, true)); } } } else { const typeCondition = element.typeCondition; if (typeCondition) { const existingEdge = builder.edges(v).find(e => e.transition.kind === 'DownCast' && e.transition.castedType.name === typeCondition.name); // We always should have an edge: otherwise it would mean we list a type condition for a type that isn't in the subgraph, but the // @provides shouldn't have validated in the first place (another way to put it is, contrary to fields, there is no way currently // to mark a full type as @external). assert(existingEdge, () => `Shouldn't have ${selection} with no corresponding edge on ${v}`); const copiedTail = builder.makeCopy(existingEdge.tail); builder.updateEdgeTail(existingEdge, copiedTail); stack.push([copiedTail, selection.selectionSet!]); } else { // Essentially ignore the condition, it's useless stack.push([v, selection.selectionSet!]); } } } } } interface SubgraphCopyPointer { copiedVertex(original: Vertex): Vertex; } /** * Temporary abstraction used to build a query graph. */ class GraphBuilder { private readonly vertices: Vertex[]; private nextIndex: number = 0; private readonly adjacencies: Edge[][]; private readonly typesToVertices: MultiMap<string, number> = new MultiMap(); private readonly rootVertices: MapWithCachedArrays<SchemaRootKind, RootVertex> = new MapWithCachedArrays(); private readonly sources: Map<string, Schema> = new Map(); constructor(verticesCount?: number) { this.vertices = verticesCount ? new Array(verticesCount) : []; this.adjacencies = verticesCount ? new Array(verticesCount) : []; } verticesForType(typeName: string): Vertex[] { const indexes = this.typesToVertices.get(typeName); return indexes == undefined ? [] : indexes.map(i => this.vertices[i]); } root(kind: SchemaRootKind): Vertex | undefined { return this.rootVertices.get(kind); } addEdge(head: Vertex, tail: Vertex, transition: Transition, conditions?: SelectionSet) { const edges = this.adjacencies[head.index]; const edge = new Edge(edges.length, head, tail, transition, conditions); edges.push(edge); } createNewVertex(type: NamedType, source: string, schema: Schema, index?: number): Vertex { if (!index) { index = this.nextIndex++; } const vertex = new Vertex(index, type, source); const previous = this.vertices[index]; assert(!previous, () => `Overriding existing vertex ${previous} with ${vertex}`); this.vertices[index] = vertex; this.typesToVertices.add(type.name, index); this.adjacencies[index] = []; if (!this.sources.has(source)) { this.sources.set(source, schema); } return vertex; } createRootVertex(kind: SchemaRootKind, type: NamedType, source: string, schema: Schema) { const vertex = this.createNewVertex(type, source, schema); assert(!this.rootVertices.has(kind), () => `Root vertex for ${kind} (${this.rootVertices.get(kind)}) already exists: cannot replace by ${vertex}`); this.setAsRoot(kind, vertex.index); } setAsRoot(kind: SchemaRootKind, index: number) { const vertex = this.vertices[index]; assert(vertex, () => `Cannot set non-existing vertex at index ${index} as root ${kind}`); const rootVertex = toRootVertex(vertex, kind); this.vertices[vertex.index] = rootVertex; this.rootVertices.set(kind, rootVertex); const rootEdges = this.adjacencies[vertex.index]; for (let i = 0; i < rootEdges.length; i++) { rootEdges[i] = rootEdges[i].withNewHead(rootVertex); } } copyGraph(graph: QueryGraph): SubgraphCopyPointer { const offset = this.nextIndex; simpleTraversal( graph, v => { this.getOrCopyVertex(v, offset, graph); }, e => { const newHead = this.getOrCopyVertex(e.head, offset, graph); const newTail = this.getOrCopyVertex(e.tail, offset, graph); this.addEdge(newHead, newTail, e.transition, e.conditions); return true; // Always traverse edges } ); this.nextIndex += graph.verticesCount(); const that = this; return { copiedVertex(original: Vertex): Vertex { const vertex = that.vertices[original.index + offset]; assert(vertex, () => `Vertex ${original} has no copy for offset ${offset}`); return vertex; } }; } vertex(index: number): Vertex { return this.vertices[index]; } edge(head: Vertex, index: number): Edge { return this.adjacencies[head.index][index]; } edges(head: Vertex): Edge[] { return this.adjacencies[head.index]; } /** * Creates a new vertex that is a full copy of the provided one, including having the same out-edge, but with no incoming edges. * * @param vertex - the vertex to copy. * @returns the newly created copy. */ makeCopy(vertex: Vertex): Vertex { const newVertex = this.createNewVertex(vertex.type, vertex.source, this.sources.get(vertex.source)!); for (const edge of this.adjacencies[vertex.index]) { this.addEdge(newVertex, edge.tail, edge.transition, edge.conditions); } return newVertex; } /** * Replaces the provided edge by an exact copy except for the tail that is said to the provide `newTail` vertex. * * @param edge - the edge to replace. * @param newTail - the tail to change in `edge`. * @returns the newly created edge that, as of this method returning, replaces `edge`. */ updateEdgeTail(edge: Edge, newTail: Vertex): Edge { const newEdge = new Edge(edge.index, edge.head, newTail, edge.transition, edge.conditions); this.adjacencies[edge.head.index][edge.index] = newEdge; return newEdge; } private getOrCopyVertex(toCopy: Vertex, indexOffset: number, graph: QueryGraph): Vertex { const index = toCopy.index + indexOffset; let v = this.vertices[index]; if (!v) { v = this.createNewVertex(toCopy.type, toCopy.source, graph.sources.get(toCopy.source)!, index); } return v; } build(name: string): QueryGraph { return new QueryGraph( name, this.vertices, this.adjacencies, this.typesToVertices, this.rootVertices, this.sources); } } /** * Specialization of `GraphBuilder` for building the parts of a query graph that correspond * to a schema API (meaning that it helps building the vertices and edges corresponding to a * schema API, but does not handle vertices and edges related to federation). */ class GraphBuilderFromSchema extends GraphBuilder { private readonly isFederatedSubgraph: boolean; private readonly forceTypeExplosion: boolean; constructor( private readonly name: string, private readonly schema: Schema, private readonly supergraphSchema?: Schema ) { super(); this.isFederatedSubgraph = isFederationSubgraphSchema(schema); assert(!this.isFederatedSubgraph || supergraphSchema, `Missing supergraph schema for building the federated subgraph graph`); // The join spec 0.1 used by "fed1" does not preserve the information on where (in which subgraphs) // an interface is defined, so we cannot ever safely avoid type explosion. this.forceTypeExplosion = supergraphSchema !== undefined && isFed1Supergraph(supergraphSchema); } /** * Adds a vertex for the provided root object type (marking that vertex as a root vertex for the * provided `kind`) and recursively descend into the type definition to adds the related vertices * and edges. * * In other words, calling this method on, say, the `Query` type of a schema will add vertices * and edges for all the type reachable from that `Query` type. */ addRecursivelyFromRoot(kind: SchemaRootKind, root: ObjectType) { this.setAsRoot(kind, this.addTypeRecursively(root).index); } /** * Adds in a vertex for the provided type in the in-building query graph, and recursively * adds edges and vertices corresponding to the type definition (so for object types, it * will add edges for each fields and recursively add vertices for each field type, etc...). */ private addTypeRecursively(type: Type): Vertex { const namedType = baseType(type); const existing = this.verticesForType(namedType.name); if (existing.length > 0) { assert(existing.length == 1, () => `Only one vertex should have been created for type ${namedType.name}, got ${existing.length}: ${inspect(this)}`); return existing[0]; } const vertex = this.createNewVertex(namedType, this.name, this.schema); if (isObjectType(namedType)) { this.addObjectTypeEdges(namedType, vertex); } else if (isInterfaceType(namedType)) { // For interfaces, we generally don't add direct edges for their fields. Because in general, the subgraph where a particular // field can be fetched from may depend on the runtime implementation. However, if the subgraph we're currently including // "provides" a particular interface field locally *for all the supergraph interfaces implementations* (in other words, we // know we can always ask the field to that subgraph directly on the interface and will never miss anything), then we can // add a direct edge to the field for the interface in that subgraph (which avoids unnecessary type exploding in practice). if (this.isFederatedSubgraph && !this.forceTypeExplosion) { this.maybeAddInterfaceFieldsEdges(namedType, vertex); } this.addAbstractTypeEdges(namedType, vertex); } else if (isUnionType(namedType)) { // Adding the special-case __typename edge for union. this.addEdgeForField(namedType.typenameField()!, vertex); this.addAbstractTypeEdges(namedType, vertex); } // Any other case (scalar or enum; inputs at not possible here) is terminal and has no edges to // consider. return vertex; } private addObjectTypeEdges(type: ObjectType, head: Vertex) { // We do want all fields, including most built-in. For instance, it's perfectly valid to query __typename manually, so we want // to have an edge for it. Also, the fact we handle the _entities field ensure that all entities are part of the graph, // even if they are not reachable by any other user operations. // We do skip introspection fields however. for (const field of type.allFields()) { // Field marked @external only exists to ensure subgraphs schema are valid graphQL, but they don't really exist as far as federation goes. if (field.isSchemaIntrospectionField() || field.hasAppliedDirective(externalDirectiveName)) { continue; } this.addEdgeForField(field, head); } } private addEdgeForField(field: FieldDefinition<any>, head: Vertex) { const tail = this.addTypeRecursively(field.type!); this.addEdge(head, tail, new FieldCollection(field)); } private isDirectlyProvidedByType(type: ObjectType, fieldName: string) { const field = type.field(fieldName); // The field is directly provided is: // 1) the type does have it. // 2) it is not external. // 3) it does not have a @require (essentially, this method is called on type implementations of an interface // to decide if we can avoid type-explosion, but if the field has a @require on an implementation, then we // need to type-explode to make we handle that @require). return field && !field.hasAppliedDirective(externalDirectiveName) && !field.hasAppliedDirective(requiresDirectiveName); } private maybeAddInterfaceFieldsEdges(type: InterfaceType, head: Vertex) { assert(this.supergraphSchema, 'Missing supergraph schema when building a subgraph'); const supergraphType = this.supergraphSchema.type(type.name); // In theory, the interface might have been marked inaccessible and not be in the supergraph. If that's the case, // we just don't add direct edges at all (adding interface edges is an optimization and if the interface is inaccessible, it // probably doesn't play any role in query planning anyway, so it doesn't matter). if (!supergraphType) { return; } const supergraphRuntimeTypes = (supergraphType as InterfaceType).possibleRuntimeTypes().map(t => t.name); // Note that it's possible that the current subgraph does not even know some of the possible runtime types of the supergraph. // But as edges to interfaces can only come from the current subgraph, it does mean that whatever field led to this // interface was resolved in this subgraph and can never return one of those unknown runtime types. So we can ignore them. // TODO: We *must* revisit this once we add @key for interfaces as it will invalidate the "edges to interfaces can only // come from the current subgraph". Most likely, _if_ an interface has a key, then we should return early from this // function (add no field edges at all) if subgraph don't know of at least one implementation. const localRuntimeTypes = supergraphRuntimeTypes.map(t => this.schema.type(t) as ObjectType).filter(t => t !== undefined); // Same as for objects, we want `allFields` so we capture __typename (which will never be external and always provided // by all local runtime types, so will always have an edge added, which we want). for (const field of type.allFields()) { // To include the field, it must not be external himself, and it must be provided on every of the runtime types if (field.hasAppliedDirective(externalDirectiveName) || localRuntimeTypes.some(t => !this.isDirectlyProvidedByType(t, field.name))) { continue; } this.addEdgeForField(field, head); } } private addAbstractTypeEdges(type: InterfaceType | UnionType, head: Vertex) { const implementations = isInterfaceType(type) ? type.possibleRuntimeTypes() : type.types(); for (const implementationType of implementations) { const tail = this.addTypeRecursively(implementationType); this.addEdge(head, tail, new DownCast(type, implementationType)); } } /* * We've added edges that avoid type-explosion _directly_ from an interface, but it means that so far we * always type-explode unions to all their implementation types, and always type-explode when we go * through 2 unrelated interfaces. For instance, say we have * ``` * type Query { * i1: I1 * i2: I2 * u: U * } * * interface I1 { * x: Int * } * * interface I2 { * y: Int * } * * type A implements I1 & I2 { * x: Int * y: Int * } * * type B implements I1 & I2 { * x: Int * y: Int * } * * union U = A | B * ``` * If we query: * ``` * { * u { * ... on I1 { * x * } * } * } * ``` * the we currently have no edge between `U` and `I1` whatsoever, so query planning would have * to type-explode `U` even though that's not necessary (assuming everything is in the same * subgraph, we'd want to send the query "as-is"). * Same thing for: * ``` * { * i1 { * x * ... on U2 { * y * } * } * } * ``` * due to not having edges from `I1` to `I2` (granted, in that example, type-exploding is not all * that worth, but it gets worth with more implementations/fields). * * And so this method is about adding such edges. Essentially, every time 2 abstract types have * an intersection of runtime types > 1, we add an edge. * * Do not that in practice we only add those edges when we build a query graph for query planning * purposes, because not type-exploding is only an optimization but type-exploding will always "work" * and for composition validation, we don't care about being optimal, while limiting edges make * validation faster by limiting the choices to explore. Also, query planning is careful, as * it walk those edges, to compute the actual possible runtime types we could have to avoid * later type-exploding in impossible runtime types. */ addAdditionalAbstractTypeEdges() { // For each abstract type in the schema, it's runtime types. const abstractTypesWithTheirRuntimeTypes: [AbstractType, readonly ObjectType[]][] = []; for (const type of this.schema.types()) { if (isAbstractType(type)) { abstractTypesWithTheirRuntimeTypes.push([type, possibleRuntimeTypes(type)]); } } // Check every pair of abstract type that intersect on at least 2 runtime types to see if have // edges to add. Note that in practice, we only care about 'Union -> Interface' and 'Interface -> Interface' for (let i = 0; i < abstractTypesWithTheirRuntimeTypes.length - 1; i++) { const [t1, t1Runtimes] = abstractTypesWithTheirRuntimeTypes[i]; // Note that in general, t1 is already part of the graph `addTypeRecursively` don't really add anything, it // just return the existing vertex. That said, if t1 is returned by no field (at least no field reachable from // a root type), the type will not be part of the graph. And in that case, we do add it. And it's actually // possible that we don't create any edge to that created vertex, so we may be creating a disconnected subset // of the graph, a part that is not reachable from any root. It's not optimal, but it's a bit hard to avoid // in the first place (we could also try to purge such subset after this method, but it's probably not worth // it in general) and it's not a big deal: it will just a bit more memory than necessary, and it's probably // pretty rare in the first place. const t1Vertex = this.addTypeRecursively(t1); for (let j = i; j < abstractTypesWithTheirRuntimeTypes.length; j++) { const [t2, t2Runtimes] = abstractTypesWithTheirRuntimeTypes[j]; // We ignore the pair if both are interfaces and one implements the other. We'll already have appropriate // edges if that's the case. if (isInterfaceType(t1) && isInterfaceType(t2) && (t1.implementsInterface(t2) || t2.implementsInterface(t1))) { continue; } // Note that as everything comes from the same subgraph schema, using reference equality is fine. const intersecting = t1Runtimes.filter(o1 => t2Runtimes.includes(o1)); if (intersecting.length >= 2) { // Same remark as for t1 above. const t2Vertex = this.addTypeRecursively(t2); this.addEdge(t1Vertex, t2Vertex, new DownCast(t1, t2)); this.addEdge(t2Vertex, t1Vertex, new DownCast(t2, t1)); } } } } build(): QueryGraph { return super.build(this.name); } } /** * Performs a simple traversal of a query graph that _ignores_ edge conditions. * * Note that the order of the traversal shouldn't be relied on strongly, only that * the provided `onVertex` and `onEdges` will called (exactly) once for every vertices * and edges in the query graph. * * That said, in practice, this method does `n` traversals, one from each root vertex in the * provided query graph (so in practice, `0 < n <= 3`) and each traversal happens to be a * depth first traversal (one that stops as soon as it encounters a vertex previously seen). * * @param graph - the query graph to traverse. * @param onVertex - a function called on each vertex traversed the first time it is traversed. * @param onEdges - a function called on each edges traversed the first time it is traversed. * When this function is called for an edge, it is guaranteed that `onVertex` has previously * been called on the edge's head vertex (there is no guarantee on the tail vertex in that * `onVertex` may or may not have been called for it). */ export function simpleTraversal( graph: QueryGraph, onVertex: (v: Vertex) => void, onEdges: (e: Edge) => boolean ) { // A marked vertex (accessed by its index) is one that has already been traversed. const marked: boolean[] = new Array(graph.verticesCount()); // The stack contains vertices that haven't been traversed yet but need to. const stack: Vertex[] = []; const maybeAdd = function(vertex: Vertex) { if (!marked[vertex.index]) { stack.push(vertex); marked[vertex.index] = true; } } graph.roots().forEach(maybeAdd); while (stack.length > 0) { const vertex = stack.pop()!; onVertex(vertex); for (const edge of graph.outEdges(vertex)) { const shouldTraverse = onEdges(edge); if (shouldTraverse) { maybeAdd(edge.tail); } } } }
the_stack
import rule, { RULE_NAME } from '../../../lib/rules/prefer-explicit-assert'; import { ALL_QUERIES_METHODS } from '../../../lib/utils'; import { createRuleTester } from '../test-utils'; const ruleTester = createRuleTester(); const COMBINED_QUERIES_METHODS = [...ALL_QUERIES_METHODS, 'ByIcon']; ruleTester.run(RULE_NAME, rule, { valid: [ ...COMBINED_QUERIES_METHODS.map((queryMethod) => ({ code: `get${queryMethod}('Hello')`, settings: { 'testing-library/utils-module': 'test-utils', }, })), ...COMBINED_QUERIES_METHODS.map((queryMethod) => ({ code: `get${queryMethod}`, })), ...COMBINED_QUERIES_METHODS.map((queryMethod) => ({ code: ` const utils = render() utils.get${queryMethod} `, })), ...COMBINED_QUERIES_METHODS.map((queryMethod) => ({ code: `screen.get${queryMethod}`, })), ...COMBINED_QUERIES_METHODS.map((queryMethod) => ({ code: `expect(get${queryMethod}('foo')).toBeDefined()`, })), ...COMBINED_QUERIES_METHODS.map((queryMethod) => ({ code: ` const utils = render() expect(utils.get${queryMethod}('foo')).toBeDefined() `, })), ...COMBINED_QUERIES_METHODS.map((queryMethod) => ({ code: `expect(screen.get${queryMethod}('foo')).toBeDefined()`, })), ...COMBINED_QUERIES_METHODS.map((queryMethod) => ({ code: `expect(getBy${queryMethod}('foo').bar).toBeInTheDocument()`, })), ...COMBINED_QUERIES_METHODS.map((queryMethod) => ({ code: ` async () => { await waitForElement(() => get${queryMethod}('foo')) } `, })), ...COMBINED_QUERIES_METHODS.map((queryMethod) => ({ code: `fireEvent.click(get${queryMethod}('bar'));`, })), ...COMBINED_QUERIES_METHODS.map((queryMethod) => ({ code: `const quxElement = get${queryMethod}('qux')`, })), ...COMBINED_QUERIES_METHODS.map((queryMethod) => ({ code: ` async () => { const quxElement = await find${queryMethod}('qux') }`, })), ...COMBINED_QUERIES_METHODS.map((queryMethod) => ({ code: ` async () => { expect(await find${queryMethod}('qux')).toBeInTheDocument(); }`, })), ...COMBINED_QUERIES_METHODS.map((queryMethod) => ({ code: ` async () => { await find${queryMethod}('foo') }`, options: [ { includeFindQueries: false, }, ], })), ...COMBINED_QUERIES_METHODS.map((queryMethod) => ({ code: `const quxElement = find${queryMethod}('qux')`, })), ...COMBINED_QUERIES_METHODS.map((queryMethod) => ({ code: `const quxElement = screen.find${queryMethod}('qux')`, })), ...COMBINED_QUERIES_METHODS.map((queryMethod) => ({ code: ` async () => { const quxElement = await screen.find${queryMethod}('qux') }`, })), ...COMBINED_QUERIES_METHODS.map((queryMethod) => ({ code: ` function findBySubmit() { return screen.find${queryMethod}('foo') }`, })), ...COMBINED_QUERIES_METHODS.map((queryMethod) => ({ code: ` function findBySubmit() { return find${queryMethod}('foo') }`, })), ...COMBINED_QUERIES_METHODS.map((queryMethod) => ({ code: ` () => { return screen.find${queryMethod}('foo') }`, })), ...COMBINED_QUERIES_METHODS.map((queryMethod) => ({ code: ` () => { return find${queryMethod}('foo') }`, })), ...COMBINED_QUERIES_METHODS.map((queryMethod) => ({ code: ` () => screen.find${queryMethod}('foo')`, })), ...COMBINED_QUERIES_METHODS.map((queryMethod) => ({ code: ` () => find${queryMethod}('foo')`, })), ...COMBINED_QUERIES_METHODS.map((queryMethod) => ({ code: `() => { return get${queryMethod}('foo') }`, })), ...COMBINED_QUERIES_METHODS.map((queryMethod) => ({ code: `function bar() { return get${queryMethod}('foo') }`, })), ...COMBINED_QUERIES_METHODS.map((queryMethod) => ({ code: `const { get${queryMethod} } = render()`, })), ...COMBINED_QUERIES_METHODS.map((queryMethod) => ({ code: `it('test', () => { const { get${queryMethod} } = render() })`, })), ...COMBINED_QUERIES_METHODS.map((queryMethod) => ({ code: `it('test', () => { const [ get${queryMethod} ] = render() })`, })), ...COMBINED_QUERIES_METHODS.map((queryMethod) => ({ code: `const a = [ get${queryMethod}('foo') ]`, })), ...COMBINED_QUERIES_METHODS.map((queryMethod) => ({ code: `const a = { foo: get${queryMethod}('bar') }`, })), ...COMBINED_QUERIES_METHODS.map((queryMethod) => ({ code: `query${queryMethod}("foo")`, })), ...COMBINED_QUERIES_METHODS.map((queryMethod) => ({ code: ` expect(get${queryMethod}('foo')).toBeTruthy() fireEvent.click(get${queryMethod}('bar')); `, options: [ { assertion: 'toBeTruthy', }, ], })), ...COMBINED_QUERIES_METHODS.map((queryMethod) => ({ code: `expect(get${queryMethod}('foo')).toBeEnabled()`, options: [ { assertion: 'toBeInTheDocument', }, ], })), { // https://github.com/testing-library/eslint-plugin-testing-library/issues/475 code: ` // incomplete expect statement should be ignored expect('something'); expect(getByText('foo')); `, options: [ { assertion: 'toBeInTheDocument', }, ], }, ], invalid: [ ...COMBINED_QUERIES_METHODS.map( (queryMethod) => ({ code: `get${queryMethod}('foo')`, errors: [ { messageId: 'preferExplicitAssert', data: { queryType: 'getBy*', }, }, ], } as const) ), ...COMBINED_QUERIES_METHODS.map( (queryMethod) => ({ code: `find${queryMethod}('foo')`, errors: [ { messageId: 'preferExplicitAssert', data: { queryType: 'findBy*' }, }, ], } as const) ), ...COMBINED_QUERIES_METHODS.map( (queryMethod) => ({ code: `screen.find${queryMethod}('foo')`, errors: [ { messageId: 'preferExplicitAssert', data: { queryType: 'findBy*' }, }, ], } as const) ), ...COMBINED_QUERIES_METHODS.map( (queryMethod) => ({ code: ` async () => { await screen.find${queryMethod}('foo') } `, errors: [ { messageId: 'preferExplicitAssert', data: { queryType: 'findBy*' }, }, ], } as const) ), ...COMBINED_QUERIES_METHODS.map( (queryMethod) => ({ code: ` async () => { await find${queryMethod}('foo') } `, errors: [ { messageId: 'preferExplicitAssert', data: { queryType: 'findBy*' }, }, ], } as const) ), ...COMBINED_QUERIES_METHODS.map( (queryMethod) => ({ code: ` const utils = render() utils.get${queryMethod}('foo') `, errors: [ { messageId: 'preferExplicitAssert', line: 3, column: 15, data: { queryType: 'getBy*', }, }, ], } as const) ), ...COMBINED_QUERIES_METHODS.map( (queryMethod) => ({ code: `screen.get${queryMethod}('foo')`, errors: [ { messageId: 'preferExplicitAssert', line: 1, column: 8, data: { queryType: 'getBy*', }, }, ], } as const) ), ...COMBINED_QUERIES_METHODS.map( (queryMethod) => ({ code: ` () => { get${queryMethod}('foo') doSomething() get${queryMethod}('bar') const quxElement = get${queryMethod}('qux') } `, errors: [ { messageId: 'preferExplicitAssert', line: 3, data: { queryType: 'getBy*', }, }, { messageId: 'preferExplicitAssert', line: 6, data: { queryType: 'getBy*', }, }, ], } as const) ), ...COMBINED_QUERIES_METHODS.map( (queryMethod) => ({ settings: { 'testing-library/utils-module': 'test-utils', }, code: ` import "test-utils" getBy${queryMethod}("Hello") `, errors: [ { messageId: 'preferExplicitAssert', data: { queryType: 'getBy*', }, }, ], } as const) ), { code: `getByIcon('foo')`, // custom `getBy` query extended through options errors: [ { messageId: 'preferExplicitAssert', }, ], }, ...COMBINED_QUERIES_METHODS.map( (queryMethod) => ({ code: `expect(get${queryMethod}('foo')).toBeDefined()`, options: [ { assertion: 'toBeInTheDocument', }, ], errors: [ { messageId: 'preferExplicitAssertAssertion', data: { assertion: 'toBeInTheDocument' }, }, ], } as const) ), ...COMBINED_QUERIES_METHODS.map( (queryMethod) => ({ code: `expect(get${queryMethod}('foo')).not.toBeNull()`, options: [ { assertion: 'toBeInTheDocument', }, ], errors: [ { messageId: 'preferExplicitAssertAssertion', data: { assertion: 'toBeInTheDocument' }, }, ], } as const) ), ...COMBINED_QUERIES_METHODS.map( (queryMethod) => ({ code: `expect(get${queryMethod}('foo')).not.toBeFalsy()`, options: [ { assertion: 'toBeInTheDocument', }, ], errors: [ { messageId: 'preferExplicitAssertAssertion', data: { assertion: 'toBeInTheDocument' }, }, ], } as const) ), ], });
the_stack
import { Event } from 'vs/base/common/event'; import { toSlashes } from 'vs/base/common/extpath'; import * as json from 'vs/base/common/json'; import * as jsonEdit from 'vs/base/common/jsonEdit'; import { FormattingOptions } from 'vs/base/common/jsonFormatter'; import { normalizeDriveLetter } from 'vs/base/common/labels'; import { Schemas } from 'vs/base/common/network'; import { isAbsolute } from 'vs/base/common/path'; import { isLinux, isMacintosh, isWindows } from 'vs/base/common/platform'; import { IExtUri, isEqualAuthority } from 'vs/base/common/resources'; import { URI } from 'vs/base/common/uri'; import { IWorkspaceBackupInfo, IFolderBackupInfo } from 'vs/platform/backup/common/backup'; import { createDecorator } from 'vs/platform/instantiation/common/instantiation'; import { ILogService } from 'vs/platform/log/common/log'; import { getRemoteAuthority } from 'vs/platform/remote/common/remoteHosts'; import { IBaseWorkspace, IRawFileWorkspaceFolder, IRawUriWorkspaceFolder, IWorkspaceIdentifier, WorkspaceFolder } from 'vs/platform/workspace/common/workspace'; export const IWorkspacesService = createDecorator<IWorkspacesService>('workspacesService'); export interface IWorkspacesService { readonly _serviceBrand: undefined; // Workspaces Management enterWorkspace(workspaceUri: URI): Promise<IEnterWorkspaceResult | undefined>; createUntitledWorkspace(folders?: IWorkspaceFolderCreationData[], remoteAuthority?: string): Promise<IWorkspaceIdentifier>; deleteUntitledWorkspace(workspace: IWorkspaceIdentifier): Promise<void>; getWorkspaceIdentifier(workspaceUri: URI): Promise<IWorkspaceIdentifier>; // Workspaces History readonly onDidChangeRecentlyOpened: Event<void>; addRecentlyOpened(recents: IRecent[]): Promise<void>; removeRecentlyOpened(workspaces: URI[]): Promise<void>; clearRecentlyOpened(): Promise<void>; getRecentlyOpened(): Promise<IRecentlyOpened>; // Dirty Workspaces getDirtyWorkspaces(): Promise<Array<IWorkspaceBackupInfo | IFolderBackupInfo>>; } //#region Workspaces Recently Opened export interface IRecentlyOpened { workspaces: Array<IRecentWorkspace | IRecentFolder>; files: IRecentFile[]; } export type IRecent = IRecentWorkspace | IRecentFolder | IRecentFile; export interface IRecentWorkspace { readonly workspace: IWorkspaceIdentifier; label?: string; readonly remoteAuthority?: string; } export interface IRecentFolder { readonly folderUri: URI; label?: string; readonly remoteAuthority?: string; } export interface IRecentFile { readonly fileUri: URI; label?: string; readonly remoteAuthority?: string; } export function isRecentWorkspace(curr: IRecent): curr is IRecentWorkspace { return curr.hasOwnProperty('workspace'); } export function isRecentFolder(curr: IRecent): curr is IRecentFolder { return curr.hasOwnProperty('folderUri'); } export function isRecentFile(curr: IRecent): curr is IRecentFile { return curr.hasOwnProperty('fileUri'); } //#endregion //#region Workspace File Utilities export function isStoredWorkspaceFolder(obj: unknown): obj is IStoredWorkspaceFolder { return isRawFileWorkspaceFolder(obj) || isRawUriWorkspaceFolder(obj); } function isRawFileWorkspaceFolder(obj: unknown): obj is IRawFileWorkspaceFolder { const candidate = obj as IRawFileWorkspaceFolder | undefined; return typeof candidate?.path === 'string' && (!candidate.name || typeof candidate.name === 'string'); } function isRawUriWorkspaceFolder(obj: unknown): obj is IRawUriWorkspaceFolder { const candidate = obj as IRawUriWorkspaceFolder | undefined; return typeof candidate?.uri === 'string' && (!candidate.name || typeof candidate.name === 'string'); } export type IStoredWorkspaceFolder = IRawFileWorkspaceFolder | IRawUriWorkspaceFolder; export interface IStoredWorkspace extends IBaseWorkspace { folders: IStoredWorkspaceFolder[]; } export interface IWorkspaceFolderCreationData { readonly uri: URI; readonly name?: string; } export interface IUntitledWorkspaceInfo { readonly workspace: IWorkspaceIdentifier; readonly remoteAuthority?: string; } export interface IEnterWorkspaceResult { readonly workspace: IWorkspaceIdentifier; readonly backupPath?: string; } /** * Given a folder URI and the workspace config folder, computes the IStoredWorkspaceFolder using * a relative or absolute path or a uri. * Undefined is returned if the folderURI and the targetConfigFolderURI don't have the same schema or authority * * @param folderURI a workspace folder * @param forceAbsolute if set, keep the path absolute * @param folderName a workspace name * @param targetConfigFolderURI the folder where the workspace is living in * @param useSlashForPath if set, use forward slashes for file paths on windows */ export function getStoredWorkspaceFolder(folderURI: URI, forceAbsolute: boolean, folderName: string | undefined, targetConfigFolderURI: URI, useSlashForPath = !isWindows, extUri: IExtUri): IStoredWorkspaceFolder { if (folderURI.scheme !== targetConfigFolderURI.scheme) { return { name: folderName, uri: folderURI.toString(true) }; } let folderPath = !forceAbsolute ? extUri.relativePath(targetConfigFolderURI, folderURI) : undefined; if (folderPath !== undefined) { if (folderPath.length === 0) { folderPath = '.'; } else if (isWindows && folderURI.scheme === Schemas.file && !useSlashForPath) { // Windows gets special treatment: // - use backslahes unless slash is used by other existing folders folderPath = folderPath.replace(/\//g, '\\'); } } else { // use absolute path if (folderURI.scheme === Schemas.file) { folderPath = folderURI.fsPath; if (isWindows) { // Windows gets special treatment: // - normalize all paths to get nice casing of drive letters // - use backslahes unless slash is used by other existing folders folderPath = normalizeDriveLetter(folderPath); if (useSlashForPath) { folderPath = toSlashes(folderPath); } } } else { if (!extUri.isEqualAuthority(folderURI.authority, targetConfigFolderURI.authority)) { return { name: folderName, uri: folderURI.toString(true) }; } folderPath = folderURI.path; } } return { name: folderName, path: folderPath }; } export function toWorkspaceFolders(configuredFolders: IStoredWorkspaceFolder[], workspaceConfigFile: URI, extUri: IExtUri): WorkspaceFolder[] { let result: WorkspaceFolder[] = []; let seen: Set<string> = new Set(); const relativeTo = extUri.dirname(workspaceConfigFile); for (let configuredFolder of configuredFolders) { let uri: URI | undefined = undefined; if (isRawFileWorkspaceFolder(configuredFolder)) { if (configuredFolder.path) { uri = extUri.resolvePath(relativeTo, configuredFolder.path); } } else if (isRawUriWorkspaceFolder(configuredFolder)) { try { uri = URI.parse(configuredFolder.uri); if (uri.path[0] !== '/') { uri = uri.with({ path: '/' + uri.path }); // this makes sure all workspace folder are absolute } } catch (e) { console.warn(e); // ignore } } if (uri) { // remove duplicates let comparisonKey = extUri.getComparisonKey(uri); if (!seen.has(comparisonKey)) { seen.add(comparisonKey); const name = configuredFolder.name || extUri.basenameOrAuthority(uri); result.push(new WorkspaceFolder({ uri, name, index: result.length }, configuredFolder)); } } } return result; } /** * Rewrites the content of a workspace file to be saved at a new location. * Throws an exception if file is not a valid workspace file */ export function rewriteWorkspaceFileForNewLocation(rawWorkspaceContents: string, configPathURI: URI, isFromUntitledWorkspace: boolean, targetConfigPathURI: URI, extUri: IExtUri) { let storedWorkspace = doParseStoredWorkspace(configPathURI, rawWorkspaceContents); const sourceConfigFolder = extUri.dirname(configPathURI); const targetConfigFolder = extUri.dirname(targetConfigPathURI); const rewrittenFolders: IStoredWorkspaceFolder[] = []; const slashForPath = useSlashForPath(storedWorkspace.folders); for (const folder of storedWorkspace.folders) { const folderURI = isRawFileWorkspaceFolder(folder) ? extUri.resolvePath(sourceConfigFolder, folder.path) : URI.parse(folder.uri); let absolute; if (isFromUntitledWorkspace) { absolute = false; // if it was an untitled workspace, try to make paths relative } else { absolute = !isRawFileWorkspaceFolder(folder) || isAbsolute(folder.path); // for existing workspaces, preserve whether a path was absolute or relative } rewrittenFolders.push(getStoredWorkspaceFolder(folderURI, absolute, folder.name, targetConfigFolder, slashForPath, extUri)); } // Preserve as much of the existing workspace as possible by using jsonEdit // and only changing the folders portion. const formattingOptions: FormattingOptions = { insertSpaces: false, tabSize: 4, eol: (isLinux || isMacintosh) ? '\n' : '\r\n' }; const edits = jsonEdit.setProperty(rawWorkspaceContents, ['folders'], rewrittenFolders, formattingOptions); let newContent = jsonEdit.applyEdits(rawWorkspaceContents, edits); if (isEqualAuthority(storedWorkspace.remoteAuthority, getRemoteAuthority(targetConfigPathURI))) { // unsaved remote workspaces have the remoteAuthority set. Remove it when no longer nexessary. newContent = jsonEdit.applyEdits(newContent, jsonEdit.removeProperty(newContent, ['remoteAuthority'], formattingOptions)); } return newContent; } function doParseStoredWorkspace(path: URI, contents: string): IStoredWorkspace { // Parse workspace file let storedWorkspace: IStoredWorkspace = json.parse(contents); // use fault tolerant parser // Filter out folders which do not have a path or uri set if (storedWorkspace && Array.isArray(storedWorkspace.folders)) { storedWorkspace.folders = storedWorkspace.folders.filter(folder => isStoredWorkspaceFolder(folder)); } else { throw new Error(`${path} looks like an invalid workspace file.`); } return storedWorkspace; } export function useSlashForPath(storedFolders: IStoredWorkspaceFolder[]): boolean { if (isWindows) { return storedFolders.some(folder => isRawFileWorkspaceFolder(folder) && folder.path.indexOf('/') >= 0); } return true; } //#endregion //#region Workspace Storage interface ISerializedRecentWorkspace { readonly workspace: { id: string; configPath: string; }; readonly label?: string; readonly remoteAuthority?: string; } interface ISerializedRecentFolder { readonly folderUri: string; readonly label?: string; readonly remoteAuthority?: string; } interface ISerializedRecentFile { readonly fileUri: string; readonly label?: string; readonly remoteAuthority?: string; } interface ISerializedRecentlyOpened { readonly entries: Array<ISerializedRecentWorkspace | ISerializedRecentFolder | ISerializedRecentFile>; // since 1.55 } export type RecentlyOpenedStorageData = object; function isSerializedRecentWorkspace(data: any): data is ISerializedRecentWorkspace { return data.workspace && typeof data.workspace === 'object' && typeof data.workspace.id === 'string' && typeof data.workspace.configPath === 'string'; } function isSerializedRecentFolder(data: any): data is ISerializedRecentFolder { return typeof data.folderUri === 'string'; } function isSerializedRecentFile(data: any): data is ISerializedRecentFile { return typeof data.fileUri === 'string'; } export function restoreRecentlyOpened(data: RecentlyOpenedStorageData | undefined, logService: ILogService): IRecentlyOpened { const result: IRecentlyOpened = { workspaces: [], files: [] }; if (data) { const restoreGracefully = function <T>(entries: T[], func: (entry: T, index: number) => void) { for (let i = 0; i < entries.length; i++) { try { func(entries[i], i); } catch (e) { logService.warn(`Error restoring recent entry ${JSON.stringify(entries[i])}: ${e.toString()}. Skip entry.`); } } }; const storedRecents = data as ISerializedRecentlyOpened; if (Array.isArray(storedRecents.entries)) { restoreGracefully(storedRecents.entries, (entry) => { const label = entry.label; const remoteAuthority = entry.remoteAuthority; if (isSerializedRecentWorkspace(entry)) { result.workspaces.push({ label, remoteAuthority, workspace: { id: entry.workspace.id, configPath: URI.parse(entry.workspace.configPath) } }); } else if (isSerializedRecentFolder(entry)) { result.workspaces.push({ label, remoteAuthority, folderUri: URI.parse(entry.folderUri) }); } else if (isSerializedRecentFile(entry)) { result.files.push({ label, remoteAuthority, fileUri: URI.parse(entry.fileUri) }); } }); } } return result; } export function toStoreData(recents: IRecentlyOpened): RecentlyOpenedStorageData { const serialized: ISerializedRecentlyOpened = { entries: [] }; for (const recent of recents.workspaces) { if (isRecentFolder(recent)) { serialized.entries.push({ folderUri: recent.folderUri.toString(), label: recent.label, remoteAuthority: recent.remoteAuthority }); } else { serialized.entries.push({ workspace: { id: recent.workspace.id, configPath: recent.workspace.configPath.toString() }, label: recent.label, remoteAuthority: recent.remoteAuthority }); } } for (const recent of recents.files) { serialized.entries.push({ fileUri: recent.fileUri.toString(), label: recent.label, remoteAuthority: recent.remoteAuthority }); } return serialized; } //#endregion
the_stack
import i18next from "i18next"; import { computed, toJS } from "mobx"; import { createTransformer } from "mobx-utils"; import filterOutUndefined from "../../../Core/filterOutUndefined"; import isDefined from "../../../Core/isDefined"; import { isJsonObject, isJsonString, JsonArray, JsonObject } from "../../../Core/Json"; import loadJson from "../../../Core/loadJson"; import runLater from "../../../Core/runLater"; import TerriaError from "../../../Core/TerriaError"; import AccessControlMixin from "../../../ModelMixins/AccessControlMixin"; import GroupMixin from "../../../ModelMixins/GroupMixin"; import ReferenceMixin from "../../../ModelMixins/ReferenceMixin"; import UrlMixin from "../../../ModelMixins/UrlMixin"; import MagdaDistributionFormatTraits from "../../../Traits/TraitsClasses/MagdaDistributionFormatTraits"; import MagdaReferenceTraits from "../../../Traits/TraitsClasses/MagdaReferenceTraits"; import ModelTraits from "../../../Traits/ModelTraits"; import CatalogMemberFactory from "../CatalogMemberFactory"; import CommonStrata from "../../Definition/CommonStrata"; import CreateModel from "../../Definition/CreateModel"; import createStratumInstance from "../../Definition/createStratumInstance"; import { BaseModel } from "../../Definition/Model"; import ModelPropertiesFromTraits from "../../Definition/ModelPropertiesFromTraits"; import proxyCatalogItemUrl from "../proxyCatalogItemUrl"; import StratumFromTraits from "../../Definition/StratumFromTraits"; import StratumOrder from "../../Definition/StratumOrder"; import Terria from "../../Terria"; import updateModelFromJson from "../../Definition/updateModelFromJson"; const magdaRecordStratum = "magda-record"; StratumOrder.addDefaultStratum(magdaRecordStratum); // If you want to supply headers sent for magda requests, supply them in // config parameters export interface MagdaReferenceHeaders { [key: string]: string; } export default class MagdaReference extends AccessControlMixin( UrlMixin(ReferenceMixin(CreateModel(MagdaReferenceTraits))) ) { static readonly defaultDistributionFormats: StratumFromTraits< MagdaDistributionFormatTraits >[] = [ createStratumInstance(MagdaDistributionFormatTraits, { id: "WMS", formatRegex: "^wms$", definition: { type: "wms" } }), createStratumInstance(MagdaDistributionFormatTraits, { id: "EsriMapServer", formatRegex: "^esri (mapserver|map server|rest|tiled map service)$", urlRegex: "MapServer", definition: { type: "esri-mapServer" } }), createStratumInstance(MagdaDistributionFormatTraits, { id: "CSV", formatRegex: "^csv(-geo-)?", definition: { type: "csv" } }), createStratumInstance(MagdaDistributionFormatTraits, { id: "CZML", formatRegex: "^czml$", definition: { type: "czml" } }), createStratumInstance(MagdaDistributionFormatTraits, { id: "KML", formatRegex: "^km[lz]$", definition: { type: "kml" } }), createStratumInstance(MagdaDistributionFormatTraits, { id: "GeoJSON", formatRegex: "^geojson$", definition: { type: "geojson" } }), createStratumInstance(MagdaDistributionFormatTraits, { id: "WFS", formatRegex: "^wfs$", definition: { type: "wfs" } }), createStratumInstance(MagdaDistributionFormatTraits, { id: "EsriFeatureServer", formatRegex: "ESRI (MAPSERVER|FEATURESERVER)", // We still allow `ESRI MAPSERVER` to be considered for compatibility reason urlRegex: "FeatureServer$|FeatureServer/$", // url Regex will exclude MapServer urls definition: { type: "esri-featureServer-group" } }), createStratumInstance(MagdaDistributionFormatTraits, { id: "EsriFeatureServer", formatRegex: "ESRI (MAPSERVER|FEATURESERVER)", // We still allow `ESRI MAPSERVER` to be considered for compatibility reason urlRegex: "FeatureServer/d", definition: { type: "esri-featureServer" } }) ]; static readonly type = "magda"; get type() { return MagdaReference.type; } constructor( id: string | undefined, terria: Terria, sourceReference?: BaseModel, strata?: Map<string, StratumFromTraits<ModelTraits>> ) { super(id, terria, sourceReference, strata); this.setTrait( CommonStrata.defaults, "distributionFormats", MagdaReference.defaultDistributionFormats ); } @computed get registryUri(): uri.URI | undefined { const uri = this.uri; if (uri === undefined) { return undefined; } return uri.clone().segment("api/v0/registry"); } @computed get preparedDistributionFormats(): PreparedDistributionFormat[] { return ( this.distributionFormats && this.distributionFormats.map(prepareDistributionFormat) ); } @computed get accessType(): string { const access = getAccessTypeFromMagdaRecord(this.magdaRecord); return access || super.accessType; } protected async forceLoadReference( previousTarget: BaseModel | undefined ): Promise<BaseModel | undefined> { const existingRecord = this.magdaRecord ? toJS(this.magdaRecord) : undefined; const magdaUri = this.uri; const override = toJS(this.override); const distributionFormats = this.preparedDistributionFormats; // `runLater` is needed due to no actions in `AsyncLoader` computed promise (See AsyncLoader.ts) return await runLater(async () => { const target = MagdaReference.createMemberFromRecord( this.terria, this, distributionFormats, magdaUri, this.uniqueId, existingRecord, override, previousTarget ); if (target !== undefined) { return target; } const record = await this.loadMagdaRecord({ id: this.recordId, optionalAspects: [ "terria", "group", "dcat-dataset-strings", "dcat-distribution-strings", "dataset-distributions", "dataset-format" ], dereference: true, magdaReferenceHeaders: this.terria.configParameters .magdaReferenceHeaders }); return MagdaReference.createMemberFromRecord( this.terria, this, distributionFormats, magdaUri, this.uniqueId, record, override, previousTarget ); }); } private static createMemberFromRecord( terria: Terria, sourceReference: BaseModel | undefined, distributionFormats: readonly PreparedDistributionFormat[], magdaUri: uri.URI | undefined, id: string | undefined, record: JsonObject | undefined, override: JsonObject | undefined, previousTarget: BaseModel | undefined ): BaseModel | undefined { if (record === undefined) { return undefined; } const aspects = record.aspects; if (!isJsonObject(aspects)) { return undefined; } if (isJsonObject(aspects.group) && Array.isArray(aspects.group.members)) { const members = aspects.group.members; if (members.every(member => isJsonObject(member))) { // Every member has been dereferenced, so we're good to go. return MagdaReference.createGroupFromRecord( terria, sourceReference, distributionFormats, magdaUri, id, record, override, previousTarget ); } else { // Not enough information to create a group yet. return undefined; } } if (isJsonObject(aspects.terria) && isJsonString(aspects.terria.type)) { // A terria aspect is really all we need, _except_ if the terria aspect indicates // this is a group and we don't have a dereferenced group aspect to tell us what's // in the group. if (aspects.terria.type === "group") { // TODO: could be other types of groups! // If we had a dereferenced group aspect, we would have returned above. return undefined; } else { return MagdaReference.createMemberFromTerriaAspect( terria, sourceReference, magdaUri, id, record, aspects.terria, override, previousTarget ); } } // If this is a dataset, we need the distributions to be dereferenced. let distributions: JsonArray | undefined; if (isJsonObject(aspects["dcat-dataset-strings"])) { const datasetDistributions = aspects["dataset-distributions"]; if ( !isJsonObject(datasetDistributions) || !Array.isArray(datasetDistributions.distributions) ) { // Distributions not present return undefined; } distributions = datasetDistributions.distributions; if (!distributions.every(distribution => isJsonObject(distribution))) { // Some of the distributions are not dereferenced. return undefined; } } // A distribution is already ready to go if (isJsonObject(aspects["dcat-distribution-strings"])) { distributions = distributions ? distributions.slice() : []; distributions.push(record); } if (distributions) { const match = MagdaReference.findPreparedDistributionFormat( distributionFormats, distributions ); if ( match !== undefined && match.format.definition && isJsonString(match.format.definition.type) ) { return MagdaReference.createMemberFromDistributionFormat( terria, sourceReference, magdaUri, id, record, match.distribution, match.format, override, previousTarget ); } } return undefined; } private static createGroupFromRecord( terria: Terria, sourceReference: BaseModel | undefined, distributionFormats: readonly PreparedDistributionFormat[], magdaUri: uri.URI | undefined, id: string | undefined, record: JsonObject, override: JsonObject | undefined, previousTarget: BaseModel | undefined ): BaseModel | undefined { const aspects = record.aspects; if (!isJsonObject(aspects)) { return undefined; } const terriaAspect = aspects.terria; const type = isJsonObject(terriaAspect) && isJsonString(terriaAspect.type) ? terriaAspect.type : "group"; const ModelClass = CatalogMemberFactory.find(type); if (ModelClass === undefined) { throw new TerriaError({ sender: this, title: i18next.t("models.catalog.unsupportedTypeTitle"), message: i18next.t("models.catalog.unsupportedTypeMessage", { type }) }); } let group: BaseModel; if (previousTarget && previousTarget instanceof ModelClass) { group = previousTarget; } else { group = new ModelClass(id, terria, sourceReference); } if (isJsonObject(aspects.group) && Array.isArray(aspects.group.members)) { const members = aspects.group.members; const ids = members.map(member => { if (!isJsonObject(member) || !isJsonString(member.id)) { return undefined; } const memberId = member.id; let overriddenMember: JsonObject | undefined; if (override && Array.isArray(override.members)) { overriddenMember = override.members.find( member => isJsonObject(member) && member.id === memberId ) as JsonObject | undefined; } const model = MagdaReference.createMemberFromRecord( terria, undefined, distributionFormats, magdaUri, member.id, member, overriddenMember, terria.getModelById(BaseModel, member.id) ); let shareKeys; if ( isJsonObject(member.aspects) && isJsonObject(member.aspects.terria) && Array.isArray(member.aspects.terria.shareKeys) ) { shareKeys = member.aspects.terria.shareKeys.filter(isJsonString); } if (!model) { // Can't create an item or group yet, so create a reference. const ref = new MagdaReference(member.id, terria, undefined); if (magdaUri) { ref.setTrait(CommonStrata.definition, "url", magdaUri.toString()); } ref.setTrait(CommonStrata.definition, "recordId", memberId); if ( isJsonObject(member.aspects) && isJsonObject(member.aspects.group) ) { // This is most likely a group. ref.setTrait(CommonStrata.definition, "isGroup", true); } else { // This is most likely a mappable or chartable item. ref.setTrait(CommonStrata.definition, "isMappable", true); ref.setTrait(CommonStrata.definition, "isChartable", true); } // Use the name from the terria aspect if there is one. if ( isJsonObject(member.aspects) && isJsonObject(member.aspects.terria) && isJsonObject(member.aspects.terria.definition) && isJsonString(member.aspects.terria.definition.name) ) { ref.setTrait( CommonStrata.definition, "name", member.aspects.terria.definition.name ); } else if (isJsonString(member.name)) { ref.setTrait(CommonStrata.definition, "name", member.name); } if (overriddenMember) { ref.setTrait(CommonStrata.definition, "override", overriddenMember); } if (terria.getModelById(BaseModel, member.id) === undefined) { terria.addModel(ref, shareKeys); } if (AccessControlMixin.isMixedInto(ref)) { ref.setAccessType(getAccessTypeFromMagdaRecord(member)); } return ref.uniqueId; } else { if (terria.getModelById(BaseModel, member.id) === undefined) { terria.addModel(model, shareKeys); } if (AccessControlMixin.isMixedInto(model)) { model.setAccessType(getAccessTypeFromMagdaRecord(member)); } return model.uniqueId; } }); if (isJsonString(record.name)) { group.setTrait(magdaRecordStratum, "name", record.name); } group.setTrait(magdaRecordStratum, "members", filterOutUndefined(ids)); if (GroupMixin.isMixedInto(group)) { console.log(`Refreshing ids for ${group.uniqueId}`); group.refreshKnownContainerUniqueIds(group.uniqueId); } } if (isJsonObject(aspects.terria)) { const terriaStrata = aspects.terria; Object.keys(terriaStrata).forEach(stratum => { if (stratum === "id" || stratum === "type" || stratum === "shareKeys") { return; } updateModelFromJson(group, stratum, terriaStrata[stratum], true); }); } if (override) { updateModelFromJson(group, CommonStrata.override, override, true); } return group; } private static createMemberFromTerriaAspect( terria: Terria, sourceReference: BaseModel | undefined, magdaUri: uri.URI | undefined, id: string | undefined, record: JsonObject, terriaAspect: JsonObject, override: JsonObject | undefined, previousTarget: BaseModel | undefined ): BaseModel | undefined { if (!isJsonString(terriaAspect.type)) { return undefined; } let result: BaseModel; if (previousTarget && previousTarget.type === terriaAspect.type) { result = previousTarget; } else { // Couldn't re-use the previous target, so create a new one. const newMember = CatalogMemberFactory.create( terriaAspect.type, id, terria, sourceReference ); if (newMember === undefined) { console.error( `Could not create unknown model type ${terriaAspect.type}.` ); // don't create a stub here, as magda should rarely create unknown model types // and we'll let the UI highlight that it's bad rather than bandaging an unknown type return undefined; } result = newMember; } if (isJsonString(record.name)) { result.setTrait(magdaRecordStratum, "name", record.name); } Object.keys(terriaAspect).forEach(stratum => { if (stratum === "id" || stratum === "type" || stratum === "shareKeys") { return; } updateModelFromJson( result, stratum, terriaAspect[stratum], true ).catchError(error => result.setTrait(CommonStrata.underride, "isExperiencingIssues", true) ); }); if (override) { updateModelFromJson(result, CommonStrata.override, override, true); } return result; } private static createMemberFromDistributionFormat( terria: Terria, sourceReference: BaseModel | undefined, magdaUri: uri.URI | undefined, id: string | undefined, datasetRecord: JsonObject, distributionRecord: JsonObject, format: PreparedDistributionFormat, override: JsonObject | undefined, previousTarget: BaseModel | undefined ): BaseModel | undefined { if ( !isJsonString(format.definition.type) || !isJsonObject(datasetRecord.aspects) || !isJsonObject(distributionRecord.aspects) ) { return undefined; } let result: BaseModel; if (previousTarget && previousTarget.type === format.definition.type) { result = previousTarget; } else { // Couldn't re-use the previous target, so create a new one. const newMember = CatalogMemberFactory.create( format.definition.type, id, terria, sourceReference ); if (newMember === undefined) { throw new TerriaError({ sender: this, title: i18next.t("models.catalog.unsupportedTypeTitle"), message: i18next.t("models.catalog.unsupportedTypeMessage", { type: format.definition.type }) }); } result = newMember; } const datasetDcat = datasetRecord.aspects["dcat-dataset-strings"]; const distributionDcat = distributionRecord.aspects["dcat-distribution-strings"]; let url: string | undefined; if (isJsonObject(distributionDcat)) { if (isJsonString(distributionDcat.downloadURL)) { url = distributionDcat.downloadURL; } if (url === undefined && isJsonString(distributionDcat.accessURL)) { url = distributionDcat.accessURL; } } const underride: any = { url: url, info: [], ...format.definition }; if ( isJsonObject(datasetDcat) && isJsonString(datasetDcat.description) && !underride.info.find( (section: any) => section.name === "Dataset Description" ) ) { underride.info.push({ name: "Dataset Description", content: datasetDcat.description }); } if ( isJsonObject(distributionDcat) && isJsonString(distributionDcat.description) && !underride.info.find( (section: any) => section.name === "Distribution Description" ) ) { underride.info.push({ name: "Distribution Description", content: distributionDcat.description }); } updateModelFromJson( result, magdaRecordStratum, { name: datasetRecord.name }, true ); updateModelFromJson(result, CommonStrata.underride, underride, true); if (override) { updateModelFromJson(result, CommonStrata.override, override, true); } return result; } private static findPreparedDistributionFormat( distributionFormats: readonly PreparedDistributionFormat[], distributions: JsonArray ): | { distribution: JsonObject; format: PreparedDistributionFormat; } | undefined { for (let i = 0; i < distributionFormats.length; ++i) { const distributionFormat = distributionFormats[i]; const formatRegex = distributionFormat.formatRegex; const urlRegex = distributionFormat.urlRegex; // Find distributions that match this format for (let j = 0; j < distributions.length; ++j) { const distribution = distributions[j]; if (!isJsonObject(distribution)) { continue; } const aspects = distribution.aspects; if (!isJsonObject(aspects)) { continue; } const dcatJson = aspects["dcat-distribution-strings"]; const datasetFormat = aspects["dataset-format"]; let format: string | undefined; let url: string | undefined; if (isJsonObject(dcatJson)) { if (typeof dcatJson.format === "string") { format = dcatJson.format; } if (typeof dcatJson.downloadURL === "string") { url = dcatJson.downloadURL; } if (url === undefined && typeof dcatJson.accessURL === "string") { url = dcatJson.accessURL; } } if ( isJsonObject(datasetFormat) && typeof datasetFormat.format === "string" ) { format = datasetFormat.format; } if (format === undefined || url === undefined) { continue; } if ( (formatRegex !== undefined && !formatRegex.test(format)) || (urlRegex !== undefined && !urlRegex.test(url)) ) { continue; } // We have a match! return { distribution: distribution, format: distributionFormat }; } } return undefined; } @computed get cacheDuration(): string { if (isDefined(super.cacheDuration)) { return super.cacheDuration; } return "0d"; } protected loadMagdaRecord(options: RecordOptions): Promise<JsonObject> { const recordUri = this.buildMagdaRecordUri(options); if (recordUri === undefined) { return Promise.reject( new TerriaError({ sender: this, title: i18next.t("models.magda.idsNotSpecifiedTitle"), message: i18next.t("models.magda.idsNotSpecifiedMessage") }) ); } const proxiedUrl = proxyCatalogItemUrl(this, recordUri.toString()); return loadJson(proxiedUrl, options.magdaReferenceHeaders); } protected buildMagdaRecordUri(options: RecordOptions): uri.URI | undefined { const registryUri = this.registryUri; if (options.id === undefined || registryUri === undefined) { return undefined; } const recordUri = registryUri .clone() .segment(`records/${encodeURIComponent(options.id)}`); if (options.aspects) { recordUri.addQuery("aspect", options.aspects); } if (options.optionalAspects) { recordUri.addQuery("optionalAspect", options.optionalAspects); } if (options.dereference) { recordUri.addQuery("dereference", "true"); } return recordUri; } } export interface RecordOptions { id: string | undefined; aspects?: string[]; optionalAspects?: string[]; dereference?: boolean; magdaReferenceHeaders?: MagdaReferenceHeaders; } interface PreparedDistributionFormat { formatRegex: RegExp | undefined; urlRegex: RegExp | undefined; definition: JsonObject; } const prepareDistributionFormat = createTransformer( (format: ModelPropertiesFromTraits<MagdaDistributionFormatTraits>) => { return { formatRegex: format.formatRegex ? new RegExp(format.formatRegex, "i") : undefined, urlRegex: format.urlRegex ? new RegExp(format.urlRegex, "i") : undefined, definition: format.definition || {} }; } ); function getAccessTypeFromMagdaRecord(magdaRecord: any): string { const record = toJS(magdaRecord); const accessControl: any = record && record.aspects && record.aspects["esri-access-control"]; const access = accessControl && accessControl.access; return access; }
the_stack
import ts from 'typescript'; import { getNumComponentsInSourceFile } from './react'; import { collectIdentifiers } from './identifiers'; import { PropTypesIdentifierMap } from '../react-props'; export type PropsTypeNode = ts.TypeLiteralNode | ts.IntersectionTypeNode; type Params = { anyAlias?: string; anyFunctionAlias?: string; implicitChildren?: boolean; spreadReplacements: { spreadId: string; typeRef: ts.TypeReferenceNode }[]; propTypeIdentifiers?: PropTypesIdentifierMap; }; export default function getTypeFromPropTypesObjectLiteral( objectLiteral: ts.ObjectLiteralExpression, sourceFile: ts.SourceFile, params: Params, ) { const members: ts.PropertySignature[] = []; const intersectionTypes: ts.TypeReferenceNode[] = []; const unhandledProperties: ts.ObjectLiteralElementLike[] = []; const comments: string[] = []; for (const property of objectLiteral.properties) { let handled = false; if (ts.isPropertyAssignment(property)) { if (params.implicitChildren && property.name.getText(sourceFile) === 'children') { handled = true; } else { const prop = convertPropertyAssignment(property, sourceFile, params); if (prop) { members.push(prop); handled = true; } } } else if (ts.isSpreadAssignment(property) && ts.isIdentifier(property.expression)) { const spreadId = property.expression.text; const replacement = params.spreadReplacements.find((cur) => cur.spreadId === spreadId); if (replacement) { intersectionTypes.push(replacement.typeRef); handled = true; } } if (!handled) { unhandledProperties.push(property); comments.push(property.getText(sourceFile)); } } let node: ts.TypeLiteralNode | ts.IntersectionTypeNode = ts.factory.createTypeLiteralNode(members); if (intersectionTypes.length > 0) { node = ts.factory.createIntersectionTypeNode([node, ...intersectionTypes]); } if (comments.length > 0) { node = ts.addSyntheticLeadingComment( node, ts.SyntaxKind.MultiLineCommentTrivia, ` (ts-migrate) TODO: Migrate the remaining prop types ${comments.join('\n')} `, true, ); } return node; } function convertPropertyAssignment( propertyAssignment: ts.PropertyAssignment, sourceFile: ts.SourceFile, params: Params, ) { const name = propertyAssignment.name.getText(sourceFile); const { initializer } = propertyAssignment; let typeExpression: ts.Expression; let isRequired: boolean; if ( ts.isPropertyAccessExpression(initializer) && /\.isRequired/.test(initializer.getText(sourceFile)) ) { typeExpression = initializer.expression; isRequired = true; } else { typeExpression = initializer; isRequired = false; } const typeNode = getTypeFromPropTypeExpression(typeExpression, sourceFile, params); let propertySignature = ts.factory.createPropertySignature( undefined, name, isRequired ? undefined : ts.factory.createToken(ts.SyntaxKind.QuestionToken), typeNode, ); propertySignature = ts.moveSyntheticComments(propertySignature, typeNode); return propertySignature; } function getTypeFromPropTypeExpression( node: ts.Expression, sourceFile: ts.SourceFile, params: Params, ): ts.TypeNode { const { anyAlias, anyFunctionAlias } = params; let text = node.getText(sourceFile).replace(/React\.PropTypes\./, ''); const isDestructuredProptypeImport = params.propTypeIdentifiers && ts.isIdentifier(node) && params.propTypeIdentifiers[text]; let result = null; if (ts.isPropertyAccessExpression(node) || isDestructuredProptypeImport) { if (isDestructuredProptypeImport && params.propTypeIdentifiers) { text = params.propTypeIdentifiers[text]; } /** * PropTypes.array, * PropTypes.bool, * PropTypes.func, * PropTypes.number, * PropTypes.object, * PropTypes.string, * PropTypes.symbol, (ignore) * PropTypes.node, * PropTypes.element, * PropTypes.any, */ if (/string/.test(text)) { result = ts.factory.createKeywordTypeNode(ts.SyntaxKind.StringKeyword); } else if (/any/.test(text)) { if (anyAlias) { result = ts.factory.createTypeReferenceNode(anyAlias, undefined); } else { result = ts.factory.createKeywordTypeNode(ts.SyntaxKind.AnyKeyword); } } else if (/array/.test(text)) { if (anyAlias) { result = ts.factory.createArrayTypeNode( ts.factory.createTypeReferenceNode(anyAlias, undefined), ); } else { result = ts.factory.createArrayTypeNode( ts.factory.createKeywordTypeNode(ts.SyntaxKind.AnyKeyword), ); } } else if (/bool/.test(text)) { result = ts.factory.createKeywordTypeNode(ts.SyntaxKind.BooleanKeyword); } else if (/number/.test(text)) { result = ts.factory.createKeywordTypeNode(ts.SyntaxKind.NumberKeyword); } else if (/object/.test(text)) { if (anyAlias) { result = ts.factory.createTypeReferenceNode(anyAlias, undefined); } else { result = ts.factory.createKeywordTypeNode(ts.SyntaxKind.AnyKeyword); } } else if (/node/.test(text)) { result = ts.factory.createTypeReferenceNode('React.ReactNode', undefined); } else if (/element/.test(text)) { result = ts.factory.createTypeReferenceNode('React.ReactElement', undefined); } else if (/func/.test(text)) { if (anyFunctionAlias) { result = ts.factory.createTypeReferenceNode(anyFunctionAlias, undefined); } else if (anyAlias) { result = ts.factory.createFunctionTypeNode( undefined, [ ts.factory.createParameterDeclaration( undefined, undefined, ts.factory.createToken(ts.SyntaxKind.DotDotDotToken), 'args', undefined, ts.factory.createArrayTypeNode( ts.factory.createTypeReferenceNode(anyAlias, undefined), ), undefined, ), ], ts.factory.createTypeReferenceNode(anyAlias, undefined), ); } else { result = ts.factory.createFunctionTypeNode( undefined, [ ts.factory.createParameterDeclaration( undefined, undefined, ts.factory.createToken(ts.SyntaxKind.DotDotDotToken), 'args', undefined, ts.factory.createArrayTypeNode( ts.factory.createKeywordTypeNode(ts.SyntaxKind.AnyKeyword), ), undefined, ), ], ts.factory.createKeywordTypeNode(ts.SyntaxKind.AnyKeyword), ); } } } else if (ts.isCallExpression(node)) { /** * PropTypes.instanceOf(), (ignore) * PropTypes.oneOf(), // only support oneOf([1, 2]), oneOf(['a', 'b']) * PropTypes.oneOfType(), * PropTypes.arrayOf(), * PropTypes.objectOf(), * PropTypes.shape(), */ const expressionText = node.expression.getText(sourceFile); if (/oneOf$/.test(expressionText)) { const argument = node.arguments[0]; if (ts.isArrayLiteralExpression(argument)) { if (argument.elements.every((elm) => ts.isStringLiteral(elm) || ts.isNumericLiteral(elm))) { result = ts.factory.createUnionTypeNode( (argument.elements as ts.NodeArray<ts.StringLiteral | ts.NumericLiteral>).map((elm) => ts.factory.createLiteralTypeNode(elm), ), ); } } } else if (/oneOfType$/.test(expressionText)) { const argument = node.arguments[0]; if (ts.isArrayLiteralExpression(argument)) { const children: ts.Node[] = []; result = ts.factory.createUnionTypeNode( argument.elements.map((elm) => { const child = getTypeFromPropTypeExpression(elm, sourceFile, params); children.push(child); return child; }), ); for (const child of children) { result = ts.moveSyntheticComments(result, child); } } } else if (/arrayOf$/.test(expressionText)) { const argument = node.arguments[0]; if (argument) { const child = getTypeFromPropTypeExpression(argument, sourceFile, params); result = ts.factory.createArrayTypeNode(child); result = ts.moveSyntheticComments(result, child); } } else if (/objectOf$/.test(expressionText)) { const argument = node.arguments[0]; if (argument) { const child = getTypeFromPropTypeExpression(argument, sourceFile, params); result = ts.factory.createTypeLiteralNode([ ts.factory.createIndexSignature( undefined, undefined, [ ts.factory.createParameterDeclaration( undefined, undefined, undefined, 'key', undefined, ts.factory.createKeywordTypeNode(ts.SyntaxKind.StringKeyword), ), ], child, ), ]); result = ts.moveSyntheticComments(result, child); } } else if (/shape$/.test(expressionText)) { const argument = node.arguments[0]; if (argument && ts.isObjectLiteralExpression(argument)) { return getTypeFromPropTypesObjectLiteral(argument, sourceFile, params); } } } else if (ts.isIdentifier(node) && node.text === 'textlike') { result = ts.factory.createUnionTypeNode([ ts.factory.createKeywordTypeNode(ts.SyntaxKind.StringKeyword), ts.factory.createTypeReferenceNode('React.ReactNode', undefined), ]); } else if (ts.isIdentifier(node)) { result = ts.factory.createTypeReferenceNode(node.text, undefined); } /** * customProp, * anything others */ if (!result) { if (anyAlias) { result = ts.factory.createTypeReferenceNode(anyAlias, undefined); } else { result = ts.factory.createKeywordTypeNode(ts.SyntaxKind.AnyKeyword); } // Add comment about what the original proptype was. result = ts.addSyntheticTrailingComment( result, ts.SyntaxKind.SingleLineCommentTrivia, ` TODO: ${text .split('\n') .map((line) => line.trim()) .join(' ')}`, true, ); } return result; } export function createPropsTypeNameGetter(sourceFile: ts.SourceFile) { const numComponentsInFile = getNumComponentsInSourceFile(sourceFile); const usedIdentifiers = collectIdentifiers(sourceFile); const getPropsTypeName = (componentName: string | undefined) => { let name = ''; if (componentName && numComponentsInFile > 1) { name = `${componentName}Props`; } else { name = 'Props'; } if (!usedIdentifiers.has(name)) { return name; } // Ensure name is unused. let i = 1; while (usedIdentifiers.has(name + i)) { i += 1; } return name + i; }; return getPropsTypeName; }
the_stack
import type * as vscode from 'vscode'; import * as assert from 'assert'; import { URI } from 'vs/base/common/uri'; import { mock } from 'vs/base/test/common/mock'; import { IEditorTabDto, IEditorTabGroupDto, MainThreadEditorTabsShape, TabInputKind, TabModelOperationKind, TextInputDto } from 'vs/workbench/api/common/extHost.protocol'; import { ExtHostEditorTabs } from 'vs/workbench/api/common/extHostEditorTabs'; import { SingleProxyRPCProtocol } from 'vs/workbench/api/test/common/testRPCProtocol'; import { TextTabInput } from 'vs/workbench/api/common/extHostTypes'; suite('ExtHostEditorTabs', function () { const defaultTabDto: IEditorTabDto = { id: 'uniquestring', input: { kind: TabInputKind.TextInput, uri: URI.parse('file://abc/def.txt') }, isActive: true, isDirty: true, isPinned: true, isPreview: false, label: 'label1', }; function createTabDto(dto?: Partial<IEditorTabDto>): IEditorTabDto { return { ...defaultTabDto, ...dto }; } test('Ensure empty model throws when accessing active group', function () { const extHostEditorTabs = new ExtHostEditorTabs( SingleProxyRPCProtocol(new class extends mock<MainThreadEditorTabsShape>() { // override/implement $moveTab or $closeTab }) ); assert.strictEqual(extHostEditorTabs.tabGroups.all.length, 0); // Active group should never be undefined (there is always an active group). Ensure accessing it undefined throws. // TODO @lramos15 Add a throw on the main side when a model is sent without an active group assert.throws(() => extHostEditorTabs.tabGroups.activeTabGroup); }); test('single tab', function () { const extHostEditorTabs = new ExtHostEditorTabs( SingleProxyRPCProtocol(new class extends mock<MainThreadEditorTabsShape>() { // override/implement $moveTab or $closeTab }) ); const tab: IEditorTabDto = createTabDto({ id: 'uniquestring', isActive: true, isDirty: true, isPinned: true, label: 'label1', }); extHostEditorTabs.$acceptEditorTabModel([{ isActive: true, viewColumn: 0, groupId: 12, tabs: [tab] }]); assert.strictEqual(extHostEditorTabs.tabGroups.all.length, 1); const [first] = extHostEditorTabs.tabGroups.all; assert.ok(first.activeTab); assert.strictEqual(first.tabs.indexOf(first.activeTab), 0); { extHostEditorTabs.$acceptEditorTabModel([{ isActive: true, viewColumn: 0, groupId: 12, tabs: [tab] }]); assert.strictEqual(extHostEditorTabs.tabGroups.all.length, 1); const [first] = extHostEditorTabs.tabGroups.all; assert.ok(first.activeTab); assert.strictEqual(first.tabs.indexOf(first.activeTab), 0); } }); test('Empty tab group', function () { const extHostEditorTabs = new ExtHostEditorTabs( SingleProxyRPCProtocol(new class extends mock<MainThreadEditorTabsShape>() { // override/implement $moveTab or $closeTab }) ); extHostEditorTabs.$acceptEditorTabModel([{ isActive: true, viewColumn: 0, groupId: 12, tabs: [] }]); assert.strictEqual(extHostEditorTabs.tabGroups.all.length, 1); const [first] = extHostEditorTabs.tabGroups.all; assert.strictEqual(first.activeTab, undefined); assert.strictEqual(first.tabs.length, 0); }); test('Ensure tabGroup change events fires', function () { const extHostEditorTabs = new ExtHostEditorTabs( SingleProxyRPCProtocol(new class extends mock<MainThreadEditorTabsShape>() { // override/implement $moveTab or $closeTab }) ); let count = 0; extHostEditorTabs.tabGroups.onDidChangeTabGroups(() => count++); assert.strictEqual(count, 0); extHostEditorTabs.$acceptEditorTabModel([{ isActive: true, viewColumn: 0, groupId: 12, tabs: [] }]); assert.ok(extHostEditorTabs.tabGroups.activeTabGroup); const activeTabGroup: vscode.TabGroup = extHostEditorTabs.tabGroups.activeTabGroup; assert.strictEqual(extHostEditorTabs.tabGroups.all.length, 1); assert.strictEqual(activeTabGroup.tabs.length, 0); assert.strictEqual(count, 1); }); test('Check TabGroupChangeEvent properties', function () { const extHostEditorTabs = new ExtHostEditorTabs( SingleProxyRPCProtocol(new class extends mock<MainThreadEditorTabsShape>() { // override/implement $moveTab or $closeTab }) ); const group1Data: IEditorTabGroupDto = { isActive: true, viewColumn: 0, groupId: 12, tabs: [] }; const group2Data: IEditorTabGroupDto = { ...group1Data, groupId: 13 }; const events: vscode.TabGroupChangeEvent[] = []; extHostEditorTabs.tabGroups.onDidChangeTabGroups(e => events.push(e)); // OPEN extHostEditorTabs.$acceptEditorTabModel([group1Data]); assert.deepStrictEqual(events, [{ changed: [], closed: [], opened: [extHostEditorTabs.tabGroups.activeTabGroup] }]); // OPEN, CHANGE events.length = 0; extHostEditorTabs.$acceptEditorTabModel([{ ...group1Data, isActive: false }, group2Data]); assert.deepStrictEqual(events, [{ changed: [extHostEditorTabs.tabGroups.all[0]], closed: [], opened: [extHostEditorTabs.tabGroups.all[1]] }]); // CHANGE events.length = 0; extHostEditorTabs.$acceptEditorTabModel([group1Data, { ...group2Data, isActive: false }]); assert.deepStrictEqual(events, [{ changed: extHostEditorTabs.tabGroups.all, closed: [], opened: [] }]); // CLOSE, CHANGE events.length = 0; const oldActiveGroup = extHostEditorTabs.tabGroups.activeTabGroup; extHostEditorTabs.$acceptEditorTabModel([group2Data]); assert.deepStrictEqual(events, [{ changed: extHostEditorTabs.tabGroups.all, closed: [oldActiveGroup], opened: [] }]); }); test('Ensure reference equality for activeTab and activeGroup', function () { const extHostEditorTabs = new ExtHostEditorTabs( SingleProxyRPCProtocol(new class extends mock<MainThreadEditorTabsShape>() { // override/implement $moveTab or $closeTab }) ); const tab = createTabDto({ id: 'uniquestring', isActive: true, isDirty: true, isPinned: true, label: 'label1', editorId: 'default', }); extHostEditorTabs.$acceptEditorTabModel([{ isActive: true, viewColumn: 0, groupId: 12, tabs: [tab] }]); assert.strictEqual(extHostEditorTabs.tabGroups.all.length, 1); const [first] = extHostEditorTabs.tabGroups.all; assert.ok(first.activeTab); assert.strictEqual(first.tabs.indexOf(first.activeTab), 0); assert.strictEqual(first.activeTab, first.tabs[0]); assert.strictEqual(extHostEditorTabs.tabGroups.activeTabGroup, first); }); test('Ensure reference stability', function () { const extHostEditorTabs = new ExtHostEditorTabs( SingleProxyRPCProtocol(new class extends mock<MainThreadEditorTabsShape>() { // override/implement $moveTab or $closeTab }) ); const tabDto = createTabDto(); // single dirty tab extHostEditorTabs.$acceptEditorTabModel([{ isActive: true, viewColumn: 0, groupId: 12, tabs: [tabDto] }]); let all = extHostEditorTabs.tabGroups.all.map(group => group.tabs).flat(); assert.strictEqual(all.length, 1); const apiTab1 = all[0]; assert.ok(apiTab1.input instanceof TextTabInput); assert.strictEqual(tabDto.input.kind, TabInputKind.TextInput); const dtoResource = (tabDto.input as TextInputDto).uri; assert.strictEqual(apiTab1.input.uri.toString(), URI.revive(dtoResource).toString()); assert.strictEqual(apiTab1.isDirty, true); // NOT DIRTY anymore const tabDto2: IEditorTabDto = { ...tabDto, isDirty: false }; // Accept a simple update extHostEditorTabs.$acceptTabOperation({ kind: TabModelOperationKind.TAB_UPDATE, index: 0, tabDto: tabDto2, groupId: 12 }); all = extHostEditorTabs.tabGroups.all.map(group => group.tabs).flat(); assert.strictEqual(all.length, 1); const apiTab2 = all[0]; assert.ok(apiTab1.input instanceof TextTabInput); assert.strictEqual(apiTab1.input.uri.toString(), URI.revive(dtoResource).toString()); assert.strictEqual(apiTab2.isDirty, false); assert.strictEqual(apiTab1 === apiTab2, true); }); test('Tab.isActive working', function () { const extHostEditorTabs = new ExtHostEditorTabs( SingleProxyRPCProtocol(new class extends mock<MainThreadEditorTabsShape>() { // override/implement $moveTab or $closeTab }) ); const tabDtoAAA = createTabDto({ id: 'AAA', isActive: true, isDirty: true, isPinned: true, label: 'label1', input: { kind: TabInputKind.TextInput, uri: URI.parse('file://abc/AAA.txt') }, editorId: 'default' }); const tabDtoBBB = createTabDto({ id: 'BBB', isActive: false, isDirty: true, isPinned: true, label: 'label1', input: { kind: TabInputKind.TextInput, uri: URI.parse('file://abc/BBB.txt') }, editorId: 'default' }); // single dirty tab extHostEditorTabs.$acceptEditorTabModel([{ isActive: true, viewColumn: 0, groupId: 12, tabs: [tabDtoAAA, tabDtoBBB] }]); const all = extHostEditorTabs.tabGroups.all.map(group => group.tabs).flat(); assert.strictEqual(all.length, 2); const activeTab1 = extHostEditorTabs.tabGroups.activeTabGroup?.activeTab; assert.ok(activeTab1?.input instanceof TextTabInput); assert.strictEqual(tabDtoAAA.input.kind, TabInputKind.TextInput); const dtoAAAResource = (tabDtoAAA.input as TextInputDto).uri; assert.strictEqual(activeTab1?.input?.uri.toString(), URI.revive(dtoAAAResource)?.toString()); assert.strictEqual(activeTab1?.isActive, true); extHostEditorTabs.$acceptTabOperation({ groupId: 12, index: 1, kind: TabModelOperationKind.TAB_UPDATE, tabDto: { ...tabDtoBBB, isActive: true } /// BBB is now active }); const activeTab2 = extHostEditorTabs.tabGroups.activeTabGroup?.activeTab; assert.ok(activeTab2?.input instanceof TextTabInput); assert.strictEqual(tabDtoBBB.input.kind, TabInputKind.TextInput); const dtoBBBResource = (tabDtoBBB.input as TextInputDto).uri; assert.strictEqual(activeTab2?.input?.uri.toString(), URI.revive(dtoBBBResource)?.toString()); assert.strictEqual(activeTab2?.isActive, true); assert.strictEqual(activeTab1?.isActive, false); }); test('vscode.window.tagGroups is immutable', function () { const extHostEditorTabs = new ExtHostEditorTabs( SingleProxyRPCProtocol(new class extends mock<MainThreadEditorTabsShape>() { // override/implement $moveTab or $closeTab }) ); assert.throws(() => { // @ts-expect-error write to readonly prop extHostEditorTabs.tabGroups.activeTabGroup = undefined; }); assert.throws(() => { // @ts-expect-error write to readonly prop extHostEditorTabs.tabGroups.all.length = 0; }); assert.throws(() => { // @ts-expect-error write to readonly prop extHostEditorTabs.tabGroups.onDidChangeActiveTabGroup = undefined; }); assert.throws(() => { // @ts-expect-error write to readonly prop extHostEditorTabs.tabGroups.onDidChangeTabGroups = undefined; }); }); test('Ensure close is called with all tab ids', function () { const closedTabIds: string[][] = []; const extHostEditorTabs = new ExtHostEditorTabs( SingleProxyRPCProtocol(new class extends mock<MainThreadEditorTabsShape>() { // override/implement $moveTab or $closeTab override async $closeTab(tabIds: string[], preserveFocus?: boolean) { closedTabIds.push(tabIds); return true; } }) ); const tab: IEditorTabDto = createTabDto({ id: 'uniquestring', isActive: true, isDirty: true, isPinned: true, label: 'label1', editorId: 'default' }); extHostEditorTabs.$acceptEditorTabModel([{ isActive: true, viewColumn: 0, groupId: 12, tabs: [tab] }]); assert.strictEqual(extHostEditorTabs.tabGroups.all.length, 1); const activeTab = extHostEditorTabs.tabGroups.activeTabGroup?.activeTab; assert.ok(activeTab); extHostEditorTabs.tabGroups.close(activeTab, false); assert.strictEqual(closedTabIds.length, 1); assert.deepStrictEqual(closedTabIds[0], ['uniquestring']); // Close with array extHostEditorTabs.tabGroups.close([activeTab], false); assert.strictEqual(closedTabIds.length, 2); assert.deepStrictEqual(closedTabIds[1], ['uniquestring']); }); test('Update tab only sends tab change event', async function () { const closedTabIds: string[][] = []; const extHostEditorTabs = new ExtHostEditorTabs( SingleProxyRPCProtocol(new class extends mock<MainThreadEditorTabsShape>() { // override/implement $moveTab or $closeTab override async $closeTab(tabIds: string[], preserveFocus?: boolean) { closedTabIds.push(tabIds); return true; } }) ); const tabDto: IEditorTabDto = createTabDto({ id: 'uniquestring', isActive: true, isDirty: true, isPinned: true, label: 'label1', editorId: 'default' }); extHostEditorTabs.$acceptEditorTabModel([{ isActive: true, viewColumn: 0, groupId: 12, tabs: [tabDto] }]); assert.strictEqual(extHostEditorTabs.tabGroups.all.length, 1); assert.strictEqual(extHostEditorTabs.tabGroups.all.map(g => g.tabs).flat().length, 1); const tab = extHostEditorTabs.tabGroups.all[0].tabs[0]; const p = new Promise<vscode.TabChangeEvent>(resolve => extHostEditorTabs.tabGroups.onDidChangeTabs(resolve)); extHostEditorTabs.$acceptTabOperation({ groupId: 12, index: 0, kind: TabModelOperationKind.TAB_UPDATE, tabDto: { ...tabDto, label: 'NEW LABEL' } }); const changedTab = (await p).changed[0]; assert.ok(tab === changedTab); assert.strictEqual(changedTab.label, 'NEW LABEL'); }); test('Active tab', function () { const extHostEditorTabs = new ExtHostEditorTabs( SingleProxyRPCProtocol(new class extends mock<MainThreadEditorTabsShape>() { // override/implement $moveTab or $closeTab }) ); const tab1: IEditorTabDto = createTabDto({ id: 'uniquestring', isActive: true, isDirty: true, isPinned: true, label: 'label1', }); const tab2: IEditorTabDto = createTabDto({ isActive: false, id: 'uniquestring2', }); const tab3: IEditorTabDto = createTabDto({ isActive: false, id: 'uniquestring3', }); extHostEditorTabs.$acceptEditorTabModel([{ isActive: true, viewColumn: 0, groupId: 12, tabs: [tab1, tab2, tab3] }]); assert.strictEqual(extHostEditorTabs.tabGroups.all.length, 1); assert.strictEqual(extHostEditorTabs.tabGroups.all.map(g => g.tabs).flat().length, 3); // Active tab is correct assert.strictEqual(extHostEditorTabs.tabGroups.activeTabGroup?.activeTab, extHostEditorTabs.tabGroups.activeTabGroup?.tabs[0]); // Switching active tab works tab1.isActive = false; tab2.isActive = true; extHostEditorTabs.$acceptTabOperation({ groupId: 12, index: 0, kind: TabModelOperationKind.TAB_UPDATE, tabDto: tab1 }); extHostEditorTabs.$acceptTabOperation({ groupId: 12, index: 1, kind: TabModelOperationKind.TAB_UPDATE, tabDto: tab2 }); assert.strictEqual(extHostEditorTabs.tabGroups.activeTabGroup?.activeTab, extHostEditorTabs.tabGroups.activeTabGroup?.tabs[1]); //Closing tabs out works tab3.isActive = true; extHostEditorTabs.$acceptEditorTabModel([{ isActive: true, viewColumn: 0, groupId: 12, tabs: [tab3] }]); assert.strictEqual(extHostEditorTabs.tabGroups.all.length, 1); assert.strictEqual(extHostEditorTabs.tabGroups.all.map(g => g.tabs).flat().length, 1); assert.strictEqual(extHostEditorTabs.tabGroups.activeTabGroup?.activeTab, extHostEditorTabs.tabGroups.activeTabGroup?.tabs[0]); // Closing out all tabs returns undefine active tab extHostEditorTabs.$acceptEditorTabModel([{ isActive: true, viewColumn: 0, groupId: 12, tabs: [] }]); assert.strictEqual(extHostEditorTabs.tabGroups.all.length, 1); assert.strictEqual(extHostEditorTabs.tabGroups.all.map(g => g.tabs).flat().length, 0); assert.strictEqual(extHostEditorTabs.tabGroups.activeTabGroup?.activeTab, undefined); }); test('Tab operations patches open and close correctly', function () { const extHostEditorTabs = new ExtHostEditorTabs( SingleProxyRPCProtocol(new class extends mock<MainThreadEditorTabsShape>() { // override/implement $moveTab or $closeTab }) ); const tab1: IEditorTabDto = createTabDto({ id: 'uniquestring', isActive: true, label: 'label1', }); const tab2: IEditorTabDto = createTabDto({ isActive: false, id: 'uniquestring2', label: 'label2', }); const tab3: IEditorTabDto = createTabDto({ isActive: false, id: 'uniquestring3', label: 'label3', }); extHostEditorTabs.$acceptEditorTabModel([{ isActive: true, viewColumn: 0, groupId: 12, tabs: [tab1, tab2, tab3] }]); assert.strictEqual(extHostEditorTabs.tabGroups.all.length, 1); assert.strictEqual(extHostEditorTabs.tabGroups.all.map(g => g.tabs).flat().length, 3); // Close tab 2 extHostEditorTabs.$acceptTabOperation({ groupId: 12, index: 1, kind: TabModelOperationKind.TAB_CLOSE, tabDto: tab2 }); assert.strictEqual(extHostEditorTabs.tabGroups.all.length, 1); assert.strictEqual(extHostEditorTabs.tabGroups.all.map(g => g.tabs).flat().length, 2); // Close active tab and update tab 3 to be active extHostEditorTabs.$acceptTabOperation({ groupId: 12, index: 0, kind: TabModelOperationKind.TAB_CLOSE, tabDto: tab1 }); assert.strictEqual(extHostEditorTabs.tabGroups.all.length, 1); assert.strictEqual(extHostEditorTabs.tabGroups.all.map(g => g.tabs).flat().length, 1); tab3.isActive = true; extHostEditorTabs.$acceptTabOperation({ groupId: 12, index: 0, kind: TabModelOperationKind.TAB_UPDATE, tabDto: tab3 }); assert.strictEqual(extHostEditorTabs.tabGroups.all.length, 1); assert.strictEqual(extHostEditorTabs.tabGroups.all.map(g => g.tabs).flat().length, 1); assert.strictEqual(extHostEditorTabs.tabGroups.all[0]?.activeTab?.label, 'label3'); // Open tab 2 back extHostEditorTabs.$acceptTabOperation({ groupId: 12, index: 1, kind: TabModelOperationKind.TAB_OPEN, tabDto: tab2 }); assert.strictEqual(extHostEditorTabs.tabGroups.all.length, 1); assert.strictEqual(extHostEditorTabs.tabGroups.all.map(g => g.tabs).flat().length, 2); assert.strictEqual(extHostEditorTabs.tabGroups.all[0]?.tabs[1]?.label, 'label2'); }); test('Tab operations patches move correctly', function () { const extHostEditorTabs = new ExtHostEditorTabs( SingleProxyRPCProtocol(new class extends mock<MainThreadEditorTabsShape>() { // override/implement $moveTab or $closeTab }) ); const tab1: IEditorTabDto = createTabDto({ id: 'uniquestring', isActive: true, label: 'label1', }); const tab2: IEditorTabDto = createTabDto({ isActive: false, id: 'uniquestring2', label: 'label2', }); const tab3: IEditorTabDto = createTabDto({ isActive: false, id: 'uniquestring3', label: 'label3', }); extHostEditorTabs.$acceptEditorTabModel([{ isActive: true, viewColumn: 0, groupId: 12, tabs: [tab1, tab2, tab3] }]); assert.strictEqual(extHostEditorTabs.tabGroups.all.length, 1); assert.strictEqual(extHostEditorTabs.tabGroups.all.map(g => g.tabs).flat().length, 3); // Move tab 2 to index 0 extHostEditorTabs.$acceptTabOperation({ groupId: 12, index: 0, oldIndex: 1, kind: TabModelOperationKind.TAB_MOVE, tabDto: tab2 }); assert.strictEqual(extHostEditorTabs.tabGroups.all.length, 1); assert.strictEqual(extHostEditorTabs.tabGroups.all.map(g => g.tabs).flat().length, 3); assert.strictEqual(extHostEditorTabs.tabGroups.all[0]?.tabs[0]?.label, 'label2'); // Move tab 3 to index 1 extHostEditorTabs.$acceptTabOperation({ groupId: 12, index: 1, oldIndex: 2, kind: TabModelOperationKind.TAB_MOVE, tabDto: tab3 }); assert.strictEqual(extHostEditorTabs.tabGroups.all.length, 1); assert.strictEqual(extHostEditorTabs.tabGroups.all.map(g => g.tabs).flat().length, 3); assert.strictEqual(extHostEditorTabs.tabGroups.all[0]?.tabs[1]?.label, 'label3'); assert.strictEqual(extHostEditorTabs.tabGroups.all[0]?.tabs[0]?.label, 'label2'); assert.strictEqual(extHostEditorTabs.tabGroups.all[0]?.tabs[2]?.label, 'label1'); }); });
the_stack
import * as tfc from '@tensorflow/tfjs-core'; import {Tensor, util} from '@tensorflow/tfjs-core'; import {Activation} from '../activations'; import * as K from '../backend/tfjs_backend'; import {checkDataFormat, checkPaddingMode} from '../common'; import {Constraint} from '../constraints'; import {InputSpec} from '../engine/topology'; import {AttributeError, NotImplementedError, ValueError} from '../errors'; import {Initializer} from '../initializers'; import {DataFormat, DataType, PaddingMode, Shape} from '../keras_format/common'; import {Regularizer} from '../regularizers'; import {Kwargs} from '../types'; import {convOutputLength, normalizeArray} from '../utils/conv_utils'; import {assertPositiveInteger} from '../utils/generic_utils'; import {getExactlyOneShape} from '../utils/types_utils'; import {BaseRNNLayerArgs, generateDropoutMask, LSTMCell, LSTMCellLayerArgs, LSTMLayerArgs, RNN, RNNCell, RNNLayerArgs, SimpleRNNCellLayerArgs} from './recurrent'; declare interface ConvRNN2DCellArgs extends Omit<SimpleRNNCellLayerArgs, 'units'> { /** * The dimensionality of the output space (i.e. the number of filters in the * convolution). */ filters: number; /** * The dimensions of the convolution window. If kernelSize is a number, the * convolutional window will be square. */ kernelSize: number|number[]; /** * The strides of the convolution in each dimension. If strides is a number, * strides in both dimensions are equal. * * Specifying any stride value != 1 is incompatible with specifying any * `dilationRate` value != 1. */ strides?: number|number[]; /** * Padding mode. */ padding?: PaddingMode; /** * Format of the data, which determines the ordering of the dimensions in * the inputs. * * `channels_last` corresponds to inputs with shape * `(batch, ..., channels)` * * `channels_first` corresponds to inputs with shape `(batch, channels, * ...)`. * * Defaults to `channels_last`. */ dataFormat?: DataFormat; /** * The dilation rate to use for the dilated convolution in each dimension. * Should be an integer or array of two or three integers. * * Currently, specifying any `dilationRate` value != 1 is incompatible with * specifying any `strides` value != 1. */ dilationRate?: number|[number]|[number, number]; } abstract class ConvRNN2DCell extends RNNCell { readonly filters: number; readonly kernelSize: number[]; readonly strides: number[]; readonly padding: PaddingMode; readonly dataFormat: DataFormat; readonly dilationRate: number[]; readonly activation: Activation; readonly useBias: boolean; readonly kernelInitializer: Initializer; readonly recurrentInitializer: Initializer; readonly biasInitializer: Initializer; readonly kernelConstraint: Constraint; readonly recurrentConstraint: Constraint; readonly biasConstraint: Constraint; readonly kernelRegularizer: Regularizer; readonly recurrentRegularizer: Regularizer; readonly biasRegularizer: Regularizer; readonly dropout: number; readonly recurrentDropout: number; } declare interface ConvRNN2DLayerArgs extends BaseRNNLayerArgs, ConvRNN2DCellArgs {} /** * Base class for convolutional-recurrent layers. */ class ConvRNN2D extends RNN { /** @nocollapse */ static className = 'ConvRNN2D'; readonly cell: ConvRNN2DCell; constructor(args: ConvRNN2DLayerArgs) { if (args.unroll) { throw new NotImplementedError( 'Unrolling is not possible with convolutional RNNs.'); } if (Array.isArray(args.cell)) { throw new NotImplementedError( 'It is not possible at the moment to stack convolutional cells.'); } super(args as RNNLayerArgs); this.inputSpec = [new InputSpec({ndim: 5})]; } call(inputs: Tensor|Tensor[], kwargs: Kwargs): Tensor|Tensor[] { return tfc.tidy(() => { if (this.cell.dropoutMask != null) { tfc.dispose(this.cell.dropoutMask); this.cell.dropoutMask = null; } if (this.cell.recurrentDropoutMask != null) { tfc.dispose(this.cell.recurrentDropoutMask); this.cell.recurrentDropoutMask = null; } if (kwargs && kwargs['constants']) { throw new ValueError('ConvRNN2D cell does not support constants'); } const mask = kwargs == null ? null : kwargs['mask']; const training = kwargs == null ? null : kwargs['training']; const initialState: Tensor[] = kwargs == null ? null : kwargs['initialState']; return super.call(inputs, {mask, training, initialState}); }); } computeOutputShape(inputShape: Shape): Shape|Shape[] { let outShape: Shape = this.computeSingleOutputShape(inputShape); if (!this.returnSequences) { outShape = [outShape[0], ...outShape.slice(2)]; } if (this.returnState) { outShape = [outShape, ...Array(2).fill([inputShape[0], ...outShape.slice(-3)])]; } return outShape; } getInitialState(inputs: tfc.Tensor): tfc.Tensor[] { return tfc.tidy(() => { const {stateSize} = this.cell; const inputShape = inputs.shape; const outputShape = this.computeSingleOutputShape(inputShape); const stateShape = [outputShape[0], ...outputShape.slice(2)]; const initialState = tfc.zeros(stateShape); if (Array.isArray(stateSize)) { return Array(stateSize.length).fill(initialState); } return [initialState]; }); } resetStates(states?: Tensor|Tensor[], training = false): void { tfc.tidy(() => { if (!this.stateful) { throw new AttributeError( 'Cannot call resetStates() on an RNN Layer that is not stateful.'); } const inputShape = this.inputSpec[0].shape; const outputShape = this.computeSingleOutputShape(inputShape); const stateShape = [outputShape[0], ...outputShape.slice(2)]; const batchSize = inputShape[0]; if (batchSize == null) { throw new ValueError( 'If an RNN is stateful, it needs to know its batch size. Specify ' + 'the batch size of your input tensors: \n' + '- If using a Sequential model, specify the batch size by ' + 'passing a `batchInputShape` option to your first layer.\n' + '- If using the functional API, specify the batch size by ' + 'passing a `batchShape` option to your Input layer.'); } // Initialize state if null. if (this.getStates() == null) { if (Array.isArray(this.cell.stateSize)) { this.states_ = this.cell.stateSize.map(() => tfc.zeros(stateShape)); } else { this.states_ = [tfc.zeros(stateShape)]; } } else if (states == null) { // Dispose old state tensors. tfc.dispose(this.states_); // For stateful RNNs, fully dispose kept old states. if (this.keptStates != null) { tfc.dispose(this.keptStates); this.keptStates = []; } if (Array.isArray(this.cell.stateSize)) { this.states_ = this.cell.stateSize.map(() => tfc.zeros(stateShape)); } else { this.states_[0] = tfc.zeros(stateShape); } } else { if (!Array.isArray(states)) { states = [states]; } if (states.length !== this.states_.length) { throw new ValueError( `Layer ${this.name} expects ${this.states_.length} state(s), ` + `but it received ${states.length} state value(s). Input ` + `received: ${states}`); } if (training) { // Store old state tensors for complete disposal later, i.e., during // the next no-arg call to this method. We do not dispose the old // states immediately because that BPTT (among other things) require // them. this.keptStates.push(this.states_.slice()); } else { tfc.dispose(this.states_); } for (let index = 0; index < this.states_.length; ++index) { const value = states[index]; const expectedShape = stateShape; if (!util.arraysEqual(value.shape, expectedShape)) { throw new ValueError( `State ${index} is incompatible with layer ${this.name}: ` + `expected shape=${expectedShape}, received shape=${ value.shape}`); } this.states_[index] = value; } } this.states_ = this.states_.map(state => tfc.keep(state.clone())); }); } protected computeSingleOutputShape(inputShape: Shape): Shape { const {dataFormat, filters, kernelSize, padding, strides, dilationRate} = this.cell; const isChannelsFirst = dataFormat === 'channelsFirst'; const h = inputShape[isChannelsFirst ? 3 : 2]; const w = inputShape[isChannelsFirst ? 4 : 3]; const hOut = convOutputLength( h, kernelSize[0], padding, strides[0], dilationRate[0]); const wOut = convOutputLength( w, kernelSize[1], padding, strides[1], dilationRate[1]); const outShape: Shape = [ ...inputShape.slice(0, 2), ...(isChannelsFirst ? [filters, hOut, wOut] : [hOut, wOut, filters]) ]; return outShape; } } export declare interface ConvLSTM2DCellArgs extends Omit<LSTMCellLayerArgs, 'units'>, ConvRNN2DCellArgs {} export class ConvLSTM2DCell extends LSTMCell implements ConvRNN2DCell { /** @nocollapse */ static className = 'ConvLSTM2DCell'; readonly filters: number; readonly kernelSize: number[]; readonly strides: number[]; readonly padding: PaddingMode; readonly dataFormat: DataFormat; readonly dilationRate: number[]; constructor(args: ConvLSTM2DCellArgs) { const { filters, kernelSize, strides, padding, dataFormat, dilationRate, } = args; super({...args, units: filters}); this.filters = filters; assertPositiveInteger(this.filters, 'filters'); this.kernelSize = normalizeArray(kernelSize, 2, 'kernelSize'); this.kernelSize.forEach(size => assertPositiveInteger(size, 'kernelSize')); this.strides = normalizeArray(strides || 1, 2, 'strides'); this.strides.forEach(stride => assertPositiveInteger(stride, 'strides')); this.padding = padding || 'valid'; checkPaddingMode(this.padding); this.dataFormat = dataFormat || 'channelsLast'; checkDataFormat(this.dataFormat); this.dilationRate = normalizeArray(dilationRate || 1, 2, 'dilationRate'); this.dilationRate.forEach( rate => assertPositiveInteger(rate, 'dilationRate')); } public build(inputShape: Shape|Shape[]): void { inputShape = getExactlyOneShape(inputShape); const channelAxis = this.dataFormat === 'channelsFirst' ? 1 : inputShape.length - 1; if (inputShape[channelAxis] == null) { throw new ValueError( `The channel dimension of the input should be defined. ` + `Found ${inputShape[channelAxis]}`); } const inputDim = inputShape[channelAxis]; const numOfKernels = 4; const kernelShape = this.kernelSize.concat([inputDim, this.filters * numOfKernels]); this.kernel = this.addWeight( 'kernel', kernelShape, null, this.kernelInitializer, this.kernelRegularizer, true, this.kernelConstraint); const recurrentKernelShape = this.kernelSize.concat([this.filters, this.filters * numOfKernels]); this.recurrentKernel = this.addWeight( 'recurrent_kernel', recurrentKernelShape, null, this.recurrentInitializer, this.recurrentRegularizer, true, this.recurrentConstraint); if (this.useBias) { let biasInitializer: Initializer; if (this.unitForgetBias) { const init = this.biasInitializer; const filters = this.filters; biasInitializer = new (class CustomInit extends Initializer { /** @nocollapse */ static className = 'CustomInit'; apply(shape: Shape, dtype?: DataType): tfc.Tensor { const biasI = init.apply([filters]); const biasF = tfc.ones([filters]); const biasCAndO = init.apply([filters * 2]); return K.concatenate([biasI, biasF, biasCAndO]); } })(); } else { biasInitializer = this.biasInitializer; } this.bias = this.addWeight( 'bias', [this.filters * numOfKernels], null, biasInitializer, this.biasRegularizer, true, this.biasConstraint); } this.built = true; } call(inputs: tfc.Tensor[], kwargs: Kwargs): tfc.Tensor[] { return tfc.tidy(() => { if (inputs.length !== 3) { throw new ValueError( `ConvLSTM2DCell expects 3 input Tensors (inputs, h, c), got ` + `${inputs.length}.`); } const training = kwargs['training'] || false; const x = inputs[0]; // Current input const hTMinus1 = inputs[1]; // Previous memory state. const cTMinus1 = inputs[2]; // Previous carry state. const numOfKernels = 4; type DropoutMasks = [tfc.Tensor, tfc.Tensor, tfc.Tensor, tfc.Tensor]; if (0 < this.dropout && this.dropout < 1 && this.dropoutMask == null) { this.dropoutMask = generateDropoutMask({ ones: () => tfc.onesLike(x), rate: this.dropout, training, count: numOfKernels, dropoutFunc: this.dropoutFunc }) as tfc.Tensor[]; } const dropoutMask = this.dropoutMask as DropoutMasks; const applyDropout = (x: tfc.Tensor, mask: tfc.Tensor[], index: number) => { if (!mask || !mask[index]) { return x; } return tfc.mul(mask[index], x); }; let xI = applyDropout(x, dropoutMask, 0); let xF = applyDropout(x, dropoutMask, 1); let xC = applyDropout(x, dropoutMask, 2); let xO = applyDropout(x, dropoutMask, 3); if (0 < this.recurrentDropout && this.recurrentDropout < 1 && this.recurrentDropoutMask == null) { this.recurrentDropoutMask = generateDropoutMask({ ones: () => tfc.onesLike(hTMinus1), rate: this.recurrentDropout, training, count: numOfKernels, dropoutFunc: this.dropoutFunc }) as tfc.Tensor[]; } const recDropoutMask = this.recurrentDropoutMask as DropoutMasks; let hI = applyDropout(hTMinus1, recDropoutMask, 0); let hF = applyDropout(hTMinus1, recDropoutMask, 1); let hC = applyDropout(hTMinus1, recDropoutMask, 2); let hO = applyDropout(hTMinus1, recDropoutMask, 3); const kernelChannelAxis = 3; const [kernelI, kernelF, kernelC, kernelO]: tfc.Tensor[] = tfc.split(this.kernel.read(), numOfKernels, kernelChannelAxis); const [biasI, biasF, biasC, biasO]: tfc.Tensor[] = this.useBias ? tfc.split(this.bias.read(), numOfKernels) : [null, null, null, null]; xI = this.inputConv(xI, kernelI, biasI, this.padding); xF = this.inputConv(xF, kernelF, biasF, this.padding); xC = this.inputConv(xC, kernelC, biasC, this.padding); xO = this.inputConv(xO, kernelO, biasO, this.padding); const [recKernelI, recKernelF, recKernelC, recKernelO]: tfc.Tensor[] = tfc.split( this.recurrentKernel.read(), numOfKernels, kernelChannelAxis); hI = this.recurrentConv(hI, recKernelI); hF = this.recurrentConv(hF, recKernelF); hC = this.recurrentConv(hC, recKernelC); hO = this.recurrentConv(hO, recKernelO); const i = this.recurrentActivation.apply(tfc.add(xI, hI)); const f = this.recurrentActivation.apply(tfc.add(xF, hF)); const c = tfc.add( tfc.mul(f, cTMinus1), tfc.mul(i, this.activation.apply(tfc.add(xC, hC)))); const h = tfc.mul( this.recurrentActivation.apply(tfc.add(xO, hO)), this.activation.apply(c)); return [h, h, c]; }); } getConfig(): tfc.serialization.ConfigDict { const {'units': _, ...baseConfig} = super.getConfig(); const config: tfc.serialization.ConfigDict = { filters: this.filters, kernelSize: this.kernelSize, padding: this.padding, dataFormat: this.dataFormat, dilationRate: this.dilationRate, strides: this.strides, }; return {...baseConfig, ...config}; } inputConv(x: Tensor, w: Tensor, b?: Tensor, padding?: PaddingMode) { const out = tfc.conv2d( x as tfc.Tensor3D, w as tfc.Tensor4D, this.strides as [number, number], (padding || 'valid') as 'same' | 'valid', this.dataFormat === 'channelsFirst' ? 'NCHW' : 'NHWC', this.dilationRate as [number, number]); if (b) { return K.biasAdd(out, b, this.dataFormat) as tfc.Tensor3D; } return out; } recurrentConv(x: Tensor, w: Tensor) { const strides = 1; return tfc.conv2d( x as tfc.Tensor3D, w as tfc.Tensor4D, strides, 'same', this.dataFormat === 'channelsFirst' ? 'NCHW' : 'NHWC'); } } tfc.serialization.registerClass(ConvLSTM2DCell); export declare interface ConvLSTM2DArgs extends Omit<LSTMLayerArgs, 'units'|'cell'>, ConvRNN2DLayerArgs {} export class ConvLSTM2D extends ConvRNN2D { /** @nocollapse */ static className = 'ConvLSTM2D'; constructor(args: ConvLSTM2DArgs) { const cell = new ConvLSTM2DCell(args); super({...args, cell} as ConvRNN2DLayerArgs); } /** @nocollapse */ static fromConfig<T extends tfc.serialization.Serializable>( cls: tfc.serialization.SerializableConstructor<T>, config: tfc.serialization.ConfigDict): T { return new cls(config); } } tfc.serialization.registerClass(ConvLSTM2D);
the_stack
// @lib: es5 // // Copyright (c) Microsoft Corporation. All rights reserved. // // Licensed under the Apache License, Version 2.0 (the "License"); // you may not use this file except in compliance with the License. // You may obtain a copy of the License at // http://www.apache.org/licenses/LICENSE-2.0 // // Unless required by applicable law or agreed to in writing, software // distributed under the License is distributed on an "AS IS" BASIS, // WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. // See the License for the specific language governing permissions and // limitations under the License. // ///<reference path='..\compiler\io.ts'/> ///<reference path='..\compiler\typescript.ts'/> ///<reference path='..\services\typescriptServices.ts' /> ///<reference path='diff.ts'/> declare var assert: Harness.Assert; declare var it; declare var describe; declare var run; declare var IO: IIO; declare var __dirname; // Node-specific function switchToForwardSlashes(path: string) { return path.replace(/\\/g, "/"); } function filePath(fullPath: string) { fullPath = switchToForwardSlashes(fullPath); var components = fullPath.split("/"); var path: string[] = components.slice(0, components.length - 1); return path.join("/") + "/"; } var typescriptServiceFileName = filePath(IO.getExecutingFilePath()) + "typescriptServices.js"; var typescriptServiceFile = IO.readFile(typescriptServiceFileName); if (typeof ActiveXObject === "function") { eval(typescriptServiceFile); } else if (typeof require === "function") { var vm = require('vm'); vm.runInThisContext(typescriptServiceFile, 'typescriptServices.js'); } else { throw new Error('Unknown context'); } declare module process { export function nextTick(callback: () => any): void; export function on(event: string, listener: Function); } module Harness { // Settings export var userSpecifiedroot = ""; var global = <any>Function("return this").call(null); export var usePull = false; export interface ITestMetadata { id: string; desc: string; pass: boolean; perfResults: { mean: number; min: number; max: number; stdDev: number; trials: number[]; }; } export interface IScenarioMetadata { id: string; desc: string; pass: boolean; bugs: string[]; } // Assert functions export module Assert { export var bugIds: string[] = []; export var throwAssertError = (error: Error) => { throw error; }; // Marks that the current scenario is impacted by a bug export function bug(id: string) { if (bugIds.indexOf(id) < 0) { bugIds.push(id); } } // If there are any bugs in the test code, mark the scenario as impacted appropriately export function bugs(content: string) { var bugs = content.match(/\bbug (\d+)/i); if (bugs) { bugs.forEach(bug => assert.bug(bug)); } } export function is(result: boolean, msg?: string) { if (!result) { throwAssertError(new Error(msg || "Expected true, got false.")); } } export function arrayLengthIs(arr: any[], length: number) { if (arr.length != length) { var actual = ''; arr.forEach(n => actual = actual + '\n ' + n.toString()); throwAssertError(new Error('Expected array to have ' + length + ' elements. Actual elements were:' + actual)); } } export function equal(actual, expected) { if (actual !== expected) { throwAssertError(new Error("Expected " + actual + " to equal " + expected)); } } export function notEqual(actual, expected) { if (actual === expected) { throwAssertError(new Error("Expected " + actual + " to *not* equal " + expected)); } } export function notNull(result) { if (result === null) { throwAssertError(new Error("Expected " + result + " to *not* be null")); } } export function compilerWarning(result: Compiler.CompilerResult, line: number, column: number, desc: string) { if (!result.isErrorAt(line, column, desc)) { var actual = ''; result.errors.forEach(err => { actual = actual + '\n ' + err.toString(); }); throwAssertError(new Error("Expected compiler warning at (" + line + ", " + column + "): " + desc + "\nActual errors follow: " + actual)); } } export function noDiff(text1, text2) { text1 = text1.replace(/^\s+|\s+$/g, "").replace(/\r\n?/g, "\n"); text2 = text2.replace(/^\s+|\s+$/g, "").replace(/\r\n?/g, "\n"); if (text1 !== text2) { var errorString = ""; var text1Lines = text1.split(/\n/); var text2Lines = text2.split(/\n/); for (var i = 0; i < text1Lines.length; i++) { if (text1Lines[i] !== text2Lines[i]) { errorString += "Difference at line " + (i + 1) + ":\n"; errorString += " Left File: " + text1Lines[i] + "\n"; errorString += " Right File: " + text2Lines[i] + "\n\n"; } } throwAssertError(new Error(errorString)); } } export function arrayContains(arr: any[], contains: any[]) { var found; for (var i = 0; i < contains.length; i++) { found = false; for (var j = 0; j < arr.length; j++) { if (arr[j] === contains[i]) { found = true; break; } } if (!found) { throwAssertError(new Error("Expected array to contain \"" + contains[i] + "\"")); } } } export function arrayContainsOnce(arr: any[], filter: (item: any) => boolean) { var foundCount = 0; for (var i = 0; i < arr.length; i++) { if (filter(arr[i])) { foundCount++; } } if (foundCount !== 1) { throwAssertError(new Error("Expected array to match element only once (instead of " + foundCount + " times)")); } } } /** Splits the given string on \r\n or on only \n if that fails */ export function splitContentByNewlines(content: string) { // Split up the input file by line // Note: IE JS engine incorrectly handles consecutive delimiters here when using RegExp split, so // we have to string-based splitting instead and try to figure out the delimiting chars var lines = content.split('\r\n'); if (lines.length === 1) { lines = content.split('\n'); } return lines; } /** Reads a file under /tests */ export function readFile(path: string) { if (path.indexOf('tests') < 0) { path = "tests/" + path; } var content = IO.readFile(Harness.userSpecifiedroot + path); if (content == null) { throw new Error("failed to read file at: '" + Harness.userSpecifiedroot + path + "'"); } return content; } // Logger export interface ILogger { start: (fileName?: string, priority?: number) => void; end: (fileName?: string) => void; scenarioStart: (scenario: IScenarioMetadata) => void; scenarioEnd: (scenario: IScenarioMetadata, error?: Error) => void; testStart: (test: ITestMetadata) => void; pass: (test: ITestMetadata) => void; bug: (test: ITestMetadata) => void; fail: (test: ITestMetadata) => void; error: (test: ITestMetadata, error: Error) => void; comment: (comment: string) => void; verify: (test: ITestMetadata, passed: boolean, actual: any, expected: any, message: string) => void; } export class Logger implements ILogger { public start(fileName?: string, priority?: number) { } public end(fileName?: string) { } public scenarioStart(scenario: IScenarioMetadata) { } public scenarioEnd(scenario: IScenarioMetadata, error?: Error) { } public testStart(test: ITestMetadata) { } public pass(test: ITestMetadata) { } public bug(test: ITestMetadata) { } public fail(test: ITestMetadata) { } public error(test: ITestMetadata, error: Error) { } public comment(comment: string) { } public verify(test: ITestMetadata, passed: boolean, actual: any, expected: any, message: string) { } } // Logger-related functions var loggers: ILogger[] = []; export function registerLogger(logger: ILogger) { loggers.push(logger); } export function emitLog(field: string, ...params: any[]) { for (var i = 0; i < loggers.length; i++) { if (typeof loggers[i][field] === 'function') { loggers[i][field].apply(loggers[i], params); } } } // BDD Framework export interface IDone { (e?: Error): void; } export class Runnable { constructor(public description: string, public block: any) { } // The current stack of Runnable objects static currentStack: Runnable[] = []; // The error, if any, that occurred when running 'block' public error: Error = null; // Whether or not this object has any failures (including in its descendants) public passed = null; // A list of bugs impacting this object public bugs: string[] = []; // A list of all our child Runnables public children: Runnable[] = []; public addChild(child: Runnable): void { this.children.push(child); } /** Call function fn, which may take a done function and may possibly execute * asynchronously, calling done when finished. Returns true or false depending * on whether the function was asynchronous or not. */ public call(fn: (done?: IDone) => void , done: IDone) { var isAsync = true; try { if (fn.length === 0) { // No async. fn(); done(); return false; } else { // Possibly async Runnable.pushGlobalErrorHandler(done); fn(function () { isAsync = false; // If we execute synchronously, this will get called before the return below. Runnable.popGlobalErrorHandler(); done(); }); return isAsync; } } catch (e) { done(e); return false; } } public run(done: IDone) { } public runBlock(done: IDone) { return this.call(this.block, done); } public runChild(index: number, done: IDone) { return this.call(<any>((done) => this.children[index].run(done)), done); } static errorHandlerStack: { (e: Error): void; }[] = []; static pushGlobalErrorHandler(done: IDone) { errorHandlerStack.push(function (e) { done(e); }); } static popGlobalErrorHandler() { errorHandlerStack.pop(); } static handleError(e: Error) { if (errorHandlerStack.length === 0) { IO.printLine('Global error: ' + e); } else { errorHandlerStack[errorHandlerStack.length - 1](e); } } } export class TestCase extends Runnable { public description: string; public block; constructor(description: string, block: any) { super(description, block); this.description = description; this.block = block; } public addChild(child: Runnable): void { throw new Error("Testcases may not be nested inside other testcases"); } /** Run the test case block and fail the test if it raised an error. If no error is raised, the test passes. */ public run(done: IDone) { var that = this; Runnable.currentStack.push(this); emitLog('testStart', { desc: this.description }); if (this.block) { var async = this.runBlock(<any>function (e) { if (e) { that.passed = false; that.error = e; emitLog('error', { desc: this.description, pass: false }, e); } else { that.passed = true; emitLog('pass', { desc: this.description, pass: true }); } Runnable.currentStack.pop(); done() }); } } } export class Scenario extends Runnable { public description: string; public block; constructor(description: string, block: any) { super(description, block); this.description = description; this.block = block; } /** Run the block, and if the block doesn't raise an error, run the children. */ public run(done: IDone) { var that = this; Runnable.currentStack.push(this); emitLog('scenarioStart', { desc: this.description }); var async = this.runBlock(<any>function (e) { Runnable.currentStack.pop(); if (e) { that.passed = false; that.error = e; var metadata: IScenarioMetadata = { id: undefined, desc: this.description, pass: false, bugs: assert.bugIds }; // Report all bugs affecting this scenario assert.bugIds.forEach(desc => emitLog('bug', metadata, desc)); emitLog('scenarioEnd', metadata, e); done(); } else { that.passed = true; // so far so good. that.runChildren(done); } }); } /** Run the children of the scenario (other scenarios and test cases). If any fail, * set this scenario to failed. Synchronous tests will run synchronously without * adding stack frames. */ public runChildren(done: IDone, index = 0) { var that = this; var async = false; for (; index < this.children.length; index++) { async = this.runChild(index, <any>function (e) { that.passed = that.passed && that.children[index].passed; if (async) that.runChildren(done, index + 1); }); if (async) return; } var metadata: IScenarioMetadata = { id: undefined, desc: this.description, pass: this.passed, bugs: assert.bugIds }; // Report all bugs affecting this scenario assert.bugIds.forEach(desc => emitLog('bug', metadata, desc)); emitLog('scenarioEnd', metadata); done(); } } export class Run extends Runnable { constructor() { super('Test Run', null); } public run() { emitLog('start'); this.runChildren(); } public runChildren(index = 0) { var async = false; var that = this; for (; index < this.children.length; index++) { // Clear out bug descriptions assert.bugIds = []; async = this.runChild(index, <any>function (e) { if (async) { that.runChildren(index + 1); } }); if (async) { return; } } Perf.runBenchmarks(); emitLog('end'); } } // Performance test export module Perf { export module Clock { export var now: () => number; export var resolution: number; declare module WScript { export function InitializeProjection(); } declare module TestUtilities { export function QueryPerformanceCounter(): number; export function QueryPerformanceFrequency(): number; } if (typeof WScript !== "undefined" && typeof global['WScript'].InitializeProjection !== "undefined") { // Running in JSHost. global['WScript'].InitializeProjection(); now = function () { return TestUtilities.QueryPerformanceCounter(); } resolution = TestUtilities.QueryPerformanceFrequency(); } else { now = function () { return Date.now(); } resolution = 1000; } } export class Timer { public startTime; public time = 0; public start() { this.time = 0; this.startTime = Clock.now(); } public end() { // Set time to MS. this.time = (Clock.now() - this.startTime) / Clock.resolution * 1000; } } export class Dataset { public data: number[] = []; public add(value: number) { this.data.push(value); } public mean() { var sum = 0; for (var i = 0; i < this.data.length; i++) { sum += this.data[i]; } return sum / this.data.length; } public min() { var min = this.data[0]; for (var i = 1; i < this.data.length; i++) { if (this.data[i] < min) { min = this.data[i]; } } return min; } public max() { var max = this.data[0]; for (var i = 1; i < this.data.length; i++) { if (this.data[i] > max) { max = this.data[i]; } } return max; } public stdDev() { var sampleMean = this.mean(); var sumOfSquares = 0; for (var i = 0; i < this.data.length; i++) { sumOfSquares += Math.pow(this.data[i] - sampleMean, 2); } return Math.sqrt(sumOfSquares / this.data.length); } } // Base benchmark class with some defaults. export class Benchmark { public iterations = 10; public description = ""; public bench(subBench?: () => void ) { } public before() { } public beforeEach() { } public after() { } public afterEach() { } public results: { [x: string]: Dataset; } = <{ [x: string]: Dataset; }>{}; public addTimingFor(name: string, timing: number) { this.results[name] = this.results[name] || new Dataset(); this.results[name].add(timing); } } export var benchmarks: { new (): Benchmark; }[] = []; var timeFunction: ( benchmark: Benchmark, description?: string, name?: string, f?: (bench?: { (): void; }) => void ) => void; timeFunction = function ( benchmark: Benchmark, description: string = benchmark.description, name: string = '', f = benchmark.bench ): void { var t = new Timer(); t.start(); var subBenchmark = function (name, f): void { timeFunction(benchmark, description, name, f); } f.call(benchmark, subBenchmark); t.end(); benchmark.addTimingFor(name, t.time); } export function runBenchmarks() { for (var i = 0; i < benchmarks.length; i++) { var b = new benchmarks[i](); var t = new Timer(); b.before(); for (var j = 0; j < b.iterations; j++) { b.beforeEach(); timeFunction(b); b.afterEach(); } b.after(); for (var prop in b.results) { var description = b.description + (prop ? ": " + prop : ''); emitLog('testStart', { desc: description }); emitLog('pass', { desc: description, pass: true, perfResults: { mean: b.results[prop].mean(), min: b.results[prop].min(), max: b.results[prop].max(), stdDev: b.results[prop].stdDev(), trials: b.results[prop].data } }); } } } // Replace with better type when classes are assignment compatible with // the below type. // export function addBenchmark(BenchmarkClass: {new(): Benchmark;}) { export function addBenchmark(BenchmarkClass: any) { benchmarks.push(BenchmarkClass); } } /** Functionality for compiling TypeScript code */ export module Compiler { /** Aggregate various writes into a single array of lines. Useful for passing to the * TypeScript compiler to fill with source code or errors. */ export class WriterAggregator implements ITextWriter { public lines: string[] = []; public currentLine = ""; public Write(str) { this.currentLine += str; } public WriteLine(str) { this.lines.push(this.currentLine + str); this.currentLine = ""; } public Close() { if (this.currentLine.length > 0) { this.lines.push(this.currentLine); } this.currentLine = ""; } public reset() { this.lines = []; this.currentLine = ""; } } /** Mimics having multiple files, later concatenated to a single file. */ export class EmitterIOHost implements TypeScript.EmitterIOHost { private fileCollection = {}; /** create file gets the whole path to create, so this works as expected with the --out parameter */ public createFile(s: string, useUTF8?: boolean): ITextWriter { if (this.fileCollection[s]) { return <ITextWriter>this.fileCollection[s]; } var writer = new Harness.Compiler.WriterAggregator(); this.fileCollection[s] = writer; return writer; } public directoryExists(s: string) { return false; } public fileExists(s: string) { return typeof this.fileCollection[s] !== 'undefined'; } public resolvePath(s: string) { return s; } public reset() { this.fileCollection = {}; } public toArray(): { filename: string; file: WriterAggregator; }[] { var result: { filename: string; file: WriterAggregator; }[] = []; for (var p in this.fileCollection) { if (this.fileCollection.hasOwnProperty(p)) { var current = <Harness.Compiler.WriterAggregator>this.fileCollection[p]; if (current.lines.length > 0) { if (p !== '0.js') { current.lines.unshift('////[' + p + ']'); } result.push({ filename: p, file: this.fileCollection[p] }); } } } return result; } } var libFolder: string = global['WScript'] ? TypeScript.filePath(global['WScript'].ScriptFullName) : (__dirname + '/'); export var libText = IO ? IO.readFile(libFolder + "lib.d.ts") : ''; var stdout = new EmitterIOHost(); var stderr = new WriterAggregator(); export function isDeclareFile(filename: string) { return /\.d\.ts$/.test(filename); } export function makeDefaultCompilerForTest(c?: TypeScript.TypeScriptCompiler) { var compiler = c || new TypeScript.TypeScriptCompiler(stderr); compiler.parser.errorRecovery = true; compiler.settings.codeGenTarget = TypeScript.CodeGenTarget.ES5; compiler.settings.controlFlow = true; compiler.settings.controlFlowUseDef = true; if (Harness.usePull) { compiler.settings.usePull = true; compiler.settings.useFidelity = true; } compiler.parseEmitOption(stdout); TypeScript.moduleGenTarget = TypeScript.ModuleGenTarget.Synchronous; compiler.addUnit(Harness.Compiler.libText, "lib.d.ts", true); return compiler; } var compiler: TypeScript.TypeScriptCompiler; recreate(); // pullUpdateUnit is sufficient if an existing unit is updated, if a new unit is added we need to do a full typecheck var needsFullTypeCheck = true; export function compile(code?: string, filename?: string) { if (usePull) { if (needsFullTypeCheck) { compiler.pullTypeCheck(true); needsFullTypeCheck = false; } else { // requires unit to already exist in the compiler compiler.pullUpdateUnit(new TypeScript.StringSourceText(""), filename, true); compiler.pullUpdateUnit(new TypeScript.StringSourceText(code), filename, true); } } else { compiler.reTypeCheck(); } } // Types export class Type { constructor(public type, public code, public identifier) { } public normalizeToArray(arg: any) { if ((Array.isArray && Array.isArray(arg)) || arg instanceof Array) return arg; return [arg]; } public compilesOk(testCode): boolean { var errors = null; compileString(testCode, 'test.ts', function (compilerResult) { errors = compilerResult.errors; }) return errors.length === 0; } public isSubtypeOf(other: Type) { var testCode = 'class __test1__ {\n'; testCode += ' public test() {\n'; testCode += ' ' + other.code + ';\n'; testCode += ' return ' + other.identifier + ';\n'; testCode += ' }\n'; testCode += '}\n'; testCode += 'class __test2__ extends __test1__ {\n'; testCode += ' public test() {\n'; testCode += ' ' + this.code + ';\n'; testCode += ' return ' + other.identifier + ';\n'; testCode += ' }\n'; testCode += '}\n'; return this.compilesOk(testCode); } // TODO: Find an implementation of isIdenticalTo that works. //public isIdenticalTo(other: Type) { // var testCode = 'module __test1__ {\n'; // testCode += ' ' + this.code + ';\n'; // testCode += ' export var __val__ = ' + this.identifier + ';\n'; // testCode += '}\n'; // testCode += 'var __test1__val__ = __test1__.__val__;\n'; // testCode += 'module __test2__ {\n'; // testCode += ' ' + other.code + ';\n'; // testCode += ' export var __val__ = ' + other.identifier + ';\n'; // testCode += '}\n'; // testCode += 'var __test2__val__ = __test2__.__val__;\n'; // testCode += 'function __test__function__() { if(true) { return __test1__val__ }; return __test2__val__; }'; // return this.compilesOk(testCode); //} public assertSubtypeOf(others: any) { others = this.normalizeToArray(others); for (var i = 0; i < others.length; i++) { if (!this.isSubtypeOf(others[i])) { throw new Error("Expected " + this.type + " to be a subtype of " + others[i].type); } } } public assertNotSubtypeOf(others: any) { others = this.normalizeToArray(others); for (var i = 0; i < others.length; i++) { if (this.isSubtypeOf(others[i])) { throw new Error("Expected " + this.type + " to be a subtype of " + others[i].type); } } } //public assertIdenticalTo(other: Type) { // if (!this.isIdenticalTo(other)) { // throw new Error("Expected " + this.type + " to be identical to " + other.type); // } //} //public assertNotIdenticalTo(other: Type) { // if (!this.isIdenticalTo(other)) { // throw new Error("Expected " + this.type + " to not be identical to " + other.type); // } //} public isAssignmentCompatibleWith(other: Type) { var testCode = 'module __test1__ {\n'; testCode += ' ' + this.code + ';\n'; testCode += ' export var __val__ = ' + this.identifier + ';\n'; testCode += '}\n'; testCode += 'var __test1__val__ = __test1__.__val__;\n'; testCode += 'module __test2__ {\n'; testCode += ' export ' + other.code + ';\n'; testCode += ' export var __val__ = ' + other.identifier + ';\n'; testCode += '}\n'; testCode += 'var __test2__val__ = __test2__.__val__;\n'; testCode += '__test2__val__ = __test1__val__;'; return this.compilesOk(testCode); } public assertAssignmentCompatibleWith(others: any) { others = this.normalizeToArray(others); for (var i = 0; i < others.length; i++) { var other = others[i]; if (!this.isAssignmentCompatibleWith(other)) { throw new Error("Expected " + this.type + " to be assignment compatible with " + other.type); } } } public assertNotAssignmentCompatibleWith(others: any) { others = this.normalizeToArray(others); for (var i = 0; i < others.length; i++) { var other = others[i]; if (this.isAssignmentCompatibleWith(other)) { throw new Error("Expected " + this.type + " to not be assignment compatible with " + other.type); } } } public assertThisCanBeAssignedTo(desc: string, these: any[], notThese: any[]) { it(desc + " is assignable to ", () => { this.assertAssignmentCompatibleWith(these); }); it(desc + " not assignable to ", () => { this.assertNotAssignmentCompatibleWith(notThese); }); } } export class TypeFactory { public any: Type; public number: Type; public string: Type; public boolean: Type; constructor() { this.any = this.get('var x : any', 'x'); this.number = this.get('var x : number', 'x'); this.string = this.get('var x : string', 'x'); this.boolean = this.get('var x : boolean', 'x'); } public get (code: string, target: any) { var targetIdentifier = ''; var targetPosition = -1; if (typeof target === "string") { targetIdentifier = target; } else if (typeof target === "number") { targetPosition = target; } else { throw new Error("Expected string or number not " + (typeof target)); } var errors = null; compileString(code, 'test.ts', function (compilerResult) { errors = compilerResult.errors; }) if (errors.length > 0) throw new Error("Type definition contains errors: " + errors.join(",")); var matchingIdentifiers: Type[] = []; if (!usePull) { // This will find the requested identifier in the first script where it's present, a naive search of each member in each script, // which means this won't play nicely if the same identifier is used in multiple units, but it will enable this to work on multi-file tests. // m = 1 because the first script will always be lib.d.ts which we don't want to search. for (var m = 1; m < compiler.scripts.members.length; m++) { var script = compiler.scripts.members[m]; var enclosingScopeContext = TypeScript.findEnclosingScopeAt(new TypeScript.NullLogger(), <TypeScript.Script>script, new TypeScript.StringSourceText(code), 0, false); var entries = new TypeScript.ScopeTraversal(compiler).getScopeEntries(enclosingScopeContext); for (var i = 0; i < entries.length; i++) { if (entries[i].name === targetIdentifier) { matchingIdentifiers.push(new Type(entries[i].type, code, targetIdentifier)); } } } } else { for (var m = 0; m < compiler.scripts.members.length; m++) { var script2 = <TypeScript.Script>compiler.scripts.members[m]; if (script2.locationInfo.filename !== 'lib.d.ts') { if (targetPosition > -1) { var tyInfo = compiler.pullGetTypeInfoAtPosition(targetPosition, script2); var name = this.getTypeInfoName(tyInfo.ast); var foundValue = new Type(tyInfo.typeInfo, code, name); if (!matchingIdentifiers.some(value => (value.identifier === foundValue.identifier) && (value.code === foundValue.code) && (value.type === foundValue.type))) { matchingIdentifiers.push(foundValue); } } else { for (var pos = 0; pos < code.length; pos++) { var tyInfo = compiler.pullGetTypeInfoAtPosition(pos, script2); var name = this.getTypeInfoName(tyInfo.ast); if (name === targetIdentifier) { var foundValue = new Type(tyInfo.typeInfo, code, targetIdentifier); if (!matchingIdentifiers.some(value => (value.identifier === foundValue.identifier) && (value.code === foundValue.code) && (value.type === foundValue.type))) { matchingIdentifiers.push(foundValue); } } } } } } } if (matchingIdentifiers.length === 0) { if (targetPosition > -1) { throw new Error("Could not find an identifier at position " + targetPosition); } else { throw new Error("Could not find an identifier " + targetIdentifier + " in any known scopes"); } } else if (matchingIdentifiers.length > 1) { throw new Error("Found multiple matching identifiers for " + target); } else { return matchingIdentifiers[0]; } } private getTypeInfoName(ast : TypeScript.AST) { var name = ''; switch (ast.nodeType) { case TypeScript.NodeType.Name: // Type Name? case TypeScript.NodeType.Null: case TypeScript.NodeType.List: case TypeScript.NodeType.Empty: case TypeScript.NodeType.EmptyExpr: case TypeScript.NodeType.Asg: case TypeScript.NodeType.True: case TypeScript.NodeType.False: case TypeScript.NodeType.ArrayLit: case TypeScript.NodeType.TypeRef: break; case TypeScript.NodeType.Super: name = (<any>ast).text; break; case TypeScript.NodeType.Regex: name = (<TypeScript.RegexLiteral>ast).text; break; case TypeScript.NodeType.QString: name = (<any>ast).text; break; case TypeScript.NodeType.NumberLit: name = (<TypeScript.NumberLiteral>ast).text; break; case TypeScript.NodeType.Return: //name = (<TypeScript.ReturnStatement>tyInfo.ast).returnExpression.actualText; // why is this complaining? break; case TypeScript.NodeType.InterfaceDeclaration: name = (<TypeScript.InterfaceDeclaration>ast).name.actualText; break; case TypeScript.NodeType.ModuleDeclaration: name = (<TypeScript.ModuleDeclaration>ast).name.actualText; break; case TypeScript.NodeType.ClassDeclaration: name = (<TypeScript.ClassDeclaration>ast).name.actualText; break; case TypeScript.NodeType.FuncDecl: name = !(<TypeScript.FuncDecl>ast).name ? "" : (<TypeScript.FuncDecl>ast).name.actualText; // name == null for lambdas break; default: // TODO: is there a reason to mess with all the special cases above and not just do this (ie take whatever property is there and works?) var a = <any>ast; name = (a.id) ? (a.id.actualText) : (a.name) ? a.name.actualText : (a.text) ? a.text : ''; break; } return name; } public isOfType(expr: string, expectedType: string) { var actualType = this.get('var _v_a_r_ = ' + expr, '_v_a_r_'); it('Expression "' + expr + '" is of type "' + expectedType + '"', function () { assert.equal(actualType.type, expectedType); }); } } /** Generates a .d.ts file for the given code * @param verifyNoDeclFile pass true when the given code should generate no decl file, false otherwise * @param unitName add the given code under thie name, else use '0.ts' * @param compilationContext a set of functions to be run before and after compiling this code for doing things like adding dependencies first * @param references the set of referenced files used by the given code */ export function generateDeclFile(code: string, verifyNoDeclFile: boolean, unitName?: string, compilationContext?: Harness.Compiler.CompilationContext, references?: TypeScript.IFileReference[]): string { reset(); compiler.settings.generateDeclarationFiles = true; var oldOutputOption = compiler.settings.outputOption; var oldEmitterIOHost = compiler.emitSettings.ioHost; try { if (compilationContext && compilationContext.preCompile) { compilationContext.preCompile(); } addUnit(code, unitName, false, false, references); compiler.reTypeCheck(); var outputs = {}; compiler.settings.outputOption = ""; compiler.parseEmitOption( { createFile: (fn: string) => { outputs[fn] = new Harness.Compiler.WriterAggregator(); return outputs[fn]; }, directoryExists: (path: string) => true, fileExists: (path: string) => true, resolvePath: (path: string) => path }); compiler.emitDeclarations(); var results: string = null; for (var fn in outputs) { if (fn.indexOf('.d.ts') >= 0) { var writer = <Harness.Compiler.WriterAggregator>outputs[fn]; writer.Close(); results = writer.lines.join('\n'); if (verifyNoDeclFile && results != "") { throw new Error('Compilation should not produce ' + fn); } } } if (results) { return results; } if (!verifyNoDeclFile) { throw new Error('Compilation did not produce .d.ts files'); } } finally { compiler.settings.generateDeclarationFiles = false; compiler.settings.outputOption = oldOutputOption; compiler.parseEmitOption(oldEmitterIOHost); if (compilationContext && compilationContext.postCompile) { compilationContext.postCompile(); } var uName = unitName || '0.ts'; updateUnit('', uName); } return ''; } /** Contains the code and errors of a compilation and some helper methods to check its status. */ export class CompilerResult { public code: string; public errors: CompilerError[]; /** @param fileResults an array of strings for the filename and an ITextWriter with its code */ constructor(public fileResults: { filename: string; file: WriterAggregator; }[], errorLines: string[], public scripts: TypeScript.Script[]) { var lines = []; fileResults.forEach(v => lines = lines.concat(v.file.lines)); this.code = lines.join("\n") this.errors = []; for (var i = 0; i < errorLines.length; i++) { if (Harness.usePull) { var err = <any>errorLines[i]; // TypeScript.PullError this.errors.push(new CompilerError(err.filename, 0, 0, err.message)); } else { var match = errorLines[i].match(/([^\(]*)\((\d+),(\d+)\):\s+((.*[\s\r\n]*.*)+)\s*$/); if (match) { this.errors.push(new CompilerError(match[1], parseFloat(match[2]), parseFloat(match[3]), match[4])); } else { WScript.Echo("non-match on: " + errorLines[i]); } } } } public isErrorAt(line: number, column: number, message: string) { for (var i = 0; i < this.errors.length; i++) { if (this.errors[i].line === line && this.errors[i].column === column && this.errors[i].message === message) return true; } return false; } } // Compiler Error. export class CompilerError { constructor(public file: string, public line: number, public column: number, public message: string) { } public toString() { return this.file + "(" + this.line + "," + this.column + "): " + this.message; } } /** Create a new instance of the compiler with default settings and lib.d.ts, then typecheck */ export function recreate() { compiler = makeDefaultCompilerForTest(); if (usePull) { compiler.pullTypeCheck(true); } else { compiler.typeCheck(); } } export function reset() { stdout.reset(); stderr.reset(); var files = compiler.units.map((value) => value.filename); for (var i = 0; i < files.length; i++) { var fname = files[i]; if(fname !== 'lib.d.ts') { updateUnit('', fname); } } compiler.errorReporter.hasErrors = false; } // Defines functions to invoke before compiling a piece of code and a post compile action intended to clean up the // effects of preCompile, preferably with something lighter weight than a full recreate() export interface CompilationContext { filename: string; preCompile: () => void; postCompile: () => void; } export function addUnit(code: string, unitName?: string, isResident?: boolean, isDeclareFile?: boolean, references?: TypeScript.IFileReference[]) { var script: TypeScript.Script = null; var uName = unitName || '0' + (isDeclareFile ? '.d.ts' : '.ts'); for (var i = 0; i < compiler.units.length; i++) { if (compiler.units[i].filename === uName) { updateUnit(code, uName); script = <TypeScript.Script>compiler.scripts.members[i]; } } if (!script) { // TODO: make this toggleable, shouldn't be necessary once typecheck bugs are cleaned up // but without it subsequent tests are treated as edits, making for somewhat useful stress testing // of persistent typecheck state //compiler.addUnit("", uName, isResident, references); // equivalent to compiler.deleteUnit(...) script = compiler.addUnit(code, uName, isResident, references); needsFullTypeCheck = true; } return script; } export function updateUnit(code: string, unitName: string, setRecovery?: boolean) { if (Harness.usePull) { compiler.pullUpdateUnit(new TypeScript.StringSourceText(code), unitName, setRecovery); } else { compiler.updateUnit(code, unitName, setRecovery); } } export function compileFile(path: string, callback: (res: CompilerResult) => void , settingsCallback?: (settings?: TypeScript.CompilationSettings) => void , context?: CompilationContext, references?: TypeScript.IFileReference[]) { path = switchToForwardSlashes(path); var filename = path.match(/[^\/]*$/)[0]; var code = readFile(path); compileUnit(code, filename, callback, settingsCallback, context, references); } export function compileUnit(code: string, filename: string, callback: (res: CompilerResult) => void , settingsCallback?: (settings?: TypeScript.CompilationSettings) => void , context?: CompilationContext, references?: TypeScript.IFileReference[]) { // not recursive function clone/* <T> */(source: any, target: any) { for (var prop in source) { target[prop] = source[prop]; } } var oldCompilerSettings = new TypeScript.CompilationSettings(); clone(compiler.settings, oldCompilerSettings); var oldEmitSettings = new TypeScript.EmitOptions(compiler.settings); clone(compiler.emitSettings, oldEmitSettings); var oldModuleGenTarget = TypeScript.moduleGenTarget; if (settingsCallback) { settingsCallback(compiler.settings); compiler.emitSettings = new TypeScript.EmitOptions(compiler.settings); } try { compileString(code, filename, callback, context, references); } finally { // If settingsCallback exists, assume that it modified the global compiler instance's settings in some way. // So that a test doesn't have side effects for tests run after it, restore the compiler settings to their previous state. if (settingsCallback) { compiler.settings = oldCompilerSettings; compiler.emitSettings = oldEmitSettings; TypeScript.moduleGenTarget = oldModuleGenTarget; } } } export function compileUnits(units: TestCaseParser.TestUnitData[], callback: (res: Compiler.CompilerResult) => void , settingsCallback?: () => void ) { var lastUnit = units[units.length - 1]; var unitName = switchToForwardSlashes(lastUnit.name).match(/[^\/]*$/)[0]; var dependencies = units.slice(0, units.length - 1); var compilationContext = Harness.Compiler.defineCompilationContextForTest(unitName, dependencies); compileUnit(lastUnit.content, unitName, callback, settingsCallback, compilationContext, lastUnit.references); } export function emitToOutfile(outfile: WriterAggregator) { compiler.emitToOutfile(outfile); } export function emit(ioHost: TypeScript.EmitterIOHost, usePullEmitter?: boolean) { compiler.emit(ioHost, usePullEmitter); } export function compileString(code: string, unitName: string, callback: (res: Compiler.CompilerResult) => void , context?: CompilationContext, references?: TypeScript.IFileReference[]) { var scripts: TypeScript.Script[] = []; reset(); if (context) { context.preCompile(); } var isDeclareFile = Harness.Compiler.isDeclareFile(unitName); // for single file tests just add them as using the old '0.ts' naming scheme var uName = context ? unitName : ((isDeclareFile) ? '0.d.ts' : '0.ts'); scripts.push(addUnit(code, uName, false, isDeclareFile, references)); compile(code, uName); var errors; if (usePull) { // TODO: no emit support with pull yet errors = compiler.pullGetErrorsForFile(uName); emit(stdout, true); } else { errors = stderr.lines; emit(stdout, false); //output decl file compiler.emitDeclarations(); } if (context) { context.postCompile(); } callback(new CompilerResult(stdout.toArray(), errors, scripts)); } /** Returns a set of functions which can be later executed to add and remove given dependencies to the compiler so that * a file can be successfully compiled. These functions will add/remove named units and code to the compiler for each dependency. */ export function defineCompilationContextForTest(filename: string, dependencies: TestCaseParser.TestUnitData[]): CompilationContext { // if the given file has no dependencies, there is no context to return, it can be compiled without additional work if (dependencies.length == 0) { return null; } else { var addedFiles = []; var precompile = () => { // REVIEW: if any dependency has a triple slash reference then does postCompile potentially have to do a recreate since we can't update references with updateUnit? // easy enough to do if so, prefer to avoid the recreate cost until it proves to be an issue dependencies.forEach(dep => { addUnit(dep.content, dep.name, false, Harness.Compiler.isDeclareFile(dep.name)); addedFiles.push(dep.name); }); }; var postcompile = () => { addedFiles.forEach(file => { updateUnit('', file); }); }; var context = { filename: filename, preCompile: precompile, postCompile: postcompile }; return context; } } } /** Parses the test cases files * extracts options and individual files in a multifile test */ export module TestCaseParser { /** all the necesarry information to set the right compiler settings */ export interface CompilerSetting { flag: string; value: string; } /** All the necessary information to turn a multi file test into useful units for later compilation */ export interface TestUnitData { content: string; name: string; originalFilePath: string; references: TypeScript.IFileReference[]; } // Regex for parsing options in the format "@Alpha: Value of any sort" private optionRegex = /^[\/]{2}\s*@(\w+):\s*(\S*)/gm; // multiple matches on multiple lines // List of allowed metadata names var fileMetadataNames = ["filename", "comments", "declaration", "module", "nolib", "sourcemap", "target", "out"]; function extractCompilerSettings(content: string): CompilerSetting[] { var opts = []; var match; while ((match = optionRegex.exec(content)) != null) { opts.push({ flag: match[1], value: match[2] }); } return opts; } /** Given a test file containing // @Filename directives, return an array of named units of code to be added to an existing compiler instance */ export function makeUnitsFromTest(code: string, filename: string): { settings: CompilerSetting[]; testUnitData: TestUnitData[]; } { var settings = extractCompilerSettings(code); // List of all the subfiles we've parsed out var files: TestUnitData[] = []; var lines = splitContentByNewlines(code); // Stuff related to the subfile we're parsing var currentFileContent: string = null; var currentFileOptions = {}; var currentFileName = null; var refs: TypeScript.IFileReference[] = []; for (var i = 0; i < lines.length; i++) { var line = lines[i]; var isTripleSlashReference = /[\/]{3}\s*<reference path/.test(line); var testMetaData = optionRegex.exec(line); // Triple slash references need to be tracked as they are added to the compiler as an additional parameter to addUnit if (isTripleSlashReference) { var isRef = line.match(/reference\spath='(\w*_?\w*\.?d?\.ts)'/); if (isRef) { var ref = { minChar: 0, limChar: 0, startLine:0, startCol:0, path: isRef[1], isResident: false }; refs.push(ref); } } else if (testMetaData) { // Comment line, check for global/file @options and record them optionRegex.lastIndex = 0; var fileNameIndex = fileMetadataNames.indexOf(testMetaData[1].toLowerCase()); if (fileNameIndex == -1) { throw new Error('Unrecognized metadata name "' + testMetaData[1] + '". Available file metadata names are: ' + fileMetadataNames.join(', ')); } else if (fileNameIndex == 0) { currentFileOptions[testMetaData[1]] = testMetaData[2]; } else { continue; } // New metadata statement after having collected some code to go with the previous metadata if (currentFileName) { // Store result file var newTestFile = { content: currentFileContent, name: currentFileName, fileOptions: currentFileOptions, originalFilePath: filename, references: refs }; files.push(newTestFile); // Reset local data currentFileContent = null; currentFileOptions = {}; currentFileName = testMetaData[2]; refs = []; } else { // First metadata marker in the file currentFileName = testMetaData[2]; } } else { // Subfile content line // Append to the current subfile content, inserting a newline needed if (currentFileContent === null) { currentFileContent = ''; } else { // End-of-line currentFileContent = currentFileContent + '\n'; } currentFileContent = currentFileContent + line; } } // normalize the filename for the single file case currentFileName = files.length > 0 ? currentFileName : '0.ts'; // EOF, push whatever remains var newTestFile = { content: currentFileContent || '', name: currentFileName, fileOptions: currentFileOptions, originalFilePath: filename, references: refs }; files.push(newTestFile); return { settings: settings, testUnitData: files }; } } export class ScriptInfo { public version: number; public editRanges: { length: number; editRange: TypeScript.ScriptEditRange; }[] = []; constructor(public name: string, public content: string, public isResident: boolean, public maxScriptVersions: number) { this.version = 1; } public updateContent(content: string, isResident: boolean) { this.editRanges = []; this.content = content; this.isResident = isResident; this.version++; } public editContent(minChar: number, limChar: number, newText: string) { // Apply edits var prefix = this.content.substring(0, minChar); var middle = newText; var suffix = this.content.substring(limChar); this.content = prefix + middle + suffix; // Store edit range + new length of script this.editRanges.push({ length: this.content.length, editRange: new TypeScript.ScriptEditRange(minChar, limChar, (limChar - minChar) + newText.length) }); if (this.editRanges.length > this.maxScriptVersions) { this.editRanges.splice(0, this.maxScriptVersions - this.editRanges.length); } // Update version # this.version++; } public getEditRangeSinceVersion(version: number): TypeScript.ScriptEditRange { if (this.version == version) { // No edits! return null; } var initialEditRangeIndex = this.editRanges.length - (this.version - version); if (initialEditRangeIndex < 0 || initialEditRangeIndex >= this.editRanges.length) { // Too far away from what we know return TypeScript.ScriptEditRange.unknown(); } var entries = this.editRanges.slice(initialEditRangeIndex); var minDistFromStart = entries.map(x => x.editRange.minChar).reduce((prev, current) => Math.min(prev, current)); var minDistFromEnd = entries.map(x => x.length - x.editRange.limChar).reduce((prev, current) => Math.min(prev, current)); var aggDelta = entries.map(x => x.editRange.delta).reduce((prev, current) => prev + current); return new TypeScript.ScriptEditRange(minDistFromStart, entries[0].length - minDistFromEnd, aggDelta); } } export class TypeScriptLS implements Services.ILanguageServiceShimHost { private ls: Services.ILanguageServiceShim = null; public scripts: ScriptInfo[] = []; public maxScriptVersions = 100; public addDefaultLibrary() { this.addScript("lib.d.ts", Harness.Compiler.libText, true); } public addFile(name: string, isResident = false) { var code: string = readFile(name); this.addScript(name, code, isResident); } public addScript(name: string, content: string, isResident = false) { var script = new ScriptInfo(name, content, isResident, this.maxScriptVersions); this.scripts.push(script); } public updateScript(name: string, content: string, isResident = false) { for (var i = 0; i < this.scripts.length; i++) { if (this.scripts[i].name == name) { this.scripts[i].updateContent(content, isResident); return; } } this.addScript(name, content, isResident); } public editScript(name: string, minChar: number, limChar: number, newText: string) { for (var i = 0; i < this.scripts.length; i++) { if (this.scripts[i].name == name) { this.scripts[i].editContent(minChar, limChar, newText); return; } } throw new Error("No script with name '" + name + "'"); } public getScriptContent(scriptIndex: number): string { return this.scripts[scriptIndex].content; } ////////////////////////////////////////////////////////////////////// // ILogger implementation // public information(): boolean { return false; } public debug(): boolean { return true; } public warning(): boolean { return true; } public error(): boolean { return true; } public fatal(): boolean { return true; } public log(s: string): void { // For debugging... //IO.printLine("TypeScriptLS:" + s); } ////////////////////////////////////////////////////////////////////// // ILanguageServiceShimHost implementation // public getCompilationSettings(): string/*json for Tools.CompilationSettings*/ { return ""; // i.e. default settings } public getScriptCount(): number { return this.scripts.length; } public getScriptSourceText(scriptIndex: number, start: number, end: number): string { return this.scripts[scriptIndex].content.substring(start, end); } public getScriptSourceLength(scriptIndex: number): number { return this.scripts[scriptIndex].content.length; } public getScriptId(scriptIndex: number): string { return this.scripts[scriptIndex].name; } public getScriptIsResident(scriptIndex: number): boolean { return this.scripts[scriptIndex].isResident; } public getScriptVersion(scriptIndex: number): number { return this.scripts[scriptIndex].version; } public getScriptEditRangeSinceVersion(scriptIndex: number, scriptVersion: number): string { var range = this.scripts[scriptIndex].getEditRangeSinceVersion(scriptVersion); var result = (range.minChar + "," + range.limChar + "," + range.delta); return result; } /** Return a new instance of the language service shim, up-to-date wrt to typecheck. * To access the non-shim (i.e. actual) language service, use the "ls.languageService" property. */ public getLanguageService(): Services.ILanguageServiceShim { var ls = new Services.TypeScriptServicesFactory().createLanguageServiceShim(this); ls.refresh(true); this.ls = ls; return ls; } /** Parse file given its source text */ public parseSourceText(fileName: string, sourceText: TypeScript.ISourceText): TypeScript.Script { var parser = new TypeScript.Parser(); parser.setErrorRecovery(null); parser.errorCallback = (a, b, c, d) => { }; var script = parser.parse(sourceText, fileName, 0); return script; } /** Parse a file on disk given its filename */ public parseFile(fileName: string) { var sourceText = new TypeScript.StringSourceText(IO.readFile(fileName)) return this.parseSourceText(fileName, sourceText); } /** * @param line 1 based index * @param col 1 based index */ public lineColToPosition(fileName: string, line: number, col: number): number { var script = this.ls.languageService.getScriptAST(fileName); assert.notNull(script); assert.is(line >= 1); assert.is(col >= 1); assert.is(line <= script.locationInfo.lineMap.length); return TypeScript.getPositionFromZeroBasedLineColumn(script, line - 1, col - 1); } /** * @param line 0 based index * @param col 0 based index */ public positionToZeroBasedLineCol(fileName: string, position: number): TypeScript.ILineCol { var script = this.ls.languageService.getScriptAST(fileName); assert.notNull(script); var result = TypeScript.getZeroBasedLineColumnFromPosition(script, position); assert.is(result.line >= 0); assert.is(result.col >= 0); return result; } /** Verify that applying edits to sourceFileName result in the content of the file baselineFileName */ public checkEdits(sourceFileName: string, baselineFileName: string, edits: Services.TextEdit[]) { var script = readFile(sourceFileName); var formattedScript = this.applyEdits(script, edits); var baseline = readFile(baselineFileName); assert.noDiff(formattedScript, baseline); assert.equal(formattedScript, baseline); } /** Apply an array of text edits to a string, and return the resulting string. */ public applyEdits(content: string, edits: Services.TextEdit[]): string { var result = content; edits = this.normalizeEdits(edits); for (var i = edits.length - 1; i >= 0; i--) { var edit = edits[i]; var prefix = result.substring(0, edit.minChar); var middle = edit.text; var suffix = result.substring(edit.limChar); result = prefix + middle + suffix; } return result; } /** Normalize an array of edits by removing overlapping entries and sorting entries on the minChar position. */ private normalizeEdits(edits: Services.TextEdit[]): Services.TextEdit[] { var result: Services.TextEdit[] = []; function mapEdits(edits: Services.TextEdit[]): { edit: Services.TextEdit; index: number; }[] { var result = []; for (var i = 0; i < edits.length; i++) { result.push({ edit: edits[i], index: i }); } return result; } var temp = mapEdits(edits).sort(function (a, b) { var result = a.edit.minChar - b.edit.minChar; if (result == 0) result = a.index - b.index; return result; }); var current = 0; var next = 1; while (current < temp.length) { var currentEdit = temp[current].edit; // Last edit if (next >= temp.length) { result.push(currentEdit); current++; continue; } var nextEdit = temp[next].edit; var gap = nextEdit.minChar - currentEdit.limChar; // non-overlapping edits if (gap >= 0) { result.push(currentEdit); current = next; next++; continue; } // overlapping edits: for now, we only support ignoring an next edit // entirely contained in the current edit. if (currentEdit.limChar >= nextEdit.limChar) { next++; continue; } else { throw new Error("Trying to apply overlapping edits"); } } return result; } public getHostSettings(): string { return JSON.stringify({ usePullLanguageService: usePull }); } } // Describe/it definitions export function describe(description: string, block: () => any) { var newScenario = new Scenario(description, block); if (Runnable.currentStack.length === 0) { Runnable.currentStack.push(currentRun); } Runnable.currentStack[Runnable.currentStack.length - 1].addChild(newScenario); } export function it(description: string, block: () => void ) { var testCase = new TestCase(description, block); Runnable.currentStack[Runnable.currentStack.length - 1].addChild(testCase); } export function run() { if (typeof process !== "undefined") { process.on('uncaughtException', Runnable.handleError); } Baseline.reset(); currentRun.run(); } /** Runs TypeScript or Javascript code. */ export module Runner { export function runCollateral(path: string, callback: (error: Error, result: any) => void ) { path = switchToForwardSlashes(path); runString(readFile(path), path.match(/[^\/]*$/)[0], callback); } export function runJSString(code: string, callback: (error: Error, result: any) => void ) { // List of names that get overriden by various test code we eval var dangerNames: any = ['Array']; var globalBackup: any = {}; var n: string = null; for (n in dangerNames) { globalBackup[dangerNames[n]] = global[dangerNames[n]]; } try { var res = eval(code); for (n in dangerNames) { global[dangerNames[n]] = globalBackup[dangerNames[n]]; } callback(null, res); } catch (e) { for (n in dangerNames) { global[dangerNames[n]] = globalBackup[dangerNames[n]]; } callback(e, null); } } export function runString(code: string, unitName: string, callback: (error: Error, result: any) => void ) { Compiler.compileString(code, unitName, function (res) { runJSString(res.code, callback); }); } } /** Support class for baseline files */ export module Baseline { var reportFilename = 'baseline-report.html'; var firstRun = true; var htmlTrailer = '</body></html>'; var htmlLeader = '<html><head><title>Baseline Report</title>'; htmlLeader += ("<style>"); htmlLeader += '\r\n' + (".code { font: 9pt 'Courier New'; }"); htmlLeader += '\r\n' + (".old { background-color: #EE1111; }"); htmlLeader += '\r\n' + (".new { background-color: #FFFF11; }"); htmlLeader += '\r\n' + (".from { background-color: #EE1111; color: #1111EE; }"); htmlLeader += '\r\n' + (".to { background-color: #EEEE11; color: #1111EE; }"); htmlLeader += '\r\n' + ("h2 { margin-bottom: 0px; }"); htmlLeader += '\r\n' + ("h2 { padding-bottom: 0px; }"); htmlLeader += '\r\n' + ("h4 { font-weight: normal; }"); htmlLeader += '\r\n' + ("</style>"); export interface BaselineOptions { LineEndingSensitive?: boolean; } function localPath(filename: string) { if (global.runners[0].testType === 'prototyping') { return Harness.userSpecifiedroot + 'tests/baselines/prototyping/local/' + filename; } else { return Harness.userSpecifiedroot + 'tests/baselines/local/' + filename; } } function referencePath(filename: string) { if (global.runners[0].testType === 'prototyping') { return Harness.userSpecifiedroot + 'tests/baselines/prototyping/reference/' + filename; } else { return Harness.userSpecifiedroot + 'tests/baselines/reference/' + filename; } } export function reset() { if (IO.fileExists(reportFilename)) { IO.deleteFile(reportFilename); } } function prepareBaselineReport(): string { var reportContent = htmlLeader; // Delete the baseline-report.html file if needed if (IO.fileExists(reportFilename)) { reportContent = IO.readFile(reportFilename); reportContent = reportContent.replace(htmlTrailer, ''); } else { reportContent = htmlLeader; } return reportContent; } function generateActual(actualFilename: string, generateContent: () => string): string { // Create folders if needed IO.createDirectory(IO.dirName(IO.dirName(actualFilename))); IO.createDirectory(IO.dirName(actualFilename)); // Delete the actual file in case it fails if (IO.fileExists(actualFilename)) { IO.deleteFile(actualFilename); } var actual = generateContent(); if (actual === undefined) { throw new Error('The generated content was "undefined". Return "null" if no baselining is required."'); } // Store the content in the 'local' folder so we // can accept it later (manually) if (actual !== null) { IO.writeFile(actualFilename, actual); } return actual; } function compareToBaseline(actual: string, relativeFilename: string, opts: BaselineOptions) { // actual is now either undefined (the generator had an error), null (no file requested), // or some real output of the function if (actual === undefined) { // Nothing to do return; } var refFilename = referencePath(relativeFilename); if (actual === null) { actual = '<no content>'; } var expected = '<no content>'; if (IO.fileExists(refFilename)) { expected = IO.readFile(refFilename); } var lineEndingSensitive = opts && opts.LineEndingSensitive; if (!lineEndingSensitive) { expected = expected.replace(/\r\n?/g, '\n') actual = actual.replace(/\r\n?/g, '\n') } return { expected: expected, actual: actual }; } function writeComparison(expected: string, actual: string, relativeFilename: string, actualFilename: string, descriptionForDescribe: string) { if (expected != actual) { // Overwrite & issue error var errMsg = 'The baseline file ' + relativeFilename + ' has changed. Please refer to baseline-report.html and '; errMsg += 'either fix the regression (if unintended) or run nmake baseline-accept (if intended).' var refFilename = referencePath(relativeFilename); // Append diff to the report var diff = new Diff.StringDiff(expected, actual); var header = '<h2>' + descriptionForDescribe + '</h2>'; header += '<h4>Left file: ' + actualFilename + '; Right file: ' + refFilename + '</h4>'; var trailer = '<hr>'; var reportContentSoFar = prepareBaselineReport(); reportContentSoFar = reportContentSoFar + header + '<div class="code">' + diff.mergedHtml + '</div>' + trailer + htmlTrailer; IO.writeFile(reportFilename, reportContentSoFar); throw new Error(errMsg); } } export function runBaseline( descriptionForDescribe: string, relativeFilename: string, generateContent: () => string, runImmediately? = false, opts?: BaselineOptions) { var actual = <string>undefined; var actualFilename = localPath(relativeFilename); if (runImmediately) { var actual = generateActual(actualFilename, generateContent); var comparison = compareToBaseline(actual, relativeFilename, opts); writeComparison(comparison.expected, comparison.actual, relativeFilename, actualFilename, descriptionForDescribe); } else { describe(descriptionForDescribe, () => { var actual: string; it('Can generate the content without error', () => { actual = generateActual(actualFilename, generateContent); }); it('Matches the baseline file', () => { var comparison = compareToBaseline(actual, relativeFilename, opts); writeComparison(comparison.expected, comparison.actual, relativeFilename, actualFilename, descriptionForDescribe); }); }); } } } var currentRun = new Run(); global.describe = describe; global.run = run; global.it = it; global.assert = Harness.Assert; }
the_stack
import { Workbook } from './../src/workbook'; import { Utils } from './../spec/utils.spec'; describe('CellStyle', () => { // afterEach(function () { // sleep(3000); // }); // function sleep(millSecs: any) { // let date: any = new Date(); // let curDate: any = null; // do { curDate = new Date(); } // while (curDate - date < millSecs); // } //Methods testcase it('Font', (done) => { let book: Workbook = new Workbook({ worksheets: [ { name: 'CellStyle', rows: [ { index: 1, cells: [{ index: 1, value: 10, style: { fontColor: '#C67878', fontName: 'Tahoma', fontSize: 20, italic: true, bold: true, underline: true } }] }, { index: 2, cells: [{ index: 1, value: 10, style: { fontColor: '#C67878', fontName: 'Tahoma', fontSize: 20, italic: true, bold: true, underline: true } }] }, { index: 3, cells: [{ index: 1, value: 10, style: { fontColor: '#C67878' } }] }, { index: 4, cells: [{ index: 1, value: 10, style: { fontColor: '#C67878' } }] }, { index: 5, cells: [{ index: 1, value: 10, style: { backColor: '#C67878' } }] }, { index: 6, cells: [{ index: 1, value: 10, style: { backColor: '#C67878' } }] }, { index: 7, cells: [{ index: 1, value: 'erterterrrrrrrrrrrrrrrrrrrrrrrrr', style: { wrapText: true, hAlign: 'right', vAlign: 'top' } }] }, { index: 8, cells: [{ index: 1, value: 'erterterrrrrrrrrrrrrrrrrrrrrrrrr', style: { wrapText: true, hAlign: 'right', vAlign: 'top' } }] }, { index: 9, cells: [{ index: 1, value: 'erterterrrrrrrrrrrrrrrrrrrrrrrrr', style: { wrapText: true, hAlign: 'center', vAlign: 'center' } }] }, { index: 10, cells: [{ index: 1, value: 'erterterrrrrrrrrrrrrrrrrrrrrrrrr', style: { wrapText: true, hAlign: 'center', vAlign: 'center' } }] }, { index: 11, cells: [{ index: 1, value: 'erterterrrrrrrrrrrrrrrrrrrrrrrrr', style: { wrapText: true, hAlign: 'fill', vAlign: 'justify' } }] }, { index: 12, cells: [{ index: 1, value: 'erterterrrrrrrrrrrrrrrrrrrrrrrrr', style: { wrapText: true, hAlign: 'fill', vAlign: 'justify' } }] }, { index: 13, cells: [{ index: 1, value: 'erterterrrrrrrrrrrrrrrrrrrrrrrrr', style: { wrapText: true, hAlign: 'fill', vAlign: 'justify' } }] }, ], }] }, 'xlsx'); book.saveAsBlob('application/vnd.openxmlformats-officedocument.spreadsheetml.sheet').then((xlBlob: { blobData: Blob }) => { if (Utils.isDownloadEnabled) { Utils.download(xlBlob.blobData, 'Font.xlsx'); } 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(); } } }); }); it('Font-duplicate', (done) => { let book: Workbook = new Workbook({ worksheets: [ { name: 'CellStyle', rows: [ { index: 1, cells: [{ index: 1, value: 10, style: { fontColor: '#C67878', fontName: 'Tahoma' } }] }, { index: 2, cells: [{ index: 1, value: 10, style: { fontColor: '#C67878', fontName: 'Tahoma', wrapText: true } }] }, { index: 3, cells: [{ index: 1, style: { wrapText: true } }] } ], }] }, 'xlsx'); book.saveAsBlob('application/vnd.openxmlformats-officedocument.spreadsheetml.sheet').then((xlBlob: { blobData: Blob }) => { if (Utils.isDownloadEnabled) { Utils.download(xlBlob.blobData, 'Font-duplicate.xlsx'); } 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(); } } }); }); it('Border', (done) => { let book: Workbook = new Workbook({ worksheets: [ { name: 'CellStyle', rows: [ { index: 1, cells: [{ index: 1, value: 'Border', style: { leftBorder: { color: '#C67878', lineStyle: 'thick' }, rightBorder: { color: '#C67878', lineStyle: 'thick' }, topBorder: { color: '#C67878', lineStyle: 'thick' }, bottomBorder: { color: '#C67878', lineStyle: 'thick' } } }, { index: 2, value: 'Border', style: { leftBorder: { color: '#C67878', lineStyle: 'thick' }, rightBorder: { color: '#C67878', lineStyle: 'thick' }, topBorder: { color: '#C67878', lineStyle: 'thick' }, bottomBorder: { color: '#C67878', lineStyle: 'thick' } } }] }, { index: 2, cells: [{ index: 1, value: 10 }] }, { index: 3, cells: [{ index: 1, value: 'Border', style: { leftBorder: {}, rightBorder: {}, topBorder: {}, bottomBorder: {} } }] }, { index: 4, cells: [{ index: 1, value: 10 }] }, { index: 5, cells: [{ index: 1, value: 'Border', style: { leftBorder: { color: '#C67878' }, rightBorder: { color: '#C67878' }, topBorder: { color: '#C67878' }, bottomBorder: { color: '#C67878' } } }] }, { index: 6, cells: [{ index: 1, value: 10 }] }, { index: 7, cells: [{ index: 1, value: 'Border', style: { leftBorder: { lineStyle: 'thick' }, rightBorder: { lineStyle: 'thick' }, topBorder: { lineStyle: 'thick' }, bottomBorder: { lineStyle: 'thick' } } }] }, ], }] }, 'xlsx'); book.saveAsBlob('application/vnd.openxmlformats-officedocument.spreadsheetml.sheet').then((xlBlob: { blobData: Blob }) => { if (Utils.isDownloadEnabled) { Utils.download(xlBlob.blobData, 'Border.xlsx'); } 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(); } } }); }); it('NumberFormat-Date', (done) => { let book: Workbook = new Workbook({ worksheets: [ { name: 'CellStyle', rows: [ { index: 1, cells: [{ index: 1, value: new Date(), style: { numberFormat: "E" } }] }, { index: 2, cells: [{ index: 1, value: new Date(), style: { numberFormat: "EHm" } }] }, { index: 3, cells: [{ index: 1, value: new Date(), style: { numberFormat: "EHms" } }] }, { index: 4, cells: [{ index: 1, value: new Date(), style: { numberFormat: "Ed" } }] }, { index: 5, cells: [{ index: 1, value: new Date(), style: { numberFormat: "Ehm" } }] }, { index: 6, cells: [{ index: 1, value: new Date(), style: { numberFormat: "Ehms" } }] }, { index: 7, cells: [{ index: 1, value: new Date(), style: { numberFormat: "Gy" } }] }, { index: 8, cells: [{ index: 1, value: new Date(), style: { numberFormat: "GyMMM" } }] }, { index: 9, cells: [{ index: 1, value: new Date(), style: { numberFormat: "GyMMMEd" } }] }, { index: 10, cells: [{ index: 1, value: new Date(), style: { numberFormat: "GyMMMd" } }] }, { index: 11, cells: [{ index: 1, value: new Date(), style: { numberFormat: "H" } }] }, { index: 12, cells: [{ index: 1, value: new Date(), style: { numberFormat: "Hm" } }] }, { index: 13, cells: [{ index: 1, value: new Date(), style: { numberFormat: "Hms" } }] }, { index: 14, cells: [{ index: 1, value: new Date(), style: { numberFormat: "M" } }] }, { index: 15, cells: [{ index: 1, value: new Date(), style: { numberFormat: "MEd" } }] }, { index: 16, cells: [{ index: 1, value: new Date(), style: { numberFormat: "MMM" } }] }, { index: 17, cells: [{ index: 1, value: new Date(), style: { numberFormat: "MMMEd" } }] }, { index: 18, cells: [{ index: 1, value: new Date(), style: { numberFormat: "MMMd" } }] }, { index: 19, cells: [{ index: 1, value: new Date(), style: { numberFormat: "Md" } }] }, { index: 20, cells: [{ index: 1, value: new Date(), style: { numberFormat: "d" } }] }, { index: 21, cells: [{ index: 1, value: new Date(), style: { numberFormat: "h" } }] }, { index: 22, cells: [{ index: 1, value: new Date(), style: { numberFormat: "hm" } }] }, { index: 23, cells: [{ index: 1, value: new Date(), style: { numberFormat: "hms" } }] }, { index: 24, cells: [{ index: 1, value: new Date(), style: { numberFormat: "ms" } }] }, { index: 25, cells: [{ index: 1, value: new Date(), style: { numberFormat: "y" } }] }, { index: 26, cells: [{ index: 1, value: new Date(), style: { numberFormat: "yM" } }] }, { index: 27, cells: [{ index: 1, value: new Date(), style: { numberFormat: "yMEd" } }] }, { index: 28, cells: [{ index: 1, value: new Date(), style: { numberFormat: "yMMM" } }] }, { index: 29, cells: [{ index: 1, value: new Date(), style: { numberFormat: "yMMMEd" } }] }, { index: 30, cells: [{ index: 1, value: new Date(), style: { numberFormat: "yMMMd" } }] }, { index: 31, cells: [{ index: 1, value: new Date(), style: { numberFormat: "yMd" } }] }, // { index: 32, cells: [{ index: 1, value: new Date(), style: { numberFormat: "yQQQ" } }] }, // { index: 33, cells: [{ index: 1, value: new Date(), style: { numberFormat: "yQQQQ" } }] }, // { index: 34, cells: [{ index: 1, value: new Date(), style: { numberFormat: "GyMMMEdhms" } }] }, { index: 35, cells: [{ index: 1, value: new Date(), style: { numberFormat: "Ehms" } }] }, // { index: 36, cells: [{ index: 1, value: new Date(), style: { numberFormat: "yQQQHm" } }] }, // { index: 37, cells: [{ index: 1, value: new Date(), style: { numberFormat: "MMMEdhm" } }] }, // { index: 38, cells: [{ index: 1, value: new Date(), style: { numberFormat: "yMMMdhm" } }] }, ], }] }, 'xlsx'); book.saveAsBlob('application/vnd.openxmlformats-officedocument.spreadsheetml.sheet').then((xlBlob: { blobData: Blob }) => { if (Utils.isDownloadEnabled) { Utils.download(xlBlob.blobData, 'NumberFormat-Date.xlsx'); } 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(); } } }); }); it('NumberFormat', (done) => { let book: Workbook = new Workbook({ worksheets: [ { name: 'CellStyle', rows: [ { index: 1, cells: [{ index: 1, value: 20, style: { numberFormat: "A5" } }] }, { index: 2, cells: [{ index: 1, value: 20, style: { numberFormat: "A3" } }] }, { index: 3, cells: [{ index: 1, value: 20, style: { numberFormat: "P3" } }] }, { index: 4, cells: [{ index: 1, value: 20, style: { numberFormat: "P2" } }] }, { index: 5, cells: [{ index: 1, value: 20, style: { numberFormat: "C2" } }] }, { index: 6, cells: [{ index: 1, value: 20, style: { numberFormat: "C" } }] }, { index: 7, cells: [{ index: 1, value: 20, style: { numberFormat: "N" } }] }, { index: 8, cells: [{ index: 1, value: 20, style: { numberFormat: "N2" } }] }, { index: 9, cells: [{ index: 1, value: 20, style: { numberFormat: "N3" } }] }, { index: 10, cells: [{ index: 1, value: 20, style: { numberFormat: "N4" } }] } ], }] }, 'xlsx'); book.saveAsBlob('application/vnd.openxmlformats-officedocument.spreadsheetml.sheet').then((xlBlob: { blobData: Blob }) => { if (Utils.isDownloadEnabled) { Utils.download(xlBlob.blobData, 'NumberFormat.xlsx'); } 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(); } } }); }); it('NumberFormat-Culture-Currency', (done) => { let book: Workbook = new Workbook({ worksheets: [ { name: 'CellStyle', rows: [ { index: 1, cells: [{ index: 1, value: 20, style: { numberFormat: "A5" } }] }, { index: 2, cells: [{ index: 1, value: 20, style: { numberFormat: "A3" } }] }, { index: 3, cells: [{ index: 1, value: 20, style: { numberFormat: "P3" } }] }, { index: 4, cells: [{ index: 1, value: 20, style: { numberFormat: "P2" } }] }, { index: 5, cells: [{ index: 1, value: 20, style: { numberFormat: "C2" } }] }, { index: 6, cells: [{ index: 1, value: 20, style: { numberFormat: "C" } }] }, { index: 7, cells: [{ index: 1, value: 20, style: { numberFormat: "N" } }] }, { index: 8, cells: [{ index: 1, value: 20, style: { numberFormat: "N2" } }] }, { index: 9, cells: [{ index: 1, value: 20, style: { numberFormat: "N3" } }] }, { index: 10, cells: [{ index: 1, value: 20, style: { numberFormat: "N4" } }] } ], }] }, 'xlsx', 'de-DE', 'EUR'); book.saveAsBlob('application/vnd.openxmlformats-officedocument.spreadsheetml.sheet').then((xlBlob: { blobData: Blob }) => { if (Utils.isDownloadEnabled) { Utils.download(xlBlob.blobData, 'NumberFormat-Culture-Currency.xlsx'); } 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(); } } }); }); it('NumberFormat-duplicate', (done) => { let book: Workbook = new Workbook({ /*Global Styles*/styles: [ /*Style ->1*/{ name: 'Currency-1', fontColor: '#C67878', fontName: 'Tahoma', fontSize: 20, italic: true, bold: true, underline: true, wrapText: true, numberFormat: 'C' }, /*Style ->2*/{ name: 'Currency-2', fontName: 'Arial', fontSize: 20, wrapText: true, numberFormat: 'C' }, /*Style ->3*/{ name: 'Date-1', fontName: 'Arial', fontSize: 18, wrapText: true, numberFormat: 'MMM' }, /*Style ->4*/{ name: 'Date-3', fontName: 'Arial', fontSize: 16, wrapText: true, numberFormat: 'yMd' }, /*Style ->4*/{ name: 'Date-4', fontName: 'Arial', fontSize: 16, wrapText: true, numberFormat: 'mm-dd-yy' }, ], worksheets: [ { name: 'CellStyle', rows: [ { index: 1, cells: [{ index: 1, value: new Date(), style: { numberFormat: 'yMd' } }] }, { index: 2, cells: [{ index: 1, value: new Date(), style: { numberFormat: 'yMd', backColor: '#C67978' } }] }, { index: 3, cells: [{ index: 1, value: new Date(), style: { backColor: '#C67878' } }] }, { index: 4, cells: [{ index: 1, value: new Date() }] }, { index: 5, cells: [{ index: 1, value: 10.0, style: { name: 'Currency-1' } }] }, { index: 6, cells: [{ index: 1, value: 10.0, style: { name: 'Currency-2' } }] }, { index: 7, cells: [{ index: 1, value: new Date(), style: { name: 'Date-1' } }] }, { index: 8, cells: [{ index: 1, value: new Date(), style: { name: 'Date-3' } }] }, { index: 9, cells: [{ index: 1, value: new Date(), style: { name: 'Date-4' } }] }, { index: 10, cells: [{ index: 1, value: new Date(), style: { numberFormat: 'yyyy-MM-dd' } }] }, ], }] }, 'xlsx'); book.saveAsBlob('application/vnd.openxmlformats-officedocument.spreadsheetml.sheet').then((xlBlob: { blobData: Blob }) => { if (Utils.isDownloadEnabled) { Utils.download(xlBlob.blobData, 'NumberFormat-duplicate.xlsx'); } 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(); } } }); }); it('fill-duplicate', (done) => { let book: Workbook = new Workbook({ worksheets: [ { name: 'CellStyle', rows: [ { index: 1, cells: [{ index: 1, value: 'text', style: { backColor: '#C67878', numberFormat: 'yyyy-mm-dd' } }] }, { index: 2, cells: [{ index: 1, value: 'text2', style: { numberFormat: 'yyyy-mm-dd', backColor: '#C67978' } }] }, { index: 3, cells: [{ index: 1, value: 'text3', style: { backColor: '#C67878' } }] }, { index: 4, cells: [{ index: 1, value: new Date() }] }, { index: 5, cells: [{ index: 1, value: 10, style: { backColor: '#C67978' } }] }, ], }] }, 'xlsx'); book.saveAsBlob('application/vnd.openxmlformats-officedocument.spreadsheetml.sheet').then((xlBlob: { blobData: Blob }) => { if (Utils.isDownloadEnabled) { Utils.download(xlBlob.blobData, 'fill-duplicate.xlsx'); } 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(); } } }); }); it('MixedFormats', (done) => { let book: Workbook = new Workbook({ worksheets: [ { name: 'CellStyle', rows: [ { index: 1, cells: [{ index: 1, value: 10.05, style: { numberFormat: 'C' } }] }, { index: 2, cells: [{ index: 1, value: new Date(), style: { numberFormat: 'yMd' } }] }, { index: 3, cells: [{ index: 1, value: 21.95, style: { numberFormat: '$ #,##0.00' } }] }, { index: 4, cells: [{ index: 1, value: new Date(), style: { numberFormat: 'mm-dd-yy' } }] }, ], }] }, 'xlsx'); book.saveAsBlob('application/vnd.openxmlformats-officedocument.spreadsheetml.sheet').then((xlBlob: { blobData: Blob }) => { if (Utils.isDownloadEnabled) { Utils.download(xlBlob.blobData, 'MixedFormats.xlsx'); } 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(); } } }); }); it('NumberFormat-full-long', (done) => { let book: Workbook = new Workbook({ /*Global Styles*/styles: [ /*Style ->3*/{ name: 'Date-1', fontName: 'Arial', fontSize: 18, wrapText: true, numberFormat: 'short' }, /*Style ->4*/{ name: 'Date-2', fontName: 'Arial', fontSize: 16, wrapText: true, numberFormat: 'medium' }, /*Style ->4*/{ name: 'Date-3', fontName: 'Arial', fontSize: 16, wrapText: true, numberFormat: 'full' }, /*Style ->4*/{ name: 'Date-4', fontName: 'Arial', fontSize: 16, wrapText: true, numberFormat: 'long' }, ], worksheets: [ { name: 'CellStyle', rows: [ { index: 1, cells: [{ index: 1, value: new Date(), style: { name: 'Date-1' } }] }, { index: 2, cells: [{ index: 1, value: new Date(), style: { name: 'Date-2' } }] }, { index: 3, cells: [{ index: 1, value: new Date(), style: { name: 'Date-3' } }] }, { index: 4, cells: [{ index: 1, value: new Date(), style: { name: 'Date-4' } }] }, ], }] }, 'xlsx'); book.saveAsBlob('application/vnd.openxmlformats-officedocument.spreadsheetml.sheet').then((xlBlob: { blobData: Blob }) => { if (Utils.isDownloadEnabled) { Utils.download(xlBlob.blobData, 'NumberFormat-full-long.xlsx'); } 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(); } } }); }); it('number-format-with-type', (done) => { let book: Workbook = new Workbook({ /*Global Styles*/styles: [ /*Style ->3*/{ name: 'time-1', fontName: 'Arial', fontSize: 18, wrapText: true, numberFormat: 'short', type: 'time' }, /*Style ->4*/{ name: 'time-2', fontName: 'Arial', fontSize: 16, wrapText: true, numberFormat: 'medium', type: 'time' }, /*Style ->4*/{ name: 'time-3', fontName: 'Arial', fontSize: 16, wrapText: true, numberFormat: 'full', type: 'time' }, /*Style ->4*/{ name: 'time-4', fontName: 'Arial', fontSize: 16, wrapText: true, numberFormat: 'long', type: 'time' }, /*Style ->3*/{ name: 'date-1', fontName: 'Arial', fontSize: 18, wrapText: true, numberFormat: 'short', type: 'date' }, /*Style ->4*/{ name: 'date-2', fontName: 'Arial', fontSize: 16, wrapText: true, numberFormat: 'medium', type: 'date' }, /*Style ->4*/{ name: 'date-3', fontName: 'Arial', fontSize: 16, wrapText: true, numberFormat: 'full', type: 'date' }, /*Style ->4*/{ name: 'date-4', fontName: 'Arial', fontSize: 16, wrapText: true, numberFormat: 'long', type: 'date' }, /*Style ->3*/{ name: 'datetime-1', fontName: 'Arial', fontSize: 18, wrapText: true, numberFormat: 'short', type: 'datetime' }, /*Style ->4*/{ name: 'datetime-2', fontName: 'Arial', fontSize: 16, wrapText: true, numberFormat: 'medium', type: 'datetime' }, /*Style ->4*/{ name: 'datetime-3', fontName: 'Arial', fontSize: 16, wrapText: true, numberFormat: 'full', type: 'datetime' }, /*Style ->4*/{ name: 'datetime-4', fontName: 'Arial', fontSize: 16, wrapText: true, numberFormat: 'long', type: 'datetime' }, /*Style ->2*/{ name: 'Currency-1', fontName: 'Arial', fontSize: 20, wrapText: true, numberFormat: 'C' }, /*Style ->2*/{ name: 'Currency-2', fontName: 'Arial', fontSize: 20, wrapText: true, numberFormat: 'C2' }, ], worksheets: [ { name: 'CellStyle', rows: [ { index: 1, cells: [ { index: 1, value: new Date(), style: { name: 'date-1' } }, { index: 2, value: new Date(), style: { name: 'time-1' } }, { index: 3, value: new Date(), style: { name: 'datetime-1' } } ] }, { index: 2, cells: [ { index: 1, value: new Date(), style: { name: 'date-2' } }, { index: 2, value: new Date(), style: { name: 'time-2' } }, { index: 3, value: new Date(), style: { name: 'datetime-2' } } ] }, { index: 3, cells: [ { index: 1, value: new Date(), style: { name: 'date-3' } }, { index: 2, value: new Date(), style: { name: 'time-3' } }, { index: 3, value: new Date(), style: { name: 'datetime-3' } } ] }, { index: 4, cells: [ { index: 1, value: new Date(), style: { name: 'date-4' } }, { index: 2, value: new Date(), style: { name: 'time-4' } }, { index: 3, value: new Date(), style: { name: 'datetime-4' } } ] }, { index: 5, cells: [{ index: 1, value: 20, style: { numberFormat: "A5" } }] }, { index: 6, cells: [{ index: 1, value: 20, style: { numberFormat: "A3" } }] }, { index: 7, cells: [{ index: 1, value: 20, style: { numberFormat: "P3" } }] }, { index: 8, cells: [{ index: 1, value: 20, style: { numberFormat: "P2" } }] }, { index: 9, cells: [{ index: 1, value: 20, style: { numberFormat: "C2" } }] }, { index: 10, cells: [{ index: 1, value: 20, style: { numberFormat: "C" } }] }, { index: 11, cells: [{ index: 1, value: 20, style: { numberFormat: "N" } }] }, { index: 12, cells: [{ index: 1, value: 20, style: { numberFormat: "N2" } }] }, { index: 13, cells: [{ index: 1, value: 20, style: { numberFormat: "N3" } }] }, { index: 14, cells: [{ index: 1, value: 20, style: { numberFormat: "N4" } }] }, { index: 15, cells: [{ index: 1, value: 21.95, style: { numberFormat: '$ #,##0.00' } }] }, { index: 16, cells: [{ index: 1, value: new Date(), style: { numberFormat: 'mm-dd-yy' } }] }, { index: 17, cells: [{ index: 1, value: 'text', style: { backColor: '#C67878', numberFormat: 'yyyy-mm-dd' } }] }, { index: 18, cells: [{ index: 1, value: 'text2', style: { numberFormat: 'yyyy-mm-dd', backColor: '#C67978' } }] }, { index: 19, cells: [{ index: 1, value: new Date(), style: { numberFormat: "E" } }] }, { index: 20, cells: [{ index: 1, value: new Date(), style: { numberFormat: "EHm" } }] }, { index: 21, cells: [{ index: 1, value: new Date(), style: { numberFormat: "EHms" } }] }, { index: 22, cells: [{ index: 1, value: new Date(), style: { numberFormat: "Ed" } }] }, { index: 23, cells: [{ index: 1, value: new Date(), style: { numberFormat: "Ehm" } }] }, { index: 24, cells: [{ index: 1, value: new Date(), style: { numberFormat: "Ehms" } }] }, { index: 25, cells: [{ index: 1, value: new Date(), style: { numberFormat: "Gy" } }] }, { index: 26, cells: [{ index: 1, value: new Date(), style: { numberFormat: "GyMMM" } }] }, { index: 27, cells: [{ index: 1, value: new Date(), style: { numberFormat: "GyMMMEd" } }] }, { index: 28, cells: [{ index: 1, value: new Date(), style: { numberFormat: "GyMMMd" } }] }, { index: 29, cells: [{ index: 1, value: new Date(), style: { numberFormat: "H" } }] }, { index: 30, cells: [{ index: 1, value: new Date(), style: { numberFormat: "Hm" } }] }, { index: 31, cells: [{ index: 1, value: new Date(), style: { numberFormat: "Hms" } }] }, { index: 32, cells: [{ index: 1, value: new Date(), style: { numberFormat: "M" } }] }, { index: 33, cells: [{ index: 1, value: new Date(), style: { numberFormat: "MEd" } }] }, { index: 34, cells: [{ index: 1, value: new Date(), style: { numberFormat: "MMM" } }] }, { index: 35, cells: [{ index: 1, value: new Date(), style: { numberFormat: "MMMEd" } }] }, { index: 36, cells: [{ index: 1, value: new Date(), style: { numberFormat: "MMMd" } }] }, { index: 37, cells: [{ index: 1, value: new Date(), style: { numberFormat: "Md" } }] }, { index: 38, cells: [{ index: 1, value: new Date(), style: { numberFormat: "d" } }] }, { index: 39, cells: [{ index: 1, value: new Date(), style: { numberFormat: "h" } }] }, { index: 40, cells: [{ index: 1, value: new Date(), style: { numberFormat: "hm" } }] }, { index: 41, cells: [{ index: 1, value: new Date(), style: { numberFormat: "hms" } }] }, { index: 42, cells: [{ index: 1, value: new Date(), style: { numberFormat: "ms" } }] }, { index: 43, cells: [{ index: 1, value: new Date(), style: { numberFormat: "y" } }] }, { index: 44, cells: [{ index: 1, value: new Date(), style: { numberFormat: "yM" } }] }, { index: 45, cells: [{ index: 1, value: new Date(), style: { numberFormat: "yMEd" } }] }, { index: 46, cells: [{ index: 1, value: new Date(), style: { numberFormat: "yMMM" } }] }, { index: 47, cells: [{ index: 1, value: new Date(), style: { numberFormat: "yMMMEd" } }] }, { index: 48, cells: [{ index: 1, value: new Date(), style: { numberFormat: "yMMMd" } }] }, { index: 49, cells: [{ index: 1, value: new Date(), style: { numberFormat: "yMd" } }] }, ], }] }, 'xlsx'); book.saveAsBlob('application/vnd.openxmlformats-officedocument.spreadsheetml.sheet').then((xlBlob: { blobData: Blob }) => { if (Utils.isDownloadEnabled) { Utils.download(xlBlob.blobData, 'number-format-with-type.xlsx'); } 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(); } } }); }); it('Text-Indent', (done) => { let book: Workbook = new Workbook({ /*Global Styles*/styles: [ /*Style ->1*/{ name: 'Indent-Left', indent: 10 }, /*Style ->2*/{ name: 'Indent-Right', hAlign: 'right', indent: 10 }, /*Style ->3*/{ name: 'Indent', hAlign: 'centre', indent: 10 }, /*Style ->4*/{ name: 'Indent-Left-dup', indent: 10 }, ], worksheets: [ { name: 'CellStyle', columns: [ /*column -> 1*/{ index: 1, width: 200, }, /*column -> 3*/{ index: 2, width: 200, }, /*column -> 3*/{ index: 3, width: 200, }, /*column -> 4*/{ index: 4, width: 200, }, /*column -> 5*/{ index: 5, width: 200, }, /*column -> 6*/{ index: 6, width: 200, } ], rows: [ { index: 1, cells: [ { index: 1, value: 'Horizontal alignment right', style: { hAlign: 'right', indent: 10 } }, { index: 2, value: 'Horizontal alignment center to left', /*Cell Style - Horizontal alignment - Center*/ style: { hAlign: 'center', indent: 10 } }, { index: 3, value: 'Horizontal alignment left', /*Cell Style - Horizontal alignment - left*/ style: { hAlign: 'left', indent: 10 } }, { index: 4, value: 'Horizontal alignment right', style: { hAlign: 'right', indent: 10 } }, { index: 5, value: 'Horizontal alignment center to left', /*Cell Style - Horizontal alignment - Center*/ style: { hAlign: 'center', indent: 10 } }, { index: 6, value: 'Horizontal alignment left', /*Cell Style - Horizontal alignment - left*/ style: { hAlign: 'left', indent: 10 } } ] }, { index: 2, cells: [ { index: 1, value: 'Horizontal alignment right', style: { name: 'Indent-Right' } }, { index: 2, value: 'Horizontal alignment center to left', /*Cell Style - Horizontal alignment - Center*/ style: { name: 'Indent' } }, { index: 3, value: 'Horizontal alignment left', /*Cell Style - Horizontal alignment - left*/ style: { name: 'Indent-Left' } }, { index: 4, value: 'Horizontal alignment left', /*Cell Style - Horizontal alignment - left*/ style: { name: 'Indent-Left-dup' } } ] } ], }] }, 'xlsx'); book.saveAsBlob('application/vnd.openxmlformats-officedocument.spreadsheetml.sheet').then((xlBlob: { blobData: Blob }) => { if (Utils.isDownloadEnabled) { Utils.download(xlBlob.blobData, 'TextIndent.xlsx'); done(); } else { 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(); } } } }); }); it('Merged-Cells-CellStyle', (done) => { let book: Workbook = new Workbook({ worksheets: [ { name: 'CellMerge', rows: [ { index: 2, cells: [ { index: 2, rowSpan: 2, colSpan: 2, value: 'Merge text', style: { leftBorder: { lineStyle: 'thick' }, rightBorder: { lineStyle: 'thick' }, topBorder: { lineStyle: 'thick' }, bottomBorder: { lineStyle: 'thick' } } }, ] }, { index: 5, cells: [ { index: 2, rowSpan: 2, colSpan: 2, value: 'Merge text', style: { leftBorder: { lineStyle: 'thick' }, rightBorder: { lineStyle: 'thick' }, topBorder: { lineStyle: 'thick' }, bottomBorder: { lineStyle: 'thick' } } }, { index: 3, value: 'Merge text' } ] }, { index: 6, cells: [ { index: 2, value: 'Merge text', }, { index: 3, value: 'Merge text', } ] }, { index: 10, cells: [ { index: 2, rowSpan: 2, colSpan: 2, value: 'Merge text', style: { leftBorder: { lineStyle: 'thick' }, rightBorder: { lineStyle: 'thick' }, topBorder: { lineStyle: 'thick' }, bottomBorder: { lineStyle: 'thick' } } } ] }, { index: 11, cells: [ { index: 2, value: 'Merge text', }, { index: 3, value: 'Merge text', } ] }, { index: 14, cells: [ { index: 2, rowSpan: 2, colSpan: 2, value: 'Merge text', style: { leftBorder: { lineStyle: 'thick' }, rightBorder: { lineStyle: 'thick' }, topBorder: { lineStyle: 'thick' }, bottomBorder: { lineStyle: 'thick' } } }, { index: 3, value: 'Merge text', }, ] } ] }] }, 'xlsx'); book.saveAsBlob('application/vnd.openxmlformats-officedocument.spreadsheetml.sheet').then((xlBlob: { blobData: Blob }) => { if (Utils.isDownloadEnabled) { Utils.download(xlBlob.blobData, 'Merged-Cells-CellStyle.xlsx'); done(); } else { 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(); } } } }); }); it('Text-Rotation', (done) => { let book: Workbook = new Workbook({ /*Global Styles*/styles: [ /*Style ->1*/{ name: 'Rotation', rotation: 30 }, ], worksheets: [ { name: 'TextRotation', rows: [ { index: 1, cells: [ { index: 1, value: 'Text1', style: { hAlign: 'right', rotation: 45 } }, { index: 2, value: 'Text2', style: { hAlign: 'center', rotation: 90 } }, { index: 3, value: 'Text3', style: { hAlign: 'left', rotation: 120 } } ] }, ], }] }, 'xlsx'); book.saveAsBlob('application/vnd.openxmlformats-officedocument.spreadsheetml.sheet').then((xlBlob: { blobData: Blob }) => { if (Utils.isDownloadEnabled) { Utils.download(xlBlob.blobData, 'TextRotation.xlsx'); done(); } else { 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(); } } } }); }); it('Custom-NumberFormat-Date', (done) => { let book: Workbook = new Workbook({ worksheets: [ { name: 'CellStyle', rows: [ { index: 1, cells: [{ index: 1, value: new Date(), style: { numberFormat: "ccc dd.MM.yyyy" } }] }, { index: 2, cells: [{ index: 1, value: new Date(), style: { numberFormat: "ccc" } }] }, { index: 3, cells: [{ index: 1, value: new Date(), style: { numberFormat: "yyy" } }] }, { index: 4, cells: [{ index: 1, value: new Date(), style: { numberFormat: "LLL" } }] }, { index: 5, cells: [{ index: 1, value: new Date(), style: { numberFormat: "EEE" } }] }, { index: 6, cells: [{ index: 1, value: new Date(), style: { numberFormat: "d" } }] }, { index: 7, cells: [{ index: 1, value: new Date(), style: { numberFormat: "m" } }] }, { index: 8, cells: [{ index: 1, value: new Date(), style: { numberFormat: "s" } }] }, { index: 9, cells: [{ index: 1, value: new Date(), style: { numberFormat: "hh:mm:ss a" } }] }, { index: 10, cells: [{ index: 1, value: new Date(), style: { numberFormat: "z" } }] }, { index: 11, cells: [{ index: 1, value: new Date(), style: { numberFormat: "hh" } }] }, ], }] }, 'xlsx'); book.saveAsBlob('application/vnd.openxmlformats-officedocument.spreadsheetml.sheet').then((xlBlob: { blobData: Blob }) => { if (Utils.isDownloadEnabled) { Utils.download(xlBlob.blobData, 'Custom-NumberFormat-Date.xlsx'); } 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(); } } }); }); it('Rich-Text-Font', (done) => { let book: Workbook = new Workbook({ worksheets: [ { name: 'Rich-Text', rows: [ { index: 1, cells: [{ index: 1, value: '<font color=\'red\' size=\'12\'>McFadden DG</font> Mike' }] }, { index: 2, cells: [{ index: 1, value: 'Hodges E, <b>Rosebrock AP</b>' }] }, { index: 3, cells: [{ index: 1, value: '<i> Chen FK</i>' }] }, { index: 4, cells: [{ index: 1, value: '<u>This is some text!</u> Plain Text' }] }, { index: 5, cells: [{ index: 1, value: '<font face="verdana" color="#CD5C5C" size="12">This is some text!</font> <b>Plain Text</b>' }] }, { index: 6, cells: [{ index: 1, value: '<font size="12" face="Segoe UI" color="blue" >This is some text!</font> <i>Plain Text</i>' }] }, ], }] }, 'xlsx'); book.saveAsBlob('application/vnd.openxmlformats-officedocument.spreadsheetml.sheet').then((xlBlob: { blobData: Blob }) => { if (Utils.isDownloadEnabled) { Utils.download(xlBlob.blobData, 'Rich-Text.xlsx'); } 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(); } } }); }); it('NumberFormatGermanCulture', (done) => { let book: Workbook = new Workbook({ worksheets: [ { name: 'CellStyle', rows: [ { index: 1, cells: [{ index: 1, value: 20, style: { numberFormat: "A5" } }] }, { index: 2, cells: [{ index: 1, value: 20, style: { numberFormat: "A3" } }] }, { index: 3, cells: [{ index: 1, value: 20, style: { numberFormat: "P3" } }] }, { index: 4, cells: [{ index: 1, value: 20, style: { numberFormat: "P2" } }] }, { index: 5, cells: [{ index: 1, value: 20, style: { numberFormat: "C2" } }] }, { index: 6, cells: [{ index: 1, value: 20, style: { numberFormat: "C" } }] }, { index: 7, cells: [{ index: 1, value: 20, style: { numberFormat: "N" } }] }, { index: 8, cells: [{ index: 1, value: 20, style: { numberFormat: "N2" } }] }, { index: 9, cells: [{ index: 1, value: 20, style: { numberFormat: "N3" } }] }, { index: 10, cells: [{ index: 1, value: 20, style: { numberFormat: "N4" } }] } ], }] }, 'xlsx', "de-DE"); book.saveAsBlob('application/vnd.openxmlformats-officedocument.spreadsheetml.sheet').then((xlBlob: { blobData: Blob }) => { if (Utils.isDownloadEnabled) { Utils.download(xlBlob.blobData, 'NumberFormatGermanCulture.xlsx'); } 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(); } } }); }); });
the_stack
import * as DOM from 'vs/base/browser/dom'; import { StandardKeyboardEvent } from 'vs/base/browser/keyboardEvent'; import { SimpleIconLabel } from 'vs/base/browser/ui/iconLabel/simpleIconLabel'; import { WorkbenchActionExecutedClassification, WorkbenchActionExecutedEvent } from 'vs/base/common/actions'; import { toErrorMessage } from 'vs/base/common/errorMessage'; import { Emitter, Event } from 'vs/base/common/event'; import { stripIcons } from 'vs/base/common/iconLabels'; import { KeyCode } from 'vs/base/common/keyCodes'; import { Disposable, DisposableStore, dispose } from 'vs/base/common/lifecycle'; import { ElementSizeObserver } from 'vs/editor/browser/config/elementSizeObserver'; import { IDimension, isThemeColor } from 'vs/editor/common/editorCommon'; import { ICommandService } from 'vs/platform/commands/common/commands'; import { IInstantiationService } from 'vs/platform/instantiation/common/instantiation'; import { INotificationService } from 'vs/platform/notification/common/notification'; import { ITelemetryService } from 'vs/platform/telemetry/common/telemetry'; import { IThemeService, ThemeColor } from 'vs/platform/theme/common/themeService'; import { INotebookCellActionContext } from 'vs/workbench/contrib/notebook/browser/controller/coreActions'; import { CodeCellLayoutInfo, MarkdownCellLayoutInfo } from 'vs/workbench/contrib/notebook/browser/notebookBrowser'; import { CellStatusbarAlignment, INotebookCellStatusBarItem } from 'vs/workbench/contrib/notebook/common/notebookCommon'; const $ = DOM.$; export interface IClickTarget { type: ClickTargetType; event: MouseEvent; } export const enum ClickTargetType { Container = 0, ContributedTextItem = 1, ContributedCommandItem = 2 } export class CellEditorStatusBar extends Disposable { readonly statusBarContainer: HTMLElement; private readonly leftItemsContainer: HTMLElement; private readonly rightItemsContainer: HTMLElement; private readonly itemsDisposable: DisposableStore; private leftItems: CellStatusBarItem[] = []; private rightItems: CellStatusBarItem[] = []; private width: number = 0; private currentContext: INotebookCellActionContext | undefined; protected readonly _onDidClick: Emitter<IClickTarget> = this._register(new Emitter<IClickTarget>()); readonly onDidClick: Event<IClickTarget> = this._onDidClick.event; constructor( container: HTMLElement, @IInstantiationService private readonly _instantiationService: IInstantiationService, @IThemeService private readonly _themeService: IThemeService, ) { super(); this.statusBarContainer = DOM.append(container, $('.cell-statusbar-container')); this.statusBarContainer.tabIndex = -1; const leftItemsContainer = DOM.append(this.statusBarContainer, $('.cell-status-left')); const rightItemsContainer = DOM.append(this.statusBarContainer, $('.cell-status-right')); this.leftItemsContainer = DOM.append(leftItemsContainer, $('.cell-contributed-items.cell-contributed-items-left')); this.rightItemsContainer = DOM.append(rightItemsContainer, $('.cell-contributed-items.cell-contributed-items-right')); this.itemsDisposable = this._register(new DisposableStore()); this._register(this._themeService.onDidColorThemeChange(() => this.currentContext && this.update(this.currentContext))); this._register(DOM.addDisposableListener(this.statusBarContainer, DOM.EventType.CLICK, e => { if (e.target === leftItemsContainer || e.target === rightItemsContainer || e.target === this.statusBarContainer) { // hit on empty space this._onDidClick.fire({ type: ClickTargetType.Container, event: e }); } else { if ((e.target as HTMLElement).classList.contains('cell-status-item-has-command')) { this._onDidClick.fire({ type: ClickTargetType.ContributedCommandItem, event: e }); } else { // text this._onDidClick.fire({ type: ClickTargetType.ContributedTextItem, event: e }); } } })); } private layout(): void { if (!this.currentContext) { return; } // TODO@roblou maybe more props should be in common layoutInfo? const layoutInfo = this.currentContext.cell.layoutInfo as CodeCellLayoutInfo | MarkdownCellLayoutInfo; const width = layoutInfo.editorWidth; if (!width) { return; } this.width = width; this.statusBarContainer.style.width = `${width}px`; const maxItemWidth = this.getMaxItemWidth(); this.leftItems.forEach(item => item.maxWidth = maxItemWidth); this.rightItems.forEach(item => item.maxWidth = maxItemWidth); } private getMaxItemWidth() { return this.width / 2; } update(context: INotebookCellActionContext) { this.currentContext = context; this.itemsDisposable.clear(); if (!this.currentContext) { return; } this.itemsDisposable.add(this.currentContext.cell.onDidChangeLayout(() => this.layout())); this.itemsDisposable.add(this.currentContext.cell.onDidChangeCellStatusBarItems(() => this.updateRenderedItems())); this.itemsDisposable.add(this.currentContext.notebookEditor.onDidChangeActiveCell(() => this.updateActiveCell())); this.layout(); this.updateActiveCell(); this.updateRenderedItems(); } private updateActiveCell(): void { const isActiveCell = this.currentContext!.notebookEditor.getActiveCell() === this.currentContext?.cell; this.statusBarContainer.classList.toggle('is-active-cell', isActiveCell); } private updateRenderedItems(): void { const items = this.currentContext!.cell.getCellStatusBarItems(); items.sort((itemA, itemB) => { return (itemB.priority ?? 0) - (itemA.priority ?? 0); }); const maxItemWidth = this.getMaxItemWidth(); const newLeftItems = items.filter(item => item.alignment === CellStatusbarAlignment.Left); const newRightItems = items.filter(item => item.alignment === CellStatusbarAlignment.Right).reverse(); const updateItems = (renderedItems: CellStatusBarItem[], newItems: INotebookCellStatusBarItem[], container: HTMLElement) => { if (renderedItems.length > newItems.length) { const deleted = renderedItems.splice(newItems.length, renderedItems.length - newItems.length); for (let deletedItem of deleted) { container.removeChild(deletedItem.container); deletedItem.dispose(); } } newItems.forEach((newLeftItem, i) => { const existingItem = renderedItems[i]; if (existingItem) { existingItem.updateItem(newLeftItem, maxItemWidth); } else { const item = this._instantiationService.createInstance(CellStatusBarItem, this.currentContext!, newLeftItem, maxItemWidth); renderedItems.push(item); container.appendChild(item.container); } }); }; updateItems(this.leftItems, newLeftItems, this.leftItemsContainer); updateItems(this.rightItems, newRightItems, this.rightItemsContainer); } override dispose() { super.dispose(); dispose(this.leftItems); dispose(this.rightItems); } } class CellStatusBarItem extends Disposable { readonly container = $('.cell-status-item'); set maxWidth(v: number) { this.container.style.maxWidth = v + 'px'; } private _currentItem!: INotebookCellStatusBarItem; private _itemDisposables = this._register(new DisposableStore()); constructor( private readonly _context: INotebookCellActionContext, itemModel: INotebookCellStatusBarItem, maxWidth: number | undefined, @ITelemetryService private readonly _telemetryService: ITelemetryService, @ICommandService private readonly _commandService: ICommandService, @INotificationService private readonly _notificationService: INotificationService, @IThemeService private readonly _themeService: IThemeService, ) { super(); this.updateItem(itemModel, maxWidth); } updateItem(item: INotebookCellStatusBarItem, maxWidth: number | undefined) { this._itemDisposables.clear(); if (!this._currentItem || this._currentItem.text !== item.text) { new SimpleIconLabel(this.container).text = item.text.replace(/\n/g, ' '); } const resolveColor = (color: ThemeColor | string) => { return isThemeColor(color) ? (this._themeService.getColorTheme().getColor(color.id)?.toString() || '') : color; }; this.container.style.color = item.color ? resolveColor(item.color) : ''; this.container.style.backgroundColor = item.backgroundColor ? resolveColor(item.backgroundColor) : ''; this.container.style.opacity = item.opacity ? item.opacity : ''; this.container.classList.toggle('cell-status-item-show-when-active', !!item.onlyShowWhenActive); if (typeof maxWidth === 'number') { this.maxWidth = maxWidth; } let ariaLabel: string; let role: string | undefined; if (item.accessibilityInformation) { ariaLabel = item.accessibilityInformation.label; role = item.accessibilityInformation.role; } else { ariaLabel = item.text ? stripIcons(item.text).trim() : ''; } this.container.setAttribute('aria-label', ariaLabel); this.container.setAttribute('role', role || ''); this.container.title = item.tooltip ?? ''; this.container.classList.toggle('cell-status-item-has-command', !!item.command); if (item.command) { this.container.tabIndex = 0; this._itemDisposables.add(DOM.addDisposableListener(this.container, DOM.EventType.CLICK, _e => { this.executeCommand(); })); this._itemDisposables.add(DOM.addDisposableListener(this.container, DOM.EventType.KEY_DOWN, e => { const event = new StandardKeyboardEvent(e); if (event.equals(KeyCode.Space) || event.equals(KeyCode.Enter)) { this.executeCommand(); } })); } else { this.container.removeAttribute('tabIndex'); } this._currentItem = item; } private async executeCommand(): Promise<void> { const command = this._currentItem.command; if (!command) { return; } const id = typeof command === 'string' ? command : command.id; const args = typeof command === 'string' ? [] : command.arguments ?? []; args.unshift(this._context); this._telemetryService.publicLog2<WorkbenchActionExecutedEvent, WorkbenchActionExecutedClassification>('workbenchActionExecuted', { id, from: 'cell status bar' }); try { await this._commandService.executeCommand(id, ...args); } catch (error) { this._notificationService.error(toErrorMessage(error)); } } } declare const ResizeObserver: any; export interface IResizeObserver { startObserving: () => void; stopObserving: () => void; getWidth(): number; getHeight(): number; dispose(): void; } export class BrowserResizeObserver extends Disposable implements IResizeObserver { private readonly referenceDomElement: HTMLElement | null; private readonly observer: any; private width: number; private height: number; constructor(referenceDomElement: HTMLElement | null, dimension: IDimension | undefined, changeCallback: () => void) { super(); this.referenceDomElement = referenceDomElement; this.width = -1; this.height = -1; this.observer = new ResizeObserver((entries: any) => { for (const entry of entries) { if (entry.target === referenceDomElement && entry.contentRect) { if (this.width !== entry.contentRect.width || this.height !== entry.contentRect.height) { this.width = entry.contentRect.width; this.height = entry.contentRect.height; DOM.scheduleAtNextAnimationFrame(() => { changeCallback(); }); } } } }); } getWidth(): number { return this.width; } getHeight(): number { return this.height; } startObserving(): void { this.observer.observe(this.referenceDomElement!); } stopObserving(): void { this.observer.unobserve(this.referenceDomElement!); } override dispose(): void { this.observer.disconnect(); super.dispose(); } } export function getResizesObserver(referenceDomElement: HTMLElement | null, dimension: IDimension | undefined, changeCallback: () => void): IResizeObserver { if (ResizeObserver) { return new BrowserResizeObserver(referenceDomElement, dimension, changeCallback); } else { return new ElementSizeObserver(referenceDomElement, dimension, changeCallback); } }
the_stack
import { css } from '@emotion/react'; import { neutral, brandBackground, brandBorder, from, until, space, } from '@guardian/source-foundations'; import { ArticleDesign, ArticleSpecial } from '@guardian/libs'; import type { ArticleFormat } from '@guardian/libs'; import { ArticleBody } from '@root/src/web/components/ArticleBody'; import { RightColumn } from '@root/src/web/components/RightColumn'; import { ArticleContainer } from '@root/src/web/components/ArticleContainer'; import { ArticleMeta } from '@root/src/web/components/ArticleMeta'; import { SubMeta } from '@root/src/web/components/SubMeta'; import { ArticleTitle } from '@root/src/web/components/ArticleTitle'; import { ArticleHeadline } from '@root/src/web/components/ArticleHeadline'; import { Standfirst } from '@root/src/web/components/Standfirst'; import { Footer } from '@root/src/web/components/Footer'; import { SubNav } from '@root/src/web/components/SubNav.importable'; import { ElementContainer } from '@root/src/web/components/ElementContainer'; import { MobileStickyContainer, AdSlot } from '@root/src/web/components/AdSlot'; import { Border } from '@root/src/web/components/Border'; import { GridItem } from '@root/src/web/components/GridItem'; import { Caption } from '@root/src/web/components/Caption'; import { HeadlineByline } from '@root/src/web/components/HeadlineByline'; import { Discussion } from '@frontend/web/components/Discussion'; import { Hide } from '@root/src/web/components/Hide'; import { GuardianLabsLines } from '@frontend/web/components/GuardianLabsLines'; import { buildAdTargeting } from '@root/src/lib/ad-targeting'; import { parse } from '@frontend/lib/slot-machine-flags'; import { BannerWrapper } from '@root/src/web/layouts/lib/stickiness'; import { decideLineCount, decideLineEffect, } from '@root/src/web/lib/layoutHelpers'; import { Lines } from '@guardian/source-react-components-development-kitchen'; import { ImmersiveHeader } from './headers/ImmersiveHeader'; import { Island } from '../components/Island'; const ImmersiveGrid = ({ children }: { children: React.ReactNode }) => ( <div css={css` /* IE Fallback */ display: flex; flex-direction: column; ${until.leftCol} { margin-left: 0px; } ${from.leftCol} { margin-left: 151px; } ${from.wide} { margin-left: 230px; } @supports (display: grid) { display: grid; width: 100%; margin-left: 0; /* Explanation of each unit of grid-template-columns Left Column (220 - 1px border) Vertical grey border Main content Right Column */ ${from.wide} { grid-column-gap: 10px; grid-template-columns: 219px 1px 1fr 300px; grid-template-areas: 'caption border title right-column' '. border headline right-column' '. border standfirst right-column' '. border byline right-column' 'lines border body right-column' 'meta border body right-column' 'meta border body right-column' '. border body right-column' '. border . right-column'; } /* Explanation of each unit of grid-template-columns Left Column (220 - 1px border) Vertical grey border Main content Right Column */ ${until.wide} { grid-column-gap: 10px; grid-template-columns: 140px 1px 1fr 300px; grid-template-areas: '. border title right-column' '. border headline right-column' '. border standfirst right-column' '. border byline right-column' 'lines border body right-column' 'meta border body right-column' 'meta border body right-column' '. border body right-column' '. border . right-column'; } /* Explanation of each unit of grid-template-columns Main content Right Column */ ${until.leftCol} { grid-template-columns: 1fr 300px; grid-column-gap: 20px; grid-template-areas: 'title right-column' 'headline right-column' 'standfirst right-column' 'byline right-column' 'caption right-column' 'lines right-column' 'meta right-column' 'body right-column'; } ${until.desktop} { grid-column-gap: 0px; grid-template-columns: 1fr; /* Main content */ grid-template-areas: 'title' 'headline' 'standfirst' 'byline' 'caption' 'lines' 'meta' 'body'; } } `} > {children} </div> ); const maxWidth = css` ${from.desktop} { max-width: 620px; } `; const stretchLines = css` ${until.phablet} { margin-left: -20px; margin-right: -20px; } ${until.mobileLandscape} { margin-left: -10px; margin-right: -10px; } `; interface Props { CAPI: CAPIType; NAV: NavType; format: ArticleFormat; palette: Palette; } const decideCaption = (mainMedia: ImageBlockElement): string => { const caption = []; if (mainMedia && mainMedia.data && mainMedia.data.caption) caption.push(mainMedia.data.caption); if ( mainMedia && mainMedia.displayCredit && mainMedia.data && mainMedia.data.credit ) caption.push(mainMedia.data.credit); return caption.join(' '); }; export const ImmersiveLayout = ({ CAPI, NAV, format, palette, }: Props): JSX.Element => { const { config: { isPaidContent, host }, } = CAPI; const adTargeting: AdTargeting = buildAdTargeting({ isAdFreeUser: CAPI.isAdFreeUser, isSensitive: CAPI.config.isSensitive, videoDuration: CAPI.config.videoDuration, edition: CAPI.config.edition, section: CAPI.config.section, sharedAdTargeting: CAPI.config.sharedAdTargeting, adUnit: CAPI.config.adUnit, }); const showBodyEndSlot = parse(CAPI.slotMachineFlags || '').showBodyEnd || CAPI.config.switches.slotBodyEnd; // TODO: // 1) Read 'forceEpic' value from URL parameter and use it to force the slot to render // 2) Otherwise, ensure slot only renders if `CAPI.config.shouldHideReaderRevenue` equals false. const seriesTag = CAPI.tags.find( (tag) => tag.type === 'Series' || tag.type === 'Blog', ); const showOnwardsLower = seriesTag && CAPI.hasStoryPackage; const showComments = CAPI.isCommentable; const mainMedia = CAPI.mainMediaElements[0] as ImageBlockElement; const captionText = decideCaption(mainMedia); const { branding } = CAPI.commercialProperties[CAPI.editionId]; return ( <> <ImmersiveHeader CAPI={CAPI} NAV={NAV} format={format} palette={palette} /> <main> <ElementContainer showTopBorder={false} showSideBorders={false} backgroundColour={palette.background.article} element="article" > <ImmersiveGrid> {/* Above leftCol, the Caption is controled by ContainerLayout ^^ */} <GridItem area="caption"> <Hide when="above" breakpoint="leftCol"> <Caption palette={palette} captionText={captionText} format={format} shouldLimitWidth={false} /> </Hide> </GridItem> <GridItem area="border"> {format.design === ArticleDesign.PhotoEssay ? ( <></> ) : ( <Border palette={palette} /> )} </GridItem> <GridItem area="title" element="aside"> <> {!mainMedia && ( <div css={css` margin-top: -8px; margin-left: -4px; margin-bottom: 12px; ${until.tablet} { margin-left: -20px; } `} > <ArticleTitle format={format} palette={palette} tags={CAPI.tags} sectionLabel={CAPI.sectionLabel} sectionUrl={CAPI.sectionUrl} guardianBaseURL={ CAPI.guardianBaseURL } badge={CAPI.badge} /> </div> )} </> </GridItem> <GridItem area="headline"> <> {!mainMedia && ( <div css={maxWidth}> <ArticleHeadline format={format} headlineString={CAPI.headline} palette={palette} tags={CAPI.tags} byline={CAPI.author.byline} /> </div> )} </> </GridItem> <GridItem area="standfirst"> <Standfirst format={format} standfirst={CAPI.standfirst} /> </GridItem> <GridItem area="byline"> <HeadlineByline format={format} tags={CAPI.tags} byline={ CAPI.author.byline ? CAPI.author.byline : '' } /> </GridItem> <GridItem area="lines"> {format.design === ArticleDesign.PhotoEssay && format.theme !== ArticleSpecial.Labs ? ( <></> ) : ( <div css={maxWidth}> <div css={stretchLines}> {format.theme === ArticleSpecial.Labs ? ( <GuardianLabsLines /> ) : ( <Lines effect={decideLineEffect( ArticleDesign.Standard, format.theme, )} count={decideLineCount( ArticleDesign.Standard, )} /> )} </div> </div> )} </GridItem> <GridItem area="meta" element="aside"> <div css={maxWidth}> <ArticleMeta branding={branding} format={format} palette={palette} pageId={CAPI.pageId} webTitle={CAPI.webTitle} author={CAPI.author} tags={CAPI.tags} primaryDateline={ CAPI.webPublicationDateDisplay } secondaryDateline={ CAPI.webPublicationSecondaryDateDisplay } /> </div> </GridItem> <GridItem area="body"> <ArticleContainer format={format}> <ArticleBody format={format} palette={palette} blocks={CAPI.blocks} adTargeting={adTargeting} host={host} pageId={CAPI.pageId} webTitle={CAPI.webTitle} /> {showBodyEndSlot && <div id="slot-body-end" />} <Lines count={4} effect="straight" /> <SubMeta palette={palette} format={format} subMetaKeywordLinks={ CAPI.subMetaKeywordLinks } subMetaSectionLinks={ CAPI.subMetaSectionLinks } pageId={CAPI.pageId} webUrl={CAPI.webURL} webTitle={CAPI.webTitle} showBottomSocialButtons={ CAPI.showBottomSocialButtons } badge={CAPI.badge} /> </ArticleContainer> </GridItem> <GridItem area="right-column"> <div css={css` padding-top: 6px; height: 100%; ${from.desktop} { /* above 980 */ margin-left: 20px; margin-right: -20px; } ${from.leftCol} { /* above 1140 */ margin-left: 0px; margin-right: 0px; } `} > <RightColumn> <> {mainMedia && ( <div css={css` margin-top: ${space[4]}px; `} > <AdSlot position="right" display={format.display} /> </div> )} </> </RightColumn> </div> </GridItem> </ImmersiveGrid> </ElementContainer> <ElementContainer padded={false} showTopBorder={false} showSideBorders={false} backgroundColour={neutral[93]} element="aside" > <AdSlot position="merchandising-high" display={format.display} /> </ElementContainer> {/* Onwards (when signed OUT) */} <aside id="onwards-upper-whensignedout" /> {showOnwardsLower && ( <ElementContainer sectionId="onwards-lower-whensignedout" element="section" /> )} {!isPaidContent && showComments && ( <ElementContainer sectionId="comments" element="aside"> <Discussion discussionApiUrl={CAPI.config.discussionApiUrl} shortUrlId={CAPI.config.shortUrlId} isCommentable={CAPI.isCommentable} format={format} discussionD2Uid={CAPI.config.discussionD2Uid} discussionApiClientHeader={ CAPI.config.discussionApiClientHeader } enableDiscussionSwitch={false} isAdFreeUser={CAPI.isAdFreeUser} shouldHideAds={CAPI.shouldHideAds} beingHydrated={false} /> </ElementContainer> )} {/* Onwards (when signed IN) */} <aside id="onwards-upper-whensignedin" /> {showOnwardsLower && ( <ElementContainer sectionId="onwards-lower-whensignedin" element="aside" /> )} {!isPaidContent && ( <ElementContainer sectionId="most-viewed-footer" element="aside" /> )} <ElementContainer padded={false} showTopBorder={false} showSideBorders={false} backgroundColour={neutral[93]} element="aside" > <AdSlot position="merchandising" display={format.display} /> </ElementContainer> </main> {NAV.subNavSections && ( <ElementContainer padded={false} element="aside"> <Island deferUntil="visible"> <SubNav subNavSections={NAV.subNavSections} currentNavLink={NAV.currentNavLink} format={format} /> </Island> </ElementContainer> )} <ElementContainer padded={false} backgroundColour={brandBackground.primary} borderColour={brandBorder.primary} showSideBorders={false} element="footer" > <Footer pageFooter={CAPI.pageFooter} pillar={format.theme} pillars={NAV.pillars} /> </ElementContainer> <BannerWrapper /> <MobileStickyContainer /> </> ); };
the_stack
// // ShadowMapping // /*global renderingCommonCreateRendererInfoFn: false, Camera: false*/ interface ShadowMap { shadowMapTexture: Texture; shadowMapRenderTarget: RenderTarget; lightInstance: LightInstance; // TODO: Is this ever set? DeferredRendering appears to refer to it. texture?: Texture; }; class ShadowMapping { /* tslint:disable:no-unused-variable */ static version = 1; /* tslint:enable:no-unused-variable */ defaultSizeLow = 512; defaultSizeHigh = 1024; blurEnabled = true; gd : GraphicsDevice; md : MathDevice; clearColor : any; // v4 tempMatrix43 : any; // m43 tempV3Up : any; // v3 tempV3At : any; // v3 tempV3Pos : any; // v3 tempV3AxisX : any; // v3 tempV3AxisY : any; // v3 tempV3AxisZ : any; // v3 quadPrimitive : number; quadSemantics : Semantics; quadVertexBuffer : VertexBuffer; pixelOffsetH : number[]; pixelOffsetV : number[]; node : SceneNode; bufferWidth : number; bufferHeight : number; techniqueParameters : TechniqueParameters; shader : Shader; shadowMapsLow : ShadowMap[]; shadowMapsHigh : ShadowMap[]; sizeLow : number; sizeHigh : number; lowIndex : number; highIndex : number; blurTextureHigh : Texture; blurTextureLow : Texture; depthBufferLow : RenderBuffer; depthBufferHigh : RenderBuffer; blurRenderTargetHigh : RenderTarget; blurRenderTargetLow : RenderTarget; occludersExtents : any[]; shadowMappingShader : Shader; rigidTechnique : Technique; skinnedTechnique : Technique; blurTechnique : Technique; shadowTechniqueParameters : TechniqueParameters; skinController : SkinController; // Methods updateShader(sm) { var shader = sm.get("shaders/shadowmapping.cgfx"); if (shader !== this.shadowMappingShader) { this.shader = shader; this.rigidTechnique = shader.getTechnique("rigid"); this.skinnedTechnique = shader.getTechnique("skinned"); this.blurTechnique = shader.getTechnique("blur"); } } update() { /* tslint:disable:no-string-literal */ this.shadowTechniqueParameters['world'] = this.node.world; /* tslint:enable:no-string-literal */ } skinnedUpdate() { var techniqueParameters = this.shadowTechniqueParameters; /* tslint:disable:no-string-literal */ techniqueParameters['world'] = this.node.world; /* tslint:enable:no-string-literal */ var skinController = this.skinController; if (skinController) { /* tslint:disable:no-string-literal */ techniqueParameters['skinBones'] = skinController.output; /* tslint:enable:no-string-literal */ skinController.update(); } } destroyBuffers() { var shadowMaps, numShadowMaps, n, shadowMap, renderTarget, texture; shadowMaps = this.shadowMapsLow; if (shadowMaps) { numShadowMaps = shadowMaps.length; for (n = 0; n < numShadowMaps; n += 1) { shadowMap = shadowMaps[n]; renderTarget = shadowMap.renderTarget; if (renderTarget) { renderTarget.destroy(); shadowMap.renderTarget = null; } texture = shadowMap.texture; if (texture) { texture.destroy(); shadowMap.texture = null; } } shadowMaps.length = 0; } shadowMaps = this.shadowMapsHigh; if (shadowMaps) { numShadowMaps = shadowMaps.length; for (n = 0; n < numShadowMaps; n += 1) { shadowMap = shadowMaps[n]; renderTarget = shadowMap.renderTarget; if (renderTarget) { renderTarget.destroy(); shadowMap.renderTarget = null; } texture = shadowMap.texture; if (texture) { texture.destroy(); shadowMap.texture = null; } } shadowMaps.length = 0; } if (this.blurRenderTargetLow) { this.blurRenderTargetLow.destroy(); this.blurRenderTargetLow = null; } if (this.blurRenderTargetHigh) { this.blurRenderTargetHigh.destroy(); this.blurRenderTargetHigh = null; } if (this.blurTextureLow) { this.blurTextureLow.destroy(); this.blurTextureLow = null; } if (this.blurTextureHigh) { this.blurTextureHigh.destroy(); this.blurTextureHigh = null; } if (this.depthBufferLow) { this.depthBufferLow.destroy(); this.depthBufferLow = null; } if (this.depthBufferHigh) { this.depthBufferHigh.destroy(); this.depthBufferHigh = null; } } updateBuffers(sizeLow, sizeHigh): boolean { if (this.sizeLow === sizeLow && this.sizeHigh === sizeHigh) { return true; } if (!sizeLow && !sizeHigh) { sizeLow = this.sizeLow; sizeHigh = this.sizeHigh; } var gd = this.gd; this.shadowMapsHigh = []; this.shadowMapsLow = []; this.destroyBuffers(); this.depthBufferLow = gd.createRenderBuffer({ width: sizeLow, height: sizeLow, format: "D16" }); this.depthBufferHigh = gd.createRenderBuffer({ width: sizeHigh, height: sizeHigh, format: "D16" }); if (this.blurEnabled) { this.blurTextureLow = gd.createTexture({ name: "blur-low", width: sizeLow, height: sizeLow, format: "R5G6B5", mipmaps: false, renderable: true }); this.blurTextureHigh = gd.createTexture({ name: "blur-high", width: sizeHigh, height: sizeHigh, format: "R5G6B5", mipmaps: false, renderable: true }); } if (this.depthBufferLow && this.depthBufferHigh && (!this.blurEnabled || (this.blurTextureLow && this.blurTextureHigh))) { if (this.blurEnabled) { this.blurRenderTargetLow = gd.createRenderTarget({ colorTexture0: this.blurTextureLow }); this.blurRenderTargetHigh = gd.createRenderTarget({ colorTexture0: this.blurTextureHigh }); if (this.blurRenderTargetLow && this.blurRenderTargetHigh) { this.sizeLow = sizeLow; this.sizeHigh = sizeHigh; return true; } } else { this.sizeLow = sizeLow; this.sizeHigh = sizeHigh; return true; } } this.sizeLow = 0; this.sizeHigh = 0; this.destroyBuffers(); return false; } findVisibleRenderables(lightInstance): boolean { var md = this.md; var light = lightInstance.light; var node = lightInstance.node; var matrix = node.world; var origin = lightInstance.lightOrigin; var target, up, frustumWorld, p0, p1, p2, direction; var halfExtents = light.halfExtents; var shadowMapInfo = lightInstance.shadowMapInfo; if (!shadowMapInfo) { shadowMapInfo = { camera: Camera.create(md), target: md.v3BuildZero() }; lightInstance.shadowMapInfo = shadowMapInfo; } target = shadowMapInfo.target; var camera = shadowMapInfo.camera; if (light.spot) { frustumWorld = md.m33MulM43(light.frustum, matrix, shadowMapInfo.frustumWorld); md.v3Add(origin, md.m43At(frustumWorld, target), target); up = md.m43Up(frustumWorld, this.tempV3Up); shadowMapInfo.frustumWorld = frustumWorld; camera.parallel = false; } else { var nodeUp = md.m43Up(matrix, this.tempV3Up); var nodeAt = md.m43At(matrix, this.tempV3At); var nodePos = md.m43Pos(matrix, this.tempV3Pos); var abs = Math.abs; if (light.point) { md.v3AddScalarMul(nodePos, nodeUp, -halfExtents[1], target); direction = md.v3Sub(target, origin, nodePos); camera.parallel = false; } else // directional { direction = light.direction; var d0 = direction[0]; var d1 = direction[1]; var d2 = direction[2]; p0 = halfExtents[0]; p1 = halfExtents[1]; p2 = halfExtents[2]; var n0 = -p0; var n1 = -p1; var n2 = -p2; var maxDistance = ((d0 * (d0 > 0 ? p0 : n0)) + (d1 * (d1 > 0 ? p1 : n1)) + (d2 * (d2 > 0 ? p2 : n2))); var minDistance = ((d0 * (d0 > 0 ? n0 : p0)) + (d1 * (d1 > 0 ? n1 : p1)) + (d2 * (d2 > 0 ? n2 : p2))); direction = md.m43TransformVector(matrix, light.direction); md.v3AddScalarMul(nodePos, direction, maxDistance, target); origin = md.v3AddScalarMul(nodePos, direction, minDistance); camera.parallel = true; } if (abs(md.v3Dot(direction, nodeAt)) < abs(md.v3Dot(direction, nodeUp))) { up = nodeAt; } else { up = nodeUp; } } // TODO: we do this in the drawShadowMap function as well // could we put this on the lightInstance? this.lookAt(camera, target, up, origin); camera.updateViewMatrix(); if (!lightInstance.lightDepth || light.dynamic) { halfExtents = light.halfExtents; var halfExtents0 = halfExtents[0]; var halfExtents1 = halfExtents[1]; var halfExtents2 = halfExtents[2]; var lightDepth, lightViewWindowX, lightViewWindowY; if (light.spot) { var tan = Math.tan; var acos = Math.acos; frustumWorld = shadowMapInfo.frustumWorld; p0 = md.m43TransformPoint(frustumWorld, md.v3Build(-1, -1, 1)); p1 = md.m43TransformPoint(frustumWorld, md.v3Build( 1, -1, 1)); p2 = md.m43TransformPoint(frustumWorld, md.v3Build(-1, 1, 1)); var p3 = md.m43TransformPoint(frustumWorld, md.v3Build( 1, 1, 1)); var farLightCenter = md.v3Sub(md.v3ScalarMul(md.v3Add4(p0, p1, p2, p3), 0.25), origin); lightDepth = md.v3Length(farLightCenter); if (lightDepth <= 0.0) { lightInstance.shadows = false; return false; } farLightCenter = md.v3ScalarMul(farLightCenter, 1.0 / lightDepth); var farLightRight = md.v3Normalize(md.v3Sub(md.v3ScalarMul(md.v3Add(p0, p2), 0.5), origin)); var farLightTop = md.v3Normalize(md.v3Sub(md.v3ScalarMul(md.v3Add(p0, p1), 0.5), origin)); lightViewWindowX = tan(acos(md.v3Dot(farLightCenter, farLightRight))); lightViewWindowY = tan(acos(md.v3Dot(farLightCenter, farLightTop))); } else if (light.point) { // HACK: as we are only rendering shadowmaps for the lower half var lightOrigin = light.origin; if (lightOrigin) { var displacedTarget = target.slice(); displacedTarget[0] -= lightOrigin[0]; displacedTarget[2] -= lightOrigin[2]; lightDepth = md.v3Length(md.v3Sub(displacedTarget, origin)); lightViewWindowX = (halfExtents0 / lightDepth); lightViewWindowY = (halfExtents2 / lightDepth); } else { lightDepth = halfExtents1; lightViewWindowX = (halfExtents0 / halfExtents1); lightViewWindowY = (halfExtents2 / halfExtents1); } if (lightDepth <= 0.0) { lightInstance.shadows = false; return false; } lightViewWindowX *= 3; lightViewWindowY *= 3; } else // directional { direction = light.direction; var lightUp; if (direction[0] < direction[2] && direction[1] < direction[2]) { lightUp = md.v3Build(0, 1, 0, this.tempV3AxisY); } else { lightUp = md.v3Build(0, 0, 1, this.tempV3AxisY); } var xaxis = md.v3Cross(lightUp, direction, this.tempV3AxisX); var yaxis = md.v3Cross(direction, xaxis, this.tempV3AxisY); var x0 = xaxis[0]; var x1 = xaxis[1]; var x2 = xaxis[2]; var y0 = yaxis[0]; var y1 = yaxis[1]; var y2 = yaxis[2]; lightViewWindowX = ((x0 < 0 ? -x0 : x0) * halfExtents0 + (x1 < 0 ? -x1 : x1) * halfExtents1 + (x2 < 0 ? -x2 : x2) * halfExtents2); lightViewWindowY = ((y0 < 0 ? -y0 : y0) * halfExtents0 + (y1 < 0 ? -y1 : y1) * halfExtents1 + (y2 < 0 ? -y2 : y2) * halfExtents2); lightDepth = md.v3Length(md.v3Sub(target, origin)); } lightInstance.lightViewWindowX = lightViewWindowX; lightInstance.lightViewWindowY = lightViewWindowY; lightInstance.lightDepth = lightDepth; } var distanceScale = (1.0 / 65536); camera.aspectRatio = 1; camera.nearPlane = (lightInstance.lightDepth * distanceScale); camera.farPlane = (lightInstance.lightDepth + distanceScale); camera.recipViewWindowX = 1.0 / lightInstance.lightViewWindowX; camera.recipViewWindowY = 1.0 / lightInstance.lightViewWindowY; camera.viewOffsetX = 0.0; camera.viewOffsetY = 0.0; camera.updateProjectionMatrix(); camera.updateViewProjectionMatrix(); camera.updateFrustumPlanes(); var numStaticOverlappingRenderables = lightInstance.numStaticOverlappingRenderables; var overlappingRenderables = lightInstance.overlappingRenderables; var numOverlappingRenderables = overlappingRenderables.length; var staticNodesChangeCounter = lightInstance.staticNodesChangeCounter; var occludersDrawArray = lightInstance.occludersDrawArray; if (!occludersDrawArray) { occludersDrawArray = new Array(numOverlappingRenderables); lightInstance.occludersDrawArray = occludersDrawArray; // Initialize some properties required on the light instance lightInstance.minLightDistance = 0; lightInstance.maxLightDistance = 0; lightInstance.minLightDistanceX = 0; lightInstance.maxLightDistanceX = 0; lightInstance.minLightDistanceY = 0; lightInstance.maxLightDistanceY = 0; lightInstance.shadowMap = null; lightInstance.shadows = false; } if (node.dynamic || numStaticOverlappingRenderables !== numOverlappingRenderables || shadowMapInfo.staticNodesChangeCounter !== staticNodesChangeCounter) { var occludersExtents = this.occludersExtents; var numOccluders = this._filterOccluders(overlappingRenderables, numStaticOverlappingRenderables, occludersDrawArray, occludersExtents); numOccluders = this._updateOccludersLimits(lightInstance, camera.viewMatrix, camera.frustumPlanes, occludersDrawArray, occludersExtents, numOccluders); occludersDrawArray.length = numOccluders; shadowMapInfo.staticNodesChangeCounter = staticNodesChangeCounter; if (1 < numOccluders) { occludersDrawArray.sort(this._sortNegative); } } return (0 < occludersDrawArray.length); } private _sortNegative(a, b) { return (a.sortKey - b.sortKey); } private _adjustCameraPosition(camera: Camera, minWindowX: number, maxWindowX: number, minWindowY: number, maxWindowY: number): void { var matrix = camera.matrix; var r0 = -matrix[0]; var r1 = -matrix[1]; var r2 = -matrix[2]; var u0 = -matrix[3]; var u1 = -matrix[4]; var u2 = -matrix[5]; var ox = (minWindowX + maxWindowX) / 2.0; var oy = (minWindowY + maxWindowY) / 2.0; var origin0 = ox * r0 + oy * u0; var origin1 = ox * r1 + oy * u1; var origin2 = ox * r2 + oy * u2; matrix[9] += origin0; matrix[10] += origin1; matrix[11] += origin2; camera.updateViewMatrix(); } updateTechniqueParameters(cameraMatrix, lightInstance): void { var md = this.md; var shadowMapInfo = lightInstance.shadowMapInfo; if (!shadowMapInfo) { return; } var camera = shadowMapInfo.camera; var viewMatrix = camera.viewMatrix; var shadowProjection = camera.viewProjectionMatrix; var distanceScale = (1.0 / 65536); var minLightDistance = (lightInstance.minLightDistance - distanceScale); var maxLightDistance = (lightInstance.maxLightDistance + distanceScale); var maxDepthReciprocal = (1.0 / (maxLightDistance - minLightDistance)); var techniqueParameters = lightInstance.techniqueParameters; techniqueParameters.shadowProjection = md.m43MulM44(cameraMatrix, shadowProjection, techniqueParameters.shadowProjection); var viewToShadowMatrix = md.m43Mul(cameraMatrix, viewMatrix, this.tempMatrix43); techniqueParameters.shadowDepth = md.v4Build(-viewToShadowMatrix[2] * maxDepthReciprocal, -viewToShadowMatrix[5] * maxDepthReciprocal, -viewToShadowMatrix[8] * maxDepthReciprocal, (-viewToShadowMatrix[11] - minLightDistance) * maxDepthReciprocal, techniqueParameters.shadowDepth); } drawShadowMap(cameraMatrix, minExtentsHigh, lightInstance) { var md = this.md; var gd = this.gd; var node = lightInstance.node; var light = lightInstance.light; var shadowMapInfo = lightInstance.shadowMapInfo; var camera = shadowMapInfo.camera; var origin = lightInstance.lightOrigin; var halfExtents = light.halfExtents; var halfExtents0 = halfExtents[0]; var halfExtents1 = halfExtents[1]; var halfExtents2 = halfExtents[2]; var lightOrigin; lightInstance.shadows = false; var occludersDrawArray = lightInstance.occludersDrawArray; var numOccluders; if (occludersDrawArray) { numOccluders = occludersDrawArray.length; if (!numOccluders) { return; } } else { return; } var numStaticOverlappingRenderables = lightInstance.numStaticOverlappingRenderables; var numOverlappingRenderables = lightInstance.overlappingRenderables.length; var maxExtentSize = Math.max(halfExtents0, halfExtents1, halfExtents2); var shadowMap, shadowMapTexture, shadowMapRenderTarget, shadowMapSize; if (maxExtentSize >= minExtentsHigh) { shadowMapSize = this.sizeHigh; var shadowMapsHighIndex = this.highIndex; if (shadowMapsHighIndex < this.shadowMapsHigh.length) { shadowMap = this.shadowMapsHigh[shadowMapsHighIndex]; shadowMapTexture = shadowMap.texture; shadowMapRenderTarget = shadowMap.renderTarget; } else { shadowMapTexture = gd.createTexture({ name: "shadowmap-high", width: shadowMapSize, height: shadowMapSize, format: "R5G6B5", mipmaps: false, renderable: true }); if (shadowMapTexture) { shadowMapRenderTarget = gd.createRenderTarget({ colorTexture0: shadowMapTexture, depthBuffer: this.depthBufferHigh }); if (!shadowMapRenderTarget) { shadowMapTexture = null; return; } else { shadowMap = { texture: shadowMapTexture, renderTarget: shadowMapRenderTarget, lightInstance: lightInstance }; this.shadowMapsHigh[shadowMapsHighIndex] = shadowMap; } } else { return; } } this.highIndex = (shadowMapsHighIndex + 1); } else { shadowMapSize = this.sizeLow; var shadowMapsLowIndex = this.lowIndex; if (shadowMapsLowIndex < this.shadowMapsLow.length) { shadowMap = this.shadowMapsLow[shadowMapsLowIndex]; shadowMapTexture = shadowMap.texture; shadowMapRenderTarget = shadowMap.renderTarget; } else { shadowMapTexture = gd.createTexture({ name: "shadowmap-low", width: shadowMapSize, height: shadowMapSize, format: "R5G6B5", mipmaps: false, renderable: true }); if (shadowMapTexture) { shadowMapRenderTarget = gd.createRenderTarget({ colorTexture0: shadowMapTexture, depthBuffer: this.depthBufferLow }); if (!shadowMapRenderTarget) { shadowMapTexture = null; return; } else { shadowMap = { texture: shadowMapTexture, renderTarget: shadowMapRenderTarget, lightInstance: lightInstance }; this.shadowMapsLow[shadowMapsLowIndex] = shadowMap; } } else { return; } } this.lowIndex = (shadowMapsLowIndex + 1); } lightInstance.shadowMap = shadowMap; lightInstance.shadows = true; var distanceScale = (1.0 / 65536); // Need padding to avoid culling near objects var minLightDistance = (lightInstance.minLightDistance - distanceScale); // Need padding to avoid encoding singularity at far plane var maxLightDistance = (lightInstance.maxLightDistance + distanceScale); var lightViewWindowX = lightInstance.lightViewWindowX; var lightViewWindowY = lightInstance.lightViewWindowY; var lightDepth = lightInstance.lightDepth; var lightViewOffsetX = 0; var lightViewOffsetY = 0; if (0 < minLightDistance) { var borderPadding = ((this.blurEnabled ? 3 : 1) / shadowMapSize); var minLightDistanceX = lightInstance.minLightDistanceX; var maxLightDistanceX = lightInstance.maxLightDistanceX; var minLightDistanceY = lightInstance.minLightDistanceY; var maxLightDistanceY = lightInstance.maxLightDistanceY; var minimalViewWindowX, minimalViewWindowY; if (light.directional) { if (minLightDistanceX < -lightViewWindowX) { minLightDistanceX = -lightViewWindowX; } if (maxLightDistanceX > lightViewWindowX) { maxLightDistanceX = lightViewWindowX; } if (minLightDistanceY < -lightViewWindowY) { minLightDistanceY = -lightViewWindowY; } if (maxLightDistanceY > lightViewWindowY) { maxLightDistanceY = lightViewWindowY; } this._adjustCameraPosition(camera, minLightDistanceX, maxLightDistanceX, minLightDistanceY, maxLightDistanceY); minimalViewWindowX = (maxLightDistanceX - minLightDistanceX) / 2.0; minimalViewWindowX += 2 * borderPadding * minimalViewWindowX; minimalViewWindowY = (maxLightDistanceY - minLightDistanceY) / 2.0; minimalViewWindowY += 2 * borderPadding * minimalViewWindowY; if (lightViewWindowX > minimalViewWindowX) { lightViewWindowX = minimalViewWindowX; } if (lightViewWindowY > minimalViewWindowY) { lightViewWindowY = minimalViewWindowY; } } else { var endLightDistance = (lightDepth < maxLightDistance ? lightDepth : maxLightDistance); lightOrigin = light.origin; if (lightOrigin) { var displacedExtent0 = (halfExtents0 + Math.abs(origin[0])); var displacedExtent2 = (halfExtents2 + Math.abs(origin[2])); if (minLightDistanceX < -displacedExtent0) { minLightDistanceX = -displacedExtent0; } if (maxLightDistanceX > displacedExtent0) { maxLightDistanceX = displacedExtent0; } if (minLightDistanceY < -displacedExtent2) { minLightDistanceY = -displacedExtent2; } if (maxLightDistanceY > displacedExtent2) { maxLightDistanceY = displacedExtent2; } } else { if (minLightDistanceX < -halfExtents0) { minLightDistanceX = -halfExtents0; } if (maxLightDistanceX > halfExtents0) { maxLightDistanceX = halfExtents0; } if (minLightDistanceY < -halfExtents2) { minLightDistanceY = -halfExtents2; } if (maxLightDistanceY > halfExtents2) { maxLightDistanceY = halfExtents2; } } minLightDistanceX /= (minLightDistanceX <= 0 ? minLightDistance : endLightDistance); maxLightDistanceX /= (maxLightDistanceX >= 0 ? minLightDistance : endLightDistance); minLightDistanceY /= (minLightDistanceY <= 0 ? minLightDistance : endLightDistance); maxLightDistanceY /= (maxLightDistanceY >= 0 ? minLightDistance : endLightDistance); minimalViewWindowX = ((0.5 * (maxLightDistanceX - minLightDistanceX)) + borderPadding); minimalViewWindowY = ((0.5 * (maxLightDistanceY - minLightDistanceY)) + borderPadding); if (lightViewWindowX > minimalViewWindowX) { lightViewWindowX = minimalViewWindowX; lightViewOffsetX = (minimalViewWindowX + minLightDistanceX - borderPadding); } if (lightViewWindowY > minimalViewWindowY) { lightViewWindowY = minimalViewWindowY; lightViewOffsetY = (minimalViewWindowY + minLightDistanceY - borderPadding); } } } camera.aspectRatio = 1; camera.nearPlane = (lightDepth * distanceScale); camera.farPlane = (lightDepth + distanceScale); camera.recipViewWindowX = 1.0 / lightViewWindowX; camera.recipViewWindowY = 1.0 / lightViewWindowY; camera.viewOffsetX = lightViewOffsetX; camera.viewOffsetY = lightViewOffsetY; if (minLightDistance > camera.nearPlane) { camera.nearPlane = minLightDistance; } if (camera.farPlane > maxLightDistance) { camera.farPlane = maxLightDistance; } camera.updateProjectionMatrix(); camera.updateViewProjectionMatrix(); var viewMatrix = camera.viewMatrix; var shadowProjection = camera.viewProjectionMatrix; var maxDepthReciprocal = (1.0 / (maxLightDistance - minLightDistance)); var techniqueParameters = lightInstance.techniqueParameters; techniqueParameters.shadowProjection = md.m43MulM44(cameraMatrix, shadowProjection, techniqueParameters.shadowProjection); var viewToShadowMatrix = md.m43Mul(cameraMatrix, viewMatrix, this.tempMatrix43); techniqueParameters.shadowDepth = md.v4Build(-viewToShadowMatrix[2] * maxDepthReciprocal, -viewToShadowMatrix[5] * maxDepthReciprocal, -viewToShadowMatrix[8] * maxDepthReciprocal, (-viewToShadowMatrix[11] - minLightDistance) * maxDepthReciprocal, techniqueParameters.shadowDepth); techniqueParameters.shadowSize = shadowMapSize; techniqueParameters.shadowMapTexture = shadowMapTexture; var frameUpdated = lightInstance.frameVisible; if (numStaticOverlappingRenderables === numOverlappingRenderables && !node.dynamic) // No dynamic renderables { if (shadowMap.numRenderables === numOccluders && shadowMap.lightNode === node && (shadowMap.frameUpdated + 1) === frameUpdated) { // No need to update shadowmap //Utilities.log(numOccluders); shadowMap.frameUpdated = frameUpdated; shadowMap.needsBlur = false; return; } else { shadowMap.numRenderables = numOccluders; shadowMap.lightNode = node; shadowMap.frameUpdated = frameUpdated; shadowMap.frameVisible = frameUpdated; shadowMap.needsBlur = this.blurEnabled; } } else { shadowMap.numRenderables = numOccluders; shadowMap.frameVisible = frameUpdated; shadowMap.needsBlur = this.blurEnabled; } if (!gd.beginRenderTarget(shadowMapRenderTarget)) { return; } gd.clear(this.clearColor, 1.0, 0); /* tslint:disable:no-string-literal */ var shadowMapTechniqueParameters = this.techniqueParameters; shadowMapTechniqueParameters['shadowProjectionTranspose'] = md.m44Transpose(shadowProjection, shadowMapTechniqueParameters['shadowProjectionTranspose']); shadowMapTechniqueParameters['shadowDepth'] = md.v4Build(-viewMatrix[2] * maxDepthReciprocal, -viewMatrix[5] * maxDepthReciprocal, -viewMatrix[8] * maxDepthReciprocal, (-viewMatrix[11] - minLightDistance) * maxDepthReciprocal, shadowMapTechniqueParameters['shadowDepth']); /* tslint:enable:no-string-literal */ gd.drawArray(occludersDrawArray, [shadowMapTechniqueParameters], 0); gd.endRenderTarget(); } private _filterOccluders(overlappingRenderables: any[], numStaticOverlappingRenderables: number, occludersDrawArray: any[], occludersExtents: any[]): number { var numOverlappingRenderables = overlappingRenderables.length; var numOccluders = 0; var n, renderable, worldExtents, rendererInfo; var drawParametersArray, numDrawParameters, drawParametersIndex; for (n = 0; n < numOverlappingRenderables; n += 1) { renderable = overlappingRenderables[n]; if (!(renderable.disabled || renderable.node.disabled || renderable.sharedMaterial.meta.noshadows)) { rendererInfo = renderable.rendererInfo; if (!rendererInfo) { rendererInfo = renderingCommonCreateRendererInfoFn(renderable); } if (rendererInfo.shadowMappingUpdate && renderable.shadowMappingDrawParameters) { rendererInfo.shadowMappingUpdate.call(renderable); if (n >= numStaticOverlappingRenderables) { worldExtents = renderable.getWorldExtents(); } else { // We can use the property directly because as it is static it should not change! worldExtents = renderable.worldExtents; } drawParametersArray = renderable.shadowMappingDrawParameters; numDrawParameters = drawParametersArray.length; for (drawParametersIndex = 0; drawParametersIndex < numDrawParameters; drawParametersIndex += 1) { occludersDrawArray[numOccluders] = drawParametersArray[drawParametersIndex]; occludersExtents[numOccluders] = worldExtents; numOccluders += 1; } } } } return numOccluders; } private _updateOccludersLimits(lightInstance: any, viewMatrix: any, frustumPlanes: any[], occludersDrawArray: any[], occludersExtents: any[], numOccluders: number): number { var r0 = -viewMatrix[0]; var r1 = -viewMatrix[3]; var r2 = -viewMatrix[6]; var roffset = viewMatrix[9]; var u0 = -viewMatrix[1]; var u1 = -viewMatrix[4]; var u2 = -viewMatrix[7]; var uoffset = viewMatrix[10]; var d0 = -viewMatrix[2]; var d1 = -viewMatrix[5]; var d2 = -viewMatrix[8]; var offset = viewMatrix[11]; var numPlanes = frustumPlanes.length; var minLightDistance = Number.MAX_VALUE; var maxLightDistance = -minLightDistance; var minLightDistanceX = minLightDistance; var maxLightDistanceX = -minLightDistance; var minLightDistanceY = minLightDistance; var maxLightDistanceY = -minLightDistance; var abs = Math.abs; var n, extents, n0, n1, n2, p0, p1, p2, p, lightDistance; for (n = 0; n < numOccluders; ) { extents = occludersExtents[n]; n0 = extents[0]; n1 = extents[1]; n2 = extents[2]; p0 = extents[3]; p1 = extents[4]; p2 = extents[5]; p = 0; do { var plane = frustumPlanes[p]; var f0 = plane[0]; var f1 = plane[1]; var f2 = plane[2]; var maxDistance = (f0 * (f0 < 0 ? n0 : p0) + f1 * (f1 < 0 ? n1 : p1) + f2 * (f2 < 0 ? n2 : p2) - plane[3]); if (maxDistance < 0.0) { break; } else { // Clamp extents to the part that is inside the plane if (maxDistance < abs(f0) * (p0 - n0)) { if (f0 < 0) { p0 = n0 - (maxDistance / f0); } else { n0 = p0 - (maxDistance / f0); } } if (maxDistance < abs(f1) * (p1 - n1)) { if (f1 < 0) { p1 = n1 - (maxDistance / f1); } else { n1 = p1 - (maxDistance / f1); } } if (maxDistance < abs(f2) * (p2 - n2)) { if (f2 < 0) { p2 = n2 - (maxDistance / f2); } else { n2 = p2 - (maxDistance / f2); } } } p += 1; } while (p < numPlanes); if (p >= numPlanes) { lightDistance = ((d0 * (d0 > 0 ? p0 : n0)) + (d1 * (d1 > 0 ? p1 : n1)) + (d2 * (d2 > 0 ? p2 : n2)) - offset); if (maxLightDistance < lightDistance) { maxLightDistance = lightDistance; } if (0 < minLightDistance) { lightDistance = ((d0 * (d0 > 0 ? n0 : p0)) + (d1 * (d1 > 0 ? n1 : p1)) + (d2 * (d2 > 0 ? n2 : p2)) - offset); if (lightDistance < minLightDistance) { minLightDistance = lightDistance; if (0 >= lightDistance) { n += 1; continue; } } lightDistance = ((r0 * (r0 > 0 ? n0 : p0)) + (r1 * (r1 > 0 ? n1 : p1)) + (r2 * (r2 > 0 ? n2 : p2)) - roffset); if (lightDistance < minLightDistanceX) { minLightDistanceX = lightDistance; } lightDistance = ((r0 * (r0 > 0 ? p0 : n0)) + (r1 * (r1 > 0 ? p1 : n1)) + (r2 * (r2 > 0 ? p2 : n2)) - roffset); if (maxLightDistanceX < lightDistance) { maxLightDistanceX = lightDistance; } lightDistance = ((u0 * (u0 > 0 ? n0 : p0)) + (u1 * (u1 > 0 ? n1 : p1)) + (u2 * (u2 > 0 ? n2 : p2)) - uoffset); if (lightDistance < minLightDistanceY) { minLightDistanceY = lightDistance; } lightDistance = ((u0 * (u0 > 0 ? p0 : n0)) + (u1 * (u1 > 0 ? p1 : n1)) + (u2 * (u2 > 0 ? p2 : n2)) - uoffset); if (maxLightDistanceY < lightDistance) { maxLightDistanceY = lightDistance; } } n += 1; } else { numOccluders -= 1; if (n < numOccluders) { occludersDrawArray[n] = occludersDrawArray[numOccluders]; occludersExtents[n] = occludersExtents[numOccluders]; } else { break; } } } if (minLightDistance < 0) { minLightDistance = 0; } if (maxLightDistance > lightInstance.lightDepth) { maxLightDistance = lightInstance.lightDepth; } lightInstance.minLightDistance = minLightDistance; lightInstance.maxLightDistance = maxLightDistance; lightInstance.minLightDistanceX = minLightDistanceX; lightInstance.maxLightDistanceX = maxLightDistanceX; lightInstance.minLightDistanceY = minLightDistanceY; lightInstance.maxLightDistanceY = maxLightDistanceY; return numOccluders; } blurShadowMaps() { var gd = this.gd; var numShadowMaps, n, shadowMaps, shadowMap, shadowMapBlurTexture, shadowMapBlurRenderTarget; gd.setStream(this.quadVertexBuffer, this.quadSemantics); var shadowMappingBlurTechnique = this.blurTechnique; gd.setTechnique(shadowMappingBlurTechnique); var quadPrimitive = this.quadPrimitive; var pixelOffsetH = this.pixelOffsetH; var pixelOffsetV = this.pixelOffsetV; numShadowMaps = this.highIndex; if (numShadowMaps) { shadowMaps = this.shadowMapsHigh; shadowMapBlurTexture = this.blurTextureHigh; shadowMapBlurRenderTarget = this.blurRenderTargetHigh; pixelOffsetV[1] = pixelOffsetH[0] = (1.0 / this.sizeHigh); for (n = 0; n < numShadowMaps; n += 1) { shadowMap = shadowMaps[n]; if (shadowMap.needsBlur) { // Horizontal if (!gd.beginRenderTarget(shadowMapBlurRenderTarget)) { break; } /* tslint:disable:no-string-literal */ shadowMappingBlurTechnique['shadowMap'] = shadowMap.texture; shadowMappingBlurTechnique['pixelOffset'] = pixelOffsetH; /* tslint:enable:no-string-literal */ gd.draw(quadPrimitive, 4); gd.endRenderTarget(); // Vertical if (!gd.beginRenderTarget(shadowMap.renderTarget)) { break; } /* tslint:disable:no-string-literal */ shadowMappingBlurTechnique['shadowMap'] = shadowMapBlurTexture; shadowMappingBlurTechnique['pixelOffset'] = pixelOffsetV; /* tslint:enable:no-string-literal */ gd.draw(quadPrimitive, 4); gd.endRenderTarget(); } } } numShadowMaps = this.lowIndex; if (numShadowMaps) { shadowMaps = this.shadowMapsLow; shadowMapBlurTexture = this.blurTextureLow; shadowMapBlurRenderTarget = this.blurRenderTargetLow; pixelOffsetV[1] = pixelOffsetH[0] = (1.0 / this.sizeLow); for (n = 0; n < numShadowMaps; n += 1) { shadowMap = shadowMaps[n]; if (shadowMap.needsBlur) { // Horizontal if (!gd.beginRenderTarget(shadowMapBlurRenderTarget)) { break; } /* tslint:disable:no-string-literal */ shadowMappingBlurTechnique['shadowMap'] = shadowMap.texture; shadowMappingBlurTechnique['pixelOffset'] = pixelOffsetH; /* tslint:enable:no-string-literal */ gd.draw(quadPrimitive, 4); gd.endRenderTarget(); // Vertical if (!gd.beginRenderTarget(shadowMap.renderTarget)) { break; } /* tslint:disable:no-string-literal */ shadowMappingBlurTechnique['shadowMap'] = shadowMapBlurTexture; shadowMappingBlurTechnique['pixelOffset'] = pixelOffsetV; /* tslint:enable:no-string-literal */ gd.draw(quadPrimitive, 4); gd.endRenderTarget(); } } } } lookAt(camera, lookAt, up, eyePosition) { var md = this.md; var zaxis = md.v3Sub(eyePosition, lookAt, this.tempV3AxisZ); md.v3Normalize(zaxis, zaxis); var xaxis = md.v3Cross(md.v3Normalize(up, up), zaxis, this.tempV3AxisX); md.v3Normalize(xaxis, xaxis); var yaxis = md.v3Cross(zaxis, xaxis, this.tempV3AxisY); camera.matrix = md.m43Build(xaxis, yaxis, zaxis, eyePosition, camera.matrix); } destroy() { delete this.shader; delete this.rigidTechnique; delete this.skinnedTechnique; delete this.blurTechnique; this.destroyBuffers(); delete this.tempV3AxisZ; delete this.tempV3AxisY; delete this.tempV3AxisX; delete this.tempV3Pos; delete this.tempV3At; delete this.tempV3Up; delete this.tempMatrix43; delete this.clearColor; delete this.quadPrimitive; delete this.quadSemantics; if (this.quadVertexBuffer) { this.quadVertexBuffer.destroy(); delete this.quadVertexBuffer; } delete this.shadowMapsLow; delete this.shadowMapsHigh; delete this.techniqueParameters; delete this.occludersExtents; delete this.md; delete this.gd; } // Constructor function static create(gd, md, shaderManager, effectsManager, sizeLow, sizeHigh, disableBlur?): ShadowMapping { var shadowMapping = new ShadowMapping(); shaderManager.load("shaders/shadowmapping.cgfx"); shadowMapping.gd = gd; shadowMapping.md = md; shadowMapping.clearColor = md.v4Build(1, 1, 1, 1); shadowMapping.tempMatrix43 = md.m43BuildIdentity(); shadowMapping.tempV3Up = md.v3BuildZero(); shadowMapping.tempV3At = md.v3BuildZero(); shadowMapping.tempV3Pos = md.v3BuildZero(); shadowMapping.tempV3AxisX = md.v3BuildZero(); shadowMapping.tempV3AxisY = md.v3BuildZero(); shadowMapping.tempV3AxisZ = md.v3BuildZero(); shadowMapping.quadPrimitive = gd.PRIMITIVE_TRIANGLE_STRIP; shadowMapping.quadSemantics = gd.createSemantics(['POSITION', 'TEXCOORD0']); shadowMapping.quadVertexBuffer = gd.createVertexBuffer({ numVertices: 4, attributes: ['FLOAT2', 'FLOAT2'], dynamic: false, data: [ -1.0, 1.0, 0.0, 1.0, 1.0, 1.0, 1.0, 1.0, -1.0, -1.0, 0.0, 0.0, 1.0, -1.0, 1.0, 0.0 ] }); shadowMapping.pixelOffsetH = [0, 0]; shadowMapping.pixelOffsetV = [0, 0]; shadowMapping.bufferWidth = 0; shadowMapping.bufferHeight = 0; shadowMapping.techniqueParameters = gd.createTechniqueParameters(); shadowMapping.shader = null; shadowMapping.shadowMapsLow = []; shadowMapping.shadowMapsHigh = []; if (disableBlur) { shadowMapping.blurEnabled = false; } else { var precision = gd.maxSupported("FRAGMENT_SHADER_PRECISION"); if (precision && // Just in case the query is not supported precision < 16) { shadowMapping.blurEnabled = false; } } sizeLow = sizeLow || shadowMapping.defaultSizeLow; sizeHigh = sizeHigh || shadowMapping.defaultSizeHigh; shadowMapping.updateBuffers(sizeLow, sizeHigh); shadowMapping.occludersExtents = []; return shadowMapping; } }
the_stack
import * as recursive from 'recursive-readdir'; import { QuickPickItem, QuickPickOptions, Range, Selection, TextDocument, TextDocumentChangeEvent, TextEditor, window, workspace, Position } from 'vscode'; import { ignoreFiles, insertContentToEditor, isMarkdownFileCheckWithoutNotification, matchAll, postWarning } from './common'; import { getLanguageIdentifierQuickPickItems, HighlightLanguage, languages } from './highlight-langs'; import { ExtensionContext, extensions } from 'vscode'; /** * Checks the user input for table creation. * Format - C:R. * Columns and Rows cannot be 0 or negative. * 4 Columns maximum. * @param {number} size - the number of array size after split user input with ':' * @param {string} colStr - the string of requested columns * @param {string} rowStr - the string of requested rows */ export function validateTableRowAndColumnCount(size: number, colStr: string, rowStr: string) { const tableTextRegex = /^-?\d*$/; const col = tableTextRegex.test(colStr) ? Number.parseInt(colStr, undefined) : undefined; const row = tableTextRegex.test(rowStr) ? Number.parseInt(rowStr, undefined) : undefined; if (col === undefined || row === undefined) { return undefined; } if (size !== 2 || isNaN(col) || isNaN(row)) { const errorMsg = 'Please input the number of columns and rows as C:R e.g. 3:4'; postWarning(errorMsg); return false; } else if (col <= 0 || row <= 0) { const errorMsg = "The number of rows or columns can't be zero or negative."; postWarning(errorMsg); return false; } else if (col > 4) { const errorMsg = 'You can only insert up to four columns via Docs Markdown.'; postWarning(errorMsg); return false; } else if (row > 50) { const errorMsg = 'You can only insert up to 50 rows via Docs Markdown.'; postWarning(errorMsg); return false; } else { return true; } } /** * Creates a string that represents a MarkDown table * @param {number} col - the number of columns in the table * @param {number} row - the number of rows in the table */ export function tableBuilder(col: number, row: number) { let str = '\n'; /// create header // DCR update: 893410 [Add leading pipe] for (let c = 1; c <= col; c++) { str += '|' + 'Column' + c + ' |'; for (c = 2; c <= col; c++) { str += 'Column' + c + ' |'; } str += '\n'; } // DCR update: 893410 [Add leading pipe] for (let c = 1; c <= col; c++) { str += '|' + '---------' + '|'; for (c = 2; c <= col; c++) { str += '---------' + '|'; } str += '\n'; } /// create each row for (let r = 1; r <= row; r++) { str += '|' + 'Row' + r + ' |'; for (let c = 2; c <= col; c++) { str += ' |'; } str += '\n'; } return str; } /** * Finds the files, then lets user pick from match list, if more than 1 match. * @param {string} searchTerm - the keyword to search directories for * @param {string} fullPath - optional, the folder to start the search under. */ export async function search( editor: TextEditor, selection: Selection, folderPath: string, fullPath?: string, crossReference?: string ) { // eslint-disable-next-line @typescript-eslint/no-var-requires const path = require('path'); let language: string | null = ''; let possibleLanguage: HighlightLanguage | null = null; let selected: QuickPickItem | undefined; let activeFilePath; let snippetLink: string = ''; if (!crossReference) { const searchTerm = await window.showInputBox({ prompt: 'Enter snippet search terms.' }); if (!searchTerm) { return; } if (fullPath == null) { fullPath = folderPath; } // searches for all files at the given directory path. const files = await recursive(fullPath, ignoreFiles); const fileOptions: QuickPickItem[] = []; files.forEach(file => { const baseName: string = path.parse(file).base; const fileName: string = file; if (fileName.includes(searchTerm)) { fileOptions.push({ label: baseName, description: fileName }); } }); // select from all files found that match search term. selected = await window.showQuickPick(fileOptions); activeFilePath = path.parse(editor.document.fileName).dir; if (!selected) { return; } const target = path.parse(selected.description); const relativePath = path.relative(activeFilePath, target.dir); possibleLanguage = inferLanguageFromFileExtension(target.ext); // change path separator syntax for commonmark snippetLink = path.join(relativePath, target.base).replace(/\\/g, '/'); } else { const inputRepoPath = await window.showInputBox({ prompt: 'Enter file path for Cross-Reference GitHub Repo' }); if (inputRepoPath) { possibleLanguage = inferLanguageFromFileExtension(path.extname(inputRepoPath)); snippetLink = `~/${crossReference}/${inputRepoPath}`; } } if (!!possibleLanguage) { language = possibleLanguage.aliases[0]; } if (!language) { const supportedLanguages = getLanguageIdentifierQuickPickItems(); const options: QuickPickOptions = { placeHolder: 'Select a programming language (required)' }; const qpSelection = await window.showQuickPick(supportedLanguages, options); if (!qpSelection) { postWarning('No code language selected. Abandoning command.'); return; } else { const selectedLang = languages.find(lang => lang.language === qpSelection.label); language = selectedLang ? selectedLang.aliases[0] : null; } } if (!language) { postWarning('Unable to determine language. Abandoning command.'); return; } const selectionRange = new Range( selection.start.line, selection.start.character, selection.end.line, selection.end.character ); const selectorOptions: QuickPickItem[] = []; selectorOptions.push({ label: 'Id', description: 'Select code by id tag (for example: <Snippet1>)' }); selectorOptions.push({ label: 'Range', description: 'Select code by line range (for example: 1-15,18,20)' }); selectorOptions.push({ label: 'None', description: 'Select entire file' }); const choice = await window.showQuickPick(selectorOptions); if (choice) { let snippet: string; switch (choice.label.toLowerCase()) { case 'id': const id = await window.showInputBox({ prompt: 'Enter id to select' }); if (id) { snippet = snippetBuilder(language, snippetLink, id, undefined); await insertContentToEditor(editor, snippet, true, selectionRange); } break; case 'range': const range = await window.showInputBox({ prompt: 'Enter line selection range' }); if (range) { snippet = snippetBuilder(language, snippetLink, undefined, range); await insertContentToEditor(editor, snippet, true, selectionRange); } break; default: snippet = snippetBuilder(language, snippetLink); await insertContentToEditor(editor, snippet, true, selectionRange); break; } } } export function inferLanguageFromFileExtension(fileExtension: string): HighlightLanguage | null { const matches = languages.filter(lang => { return lang.extensions ? lang.extensions.some(ext => ext === fileExtension) : false; }); if (matches && matches.length) { return matches[0]; } return null; } export function internalLinkBuilder( isArt: boolean, pathSelection: string, selectedText: string = '', languageId?: string ) { // eslint-disable-next-line @typescript-eslint/no-var-requires const os = require('os'); let link = ''; let startBrace = ''; if (isArt) { startBrace = '!['; } else { startBrace = '['; } // replace the selected text with the properly formatted link if (pathSelection === '') { link = `${startBrace}${selectedText}]()`; } else { link = `${startBrace}${selectedText}](${pathSelection.replace(/[ ]/g, '%20')})`; } const langId = languageId || 'markdown'; const isYaml = langId === 'yaml' && !isArt; if (isYaml) { link = pathSelection; } // The relative path comparison creates an additional level that is not needed and breaks linking. // The path module adds an additional level so we'll need to handle this in our code. // Update slashes bug 944097. if (os.type() === 'Windows_NT') { link = link.replace(/\\/g, '/'); } if (isArt) { // Art links need backslashes to preview and publish correctly. link = link.replace(/\\/g, '/'); } return link; } export function externalLinkBuilder(link: string, title: string = '') { if (title === '') { title = link; } const externalLink = `[${title}](${link})`; return externalLink; } export function videoLinkBuilder(link: string) { const config = workspace.getConfiguration('markdown'); const previewTripleColonVideoSyntax = config.get<boolean>('previewFeatures'); let videoLink = ''; if (!previewTripleColonVideoSyntax) { videoLink = `> [!VIDEO ${link}]`; } else { videoLink = `:::video source="${link}":::`; } return videoLink; } export function includeBuilder(link: string, title: string) { // Include link syntax for reference: [!INCLUDE[sampleinclude](./includes/sampleinclude.md)] const include = `[!INCLUDE [${title}](${link})]`; return include; } export function snippetBuilder( language: string, relativePath: string, id?: string, range?: string ) { if (id) { return `:::code language="${language}" source="${relativePath}" id="${id}":::`; } else if (range) { return `:::code language="${language}" source="${relativePath}" range="${range}":::`; } else { return `:::code language="${language}" source="${relativePath}":::`; } } /** * Strip out BOM from a string if presented, to prevent exception from JSON.parse function. * In Javascript, \uFEFF represents the Byte Order Mark (BOM). * @param originalText - the original string of text */ export function stripBOMFromString(originalText: string) { if (originalText === undefined) { return undefined; } return originalText.replace(/^\uFEFF/, ''); } /** * Create child process. */ export function createChildProcess(path: any, args: any, options: any) { const spawn = require('child-process-promise').spawn; const promise = spawn(path, args, options); const childProcess = promise.childProcess; return childProcess; } interface IExpressionReplacementPair { expression: RegExp; replacement: string; } const expressionToReplacementMap: IExpressionReplacementPair[] = [ { expression: /\u201c/gm /* double left quote “ */, replacement: '"' }, { expression: /\u201d/gm /* double right quote ” */, replacement: '"' }, { expression: /\u2018/gm /* single left quote ‘ */, replacement: "'" }, { expression: /\u2019/gm /* single right quote ’ */, replacement: "'" }, { expression: /\u00A9/gm /* copyright character © */, replacement: '&copy;' }, { expression: /\u2122/gm /* trademark character ™ */, replacement: '&trade;' }, { expression: /\u00AE/gm /* registered trademark character ® */, replacement: '&reg;' }, { expression: /\u20AC/gm /* euro character € */, replacement: '&euro;' }, { expression: /\u2022/gm /* bullet character • */, replacement: '*' }, // Superscript { expression: /\u2070/gm /* 0 superscript character ⁰ */, replacement: '<sup>0</sup>' }, { expression: /\u00B9/gm /* 1 superscript character ⁴ */, replacement: '<sup>1</sup>' }, { expression: /\u00B2/gm /* 2 superscript character ⁴ */, replacement: '<sup>2</sup>' }, { expression: /\u00B3/gm /* 3 superscript character ⁴ */, replacement: '<sup>3</sup>' }, { expression: /\u2074/gm /* 4 superscript character ⁴ */, replacement: '<sup>4</sup>' }, { expression: /\u2075/gm /* 5 superscript character ⁵ */, replacement: '<sup>5</sup>' }, { expression: /\u2076/gm /* 6 superscript character ⁶ */, replacement: '<sup>6</sup>' }, { expression: /\u2077/gm /* 7 superscript character ⁷ */, replacement: '<sup>7</sup>' }, { expression: /\u2078/gm /* 8 superscript character ⁸ */, replacement: '<sup>8</sup>' }, { expression: /\u2079/gm /* 9 superscript character ⁹ */, replacement: '<sup>9</sup>' }, // Subscript { expression: /\u2080/gm /* 0 subscript character ₀ */, replacement: '<sub>0</sub>' }, { expression: /\u2081/gm /* 1 subscript character ₁ */, replacement: '<sub>1</sub>' }, { expression: /\u2082/gm /* 2 subscript character ₂ */, replacement: '<sub>2</sub>' }, { expression: /\u2083/gm /* 3 subscript character ₃ */, replacement: '<sub>3</sub>' }, { expression: /\u2084/gm /* 4 subscript character ₄ */, replacement: '<sub>4</sub>' }, { expression: /\u2085/gm /* 5 subscript character ₅ */, replacement: '<sub>5</sub>' }, { expression: /\u2086/gm /* 6 subscript character ₆ */, replacement: '<sub>6</sub>' }, { expression: /\u2087/gm /* 7 subscript character ₇ */, replacement: '<sub>7</sub>' }, { expression: /\u2088/gm /* 8 subscript character ₈ */, replacement: '<sub>8</sub>' }, { expression: /\u2089/gm /* 9 subscript character ₉ */, replacement: '<sub>9</sub>' } ]; const tabExpression: RegExp = /\t/gm; /** * Finds and replaces target expressions. For example, smart quotes (`“, ”, ‘, and ’` such as those found in Word documents) with standard quotes. * @param event the event fired when a text document is changed. */ export async function findAndReplaceTargetExpressions(event: TextDocumentChangeEvent) { if (!workspace.getConfiguration('markdown').replaceSmartQuotes) { return; } if (!!event && event.document) { const editor = window.activeTextEditor; if ( editor && isMarkdownFileCheckWithoutNotification(editor) && event.document.fileName === editor.document.fileName ) { const document = event.document; const content = document.getText(); if (!!content) { const replacements: Replacements = []; if (workspace.getConfiguration('editor').insertSpaces) { const tabSize = (workspace.getConfiguration('editor').tabSize as number) || 4; if (!expressionToReplacementMap.some(pair => pair.expression === tabExpression)) { expressionToReplacementMap.push({ expression: tabExpression, replacement: ''.padEnd(tabSize, ' ') }); } } expressionToReplacementMap.forEach( (expressionToReplacement: IExpressionReplacementPair) => { const targetReplacements = findReplacements( document, content, expressionToReplacement.replacement, expressionToReplacement.expression ); if (targetReplacements && targetReplacements.length) { for (let index = 0; index < targetReplacements.length; index++) { const replacement = targetReplacements[index]; replacements.push(replacement); } } } ); if (replacements.length > 0) { await applyReplacements(replacements, editor); } } } } return event; } export interface RegExpWithGroup { expression: RegExp; groups: string[]; } export type RegExpOrRegExpWithGroup = RegExp | RegExpWithGroup; function isRegExp(expression: RegExpOrRegExpWithGroup): expression is RegExp { return (expression as RegExp).source !== undefined; } export interface Replacement { selection: Selection; value: string; } export type Replacements = Replacement[]; export function findReplacements( document: TextDocument, content: string, value: string, expression?: RegExpOrRegExpWithGroup ): Replacements | undefined { if (!expression) { return undefined; } const exp = isRegExp(expression) ? expression : expression.expression; const results = matchAll(exp, content); if (!results || !results.length) { return undefined; } const groups = !isRegExp(expression) ? expression.groups : null; const replacements: Replacements = []; for (let i = 0; i < results.length; i++) { const result = results[i]; if (result !== null && result.length) { const match = groups && result.groups ? result.groups[groups[0]] : result[0]; if (match) { let index = result.index !== undefined ? result.index : -1; if (index === -1) { continue; } if (groups) { index += result[0].indexOf(match); } const startPosition = document.positionAt(index); const endPosition = document.positionAt(index + match.length); const selection = new Selection(startPosition, endPosition); replacements.push({ selection, value: value ? value : document.getText(selection) }); } } } return replacements; } export function findReplacement( document: TextDocument, content: string, value: string, expression?: RegExpOrRegExpWithGroup ): Replacement | undefined { const exp = isRegExp(expression) ? expression : expression.expression; const result = exp ? exp.exec(content) : null; if (result !== null && result.length) { const groups = !isRegExp(expression) ? expression.groups : null; const match = groups && result.groups ? result.groups[groups[0]] : result[0]; if (match && match !== value) { let index = result.index; if (groups) { index += result[0].indexOf(match); } const startPosition = document.positionAt(index); const endPosition = new Position(startPosition.line, startPosition.character + match.length); const selection = new Selection(startPosition, endPosition); return { selection, value: value ? value : document.getText(selection) }; } } return undefined; } export async function applyReplacements(replacements: Replacements, editor: TextEditor) { if (replacements && replacements.length) { await editor.edit(builder => { replacements.forEach(replacement => builder.replace(replacement.selection, replacement.value) ); }); } } export interface RangeValuePair { index: number; length: number; value: string; } export function findMatchesInText( content: string, expression?: RegExpOrRegExpWithGroup ): RangeValuePair[] | undefined { if (!expression) { return undefined; } const exp = isRegExp(expression) ? expression : expression.expression; const results = matchAll(exp, content); if (!results || !results.length) { return undefined; } const groups = !isRegExp(expression) ? expression.groups : null; const values: RangeValuePair[] = []; for (let i = 0; i < results.length; i++) { const result = results[i]; if (result !== null && result.length) { const match = groups && result.groups ? result.groups[groups[0]] : result[0]; if (match) { let index = result.index !== undefined ? result.index : -1; if (index === -1) { continue; } if (groups) { index += result[0].indexOf(match); } values.push({ index, length: match.length, value: match }); } } } return values; } export function checkVersion(context: ExtensionContext) { const extensionVersion = extensions.getExtension('docsmsft.docs-markdown').packageJSON.version; const version = context.globalState.get('version'); if (!version || version !== extensionVersion) { context.globalState.update('version', extensionVersion); return true; } else { return false; } } export function removeFirstOccurrence(str: string, searchstr: string) { const index = str.indexOf(searchstr); if (index === -1) { return str; } return str.slice(0, index) + str.slice(index + searchstr.length); }
the_stack
import { Injectable } from '@angular/core'; import { HttpResponse, HttpParams } from '@angular/common/http'; import { FileEntry } from '@ionic-native/file/ngx'; import { FileUploadOptions, FileUploadResult } from '@ionic-native/file-transfer/ngx'; import { Md5 } from 'ts-md5/dist/md5'; import { Observable } from 'rxjs'; import { timeout } from 'rxjs/operators'; import { CoreNativeToAngularHttpResponse } from '@classes/native-to-angular-http'; import { CoreApp } from '@services/app'; import { CoreFile, CoreFileFormat } from '@services/file'; import { CoreMimetypeUtils } from '@services/utils/mimetype'; import { CoreTextErrorObject, CoreTextUtils } from '@services/utils/text'; import { CoreUtils, PromiseDefer } from '@services/utils/utils'; import { CoreConstants } from '@/core/constants'; import { CoreError } from '@classes/errors/error'; import { CoreInterceptor } from '@classes/interceptor'; import { makeSingleton, Translate, FileTransfer, Http, NativeHttp } from '@singletons'; import { CoreArray } from '@singletons/array'; import { CoreLogger } from '@singletons/logger'; import { CoreWSError } from '@classes/errors/wserror'; import { CoreAjaxError } from '@classes/errors/ajaxerror'; import { CoreAjaxWSError } from '@classes/errors/ajaxwserror'; import { CoreNetworkError } from '@classes/errors/network-error'; import { CoreSite } from '@classes/site'; import { CoreHttpError } from '@classes/errors/httperror'; /** * This service allows performing WS calls and download/upload files. */ @Injectable({ providedIn: 'root' }) export class CoreWSProvider { protected logger: CoreLogger; protected mimeTypeCache: {[url: string]: string | null} = {}; // A "cache" to store file mimetypes to decrease HEAD requests. // eslint-disable-next-line @typescript-eslint/no-explicit-any protected ongoingCalls: {[queueItemId: string]: Promise<any>} = {}; protected retryCalls: RetryCall[] = []; protected retryTimeout = 0; constructor() { this.logger = CoreLogger.getInstance('CoreWSProvider'); } /** * Adds the call data to an special queue to be processed when retrying. * * @param method The WebService method to be called. * @param siteUrl Complete site url to perform the call. * @param data Arguments to pass to the method. * @param preSets Extra settings and information. * @return Deferred promise resolved with the response data in success and rejected with the error if it fails. */ protected addToRetryQueue<T = unknown>( method: string, siteUrl: string, data: Record<string, unknown>, preSets: CoreWSPreSets, ): Promise<T> { const call = { method, siteUrl, data, preSets, deferred: CoreUtils.promiseDefer<T>(), }; this.retryCalls.push(call); return call.deferred.promise; } /** * A wrapper function for a moodle WebService call. * * @param method The WebService method to be called. * @param data Arguments to pass to the method. It's recommended to call convertValuesToString before passing the data. * @param preSets Extra settings and information. * @return Promise resolved with the response data in success and rejected if it fails. */ call<T = unknown>(method: string, data: Record<string, unknown>, preSets: CoreWSPreSets): Promise<T> { if (!preSets) { throw new CoreError(Translate.instant('core.unexpectederror')); } else if (!CoreApp.isOnline()) { throw new CoreNetworkError(); } preSets.typeExpected = preSets.typeExpected || 'object'; if (preSets.responseExpected === undefined) { preSets.responseExpected = true; } const dataToSend = Object.assign({}, data); // Create a new object so the changes don't affect the original data. dataToSend['wsfunction'] = method; dataToSend['wstoken'] = preSets.wsToken; const siteUrl = preSets.siteUrl + '/webservice/rest/server.php?moodlewsrestformat=json'; // There are some ongoing retry calls, wait for timeout. if (this.retryCalls.length > 0) { this.logger.warn('Calls locked, trying later...'); return this.addToRetryQueue<T>(method, siteUrl, dataToSend, preSets); } else { return this.performPost<T>(method, siteUrl, dataToSend, preSets); } } /** * Call a Moodle WS using the AJAX API. Please use it if the WS layer is not an option. * It uses a cache to prevent duplicate requests. * * @param method The WebService method to be called. * @param data Arguments to pass to the method. * @param preSets Extra settings and information. Only some * @return Promise resolved with the response data in success and rejected with CoreAjaxError. */ callAjax<T = unknown>(method: string, data: Record<string, unknown>, preSets: CoreWSAjaxPreSets): Promise<T> { const cacheParams = { methodname: method, args: data, }; let promise = this.getPromiseHttp<T>('ajax', preSets.siteUrl, cacheParams); if (!promise) { promise = this.performAjax<T>(method, data, preSets); promise = this.setPromiseHttp<T>(promise, 'ajax', preSets.siteUrl, cacheParams); } return promise; } /** * Converts an objects values to strings where appropriate. * Arrays (associative or otherwise) will be maintained, null values will be removed. * * @param data The data that needs all the non-object values set to strings. * @param stripUnicode If Unicode long chars need to be stripped. * @return The cleaned object or null if some strings becomes empty after stripping Unicode. */ // eslint-disable-next-line @typescript-eslint/no-explicit-any convertValuesToString(data: any, stripUnicode?: boolean): any { // eslint-disable-next-line @typescript-eslint/no-explicit-any const result: any = Array.isArray(data) ? [] : {}; for (const key in data) { let value = data[key]; if (value == null) { // Skip null or undefined value. continue; } else if (typeof value == 'object') { // Object or array. value = this.convertValuesToString(value, stripUnicode); if (value == null) { return null; } } else if (typeof value == 'string') { if (stripUnicode) { const stripped = CoreTextUtils.stripUnicode(value); if (stripped != value && stripped.trim().length == 0) { return null; } value = stripped; } } else if (typeof value == 'boolean') { /* Moodle does not allow "true" or "false" in WS parameters, only in POST parameters. We've been using "true" and "false" for WS settings "filter" and "fileurl", we keep it this way to avoid changing cache keys. */ if (key == 'moodlewssettingfilter' || key == 'moodlewssettingfileurl') { value = value ? 'true' : 'false'; } else { value = value ? '1' : '0'; } } else if (typeof value == 'number') { value = String(value); } else { // Unknown type. continue; } if (Array.isArray(result)) { result.push(value); } else { result[key] = value; } } return result; } /** * Create a "fake" WS error for local errors. * * @param message The message to include in the error. * @param needsTranslate If the message needs to be translated. * @param translateParams Translation params, if needed. * @return Fake WS error. * @deprecated since 3.9.5. Just create the error directly. */ createFakeWSError(message: string, needsTranslate?: boolean, translateParams?: {[name: string]: string}): CoreError { if (needsTranslate) { message = Translate.instant(message, translateParams); } return new CoreError(message); } /** * It will check if response has failed and throw the propper error. * * @param response WS response. * @param defaultMessage Message to be used in case warnings is empty. */ throwOnFailedStatus(response: CoreStatusWithWarningsWSResponse, defaultMessage: string): void { if (!response.status) { if (response.warnings && response.warnings.length) { throw new CoreWSError(response.warnings[0]); } throw new CoreError(defaultMessage); } } /** * Downloads a file from Moodle using Cordova File API. * * @param url Download url. * @param path Local path to store the file. * @param addExtension True if extension need to be added to the final path. * @param onProgress Function to call on progress. * @return Promise resolved with the downloaded file. */ async downloadFile( url: string, path: string, addExtension?: boolean, onProgress?: (event: ProgressEvent) => void, ): Promise<CoreWSDownloadedFileEntry> { this.logger.debug('Downloading file', url, path, addExtension); if (!CoreApp.isOnline()) { throw new CoreNetworkError(); } // Use a tmp path to download the file and then move it to final location. // This is because if the download fails, the local file is deleted. const tmpPath = path + '.tmp'; try { // Create the tmp file as an empty file. const fileEntry = await CoreFile.createFile(tmpPath); const transfer = FileTransfer.create(); onProgress && transfer.onProgress(onProgress); // Download the file in the tmp file. await transfer.download(url, fileEntry.toURL(), true, { headers: { 'User-Agent': navigator.userAgent, // eslint-disable-line @typescript-eslint/naming-convention }, }); let extension = ''; if (addExtension) { extension = CoreMimetypeUtils.getFileExtension(path) || ''; // Google Drive extensions will be considered invalid since Moodle usually converts them. if (!extension || CoreArray.contains(['gdoc', 'gsheet', 'gslides', 'gdraw', 'php'], extension)) { // Not valid, get the file's mimetype. const mimetype = await this.getRemoteFileMimeType(url); if (mimetype) { const remoteExtension = CoreMimetypeUtils.getExtension(mimetype, url); // If the file is from Google Drive, ignore mimetype application/json. if (remoteExtension && (!extension || mimetype != 'application/json')) { if (extension) { // Remove existing extension since we will use another one. path = CoreMimetypeUtils.removeExtension(path); } path += '.' + remoteExtension; extension = remoteExtension; } } } } // Move the file to the final location. const movedEntry = await CoreFile.moveFile(tmpPath, path); this.logger.debug(`Success downloading file ${url} to ${path} with extension ${extension}`); // Also return the extension and path. return <CoreWSDownloadedFileEntry> Object.assign(movedEntry, { extension: extension, path: path, }); } catch (error) { this.logger.error(`Error downloading ${url} to ${path}`, error); throw error; } } /** * Get a promise from the cache. * * @param method Method of the HTTP request. * @param url Base URL of the HTTP request. * @param params Params of the HTTP request. */ protected getPromiseHttp<T = unknown>(method: string, url: string, params?: Record<string, unknown>): Promise<T> | undefined { const queueItemId = this.getQueueItemId(method, url, params); if (this.ongoingCalls[queueItemId] !== undefined) { return this.ongoingCalls[queueItemId]; } } /** * Perform a HEAD request to get the mimetype of a remote file. * * @param url File URL. * @param ignoreCache True to ignore cache, false otherwise. * @return Promise resolved with the mimetype or '' if failure. */ async getRemoteFileMimeType(url: string, ignoreCache?: boolean): Promise<string> { const cachedMimeType = this.mimeTypeCache[url]; if (cachedMimeType && !ignoreCache) { return cachedMimeType; } try { const response = await this.performHead(url); let mimeType = response.headers.get('Content-Type'); if (mimeType) { // Remove "parameters" like charset. mimeType = mimeType.split(';')[0]; } this.mimeTypeCache[url] = mimeType; return mimeType || ''; } catch (error) { // Error, resolve with empty mimetype. return ''; } } /** * Perform a HEAD request to get the size of a remote file. * * @param url File URL. * @return Promise resolved with the size or -1 if failure. */ getRemoteFileSize(url: string): Promise<number> { return this.performHead(url).then((response) => { const contentLength = response.headers.get('Content-Length'); const size = contentLength ? parseInt(contentLength, 10) : 0; if (size) { return size; } return -1; }).catch(() => -1); } /** * Get a request timeout based on the network connection. * * @return Timeout in ms. */ getRequestTimeout(): number { return CoreApp.isNetworkAccessLimited() ? CoreConstants.WS_TIMEOUT : CoreConstants.WS_TIMEOUT_WIFI; } /** * Get the unique queue item id of the cache for a HTTP request. * * @param method Method of the HTTP request. * @param url Base URL of the HTTP request. * @param params Params of the HTTP request. * @return Queue item ID. */ protected getQueueItemId(method: string, url: string, params?: Record<string, unknown>): string { if (params) { url += '###' + CoreInterceptor.serialize(params); } return method + '#' + Md5.hashAsciiStr(url); } /** * Call a Moodle WS using the AJAX API. * * @param method The WebService method to be called. * @param data Arguments to pass to the method. * @param preSets Extra settings and information. Only some * @return Promise resolved with the response data in success and rejected with CoreAjaxError. */ protected performAjax<T = unknown>(method: string, data: Record<string, unknown>, preSets: CoreWSAjaxPreSets): Promise<T> { // eslint-disable-next-line @typescript-eslint/no-explicit-any let promise: Promise<HttpResponse<any>>; if (preSets.siteUrl === undefined) { throw new CoreAjaxError(Translate.instant('core.unexpectederror')); } else if (!CoreApp.isOnline()) { throw new CoreAjaxError(Translate.instant('core.networkerrormsg')); } if (preSets.responseExpected === undefined) { preSets.responseExpected = true; } const script = preSets.noLogin ? 'service-nologin.php' : 'service.php'; const ajaxData = [{ index: 0, methodname: method, args: this.convertValuesToString(data), }]; // The info= parameter has no function. It is just to help with debugging. // We call it info to match the parameter name use by Moodle's AMD ajax module. let siteUrl = preSets.siteUrl + '/lib/ajax/' + script + '?info=' + method; if (preSets.noLogin && preSets.useGet) { // Send params using GET. siteUrl += '&args=' + encodeURIComponent(JSON.stringify(ajaxData)); promise = this.sendHTTPRequest<T>(siteUrl, { method: 'get', }); } else { promise = this.sendHTTPRequest<T>(siteUrl, { method: 'post', // eslint-disable-next-line @typescript-eslint/no-explicit-any data: <any> ajaxData, serializer: 'json', }); } return promise.then((response) => { let data = response.body; // Some moodle web services return null. // If the responseExpected value is set then so long as no data is returned, we create a blank object. if (!data && !preSets.responseExpected) { data = [{}]; } // Check if error. Ajax layer should always return an object (if error) or an array (if success). if (!data || typeof data != 'object') { throw new CoreAjaxError(Translate.instant('core.serverconnection')); } else if (data.error) { throw new CoreAjaxWSError(data); } // Get the first response since only one request was done. data = data[0]; if (data.error) { throw new CoreAjaxWSError(data.exception); } return data.data; }, (data) => { let message = ''; switch (data.status) { case -2: // Certificate error. message = this.getCertificateErrorMessage(data.error); break; case 404: // AJAX endpoint not found. message = Translate.instant('core.ajaxendpointnotfound', { $a: CoreSite.MINIMUM_MOODLE_VERSION, whoisadmin: Translate.instant('core.whoissiteadmin'), }); break; default: message = Translate.instant('core.serverconnection'); } throw new CoreAjaxError(message, 1, data.status); }); } /** * Perform a HEAD request and save the promise while waiting to be resolved. * * @param url URL to perform the request. * @return Promise resolved with the response. */ performHead<T = unknown>(url: string): Promise<HttpResponse<T>> { let promise = this.getPromiseHttp<HttpResponse<T>>('head', url); if (!promise) { promise = this.sendHTTPRequest<T>(url, { method: 'head', responseType: 'text', }); promise = this.setPromiseHttp<HttpResponse<T>>(promise, 'head', url); } return promise; } /** * Perform the post call. It can be split into several requests. * * @param method The WebService method to be called. * @param siteUrl Complete site url to perform the call. * @param ajaxData Arguments to pass to the method. * @param preSets Extra settings and information. * @return Promise resolved with the response data in success and rejected with CoreWSError if it fails. */ async performPost<T = unknown>( method: string, siteUrl: string, ajaxData: Record<string, unknown>, preSets: CoreWSPreSets, ): Promise<T> { // eslint-disable-next-line @typescript-eslint/no-explicit-any const options: any = {}; // This is done because some returned values like 0 are treated as null if responseType is json. if (preSets.typeExpected == 'number' || preSets.typeExpected == 'boolean' || preSets.typeExpected == 'string') { options.responseType = 'text'; } if (!preSets.splitRequest || !ajaxData[preSets.splitRequest.param]) { return this.performSinglePost(method, siteUrl, ajaxData, preSets, options); } // Split the request into several requests if needed. const promises: Promise<T>[] = []; const splitParam = <unknown[]> ajaxData[preSets.splitRequest.param]; for (let i = 0; i < splitParam.length; i += preSets.splitRequest.maxLength) { // Limit the array sent. const limitedData = Object.assign({}, ajaxData); limitedData[preSets.splitRequest.param] = splitParam.slice(i, i + preSets.splitRequest.maxLength); promises.push(this.performSinglePost(method, siteUrl, limitedData, preSets, options)); } const results = await Promise.all(promises); // Combine the results. const firstResult = results.shift(); if (preSets.splitRequest.combineCallback) { return <T> results.reduce(preSets.splitRequest.combineCallback, firstResult); } return <T> results.reduce((previous: T, current: T) => this.combineObjectsArrays<T>(previous, current), firstResult); } /** * Combine the arrays of two objects, adding them to the first object. * * @param object1 First object. * @param object2 Second object. * @return First object with items added. */ protected combineObjectsArrays<T>(object1: T, object2: T): T { for (const name in object2) { const value = object2[name]; if (Array.isArray(value)) { (object1 as Record<string, unknown>)[name] = (object1[name] as typeof value).concat(value); } } return object1; } /** * Perform a single post request. * * @param method The WebService method to be called. * @param siteUrl Complete site url to perform the call. * @param ajaxData Arguments to pass to the method. * @param preSets Extra settings and information. * @param options Request options. * @return Promise resolved with the response data in success and rejected with CoreWSError if it fails. */ protected performSinglePost<T>( method: string, siteUrl: string, ajaxData: Record<string, unknown>, preSets: CoreWSPreSets, options: any, // eslint-disable-line @typescript-eslint/no-explicit-any ): Promise<T> { // We add the method name to the URL purely to help with debugging. // This duplicates what is in the ajaxData, but that does no harm. // POST variables take precedence over GET. const requestUrl = siteUrl + '&wsfunction=' + method; // Perform the post request. const promise = Http.post(requestUrl, ajaxData, options).pipe(timeout(this.getRequestTimeout())).toPromise(); // eslint-disable-next-line @typescript-eslint/no-explicit-any return promise.then((data: any) => { // Some moodle web services return null. // If the responseExpected value is set to false, we create a blank object if the response is null. if (!data && !preSets.responseExpected) { data = {}; } if (!data) { throw new CoreError(Translate.instant('core.serverconnection')); } else if (typeof data != preSets.typeExpected) { // If responseType is text an string will be returned, parse before returning. if (typeof data == 'string') { if (preSets.typeExpected == 'number') { data = Number(data); if (isNaN(data)) { this.logger.warn(`Response expected type "${preSets.typeExpected}" cannot be parsed to number`); throw new CoreError(Translate.instant('core.errorinvalidresponse')); } } else if (preSets.typeExpected == 'boolean') { if (data === 'true') { data = true; } else if (data === 'false') { data = false; } else { this.logger.warn(`Response expected type "${preSets.typeExpected}" is not true or false`); throw new CoreError(Translate.instant('core.errorinvalidresponse')); } } else { this.logger.warn('Response of type "' + typeof data + `" received, expecting "${preSets.typeExpected}"`); throw new CoreError(Translate.instant('core.errorinvalidresponse')); } } else { this.logger.warn('Response of type "' + typeof data + `" received, expecting "${preSets.typeExpected}"`); throw new CoreError(Translate.instant('core.errorinvalidresponse')); } } if (data.exception !== undefined) { // Special debugging for site plugins, otherwise it's hard to debug errors if the data is cached. if (method == 'tool_mobile_get_content') { this.logger.error('Error calling WS', method, data); } throw new CoreWSError(data); } if (data.debuginfo !== undefined) { throw new CoreError('Error. ' + data.message); } return data; }, (error) => { // If server has heavy load, retry after some seconds. if (error.status == 429) { const retryPromise = this.addToRetryQueue<T>(method, siteUrl, ajaxData, preSets); // Only process the queue one time. if (this.retryTimeout == 0) { this.retryTimeout = parseInt(error.headers.get('Retry-After'), 10) || 5; this.logger.warn(`${error.statusText}. Retrying in ${this.retryTimeout} seconds. ` + `${this.retryCalls.length} calls left.`); setTimeout(() => { this.logger.warn(`Retrying now with ${this.retryCalls.length} calls to process.`); // Finish timeout. this.retryTimeout = 0; this.processRetryQueue(); }, this.retryTimeout * 1000); } else { this.logger.warn('Calls locked, trying later...'); } return retryPromise; } else if (error.status === -2) { throw new CoreError(this.getCertificateErrorMessage(error.error)); } else if (error.status > 0) { throw this.createHttpError(error, error.status); } throw new CoreError(Translate.instant('core.serverconnection')); }); } /** * Get error message about certificate error. * * @param error Exact error message. * @return Certificate error message. */ protected getCertificateErrorMessage(error?: string): string { const message = Translate.instant('core.certificaterror', { whoisadmin: Translate.instant('core.whoissiteadmin'), }); if (error) { return `${message}\n<p>${error}</p>`; } return message; } /** * Retry all requests in the queue. * This function uses recursion in order to add a delay between requests to reduce stress. */ protected processRetryQueue(): void { if (this.retryCalls.length > 0 && this.retryTimeout == 0) { const call = this.retryCalls[0]; this.retryCalls.shift(); // Add a delay between calls. setTimeout(() => { call.deferred.resolve(this.performPost(call.method, call.siteUrl, call.data, call.preSets)); this.processRetryQueue(); }, 200); } else { this.logger.warn(`Retry queue has stopped with ${this.retryCalls.length} calls and ${this.retryTimeout} timeout secs.`); } } /** * Save promise on the cache. * * @param promise Promise to be saved. * @param method Method of the HTTP request. * @param url Base URL of the HTTP request. * @param params Params of the HTTP request. * @return The promise saved. */ protected setPromiseHttp<T = unknown>( promise: Promise<T>, method: string, url: string, params?: Record<string, unknown>, ): Promise<T> { const queueItemId = this.getQueueItemId(method, url, params); this.ongoingCalls[queueItemId] = promise; // HTTP not finished, but we should delete the promise after timeout. const timeout = setTimeout(() => { delete this.ongoingCalls[queueItemId]; }, this.getRequestTimeout()); // HTTP finished, delete from ongoing. return promise.finally(() => { delete this.ongoingCalls[queueItemId]; clearTimeout(timeout); }); } /** * A wrapper function for a synchronous Moodle WebService call. * Warning: This function should only be used if synchronous is a must. It's recommended to use call. * * @param method The WebService method to be called. * @param data Arguments to pass to the method. * @param preSets Extra settings and information. * @return Promise resolved with the response data in success and rejected with the error message if it fails. * @return Request response. */ // eslint-disable-next-line @typescript-eslint/no-explicit-any syncCall<T = unknown>(method: string, data: any, preSets: CoreWSPreSets): T { if (!preSets) { throw new CoreError(Translate.instant('core.unexpectederror')); } else if (!CoreApp.isOnline()) { throw new CoreNetworkError(); } preSets.typeExpected = preSets.typeExpected || 'object'; if (preSets.responseExpected === undefined) { preSets.responseExpected = true; } data = this.convertValuesToString(data || {}, preSets.cleanUnicode); if (data == null) { // Empty cleaned text found. throw new CoreError(Translate.instant('core.unicodenotsupportedcleanerror')); } data.wsfunction = method; data.wstoken = preSets.wsToken; const siteUrl = preSets.siteUrl + '/webservice/rest/server.php?moodlewsrestformat=json'; // Serialize data. data = CoreInterceptor.serialize(data); // Perform sync request using XMLHttpRequest. const xhr = new XMLHttpRequest(); xhr.open('post', siteUrl, false); xhr.setRequestHeader('Content-Type', 'application/x-www-form-urlencoded;charset=utf-8'); xhr.send(data); // Get response. // eslint-disable-next-line @typescript-eslint/no-explicit-any data = ('response' in xhr) ? xhr.response : (<any> xhr).responseText; // Check status. const status = Math.max(xhr.status === 1223 ? 204 : xhr.status, 0); if (status < 200 || status >= 300) { // Request failed. throw new CoreError(data); } // Treat response. data = CoreTextUtils.parseJSON(data); // Some moodle web services return null. // If the responseExpected value is set then so long as no data is returned, we create a blank object. if ((!data || !data.data) && !preSets.responseExpected) { data = {}; } if (!data) { throw new CoreError(Translate.instant('core.serverconnection')); } else if (typeof data != preSets.typeExpected) { this.logger.warn('Response of type "' + typeof data + '" received, expecting "' + preSets.typeExpected + '"'); throw new CoreError(Translate.instant('core.errorinvalidresponse')); } if (data.exception !== undefined || data.debuginfo !== undefined) { throw new CoreWSError(data); } return data; } /* * Uploads a file. * * @param filePath File path. * @param options File upload options. * @param preSets Must contain siteUrl and wsToken. * @param onProgress Function to call on progress. * @return Promise resolved when uploaded. */ async uploadFile( filePath: string, options: CoreWSFileUploadOptions, preSets: CoreWSPreSets, onProgress?: (event: ProgressEvent) => void, ): Promise<CoreWSUploadFileResult> { this.logger.debug(`Trying to upload file: ${filePath}`); if (!filePath || !options || !preSets) { throw new CoreError('Invalid options passed to upload file.'); } if (!CoreApp.isOnline()) { throw new CoreNetworkError(); } const uploadUrl = preSets.siteUrl + '/webservice/upload.php'; const transfer = FileTransfer.create(); onProgress && transfer.onProgress(onProgress); options.httpMethod = 'POST'; options.params = { token: preSets.wsToken, filearea: options.fileArea || 'draft', itemid: options.itemId || 0, }; options.chunkedMode = false; options.headers = { 'User-Agent': navigator.userAgent, // eslint-disable-line @typescript-eslint/naming-convention }; options['Connection'] = 'close'; let success: FileUploadResult; try { success = await transfer.upload(filePath, uploadUrl, options, true); } catch (error) { this.logger.error('Error while uploading file', filePath, error); throw this.createHttpError(error, error.http_status ?? 0); } // eslint-disable-next-line @typescript-eslint/no-explicit-any const data = CoreTextUtils.parseJSON<any>( success.response, null, this.logger.error.bind(this.logger, 'Error parsing response from upload', success.response), ); if (data === null) { throw new CoreError(Translate.instant('core.errorinvalidresponse')); } if (!data) { throw new CoreError(Translate.instant('core.serverconnection')); } else if (typeof data != 'object') { this.logger.warn('Upload file: Response of type "' + typeof data + '" received, expecting "object"'); throw new CoreError(Translate.instant('core.errorinvalidresponse')); } if (data.exception !== undefined) { throw new CoreWSError(data); } else if (data.error !== undefined) { throw new CoreWSError({ errorcode: data.errortype, message: data.error, }); } else if (data[0] && data[0].error !== undefined) { throw new CoreWSError({ errorcode: data[0].errortype, message: data[0].error, }); } // We uploaded only 1 file, so we only return the first file returned. this.logger.debug('Successfully uploaded file', filePath); return data[0]; } /** * Create a CoreHttpError based on a certain error. * * @param error Original error. * @param status Status code (if any). * @return CoreHttpError. */ protected createHttpError(error: CoreTextErrorObject, status: number): CoreHttpError { const message = CoreTextUtils.buildSeveralParagraphsMessage([ Translate.instant('core.cannotconnecttrouble'), CoreTextUtils.getHTMLBodyContent(CoreTextUtils.getErrorMessageFromError(error) || ''), ]); return new CoreHttpError(message, status); } /** * Perform an HTTP request requesting for a text response. * * @param url Url to get. * @return Resolved with the text when done. */ async getText(url: string): Promise<string> { // Fetch the URL content. const options: HttpRequestOptions = { method: 'get', responseType: 'text', }; const response = await this.sendHTTPRequest<string>(url, options); const content = response.body; if (typeof content !== 'string') { throw new Error('Error reading content'); } return content; } /** * Send an HTTP request. In mobile devices it will use the cordova plugin. * * @param url URL of the request. * @param options Options for the request. * @return Promise resolved with the response. */ async sendHTTPRequest<T = unknown>(url: string, options: HttpRequestOptions): Promise<HttpResponse<T>> { // Set default values. options.responseType = options.responseType || 'json'; options.timeout = options.timeout === undefined ? this.getRequestTimeout() : options.timeout; if (CoreApp.isMobile()) { // Use the cordova plugin. if (url.indexOf('file://') === 0) { // We cannot load local files using the http native plugin. Use file provider instead. const content = options.responseType == 'json' ? await CoreFile.readFile<T>(url, CoreFileFormat.FORMATJSON) : await CoreFile.readFile(url, CoreFileFormat.FORMATTEXT); return new HttpResponse<T>({ body: <T> content, headers: undefined, status: 200, statusText: 'OK', url, }); } return NativeHttp.sendRequest(url, options).then((response) => new CoreNativeToAngularHttpResponse(response)); } else { // eslint-disable-next-line @typescript-eslint/no-explicit-any let observable: Observable<HttpResponse<any>>; const angularOptions = <AngularHttpRequestOptions> options; // Use Angular's library. switch (angularOptions.method) { case 'get': observable = Http.get(url, { headers: angularOptions.headers, params: angularOptions.params, observe: 'response', // eslint-disable-next-line @typescript-eslint/no-explicit-any responseType: <any> angularOptions.responseType, }); break; case 'post': if (angularOptions.serializer == 'json') { angularOptions.data = JSON.stringify(angularOptions.data); } observable = Http.post(url, angularOptions.data, { headers: angularOptions.headers, observe: 'response', // eslint-disable-next-line @typescript-eslint/no-explicit-any responseType: <any> angularOptions.responseType, }); break; case 'head': observable = Http.head(url, { headers: angularOptions.headers, observe: 'response', // eslint-disable-next-line @typescript-eslint/no-explicit-any responseType: <any> angularOptions.responseType, }); break; default: throw new CoreError('Method not implemented yet.'); } if (angularOptions.timeout) { observable = observable.pipe(timeout(angularOptions.timeout)); } return observable.toPromise(); } } /** * Check if a URL works (it returns a 2XX status). * * @param url URL to check. * @return Promise resolved with boolean: whether it works. */ async urlWorks(url: string): Promise<boolean> { try { const result = await this.performHead(url); return result.status >= 200 && result.status < 300; } catch (error) { return false; } } } export const CoreWS = makeSingleton(CoreWSProvider); /** * File upload options. */ export interface CoreWSFileUploadOptions extends FileUploadOptions { /** * The file area where to put the file. By default, 'draft'. */ fileArea?: string; /** * Item ID of the area where to put the file. By default, 0. */ itemId?: number; } /** * Structure of warnings returned by WS. */ export type CoreWSExternalWarning = { /** * Item. */ item?: string; /** * Item id. */ itemid?: number; /** * The warning code can be used by the client app to implement specific behaviour. */ warningcode: string; /** * Untranslated english message to explain the warning. */ message: string; }; /** * Special response structure of many webservices that contains success status and warnings. */ export type CoreStatusWithWarningsWSResponse = { status: boolean; // Status: true if success. offline?: boolean; // True if information has been stored in offline for future use. warnings?: CoreWSExternalWarning[]; }; /** * Special response structure of many webservices that contains only warnings. */ export type CoreWarningsWSResponse = { warnings?: CoreWSExternalWarning[]; }; /** * Structure of files returned by WS. */ export type CoreWSExternalFile = { fileurl: string; // Downloadable file url. filename?: string; // File name. filepath?: string; // File path. filesize?: number; // File size. timemodified?: number; // Time modified. mimetype?: string; // File mime type. isexternalfile?: number; // Whether is an external file. repositorytype?: string; // The repository type for external files. }; /** * Structure of files returned by stored_file_exporter. */ export type CoreWSStoredFile = { contextid: number; // Contextid. component: string; // Component. filearea: string; // Filearea. itemid: number; // Itemid. filepath: string; // Filepath. filename: string; // Filename. isdir: boolean; // Isdir. isimage: boolean; // Isimage. timemodified: number; // Timemodified. timecreated: number; // Timecreated. filesize: number; // Filesize. author: string; // Author. license: string; // License. filenameshort: string; // Filenameshort. filesizeformatted: string; // Filesizeformatted. icon: string; // Icon. timecreatedformatted: string; // Timecreatedformatted. timemodifiedformatted: string; // Timemodifiedformatted. url: string; // Url. urls: { export?: string; // The URL used to export the attachment. }; html: { plagiarism?: string; // The HTML source for the Plagiarism Response. }; mimetype: undefined; // File mimetype. @todo Not implemented yet in Moodle, see MDL-71354. }; /** * Common file structures returned by WS. */ export type CoreWSFile = CoreWSExternalFile | CoreWSStoredFile; /** * Data returned by date_exporter. */ export type CoreWSDate = { seconds: number; // Seconds. minutes: number; // Minutes. hours: number; // Hours. mday: number; // Mday. wday: number; // Wday. mon: number; // Mon. year: number; // Year. yday: number; // Yday. weekday: string; // Weekday. month: string; // Month. timestamp: number; // Timestamp. }; /** * PreSets accepted by the WS call. */ export type CoreWSPreSets = { /** * The site URL. */ siteUrl: string; /** * The Webservice token. */ wsToken: string; /** * Defaults to true. Set to false when the expected response is null. */ responseExpected?: boolean; /** * Defaults to 'object'. Use it when you expect a type that's not an object|array. */ typeExpected?: string; /** * Defaults to false. Clean multibyte Unicode chars from data. */ cleanUnicode?: boolean; /** * Whether to split a request if it has too many parameters. Sending too many parameters to the site * can cause the request to fail (see PHP's max_input_vars). */ splitRequest?: CoreWSPreSetsSplitRequest; }; /** * Options to split a request. */ export type CoreWSPreSetsSplitRequest = { /** * Name of the parameter used to split the request if too big. Must be an array parameter. */ param: string; /** * Max number of entries sent per request. */ maxLength: number; /** * Callback to combine the results. If not supplied, arrays in the result will be concatenated. */ combineCallback?: (previousValue: unknown, currentValue: unknown, currentIndex: number, array: unknown[]) => unknown; }; /** * PreSets accepted by AJAX WS calls. */ export type CoreWSAjaxPreSets = { /** * The site URL. */ siteUrl: string; /** * Defaults to true. Set to false when the expected response is null. */ responseExpected?: boolean; /** * Whether to use the no-login endpoint instead of the normal one. Use it for requests that don't require authentication. */ noLogin?: boolean; /** * Whether to send the parameters via GET. Only if noLogin is true. */ useGet?: boolean; }; /** * Options for HTTP requests. */ export type HttpRequestOptions = { /** * The HTTP method. */ method: 'get' | 'post' | 'put' | 'patch' | 'head' | 'delete' | 'options' | 'upload' | 'download'; /** * Payload to send to the server. Only applicable on post, put or patch methods. */ data?: Record<string, unknown>; /** * Query params to be appended to the URL (only applicable on get, head, delete, upload or download methods). */ params?: Record<string, string | number>; /** * Response type. Defaults to json. */ responseType?: 'json' | 'text' | 'arraybuffer' | 'blob'; /** * Timeout for the request in seconds. If undefined, the default value will be used. If null, no timeout. */ timeout?: number; /** * Serializer to use. Defaults to 'urlencoded'. Only for mobile environments. */ serializer?: 'json' | 'urlencoded' | 'utf8' | 'multipart'; /** * Whether to follow redirects. Defaults to true. Only for mobile environments. */ followRedirect?: boolean; /** * Headers. Only for mobile environments. */ headers?: Record<string, string>; /** * File paths to use for upload or download. Only for mobile environments. */ filePath?: string | string[]; /** * Name to use during upload. Only for mobile environments. */ name?: string | string[]; }; /** * Options for JSON HTTP requests using Angular Http. */ type AngularHttpRequestOptions = Omit<HttpRequestOptions, 'data'|'params'> & { // eslint-disable-next-line @typescript-eslint/no-explicit-any data?: Record<string, any> | string; params?: HttpParams | { [param: string]: string | string[]; }; }; /** * Data needed to retry a WS call. */ type RetryCall = { method: string; siteUrl: string; data: Record<string, unknown>; preSets: CoreWSPreSets; deferred: PromiseDefer<unknown>; }; /** * Downloaded file entry. It includes some calculated data. */ export type CoreWSDownloadedFileEntry = FileEntry & { extension: string; // File extension. path: string; // File path. }; export type CoreWSUploadFileResult = { component: string; // Component the file was uploaded to. context: string; // Context the file was uploaded to. userid: number; // User that uploaded the file. filearea: string; // File area the file was uploaded to. filename: string; // File name. filepath: string; // File path. itemid: number; // Item ID the file was uploaded to. license: string; // File license. author: string; // Author name. source: string; // File source. };
the_stack
import debugFactory from 'debug'; import {EventEmitter} from 'events'; import {iterator, multiple} from 'p-event'; import {Context} from './context'; import {ContextEvent, ContextEventListener} from './context-event'; import { ContextEventObserver, ContextEventType, ContextObserver, } from './context-observer'; const debug = debugFactory('loopback:context:subscription'); /** * Subscription of context events. It's modeled after * https://github.com/tc39/proposal-observable. */ export interface Subscription { /** * unsubscribe */ unsubscribe(): void; /** * Is the subscription closed? */ closed: boolean; } /** * Event data for observer notifications */ export interface Notification extends ContextEvent { /** * A snapshot of observers when the original event is emitted */ observers: Set<ContextEventObserver>; } /** * An implementation of `Subscription` interface for context events */ class ContextSubscription implements Subscription { constructor( protected context: Context, protected observer: ContextEventObserver, ) {} private _closed = false; unsubscribe() { this.context.unsubscribe(this.observer); this._closed = true; } get closed() { return this._closed; } } /** * Manager for context observer subscriptions */ export class ContextSubscriptionManager extends EventEmitter { /** * A listener to watch parent context events */ protected _parentContextEventListener?: ContextEventListener; /** * A list of registered context observers. The Set will be created when the * first observer is added. */ protected _observers: Set<ContextEventObserver> | undefined; /** * Internal counter for pending notification events which are yet to be * processed by observers. */ private pendingNotifications = 0; /** * Queue for background notifications for observers */ private notificationQueue: AsyncIterableIterator<Notification> | undefined; constructor(protected readonly context: Context) { super(); this.setMaxListeners(Infinity); } /** * @internal */ get parentContextEventListener() { return this._parentContextEventListener; } /** * @internal */ get observers() { return this._observers; } /** * Wrap the debug statement so that it always print out the context name * as the prefix * @param args - Arguments for the debug */ private _debug(...args: unknown[]) { /* istanbul ignore if */ if (!debug.enabled) return; const formatter = args.shift(); if (typeof formatter === 'string') { debug(`[%s] ${formatter}`, this.context.name, ...args); } else { debug('[%s] ', this.context.name, formatter, ...args); } } /** * Set up an internal listener to notify registered observers asynchronously * upon `bind` and `unbind` events. This method will be called lazily when * the first observer is added. */ private setupEventHandlersIfNeeded() { if (this.notificationQueue != null) return; if (this.context.parent != null) { /** * Add an event listener to its parent context so that this context will * be notified of parent events, such as `bind` or `unbind`. */ this._parentContextEventListener = event => { this.handleParentEvent(event); }; // Listen on the parent context events this.context.parent.on('bind', this._parentContextEventListener!); this.context.parent.on('unbind', this._parentContextEventListener!); } // The following are two async functions. Returned promises are ignored as // they are long-running background tasks. this.startNotificationTask().catch(err => { this.handleNotificationError(err); }); let ctx = this.context.parent; while (ctx) { ctx.subscriptionManager.setupEventHandlersIfNeeded(); ctx = ctx.parent; } } private handleParentEvent(event: ContextEvent) { const {binding, context, type} = event; // Propagate the event to this context only if the binding key does not // exist in this context. The parent binding is shadowed if there is a // binding with the same key in this one. if (this.context.contains(binding.key)) { this._debug( 'Event %s %s is not re-emitted from %s to %s', type, binding.key, context.name, this.context.name, ); return; } this._debug( 'Re-emitting %s %s from %s to %s', type, binding.key, context.name, this.context.name, ); this.context.emitEvent(type, event); } /** * A strongly-typed method to emit context events * @param type Event type * @param event Context event */ private emitEvent<T extends ContextEvent>(type: string, event: T) { this.emit(type, event); } /** * Emit an `error` event * @param err Error */ private emitError(err: unknown) { this.emit('error', err); } /** * Start a background task to listen on context events and notify observers */ private startNotificationTask() { // Set up listeners on `bind` and `unbind` for notifications this.setupNotification('bind', 'unbind'); // Create an async iterator for the `notification` event as a queue this.notificationQueue = iterator(this, 'notification', { // Do not end the iterator if an error event is emitted on the // subscription manager rejectionEvents: [], }); return this.processNotifications(); } /** * Publish an event to the registered observers. Please note the * notification is queued and performed asynchronously so that we allow fluent * APIs such as `ctx.bind('key').to(...).tag(...);` and give observers the * fully populated binding. * * @param event - Context event * @param observers - Current set of context observers */ protected async notifyObservers( event: ContextEvent, observers = this._observers, ) { if (!observers || observers.size === 0) return; const {type, binding, context} = event; for (const observer of observers) { if (typeof observer === 'function') { await observer(type, binding, context); } else if (!observer.filter || observer.filter(binding)) { await observer.observe(type, binding, context); } } } /** * Process notification events as they arrive on the queue */ private async processNotifications() { const events = this.notificationQueue; if (events == null) return; for await (const {type, binding, context, observers} of events) { // The loop will happen asynchronously upon events try { // The execution of observers happen in the Promise micro-task queue await this.notifyObservers({type, binding, context}, observers); this.pendingNotifications--; this._debug( 'Observers notified for %s of binding %s', type, binding.key, ); this.emitEvent('observersNotified', {type, binding, context}); } catch (err) { // Do not reduce the pending notification count so that errors // can be captured by waitUntilPendingNotificationsDone this._debug('Error caught from observers', err); // Errors caught from observers. if (this.listenerCount('error') > 0) { // waitUntilPendingNotificationsDone may be called this.emitError(err); } else { // Emit it to the current context. If no error listeners are // registered, crash the process. this.handleNotificationError(err); } } } } /** * Listen on given event types and emit `notification` event. This method * merge multiple event types into one for notification. * @param eventTypes - Context event types */ private setupNotification(...eventTypes: ContextEventType[]) { for (const type of eventTypes) { this.context.on(type, ({binding, context}) => { // No need to schedule notifications if no observers are present if (!this._observers || this._observers.size === 0) return; // Track pending events this.pendingNotifications++; // Take a snapshot of current observers to ensure notifications of this // event will only be sent to current ones. Emit a new event to notify // current context observers. this.emitEvent('notification', { type, binding, context, observers: new Set(this._observers), }); }); } } /** * Wait until observers are notified for all of currently pending notification * events. * * This method is for test only to perform assertions after observers are * notified for relevant events. */ async waitUntilPendingNotificationsDone(timeout?: number) { const count = this.pendingNotifications; debug('Number of pending notifications: %d', count); if (count === 0) return; await multiple(this, 'observersNotified', {count, timeout}); } /** * Add a context event observer to the context * @param observer - Context observer instance or function */ subscribe(observer: ContextEventObserver): Subscription { this._observers = this._observers ?? new Set(); this.setupEventHandlersIfNeeded(); this._observers.add(observer); return new ContextSubscription(this.context, observer); } /** * Remove the context event observer from the context * @param observer - Context event observer */ unsubscribe(observer: ContextEventObserver): boolean { if (!this._observers) return false; return this._observers.delete(observer); } /** * Check if an observer is subscribed to this context * @param observer - Context observer */ isSubscribed(observer: ContextObserver) { if (!this._observers) return false; return this._observers.has(observer); } /** * Handle errors caught during the notification of observers * @param err - Error */ private handleNotificationError(err: unknown) { // Bubbling up the error event over the context chain // until we find an error listener let ctx: Context | undefined = this.context; while (ctx) { if (ctx.listenerCount('error') === 0) { // No error listener found, try its parent ctx = ctx.parent; continue; } this._debug('Emitting error to context %s', ctx.name, err); ctx.emitError(err); return; } // No context with error listeners found this._debug('No error handler is configured for the context chain', err); // Let it crash now by emitting an error event this.context.emitError(err); } /** * Close the context: clear observers, stop notifications, and remove event * listeners from its parent context. * * @remarks * This method MUST be called to avoid memory leaks once a context object is * no longer needed and should be recycled. An example is the `RequestContext`, * which is created per request. */ close() { this._observers = undefined; if (this.notificationQueue != null) { // Cancel the notification iterator this.notificationQueue.return!(undefined).catch(err => { this.handleNotificationError(err); }); this.notificationQueue = undefined; } if (this.context.parent && this._parentContextEventListener) { this.context.parent.removeListener( 'bind', this._parentContextEventListener, ); this.context.parent.removeListener( 'unbind', this._parentContextEventListener, ); this._parentContextEventListener = undefined; } } }
the_stack
import * as React from 'react'; import { Animated, TextInputProps as RNTextInputProps } from 'react-native'; import { createComponent, createElement, createHook, hexToRgb, mergeRefs, omitCSSProps, pickCSSProps, useTheme, } from 'bumbag/utils'; import { Palette, Size } from 'bumbag/types'; import { Box, BoxProps } from '../Box'; import { Icon, IconProps } from '../Icon'; import { FieldWrapper, FieldWrapperProps } from '../FieldWrapper'; import { Pressable } from '../Pressable'; import { palette, useSpace, usePalette } from '../utils'; import * as styles from './Input.styles'; export type LocalInputProps = { accessibilityLabelledBy?: string; /** Icon to place before the input. */ iconAfter?: string; iconAfterProps?: Partial<IconProps>; /** Icon to place after the input. */ iconBefore?: string; iconBeforeProps?: Partial<IconProps>; inputProps?: Partial<InputProps>; inputRef?: React.Ref<any>; /** Label of the input. */ label?: string; /** Label color of the input. Can be any color in your palette. */ labelTextColor?: Palette; labelProps?: any; palette?: Palette; /** Placeholder color of the input. Can be any color in your palette. */ placeholderTextColor?: Palette; /** State of the input. Can be any color in your palette. */ state?: Palette; /** Alters the size of the input. Can be "small", "medium" or "large" */ size?: Size; }; export type InputProps = BoxProps & RNTextInputProps & LocalInputProps; const defaultProps = { placeholderTextColor: 'gray300', size: 'default', variant: 'bordered' }; const useProps = createHook<InputProps>( (props) => { const ref = React.useRef(); const boxProps = Box.useProps({ ...props, elementRef: mergeRefs(ref, props.elementRef), _focus: true, _hover: true, _active: true, _hoveractive: true, }); const { theme } = useTheme(); return { ...boxProps, accessibilityLabelledBy: props.accessibilityLabelledBy, placeholderTextColor: props.placeholderTextColor ? palette(props.placeholderTextColor)({ theme }) : undefined, }; }, { defaultProps, themeKey: 'native.Input' } ); export const Input = createComponent<InputProps>( (_props) => { const props = { ..._props, ..._props.inputProps }; const { colorMode, disabled, iconAfter, iconAfterProps, iconBefore, iconBeforeProps, label, labelProps, size, } = props; const defaultFontSize = props.fontSize || styles.SIZES[size]; ///////////////////////////////////////////////////////////////////// const [value, setValue] = React.useState(props.defaultValue); const inputRef = React.useRef({ value: null, _lastNativeText: null }); const [isFocused, setIsFocused] = React.useState(false); ///////////////////////////////////////////////////////////////////// const handleBlur = React.useCallback( (e) => { setIsFocused(false); props.onBlur && props.onBlur(e); }, [props] ); const handleChange = React.useCallback( (e) => { setValue(e); props.onChangeText && props.onChangeText(e); }, [props] ); const handleFocus = React.useCallback( (e) => { setIsFocused(true); props.onFocus && props.onFocus(e); }, [props] ); const handlePress = React.useCallback(() => { setIsFocused(true); // @ts-ignore inputRef.current && inputRef.current.focus(); }, []); ///////////////////////////////////////////////////////////////////// const htmlProps = useProps({ ...omitCSSProps({ ...props, ref: mergeRefs(inputRef, props.inputRef), onBlur: handleBlur, onFocus: handleFocus, onChangeText: handleChange, placeholder: !label || props.disabled ? props.placeholder || props.label : '', }), borderLeftRadius: props.borderLeftRadius, borderRightRadius: props.borderRightRadius, }); const element = createElement({ children: props.children, component: styles.StyledInput, htmlProps: { ...htmlProps, iconAfter, iconBefore, styledFontSize: defaultFontSize }, }); ///////////////////////////////////////////////////////////////////// const labelStartColor = usePalette(props.state || props.placeholderTextColor || props.palette || 'gray300'); const labelEndColor = usePalette(props.state || props.labelTextColor || props.palette || 'gray300'); const topStart = useSpace(props.defaultValue ? -0.5 : 0.8, defaultFontSize); const topEnd = useSpace(-0.5, defaultFontSize); const fontSizeStart = useSpace(props.defaultValue ? 0.75 : 1, defaultFontSize); const fontSizeEnd = useSpace(0.75, defaultFontSize); const colorAnimation = React.useRef(new Animated.Value(0)).current; const topAnimation = React.useRef(new Animated.Value(topStart)).current; const fontSizeAnimation = React.useRef(new Animated.Value(0)).current; React.useEffect(() => { if (isFocused || value) { Animated.timing(colorAnimation, { toValue: 1, duration: 100, useNativeDriver: false, }).start(); Animated.timing(topAnimation, { toValue: topEnd, duration: 100, useNativeDriver: false, }).start(); Animated.timing(fontSizeAnimation, { toValue: 1, duration: 100, useNativeDriver: false, }).start(); } else { Animated.timing(colorAnimation, { toValue: 0, duration: 100, useNativeDriver: false, }).start(); Animated.timing(topAnimation, { toValue: topStart, duration: 100, useNativeDriver: false, }).start(); Animated.timing(fontSizeAnimation, { toValue: 0, duration: 100, useNativeDriver: false, }).start(); } }, [ colorAnimation, fontSizeAnimation, fontSizeEnd, fontSizeStart, isFocused, topAnimation, topEnd, topStart, value, ]); const color = colorAnimation.interpolate({ inputRange: [0, 1], outputRange: [hexToRgb(labelStartColor), hexToRgb(labelEndColor)], }); const fontSize = fontSizeAnimation.interpolate({ inputRange: [0, 1], outputRange: [fontSizeStart, fontSizeEnd], }); ///////////////////////////////////////////////////////////////////// return ( <Box colorMode={colorMode} position="relative" {...pickCSSProps(props)}> {element} {iconBefore && ( <styles.StyledIconWrapper colorMode={colorMode} // @ts-ignore isBefore defaultFontSize={defaultFontSize} variant={props.variant} > <Icon color="gray200" icon={iconBefore} size={defaultFontSize} {...iconBeforeProps} /> </styles.StyledIconWrapper> )} {iconAfter && ( <styles.StyledIconWrapper colorMode={colorMode} // @ts-ignore isAfter defaultFontSize={defaultFontSize} variant={props.variant} > <Icon color="gray200" icon={iconAfter} size={defaultFontSize} {...iconAfterProps} /> </styles.StyledIconWrapper> )} {label && !props.disabled && ( <styles.StyledAnimatedLabelWrapper colorMode={colorMode} iconAfter={iconAfter} iconBefore={iconBefore} defaultFontSize={defaultFontSize} variant={props.variant} style={{ position: 'absolute', top: topAnimation }} > <Pressable onPress={handlePress}> <styles.StyledAnimatedLabel colorMode={colorMode} // @ts-ignore color={color} // @ts-ignore fontSize={fontSize} variant={props.variant} _web={{ cursor: 'text' }} {...labelProps} > {label} </styles.StyledAnimatedLabel> </Pressable> </styles.StyledAnimatedLabelWrapper> )} </Box> ); }, { attach: { useProps, displayName: 'native.Input', }, defaultProps, themeKey: 'native.Input', } ); //////////////////////////////////////////////////////////////// export type LocalInputFieldProps = { /** Additional props for the Input component */ inputProps?: InputProps; /** If addonBefore or addonAfter exists, then the addons will render vertically. */ orientation?: 'vertical' | 'horizontal'; useInlineLabel?: boolean; }; export type InputFieldProps = BoxProps & FieldWrapperProps & InputProps & LocalInputFieldProps; const useInputFieldProps = createHook<InputFieldProps>( (props) => { const { accessibilityLabelledBy, children, autoFocus, defaultValue, description, disabled, hint, iconAfter, iconAfterProps, iconBefore, iconBeforeProps, inputRef, inputProps, isOptional, isRequired, labelProps, labelTextColor, orientation, label, size, palette, placeholder, placeholderTextColor, state, value, onBlur, onChangeText, onFocus, overrides, validationText, variant, useInlineLabel, ...restProps } = props; const boxProps = Box.useProps(restProps); return { ...boxProps, children: ( <FieldWrapper description={description} hint={hint} isOptional={isOptional} isRequired={isRequired} label={!useInlineLabel ? label : undefined} overrides={overrides} state={state} variant={variant} validationText={validationText} > <Input accessibilityLabelledBy={accessibilityLabelledBy} iconAfter={iconAfter} iconAfterProps={iconAfterProps} iconBefore={iconBefore} iconBeforeProps={iconBeforeProps} inputProps={inputProps} inputRef={inputRef} label={useInlineLabel ? label : undefined} labelTextColor={labelTextColor} labelProps={labelProps} palette={palette} placeholder={placeholder} placeholderTextColor={placeholderTextColor} state={state} size={size} value={value} variant={variant} onBlur={onBlur} onChangeText={onChangeText} onFocus={onFocus} overrides={overrides} /> </FieldWrapper> ), }; }, { defaultProps: { orientation: 'horizontal' }, themeKey: 'InputField' } ); export const InputField = createComponent<InputFieldProps>( (props) => { const inputFieldProps = useInputFieldProps(props); return createElement({ children: props.children, component: styles.InputField, htmlProps: inputFieldProps, }); }, { attach: { useProps, displayName: 'InputField', }, themeKey: 'InputField', } );
the_stack
import { Autowired, Injectable } from '@opensumi/di'; import { AllowedExtension, IAuthenticationService, IAuthenticationProvider, AuthenticationSessionsChangeEvent, AuthenticationSession, IAccountUsage, StorageProvider, IStorage, URI, STORAGE_SCHEMA, ILogger, IEventBus, ExtensionActivateEvent, Event, Emitter, AuthenticationProviderInformation, Disposable, SessionRequestInfo, formatLocalize, CommandRegistry, IDisposable, noAccountsId, DisposableCollection, } from '@opensumi/ide-core-common'; import { IMenuRegistry, MenuId } from '../menu/next'; @Injectable() export class AuthenticationService extends Disposable implements IAuthenticationService { @Autowired(ILogger) protected readonly logger: ILogger; @Autowired(StorageProvider) protected readonly getStorage: StorageProvider; @Autowired(IEventBus) protected readonly eventBus: IEventBus; @Autowired(IMenuRegistry) protected readonly menus: IMenuRegistry; @Autowired(CommandRegistry) protected readonly commands: CommandRegistry; private _onDidRegisterAuthenticationProvider: Emitter<AuthenticationProviderInformation> = this.registerDispose( new Emitter<AuthenticationProviderInformation>(), ); public readonly onDidRegisterAuthenticationProvider: Event<AuthenticationProviderInformation> = this._onDidRegisterAuthenticationProvider.event; private _onDidUnregisterAuthenticationProvider: Emitter<AuthenticationProviderInformation> = this.registerDispose( new Emitter<AuthenticationProviderInformation>(), ); readonly onDidUnregisterAuthenticationProvider: Event<AuthenticationProviderInformation> = this._onDidUnregisterAuthenticationProvider.event; private _onDidChangeSessions: Emitter<{ providerId: string; label: string; event: AuthenticationSessionsChangeEvent; }> = this.registerDispose( new Emitter<{ providerId: string; label: string; event: AuthenticationSessionsChangeEvent }>(), ); readonly onDidChangeSessions: Event<{ providerId: string; label: string; event: AuthenticationSessionsChangeEvent }> = this._onDidChangeSessions.event; private _storage: IStorage; private _authenticationProviders: Map<string, IAuthenticationProvider> = new Map<string, IAuthenticationProvider>(); private _signInRequestItems = new Map<string, SessionRequestInfo>(); private _noAccountsMenuItem: IDisposable | undefined; async initialize() { this._storage = await this.getStorage(new URI('authentication').withScheme(STORAGE_SCHEMA.GLOBAL)); const disposableMap = new Map<string, DisposableCollection>(); this.onDidChangeSessions(async (e) => { if (e.event.added.length > 0) { const sessions = await this.getSessions(e.providerId); sessions.forEach((session) => { if (sessions.find((s) => disposableMap.get(s.id))) { return; } const disposables = new DisposableCollection(); const signOutCommandId = `account-sign-out-${e.providerId}-${session.id}`; const signOutCommand = this.commands.registerCommand( { id: signOutCommandId, label: formatLocalize('authentication.signOut', e.label), }, { execute: async () => { await this.signOutOfAccount(e.providerId, session.account.label); }, }, ); const manageTrustedCommandId = `manage-trusted-${e.providerId}-${session.id}`; const manageTrustedCommand = this.commands.registerCommand( { id: manageTrustedCommandId, label: '%authentication.manageTrustedExtensions%', }, { execute: async () => { await this.manageTrustedExtensionsForAccount(e.providerId, session.account.label); }, }, ); const accountMenuId = `${e.providerId}${session.account.label}`; const accountMenu = this.menus.registerMenuItem(MenuId.AccountsContext, { submenu: accountMenuId, label: `${session.account.label} (${e.label})`, }); const menuAction = this.menus.registerMenuItems(accountMenuId, [ { command: manageTrustedCommandId, }, { command: signOutCommandId, }, ]); disposables.push(accountMenu); disposables.push(menuAction); disposables.push(signOutCommand); disposables.push(manageTrustedCommand); disposableMap.set(session.id, disposables); }); } if (e.event.removed.length > 0) { e.event.removed.forEach((removed) => { const toDispose = disposableMap.get(removed.id); if (toDispose) { toDispose.dispose(); disposableMap.delete(removed.id); } }); } }); } get storage() { return this._storage; } registerAuthenticationProvider(id: string, provider: IAuthenticationProvider) { this._authenticationProviders.set(id, provider); this._onDidRegisterAuthenticationProvider.fire({ id, label: provider.label }); this.updateAccountsMenuItem(); } async sessionsUpdate(providerId: string, event: AuthenticationSessionsChangeEvent) { const provider = this._authenticationProviders.get(providerId); if (provider) { this._onDidChangeSessions.fire({ providerId, label: provider.label, event }); await provider.updateSessionItems(event); this.updateAccountsMenuItem(); if (event.added) { await this.updateNewSessionRequests(provider); } } } private async updateNewSessionRequests(provider: IAuthenticationProvider): Promise<void> { const existingRequestsForProvider = this._signInRequestItems.get(provider.id); if (!existingRequestsForProvider) { return; } const sessions = await provider.getSessions(); Object.keys(existingRequestsForProvider).forEach((requestedScopes) => { if (sessions.some((session) => session.scopes.slice().sort().join('') === requestedScopes)) { const sessionRequest = existingRequestsForProvider[requestedScopes]; if (sessionRequest) { sessionRequest.disposables.forEach((item) => item.dispose()); } delete existingRequestsForProvider[requestedScopes]; if (Object.keys(existingRequestsForProvider).length === 0) { this._signInRequestItems.delete(provider.id); } else { this._signInRequestItems.set(provider.id, existingRequestsForProvider); } } }); } private getTrustedKey(providerId: string, accountName: string) { return `trusted-${providerId}-${accountName}`; } async getAllowedExtensions(providerId: string, accountName: string) { const storageKey = this.getTrustedKey(providerId, accountName); let trustedExtensions: AllowedExtension[] = []; try { const trustedExtensionSrc = await this.storage.get<string>(storageKey); if (trustedExtensionSrc) { trustedExtensions = JSON.parse(trustedExtensionSrc); } } catch (err) { this.logger.warn('read allow extensions error: ' + err); } return trustedExtensions; } async setAllowedExtensions(providerId: string, accountName: string, allowList: AllowedExtension[]) { const storageKey = this.getTrustedKey(providerId, accountName); await this.storage.set(storageKey, JSON.stringify(allowList)); } async removeAllowedExtensions(providerId: string, accountName: string) { const storageKey = this.getTrustedKey(providerId, accountName); await this.storage.delete(storageKey); } async updatedAllowedExtension( providerId: string, accountName: string, extensionId: string, extensionName: string, isAllowed: boolean, ) { const allowList = await this.getAllowedExtensions(providerId, accountName); const index = allowList.findIndex((extension) => extension.id === extensionId); if (index === -1) { allowList.push({ id: extensionId, name: extensionName, allowed: isAllowed }); } else { allowList[index].allowed = isAllowed; } await this.setAllowedExtensions(providerId, accountName, allowList); } async isAccessAllowed(providerId: string, accountName: string, extensionId: string) { const allowList = await this.getAllowedExtensions(providerId, accountName); const extensionData = allowList.find((extension) => extension.id === extensionId); if (extensionData) { // This property didn't exist on this data previously, inclusion in the list at all indicates allowance return extensionData.allowed !== undefined ? extensionData.allowed : true; } // TODO: Need to allow access to whitelist extension return false; } private async tryActivateProvider(providerId: string): Promise<IAuthenticationProvider> { await this.eventBus.fireAndAwait(new ExtensionActivateEvent({ topic: 'onView', data: providerId })); let provider = this._authenticationProviders.get(providerId); if (provider) { return provider; } // When activate has completed, the extension has made the call to `registerAuthenticationProvider`. // However, activate cannot block on this, so the renderer may not have gotten the event yet. const didRegister: Promise<IAuthenticationProvider> = new Promise((resolve, _) => { this.onDidRegisterAuthenticationProvider((e) => { if (e.id === providerId) { provider = this._authenticationProviders.get(providerId); if (provider) { resolve(provider); } else { throw new Error(`No authentication provider '${providerId}' is currently registered.`); } } }); }); const didTimeout: Promise<IAuthenticationProvider> = new Promise((_, reject) => { setTimeout(() => { reject(new Error(`didRegister ${providerId} timeout`)); }, 5000); }); return Promise.race([didRegister, didTimeout]); } async getSessions(providerId: string): Promise<ReadonlyArray<AuthenticationSession>> { try { const authProvider = this._authenticationProviders.get(providerId) || (await this.tryActivateProvider(providerId)); return await authProvider.getSessions(); } catch (_) { throw new Error(`No authentication provider '${providerId}' is currently registered.`); } } isAuthenticationProviderRegistered(id: string): boolean { return this._authenticationProviders.has(id); } getProviderIds(): string[] { const providerIds: string[] = []; this._authenticationProviders.forEach((provider) => { providerIds.push(provider.id); }); return providerIds; } unregisterAuthenticationProvider(id: string): void { const provider = this._authenticationProviders.get(id); if (provider) { provider.dispose(); this._authenticationProviders.delete(id); this._onDidUnregisterAuthenticationProvider.fire({ id, label: provider.label }); this.updateAccountsMenuItem(); } } private updateAccountsMenuItem(): void { let hasSession = false; this._authenticationProviders.forEach((provider) => { hasSession = hasSession || provider.hasSessions(); }); if (hasSession && this._noAccountsMenuItem) { this._noAccountsMenuItem.dispose(); this._noAccountsMenuItem = undefined; } if (!hasSession && !this._noAccountsMenuItem) { this._noAccountsMenuItem = this.menus.registerMenuItem(MenuId.AccountsContext, { group: '0_accounts', command: noAccountsId, }); } } async requestNewSession(providerId: string, scopes: string[], extensionId: string, extensionName: string) { let provider = this._authenticationProviders.get(providerId); if (!provider) { // Activate has already been called for the authentication provider, but it cannot block on registering itself // since this is sync and returns a disposable. So, wait for registration event to fire that indicates the // provider is now in the map. await new Promise<void>((resolve, _) => { this.onDidRegisterAuthenticationProvider((e) => { if (e.id === providerId) { provider = this._authenticationProviders.get(providerId); resolve(); } }); }); } if (provider) { const providerRequests = this._signInRequestItems.get(providerId); const scopesList = scopes.sort().join(''); const extensionHasExistingRequest = providerRequests && providerRequests[scopesList] && providerRequests[scopesList].requestingExtensionIds.includes(extensionId); if (extensionHasExistingRequest) { return; } const signInCommand = this.commands.registerCommand( { id: `${extensionId}signIn`, label: formatLocalize('authentication.signInRequests', extensionName), }, { execute: async () => { const session = await this.login(providerId, scopes); const accountName = session.account.label; // Add extension to allow list since user explicitly signed in on behalf of it const allowList = await this.getAllowedExtensions(providerId, accountName); if (!allowList.find((allowed) => allowed.id === extensionId)) { allowList.push({ id: extensionId, name: extensionName }); await this.setAllowedExtensions(providerId, accountName, allowList); } // And also set it as the preferred account for the extension await this.setExtensionSessionId(extensionName, providerId, session.id); }, }, ); const menuItem = this.menus.registerMenuItem(MenuId.AccountsContext, { group: '2_signInRequests', command: `${extensionId}signIn`, }); if (providerRequests) { const existingRequest = providerRequests[scopesList] || { disposables: [], requestingExtensionIds: [] }; providerRequests[scopesList] = { disposables: [...existingRequest.disposables, menuItem, signInCommand], requestingExtensionIds: [...existingRequest.requestingExtensionIds, extensionId], }; this._signInRequestItems.set(providerId, providerRequests); } else { this._signInRequestItems.set(providerId, { [scopesList]: { disposables: [menuItem, signInCommand], requestingExtensionIds: [extensionId], }, }); } } } getLabel(providerId: string): string { const authProvider = this._authenticationProviders.get(providerId); if (authProvider) { return authProvider.label; } else { throw new Error(`No authentication provider '${providerId}' has been declared.`); } } supportsMultipleAccounts(providerId: string): boolean { const authProvider = this._authenticationProviders.get(providerId); if (authProvider) { return authProvider.supportsMultipleAccounts; } else { throw new Error(`No authentication provider '${providerId}' is currently registered.`); } } async login(providerId: string, scopes: string[]): Promise<AuthenticationSession> { try { const authProvider = this._authenticationProviders.get(providerId) || (await this.tryActivateProvider(providerId)); return await authProvider.login(scopes); } catch (err) { throw new Error( `No authentication provider '${providerId}' is currently registered, error messge: ${err.message}`, ); } } logout(providerId: string, sessionId: string): Promise<void> { const authProvider = this._authenticationProviders.get(providerId); if (authProvider) { return authProvider.logout(sessionId); } else { throw new Error(`No authentication provider '${providerId}' is currently registered.`); } } manageTrustedExtensionsForAccount(providerId: string, accountName: string): Promise<void> { const authProvider = this._authenticationProviders.get(providerId); if (authProvider) { return authProvider.manageTrustedExtensions(accountName); } else { throw new Error(`No authentication provider '${providerId}' is currently registered.`); } } signOutOfAccount(providerId: string, accountName: string): Promise<void> { const authProvider = this._authenticationProviders.get(providerId); if (authProvider) { return authProvider.signOut(accountName); } else { throw new Error(`No authentication provider '${providerId}' is currently registered.`); } } private getUsagesKey(providerId: string, accountName: string) { return `usages-${providerId}-${accountName}`; } async getAccountUsages(providerId: string, accountName: string) { const accountKey = this.getUsagesKey(providerId, accountName); const storedUsages = await this.storage.get<string>(accountKey); let usages: IAccountUsage[] = []; if (storedUsages) { try { usages = JSON.parse(storedUsages); } catch (err) { this.logger.warn('parse account usages error: ' + err); } } return usages; } async addAccountUsage(providerId: string, accountName: string, extensionId: string, extensionName: string) { const accountKey = this.getUsagesKey(providerId, accountName); const usages = await this.getAccountUsages(providerId, accountName); const existingUsageIndex = usages.findIndex((usage) => usage.extensionId === extensionId); if (existingUsageIndex > -1) { usages.splice(existingUsageIndex, 1, { extensionId, extensionName, lastUsed: Date.now(), }); } else { usages.push({ extensionId, extensionName, lastUsed: Date.now(), }); } await this.storage.set(accountKey, JSON.stringify(usages)); } async removeAccountUsage(providerId: string, accountName: string) { const accountKey = this.getUsagesKey(providerId, accountName); await this.storage.delete(accountKey); } private getExtensionSessionIdKey(providerId: string, accountName: string) { return `session-${providerId}-${accountName}`; } async getExtensionSessionId(extensionName: string, providerId: string): Promise<string | undefined> { const accountKey = this.getExtensionSessionIdKey(extensionName, providerId); return await this.storage.get(accountKey); } async setExtensionSessionId(extensionName: string, providerId: string, sessionId: string): Promise<void> { const accountKey = this.getExtensionSessionIdKey(extensionName, providerId); await this.storage.set(accountKey, sessionId); } async removeExtensionSessionId(extensionName: string, providerId: string): Promise<void> { const accountKey = this.getExtensionSessionIdKey(extensionName, providerId); await this.storage.delete(accountKey); } }
the_stack
import * as d3 from 'd3'; import Pikaday from '../../../packages/pikaday/pikaday'; import '../../../packages/pikaday/css/pikaday.css' import moment from 'moment'; import './DateTimePicker.scss'; import { ChartComponent } from '../../Interfaces/ChartComponent'; import TimezonePicker from '../TimezonePicker/TimezonePicker'; import Utils from "../../Utils"; class DateTimePicker extends ChartComponent{ private calendar: any; private calendarPicker: any; private timeControls: any; private minMillis: number; private maxMillis: number; private fromMillis: number; private toMillis: number; private fromMinutes: number; private fromHours: number; private toMinutes: number; private toHours: number; private onSet: any; private onCancel: any; private isValid: boolean = true; private targetElement: any; private dateTimeSelectionPanel: any; private quickTimesPanel: any; private isSettingStartTime: boolean = true; private startRange; private endRange; private anchorDate; private offsetName: string; private fromInput: any; private toInput: any; private quickTimeArray: Array<any> = [ ["Last 15 mins", 15 * 60 * 1000], ["Last 30 mins", 30 * 60 * 1000], ["Last Hour", 60 * 60 * 1000], ["Last 2 Hours", 2 * 60 * 60 * 1000], ["Last 4 Hours", 4 * 60 * 60 * 1000], ["Last 12 Hours", 12 * 60 * 60 * 1000], ["Last 24 Hours", 24 * 60 * 60 * 1000], ["Last 7 Days", 7 * 24 * 60 * 60 * 1000], ["Last 30 Days", 30 * 24 * 60 * 60 * 1000], ["Last 90 Days", 90 * 24 * 60 * 60 * 1000] ]; constructor(renderTarget: Element){ super(renderTarget); } // returns -1 if not currently a quicktime private getCurrentQuickTime () { let matchingQuickTime = this.quickTimeArray.filter((quickTimeTuple) => { return (this.toMillis - this.fromMillis === quickTimeTuple[1]); }); if (matchingQuickTime.length !== 1 || this.toMillis !== this.maxMillis) { return -1; } return matchingQuickTime[0][1]; } public getQuickTimeText (quickTimeMillis) { let filteredQuickTime = this.quickTimeArray.filter((quickTimeTuple) => { return (quickTimeMillis === quickTimeTuple[1]); }); if (filteredQuickTime.length !== 1) { return null; } return filteredQuickTime[0][0]; } private convertToCalendarDate (millis) { return this.roundDay(Utils.adjustDateFromTimezoneOffset(Utils.offsetFromUTC(new Date(millis), this.chartOptions.offset))) } private setNewOffset (oldOffset: any) { var valuesToUpdate = ['fromMillis', 'toMillis']; valuesToUpdate.forEach((currValue: string) => { var oldOffsetMinutes = Utils.getMinutesToUTC(oldOffset, this[currValue]); var utcMillis = this[currValue] - (oldOffsetMinutes * 60 * 1000); this[currValue] = utcMillis - Utils.getOffsetMinutes(this.chartOptions.offset, utcMillis) * 60 * 1000; }); this.setFromMillis(this.fromMillis); this.setToMillis(this.toMillis); this.updateDisplayedFromDateTime(); this.updateDisplayedToDateTime(); this.startRange = new Date(this.fromMillis); this.endRange = new Date(this.toMillis); this.calendarPicker.config({minDate: this.convertToCalendarDate(this.minMillis)}); this.calendarPicker.config({maxDate: this.convertToCalendarDate(this.maxMillis)}); this.calendarPicker.draw(); var rangeErrorCheck = this.rangeIsValid(this.fromMillis, this.toMillis); this.setIsSaveable(rangeErrorCheck.isSaveable); this.displayRangeErrors(rangeErrorCheck.errors); } private onSaveOrCancel = () => { this.isSettingStartTime = true; } public render (chartOptions: any = {}, minMillis: number, maxMillis: number, fromMillis: number = null, toMillis: number = null, onSet = null, onCancel = null) { this.isSettingStartTime = true; this.minMillis = minMillis; this.maxMillis = maxMillis; if (chartOptions.offset && (typeof chartOptions.offset === "string")) { this.offsetName = chartOptions.offset; } if (toMillis == null) { toMillis = this.maxMillis; } if (fromMillis == null) { fromMillis = Math.max(toMillis - (24 * 60 * 60 * 1000), minMillis); } this.chartOptions.setOptions(chartOptions); moment.locale(this.chartOptions.dateLocale); this.fromMillis = fromMillis; this.toMillis = toMillis; this.onSet = onSet; this.onCancel = onCancel; this.targetElement = d3.select(this.renderTarget) .classed("tsi-dateTimePicker", true); this.targetElement.html(''); super.themify(this.targetElement, this.chartOptions.theme); let group = this.targetElement.append('div') .classed('tsi-dateTimeGroup', true) .on('keydown', (e) => { if (d3.event.keyCode <= 40 && d3.event.keyCode >= 37) { //arrow key d3.event.stopPropagation(); } if (d3.event.keyCode === 27 && this.chartOptions.dTPIsModal) { //escape this.onCancel(); this.onSaveOrCancel(); } }); this.quickTimesPanel = group.append('div') .classed('tsi-quickTimesPanel', true); this.buildQuickTimesPanel(); this.dateTimeSelectionPanel = group.append('div') .classed('tsi-dateTimeSelectionPanel', true); this.timeControls = this.dateTimeSelectionPanel.append("div").classed("tsi-timeControlsContainer", true); this.calendar = this.dateTimeSelectionPanel.append("div").classed("tsi-calendarPicker", true); this.createTimezonePicker(); var saveButtonContainer = this.dateTimeSelectionPanel.append("div").classed("tsi-saveButtonContainer", true); var self = this; var saveButton = saveButtonContainer.append("button").classed("tsi-saveButton", true).text(this.getString("Save")) .on("click", function () { self.onSet(self.fromMillis, self.toMillis, self.chartOptions.offset, self.maxMillis === self.toMillis, self.getCurrentQuickTime()); self.onSaveOrCancel(); }); var cancelButton = saveButtonContainer.append('button') .attr('class', 'tsi-cancelButton') .text(this.getString('Cancel')) .on('click', () => { this.onCancel(); this.onSaveOrCancel(); }) .on('keydown', () => { if (d3.event.keyCode === 9 && !d3.event.shiftKey && this.chartOptions.dTPIsModal) { // tab this.quickTimesPanel.selectAll('.tsi-quickTime') .filter((d, i) => i === 0) .node() .focus(); d3.event.preventDefault(); } }); //originally set toMillis to last possible time this.toMillis = this.maxMillis; this.setFromMillis(fromMillis); this.setToMillis(toMillis); this.targetElement.append("div").classed("tsi-errorMessageContainer", true); this.createTimePicker(); this.createCalendar(); this.calendarPicker.draw(); this.updateDisplayedFromDateTime(); this.updateDisplayedToDateTime(); this.startRange = new Date(this.fromMillis); this.endRange = new Date(this.toMillis); this.calendarPicker.draw(); return; } private updateDisplayedDateTimes () { ['from', 'to'].forEach((fromOrTo) => { var selectedDate = new Date(this[fromOrTo + 'Millis']); this.calendarPicker.setDate(this.roundDay(Utils.offsetFromUTC(selectedDate))); this[fromOrTo + 'Input'].node().value = this.createTimeString(Utils.offsetFromUTC(selectedDate)); }) } private setFromQuickTimes (relativeMillis) { this.isSettingStartTime = true; this.setToMillis(this.maxMillis); this.setFromMillis(this.maxMillis - relativeMillis); this.updateDisplayedFromDateTime(); this.updateDisplayedToDateTime(); this.calendarPicker.draw(); } private buildQuickTimesPanel () { let quickTimes = this.quickTimesPanel.selectAll('.tsi-quickTime') .data(this.quickTimeArray); let enteredQuickTimes = quickTimes.enter() .append('button') .attr('class', 'tsi-quickTime') .on('click', (d) => { this.setFromQuickTimes(d[1]); }) .text((d) => d[0]) .attr('aria-label', (d) => `${this.getString('select quick time of')} ${d[0]}`); // wrap around tab order if dTP in modal form let firstQuickTime = enteredQuickTimes.filter((d, i) => { return (i === 0); }) .on('keydown', () => { if (d3.event.keyCode === 9 && d3.event.shiftKey && this.chartOptions.dTPIsModal) { // shift tab this.dateTimeSelectionPanel.select(".tsi-saveButtonContainer").select(".tsi-cancelButton").node().focus(); d3.event.preventDefault(); } }); if (this.chartOptions.dTPIsModal) { firstQuickTime.node().focus(); } } private createTimeString (currDate: Date) { return this.getTimeFormat()(currDate); } private getTimeFormat () { return Utils.timeFormat(true, true, this.chartOptions.offset, true, 0, null, this.chartOptions.dateLocale); } public updateFromAndTo (fromMillis, toMillis) { this.setFromMillis(fromMillis); this.setToMillis(toMillis); this.updateDisplayedFromDateTime(); this.updateDisplayedToDateTime(); this.startRange = new Date(this.fromMillis); this.endRange = new Date(this.toMillis); this.calendarPicker.draw(); } private createTimezonePicker () { const offset = this.chartOptions.offset; if (this.chartOptions.includeTimezones && (typeof offset == "string" || offset == 0)) { var timezoneContainer = this.dateTimeSelectionPanel.append("div").attr("class", "tsi-timezoneContainer"); let timezoneSelectionLabelID = Utils.guid(); let timezoneSelectionID = timezoneSelectionLabelID + 'Tz'; timezoneContainer.append("label") .classed("tsi-timeLabel", true) .attr('aria-label', this.getString('timezone selection')) .attr('id', timezoneSelectionLabelID) .attr('for', timezoneSelectionID) .text(this.getString('timezone')); var timezonePickerContainer = timezoneContainer.append("div").classed("tsi-timezonePickerContainer", true); var timezonePicker = new TimezonePicker(timezonePickerContainer.node()); timezonePicker.render((newOffset) => { let matchingQuickTime = this.getCurrentQuickTime(); var oldOffset = this.chartOptions.offset; this.chartOptions.offset = newOffset; this.setNewOffset(oldOffset); if (matchingQuickTime !== -1) { this.setFromQuickTimes(matchingQuickTime); } }, (typeof offset == "string" ? offset : "UTC")); d3.select(timezonePicker.renderTarget).select('select') .attr('aria-labelledBy', timezoneSelectionLabelID) .attr('id', timezoneSelectionID); } } //zero out everything but year, month and day private roundDay (d: Date) { return new Date(d.getFullYear(), d.getMonth(), d.getDate()); } private setTimeRange (d: Date, isFromSelect: boolean) { if (this.isSettingStartTime) { this.calendarPicker.setStartRange(d); this.calendarPicker.setEndRange(null); this.startRange = d; this.anchorDate = d; } else { if (d.valueOf() > this.anchorDate.valueOf()) { if (isFromSelect) { this.setFromDate(this.anchorDate); this.setToDate(d); } this.calendarPicker.setEndRange(d); this.calendarPicker.setStartRange(this.anchorDate); this.startRange = this.anchorDate; this.endRange = d; } else { if (isFromSelect) { this.setFromDate(d); this.setToDate(this.anchorDate); } this.calendarPicker.setStartRange(d); this.calendarPicker.setEndRange(this.anchorDate); this.endRange = this.anchorDate; this.startRange = d; } this.setTimeInputBox(this.fromMillis, true); this.setTimeInputBox(this.toMillis, false); } } private createCalendar () { var i18nOptions = { previousMonth : this.getString('Previous Month'), nextMonth : this.getString('Next Month'), months : moment.localeData().months(), weekdays : moment.localeData().weekdays(), weekdaysShort : moment.localeData().weekdaysMin() }; //@ts-ignore this.calendarPicker = new Pikaday({ bound: false, container: this.calendar.node(), field: this.calendar.node(), i18n: i18nOptions, numberOfMonths: 2, onSelect: (d) => { this.setTimeRange(d, true); this.isSettingStartTime = !this.isSettingStartTime; this.calendarPicker.draw(); }, onDraw: (d) => { if (this.isSettingStartTime) return; var self = this; this.calendar.select(".pika-single").selectAll(".pika-day") .on("mouseover", function (d) { var date = new Date( Number(d3.select(this).attr("data-pika-year")), Number(d3.select(this).attr("data-pika-month")), Number(d3.select(this).attr("data-pika-day"))); if (!self.isSettingStartTime) { if (date.valueOf() < self.anchorDate.valueOf() && self.startRange.valueOf() != date.valueOf()) { self.setTimeRange(date, false); self.calendarPicker.draw(); return; } if (date.valueOf() >= self.anchorDate.valueOf() && (self.endRange == undefined || self.endRange.valueOf() != date.valueOf())) { self.setTimeRange(date, false); self.calendarPicker.draw(); return; } } }); }, minDate: this.convertToCalendarDate(this.minMillis), maxDate: this.convertToCalendarDate(this.maxMillis), defaultDate: Utils.adjustDateFromTimezoneOffset(new Date(this.fromMillis)) }); } private setSelectedQuickTimes () { let isSelected = d => { return (this.toMillis === this.maxMillis && (this.toMillis - this.fromMillis === d[1])); } this.quickTimesPanel.selectAll('.tsi-quickTime') .classed('tsi-isSelected', isSelected) .attr('aria-pressed', isSelected); } private setFromDate (calendarDate: Date) { let convertedFrom = new Date(Utils.offsetFromUTC(new Date(this.fromMillis), this.chartOptions.offset)); convertedFrom.setUTCFullYear(calendarDate.getFullYear()); convertedFrom.setUTCMonth(calendarDate.getMonth()); convertedFrom.setUTCDate(calendarDate.getDate()); this.setFromMillis(Utils.offsetToUTC(convertedFrom, this.chartOptions.offset).valueOf()); } private setToDate (calendarDate: Date) { let convertedTo = new Date(Utils.offsetFromUTC(new Date(this.toMillis), this.chartOptions.offset)); convertedTo.setUTCFullYear(calendarDate.getFullYear()); convertedTo.setUTCMonth(calendarDate.getMonth()); convertedTo.setUTCDate(calendarDate.getDate()); this.setToMillis(Utils.offsetToUTC(convertedTo, this.chartOptions.offset).valueOf()); } private setIsSaveable (isSaveable: boolean){ // For now, lets allow users to save the time even in the presence of errors this.dateTimeSelectionPanel.select(".tsi-saveButtonContainer").select(".tsi-saveButton") .attr("disabled", isSaveable ? null : true) .classed("tsi-buttonDisabled", !isSaveable); this.isValid = isSaveable; } //line up the seconds and millis with the second and millis of the max date private adjustSecondsAndMillis (rawMillis) { var currDate = new Date(rawMillis); var maxDate = new Date(this.maxMillis); currDate.setUTCSeconds(maxDate.getUTCSeconds()); currDate.setUTCMilliseconds(maxDate.getUTCMilliseconds()); return currDate.valueOf(); } private setFromMillis (millis: number) { var rangeErrorCheck = this.rangeIsValid(millis, this.toMillis); this.fromMillis = millis; this.setIsSaveable(rangeErrorCheck.isSaveable); this.displayRangeErrors(rangeErrorCheck.errors); this.setSelectedQuickTimes(); } private setToMillis (millis: number) { var rangeErrorCheck = this.rangeIsValid(this.fromMillis, millis); this.toMillis = millis; this.setIsSaveable(rangeErrorCheck.isSaveable); this.displayRangeErrors(rangeErrorCheck.errors); this.setSelectedQuickTimes(); } private displayRangeErrors (rangeErrors) { this.targetElement.select(".tsi-errorMessageContainer").selectAll(".tsi-errorMessage").remove(); if (rangeErrors.length != 0) { this.targetElement.select(".tsi-errorMessageContainer").selectAll(".tsi-errorMessages") .data(rangeErrors) .enter() .append("div") .classed("tsi-errorMessage", true) .text(d => d); } } private rangeIsValid (prospectiveFromMillis: number, prospectiveToMillis: number) { var accumulatedErrors = []; var isSaveable = true; let bothTimesValid = !isNaN(prospectiveFromMillis) && !isNaN(prospectiveToMillis); if (isNaN(prospectiveFromMillis)) { accumulatedErrors.push("*Invalid start date/time"); isSaveable = false; } if (isNaN(prospectiveToMillis)) { accumulatedErrors.push("*Invalid end date/time"); isSaveable = false; } if (bothTimesValid) { if (prospectiveFromMillis > prospectiveToMillis) { accumulatedErrors.push("*Start time must be before end time"); isSaveable = false; } if (prospectiveFromMillis < this.minMillis) { accumulatedErrors.push("*Start time is before first possible time (" + this.getTimeFormat()(this.minMillis) + ")"); } if (prospectiveFromMillis > this.maxMillis) { accumulatedErrors.push("*Start time is after last possible time (" + this.getTimeFormat()(this.maxMillis) + ")"); } if (prospectiveToMillis > this.maxMillis) { accumulatedErrors.push("*End time is after last possible time (" + this.getTimeFormat()(this.maxMillis) + ")"); } if (prospectiveToMillis < this.minMillis) { accumulatedErrors.push("*End time is before first possible time (" + this.getTimeFormat()(this.minMillis) + ")"); } } return { rangeIsValid : (accumulatedErrors.length == 0), errors: accumulatedErrors, isSaveable: isSaveable }; } private updateDisplayedFromDateTime (fromInput = false) { this.calendarPicker.setStartRange(this.convertToCalendarDate(this.fromMillis)); if (!fromInput) this.setTimeInputBox(new Date(this.fromMillis), true); } private updateDisplayedToDateTime (fromInput = false) { this.calendarPicker.setEndRange(this.convertToCalendarDate(this.toMillis)); if (!fromInput) this.setTimeInputBox(new Date(this.toMillis), false); } private offsetUTC (date: Date) { var dateCopy = new Date(date.valueOf()) dateCopy.setTime(dateCopy.getTime() - dateCopy.getTimezoneOffset()*60*1000); return dateCopy; } private offsetFromUTC (date: Date) { var dateCopy = new Date(date.valueOf()) dateCopy.setTime(dateCopy.getTime() + dateCopy.getTimezoneOffset()*60*1000 ); return dateCopy; } private checkDateTimeValidity () { let parsedFrom = Utils.parseUserInputDateTime(this.fromInput.node().value, this.chartOptions.offset); let parsedTo = Utils.parseUserInputDateTime(this.toInput.node().value, this.chartOptions.offset); let rangeErrorCheck = this.rangeIsValid(parsedFrom, parsedTo); this.setIsSaveable(rangeErrorCheck.isSaveable); this.displayRangeErrors(rangeErrorCheck.errors); } private setTimeInputBox (utcDate, isFrom) { if (isFrom) { this.fromInput.node().value = this.createTimeString(utcDate); } else { this.toInput.node().value = this.createTimeString(utcDate); } } private createTimePicker () { var timeInputContainer = this.timeControls.append("div").attr("class", "tsi-timeInputContainer"); var createTimePicker = (startOrEnd) => { var fromOrToContainer = timeInputContainer.append("div").classed("tsi-" + startOrEnd + "Container", true); let inputLabelID = Utils.guid(); let inputID = inputLabelID + 'Input'; let timeLabel = fromOrToContainer.append("label") .classed("tsi-timeLabel", true) .attr('id', inputLabelID) .attr('for', inputID) .attr('aria-label', `${startOrEnd === 'start' ? this.getString('Start time input') : this.getString('End time input')}`) .text(this.getString(startOrEnd)); let inputName = startOrEnd === 'start' ? 'fromInput' : 'toInput' this[inputName] = fromOrToContainer.append('input') .attr('class', 'tsi-dateTimeInput', true) .attr('aria-labelledby', inputLabelID) .attr('id', inputID) .on('input', () => { let rangeErrorCheck: any = this.checkDateTimeValidity(); this.isSettingStartTime = true; if (this.isValid) { if (startOrEnd === 'start') { let parsedFrom = Utils.parseUserInputDateTime(this.fromInput.node().value, this.chartOptions.offset); this.setFromMillis(parsedFrom); this.updateDisplayedFromDateTime(true); this.calendarPicker.draw(); } else { let parsedTo = Utils.parseUserInputDateTime(this.toInput.node().value, this.chartOptions.offset); this.setToMillis(parsedTo); this.updateDisplayedToDateTime(true); this.calendarPicker.draw(); } } }); if (startOrEnd == 'end') { fromOrToContainer.append("button") .attr("class", "tsi-snapToEndRangeButton") .text(this.getString("Latest")) .attr('aria-label', this.getString('snap end time to latest')) .on("click", () => { if (!this.isSettingStartTime) { this.setFromDate(this.startRange); } this.setToMillis(this.maxMillis); this.updateDisplayedFromDateTime(); this.updateDisplayedToDateTime(); this.isSettingStartTime = true; this.calendarPicker.draw(); }); } } createTimePicker("start"); createTimePicker("end"); } } export default DateTimePicker;
the_stack
declare module 'sway' { /** * Creates an ApiDefinition object from the provided OpenAPI definition. * @param options - The options for loading the definition(s) * @returns The promise */ export function create(options: CreateOptions): Promise<ApiDefinition>; /** * Options used when creating the `ApiDefinition`. */ interface CreateOptions { /** * The OpenAPI definition location or structure */ definition: object | string; /** * *(See [JsonRefs~JsonRefsOptions](https://github.com/whitlockjc/json-refs/blob/master/docs/API.md#module_JsonRefs..JsonRefsOptions))* */ jsonRefs?: object; /** * The key/value pair of custom formats *(The keys are the format name and the * values are async functions. See [ZSchema Custom Formats](https://github.com/zaggino/z-schema#register-a-custom-format))* */ customFormats?: object; /** * The key/value pair of custom format generators *(The keys are the * format name and the values are functions. See [json-schema-mocker Custom Format](https://github.com/json-schema-faker/json-schema-faker#custom-formats))* */ customFormatGenerators?: object; /** * The custom validators */ customValidators?: any[]; } /** * Function used for custom validation of OpenAPI documents * @param apiDefinition - The `ApiDefinition` object * @returns The validation results */ export type DocumentValidationFunction = (apiDefinition: ApiDefinition)=>ValidationResults; /** * Request validation function. * @param res - The response or response like object * @param def - The `Response` definition _(useful primarily when calling * `Operation#validateResponse` as `Response#validateResponse` the caller should have access to the `Response` object * already.)_ * @returns The validation results */ export type RequestValidationFunction = (res: ServerResponseWrapper, def: Response)=>ValidationResults; /** * Request validation options. */ interface RequestValidationOptions { /** * Enablement of strict mode validation. If `strictMode` is a * `boolean` and is `true`, all form fields, headers and query parameters **must** be defined in the OpenAPI document * for this operation. If `strictMode` is an `object`, the keys correspond to the `in` property values of the * [OpenAPI Parameter Object](https://github.com/OAI/OpenAPI-Specification/blob/master/versions/3.0.0.md#parameterObject) * and its value is a `boolean` that when `true` turns on strict mode validation for the request location matching the * key. Valid keys are `formData`, `header` and `query`. _(`body` and `path` are not necessary since `body` strict * mode is possible via its schema and `path` is **always** required.)_ */ strictMode?: boolean | object; /** * The custom validators */ customValidators?: RequestValidationFunction; } /** * Response validation function. * @param req - The http client request *(or equivalent)* * @param op - The `Operation` object for the request * @returns The validation results */ export type ResponseValidationFunction = (req: object, op: Operation)=>ValidationResults; /** * Response validation options. */ interface ResponseValidationOptions { /** * Enablement of strict mode validation. If `strictMode` is a * `boolean` and is `true`, all form fields, headers and query parameters **must** be defined in the OpenAPI definition * for this operation. If `strictMode` is an `object`, the keys correspond to the `in` property values of the * [OpenAPI Parameter Object](https://github.com/OAI/OpenAPI-Specification/blob/master/versions/2.0.md#parameterObject) * and its value is a `boolean` that when `true` turns on strict mode validation for the request location matching the * key. Valid keys are `header`. _(`body`, `query` and `path` are not necessary since `body` strict mode is possible * via its schema and `path`, `query` do not matter for responses.)_ */ strictMode?: boolean | object; /** * The custom validators */ customValidators?: RequestValidationFunction; } /** * Server response wrapper. * * Since the low level `http.ServerResponse` object is not always guaranteed and even if it is, there is no public way * to gather the necessary parts of the response to perform validation, this object encapsulates the required response * information to perform response validation. */ interface ServerResponseWrapper { /** * The response body */ body: any; /** * The encoding of the body when the body is a `Buffer` */ encoding?: string; /** * The response headers */ headers?: object; /** * The response status code */ statusCode?: number | string; } /** * Validation error/warning object. * * When this object is created as a result of JSON Schema validation, this object is created by * [z-schema](https://github.com/zaggino/z-schema) and it owns the structure so there can be extra properties not * documented below. */ interface ValidationEntry { /** * The code used to identify the error/warning */ code: string; /** * Whenever there is an upstream `Error` encountered, its message is here */ error?: string; /** * The nested error(s) encountered during validation */ errors?: any[]; /** * Contains the composition lineage for circular composition errors */ lineage?: string[]; /** * The human readable description of the error/warning */ message: string; /** * The header name for header validation errors */ name?: string; /** * The parameters used when validation failed *(This is a z-schema construct and is only * set for JSON Schema validation errors.)* */ params?: any[]; /** * The path to the location in the document where the error/warning occurred */ path: string[]; /** * The schema id *(This is a z-schema construct and is only set for JSON Schema * validation errors and when its value is not `undefined`.) */ schemaId?: string; } /** * Validation results object. */ interface ValidationResults { /** * The validation errors */ errors: any[]; /** * The validation warnings */ warnings: any[]; } class ApiDefinition { /** * The OpenAPI Definition object. * * **Note:** Do not use directly. * * **Extra Properties:** Other than the documented properties, this object also exposes all properties of the * [OpenAPI Object](https://github.com/OAI/OpenAPI-Specification/blob/master/versions/3.0.0.md#openapi-object). * @param definition - The original OpenAPI definition * @param definitionRemotesResolved - The OpenAPI definition with all of its remote references resolved * @param definitionFullyResolved - The OpenAPI definition with all of its references resolved * @param references - The location and resolution of the resolved references in the OpenAPI definition * @param options - The options passed to ApiDefinition.create */ constructor(definition: object, definitionRemotesResolved: object, definitionFullyResolved: object, references: object, options: object); /** * Returns the operation for the given path and operation. * * **Note:** Below is the list of properties used when `reqOrPath` is an `http.ClientRequest` *(or equivalent)*: * * * `method` * * `originalUrl` * * `url` * * *(See: {@link https://nodejs.org/api/http.html#http_class_http_clientrequest})* * @param idOrPathOrReq - The OpenAPI operation id, path string or the http client request *(or * equivalent)* * @param method - The OpenAPI operation method _(not used when providing an operation id)_ * @returns The `Operation` for the provided operation id, or path and method or `undefined` if * there is no operation for that operation id, or path and method combination */ getOperation(idOrPathOrReq: string | object, method?: string): Operation; /** * Returns all operations for the provided path or all operations in the API. * @param path - The OpenAPI path * @returns All `Operation` objects for the provided path or all API operations */ getOperations(path?: string): any[]; /** * Returns all operations for the provided tag. * @param tag - The OpenAPI tag * @returns All `Operation` objects for the provided tag */ getOperationsByTag(tag?: string): any[]; /** * Returns the path object for the given path or request. * * **Note:** Below is the list of properties used when `reqOrPath` is an `http.ClientRequest` *(or equivalent)*: * * * `originalUrl` * * `url` * * *(See: {@link https://nodejs.org/api/http.html#http_class_http_clientrequest})* * @param pathOrReq - The OpenAPI path string or the http client request *(or equivalent)* * @returns The corresponding `Path` object for the requested path or request */ getPath(pathOrReq: string | object): Path; /** * Returns all path objects for the OpenAPI definition. * @returns The `Path` objects */ getPaths(): any[]; /** * Registers a custom format. * @param name - The name of the format * @param validator - The format validator *(See [ZSchema Custom Format](https://github.com/zaggino/z-schema#register-a-custom-format))* */ registerFormat(name: string, validator: Function): void; /** * Registers a custom format generator. * @param name - The name of the format * @param formatGenerator - The format generator *(See [json-schema-mocker Custom Format](https://github.com/json-schema-faker/json-schema-faker#custom-formats))* */ registerFormatGenerator(name: string, formatGenerator: Function): void; /** * Unregisters a custom format. * @param name - The name of the format */ unregisterFormat(name: string): void; /** * Unregisters a custom format generator. * @param name - The name of the format generator */ unregisterFormatGenerator(name: string): void; /** * Registers a custom validator. * @param validator - The validator * @throws If the validator is not a function */ registerValidator(validator: DocumentValidationFunction): void; /** * Performs validation of the OpenAPI definition. * @returns The validation results */ validate(): ValidationResults; } class Operation { /** * The OpenAPI Operation object. * * **Note:** Do not use directly. * * **Extra Properties:** Other than the documented properties, this object also exposes all properties of the * [OpenAPI Operation Object](https://github.com/OAI/OpenAPI-Specification/blob/master/versions/3.0.0.md#operationObject). * @param pathObject - The Path object * @param method - The operation method * @param definition - The operation definition *(The raw operation definition __after__ remote references were * resolved)* * @param definitionFullyResolved - The operation definition with all of its resolvable references resolved * @param pathToDefinition - The path segments to the operation definition */ constructor(pathObject: Path, method: string, definition: object, definitionFullyResolved: object, pathToDefinition: string[]); /** * Returns the parameter with the provided name and location when provided. * @param name - The name of the parameter * @param location - The location *(`in`)* of the parameter *(Used for disambiguation)* * @returns The `Parameter` matching the location and name combination or `undefined` if there * is no match */ getParameter(name: string, location?: string): Parameter; /** * Returns all parameters for the operation. * @returns All `Parameter` objects for the operation */ getParameters(): any[]; /** * Returns the response for the requested status code or the default response *(if available)* if none is provided. * @param statusCode - The status code * @returns The `Response` or `undefined` if one cannot be found */ getResponse(statusCode?: number | string): Response; /** * Returns all responses for the operation. * @returns All `Response` objects for the operation */ getResponses(): any[]; /** * Returns the composite security definitions for this operation. * * The difference between this API and `this.security` is that `this.security` is the raw `security` value for the * operation where as this API will return the global `security` value when available and this operation's security * is undefined. * @returns The security for this operation */ getSecurity(): object[]; /** * Validates the request. * * **Note:** Below is the list of `req` properties used *(req should be an `http.ClientRequest` or equivalent)*: * * * `body`: Used for `body` and `formData` parameters * * `files`: Used for `formData` parameters whose `type` is `file` * * `headers`: Used for `header` parameters and consumes * * `originalUrl`: used for `path` parameters * * `query`: Used for `query` parameters * * `url`: used for `path` parameters * * For `path` parameters, we will use the operation's `regexp` property to parse out path parameters using the * `originalUrl` or `url` property. * * *(See: {@link https://nodejs.org/api/http.html#http_class_http_clientrequest})* * @param req - The http client request *(or equivalent)* * @param options - The validation options * @returns The validation results */ validateRequest(req: object, options?: RequestValidationOptions): ValidationResults; /** * Validates the response. * @param res - The response or response like object * @param options - The validation options * @returns The validation results */ validateResponse(res: ServerResponseWrapper, options?: ResponseValidationOptions): ValidationResults; } class ParameterValue { /** * Object representing a parameter value. * * **Note:** Do not use directly. * @param parameterObject - The `Parameter` object * @param raw - The original/raw value */ constructor(parameterObject: Parameter, raw: any); } class Parameter { /** * The OpenAPI Parameter object. * * **Note:** Do not use directly. * * **Extra Properties:** Other than the documented properties, this object also exposes all properties of the * [OpenAPI Parameter Object](https://github.com/OAI/OpenAPI-Specification/blob/master/versions/3.0.0.md#parameterObject). * @param opOrPathObject - The `Operation` or `Path` object * @param definition - The parameter definition *(The raw parameter definition __after__ remote references were * resolved)* * @param definitionFullyResolved - The parameter definition with all of its resolvable references resolved * @param pathToDefinition - The path segments to the parameter definition */ constructor(opOrPathObject: Operation | Path, definition: object, definitionFullyResolved: object, pathToDefinition: string[]); /** * Returns a sample value for the parameter based on its schema; * @returns The sample value */ getSample(): any; /** * Returns the parameter value from the request. * * **Note:** Below is the list of `req` properties used *(req should be an `http.ClientRequest` or equivalent)*: * * * `body`: Used for `body` and `formData` parameters * * `files`: Used for `formData` parameters whose `type` is `file` * * `headers`: Used for `header` parameters * * `originalUrl`: used for `path` parameters * * `query`: Used for `query` parameters * * `url`: used for `path` parameters * * For `path` parameters, we will use the operation's `regexp` property to parse out path parameters using the * `originalUrl` or `url` property. * * *(See: {@link https://nodejs.org/api/http.html#http_class_http_clientrequest})* * @param req - The http client request *(or equivalent)* * @returns The parameter value object * @throws If the `in` value of the parameter's schema is not valid or if the `req` property to retrieve the * parameter is missing */ getValue(req: object): ParameterValue; } class Path { /** * The Path object. * * **Note:** Do not use directly. * * **Extra Properties:** Other than the documented properties, this object also exposes all properties of the * [OpenAPI Path Object](https://github.com/OAI/OpenAPI-Specification/blob/master/versions/3.0.0.md#pathItemObject). * @param apiDefinition - The `ApiDefinition` object * @param path - The path string * @param definition - The path definition *(The raw path definition __after__ remote references were * resolved)* * @param definitionFullyResolved - The path definition with all of its resolvable references resolved * @param pathToDefinition - The path segments to the path definition */ constructor(apiDefinition: ApiDefinition, path: string, definition: object, definitionFullyResolved: object, pathToDefinition: string[]); /** * Return the operation for this path and operation id or method. * @param idOrMethod - The operation id or method * @returns The `Operation` objects for this path and method or `undefined` if there is no * operation for the provided method */ getOperation(idOrMethod: string): any[]; /** * Return the operations for this path. * @returns The `Operation` objects for this path */ getOperations(): any[]; /** * Return the operations for this path and tag. * @param tag - The tag * @returns The `Operation` objects for this path and tag */ getOperationsByTag(tag: string): any[]; /** * Return the parameters for this path. * @returns The `Parameter` objects for this path */ getParameters(): any[]; } class Response { /** * The OpenAPI Response object. * * **Note:** Do not use directly. * * **Extra Properties:** Other than the documented properties, this object also exposes all properties of the * [OpenAPI Response Object](https://github.com/OAI/OpenAPI-Specification/blob/master/versions/3.0.0.md#responseObject). * @param operationObject - The `Operation` object * @param statusCode - The status code * @param definition - The response definition *(The raw response definition __after__ remote references were * resolved)* * @param definitionFullyResolved - The response definition with all of its resolvable references resolved * @param pathToDefinition - The path segments to the path definition */ constructor(operationObject: Operation, statusCode: string, definition: object, definitionFullyResolved: object, pathToDefinition: string[]); /** * Returns the response example for the mime-type. * @param mimeType - The mime type * @returns The response example as a string or `undefined` if the response code and/or mime-type is missing */ getExample(mimeType?: string): string; /** * Returns a sample value. * @returns The sample value for the response, which can be undefined if the response schema is not provided */ getSample(): any; /** * Validates the response. * @param res - The response or response like object * @param options - The validation options * @returns The validation results */ validateResponse(res: ServerResponseWrapper, options?: ResponseValidationOptions): ValidationResults; } }
the_stack
import * as React from "react"; import * as ReactDOM from "react-dom"; import {observer} from "mobx-react"; import {autorun, reaction, toJS, intercept} from 'mobx'; import * as d3 from "d3"; import SelectVoucherType from "../Shared/Components/SelectVoucherType"; import SelectAccount from "../Shared/Components/SelectAccount"; import SelectDebitCredit from "../Shared/Components/SelectDebitCredit"; import JournalEntryStore from "../Shared/Stores/Financials/JournalEntryStore"; import JournalEntryUIStore from "../Shared/Stores/Financials/JournalEntryUIStore"; let store = new JournalEntryStore(); let uiStore = new JournalEntryUIStore(store); @observer class ValidationErrors extends React.Component<any, {}>{ render() { if (store.validationErrors !== undefined && store.validationErrors.length > 0) { var errors = []; store.validationErrors.map(function (item, index) { errors.push(<li key={index}>{item}</li>); }); return ( <div> <ul> {errors} </ul> </div> ); } return null; } } @observer class EditButton extends React.Component<any, {}>{ onClickEditButton() { // Remove " disabledControl" from current className var nodes = document.getElementById("divJournalEntryForm").getElementsByTagName('*'); for (var i = 0; i < nodes.length; i++) { var subStringLength = nodes[i].className.length - " disabledControl".length; nodes[i].className = nodes[i].className.substring(0, subStringLength); } store.changedEditMode(true) } render() { return ( <a href="#" id="linkEdit" onClick={this.onClickEditButton} className={!store.journalEntry.posted && !store.editMode ? "btn" : "btn inactiveLink"}> <i className="fa fa-edit"></i> Edit </a> ); } } @observer class SaveJournalEntryButton extends React.Component<any, {}>{ onClickSaveNewJournalEntry(e) { store.saveNewJournalEntry(); } render() { return ( <input type="button" value="Save" onClick={this.onClickSaveNewJournalEntry.bind(this) } className={!store.journalEntry.posted && store.editMode ? "btn btn-sm btn-primary btn-flat pull-left" : "btn btn-sm btn-primary btn-flat pull-left inactiveLink"} /> ); } } class CancelJournalEntryButton extends React.Component<any, {}>{ cancelOnClick() { let baseUrl = location.protocol + "//" + location.hostname + (location.port && ":" + location.port) + "/"; window.location.href = baseUrl + 'financials/journalentries'; } render() { return ( <input type="button" onClick={ this.cancelOnClick.bind(this) } id="btnCancel" className="btn btn-sm btn-default btn-flat pull-left" value="Cancel" /> ); } } @observer class PostJournalEntryButton extends React.Component<any, {}>{ postOnClick(e) { store.postJournal(); } render() { return ( <input type="button" value="Post" onClick={ this.postOnClick.bind(this) } className={!store.journalEntry.posted && store.journalEntry.readyForPosting && !store.editMode ? "btn btn-sm btn-primary btn-flat btn-danger pull-right" : "btn btn-sm btn-primary btn-flat btn-danger pull-right inactiveLink"} /> ); } } @observer class JournalEntryHeader extends React.Component<any, {}>{ onChangeJournalDate(e) { store.changedJournalDate(e.target.value); } onChangeReferenceNo(e) { store.changedReferenceNo(e.target.value); } onChangeMemo(e) { store.changedMemo(e.target.value); } render() { return ( <div className="card"> <div class="card-header"> <a data-toggle="collapse" href="#general" aria-expanded="true" aria-controls="general"><i class="fa fa-align-justify"></i></a> General </div> <div className="card-body collapse show row" id="general"> <div className="col-sm-6"> <div className="row"> <div className="col-sm-3">Date</div> <div className="col-sm-9"><input type="date" className="form-control" id="newJournalDate" onChange={this.onChangeJournalDate.bind(this) } value={store.journalEntry.journalDate !== undefined ? store.journalEntry.journalDate.substring(0, 10) : new Date(Date.now()).toISOString().substring(0, 10) } /></div> </div> <div className="row"> <div className="col-sm-3">Voucher</div> <div className="col-sm-9"><SelectVoucherType store={store} controlId="optNewVoucherType" selected={store.journalEntry.voucherType} /></div> </div> <div className="row"> <div className="col-sm-3">Reference no</div> <div className="col-sm-9"><input type="text" className="form-control" value={store.journalEntry.referenceNo || ''} /* || '' fix the issue about uncontrolled input warning when using React 15*/ onChange={this.onChangeReferenceNo.bind(this)} /></div> </div> <div className="row"> <div className="col-sm-3">Memo</div> <div className="col-sm-9"><input type="text" className="form-control" value={store.journalEntry.memo || ''} onChange={this.onChangeMemo.bind(this) } /></div> </div> </div> <div className="col-sm-6"> <div className="row"> <div className="col-sm-2">Posted</div> <div className="col-sm-10"><input type="checkbox" readOnly checked={store.journalEntry.posted === true ? true : false} /></div> </div> </div> </div> </div> ); } } @observer class JournalEntryLines extends React.Component<any, {}>{ onChangeAmount(e) { store.updateLineItem(e.target.name, "amount", e.target.value); } onChangeMemo(e) { store.updateLineItem(e.target.name, "memo", e.target.value); } onClickRemoveLineItem(i, e) { store.removeLineItem(i); } addLineItem() { var accountId, drcr, amount, memo; accountId = (document.getElementById("optNewAccountId") as HTMLInputElement).value;; drcr = (document.getElementById("optNewDebitCredit") as HTMLInputElement).value; amount = (document.getElementById("txtNewAmount") as HTMLInputElement).value; memo = (document.getElementById("txtNewMemo") as HTMLInputElement).value; store.addLineItem(0, accountId, drcr, amount, memo); (document.getElementById("txtNewAmount") as HTMLInputElement).value = "0"; (document.getElementById("txtNewMemo") as HTMLInputElement).value = ""; } render() { var lineItems = []; for (var i = 0; i < store.journalEntry.journalEntryLines.length; i++) { lineItems.push( <tr key={i}> <td><SelectAccount store={store} row={i} selected={store.journalEntry.journalEntryLines[i].accountId} /></td> <td><SelectDebitCredit store={store} row={i} selected={store.journalEntry.journalEntryLines[i].drcr} /></td> <td><input type="text" className="form-control" name={i.toString()} onChange={this.onChangeAmount.bind(this)} value={store.journalEntry.journalEntryLines[i].amount} /></td> <td><input type="text" className="form-control" name={i.toString()} onChange={this.onChangeMemo.bind(this) } value={store.journalEntry.journalEntryLines[i].memo || ''} /></td> <td> <button type="button" className="btn btn-box-tool" onClick={this.onClickRemoveLineItem.bind(this, i) }> <i className="fa fa-fw fa-times"></i> </button> </td> </tr> ); } return ( <div className="card"> <div className="card-header"> <a data-toggle="collapse" href="#line-items" aria-expanded="true" aria-controls="line-items"><i className="fa fa-align-justify"></i></a> Line Items </div> <div className="card-body collapse show table-responsive" id="line-items"> <table> <thead> <tr> <td>Account</td> <td>DrCr</td> <td>Amount</td> <td>Memo</td> <td></td> </tr> </thead> <tbody> {lineItems} <tr> <td><SelectAccount store={store} controlId="optNewAccountId" /></td> <td><SelectDebitCredit store={store} controlId="optNewDebitCredit" /></td> <td><input type="text" className="form-control" id="txtNewAmount" /></td> <td><input type="text" className="form-control" id="txtNewMemo" /></td> <td> <button type="button" className="btn btn-box-tool" onClick={this.addLineItem}> <i className="fa fa-fw fa-check"></i> </button> </td> </tr> </tbody> </table> </div> </div> ); } } @observer export default class JournalEntry extends React.Component<any, {}> { render() { return ( <div> <div id="divActionsTop"> <EditButton /> </div> <div id="divJournalEntryForm"> <ValidationErrors /> <JournalEntryHeader /> <JournalEntryLines /> </div> <div id="divActionsBottom"> <SaveJournalEntryButton /> <CancelJournalEntryButton /> <PostJournalEntryButton /> </div> </div> ); } } ReactDOM.render(<JournalEntry />, document.getElementById("divJournalEntry"));
the_stack
import _ from 'lodash'; const debug = require('debug')('restapi'); import cost from './cost'; import { IRestResponse, flattenData } from './core'; import { CompositeApiContext, CompositeIntelligentEngine } from './composite'; import { Collaborator } from '../../business/collaborator'; import { Team } from '../../business/team'; import { IPagedCacheOptions, IGetAuthorizationHeader, IDictionary } from '../../interfaces'; import { RestLibrary } from '.'; import { sleep } from '../../utils'; import GitHubApplication from '../../business/application'; import { RepositoryPrimaryProperties } from '../../business/primaryProperties'; export interface IGetAppInstallationsParameters { app_id: string; } export enum GitHubPullRequestState { Open = 'open', Closed = 'closed', All = 'all', } export enum GitHubIssueState { Open = 'open', Closed = 'closed', All = 'all', } export enum GitHubPullRequestSort { Created = 'created', Updated = 'updated', Popularity = 'popularity', // comment count LongRunning = 'long-running', // age, filtering by pulls updated in the last month } export enum GitHubSortDirection { Ascending = 'asc', Descending = 'desc', } export interface IListPullsParameters { owner: string; repo: string; state?: GitHubPullRequestState; head?: string; base?: string; sort?: GitHubPullRequestSort; direction?: GitHubSortDirection; } const branchDetailsToCopy = [ 'name', 'commit', 'protected', ]; const repoDetailsToCopy = RepositoryPrimaryProperties; const teamDetailsToCopy = Team.PrimaryProperties; const memberDetailsToCopy = Collaborator.PrimaryProperties; const appInstallDetailsToCopy = GitHubApplication.PrimaryInstallationProperties; const contributorsDetailsToCopy = [ ...Collaborator.PrimaryProperties, 'contributions', ]; const teamPermissionsToCopy = [ 'id', 'name', 'slug', 'description', 'members_count', 'repos_count', 'privacy', 'permission', ]; const teamRepoPermissionsToCopy = [ 'id', 'name', 'full_name', 'description', 'private', 'fork', 'permissions', ]; const pullDetailsToCopy = [ 'id', 'number', 'state', 'locked', 'title', // user 'body', // labels // milestone // active_lock_reason 'created_at', 'updated_at', 'closed_at', 'merged_at', 'merge_commit_sha', 'assignee', // << NOTE: this was deprecated in 2020 (? not sure on date) 'assignees', // requested_reviewers // requested_teams 'head', // PERF: large user of list storage 'base', // PERF: large user of list storage 'author_association', 'draft', ]; interface IRequestWithData { data: unknown; requests: IPageRequest[]; } interface IPageRequest { cost: unknown; headers: IDictionary<string>; status?: number; } export class RestCollections { private libraryContext: RestLibrary; private githubCall: unknown; constructor(libraryContext: RestLibrary, githubCall: unknown) { this.libraryContext = libraryContext; this.githubCall = githubCall; } getOrgRepos(token: string | IGetAuthorizationHeader, options, cacheOptions: IPagedCacheOptions): Promise<any> { return this.generalizedCollectionWithFilter('orgRepos', 'repos.listForOrg', repoDetailsToCopy, token, options, cacheOptions); } getOrgTeams(token: string | IGetAuthorizationHeader, options, cacheOptions: IPagedCacheOptions): Promise<any> { return this.generalizedCollectionWithFilter('orgTeams', 'teams.list', teamDetailsToCopy, token, options, cacheOptions); } getTeamChildTeams(token: string | IGetAuthorizationHeader, options, cacheOptions: IPagedCacheOptions): Promise<any> { return this.generalizedCollectionWithFilter('teamChildTeams', 'teams.listChildInOrg', teamDetailsToCopy, token, options, cacheOptions); } getUserActivity(token: string | IGetAuthorizationHeader, options, cacheOptions: IPagedCacheOptions): Promise<any> { return this.generalizedCollectionWithFilter('userActivity', 'activity.listEventsForAuthenticatedUser', null /*activityDetailsToCopy*/, token, options, cacheOptions); } getOrgMembers(token: string | IGetAuthorizationHeader, options, cacheOptions: IPagedCacheOptions): Promise<any> { return this.generalizedCollectionWithFilter('orgMembers', 'orgs.listMembers', memberDetailsToCopy, token, options, cacheOptions); } getAppInstallations(token: string | IGetAuthorizationHeader, parameters: IGetAppInstallationsParameters, cacheOptions: IPagedCacheOptions): Promise<any> { if (!parameters.app_id) { throw new Error('parameters.app_id required'); } const projectedOptions = { additionalDifferentiationParameters: parameters, }; return this.generalizedCollectionWithFilter(`appInstallations`, 'apps.listInstallations', appInstallDetailsToCopy, token, projectedOptions, cacheOptions); } getRepoIssues(token: string | IGetAuthorizationHeader, options, cacheOptions: IPagedCacheOptions): Promise<any[]> { return this.generalizedCollectionWithFilter('repoIssues', 'issues.listForRepo', null, token, options, cacheOptions); } getRepoProjects(token: string | IGetAuthorizationHeader, options, cacheOptions: IPagedCacheOptions): Promise<any[]> { return this.generalizedCollectionWithFilter('repoProjects', 'projects.listForRepo', null, token, options, cacheOptions); } getRepoTeams(token: string | IGetAuthorizationHeader, options, cacheOptions: IPagedCacheOptions): Promise<any> { return this.generalizedCollectionWithFilter('repoTeamPermissions', 'repos.listTeams', teamPermissionsToCopy, token, options, cacheOptions); } getRepoContributors(token: string | IGetAuthorizationHeader, options, cacheOptions: IPagedCacheOptions): Promise<any> { return this.generalizedCollectionWithFilter('repoListContributors', 'repos.listContributors', contributorsDetailsToCopy, token, options, cacheOptions); } getRepoCollaborators(token: string | IGetAuthorizationHeader, options, cacheOptions: IPagedCacheOptions): Promise<any> { return this.generalizedCollectionWithFilter('repoCollaborators', 'repos.listCollaborators', memberDetailsToCopy, token, options, cacheOptions); } getRepoBranches(token: string | IGetAuthorizationHeader, options, cacheOptions: IPagedCacheOptions): Promise<any> { return this.generalizedCollectionWithFilter('repoBranches', 'repos.listBranches', branchDetailsToCopy, token, options, cacheOptions); } getRepoPullRequests(token: string | IGetAuthorizationHeader, options: IListPullsParameters, cacheOptions: IPagedCacheOptions): Promise<any> { return this.generalizedCollectionWithFilter('repoPullRequests', 'pulls.list', pullDetailsToCopy, token, options, cacheOptions); } getTeamMembers(token: string | IGetAuthorizationHeader, options, cacheOptions: IPagedCacheOptions): Promise<any> { return this.generalizedCollectionWithFilter('teamMembers', 'teams.listMembersInOrg', memberDetailsToCopy, token, options, cacheOptions); } getTeamRepos(token: string | IGetAuthorizationHeader, options, cacheOptions: IPagedCacheOptions): Promise<any> { return this.generalizedCollectionWithFilter('teamRepos', 'teams.listReposInOrg', teamRepoPermissionsToCopy, token, options, cacheOptions); } private async getGithubCollection(token: string | IGetAuthorizationHeader, methodName, options, cacheOptions: IPagedCacheOptions): Promise<IRequestWithData> { const hasNextPage = this.libraryContext.hasNextPage; const githubCall = this.githubCall; let done = false; let results = []; let recentResult = null; let requests = []; let pages = 0; let currentPage = 0; const pageLimit = options.pageLimit || cacheOptions['pageLimit'] || Number.MAX_VALUE; const pageRequestDelay = cacheOptions.pageRequestDelay || null; while (!done) { const method = githubCall; const args = []; const currentToken = typeof (token) === 'string' ? token : await token(); args.push(currentToken); const clonedOptions = Object.assign({}, options); if (++currentPage > 1) { clonedOptions.page = currentPage; } args.push(methodName, clonedOptions); let error = null; let result = null; try { result = await (method as any).apply(null, args); recentResult = result; if (result) { ++pages; if (Array.isArray(result)) { results = results.concat(result); } requests.push({ cost: result.cost, headers: result.headers, }); } try { done = pages >= pageLimit || !hasNextPage(result); } catch (nextPageError) { error = nextPageError; done = true; } } catch (iterationError) { done = true; error = iterationError; } if (!done && !error && result.headers && result.headers['retry-after']) { // actual retry headers win const delaySeconds = result.headers['retry-after']; debug(`Retry-After header was present. Delaying before next page ${delaySeconds}s.`); await sleep(delaySeconds * 1000); } else if (pageRequestDelay) { const to = typeof (pageRequestDelay); let evaluatedTime = 0; if (to === 'number') { evaluatedTime = pageRequestDelay as number; } else if (to === 'function') { evaluatedTime = (pageRequestDelay as unknown as any)(); } else { throw new Error(`Unsupported pageRequestDelay type: ${to}`); } await sleep(evaluatedTime); } if (error) { throw error; } } const data = { data: results, }; return { data, requests }; } private async getFilteredGithubCollection(token: string | IGetAuthorizationHeader, methodName, options, cacheOptions: IPagedCacheOptions, propertiesToKeep): Promise<IRequestWithData> { const keepAll = !propertiesToKeep; try { // IRequestWithData const getCollectionResponse = await this.getGithubCollection(token, methodName, options, cacheOptions); if (!getCollectionResponse) { throw new Error('No response'); } const root = getCollectionResponse.data as any; if (!root) { throw new Error('No object, no data'); } if (!root.data) { throw new Error('The resulting object did not contain a data property'); } const requests = getCollectionResponse.requests; const results = root.data; const repos = []; for (let i = 0; i < results.length; i++) { const doNotModify = results[i]; if (doNotModify) { const r = {}; _.forOwn(doNotModify, (value, key) => { if (keepAll || propertiesToKeep.indexOf(key) >= 0) { r[key] = value; } }); repos.push(r); } } const filteredData = { data: repos, }; return { data: filteredData, requests, }; } catch (error) { throw error; } } private async getFilteredGithubCollectionWithMetadataAnalysis(token: string | IGetAuthorizationHeader, methodName, options, cacheOptions: IPagedCacheOptions, propertiesToKeep): Promise<IRestResponse> { const collectionResults = await this.getFilteredGithubCollection(token, methodName, options, cacheOptions, propertiesToKeep); const results = collectionResults.data as IRestResponse; const requests = collectionResults.requests; const pages = []; let dirty = false; let dirtyModified = []; let compositeCost = cost.create(); for (let i = 0; i < requests.length; i++) { if (requests[i] && requests[i].headers && requests[i].headers.etag) { pages.push(requests[i].headers.etag); } else { throw new Error('Invalid set of responses for pages'); } if (requests[i] && requests[i].status && requests[i].status !== 304) { dirty = true; let lastModified = requests[i].headers['last-modified']; if (lastModified) { dirtyModified.push(lastModified); } } if (requests[i] && requests[i].cost) { cost.add(compositeCost, requests[i].cost); } } if (dirtyModified.length > 0) { debug('Last-Modified response was present. This work is not yet implemented.'); // Some types, typically direct entities, will return this value; collections do not. // Would want to use the Last-Modified over the refresh time, sorting to find the latest. } results.headers = { pages, dirty, }; results.cost = compositeCost; return results; } private generalizedCollectionMethod(token: string | IGetAuthorizationHeader, apiName: string, method, options, cacheOptions: IPagedCacheOptions): Promise<IRestResponse> { const apiContext = new CompositeApiContext(apiName, method, options); apiContext.maxAgeSeconds = cacheOptions.maxAgeSeconds || 600; apiContext.overrideToken(token); apiContext.libraryContext = this.libraryContext; if (cacheOptions.backgroundRefresh) { apiContext.backgroundRefresh = true; } const compositeEngine = this.libraryContext.compositeEngine as CompositeIntelligentEngine; return compositeEngine.execute(apiContext); } private getCollectionAndFilter(token: string | IGetAuthorizationHeader, options, cacheOptions: IPagedCacheOptions, githubClientMethod, propertiesToKeep) { const capturedThis = this; return function (token, options) { return capturedThis.getFilteredGithubCollectionWithMetadataAnalysis(token, githubClientMethod, options, cacheOptions, propertiesToKeep); }; } private async generalizedCollectionWithFilter(name, githubClientMethod, propertiesToKeep, token, options, cacheOptions: IPagedCacheOptions): Promise<any> { const rows = await this.generalizedCollectionMethod(token, name, this.getCollectionAndFilter(token, options, cacheOptions, githubClientMethod, propertiesToKeep), options, cacheOptions); const flattened = flattenData(rows); return flattened; } }
the_stack
import { Template } from '@aws-cdk/assertions'; import * as lambda from '@aws-cdk/aws-lambda'; import { Duration, Stack } from '@aws-cdk/core'; import * as apigw from '../lib'; describe('cors', () => { test('adds an OPTIONS method to a resource', () => { // GIVEN const stack = new Stack(); const api = new apigw.RestApi(stack, 'api'); const resource = api.root.addResource('MyResource'); // WHEN resource.addCorsPreflight({ allowOrigins: ['https://amazon.com'], }); // THEN Template.fromStack(stack).hasResourceProperties('AWS::ApiGateway::Method', { HttpMethod: 'OPTIONS', ResourceId: { Ref: 'apiMyResourceD5CDB490' }, Integration: { IntegrationResponses: [ { ResponseParameters: { 'method.response.header.Access-Control-Allow-Headers': "'Content-Type,X-Amz-Date,Authorization,X-Api-Key,X-Amz-Security-Token,X-Amz-User-Agent'", 'method.response.header.Access-Control-Allow-Origin': "'https://amazon.com'", 'method.response.header.Vary': "'Origin'", 'method.response.header.Access-Control-Allow-Methods': "'OPTIONS,GET,PUT,POST,DELETE,PATCH,HEAD'", }, StatusCode: '204', }, ], RequestTemplates: { 'application/json': '{ statusCode: 200 }', }, Type: 'MOCK', }, MethodResponses: [ { ResponseParameters: { 'method.response.header.Access-Control-Allow-Headers': true, 'method.response.header.Access-Control-Allow-Origin': true, 'method.response.header.Vary': true, 'method.response.header.Access-Control-Allow-Methods': true, }, StatusCode: '204', }, ], }); }); test('allowCredentials', () => { // GIVEN const stack = new Stack(); const api = new apigw.RestApi(stack, 'api'); const resource = api.root.addResource('MyResource'); // WHEN resource.addCorsPreflight({ allowOrigins: ['https://amazon.com'], allowCredentials: true, }); // THEN Template.fromStack(stack).hasResourceProperties('AWS::ApiGateway::Method', { HttpMethod: 'OPTIONS', ResourceId: { Ref: 'apiMyResourceD5CDB490' }, Integration: { IntegrationResponses: [ { ResponseParameters: { 'method.response.header.Access-Control-Allow-Headers': "'Content-Type,X-Amz-Date,Authorization,X-Api-Key,X-Amz-Security-Token,X-Amz-User-Agent'", 'method.response.header.Access-Control-Allow-Origin': "'https://amazon.com'", 'method.response.header.Vary': "'Origin'", 'method.response.header.Access-Control-Allow-Methods': "'OPTIONS,GET,PUT,POST,DELETE,PATCH,HEAD'", 'method.response.header.Access-Control-Allow-Credentials': "'true'", }, StatusCode: '204', }, ], RequestTemplates: { 'application/json': '{ statusCode: 200 }', }, Type: 'MOCK', }, MethodResponses: [ { ResponseParameters: { 'method.response.header.Access-Control-Allow-Headers': true, 'method.response.header.Access-Control-Allow-Origin': true, 'method.response.header.Vary': true, 'method.response.header.Access-Control-Allow-Methods': true, 'method.response.header.Access-Control-Allow-Credentials': true, }, StatusCode: '204', }, ], }); }); test('allowMethods', () => { // GIVEN const stack = new Stack(); const api = new apigw.RestApi(stack, 'api'); const resource = api.root.addResource('MyResource'); // WHEN resource.addCorsPreflight({ allowOrigins: ['https://aws.amazon.com'], allowMethods: ['GET', 'PUT'], }); // THEN Template.fromStack(stack).hasResourceProperties('AWS::ApiGateway::Method', { HttpMethod: 'OPTIONS', ResourceId: { Ref: 'apiMyResourceD5CDB490' }, Integration: { IntegrationResponses: [ { ResponseParameters: { 'method.response.header.Access-Control-Allow-Headers': "'Content-Type,X-Amz-Date,Authorization,X-Api-Key,X-Amz-Security-Token,X-Amz-User-Agent'", 'method.response.header.Access-Control-Allow-Origin': "'https://aws.amazon.com'", 'method.response.header.Vary': "'Origin'", 'method.response.header.Access-Control-Allow-Methods': "'GET,PUT'", }, StatusCode: '204', }, ], RequestTemplates: { 'application/json': '{ statusCode: 200 }', }, Type: 'MOCK', }, MethodResponses: [ { ResponseParameters: { 'method.response.header.Access-Control-Allow-Headers': true, 'method.response.header.Access-Control-Allow-Origin': true, 'method.response.header.Vary': true, 'method.response.header.Access-Control-Allow-Methods': true, }, StatusCode: '204', }, ], }); }); test('allowMethods ANY will expand to all supported methods', () => { // GIVEN const stack = new Stack(); const api = new apigw.RestApi(stack, 'api'); const resource = api.root.addResource('MyResource'); // WHEN resource.addCorsPreflight({ allowOrigins: ['https://aws.amazon.com'], allowMethods: ['ANY'], }); // THEN Template.fromStack(stack).hasResourceProperties('AWS::ApiGateway::Method', { HttpMethod: 'OPTIONS', ResourceId: { Ref: 'apiMyResourceD5CDB490' }, Integration: { IntegrationResponses: [ { ResponseParameters: { 'method.response.header.Access-Control-Allow-Headers': "'Content-Type,X-Amz-Date,Authorization,X-Api-Key,X-Amz-Security-Token,X-Amz-User-Agent'", 'method.response.header.Access-Control-Allow-Origin': "'https://aws.amazon.com'", 'method.response.header.Vary': "'Origin'", 'method.response.header.Access-Control-Allow-Methods': "'OPTIONS,GET,PUT,POST,DELETE,PATCH,HEAD'", }, StatusCode: '204', }, ], RequestTemplates: { 'application/json': '{ statusCode: 200 }', }, Type: 'MOCK', }, MethodResponses: [ { ResponseParameters: { 'method.response.header.Access-Control-Allow-Headers': true, 'method.response.header.Access-Control-Allow-Origin': true, 'method.response.header.Vary': true, 'method.response.header.Access-Control-Allow-Methods': true, }, StatusCode: '204', }, ], }); }); test('allowMethods ANY cannot be used with any other method', () => { // GIVEN const stack = new Stack(); const api = new apigw.RestApi(stack, 'api'); const resource = api.root.addResource('MyResource'); // THEN expect(() => resource.addCorsPreflight({ allowOrigins: ['https://aws.amazon.com'], allowMethods: ['ANY', 'PUT'], })).toThrow(/ANY cannot be used with any other method. Received: ANY,PUT/); }); test('statusCode can be used to set the response status code', () => { // GIVEN const stack = new Stack(); const api = new apigw.RestApi(stack, 'api'); const resource = api.root.addResource('MyResource'); // WHEN resource.addCorsPreflight({ allowOrigins: ['https://aws.amazon.com'], statusCode: 200, }); // THEN Template.fromStack(stack).hasResourceProperties('AWS::ApiGateway::Method', { HttpMethod: 'OPTIONS', ResourceId: { Ref: 'apiMyResourceD5CDB490' }, Integration: { IntegrationResponses: [ { ResponseParameters: { 'method.response.header.Access-Control-Allow-Headers': "'Content-Type,X-Amz-Date,Authorization,X-Api-Key,X-Amz-Security-Token,X-Amz-User-Agent'", 'method.response.header.Access-Control-Allow-Origin': "'https://aws.amazon.com'", 'method.response.header.Vary': "'Origin'", 'method.response.header.Access-Control-Allow-Methods': "'OPTIONS,GET,PUT,POST,DELETE,PATCH,HEAD'", }, StatusCode: '200', }, ], RequestTemplates: { 'application/json': '{ statusCode: 200 }', }, Type: 'MOCK', }, MethodResponses: [ { ResponseParameters: { 'method.response.header.Access-Control-Allow-Headers': true, 'method.response.header.Access-Control-Allow-Origin': true, 'method.response.header.Vary': true, 'method.response.header.Access-Control-Allow-Methods': true, }, StatusCode: '200', }, ], }); }); test('allowOrigins must contain at least one origin', () => { // GIVEN const stack = new Stack(); const api = new apigw.RestApi(stack, 'api'); const resource = api.root.addResource('MyResource'); // WHEN expect(() => resource.addCorsPreflight({ allowOrigins: [], })).toThrow(/allowOrigins must contain at least one origin/); }); test('allowOrigins can be used to specify multiple origins', () => { // GIVEN const stack = new Stack(); const api = new apigw.RestApi(stack, 'api'); const resource = api.root.addResource('MyResource'); // WHEN resource.addCorsPreflight({ allowOrigins: ['https://twitch.tv', 'https://amazon.com', 'https://aws.amazon.com'], }); // THEN Template.fromStack(stack).hasResourceProperties('AWS::ApiGateway::Method', { HttpMethod: 'OPTIONS', ResourceId: { Ref: 'apiMyResourceD5CDB490' }, Integration: { IntegrationResponses: [ { ResponseParameters: { 'method.response.header.Access-Control-Allow-Headers': "'Content-Type,X-Amz-Date,Authorization,X-Api-Key,X-Amz-Security-Token,X-Amz-User-Agent'", 'method.response.header.Access-Control-Allow-Origin': "'https://twitch.tv'", 'method.response.header.Vary': "'Origin'", 'method.response.header.Access-Control-Allow-Methods': "'OPTIONS,GET,PUT,POST,DELETE,PATCH,HEAD'", }, ResponseTemplates: { 'application/json': '#set($origin = $input.params().header.get("Origin"))\n#if($origin == "") #set($origin = $input.params().header.get("origin")) #end\n#if($origin.matches("https://amazon.com") || $origin.matches("https://aws.amazon.com"))\n #set($context.responseOverride.header.Access-Control-Allow-Origin = $origin)\n#end', }, StatusCode: '204', }, ], RequestTemplates: { 'application/json': '{ statusCode: 200 }', }, Type: 'MOCK', }, MethodResponses: [ { ResponseParameters: { 'method.response.header.Access-Control-Allow-Headers': true, 'method.response.header.Access-Control-Allow-Origin': true, 'method.response.header.Vary': true, 'method.response.header.Access-Control-Allow-Methods': true, }, StatusCode: '204', }, ], }); }); test('maxAge can be used to specify Access-Control-Max-Age', () => { // GIVEN const stack = new Stack(); const api = new apigw.RestApi(stack, 'api'); const resource = api.root.addResource('MyResource'); // WHEN resource.addCorsPreflight({ allowOrigins: ['https://amazon.com'], maxAge: Duration.minutes(60), }); // THEN Template.fromStack(stack).hasResourceProperties('AWS::ApiGateway::Method', { HttpMethod: 'OPTIONS', ResourceId: { Ref: 'apiMyResourceD5CDB490' }, Integration: { IntegrationResponses: [ { ResponseParameters: { 'method.response.header.Access-Control-Allow-Headers': "'Content-Type,X-Amz-Date,Authorization,X-Api-Key,X-Amz-Security-Token,X-Amz-User-Agent'", 'method.response.header.Access-Control-Allow-Origin': "'https://amazon.com'", 'method.response.header.Vary': "'Origin'", 'method.response.header.Access-Control-Allow-Methods': "'OPTIONS,GET,PUT,POST,DELETE,PATCH,HEAD'", 'method.response.header.Access-Control-Max-Age': `'${60 * 60}'`, }, StatusCode: '204', }, ], RequestTemplates: { 'application/json': '{ statusCode: 200 }', }, Type: 'MOCK', }, MethodResponses: [ { ResponseParameters: { 'method.response.header.Access-Control-Allow-Headers': true, 'method.response.header.Access-Control-Allow-Origin': true, 'method.response.header.Vary': true, 'method.response.header.Access-Control-Allow-Methods': true, 'method.response.header.Access-Control-Max-Age': true, }, StatusCode: '204', }, ], }); }); test('disableCache will set Max-Age to -1', () => { // GIVEN const stack = new Stack(); const api = new apigw.RestApi(stack, 'api'); const resource = api.root.addResource('MyResource'); // WHEN resource.addCorsPreflight({ allowOrigins: ['https://amazon.com'], disableCache: true, }); // THEN Template.fromStack(stack).hasResourceProperties('AWS::ApiGateway::Method', { HttpMethod: 'OPTIONS', ResourceId: { Ref: 'apiMyResourceD5CDB490' }, Integration: { IntegrationResponses: [ { ResponseParameters: { 'method.response.header.Access-Control-Allow-Headers': "'Content-Type,X-Amz-Date,Authorization,X-Api-Key,X-Amz-Security-Token,X-Amz-User-Agent'", 'method.response.header.Access-Control-Allow-Origin': "'https://amazon.com'", 'method.response.header.Vary': "'Origin'", 'method.response.header.Access-Control-Allow-Methods': "'OPTIONS,GET,PUT,POST,DELETE,PATCH,HEAD'", 'method.response.header.Access-Control-Max-Age': '\'-1\'', }, StatusCode: '204', }, ], RequestTemplates: { 'application/json': '{ statusCode: 200 }', }, Type: 'MOCK', }, MethodResponses: [ { ResponseParameters: { 'method.response.header.Access-Control-Allow-Headers': true, 'method.response.header.Access-Control-Allow-Origin': true, 'method.response.header.Vary': true, 'method.response.header.Access-Control-Allow-Methods': true, 'method.response.header.Access-Control-Max-Age': true, }, StatusCode: '204', }, ], }); }); test('maxAge and disableCache are mutually exclusive', () => { // GIVEN const stack = new Stack(); const api = new apigw.RestApi(stack, 'api'); const resource = api.root.addResource('MyResource'); // THEN expect(() => resource.addCorsPreflight({ allowOrigins: ['https://amazon.com'], disableCache: true, maxAge: Duration.seconds(10), })).toThrow(/The options "maxAge" and "disableCache" are mutually exclusive/); }); test('exposeHeaders can be used to specify Access-Control-Expose-Headers', () => { // GIVEN const stack = new Stack(); const api = new apigw.RestApi(stack, 'api'); const resource = api.root.addResource('MyResource'); // WHEN resource.addCorsPreflight({ allowOrigins: ['https://amazon.com'], exposeHeaders: ['Authorization', 'Foo'], }); // THEN Template.fromStack(stack).hasResourceProperties('AWS::ApiGateway::Method', { HttpMethod: 'OPTIONS', ResourceId: { Ref: 'apiMyResourceD5CDB490' }, Integration: { IntegrationResponses: [ { ResponseParameters: { 'method.response.header.Access-Control-Allow-Headers': "'Content-Type,X-Amz-Date,Authorization,X-Api-Key,X-Amz-Security-Token,X-Amz-User-Agent'", 'method.response.header.Access-Control-Allow-Origin': "'https://amazon.com'", 'method.response.header.Vary': "'Origin'", 'method.response.header.Access-Control-Allow-Methods': "'OPTIONS,GET,PUT,POST,DELETE,PATCH,HEAD'", 'method.response.header.Access-Control-Expose-Headers': "'Authorization,Foo'", }, StatusCode: '204', }, ], RequestTemplates: { 'application/json': '{ statusCode: 200 }', }, Type: 'MOCK', }, MethodResponses: [ { ResponseParameters: { 'method.response.header.Access-Control-Allow-Headers': true, 'method.response.header.Access-Control-Allow-Origin': true, 'method.response.header.Vary': true, 'method.response.header.Access-Control-Allow-Methods': true, 'method.response.header.Access-Control-Expose-Headers': true, }, StatusCode: '204', }, ], }); }); test('defaultCorsPreflightOptions can be used to specify CORS for all resource tree', () => { // GIVEN const stack = new Stack(); const api = new apigw.RestApi(stack, 'api'); // WHEN const resource = api.root.addResource('MyResource', { defaultCorsPreflightOptions: { allowOrigins: ['https://amazon.com'], }, }); resource.addResource('MyChildResource'); // THEN Template.fromStack(stack).resourceCountIs('AWS::ApiGateway::Method', 2); // on both resources Template.fromStack(stack).hasResourceProperties('AWS::ApiGateway::Method', { HttpMethod: 'OPTIONS', ResourceId: { Ref: 'apiMyResourceD5CDB490' }, }); Template.fromStack(stack).hasResourceProperties('AWS::ApiGateway::Method', { HttpMethod: 'OPTIONS', ResourceId: { Ref: 'apiMyResourceMyChildResource2DC010C5' }, }); }); test('defaultCorsPreflightOptions can be specified at the API level to apply to all resources', () => { // GIVEN const stack = new Stack(); // WHEN const api = new apigw.RestApi(stack, 'api', { defaultCorsPreflightOptions: { allowOrigins: ['https://amazon.com'], }, }); const child1 = api.root.addResource('child1'); child1.addResource('child2'); // THEN Template.fromStack(stack).hasResourceProperties('AWS::ApiGateway::Method', { HttpMethod: 'OPTIONS', ResourceId: { 'Fn::GetAtt': ['apiC8550315', 'RootResourceId'] }, }); Template.fromStack(stack).hasResourceProperties('AWS::ApiGateway::Method', { HttpMethod: 'OPTIONS', ResourceId: { Ref: 'apichild1841A5840' }, }); Template.fromStack(stack).hasResourceProperties('AWS::ApiGateway::Method', { HttpMethod: 'OPTIONS', ResourceId: { Ref: 'apichild1child26A9A7C47' }, }); }); test('Vary: Origin is sent back if Allow-Origin is not "*"', () => { // GIVEN const stack = new Stack(); const api = new apigw.RestApi(stack, 'api'); // WHEN api.root.addResource('AllowAll', { defaultCorsPreflightOptions: { allowOrigins: apigw.Cors.ALL_ORIGINS, }, }); api.root.addResource('AllowSpecific', { defaultCorsPreflightOptions: { allowOrigins: ['http://specific.com'], }, }); // THENB Template.fromStack(stack).hasResourceProperties('AWS::ApiGateway::Method', { ResourceId: { Ref: 'apiAllowAll2F5BC564', }, Integration: { IntegrationResponses: [ { ResponseParameters: { 'method.response.header.Access-Control-Allow-Headers': "'Content-Type,X-Amz-Date,Authorization,X-Api-Key,X-Amz-Security-Token,X-Amz-User-Agent'", 'method.response.header.Access-Control-Allow-Origin': "'*'", 'method.response.header.Access-Control-Allow-Methods': "'OPTIONS,GET,PUT,POST,DELETE,PATCH,HEAD'", }, StatusCode: '204', }, ], RequestTemplates: { 'application/json': '{ statusCode: 200 }', }, Type: 'MOCK', }, MethodResponses: [ { ResponseParameters: { 'method.response.header.Access-Control-Allow-Headers': true, 'method.response.header.Access-Control-Allow-Origin': true, 'method.response.header.Access-Control-Allow-Methods': true, }, StatusCode: '204', }, ], }); Template.fromStack(stack).hasResourceProperties('AWS::ApiGateway::Method', { ResourceId: { Ref: 'apiAllowSpecific77DD8AF1', }, Integration: { IntegrationResponses: [ { ResponseParameters: { 'method.response.header.Access-Control-Allow-Headers': "'Content-Type,X-Amz-Date,Authorization,X-Api-Key,X-Amz-Security-Token,X-Amz-User-Agent'", 'method.response.header.Access-Control-Allow-Origin': "'http://specific.com'", 'method.response.header.Access-Control-Allow-Methods': "'OPTIONS,GET,PUT,POST,DELETE,PATCH,HEAD'", 'method.response.header.Vary': "'Origin'", }, StatusCode: '204', }, ], RequestTemplates: { 'application/json': '{ statusCode: 200 }', }, Type: 'MOCK', }, MethodResponses: [ { ResponseParameters: { 'method.response.header.Access-Control-Allow-Headers': true, 'method.response.header.Access-Control-Allow-Origin': true, 'method.response.header.Access-Control-Allow-Methods': true, 'method.response.header.Vary': true, }, StatusCode: '204', }, ], }); }); test('If "*" is specified in allow-origin, it cannot be mixed with specific origins', () => { // GIVEN const stack = new Stack(); const api = new apigw.RestApi(stack, 'api'); // WHEN expect(() => api.root.addResource('AllowAll', { defaultCorsPreflightOptions: { allowOrigins: ['https://bla.com', '*', 'https://specific'], }, })).toThrow(/Invalid "allowOrigins" - cannot mix "\*" with specific origins: https:\/\/bla\.com,\*,https:\/\/specific/); }); test('defaultCorsPreflightOptions can be used to specify CORS for all resource tree [LambdaRestApi]', () => { // GIVEN const stack = new Stack(); const handler = new lambda.Function(stack, 'handler', { handler: 'index.handler', code: lambda.Code.fromInline('boom'), runtime: lambda.Runtime.NODEJS_14_X, }); // WHEN new apigw.LambdaRestApi(stack, 'lambda-rest-api', { handler, defaultCorsPreflightOptions: { allowOrigins: ['https://amazon.com'], }, }); // THEN Template.fromStack(stack).resourceCountIs('AWS::ApiGateway::Method', 4); // two ANY and two OPTIONS resources Template.fromStack(stack).hasResourceProperties('AWS::ApiGateway::Method', { HttpMethod: 'OPTIONS', ResourceId: { 'Fn::GetAtt': [ 'lambdarestapiAAD10924', 'RootResourceId', ], }, }); Template.fromStack(stack).hasResourceProperties('AWS::ApiGateway::Method', { HttpMethod: 'OPTIONS', ResourceId: { Ref: 'lambdarestapiproxyE3AE07E3', }, }); }); test('CORS and proxy resources', () => { // GIVEN const stack = new Stack(); // WHEN const api = new apigw.RestApi(stack, 'API', { defaultCorsPreflightOptions: { allowOrigins: ['*'] }, }); api.root.addProxy(); // THEN Template.fromStack(stack).hasResourceProperties('AWS::ApiGateway::Method', { HttpMethod: 'OPTIONS', }); }); });
the_stack
import { Help } from '@cli-engine/command/lib/help' import { ICommand } from '@cli-engine/config' import cli from 'cli-ux' import * as path from 'path' import RWLockfile, { rwlockfile } from 'rwlockfile' import _ from 'ts-lodash' import { ICommandInfo, ICommandManager, ILoadResult } from '../command' import Config from '../config' import deps from '../deps' import { ITopic, ITopics, topicsToArray } from '../topic' import { PluginManifest } from './manifest' export type PluginType = 'builtin' | 'main' | 'core' | 'user' | 'link' export interface IPluginPJSON { name: string version: string main?: string scripts?: { [k: string]: string } oclif: { commands?: string topics?: ITopics } 'cli-engine': { commands?: string topics?: ITopics } } export interface IPluginTopic { name: string description?: string hidden?: boolean } export interface IPluginModule { commands: ICommand[] topic?: IPluginTopic topics: IPluginTopic[] } export interface IPluginOptions { config: Config root: string pjson: IPluginPJSON type: PluginType } export abstract class Plugin implements ICommandManager { public type: PluginType public name: string public version: string public tag?: string public pjson: IPluginPJSON public root: string protected config: Config protected debug: any protected lock: RWLockfile protected result: ILoadResult protected skipCache?: boolean private _module: Promise<IPluginModule> private cache: PluginManifest constructor(opts: IPluginOptions) { this.config = opts.config this.root = opts.root this.pjson = opts.pjson if (!this.pjson['cli-engine']) this.pjson['cli-engine'] = {} this.name = this.name || this.pjson.name this.version = this.version || this.pjson.version let cacheKey = [this.config.version, this.version].join(path.sep) let cacheFile = path.join(this.config.cacheDir, 'plugins', [opts.type, this.name + '.json'].join(path.sep)) this.cache = new deps.PluginManifest({ file: cacheFile, invalidate: cacheKey, name: this.name }) this.debug = require('debug')(`cli:plugins:${[opts.type, this.name, this.version].join(':')}`) this.lock = new RWLockfile(cacheFile, { ifLocked: () => cli.action.start(`Plugin ${this.name} is updating`) }) this.type = opts.type } public async load(): Promise<ILoadResult> { if (this.result) return this.result this.result = { commands: await this.commands(), topics: await this.topics(), } return this.result } @rwlockfile('lock', 'write') public async reset(reload = false) { await this.cache.reset() if (reload) await this.load() } public async findCommand(id: string, must: true): Promise<ICommand> public async findCommand(id: string, must?: boolean): Promise<ICommand | undefined> public async findCommand(id: string, must = false): Promise<ICommand | undefined> { let cmd = await this.findCommandInModule(id) if (!cmd) cmd = await this.findCommandInDir(id) if (cmd) { cmd = this.addPluginToCommand(cmd) return cmd } if (must) throw new Error(`${id} not found`) } protected async commands(): Promise<ICommandInfo[]> { let cacheFetchCallback = async (): Promise<ICommandInfo[]> => { this.debug('fetching commands') const commands = await deps .assync<any>([this.commandsFromModule(), this.commandsFromDir()]) .flatMap<ICommandInfo>() const r = await Promise.all(commands) return r } let cache: ICommandInfo[] = await this.cacheFetch('commands', cacheFetchCallback) if (!cache) cache = await cacheFetchCallback() return cache.map(c => ({ ...c, fetchCommand: () => this.findCommand(c.id, true), run: async (argv: string[]) => { // await this.lock.add('read', { reason: 'running plugin' }) let cmd = await this.findCommand(c.id, true) let res let base = (cmd as any)._base let legacy = (cmd as any).legacy if (!legacy && base && base.startsWith('@oclif')) { res = await cmd.run(argv.slice(3) as any, { root: cmd.plugin!.root, devPlugins: false } as any) } else if ((!legacy && !c._version) || c._version === '0.0.0') { // this.debug('legacy @cli-engine/command version', c._version) res = await (cmd as any).run({ ...this.config, argv: argv.slice(4) }) } else if (!legacy && deps.semver.lt(c._version || '', '10.0.0')) { // this.debug('legacy @cli-engine/command version', c._version) let cvrtConfig = this.convertConfig(this.config) res = await (cmd as any).run({ ...cvrtConfig, argv: argv.slice(1) }) } else if (!legacy && deps.semver.lt(c._version || '', '11.0.0-beta.0')) { // this.debug(`legacy @cli-engine/command version`, c._version) res = await (cmd as any).run({ ...this.config, argv: argv.slice(2) }) } else { res = await cmd.run(argv.slice(3), this.config) } // await this.lock.remove('read') return res }, })) } protected async topics(): Promise<ITopic[]> { const cache: ITopic[] = await this.cacheFetch('topics', async () => { this.debug('fetching topics') const m = await this.fetchModule() if (!m) return [] return m.topics }) let pjson = this.pjson.oclif || this.pjson['cli-engine'] let pjsonTopics = pjson.topics if (pjsonTopics) return cache.concat(topicsToArray(pjsonTopics)) return cache } protected get commandsDir(): string | undefined { let pjson = this.pjson.oclif || this.pjson['cli-engine'] let d = pjson.commands if (d) return path.join(this.root, d) } protected async commandIDsFromDir(): Promise<string[]> { const d = this.commandsDir if (!d) return Promise.resolve([]) this.debug(`loading IDs from ${d}`) const files = await deps.globby(['**/*.+(js|ts)', '!**/*.+(d.ts|test.ts|test.js)'], { nodir: true, cwd: d }) const ids = files .map(path.parse) .map((p: any) => _.compact([...p.dir.split(path.sep), p.name === 'index' ? '' : p.name]).join(':')) this.debug(`commandIDsFromDir dir:%s, ids:%o`, d, ids) return ids } private commandPath(id: string): string { if (!this.commandsDir) throw new Error('commandsDir not set') return require.resolve(path.join(this.commandsDir, id.split(':').join(path.sep))) } private async commandsFromModule(): Promise<Partial<ICommandInfo>[]> { const m = await this.fetchModule() if (!m) return [] return deps.assync(m.commands).map(c => this.commandInfoFromICommand(c)) } private async commandsFromDir(): Promise<Partial<ICommandInfo>[]> { const ids = await this.commandIDsFromDir() return deps .assync(ids) .map(id => ({ cmd: this.findCommandInDir(id), id })) .map(({ cmd, id }) => this.commandInfoFromICommand(cmd, id)) } private async commandInfoFromICommand(icommand: ICommand, id = icommand.id): Promise<Partial<ICommandInfo>> { let help = await (icommand.buildHelp ? icommand.buildHelp(this.config) : this.buildHelp(icommand)) let helpLine = await (icommand.buildHelpLine ? icommand.buildHelpLine(this.config) : this.buildHelpLine(icommand)) return { id, _version: icommand._version, description: icommand.description, usage: icommand.usage, plugin: { name: this.name, version: this.version }, hidden: icommand.hidden, aliases: icommand.aliases || [], help, helpLine, } } private async buildHelp(c: ICommand): Promise<string> { return new Help(this.config).command(c) } private async buildHelpLine(c: ICommand) { return new Help(this.config).commandLine(c) } private findCommandInDir(id: string): ICommand { let c = deps.util.undefault(require(this.commandPath(id))) if (!c.id) c.id = id return c } private async findCommandInModule(id: string) { const m = await this.fetchModule() if (!m) return return m.commands.find(c => c.id === id) } private addPluginToCommand(cmd: ICommand): ICommand { cmd.plugin = { type: this.type, root: this.root, name: this.name, version: this.version, } return cmd } private async fetchModule(): Promise<IPluginModule | undefined> { if (!this.pjson.main) return if (this._module) return this._module return (this._module = (async () => { this.debug(`requiring ${this.name}@${this.version}`) const m: IPluginModule = { commands: [], topics: [], ...require(path.join(this.root, this.pjson.main!)), } if (m.topic) m.topics.push(m.topic) m.commands = m.commands.map(deps.util.undefault) const hooks = new deps.Hooks(this.config) await hooks.run('plugins:parse', { module: m, pjson: this.pjson }) let legacy = new deps.PluginLegacy(this.config) return legacy.convert(m) })()) } private cacheFetch<T>(key: string, fn: () => Promise<T>) { return this.skipCache ? fn() : this.cache.fetch(key, fn) } private convertConfig(config: Config): Partial<Config> { return { argv: config.argv, bin: config.bin, channel: config.channel, name: config.name, reexecBin: config.reexecBin, root: config.root, version: config.version, arch: config.arch, platform: config.platform, windows: config.windows, corePlugins: config.corePlugins, defaultCommand: config.defaultCommand, hooks: config.hooks, npmRegistry: config.npmRegistry, topics: config.topics, userPluginsEnabled: config.userPluginsEnabled, s3: config.s3, dirname: config.dirname, home: config.home, cacheDir: config.cacheDir, configDir: config.configDir, dataDir: config.dataDir, errlog: config.errlog, pjson: config.pjson, userAgent: config.userAgent, commandsDir: config.commandsDir, updateDisabled: config.updateDisabled, shell: config.shell, debug: config.debug, } } }
the_stack
import { throwError, ConnectableObservable, Observable, Subscription, from, of as just } from 'rxjs' import { concatMap, map, tap } from 'rxjs/operators' import * as lf from 'lovefield' import * as Exception from '../exception' import * as typeDefinition from './helper/definition' import Version from '../version' import { Traversable } from '../shared' import { Mutation, Selector, QueryToken, PredicateProvider } from './modules' import { dispose, contextTableName, fieldIdentifier, hiddenColName } from './symbols' import { forEach, clone, contains, tryCatch, isException, hasOwn, getType, assert, assertValue, warn, isNonNullable, } from '../utils' import { createPredicate, createPkClause, mergeTransactionResult, predicatableQuery, lfFactory } from './helper' import { Relationship, RDBType, DataStoreType, LeafType, StatementType, JoinMode } from '../interface/enum' import { SchemaDef, ColumnDef, ParsedSchema, Association, ScopedHandler } from '../interface' import { ColumnLeaf, NavigatorLeaf, ExecutorResult, UpsertContext, SelectContext } from '../interface' import { Record, Field, JoinInfo, Query, Clause, Predicate, Transaction, TransactionDescriptor, TransactionEffects, } from '../interface' const transactionErrorHandler = { error: () => warn(`Execute failed, transaction is already marked for rollback.`), } const tryCatchCreatePredicate = tryCatch(createPredicate) export class Database { public static version = Version public static getTables(db: lf.Database, ...tableNames: string[]) { return tableNames.map((name) => db.getSchema().table(name)) } public readonly database$: ConnectableObservable<lf.Database> public readonly inTransaction: boolean = false private schemaDefs = new Map<string, SchemaDef<any>>() private schemas = new Map<string, ParsedSchema>() private schemaBuilder: lf.schema.Builder | null private connected = false // note thin cache will be unreliable in some eage case private storedIds = new Set<string>() private subscription: Subscription | null = null private findSchema = (name: string): ParsedSchema => { const schema = this.schemas.get(name) assertValue(schema, Exception.NonExistentTable, name) return schema } private tryCatchFindPrimaryKey = tryCatch((name: string) => { return this.findSchema(name).pk }) private tryCatchFindSchema = tryCatch(this.findSchema) /** * @method defineSchema * @description 定义数据表的 metadata, 通过ReactiveDB查询时会根据这些 metadata 决定如何处理关联数据 */ defineSchema<T>(tableName: string, schema: SchemaDef<T>) { const advanced = !this.schemaDefs.has(tableName) && !this.connected assert(advanced, Exception.UnmodifiableTable) const hasPK = Object.keys(schema).some((key: string) => schema[key].primaryKey === true) assert(hasPK, Exception.PrimaryKeyNotProvided, { tableName }) this.schemaDefs.set(tableName, schema) return this } /** * @constructor ReactiveDB * @param storeType 定义使用的BackStore类型 * @param enableInspector 是否允许外联Inspector * @param name 定义当前数据仓储的名字 * @param version 定义当前数据仓储的版本 */ constructor( storeType: DataStoreType = DataStoreType.MEMORY, enableInspector: boolean = false, name = 'ReactiveDB', version = 1, ) { this.schemaBuilder = lf.schema.create(name, version) this.database$ = lfFactory(this.schemaBuilder, { storeType, enableInspector }) } connect() { this.buildTables() this.connected = true // definition should be clear once database is connected this.schemaDefs.clear() this.subscription = this.database$.connect() } dump() { const dump = (db: lf.Database) => db.export() return this.database$.pipe(concatMap(dump)) } load(data: any) { assert(!this.connected, Exception.DatabaseIsNotEmpty) const load = (db: lf.Database) => { const findPrimaryKey = this.tryCatchFindPrimaryKey({ call: 'load', doThrow: true }) forEach(data.tables, (entities: any[], name: string) => { const { unwrapped: pk } = findPrimaryKey(name) entities.forEach((entity: any) => this.storedIds.add(fieldIdentifier(name, entity[pk]))) }) return db.import(data).catch(() => { forEach(data.tables, (entities: any[], name: string) => { const { unwrapped: pk } = findPrimaryKey(name) entities.forEach((entity: any) => this.storedIds.delete(fieldIdentifier(name, entity[pk]))) }) }) } return this.database$.pipe(concatMap(load)) } insert<T>(tableName: string, raw: T[]): Observable<ExecutorResult> insert<T>(tableName: string, raw: T): Observable<ExecutorResult> insert<T>(tableName: string, raw: T | T[]): Observable<ExecutorResult> insert<T>(tableName: string, raw: T | T[]): Observable<ExecutorResult> { const insert = (db: lf.Database) => { const maybeSchema = this.tryCatchFindSchema({ op: 'insert' })(tableName) if (isException(maybeSchema)) { return throwError(maybeSchema.unwrapped) } const schema = maybeSchema.unwrapped const pk = schema.pk const columnMapper = schema.mapper const [table] = Database.getTables(db, tableName) const muts: Mutation[] = [] const entities = clone(raw) const iterator = Array.isArray(entities) ? entities : [entities] iterator.forEach((entity: any) => { const mut = new Mutation(db, table) const hiddenPayload = Object.create(null) columnMapper.forEach((mapper, key) => { // cannot create a hidden column for primary key if (!hasOwn(entity, key) || key === pk) { return } const val = entity[key] hiddenPayload[key] = mapper(val) hiddenPayload[hiddenColName(key)] = val }) mut.patch({ ...entity, ...hiddenPayload }) mut.withId(pk, entity[pk]) muts.push(mut) }) const { contextIds, queries } = Mutation.aggregate(db, muts, []) contextIds.forEach((id) => this.storedIds.add(id)) const onError = { error: () => contextIds.forEach((id) => this.storedIds.delete(id)) } if (this.inTransaction) { this.attachTx(onError) return this.executor(db, queries) } return this.executor(db, queries).pipe(tap(onError)) } return this.database$.pipe(concatMap(insert)) } get<T>(tableName: string, query: Query<T> = {}, mode: JoinMode = JoinMode.imlicit): QueryToken<T> { const selector$ = this.database$.pipe(map((db) => this.buildSelector(db, tableName, query, mode))) return new QueryToken<T>(selector$) } update<T>(tableName: string, clause: Predicate<T>, raw: Partial<T>): Observable<ExecutorResult> { const type = getType(raw) if (type !== 'Object') { return throwError(Exception.InvalidType(['Object', type])) } const maybeSchema = this.tryCatchFindSchema({ op: 'update' })(tableName) if (isException(maybeSchema)) { return throwError(maybeSchema.unwrapped) } const schema = maybeSchema.unwrapped const update = (db: lf.Database) => { const entity = clone(raw) const [table] = Database.getTables(db, tableName) const columnMapper = schema.mapper const hiddenPayload = Object.create(null) columnMapper.forEach((mapper, key) => { // cannot create a hidden column for primary key if (!hasOwn(entity, key) || key === schema.pk) { return } const val = (entity as any)[key] hiddenPayload[key] = mapper(val) hiddenPayload[hiddenColName(key)] = val }) const mut = { ...(entity as any), ...hiddenPayload } const predicate = createPredicate(table, clause) const query = predicatableQuery(db, table, predicate!, StatementType.Update) forEach(mut, (val, key) => { const column = table[key] if (key === schema.pk) { warn(`Primary key is not modifiable.`) } else if (!column) { warn(`Column: ${key} is not existent on table:${tableName}`) } else { query.set(column, val) } }) return this.executor(db, [query]) } return this.database$.pipe(concatMap(update)) } delete<T>(tableName: string, clause: Predicate<T> = {}): Observable<ExecutorResult> { const maybePK = this.tryCatchFindPrimaryKey({ op: 'delete' })(tableName) if (isException(maybePK)) { return throwError(maybePK.unwrapped) } const pk = maybePK.unwrapped const deletion = (db: lf.Database): Observable<ExecutorResult> => { const [table] = Database.getTables(db, tableName) const column = table[pk] const provider = new PredicateProvider(table, clause) const prefetch = predicatableQuery(db, table, provider.getPredicate(), StatementType.Select, column) const deleteByScopedIds = (scopedIds: Object[]) => { const query = predicatableQuery(db, table, provider.getPredicate(), StatementType.Delete) scopedIds.forEach((entity) => this.storedIds.delete(fieldIdentifier(tableName, entity[pk]))) const onError = { error: () => { scopedIds.forEach((entity: object) => this.storedIds.add(fieldIdentifier(tableName, entity[pk]))) }, } if (this.inTransaction) { this.attachTx(onError) return this.executor(db, [query]) } return this.executor(db, [query]).pipe(tap(onError)) } return from(prefetch.exec()).pipe(concatMap(deleteByScopedIds)) } return this.database$.pipe(concatMap(deletion)) } upsert<T>(tableName: string, raw: T): Observable<ExecutorResult> upsert<T>(tableName: string, raw: T[]): Observable<ExecutorResult> upsert<T>(tableName: string, raw: T | T[]): Observable<ExecutorResult> upsert<T>(tableName: string, raw: T | T[]): Observable<ExecutorResult> { const upsert = (db: lf.Database) => { const sharing = new Map<any, Mutation>() const insert: Mutation[] = [] const update: Mutation[] = [] this.traverseCompound(db, tableName, clone(raw), insert, update, sharing) const { contextIds, queries } = Mutation.aggregate(db, insert, update) if (queries.length > 0) { contextIds.forEach((id) => this.storedIds.add(id)) const onError = { error: () => contextIds.forEach((id) => this.storedIds.delete(id)) } if (this.inTransaction) { this.attachTx(onError) return this.executor(db, queries) } return this.executor(db, queries).pipe(tap(onError)) } else { return just({ result: false, insert: 0, update: 0, delete: 0, select: 0 }) } } return this.database$.pipe(concatMap(upsert)) } remove<T>(tableName: string, clause: Clause<T> = {}): Observable<ExecutorResult> { const maybeSchema = this.tryCatchFindSchema({ op: 'remove' })(tableName) if (isException(maybeSchema)) { return throwError(maybeSchema.unwrapped) } const schema = maybeSchema.unwrapped const disposeHandler = schema.dispose const remove = (db: lf.Database) => { const [table] = Database.getTables(db, tableName) const predicate = createPredicate(table, clause.where) const queries: lf.query.Builder[] = [] const removedIds: any = [] queries.push(predicatableQuery(db, table, predicate!, StatementType.Delete)) const removeByRootEntities = (rootEntities: Object[]) => { rootEntities.forEach((entity) => { removedIds.push(fieldIdentifier(tableName, entity[schema.pk])) }) const onError = { error: () => removedIds.forEach((id: string) => this.storedIds.add(id)), } if (disposeHandler) { const scope = this.createScopedHandler<T>(db, queries, removedIds) return disposeHandler(rootEntities, scope).pipe( tap(() => removedIds.forEach((id: string) => this.storedIds.delete(id))), concatMap(() => { if (this.inTransaction) { this.attachTx(onError) return this.executor(db, queries) } return this.executor(db, queries).pipe(tap(onError)) }), ) } else { removedIds.forEach((id: string) => this.storedIds.delete(id)) if (this.inTransaction) { this.attachTx(onError) return this.executor(db, queries) } return this.executor(db, queries).pipe(tap(onError)) } } const prefetch = predicatableQuery(db, table, predicate!, StatementType.Select) return from(prefetch.exec()).pipe(concatMap(removeByRootEntities)) } return this.database$.pipe(concatMap(remove)) } dispose(): Observable<never> | Observable<ExecutorResult> { if (!this.connected) { return throwError(Exception.NotConnected()) } const cleanUp = (db: lf.Database) => { const deletions = db .getSchema() .tables() .map((t) => db.delete().from(t)) return this.executor(db, deletions).pipe( tap(() => { db.close() this.schemas.clear() this.storedIds.clear() this.schemaBuilder = null this.subscription!.unsubscribe() }), ) } return this.database$.pipe(concatMap(cleanUp)) } attachTx(_: TransactionEffects) { throw Exception.UnexpectedTransactionUse() } executor(db: lf.Database, queries: lf.query.Builder[]) { const tx = db.createTransaction() return from(tx.exec(queries)).pipe( tap(transactionErrorHandler), map((ret) => { return { result: true, ...mergeTransactionResult(queries, ret), } }), ) } transaction(): Observable<Transaction<Database>> { type ProxyProperty = Pick<Database, 'attachTx' | 'executor' | 'inTransaction'> return this.database$.pipe( map((db) => { const tx = db.createTransaction() const transactionQueries: lf.query.Builder[] = [] const effects: TransactionEffects[] = [] const transactionContext: TransactionDescriptor<ProxyProperty> = { attachTx: { get() { return (handler: TransactionEffects) => { effects.push(handler) } }, }, executor: { get() { return (_: lf.Database, queries: lf.query.Builder[]) => { transactionQueries.push(...queries) return just(null) } }, }, inTransaction: { get() { return true }, }, } const customTx = { commit: () => { return effects .reduce((acc, curr) => { return acc.pipe(tap(curr)) }, from(tx.exec(transactionQueries))) .pipe( map((r) => { return { result: true, ...mergeTransactionResult(transactionQueries, r), } }), ) }, abort: () => { effects.length = 0 transactionQueries.length = 0 }, } const ret: Transaction<Database> = [Object.create(this, transactionContext), customTx] return ret }), ) } private buildTables() { this.schemaDefs.forEach((schemaDef, tableName) => { const tableBuilder = this.schemaBuilder!.createTable(tableName) this.parseSchemaDef(tableName, schemaDef, tableBuilder) }) } /** * 解析 schemaDefs, 根据解析后的 metadata 建表 */ private parseSchemaDef(tableName: string, schemaDef: SchemaDef<any>, tableBuilder: lf.schema.TableBuilder) { const uniques: string[] = [] const indexes: string[] = [] const primaryKey: string[] = [] const nullable: string[] = [] const columns = new Map<string, RDBType>() const associations = new Map<string, Association>() const mapper = new Map<string, Function>() const disposeHandler = (typeof schemaDef.dispose === 'function' && schemaDef.dispose) || (typeof schemaDef[dispose] === 'function' && schemaDef[dispose]) || undefined // src: schemaDef; dest: uniques, indexes, primaryKey, nullable, associations, mapper // no short-curcuiting forEach(schemaDef, (def, key) => { const currentPK: string | undefined = primaryKey[0] if (typeof def === 'function') { return } if (!def.virtual) { this.createColumn(tableBuilder, key, def.type as RDBType, nullable, mapper) columns.set(key, def.type as RDBType) if (def.primaryKey) { assert(!currentPK, Exception.PrimaryKeyConflict, { tableName, currentPK, incomingPK: key }) primaryKey.push(key) } if (def.unique) { uniques.push(key) } if (def.index) { indexes.push(key) } const isNullable = ![def.primaryKey, def.index, def.unique].some(isNonNullable) if (isNullable) { nullable.push(key) } } else { associations.set(key, { where: def.virtual.where, type: def.type as Relationship, name: def.virtual.name, }) } }) this.schemas.set(tableName, { pk: primaryKey[0], mapper, columns, dispose: disposeHandler, associations, }) if (indexes.length) { tableBuilder.addIndex('index', indexes) } if (uniques.length) { tableBuilder.addUnique('unique', uniques) } if (nullable.length) { tableBuilder.addNullable(nullable) } tableBuilder.addPrimaryKey(primaryKey) } private buildSelector<T>(db: lf.Database, tableName: string, clause: Query<T>, mode: JoinMode) { const { unwrapped: schema } = this.tryCatchFindSchema({ call: 'buildSelector', doThrow: true, })(tableName) const pk = schema.pk const containFields = !!clause.fields const containKey = containFields ? contains(pk, clause.fields!) : true const fields: Set<Field> = containFields ? new Set(clause.fields) : new Set(schema.columns.keys()) const { table, columns, joinInfo, definition } = this.traverseQueryFields( db, tableName, fields, containKey, !containFields, [], {}, mode, ) const query = predicatableQuery(db, table!, null, StatementType.Select, ...columns) joinInfo.forEach((info: JoinInfo) => query.leftOuterJoin(info.table, info.predicate)) const orderDesc = (clause.orderBy || []).map((desc) => { return { column: table![desc.fieldName], orderBy: !desc.orderBy ? null : lf.Order[desc.orderBy], } }) const matcher = { pk: { name: pk, queried: containKey, }, definition, mainTable: table!, } const { limit, skip } = clause const provider = new PredicateProvider(table!, clause.where) return new Selector<T>(db, query, matcher, provider, limit, skip, orderDesc) } private createColumn( tableBuilder: lf.schema.TableBuilder, columnName: string, rdbType: RDBType, nullable: string[], mapper: Map<string, Function>, ): lf.schema.TableBuilder { const hiddenName = hiddenColName(columnName) switch (rdbType) { case RDBType.ARRAY_BUFFER: return tableBuilder.addColumn(columnName, lf.Type.ARRAY_BUFFER) case RDBType.BOOLEAN: return tableBuilder.addColumn(columnName, lf.Type.BOOLEAN) case RDBType.DATE_TIME: nullable.push(hiddenName) mapper.set(columnName, (val: string) => (val ? new Date(val).valueOf() : new Date(0).valueOf())) return tableBuilder.addColumn(columnName, lf.Type.INTEGER).addColumn(hiddenName, lf.Type.STRING) case RDBType.INTEGER: return tableBuilder.addColumn(columnName, lf.Type.INTEGER) case RDBType.LITERAL_ARRAY: nullable.push(hiddenName) mapper.set(columnName, (val: any[]) => (val ? val.join('|') : '')) return tableBuilder.addColumn(columnName, lf.Type.STRING).addColumn(hiddenName, lf.Type.OBJECT) case RDBType.NUMBER: return tableBuilder.addColumn(columnName, lf.Type.NUMBER) case RDBType.OBJECT: return tableBuilder.addColumn(columnName, lf.Type.OBJECT) case RDBType.STRING: return tableBuilder.addColumn(columnName, lf.Type.STRING) default: throw Exception.InvalidType() } } // context 用来标记DFS路径中的所有出现过的表,用于解决self-join时的二义性 // path 用来标记每个查询路径上出现的表,用于解决circular reference private traverseQueryFields( db: lf.Database, tableName: string, fieldsValue: Set<Field>, hasKey: boolean, glob: boolean, path: string[] = [], context: Record = {}, mode: JoinMode, ) { const { unwrapped: schema } = this.tryCatchFindSchema({ call: 'traverseQueryFields', doThrow: true, })(tableName) const rootDefinition = Object.create(null) const navigators: string[] = [] const columns: lf.schema.Column[] = [] const joinInfo: JoinInfo[] = [] if (mode === JoinMode.imlicit && contains(tableName, path)) { return { columns, joinInfo, advanced: false, table: null, definition: null } } else { path.push(tableName) } schema.associations.forEach((_, nav) => { if (glob && !contains(nav, path)) { fieldsValue.add(nav) } navigators.push(nav) }) const onlyNavigator = Array.from(fieldsValue.keys()).every((key) => contains(key, navigators)) assert(!onlyNavigator, Exception.InvalidQuery) if (!hasKey) { // 保证主键一定比关联字段更早的被遍历到 const fields = Array.from(fieldsValue) fields.unshift(schema.pk) fieldsValue = new Set(fields) } const suffix = (context[tableName] || 0) + 1 context[tableName] = suffix const contextName = contextTableName(tableName, suffix) const currentTable = Database.getTables(db, tableName)[0].as(contextName) const handleAdvanced = (ret: any, key: string, defs: Association | ColumnDef) => { if (!ret.advanced) { return } columns.push(...ret.columns) assert(!rootDefinition[key], Exception.AliasConflict, key, tableName) if ((defs as ColumnDef).column) { rootDefinition[key] = defs } else { const { where, type } = defs as Association rootDefinition[key] = typeDefinition.revise(type!, ret.definition) const maybePredicate = tryCatchCreatePredicate({ tableName: ret.table.getName(), })(currentTable, where(ret.table)) if (isException(maybePredicate)) { warn(`Failed to build predicate, since ${maybePredicate.unwrapped.message}`) } const predicate = maybePredicate.unwrapped const joinLink = predicate ? [{ table: ret.table, predicate }, ...ret.joinInfo] : ret.joinInfo joinInfo.push(...joinLink) } } const traversable = new Traversable<SelectContext>(fieldsValue) traversable.context((field, val, ctx) => { if (!ctx || ctx.isRoot || typeof field !== 'string') { return false } const isNavigatorLeaf = contains(field, navigators) const type = isNavigatorLeaf ? LeafType.navigator : LeafType.column const key = ctx.key ? ctx.key : val if (isNavigatorLeaf) { const description = schema.associations.get(ctx.key) if (!description) { warn(`Build a relationship failed, field: ${ctx.key}.`) return false } return { type, key, leaf: this.navigatorLeaf(description, ctx.key, val) } } if (!currentTable[field]) { warn(`Column: ${field} is not exist on ${tableName}`) return false } return { type, key, leaf: this.columnLeaf(currentTable, contextName, field) } }) traversable.forEach((ctx) => { switch (ctx.type) { case LeafType.column: const { column, identifier } = ctx.leaf as ColumnLeaf const type = schema.columns.get(ctx.key)! const columnDef = typeDefinition.create(identifier, schema.pk === ctx.key, type) handleAdvanced({ columns: [column], advanced: true }, ctx.key, columnDef) break case LeafType.navigator: const { containKey, fields, assocaiation } = ctx.leaf as NavigatorLeaf const ret = this.traverseQueryFields( db, assocaiation.name, new Set(fields), containKey, glob, path.slice(0), context, mode, ) handleAdvanced(ret, ctx.key, assocaiation) ctx.skip() break } }) return { columns, joinInfo, advanced: true, table: currentTable, definition: rootDefinition } } private traverseCompound( db: lf.Database, tableName: string, compoundEntites: any, insertMutList: Mutation[], updateMutList: Mutation[], sharing: Map<string, Mutation>, ) { if (compoundEntites == null) { return } if (Array.isArray(compoundEntites)) { compoundEntites.forEach((item) => this.traverseCompound(db, tableName, item, insertMutList, updateMutList, sharing), ) return } const { unwrapped: schema } = this.tryCatchFindSchema({ call: 'traverseCompound', doThrow: true, })(tableName) const pk = schema.pk const pkVal = compoundEntites[pk] assert(pkVal !== undefined, Exception.PrimaryKeyNotProvided, { tableName, pk, entry: compoundEntites }) const [table] = Database.getTables(db, tableName) const identifier = fieldIdentifier(tableName, pkVal) const visited = contains(identifier, sharing) const stored = contains(identifier, this.storedIds) const mut = visited ? sharing.get(identifier)! : new Mutation(db, table) if (!visited) { const list = stored ? updateMutList : insertMutList list.push(mut) sharing.set(identifier, mut) } const traversable = new Traversable<UpsertContext>(compoundEntites) traversable.context((key, _, ctx) => { const isNavigator = schema.associations.has(key) const isColumn = schema.columns.has(key) const mapper = (isColumn && schema.mapper.get(key)) || null if (!(isColumn || isNavigator || ctx!.isRoot)) { // 若当前节点非 有效节点、叶子节点或者根节点中任意一种时,直接停止子节点的迭代 ctx!.skip() } return ctx!.isRoot || (!isColumn && !isNavigator) ? false : { mapper, visited, isNavigatorLeaf: isNavigator, } }) traversable.forEach((ctx, node) => { // 考虑到叶节点可能存在`Object` type, 所以无论分支节点还是叶节点,其后的结构都不迭代 ctx.skip() if (ctx.isNavigatorLeaf) { const ref = schema.associations.get(ctx.key)!.name return this.traverseCompound(db, ref, node, insertMutList, updateMutList, sharing) } if (ctx.key !== pk) { // 如果字段不为主键 const res = ctx.mapper ? { [ctx.key]: ctx.mapper(node), [hiddenColName(ctx.key)]: node, } : { [ctx.key]: node } mut.patch(res) } else if (ctx.key === pk && !ctx.visited) { // 如果该字段为该表主键, 且该节点是第一次在过程中访问 // i.e. sharing.has(identifier) is equl to false mut.withId(ctx.key, node) } }) } private columnLeaf(table: lf.schema.Table, tableName: string, key: string) { const column = table[key] const hiddenName = hiddenColName(key) const identifier = fieldIdentifier(tableName, key) const hiddenCol = table[hiddenName] const ret = hiddenCol ? hiddenCol.as(identifier) : column.as(identifier) return { identifier, column: ret, } } private navigatorLeaf(assocaiation: Association, _: string, val: any) { const { unwrapped: schema } = this.tryCatchFindSchema({ call: 'navigatorLeaf', doThrow: true, })(assocaiation.name) const fields = typeof val === 'string' ? new Set(schema.columns.keys()) : val return { fields, assocaiation, containKey: contains(schema.pk, val), } } private createScopedHandler<T>(db: lf.Database, queryCollection: any[], keys: any[]) { return (tableName: string): ScopedHandler => { const { unwrapped: pk } = this.tryCatchFindPrimaryKey({ call: 'createScopedHandler', doThrow: true, })(tableName) const remove = (entities: T[]) => { const [table] = Database.getTables(db, tableName) entities.forEach((entity) => { const pkVal = entity[pk] const clause = createPkClause(pk, pkVal) const predicate = createPredicate(table, clause) const query = predicatableQuery(db, table, predicate!, StatementType.Delete) queryCollection.push(query) keys.push(fieldIdentifier(tableName, pkVal)) }) } const get = (where: Predicate<any> | null = null) => { const [table] = Database.getTables(db, tableName) const maybePredicate = tryCatchCreatePredicate({ call: 'createScopedHandler', })(table, where) if (isException(maybePredicate)) { return throwError(maybePredicate.unwrapped) } const predicate = maybePredicate.unwrapped const query = predicatableQuery(db, table, predicate, StatementType.Select) return from<T[]>(query.exec() as any) } return [get, remove] } } }
the_stack
import { defineComponent, getCurrentInstance, ref, h, nextTick, toRef, VNode } from 'vue' import { VcComponentInternalInstance, VcComponentPublicInstance } from '@vue-cesium/utils/types' import { useCommon } from '@vue-cesium/composables' import { VcPrimitive, VcPrimitiveGroundPolyline } from '@vue-cesium/components/primitives' import { VcCollectionPoint, VcCollectionPrimitive } from '@vue-cesium/components/primitive-collections' import { makeMaterial } from '@vue-cesium/utils/cesium-helpers' import VcInstanceGeometry from '@vue-cesium/components/geometry-instance' import { VcGeometryPolyline, VcGeometryPolylineGround } from '@vue-cesium/components/geometries' import defaultProps from './defaultProps' import { VcOverlayHtml } from '@vue-cesium/components/overlays' import { t } from '@vue-cesium/locale' import { VcBtn, VcTooltip } from '@vue-cesium/components/ui' import { usePolylineDrawing } from '@vue-cesium/composables' import { DrawStatus } from '@vue-cesium/shared' import useCustomUpdate from '@vue-cesium/composables/private/use-custom-update' export default defineComponent({ name: 'VcDrawingPolyline', props: defaultProps, emits: ['beforeLoad', 'ready', 'destroyed', 'drawEvt', 'editorEvt', 'mouseEvt'], setup(props, ctx) { // state const instance = getCurrentInstance() as VcComponentInternalInstance instance.cesiumClass = 'VcDrawingPolyline' instance.cesiumEvents = [] const commonState = useCommon(props, ctx, instance) if (commonState === void 0) { return } const { $services } = commonState const { emit } = ctx const drawTip = toRef(props, 'drawtip') ;(drawTip.value as any).drawTip1 = drawTip.value?.drawingTip1 || t('vc.drawing.polyline.drawTip1') ;(drawTip.value as any).drawTip2 = drawTip.value?.drawingTip2 || t('vc.drawing.polyline.drawTip2') ;(drawTip.value as any).drawTip3 = drawTip.value?.drawingTip3 || t('vc.drawing.polyline.drawTip3') const polylineDrawingState = usePolylineDrawing(props, $services, drawTip.value, ctx) const primitiveCollectionRef = ref<VcComponentPublicInstance | null>(null) const { onVcCollectionPointReady } = useCustomUpdate() // methods instance.createCesiumObject = async () => { return primitiveCollectionRef } const handleMouseClick = (movement: Cesium.Cartesian2, options?) => { const result = polylineDrawingState.handleMouseClick(movement, options) const { defined } = Cesium if (defined(result)) { const { drawingVm, selectedDrawingOption, viewer } = $services if (defined(result?.position)) { if (result?.type !== 'new') { ;(drawingVm?.proxy as any).editingDrawingName = undefined polylineDrawingState.canShowDrawTip.value = defined(selectedDrawingOption) } nextTick(() => { emit( 'drawEvt', Object.assign(result, { name: 'polyline' }), viewer ) }) } else { const drawingsOption = (drawingVm?.proxy as any).drawingsOptions.find(v => v.name === 'polyline') ;(drawingVm?.proxy as any).toggleAction(drawingsOption) } } } const handleMouseMove = (movement: Cesium.Cartesian2) => { const result = polylineDrawingState.handleMouseMove(movement) const { defined } = Cesium if (defined(result)) { const { viewer } = $services if (defined(result?.position)) { nextTick(() => { emit( 'drawEvt', Object.assign(result, { name: 'polyline' }), viewer ) }) } } } const handleDoubleClick = movement => { const { drawingVm, selectedDrawingOption, viewer } = $services const result = polylineDrawingState.handleDoubleClick(movement) const { defined } = Cesium if (defined(result)) { if (defined(result?.position)) { nextTick(() => { emit( 'drawEvt', Object.assign(result, { name: 'polyline' }), viewer ) if (props.mode === 1) { ;(drawingVm?.proxy as any).toggleAction(selectedDrawingOption) } }) } } } const startNew = () => { polylineDrawingState.startNew() } const stop = () => { polylineDrawingState.stop() } const clear = () => { polylineDrawingState.polylines.value = [] stop() } const onPrimitiveCollectionReady = ({ cesiumObject }) => { cesiumObject._vcId = 'VcDrawingPolyline' } const onEditorClick = function (this, e) { polylineDrawingState.onEditorClick.bind(this)(e) if (e === 'move' || e === 'insert') { const { drawingVm } = $services ;(drawingVm?.proxy as any).editingDrawingName = 'polyline' } } // expose public methods const publicMethods = { polylines: polylineDrawingState.polylines, startNew, stop, clear, handleMouseClick, handleMouseMove, handleDoubleClick } Object.assign(instance.proxy, publicMethods) return () => { const { PolylineMaterialAppearance, createGuid } = Cesium const polylineOpts: any = { ...props.polylineOpts, vertexFormat: PolylineMaterialAppearance.VERTEX_FORMAT } props.clampToGround && delete polylineOpts.arcType const children: Array<VNode> = [] polylineDrawingState.polylines.value.forEach((polyline, index) => { const positions = polyline.positions.slice() if (positions.length > 1) { // polyline polyline.loop && positions.push(positions[0]) children.push( h( props.clampToGround ? VcPrimitiveGroundPolyline : VcPrimitive, { show: polyline.show, enableMouseEvent: props.enableMouseEvent, appearance: new PolylineMaterialAppearance({ material: makeMaterial.call(instance, props.polylineOpts?.material) as Cesium.Material }), depthFailAppearance: new PolylineMaterialAppearance({ material: makeMaterial.call(instance, props.polylineOpts?.depthFailMaterial) as Cesium.Material }), asynchronous: false }, () => h( VcInstanceGeometry, { id: createGuid() }, () => h(props.clampToGround ? VcGeometryPolylineGround : VcGeometryPolyline, { positions: positions, ...polylineOpts }) ) ) ) } // points children.push( h(VcCollectionPoint, { enableMouseEvent: props.enableMouseEvent, show: polyline.show, points: polyline.positions.map(position => ({ position: position, id: createGuid(), _vcPolylineIndx: index, // for editor ...props.pointOpts, show: props.pointOpts?.show || props.editable || polyline.drawStatus === DrawStatus.Drawing })), onMouseover: polylineDrawingState.onMouseoverPoints.bind('polyline'), onMouseout: polylineDrawingState.onMouseoutPoints.bind('polyline'), onReady: onVcCollectionPointReady }) ) }) if (props.drawtip?.show && polylineDrawingState.canShowDrawTip.value) { const { viewer } = $services children.push( h( VcOverlayHtml, { position: polylineDrawingState.drawTipPosition.value, pixelOffset: props.drawtip.pixelOffset, teleport: { to: viewer.container } }, () => h( 'div', { class: 'vc-drawtip vc-tooltip--style' }, polylineDrawingState.drawTip.value ) ) ) } if (polylineDrawingState.showEditor.value) { const buttons: Array<VNode> = [] if (polylineDrawingState.mouseoverPoint.value) { const editorOpts = props.editorOpts for (const key in editorOpts) { if (!Array.isArray(editorOpts[key]) && typeof editorOpts[key] !== 'number') { const opts = { ...editorOpts[key] } delete opts.color buttons.push( h( VcBtn, { style: { color: editorOpts[key].color, background: editorOpts[key].background }, ...opts, onclick: onEditorClick.bind('polyline', key) }, () => h( VcTooltip, { ...editorOpts[key].tooltip }, () => h('strong', null, editorOpts[key].tooltip?.tip || t(`vc.drawing.editor.${key}`)) ) ) ) } } } const { viewer } = $services children.push( h( VcOverlayHtml, { position: polylineDrawingState.editorPosition.value, pixelOffset: props.editorOpts?.pixelOffset, teleport: { to: viewer.container }, onMouseenter: polylineDrawingState.onMouseenterEditor, onMouseleave: polylineDrawingState.onMouseleaveEditor }, () => h( 'div', { class: 'vc-editor' }, buttons ) ) ) } return h( VcCollectionPrimitive, { ref: primitiveCollectionRef, show: props.show, onReady: onPrimitiveCollectionReady }, () => children ) } } })
the_stack
import { Component, OnInit, AfterViewInit } from '@angular/core'; import { ActivatedRoute, Router } from '@angular/router'; import { HttpErrorResponse, HttpResponse } from '@angular/common/http'; import { AlertService } from 'app/core/util/alert.service'; import { Location } from '@angular/common'; import { TextAssessmentBaseComponent } from 'app/exercises/text/assess/text-assessment-base.component'; import { TextSubmission } from 'app/entities/text-submission.model'; import { TextAssessmentService } from 'app/exercises/text/assess/text-assessment.service'; import { TextBlockRef } from 'app/entities/text-block-ref.model'; import { TextBlock, TextBlockType } from 'app/entities/text-block.model'; import { TextExercise } from 'app/entities/text-exercise.model'; import { Result } from 'app/entities/result.model'; import { FeedbackConflict } from 'app/entities/feedback-conflict'; import { AccountService } from 'app/core/auth/account.service'; import { StructuredGradingCriterionService } from 'app/exercises/shared/structured-grading-criterion/structured-grading-criterion.service'; import { getLatestSubmissionResult, setLatestSubmissionResult } from 'app/entities/submission.model'; import interact from 'interactjs'; import dayjs from 'dayjs'; import { lastValueFrom } from 'rxjs'; @Component({ selector: 'jhi-text-feedback-conflicts', templateUrl: './text-feedback-conflicts.component.html', styleUrls: ['./text-feedback-conflicts.component.scss'], }) export class TextFeedbackConflictsComponent extends TextAssessmentBaseComponent implements OnInit, AfterViewInit { conflictingSubmissions?: TextSubmission[]; leftSubmission?: TextSubmission; leftTextBlockRefs: TextBlockRef[]; leftUnusedTextBlockRefs: TextBlockRef[]; leftTotalScore: number; leftFeedbackId: number; rightSubmission?: TextSubmission; rightTextBlockRefs: TextBlockRef[]; rightUnusedTextBlockRefs: TextBlockRef[]; rightTotalScore: number; feedbackConflicts: FeedbackConflict[]; overrideBusy = false; markBusy = false; isOverrideDisabled = true; isMarkingDisabled = true; selectedRightFeedbackId?: number; private get textBlocksWithFeedbackForLeftSubmission(): TextBlock[] { return [...this.leftTextBlockRefs, ...this.leftUnusedTextBlockRefs] .filter(({ block, feedback }) => block?.type === TextBlockType.AUTOMATIC || !!feedback) .map(({ block }) => block!); } constructor( private activatedRoute: ActivatedRoute, private router: Router, private location: Location, protected accountService: AccountService, protected assessmentsService: TextAssessmentService, protected alertService: AlertService, protected structuredGradingCriterionService: StructuredGradingCriterionService, ) { super(alertService, accountService, assessmentsService, structuredGradingCriterionService); const state = router.getCurrentNavigation()?.extras.state as { submission: TextSubmission }; this.leftFeedbackId = Number(activatedRoute.snapshot.paramMap.get('feedbackId')); this.leftSubmission = state?.submission; this.exercise = this.leftSubmission?.participation?.exercise as TextExercise; this.leftTextBlockRefs = []; this.leftUnusedTextBlockRefs = []; this.rightTextBlockRefs = []; this.rightUnusedTextBlockRefs = []; this.feedbackConflicts = []; } /** * Handles the resizable layout on the right hand side. Adapted from: * @see resizeable-container.component.ts */ ngAfterViewInit() { interact('.movable') .resizable({ edges: { left: '.draggable-left', right: false, bottom: false, top: false }, modifiers: [ // Set maximum width interact.modifiers!.restrictSize({ min: { width: 500, height: 0 }, max: { width: 750, height: 2000 }, }), ], inertia: true, }) .on('resizestart', (event: any) => { event.target.classList.add('card-resizable'); }) .on('resizeend', (event: any) => { event.target.classList.remove('card-resizable'); }) .on('resizemove', (event: any) => { const target = event.target; target.style.width = event.rect.width + 'px'; }); } async ngOnInit() { await super.ngOnInit(); if (!this.leftSubmission) { const submissionId = Number(this.activatedRoute.snapshot.paramMap.get('submissionId')); const participationId = Number(this.activatedRoute.snapshot.paramMap.get('participationId')); const participation = await lastValueFrom(this.assessmentsService.getFeedbackDataForExerciseSubmission(participationId, submissionId)); this.leftSubmission = participation!.submissions![0]; setLatestSubmissionResult(this.leftSubmission, getLatestSubmissionResult(this.leftSubmission)); this.exercise = participation!.exercise as TextExercise; } this.activatedRoute.data.subscribe(({ conflictingTextSubmissions }) => this.setPropertiesFromServerResponse(conflictingTextSubmissions)); } private setPropertiesFromServerResponse(conflictingTextSubmissions: TextSubmission[]) { if (!this.leftSubmission) { return; } this.conflictingSubmissions = conflictingTextSubmissions; conflictingTextSubmissions.forEach((submission) => setLatestSubmissionResult(submission, getLatestSubmissionResult(submission))); this.prepareTextBlocksAndFeedbackFor(this.leftSubmission!, this.leftTextBlockRefs, this.leftUnusedTextBlockRefs); this.leftTotalScore = this.computeTotalScore(this.leftSubmission!.latestResult?.feedbacks!); this.setConflictingSubmission(0); } private setConflictingSubmission(index: number) { this.rightSubmission = this.conflictingSubmissions ? this.conflictingSubmissions[index] : undefined; if (this.rightSubmission) { this.prepareTextBlocksAndFeedbackFor(this.rightSubmission!, this.rightTextBlockRefs, this.rightUnusedTextBlockRefs); this.rightTotalScore = this.computeTotalScore(getLatestSubmissionResult(this.rightSubmission)!.feedbacks!); this.feedbackConflicts = getLatestSubmissionResult(this.leftSubmission)!.feedbacks!.find((f) => f.id === this.leftFeedbackId)?.conflictingTextAssessments || []; } } /** * Changes the displayed submission in the right text assessment area. * @param conflictIndex */ didChangeConflictIndex(conflictIndex: number) { this.rightUnusedTextBlockRefs = []; this.rightTextBlockRefs = []; this.feedbackConflicts = []; this.selectedRightFeedbackId = undefined; this.isMarkingDisabled = true; this.setConflictingSubmission(conflictIndex - 1); } /** * Checks if the current user is the assessor of the passed result. * Passed result could be belong to left or right submission * * @param result - result to check its assessor */ isAssessor(result: Result): boolean { return result?.assessor?.id === this.userId; } /** * Checks if the current user can override the submission. * Only possible if the user is an instructor for the exercise or * If s/he is an assessor of the submission and it is still before assessment due date. * * @param result - result to check override access */ canOverride(result: Result): boolean { if (this.exercise) { if (this.isAtLeastInstructor) { // Instructors can override any assessment at any time. return true; } let isBeforeAssessmentDueDate = true; // Add check as the assessmentDueDate must not be set for exercises if (this.exercise.assessmentDueDate) { isBeforeAssessmentDueDate = dayjs().isBefore(this.exercise.assessmentDueDate!); } // tutors are allowed to override one of their assessments before the assessment due date. return this.isAssessor(result) && isBeforeAssessmentDueDate; } return false; } /** * submits the left submission */ overrideLeftSubmission() { if (!this.leftSubmission || !this.leftSubmission!.latestResult || !this.leftSubmission!.latestResult!.id || this.overrideBusy) { return; } this.overrideBusy = true; this.assessmentsService .submit( this.leftSubmission!.latestResult!.participation?.id!, this.leftSubmission!.latestResult!.id!, this.leftSubmission!.latestResult!.feedbacks!, this.textBlocksWithFeedbackForLeftSubmission, ) .subscribe( (response) => this.handleSaveOrSubmitSuccessWithAlert(response, 'artemisApp.textAssessment.submitSuccessful'), (error: HttpErrorResponse) => this.handleError(error), ); } /** * if the there is a change in left text block (one with the conflicts), total score is calculated again and * override button is enabled. */ leftTextBlockRefsChange(): void { this.leftTotalScore = this.computeTotalScore(this.leftSubmission!.latestResult?.feedbacks!); this.isOverrideDisabled = false; } /** * selects and unselects one of the right conflicting feedback * @param rightFeedbackId - feedback id to un/select */ didSelectConflictingFeedback(rightFeedbackId: number): void { this.selectedRightFeedbackId = rightFeedbackId !== this.selectedRightFeedbackId ? rightFeedbackId : undefined; this.isMarkingDisabled = !this.selectedRightFeedbackId; } /** * Finds the feedback conflict id based on the selected conflicting right feedback's id and calls the service function to solve conflict. */ discardConflict(): void { if (this.markBusy || !this.selectedRightFeedbackId) { return; } const feedbackConflictId = this.feedbackConflicts.find((feedbackConflict) => feedbackConflict.conflictingFeedbackId === this.selectedRightFeedbackId)?.id; if (!feedbackConflictId || !this.exercise) { return; } this.markBusy = true; this.assessmentsService.solveFeedbackConflict(this.exercise!.id!, feedbackConflictId).subscribe( (response) => this.handleSolveConflictsSuccessWithAlert(response, 'artemisApp.textAssessment.solveFeedbackConflictSuccessful'), (error) => this.handleSolveConflictsError(error), ); } private prepareTextBlocksAndFeedbackFor(submission: TextSubmission, textBlockRefs: TextBlockRef[], unusedTextBlockRefs: TextBlockRef[]): void { const feedbackList = submission.latestResult?.feedbacks || []; const matchBlocksWithFeedbacks = TextAssessmentService.matchBlocksWithFeedbacks(submission?.blocks || [], feedbackList); this.sortAndSetTextBlockRefs(matchBlocksWithFeedbacks, textBlockRefs, unusedTextBlockRefs, submission); } protected handleSaveOrSubmitSuccessWithAlert(response: HttpResponse<Result>, translationKey: string): void { super.handleSaveOrSubmitSuccessWithAlert(response, translationKey); this.overrideBusy = false; this.isOverrideDisabled = true; this.location.back(); } private handleSolveConflictsSuccessWithAlert(response: FeedbackConflict, translationKey: string): void { this.alertService.success(translationKey); this.markBusy = false; this.isMarkingDisabled = true; this.location.back(); } protected handleError(error: HttpErrorResponse): void { super.handleError(error); this.overrideBusy = false; this.isOverrideDisabled = true; } private handleSolveConflictsError(error: HttpErrorResponse): void { super.handleError(error); this.markBusy = false; this.isMarkingDisabled = true; } didClickedButtonNoConflict() { this.location.back(); } }
the_stack
import isEqual from 'fast-deep-equal'; import PropTypes from 'prop-types'; import React, { ChangeEvent, FocusEvent, KeyboardEvent, MouseEvent, SyntheticEvent, } from 'react'; import TypeaheadManager from './TypeaheadManager'; import { caseSensitiveType, checkPropType, defaultInputValueType, defaultSelectedType, highlightOnlyResultType, ignoreDiacriticsType, isRequiredForA11y, labelKeyType, optionType, selectedType, } from '../propTypes'; import { addCustomOption, defaultFilterBy, getOptionLabel, getOptionProperty, getStringLabelKey, getUpdatedActiveIndex, getTruncatedOptions, isFunction, isShown, isString, noop, uniqueId, validateSelectedPropChange, } from '../utils'; import { DEFAULT_LABELKEY } from '../constants'; import type { FilterByCallback, Option, RefElement, SelectEvent, TypeaheadProps, TypeaheadState, } from '../types'; const propTypes = { /** * Allows the creation of new selections on the fly. Note that any new items * will be added to the list of selections, but not the list of original * options unless handled as such by `Typeahead`'s parent. * * If a function is specified, it will be used to determine whether a custom * option should be included. The return value should be true or false. */ allowNew: PropTypes.oneOfType([PropTypes.bool, PropTypes.func]), /** * Autofocus the input when the component initially mounts. */ autoFocus: PropTypes.bool, /** * Whether or not filtering should be case-sensitive. */ caseSensitive: checkPropType(PropTypes.bool, caseSensitiveType), /** * The initial value displayed in the text input. */ defaultInputValue: checkPropType(PropTypes.string, defaultInputValueType), /** * Whether or not the menu is displayed upon initial render. */ defaultOpen: PropTypes.bool, /** * Specify any pre-selected options. Use only if you want the component to * be uncontrolled. */ defaultSelected: checkPropType( PropTypes.arrayOf(optionType), defaultSelectedType ), /** * Either an array of fields in `option` to search, or a custom filtering * callback. */ filterBy: PropTypes.oneOfType([ PropTypes.arrayOf(PropTypes.string.isRequired), PropTypes.func, ]), /** * Highlights the menu item if there is only one result and allows selecting * that item by hitting enter. Does not work with `allowNew`. */ highlightOnlyResult: checkPropType(PropTypes.bool, highlightOnlyResultType), /** * An html id attribute, required for assistive technologies such as screen * readers. */ id: checkPropType( PropTypes.oneOfType([PropTypes.number, PropTypes.string]), isRequiredForA11y ), /** * Whether the filter should ignore accents and other diacritical marks. */ ignoreDiacritics: checkPropType(PropTypes.bool, ignoreDiacriticsType), /** * Specify the option key to use for display or a function returning the * display string. By default, the selector will use the `label` key. */ labelKey: checkPropType( PropTypes.oneOfType([PropTypes.string, PropTypes.func]), labelKeyType ), /** * Maximum number of results to display by default. Mostly done for * performance reasons so as not to render too many DOM nodes in the case of * large data sets. */ maxResults: PropTypes.number, /** * Number of input characters that must be entered before showing results. */ minLength: PropTypes.number, /** * Whether or not multiple selections are allowed. */ multiple: PropTypes.bool, /** * Invoked when the input is blurred. Receives an event. */ onBlur: PropTypes.func, /** * Invoked whenever items are added or removed. Receives an array of the * selected options. */ onChange: PropTypes.func, /** * Invoked when the input is focused. Receives an event. */ onFocus: PropTypes.func, /** * Invoked when the input value changes. Receives the string value of the * input. */ onInputChange: PropTypes.func, /** * Invoked when a key is pressed. Receives an event. */ onKeyDown: PropTypes.func, /** * Invoked when menu visibility changes. */ onMenuToggle: PropTypes.func, /** * Invoked when the pagination menu item is clicked. Receives an event. */ onPaginate: PropTypes.func, /** * Whether or not the menu should be displayed. `undefined` allows the * component to control visibility, while `true` and `false` show and hide * the menu, respectively. */ open: PropTypes.bool, /** * Full set of options, including pre-selected options. Must either be an * array of objects (recommended) or strings. */ options: PropTypes.arrayOf(optionType).isRequired, /** * Give user the ability to display additional results if the number of * results exceeds `maxResults`. */ paginate: PropTypes.bool, /** * The selected option(s) displayed in the input. Use this prop if you want * to control the component via its parent. */ selected: checkPropType(PropTypes.arrayOf(optionType), selectedType), }; const defaultProps = { allowNew: false, autoFocus: false, caseSensitive: false, defaultInputValue: '', defaultOpen: false, defaultSelected: [], filterBy: [], highlightOnlyResult: false, ignoreDiacritics: true, labelKey: DEFAULT_LABELKEY, maxResults: 100, minLength: 0, multiple: false, onBlur: noop, onFocus: noop, onInputChange: noop, onKeyDown: noop, onMenuToggle: noop, onPaginate: noop, paginate: true, }; interface Props extends Omit<TypeaheadProps, 'onChange' | 'selected'> { onChange?: (selected: Option[]) => void; selected?: Option[]; } export function getInitialState(props: Props): TypeaheadState { const { defaultInputValue, defaultOpen, defaultSelected, maxResults, multiple, } = props; let selected = props.selected ? props.selected.slice() : defaultSelected.slice(); let text = defaultInputValue; if (!multiple && selected.length) { // Set the text if an initial selection is passed in. text = getOptionLabel(selected[0], props.labelKey); if (selected.length > 1) { // Limit to 1 selection in single-select mode. selected = selected.slice(0, 1); } } return { activeIndex: -1, activeItem: undefined, initialItem: undefined, isFocused: false, selected, showMenu: defaultOpen, shownResults: maxResults, text, }; } export function clearTypeahead(state: TypeaheadState, props: Props) { return { ...getInitialState(props), isFocused: state.isFocused, selected: [], text: '', }; } export function clickOrFocusInput(state: TypeaheadState) { return { ...state, isFocused: true, showMenu: true, }; } export function hideMenu(state: TypeaheadState, props: Props) { const { activeIndex, activeItem, initialItem, shownResults } = getInitialState(props); return { ...state, activeIndex, activeItem, initialItem, showMenu: false, shownResults, }; } export function toggleMenu(state: TypeaheadState, props: Props) { return state.showMenu ? hideMenu(state, props) : { ...state, showMenu: true }; } /** * Manually trigger the input's change event. * https://stackoverflow.com/questions/23892547/what-is-the-best-way-to-trigger-onchange-event-in-react-js/46012210#46012210 */ function triggerInputChange(input: HTMLInputElement, value: string) { const inputValue = Object.getOwnPropertyDescriptor( window.HTMLInputElement.prototype, 'value' ); inputValue && inputValue.set && inputValue.set.call(input, value); const e = new Event('input', { bubbles: true }); input.dispatchEvent(e); } class Typeahead extends React.Component<Props, TypeaheadState> { static propTypes = propTypes; static defaultProps = defaultProps; state = getInitialState(this.props); inputNode: RefElement<HTMLInputElement> = null; isMenuShown = false; // Keeps track of actual items displayed in the menu, after sorting, // truncating, grouping, etc. items: Option[] = []; componentDidMount() { this.props.autoFocus && this.focus(); } componentDidUpdate(prevProps: Props, prevState: TypeaheadState) { const { labelKey, multiple, selected } = this.props; validateSelectedPropChange(selected, prevProps.selected); // Sync selections in state with those in props. if (selected && !isEqual(selected, prevState.selected)) { this.setState({ selected }); if (!multiple) { this.setState({ text: selected.length ? getOptionLabel(selected[0], labelKey) : '', }); } } } render() { const { onChange, ...props } = this.props; const mergedPropsAndState = { ...props, ...this.state }; const { filterBy, labelKey, options, paginate, shownResults, text } = mergedPropsAndState; this.isMenuShown = isShown(mergedPropsAndState); this.items = []; // Reset items on re-render. let results: Option[] = []; if (this.isMenuShown) { const cb = ( isFunction(filterBy) ? filterBy : defaultFilterBy ) as FilterByCallback; results = options.filter((option: Option) => cb(option, mergedPropsAndState) ); // This must come before results are truncated. const shouldPaginate = paginate && results.length > shownResults; // Truncate results if necessary. results = getTruncatedOptions(results, shownResults); // Add the custom option if necessary. if (addCustomOption(results, mergedPropsAndState)) { results.push({ customOption: true, [getStringLabelKey(labelKey)]: text, }); } // Add the pagination item if necessary. if (shouldPaginate) { results.push({ [getStringLabelKey(labelKey)]: '', paginationOption: true, }); } } return ( <TypeaheadManager {...mergedPropsAndState} hideMenu={this.hideMenu} inputNode={this.inputNode} inputRef={this.inputRef} isMenuShown={this.isMenuShown} onActiveItemChange={this._handleActiveItemChange} onAdd={this._handleSelectionAdd} onBlur={this._handleBlur} onChange={this._handleInputChange} onClear={this._handleClear} onClick={this._handleClick} onFocus={this._handleFocus} onHide={this.hideMenu} onInitialItemChange={this._handleInitialItemChange} onKeyDown={this._handleKeyDown} onMenuItemClick={this._handleMenuItemSelect} onRemove={this._handleSelectionRemove} results={results} setItem={this.setItem} toggleMenu={this.toggleMenu} /> ); } blur = () => { this.inputNode && this.inputNode.blur(); this.hideMenu(); }; clear = () => { this.setState(clearTypeahead); }; focus = () => { this.inputNode && this.inputNode.focus(); }; getInput = () => { return this.inputNode; }; inputRef = (inputNode: RefElement<HTMLInputElement>) => { this.inputNode = inputNode; }; setItem = (item: Option, position: number) => { this.items[position] = item; }; hideMenu = () => { this.setState(hideMenu); }; toggleMenu = () => { this.setState(toggleMenu); }; _handleActiveIndexChange = (activeIndex: number) => { this.setState((state: TypeaheadState) => ({ activeIndex, activeItem: activeIndex >= 0 ? state.activeItem : undefined, })); }; _handleActiveItemChange = (activeItem: Option) => { // Don't update the active item if it hasn't changed. if (!isEqual(activeItem, this.state.activeItem)) { this.setState({ activeItem }); } }; _handleBlur = (e: FocusEvent<HTMLInputElement>) => { e.persist(); this.setState({ isFocused: false }, () => this.props.onBlur(e)); }; _handleChange = (selected: Option[]) => { this.props.onChange && this.props.onChange(selected); }; _handleClear = () => { this.inputNode && triggerInputChange(this.inputNode, ''); this.setState(clearTypeahead, () => { // Change handler is automatically triggered for single selections but // not multi-selections. if (this.props.multiple) { this._handleChange([]); } }); }; _handleClick = (e: MouseEvent<HTMLInputElement>) => { e.persist(); const onClick = this.props.inputProps?.onClick; this.setState(clickOrFocusInput, () => isFunction(onClick) && onClick(e)); }; _handleFocus = (e: SyntheticEvent<HTMLInputElement>) => { e.persist(); this.setState(clickOrFocusInput, () => this.props.onFocus(e)); }; _handleInitialItemChange = (initialItem?: Option) => { // Don't update the initial item if it hasn't changed. if (!isEqual(initialItem, this.state.initialItem)) { this.setState({ initialItem }); } }; _handleInputChange = (e: ChangeEvent<HTMLInputElement>) => { e.persist(); const text = e.currentTarget.value; const { multiple, onInputChange } = this.props; // Clear selections when the input value changes in single-select mode. const shouldClearSelections = this.state.selected.length && !multiple; this.setState( (state, props) => { const { activeIndex, activeItem, shownResults } = getInitialState(props); return { activeIndex, activeItem, selected: shouldClearSelections ? [] : state.selected, showMenu: true, shownResults, text, }; }, () => { onInputChange(text, e); shouldClearSelections && this._handleChange([]); } ); }; _handleKeyDown = (e: KeyboardEvent<HTMLInputElement>) => { const { activeItem } = this.state; // Skip most actions when the menu is hidden. if (!this.isMenuShown) { if (e.key === 'ArrowUp' || e.key === 'ArrowDown') { this.setState({ showMenu: true }); } this.props.onKeyDown(e); return; } switch (e.key) { case 'ArrowUp': case 'ArrowDown': // Prevent input cursor from going to the beginning when pressing up. e.preventDefault(); this._handleActiveIndexChange( getUpdatedActiveIndex(this.state.activeIndex, e.key, this.items) ); break; case 'Enter': // Prevent form submission while menu is open. e.preventDefault(); activeItem && this._handleMenuItemSelect(activeItem, e); break; case 'Escape': case 'Tab': // ESC simply hides the menu. TAB will blur the input and move focus to // the next item; hide the menu so it doesn't gain focus. this.hideMenu(); break; default: break; } this.props.onKeyDown(e); }; _handleMenuItemSelect = (option: Option, e: SelectEvent<HTMLElement>) => { if (getOptionProperty(option, 'paginationOption')) { this._handlePaginate(e); } else { this._handleSelectionAdd(option); } }; _handlePaginate = (e: SelectEvent<HTMLElement>) => { e.persist(); this.setState( (state, props) => ({ shownResults: state.shownResults + props.maxResults, }), () => this.props.onPaginate(e, this.state.shownResults) ); }; _handleSelectionAdd = (option: Option) => { const { multiple, labelKey } = this.props; let selected: Option[]; let selection = option; let text: string; // Add a unique id to the custom selection. Avoid doing this in `render` so // the id doesn't increment every time. if (!isString(selection) && selection.customOption) { selection = { ...selection, id: uniqueId('new-id-') }; } if (multiple) { // If multiple selections are allowed, add the new selection to the // existing selections. selected = this.state.selected.concat(selection); text = ''; } else { // If only a single selection is allowed, replace the existing selection // with the new one. selected = [selection]; text = getOptionLabel(selection, labelKey); } this.setState( (state, props) => ({ ...hideMenu(state, props), initialItem: selection, selected, text, }), () => this._handleChange(selected) ); }; _handleSelectionRemove = (selection: Option) => { const selected = this.state.selected.filter( (option) => !isEqual(option, selection) ); // Make sure the input stays focused after the item is removed. this.focus(); this.setState( (state, props) => ({ ...hideMenu(state, props), selected, }), () => this._handleChange(selected) ); }; } export default Typeahead;
the_stack
import * as pulumi from "@pulumi/pulumi"; import { input as inputs, output as outputs } from "../types"; import * as utilities from "../utilities"; /** * An SslCertificate resource, used for HTTPS load balancing. This resource * represents a certificate for which the certificate secrets are created and * managed by Google. * * For a resource where you provide the key, see the * SSL Certificate resource. * * To get more information about ManagedSslCertificate, see: * * * [API documentation](https://cloud.google.com/compute/docs/reference/rest/v1/sslCertificates) * * How-to Guides * * [Official Documentation](https://cloud.google.com/load-balancing/docs/ssl-certificates) * * > **Warning:** This resource should be used with extreme caution! Provisioning an SSL * certificate is complex. Ensure that you understand the lifecycle of a * certificate before attempting complex tasks like cert rotation automatically. * This resource will "return" as soon as the certificate object is created, * but post-creation the certificate object will go through a "provisioning" * process. The provisioning process can complete only when the domain name * for which the certificate is created points to a target pool which, itself, * points at the certificate. Depending on your DNS provider, this may take * some time, and migrating from self-managed certificates to Google-managed * certificates may entail some downtime while the certificate provisions. * * In conclusion: Be extremely cautious. * * ## Example Usage * ### Managed Ssl Certificate Basic * * ```typescript * import * as pulumi from "@pulumi/pulumi"; * import * as gcp from "@pulumi/gcp"; * * const defaultManagedSslCertificate = new gcp.compute.ManagedSslCertificate("defaultManagedSslCertificate", {managed: { * domains: ["sslcert.tf-test.club."], * }}); * const defaultHttpHealthCheck = new gcp.compute.HttpHealthCheck("defaultHttpHealthCheck", { * requestPath: "/", * checkIntervalSec: 1, * timeoutSec: 1, * }); * const defaultBackendService = new gcp.compute.BackendService("defaultBackendService", { * portName: "http", * protocol: "HTTP", * timeoutSec: 10, * healthChecks: [defaultHttpHealthCheck.id], * }); * const defaultURLMap = new gcp.compute.URLMap("defaultURLMap", { * description: "a description", * defaultService: defaultBackendService.id, * hostRules: [{ * hosts: ["sslcert.tf-test.club"], * pathMatcher: "allpaths", * }], * pathMatchers: [{ * name: "allpaths", * defaultService: defaultBackendService.id, * pathRules: [{ * paths: ["/*"], * service: defaultBackendService.id, * }], * }], * }); * const defaultTargetHttpsProxy = new gcp.compute.TargetHttpsProxy("defaultTargetHttpsProxy", { * urlMap: defaultURLMap.id, * sslCertificates: [defaultManagedSslCertificate.id], * }); * const zone = new gcp.dns.ManagedZone("zone", {dnsName: "sslcert.tf-test.club."}); * const defaultGlobalForwardingRule = new gcp.compute.GlobalForwardingRule("defaultGlobalForwardingRule", { * target: defaultTargetHttpsProxy.id, * portRange: 443, * }); * const set = new gcp.dns.RecordSet("set", { * name: "sslcert.tf-test.club.", * type: "A", * ttl: 3600, * managedZone: zone.name, * rrdatas: [defaultGlobalForwardingRule.ipAddress], * }); * ``` * * ## Import * * ManagedSslCertificate can be imported using any of these accepted formats * * ```sh * $ pulumi import gcp:compute/managedSslCertificate:ManagedSslCertificate default projects/{{project}}/global/sslCertificates/{{name}} * ``` * * ```sh * $ pulumi import gcp:compute/managedSslCertificate:ManagedSslCertificate default {{project}}/{{name}} * ``` * * ```sh * $ pulumi import gcp:compute/managedSslCertificate:ManagedSslCertificate default {{name}} * ``` */ export class ManagedSslCertificate extends pulumi.CustomResource { /** * Get an existing ManagedSslCertificate resource's state with the given name, ID, and optional extra * properties used to qualify the lookup. * * @param name The _unique_ name of the resulting resource. * @param id The _unique_ provider ID of the resource to lookup. * @param state Any extra arguments used during the lookup. * @param opts Optional settings to control the behavior of the CustomResource. */ public static get(name: string, id: pulumi.Input<pulumi.ID>, state?: ManagedSslCertificateState, opts?: pulumi.CustomResourceOptions): ManagedSslCertificate { return new ManagedSslCertificate(name, <any>state, { ...opts, id: id }); } /** @internal */ public static readonly __pulumiType = 'gcp:compute/managedSslCertificate:ManagedSslCertificate'; /** * Returns true if the given object is an instance of ManagedSslCertificate. This is designed to work even * when multiple copies of the Pulumi SDK have been loaded into the same process. */ public static isInstance(obj: any): obj is ManagedSslCertificate { if (obj === undefined || obj === null) { return false; } return obj['__pulumiType'] === ManagedSslCertificate.__pulumiType; } /** * The unique identifier for the resource. */ public readonly certificateId!: pulumi.Output<number>; /** * Creation timestamp in RFC3339 text format. */ public /*out*/ readonly creationTimestamp!: pulumi.Output<string>; /** * An optional description of this resource. */ public readonly description!: pulumi.Output<string | undefined>; /** * Expire time of the certificate. */ public /*out*/ readonly expireTime!: pulumi.Output<string>; /** * Properties relevant to a managed certificate. These will be used if the * certificate is managed (as indicated by a value of `MANAGED` in `type`). * Structure is documented below. */ public readonly managed!: pulumi.Output<outputs.compute.ManagedSslCertificateManaged | undefined>; /** * Name of the resource. Provided by the client when the resource is * created. The name must be 1-63 characters long, and comply with * RFC1035. Specifically, the name must be 1-63 characters long and match * the regular expression `a-z?` which means the * first character must be a lowercase letter, and all following * characters must be a dash, lowercase letter, or digit, except the last * character, which cannot be a dash. */ public readonly name!: pulumi.Output<string>; /** * The ID of the project in which the resource belongs. * If it is not provided, the provider project is used. */ public readonly project!: pulumi.Output<string>; /** * The URI of the created resource. */ public /*out*/ readonly selfLink!: pulumi.Output<string>; /** * Domains associated with the certificate via Subject Alternative Name. */ public /*out*/ readonly subjectAlternativeNames!: pulumi.Output<string[]>; /** * Enum field whose value is always `MANAGED` - used to signal to the API * which type this is. * Default value is `MANAGED`. * Possible values are `MANAGED`. */ public readonly type!: pulumi.Output<string | undefined>; /** * Create a ManagedSslCertificate resource with the given unique name, arguments, and options. * * @param name The _unique_ name of the resource. * @param args The arguments to use to populate this resource's properties. * @param opts A bag of options that control this resource's behavior. */ constructor(name: string, args?: ManagedSslCertificateArgs, opts?: pulumi.CustomResourceOptions) constructor(name: string, argsOrState?: ManagedSslCertificateArgs | ManagedSslCertificateState, opts?: pulumi.CustomResourceOptions) { let inputs: pulumi.Inputs = {}; opts = opts || {}; if (opts.id) { const state = argsOrState as ManagedSslCertificateState | undefined; inputs["certificateId"] = state ? state.certificateId : undefined; inputs["creationTimestamp"] = state ? state.creationTimestamp : undefined; inputs["description"] = state ? state.description : undefined; inputs["expireTime"] = state ? state.expireTime : undefined; inputs["managed"] = state ? state.managed : undefined; inputs["name"] = state ? state.name : undefined; inputs["project"] = state ? state.project : undefined; inputs["selfLink"] = state ? state.selfLink : undefined; inputs["subjectAlternativeNames"] = state ? state.subjectAlternativeNames : undefined; inputs["type"] = state ? state.type : undefined; } else { const args = argsOrState as ManagedSslCertificateArgs | undefined; inputs["certificateId"] = args ? args.certificateId : undefined; inputs["description"] = args ? args.description : undefined; inputs["managed"] = args ? args.managed : undefined; inputs["name"] = args ? args.name : undefined; inputs["project"] = args ? args.project : undefined; inputs["type"] = args ? args.type : undefined; inputs["creationTimestamp"] = undefined /*out*/; inputs["expireTime"] = undefined /*out*/; inputs["selfLink"] = undefined /*out*/; inputs["subjectAlternativeNames"] = undefined /*out*/; } if (!opts.version) { opts = pulumi.mergeOptions(opts, { version: utilities.getVersion()}); } const aliasOpts = { aliases: [{ type: "gcp:compute/mangedSslCertificate:MangedSslCertificate" }] }; opts = pulumi.mergeOptions(opts, aliasOpts); super(ManagedSslCertificate.__pulumiType, name, inputs, opts); } } /** * Input properties used for looking up and filtering ManagedSslCertificate resources. */ export interface ManagedSslCertificateState { /** * The unique identifier for the resource. */ certificateId?: pulumi.Input<number>; /** * Creation timestamp in RFC3339 text format. */ creationTimestamp?: pulumi.Input<string>; /** * An optional description of this resource. */ description?: pulumi.Input<string>; /** * Expire time of the certificate. */ expireTime?: pulumi.Input<string>; /** * Properties relevant to a managed certificate. These will be used if the * certificate is managed (as indicated by a value of `MANAGED` in `type`). * Structure is documented below. */ managed?: pulumi.Input<inputs.compute.ManagedSslCertificateManaged>; /** * Name of the resource. Provided by the client when the resource is * created. The name must be 1-63 characters long, and comply with * RFC1035. Specifically, the name must be 1-63 characters long and match * the regular expression `a-z?` which means the * first character must be a lowercase letter, and all following * characters must be a dash, lowercase letter, or digit, except the last * character, which cannot be a dash. */ name?: pulumi.Input<string>; /** * The ID of the project in which the resource belongs. * If it is not provided, the provider project is used. */ project?: pulumi.Input<string>; /** * The URI of the created resource. */ selfLink?: pulumi.Input<string>; /** * Domains associated with the certificate via Subject Alternative Name. */ subjectAlternativeNames?: pulumi.Input<pulumi.Input<string>[]>; /** * Enum field whose value is always `MANAGED` - used to signal to the API * which type this is. * Default value is `MANAGED`. * Possible values are `MANAGED`. */ type?: pulumi.Input<string>; } /** * The set of arguments for constructing a ManagedSslCertificate resource. */ export interface ManagedSslCertificateArgs { /** * The unique identifier for the resource. */ certificateId?: pulumi.Input<number>; /** * An optional description of this resource. */ description?: pulumi.Input<string>; /** * Properties relevant to a managed certificate. These will be used if the * certificate is managed (as indicated by a value of `MANAGED` in `type`). * Structure is documented below. */ managed?: pulumi.Input<inputs.compute.ManagedSslCertificateManaged>; /** * Name of the resource. Provided by the client when the resource is * created. The name must be 1-63 characters long, and comply with * RFC1035. Specifically, the name must be 1-63 characters long and match * the regular expression `a-z?` which means the * first character must be a lowercase letter, and all following * characters must be a dash, lowercase letter, or digit, except the last * character, which cannot be a dash. */ name?: pulumi.Input<string>; /** * The ID of the project in which the resource belongs. * If it is not provided, the provider project is used. */ project?: pulumi.Input<string>; /** * Enum field whose value is always `MANAGED` - used to signal to the API * which type this is. * Default value is `MANAGED`. * Possible values are `MANAGED`. */ type?: pulumi.Input<string>; }
the_stack
import { state, ExpressionEvaluator, numberPickerMechanics, MealMechanics, translations, randomTable, mechanicsEngine, EquipmentSectionMechanics, gameView, template } from "../.."; /** * Random table links mechanics */ export const randomMechanics = { /** * The last random number picked, with the increment added */ lastValue: null as number, /** * Assing an action to a random table link. */ randomTable(rule) { // Do not enable anything if the player is death: if (state.actionChart.currentEndurance <= 0) { return; } // The DOM link: let $link; // Check if the link is selected by plain text: const linkText = $(rule).attr("text-" + state.language); if (linkText) { const $textContainer = $(':contains("' + linkText + '")').last(); const newHtml = $textContainer.html().replace(linkText, '<span class="random">' + linkText + "</span>"); $textContainer.html(newHtml); $link = $textContainer.find(".random"); } else { // Get the index of the random table tag to handle $link = randomMechanics.getRandomTableRefByRule(rule); } // Check if the rule was already executed (= link clicked): const result = state.sectionStates.ruleHasBeenExecuted(rule); if (result) { // Setup the link, but disabled and with the value choosed: randomMechanics.setupRandomTableLink($link, true, result.randomValue, result.increment); // Fire the inner rules: randomMechanics.onRandomTableMechanicsClicked(rule, result.randomValue, result.increment); } else { // Bind the tag click event const zeroAsTen = $(rule).attr("zeroAsTen") === "true"; randomMechanics.bindTableRandomLink($link, (value, increment) => { randomMechanics.onRandomTableMechanicsClicked(rule, value, increment); }, false, zeroAsTen); } }, getRandomTableRefByIndex(index: number): any { if (!index) { index = 0; } return $(".random:eq( " + index + ")"); }, getRandomTableRefByRule(rule: any) { // Not really clear for me: parseInt(undefined) => Nan. It works, because (parseInt(undefined) ? true : false) === false, but, brfff... // return randomMechanics.getRandomTableRefByIndex( parseInt($(rule).attr('index')) ); let indexValue = $(rule).attr("index"); if (!indexValue) { indexValue = "0"; } return randomMechanics.getRandomTableRefByIndex( parseInt(indexValue, 10) ); }, /** * This will clear any increment on the random table links * It can be needed if a section rules need to be re-executed without re-rendering the section * @param {jQuery} $link The random table link to reset. If it's null all section random table link will be reset */ resetRandomTableIncrements($link: JQuery<HTMLElement> = null) { if (!$link) { // Reset all random tables $link = $(".random[data-increment]"); } $link.attr("data-increment", "0"); }, /** Increment for random table selection */ randomTableIncrement(rule: any) { const $link = randomMechanics.getRandomTableRefByRule(rule); const txtIncrement: string = $(rule).attr("increment"); if (txtIncrement === "reset") { // Reset the random table increment to zero randomMechanics.resetRandomTableIncrements($link); return; } // Increase the increment const newIncrement = ExpressionEvaluator.evalInteger(txtIncrement); // Check if already there is an increment: let increment = 0; const txtCurrentIncrement = $link.attr("data-increment"); if (txtCurrentIncrement) { increment = parseInt(txtCurrentIncrement, 10); } increment += newIncrement; $link.attr("data-increment", increment); }, /** * Bind a link event to a random table table * @param $element The jquery element with the random table tag * @param onLinkPressed Callback to call when the link is pressed * @param {boolean} ignoreZero True if the zero random value should be ignored * @param {boolean} zeroAsTen true if the zero must to be returned as ten */ bindTableRandomLink($element: any, onLinkPressed: (value: number, increment: number) => void, ignoreZero: boolean, zeroAsTen: boolean) { // If the element is an span, replace it by a link $element = randomMechanics.setupRandomTableLink($element); $element.click(function(e: Event) { e.preventDefault(); if ($(this).hasClass("disabled")) { // Already clicked return; } // Validate money picker, if there is. If its not valid, don't follow with this link if (!numberPickerMechanics.isValid()) { return; } // If there are pending meals, don't follow with this link if (MealMechanics.arePendingMeals()) { alert(translations.text("doMealFirst")); return; } // Get the random value randomTable.getRandomValueAsync(ignoreZero, zeroAsTen) .then((value) => { // Get the increment const incrementValue = $(this).attr("data-increment"); let increment = 0; if (incrementValue) { increment = parseInt(incrementValue, 10); } // Show the result on the link randomMechanics.linkAddChooseValue($(this), value, increment); // Fire the event: onLinkPressed(value, increment); template.addSectionReadyMarker(); }); }); }, /** * Setup a tag to link to the random table * @param {jQuery} $element The DOM element to setup * @param alreadyChoose If it's true, the link will be set disabled * @param valueAlreadyChoose Only needed if alreadyChoose is true. It's the * previously random value got * @param increment The increment to the choose value, due to game rules * @return {jquery} The link tag already processed */ setupRandomTableLink($element: any, alreadyChoose: boolean = false, valueAlreadyChoose: number = 0, increment: number = 0): any { if (!$element || $element.length === 0) { mechanicsEngine.debugWarning("Random table link not found"); return; } // Initially, the random table links are plain text (spans). When they got setup by a random rule, they // are converted to links: if ($element.prop("tagName").toLowerCase() === "span") { const $link = $('<a class="random action" href="#">' + $element.html() + "</a>"); $element.replaceWith($link); $element = $link; } if (alreadyChoose) { randomMechanics.linkAddChooseValue($element, valueAlreadyChoose, increment); } return $element; }, /** * Change a random table link to clicked */ linkAddChooseValue($link: any, valueChoose: number, increment: number) { if ($link.hasClass("picked")) { // The link text / format has been already assigned return; } let html = valueChoose.toString(); if (increment > 0) { html += " + " + increment; } else if (increment < 0) { html += " - " + (-increment); } $link.append(" (" + html + ")"); // Disable the link: $link.addClass("disabled").addClass("picked"); // Store the value on the UI too $link.attr("data-picked", valueChoose + increment); }, /** * Event handler of a random table link clicked * @param rule The "randomTable" rule * @param randomValue The random value result from the table */ onRandomTableMechanicsClicked(rule: any, randomValue: number, increment: number) { // Set the last choosed value randomMechanics.lastValue = randomValue + increment; // Process rule childs. It can be a single action, and/or a set of "case" rules $(rule).children().each((index, childRule) => { if (childRule.nodeName === "case") { // Evaluate the case rule if (randomMechanics.evaluateCaseRule(childRule, randomValue + increment)) { mechanicsEngine.runChildRules($(childRule)); } } else { // Run unconditional rule mechanicsEngine.runRule(childRule); } }); // Ugly hack: If we are on the 'equipment' section, check if all link has been clicked if (state.sectionStates.currentSection === "equipmnt") { EquipmentSectionMechanics.checkExitEquipmentSection(); } // Mark the rule as executed state.sectionStates.markRuleAsExecuted(rule, { randomValue, increment }); }, getCaseRuleBounds($rule: JQuery<Element>): number[] { // Test single value const txtValue: string = $rule.attr("value"); if (txtValue) { const value = parseInt(txtValue, 10); return [value, value]; } // Test from / to value let fromValue = null; const txtFromValue: string = $rule.attr("from"); if (txtFromValue) { fromValue = parseInt(txtFromValue, 10); } // Test from / to value let toValue = null; const txtToValue: string = $rule.attr("to"); if (txtToValue) { toValue = parseInt(txtToValue, 10); } if (fromValue !== null || toValue !== null) { return [fromValue !== null ? fromValue : -99, toValue !== null ? toValue : 99]; } return null; }, /** * Evaluates a "case" rule. * @param rule The rule to evaluate * @return True if the case conditions are satisfied */ evaluateCaseRule(rule: Element, randomValue: number): boolean { const bounds = randomMechanics.getCaseRuleBounds($(rule)); if (!bounds) { return false; } return randomValue >= bounds[0] && randomValue <= bounds[1]; }, /** * Get the choosen value of a given random table on the section * @param {number} index The index of the random table on the section * @returns {number} The choosen value, with increments. -1 if it was not picked */ getRandomValueChoosed(index: number): number { const $link = randomMechanics.getRandomTableRefByIndex(index); if ($link.length === 0) { return -1; } const txtPicked = $link.attr("data-picked"); if (txtPicked === null || txtPicked === undefined) { return -1; } return parseInt(txtPicked, 10); } };
the_stack
import * as msRest from "@azure/ms-rest-js"; import * as msRestAzure from "@azure/ms-rest-azure-js"; import * as Models from "../models"; import * as Mappers from "../models/servicesMappers"; import * as Parameters from "../models/parameters"; import { DataMigrationServiceClientContext } from "../dataMigrationServiceClientContext"; /** Class representing a Services. */ export class Services { private readonly client: DataMigrationServiceClientContext; /** * Create a Services. * @param {DataMigrationServiceClientContext} client Reference to the service client. */ constructor(client: DataMigrationServiceClientContext) { this.client = client; } /** * The services resource is the top-level resource that represents the Database Migration Service. * The PUT method creates a new service or updates an existing one. When a service is updated, * existing child resources (i.e. tasks) are unaffected. Services currently support a single kind, * "vm", which refers to a VM-based service, although other kinds may be added in the future. This * method can change the kind, SKU, and network of the service, but if tasks are currently running * (i.e. the service is busy), this will fail with 400 Bad Request ("ServiceIsBusy"). The provider * will reply when successful with 200 OK or 201 Created. Long-running operations use the * provisioningState property. * @summary Create or update DMS Instance * @param parameters Information about the service * @param groupName Name of the resource group * @param serviceName Name of the service * @param [options] The optional parameters * @returns Promise<Models.ServicesCreateOrUpdateResponse> */ createOrUpdate(parameters: Models.DataMigrationService, groupName: string, serviceName: string, options?: msRest.RequestOptionsBase): Promise<Models.ServicesCreateOrUpdateResponse> { return this.beginCreateOrUpdate(parameters,groupName,serviceName,options) .then(lroPoller => lroPoller.pollUntilFinished()) as Promise<Models.ServicesCreateOrUpdateResponse>; } /** * The services resource is the top-level resource that represents the Database Migration Service. * The GET method retrieves information about a service instance. * @summary Get DMS Service Instance * @param groupName Name of the resource group * @param serviceName Name of the service * @param [options] The optional parameters * @returns Promise<Models.ServicesGetResponse> */ get(groupName: string, serviceName: string, options?: msRest.RequestOptionsBase): Promise<Models.ServicesGetResponse>; /** * @param groupName Name of the resource group * @param serviceName Name of the service * @param callback The callback */ get(groupName: string, serviceName: string, callback: msRest.ServiceCallback<Models.DataMigrationService>): void; /** * @param groupName Name of the resource group * @param serviceName Name of the service * @param options The optional parameters * @param callback The callback */ get(groupName: string, serviceName: string, options: msRest.RequestOptionsBase, callback: msRest.ServiceCallback<Models.DataMigrationService>): void; get(groupName: string, serviceName: string, options?: msRest.RequestOptionsBase | msRest.ServiceCallback<Models.DataMigrationService>, callback?: msRest.ServiceCallback<Models.DataMigrationService>): Promise<Models.ServicesGetResponse> { return this.client.sendOperationRequest( { groupName, serviceName, options }, getOperationSpec, callback) as Promise<Models.ServicesGetResponse>; } /** * The services resource is the top-level resource that represents the Database Migration Service. * The DELETE method deletes a service. Any running tasks will be canceled. * @summary Delete DMS Service Instance * @param groupName Name of the resource group * @param serviceName Name of the service * @param [options] The optional parameters * @returns Promise<msRest.RestResponse> */ deleteMethod(groupName: string, serviceName: string, options?: Models.ServicesDeleteMethodOptionalParams): Promise<msRest.RestResponse> { return this.beginDeleteMethod(groupName,serviceName,options) .then(lroPoller => lroPoller.pollUntilFinished()); } /** * The services resource is the top-level resource that represents the Database Migration Service. * The PATCH method updates an existing service. This method can change the kind, SKU, and network * of the service, but if tasks are currently running (i.e. the service is busy), this will fail * with 400 Bad Request ("ServiceIsBusy"). * @summary Create or update DMS Service Instance * @param parameters Information about the service * @param groupName Name of the resource group * @param serviceName Name of the service * @param [options] The optional parameters * @returns Promise<Models.ServicesUpdateResponse> */ update(parameters: Models.DataMigrationService, groupName: string, serviceName: string, options?: msRest.RequestOptionsBase): Promise<Models.ServicesUpdateResponse> { return this.beginUpdate(parameters,groupName,serviceName,options) .then(lroPoller => lroPoller.pollUntilFinished()) as Promise<Models.ServicesUpdateResponse>; } /** * The services resource is the top-level resource that represents the Database Migration Service. * This action performs a health check and returns the status of the service and virtual machine * size. * @summary Check service health status * @param groupName Name of the resource group * @param serviceName Name of the service * @param [options] The optional parameters * @returns Promise<Models.ServicesCheckStatusResponse> */ checkStatus(groupName: string, serviceName: string, options?: msRest.RequestOptionsBase): Promise<Models.ServicesCheckStatusResponse>; /** * @param groupName Name of the resource group * @param serviceName Name of the service * @param callback The callback */ checkStatus(groupName: string, serviceName: string, callback: msRest.ServiceCallback<Models.DataMigrationServiceStatusResponse>): void; /** * @param groupName Name of the resource group * @param serviceName Name of the service * @param options The optional parameters * @param callback The callback */ checkStatus(groupName: string, serviceName: string, options: msRest.RequestOptionsBase, callback: msRest.ServiceCallback<Models.DataMigrationServiceStatusResponse>): void; checkStatus(groupName: string, serviceName: string, options?: msRest.RequestOptionsBase | msRest.ServiceCallback<Models.DataMigrationServiceStatusResponse>, callback?: msRest.ServiceCallback<Models.DataMigrationServiceStatusResponse>): Promise<Models.ServicesCheckStatusResponse> { return this.client.sendOperationRequest( { groupName, serviceName, options }, checkStatusOperationSpec, callback) as Promise<Models.ServicesCheckStatusResponse>; } /** * The services resource is the top-level resource that represents the Database Migration Service. * This action starts the service and the service can be used for data migration. * @summary Start service * @param groupName Name of the resource group * @param serviceName Name of the service * @param [options] The optional parameters * @returns Promise<msRest.RestResponse> */ start(groupName: string, serviceName: string, options?: msRest.RequestOptionsBase): Promise<msRest.RestResponse> { return this.beginStart(groupName,serviceName,options) .then(lroPoller => lroPoller.pollUntilFinished()); } /** * The services resource is the top-level resource that represents the Database Migration Service. * This action stops the service and the service cannot be used for data migration. The service * owner won't be billed when the service is stopped. * @summary Stop service * @param groupName Name of the resource group * @param serviceName Name of the service * @param [options] The optional parameters * @returns Promise<msRest.RestResponse> */ stop(groupName: string, serviceName: string, options?: msRest.RequestOptionsBase): Promise<msRest.RestResponse> { return this.beginStop(groupName,serviceName,options) .then(lroPoller => lroPoller.pollUntilFinished()); } /** * The services resource is the top-level resource that represents the Database Migration Service. * The skus action returns the list of SKUs that a service resource can be updated to. * @summary Get compatible SKUs * @param groupName Name of the resource group * @param serviceName Name of the service * @param [options] The optional parameters * @returns Promise<Models.ServicesListSkusResponse> */ listSkus(groupName: string, serviceName: string, options?: msRest.RequestOptionsBase): Promise<Models.ServicesListSkusResponse>; /** * @param groupName Name of the resource group * @param serviceName Name of the service * @param callback The callback */ listSkus(groupName: string, serviceName: string, callback: msRest.ServiceCallback<Models.ServiceSkuList>): void; /** * @param groupName Name of the resource group * @param serviceName Name of the service * @param options The optional parameters * @param callback The callback */ listSkus(groupName: string, serviceName: string, options: msRest.RequestOptionsBase, callback: msRest.ServiceCallback<Models.ServiceSkuList>): void; listSkus(groupName: string, serviceName: string, options?: msRest.RequestOptionsBase | msRest.ServiceCallback<Models.ServiceSkuList>, callback?: msRest.ServiceCallback<Models.ServiceSkuList>): Promise<Models.ServicesListSkusResponse> { return this.client.sendOperationRequest( { groupName, serviceName, options }, listSkusOperationSpec, callback) as Promise<Models.ServicesListSkusResponse>; } /** * This method checks whether a proposed nested resource name is valid and available. * @summary Check nested resource name validity and availability * @param groupName Name of the resource group * @param serviceName Name of the service * @param parameters Requested name to validate * @param [options] The optional parameters * @returns Promise<Models.ServicesCheckChildrenNameAvailabilityResponse> */ checkChildrenNameAvailability(groupName: string, serviceName: string, parameters: Models.NameAvailabilityRequest, options?: msRest.RequestOptionsBase): Promise<Models.ServicesCheckChildrenNameAvailabilityResponse>; /** * @param groupName Name of the resource group * @param serviceName Name of the service * @param parameters Requested name to validate * @param callback The callback */ checkChildrenNameAvailability(groupName: string, serviceName: string, parameters: Models.NameAvailabilityRequest, callback: msRest.ServiceCallback<Models.NameAvailabilityResponse>): void; /** * @param groupName Name of the resource group * @param serviceName Name of the service * @param parameters Requested name to validate * @param options The optional parameters * @param callback The callback */ checkChildrenNameAvailability(groupName: string, serviceName: string, parameters: Models.NameAvailabilityRequest, options: msRest.RequestOptionsBase, callback: msRest.ServiceCallback<Models.NameAvailabilityResponse>): void; checkChildrenNameAvailability(groupName: string, serviceName: string, parameters: Models.NameAvailabilityRequest, options?: msRest.RequestOptionsBase | msRest.ServiceCallback<Models.NameAvailabilityResponse>, callback?: msRest.ServiceCallback<Models.NameAvailabilityResponse>): Promise<Models.ServicesCheckChildrenNameAvailabilityResponse> { return this.client.sendOperationRequest( { groupName, serviceName, parameters, options }, checkChildrenNameAvailabilityOperationSpec, callback) as Promise<Models.ServicesCheckChildrenNameAvailabilityResponse>; } /** * The Services resource is the top-level resource that represents the Database Migration Service. * This method returns a list of service resources in a resource group. * @summary Get services in resource group * @param groupName Name of the resource group * @param [options] The optional parameters * @returns Promise<Models.ServicesListByResourceGroupResponse> */ listByResourceGroup(groupName: string, options?: msRest.RequestOptionsBase): Promise<Models.ServicesListByResourceGroupResponse>; /** * @param groupName Name of the resource group * @param callback The callback */ listByResourceGroup(groupName: string, callback: msRest.ServiceCallback<Models.DataMigrationServiceList>): void; /** * @param groupName Name of the resource group * @param options The optional parameters * @param callback The callback */ listByResourceGroup(groupName: string, options: msRest.RequestOptionsBase, callback: msRest.ServiceCallback<Models.DataMigrationServiceList>): void; listByResourceGroup(groupName: string, options?: msRest.RequestOptionsBase | msRest.ServiceCallback<Models.DataMigrationServiceList>, callback?: msRest.ServiceCallback<Models.DataMigrationServiceList>): Promise<Models.ServicesListByResourceGroupResponse> { return this.client.sendOperationRequest( { groupName, options }, listByResourceGroupOperationSpec, callback) as Promise<Models.ServicesListByResourceGroupResponse>; } /** * The services resource is the top-level resource that represents the Database Migration Service. * This method returns a list of service resources in a subscription. * @summary Get services in subscription * @param [options] The optional parameters * @returns Promise<Models.ServicesListResponse> */ list(options?: msRest.RequestOptionsBase): Promise<Models.ServicesListResponse>; /** * @param callback The callback */ list(callback: msRest.ServiceCallback<Models.DataMigrationServiceList>): void; /** * @param options The optional parameters * @param callback The callback */ list(options: msRest.RequestOptionsBase, callback: msRest.ServiceCallback<Models.DataMigrationServiceList>): void; list(options?: msRest.RequestOptionsBase | msRest.ServiceCallback<Models.DataMigrationServiceList>, callback?: msRest.ServiceCallback<Models.DataMigrationServiceList>): Promise<Models.ServicesListResponse> { return this.client.sendOperationRequest( { options }, listOperationSpec, callback) as Promise<Models.ServicesListResponse>; } /** * This method checks whether a proposed top-level resource name is valid and available. * @summary Check name validity and availability * @param location The Azure region of the operation * @param parameters Requested name to validate * @param [options] The optional parameters * @returns Promise<Models.ServicesCheckNameAvailabilityResponse> */ checkNameAvailability(location: string, parameters: Models.NameAvailabilityRequest, options?: msRest.RequestOptionsBase): Promise<Models.ServicesCheckNameAvailabilityResponse>; /** * @param location The Azure region of the operation * @param parameters Requested name to validate * @param callback The callback */ checkNameAvailability(location: string, parameters: Models.NameAvailabilityRequest, callback: msRest.ServiceCallback<Models.NameAvailabilityResponse>): void; /** * @param location The Azure region of the operation * @param parameters Requested name to validate * @param options The optional parameters * @param callback The callback */ checkNameAvailability(location: string, parameters: Models.NameAvailabilityRequest, options: msRest.RequestOptionsBase, callback: msRest.ServiceCallback<Models.NameAvailabilityResponse>): void; checkNameAvailability(location: string, parameters: Models.NameAvailabilityRequest, options?: msRest.RequestOptionsBase | msRest.ServiceCallback<Models.NameAvailabilityResponse>, callback?: msRest.ServiceCallback<Models.NameAvailabilityResponse>): Promise<Models.ServicesCheckNameAvailabilityResponse> { return this.client.sendOperationRequest( { location, parameters, options }, checkNameAvailabilityOperationSpec, callback) as Promise<Models.ServicesCheckNameAvailabilityResponse>; } /** * The services resource is the top-level resource that represents the Database Migration Service. * The PUT method creates a new service or updates an existing one. When a service is updated, * existing child resources (i.e. tasks) are unaffected. Services currently support a single kind, * "vm", which refers to a VM-based service, although other kinds may be added in the future. This * method can change the kind, SKU, and network of the service, but if tasks are currently running * (i.e. the service is busy), this will fail with 400 Bad Request ("ServiceIsBusy"). The provider * will reply when successful with 200 OK or 201 Created. Long-running operations use the * provisioningState property. * @summary Create or update DMS Instance * @param parameters Information about the service * @param groupName Name of the resource group * @param serviceName Name of the service * @param [options] The optional parameters * @returns Promise<msRestAzure.LROPoller> */ beginCreateOrUpdate(parameters: Models.DataMigrationService, groupName: string, serviceName: string, options?: msRest.RequestOptionsBase): Promise<msRestAzure.LROPoller> { return this.client.sendLRORequest( { parameters, groupName, serviceName, options }, beginCreateOrUpdateOperationSpec, options); } /** * The services resource is the top-level resource that represents the Database Migration Service. * The DELETE method deletes a service. Any running tasks will be canceled. * @summary Delete DMS Service Instance * @param groupName Name of the resource group * @param serviceName Name of the service * @param [options] The optional parameters * @returns Promise<msRestAzure.LROPoller> */ beginDeleteMethod(groupName: string, serviceName: string, options?: Models.ServicesBeginDeleteMethodOptionalParams): Promise<msRestAzure.LROPoller> { return this.client.sendLRORequest( { groupName, serviceName, options }, beginDeleteMethodOperationSpec, options); } /** * The services resource is the top-level resource that represents the Database Migration Service. * The PATCH method updates an existing service. This method can change the kind, SKU, and network * of the service, but if tasks are currently running (i.e. the service is busy), this will fail * with 400 Bad Request ("ServiceIsBusy"). * @summary Create or update DMS Service Instance * @param parameters Information about the service * @param groupName Name of the resource group * @param serviceName Name of the service * @param [options] The optional parameters * @returns Promise<msRestAzure.LROPoller> */ beginUpdate(parameters: Models.DataMigrationService, groupName: string, serviceName: string, options?: msRest.RequestOptionsBase): Promise<msRestAzure.LROPoller> { return this.client.sendLRORequest( { parameters, groupName, serviceName, options }, beginUpdateOperationSpec, options); } /** * The services resource is the top-level resource that represents the Database Migration Service. * This action starts the service and the service can be used for data migration. * @summary Start service * @param groupName Name of the resource group * @param serviceName Name of the service * @param [options] The optional parameters * @returns Promise<msRestAzure.LROPoller> */ beginStart(groupName: string, serviceName: string, options?: msRest.RequestOptionsBase): Promise<msRestAzure.LROPoller> { return this.client.sendLRORequest( { groupName, serviceName, options }, beginStartOperationSpec, options); } /** * The services resource is the top-level resource that represents the Database Migration Service. * This action stops the service and the service cannot be used for data migration. The service * owner won't be billed when the service is stopped. * @summary Stop service * @param groupName Name of the resource group * @param serviceName Name of the service * @param [options] The optional parameters * @returns Promise<msRestAzure.LROPoller> */ beginStop(groupName: string, serviceName: string, options?: msRest.RequestOptionsBase): Promise<msRestAzure.LROPoller> { return this.client.sendLRORequest( { groupName, serviceName, options }, beginStopOperationSpec, options); } /** * The services resource is the top-level resource that represents the Database Migration Service. * The skus action returns the list of SKUs that a service resource can be updated to. * @summary Get compatible SKUs * @param nextPageLink The NextLink from the previous successful call to List operation. * @param [options] The optional parameters * @returns Promise<Models.ServicesListSkusNextResponse> */ listSkusNext(nextPageLink: string, options?: msRest.RequestOptionsBase): Promise<Models.ServicesListSkusNextResponse>; /** * @param nextPageLink The NextLink from the previous successful call to List operation. * @param callback The callback */ listSkusNext(nextPageLink: string, callback: msRest.ServiceCallback<Models.ServiceSkuList>): void; /** * @param nextPageLink The NextLink from the previous successful call to List operation. * @param options The optional parameters * @param callback The callback */ listSkusNext(nextPageLink: string, options: msRest.RequestOptionsBase, callback: msRest.ServiceCallback<Models.ServiceSkuList>): void; listSkusNext(nextPageLink: string, options?: msRest.RequestOptionsBase | msRest.ServiceCallback<Models.ServiceSkuList>, callback?: msRest.ServiceCallback<Models.ServiceSkuList>): Promise<Models.ServicesListSkusNextResponse> { return this.client.sendOperationRequest( { nextPageLink, options }, listSkusNextOperationSpec, callback) as Promise<Models.ServicesListSkusNextResponse>; } /** * The Services resource is the top-level resource that represents the Database Migration Service. * This method returns a list of service resources in a resource group. * @summary Get services in resource group * @param nextPageLink The NextLink from the previous successful call to List operation. * @param [options] The optional parameters * @returns Promise<Models.ServicesListByResourceGroupNextResponse> */ listByResourceGroupNext(nextPageLink: string, options?: msRest.RequestOptionsBase): Promise<Models.ServicesListByResourceGroupNextResponse>; /** * @param nextPageLink The NextLink from the previous successful call to List operation. * @param callback The callback */ listByResourceGroupNext(nextPageLink: string, callback: msRest.ServiceCallback<Models.DataMigrationServiceList>): void; /** * @param nextPageLink The NextLink from the previous successful call to List operation. * @param options The optional parameters * @param callback The callback */ listByResourceGroupNext(nextPageLink: string, options: msRest.RequestOptionsBase, callback: msRest.ServiceCallback<Models.DataMigrationServiceList>): void; listByResourceGroupNext(nextPageLink: string, options?: msRest.RequestOptionsBase | msRest.ServiceCallback<Models.DataMigrationServiceList>, callback?: msRest.ServiceCallback<Models.DataMigrationServiceList>): Promise<Models.ServicesListByResourceGroupNextResponse> { return this.client.sendOperationRequest( { nextPageLink, options }, listByResourceGroupNextOperationSpec, callback) as Promise<Models.ServicesListByResourceGroupNextResponse>; } /** * The services resource is the top-level resource that represents the Database Migration Service. * This method returns a list of service resources in a subscription. * @summary Get services in subscription * @param nextPageLink The NextLink from the previous successful call to List operation. * @param [options] The optional parameters * @returns Promise<Models.ServicesListNextResponse> */ listNext(nextPageLink: string, options?: msRest.RequestOptionsBase): Promise<Models.ServicesListNextResponse>; /** * @param nextPageLink The NextLink from the previous successful call to List operation. * @param callback The callback */ listNext(nextPageLink: string, callback: msRest.ServiceCallback<Models.DataMigrationServiceList>): void; /** * @param nextPageLink The NextLink from the previous successful call to List operation. * @param options The optional parameters * @param callback The callback */ listNext(nextPageLink: string, options: msRest.RequestOptionsBase, callback: msRest.ServiceCallback<Models.DataMigrationServiceList>): void; listNext(nextPageLink: string, options?: msRest.RequestOptionsBase | msRest.ServiceCallback<Models.DataMigrationServiceList>, callback?: msRest.ServiceCallback<Models.DataMigrationServiceList>): Promise<Models.ServicesListNextResponse> { return this.client.sendOperationRequest( { nextPageLink, options }, listNextOperationSpec, callback) as Promise<Models.ServicesListNextResponse>; } } // Operation Specifications const serializer = new msRest.Serializer(Mappers); const getOperationSpec: msRest.OperationSpec = { httpMethod: "GET", path: "subscriptions/{subscriptionId}/resourceGroups/{groupName}/providers/Microsoft.DataMigration/services/{serviceName}", urlParameters: [ Parameters.subscriptionId, Parameters.groupName, Parameters.serviceName ], queryParameters: [ Parameters.apiVersion ], headerParameters: [ Parameters.acceptLanguage ], responses: { 200: { bodyMapper: Mappers.DataMigrationService }, default: { bodyMapper: Mappers.ApiError } }, serializer }; const checkStatusOperationSpec: msRest.OperationSpec = { httpMethod: "POST", path: "subscriptions/{subscriptionId}/resourceGroups/{groupName}/providers/Microsoft.DataMigration/services/{serviceName}/checkStatus", urlParameters: [ Parameters.subscriptionId, Parameters.groupName, Parameters.serviceName ], queryParameters: [ Parameters.apiVersion ], headerParameters: [ Parameters.acceptLanguage ], responses: { 200: { bodyMapper: Mappers.DataMigrationServiceStatusResponse }, default: { bodyMapper: Mappers.ApiError } }, serializer }; const listSkusOperationSpec: msRest.OperationSpec = { httpMethod: "GET", path: "subscriptions/{subscriptionId}/resourceGroups/{groupName}/providers/Microsoft.DataMigration/services/{serviceName}/skus", urlParameters: [ Parameters.subscriptionId, Parameters.groupName, Parameters.serviceName ], queryParameters: [ Parameters.apiVersion ], headerParameters: [ Parameters.acceptLanguage ], responses: { 200: { bodyMapper: Mappers.ServiceSkuList }, default: { bodyMapper: Mappers.ApiError } }, serializer }; const checkChildrenNameAvailabilityOperationSpec: msRest.OperationSpec = { httpMethod: "POST", path: "subscriptions/{subscriptionId}/resourceGroups/{groupName}/providers/Microsoft.DataMigration/services/{serviceName}/checkNameAvailability", urlParameters: [ Parameters.subscriptionId, Parameters.groupName, Parameters.serviceName ], queryParameters: [ Parameters.apiVersion ], headerParameters: [ Parameters.acceptLanguage ], requestBody: { parameterPath: "parameters", mapper: { ...Mappers.NameAvailabilityRequest, required: true } }, responses: { 200: { bodyMapper: Mappers.NameAvailabilityResponse }, default: { bodyMapper: Mappers.ApiError } }, serializer }; const listByResourceGroupOperationSpec: msRest.OperationSpec = { httpMethod: "GET", path: "subscriptions/{subscriptionId}/resourceGroups/{groupName}/providers/Microsoft.DataMigration/services", urlParameters: [ Parameters.subscriptionId, Parameters.groupName ], queryParameters: [ Parameters.apiVersion ], headerParameters: [ Parameters.acceptLanguage ], responses: { 200: { bodyMapper: Mappers.DataMigrationServiceList }, default: { bodyMapper: Mappers.ApiError } }, serializer }; const listOperationSpec: msRest.OperationSpec = { httpMethod: "GET", path: "subscriptions/{subscriptionId}/providers/Microsoft.DataMigration/services", urlParameters: [ Parameters.subscriptionId ], queryParameters: [ Parameters.apiVersion ], headerParameters: [ Parameters.acceptLanguage ], responses: { 200: { bodyMapper: Mappers.DataMigrationServiceList }, default: { bodyMapper: Mappers.ApiError } }, serializer }; const checkNameAvailabilityOperationSpec: msRest.OperationSpec = { httpMethod: "POST", path: "subscriptions/{subscriptionId}/providers/Microsoft.DataMigration/locations/{location}/checkNameAvailability", urlParameters: [ Parameters.subscriptionId, Parameters.location ], queryParameters: [ Parameters.apiVersion ], headerParameters: [ Parameters.acceptLanguage ], requestBody: { parameterPath: "parameters", mapper: { ...Mappers.NameAvailabilityRequest, required: true } }, responses: { 200: { bodyMapper: Mappers.NameAvailabilityResponse }, default: { bodyMapper: Mappers.ApiError } }, serializer }; const beginCreateOrUpdateOperationSpec: msRest.OperationSpec = { httpMethod: "PUT", path: "subscriptions/{subscriptionId}/resourceGroups/{groupName}/providers/Microsoft.DataMigration/services/{serviceName}", urlParameters: [ Parameters.subscriptionId, Parameters.groupName, Parameters.serviceName ], queryParameters: [ Parameters.apiVersion ], headerParameters: [ Parameters.acceptLanguage ], requestBody: { parameterPath: "parameters", mapper: { ...Mappers.DataMigrationService, required: true } }, responses: { 200: { bodyMapper: Mappers.DataMigrationService }, 201: { bodyMapper: Mappers.DataMigrationService }, 202: {}, default: { bodyMapper: Mappers.ApiError } }, serializer }; const beginDeleteMethodOperationSpec: msRest.OperationSpec = { httpMethod: "DELETE", path: "subscriptions/{subscriptionId}/resourceGroups/{groupName}/providers/Microsoft.DataMigration/services/{serviceName}", urlParameters: [ Parameters.subscriptionId, Parameters.groupName, Parameters.serviceName ], queryParameters: [ Parameters.deleteRunningTasks, Parameters.apiVersion ], headerParameters: [ Parameters.acceptLanguage ], responses: { 200: {}, 202: {}, 204: {}, default: { bodyMapper: Mappers.ApiError } }, serializer }; const beginUpdateOperationSpec: msRest.OperationSpec = { httpMethod: "PATCH", path: "subscriptions/{subscriptionId}/resourceGroups/{groupName}/providers/Microsoft.DataMigration/services/{serviceName}", urlParameters: [ Parameters.subscriptionId, Parameters.groupName, Parameters.serviceName ], queryParameters: [ Parameters.apiVersion ], headerParameters: [ Parameters.acceptLanguage ], requestBody: { parameterPath: "parameters", mapper: { ...Mappers.DataMigrationService, required: true } }, responses: { 200: { bodyMapper: Mappers.DataMigrationService }, 202: {}, default: { bodyMapper: Mappers.ApiError } }, serializer }; const beginStartOperationSpec: msRest.OperationSpec = { httpMethod: "POST", path: "subscriptions/{subscriptionId}/resourceGroups/{groupName}/providers/Microsoft.DataMigration/services/{serviceName}/start", urlParameters: [ Parameters.subscriptionId, Parameters.groupName, Parameters.serviceName ], queryParameters: [ Parameters.apiVersion ], headerParameters: [ Parameters.acceptLanguage ], responses: { 200: {}, 202: {}, default: { bodyMapper: Mappers.ApiError } }, serializer }; const beginStopOperationSpec: msRest.OperationSpec = { httpMethod: "POST", path: "subscriptions/{subscriptionId}/resourceGroups/{groupName}/providers/Microsoft.DataMigration/services/{serviceName}/stop", urlParameters: [ Parameters.subscriptionId, Parameters.groupName, Parameters.serviceName ], queryParameters: [ Parameters.apiVersion ], headerParameters: [ Parameters.acceptLanguage ], responses: { 200: {}, 202: {}, default: { bodyMapper: Mappers.ApiError } }, serializer }; const listSkusNextOperationSpec: msRest.OperationSpec = { httpMethod: "GET", baseUrl: "https://management.azure.com", path: "{nextLink}", urlParameters: [ Parameters.nextPageLink ], headerParameters: [ Parameters.acceptLanguage ], responses: { 200: { bodyMapper: Mappers.ServiceSkuList }, default: { bodyMapper: Mappers.ApiError } }, serializer }; const listByResourceGroupNextOperationSpec: msRest.OperationSpec = { httpMethod: "GET", baseUrl: "https://management.azure.com", path: "{nextLink}", urlParameters: [ Parameters.nextPageLink ], headerParameters: [ Parameters.acceptLanguage ], responses: { 200: { bodyMapper: Mappers.DataMigrationServiceList }, default: { bodyMapper: Mappers.ApiError } }, serializer }; const listNextOperationSpec: msRest.OperationSpec = { httpMethod: "GET", baseUrl: "https://management.azure.com", path: "{nextLink}", urlParameters: [ Parameters.nextPageLink ], headerParameters: [ Parameters.acceptLanguage ], responses: { 200: { bodyMapper: Mappers.DataMigrationServiceList }, default: { bodyMapper: Mappers.ApiError } }, serializer };
the_stack
import { h, Component } from 'preact'; import { Side } from '@t/store/focus'; import { createDraggableRowInfo, DraggableRowInfo, getMovedPosAndIndexOfRow, MovedIndexAndPosInfoOfRow, PosInfo, getResolvedOffsets, FloatingRowSize, } from '../query/draggable'; import { RowKey } from '@t/store/data'; import { PagePosition, DragStartData } from '@t/store/selection'; import { BodyRows } from './bodyRows'; import { ColGroup } from './colGroup'; import { cls, getCoordinateWithOffset, setCursorStyle, hasClass, isDatePickerElement, findParentByClassName, getCellAddress, } from '../helper/dom'; import { DispatchProps } from '../dispatch/create'; import { connect } from './hoc'; import { FocusLayer } from './focusLayer'; import { SelectionLayer } from './selectionLayer'; import { some, debounce, isNil } from '../helper/common'; import { EditingLayer } from './editingLayer'; import GridEvent from '../event/gridEvent'; import { getEventBus, EventBus } from '../event/eventBus'; import { RIGHT_MOUSE_BUTTON } from '../helper/constant'; import { isFocusedCell } from '../query/focus'; interface OwnProps { side: Side; } interface StoreProps { bodyHeight: number; totalRowHeight: number; totalColumnWidth: number; scrollTop: number; scrollLeft: number; scrollXHeight: number; offsetTop: number; offsetLeft: number; dummyRowCount: number; scrollX: boolean; scrollY: boolean; cellBorderWidth: number; eventBus: EventBus; hasTreeColumn: boolean; visibleTotalWidth: number; } type Props = OwnProps & StoreProps & DispatchProps; type Overflow = 'hidden' | 'scroll' | 'auto'; interface AreaStyle { height: number; overflowX?: Overflow; overflowY?: Overflow; } interface MovedIndexInfo { index: number; rowKey: RowKey | null; moveToLast?: boolean; appended?: boolean; } // only updates when these props are changed // for preventing unnecessary rendering when scroll changes const PROPS_FOR_UPDATE: (keyof StoreProps)[] = [ 'bodyHeight', 'totalRowHeight', 'offsetLeft', 'offsetTop', 'totalColumnWidth', 'visibleTotalWidth', ]; // Minimum distance (pixel) to detect if user wants to drag when moving mouse with button pressed. const MIN_DISTANCE_FOR_DRAG = 10; const ADDITIONAL_RANGE = 3; const DRAGGING_CLASS = 'dragging'; const PARENT_CELL_CLASS = 'parent-cell'; const DRAGGABLE_COLUMN_NAME = '_draggable'; class BodyAreaComp extends Component<Props> { private el!: HTMLElement; private boundingRect?: { top: number; left: number }; private dragStartData: DragStartData = { pageX: null, pageY: null, }; private prevScrollLeft = 0; // draggable info when start to move the row private draggableInfo: DraggableRowInfo | null = null; // floating row width and height for dragging private floatingRowSize: FloatingRowSize | null = null; // the index info to move row through drag private movedIndexInfo: MovedIndexInfo | null = null; private scrollToNextDebounced = debounce(() => { this.props.dispatch('scrollToNext'); }, 200); private handleScroll = (ev: UIEvent) => { const { scrollLeft, scrollTop, scrollHeight, clientHeight } = ev.target as HTMLElement; const { dispatch, eventBus, side } = this.props; dispatch('setScrollTop', scrollTop); if (side === 'R') { dispatch('setScrollLeft', scrollLeft); if ( scrollTop > 0 && scrollHeight - scrollTop === clientHeight && this.prevScrollLeft === scrollLeft ) { const gridEvent = new GridEvent(); /** * Occurs when scroll at the bottommost * @event Grid#scrollEnd * @property {Grid} instance - Current grid instance */ eventBus.trigger('scrollEnd', gridEvent); this.scrollToNextDebounced(); } this.prevScrollLeft = scrollLeft; } }; private dragRow = (ev: MouseEvent) => { const [pageX, pageY] = getCoordinateWithOffset(ev.pageX, ev.pageY); if (this.moveEnoughToTriggerDragEvent({ pageX, pageY })) { const { el, boundingRect, props } = this; const { scrollTop, scrollLeft } = el!; const movedPosAndIndex = getMovedPosAndIndexOfRow(this.context.store, { scrollLeft, scrollTop, left: boundingRect!.left, top: boundingRect!.top, pageX, pageY, }); const { index, targetRow } = movedPosAndIndex; const rowKeyToMove = targetRow.rowKey; const { row, rowKey } = this.draggableInfo!; const { offsetLeft, offsetTop } = getResolvedOffsets( this.context.store, movedPosAndIndex, this.floatingRowSize! ); row.style.left = `${offsetLeft}px`; row.style.top = `${offsetTop}px`; if (props.hasTreeColumn) { this.setTreeMovedIndexInfo(movedPosAndIndex); } else { // move the row to next index this.movedIndexInfo = { index, rowKey: rowKeyToMove, appended: false }; this.props.dispatch('moveRow', rowKey, index); } const gridEvent = new GridEvent({ rowKey, targetRowKey: this.movedIndexInfo!.rowKey, appended: this.movedIndexInfo!.appended, }); /** * Occurs when dragging the row * @event Grid#drag * @property {Grid} instance - Current grid instance * @property {RowKey} rowKey - The rowKey of the dragging row * @property {RowKey} targetRowKey - The rowKey of the row at current dragging position * @property {boolean} appended - Whether the row is appended to other row as the child in tree data. */ this.props.eventBus.trigger('drag', gridEvent); } }; private setTreeMovedIndexInfo(movedPosAndIndex: MovedIndexAndPosInfoOfRow) { const { line } = this.draggableInfo!; const { index, offsetTop, height, targetRow, moveToLast } = movedPosAndIndex; const { rowKey } = targetRow; if (!isNil(this.movedIndexInfo?.rowKey)) { this.props.dispatch('removeRowClassName', this.movedIndexInfo!.rowKey, PARENT_CELL_CLASS); } const targetRowKey = moveToLast ? null : rowKey; // display line border to mark the index to move if (Math.abs(height - offsetTop) < ADDITIONAL_RANGE || moveToLast) { line.style.top = `${height}px`; line.style.display = 'block'; this.movedIndexInfo = { index, rowKey: targetRowKey, moveToLast, appended: false }; // show the background color to mark parent row } else { line.style.display = 'none'; this.movedIndexInfo = { index, rowKey: targetRowKey, appended: true }; this.props.dispatch('addRowClassName', rowKey, PARENT_CELL_CLASS); } } private startToDragRow = (posInfo: PosInfo) => { const container = this.el.parentElement!.parentElement!; posInfo.container = container; this.props.dispatch('resetRowSpan'); const draggableInfo = createDraggableRowInfo(this.context.store, posInfo); if (draggableInfo) { const { row, rowKey, line } = draggableInfo; const gridEvent = new GridEvent({ rowKey, floatingRow: row }); /** * Occurs when starting to drag the row * @event Grid#dragStart * @property {Grid} instance - Current grid instance * @property {RowKey} rowKey - The rowKey of the row to drag * @property {HTMLElement} floatingRow - The floating row DOM element */ this.props.eventBus.trigger('dragStart', gridEvent); if (!gridEvent.isStopped()) { container.appendChild(row); const { clientWidth, clientHeight } = row; this.floatingRowSize = { width: clientWidth, height: clientHeight }; this.draggableInfo = draggableInfo; if (this.props.hasTreeColumn) { container!.appendChild(line); } this.props.dispatch('addRowClassName', rowKey, DRAGGING_CLASS); this.props.dispatch('setFocusInfo', null, null, false); this.props.dispatch('initSelection'); document.addEventListener('mousemove', this.dragRow); document.addEventListener('mouseup', this.dropRow); document.addEventListener('selectstart', this.handleSelectStart); } } }; private isSelectedCell(element: HTMLElement) { const cellAddress = getCellAddress(element); if (cellAddress) { const { rowKey, columnName } = cellAddress; return isFocusedCell(this.context.store.focus, rowKey, columnName); } return !!findParentByClassName(element, 'layer-selection'); } private handleMouseDown = (ev: MouseEvent) => { const targetElement = ev.target as HTMLElement; if ( !this.el || targetElement === this.el || (ev.button === RIGHT_MOUSE_BUTTON && this.isSelectedCell(targetElement)) ) { return; } const { side, dispatch } = this.props; if (hasClass(targetElement, 'cell-dummy')) { dispatch('saveAndFinishEditing'); dispatch('initFocus'); dispatch('initSelection'); return; } const { el } = this; const { shiftKey } = ev; const [pageX, pageY] = getCoordinateWithOffset(ev.pageX, ev.pageY); const { scrollTop, scrollLeft } = el; const { top, left } = el.getBoundingClientRect(); this.boundingRect = { top, left }; if (getCellAddress(targetElement)?.columnName === DRAGGABLE_COLUMN_NAME) { this.startToDragRow({ pageX, pageY, left, top, scrollLeft, scrollTop }); return; } if ( !isDatePickerElement(targetElement) && !findParentByClassName(targetElement, 'layer-editing') ) { dispatch( 'mouseDownBody', { scrollTop, scrollLeft, side, ...this.boundingRect }, { pageX, pageY, shiftKey } ); } this.dragStartData = { pageX, pageY }; setCursorStyle('default'); document.addEventListener('mousemove', this.handleMouseMove); document.addEventListener('mouseup', this.clearDocumentEvents); document.addEventListener('selectstart', this.handleSelectStart); }; private moveEnoughToTriggerDragEvent = (current: PagePosition) => { const dx = Math.abs(this.dragStartData.pageX! - current.pageX!); const dy = Math.abs(this.dragStartData.pageY! - current.pageY!); const movedDistance = Math.round(Math.sqrt(Math.pow(dx, 2) + Math.pow(dy, 2))); return movedDistance >= MIN_DISTANCE_FOR_DRAG; }; private handleSelectStart = (ev: Event) => { ev.preventDefault(); }; private handleMouseMove = (ev: MouseEvent) => { const [pageX, pageY] = getCoordinateWithOffset(ev.pageX, ev.pageY); if (this.moveEnoughToTriggerDragEvent({ pageX, pageY })) { const { el, boundingRect, props } = this; const { scrollTop, scrollLeft } = el!; const { side, dispatch } = props; dispatch( 'dragMoveBody', this.dragStartData as PagePosition, { pageX, pageY }, { scrollTop, scrollLeft, side, ...boundingRect! } ); } }; private dropRow = () => { const { hasTreeColumn } = this.props; const { rowKey } = this.draggableInfo!; if (this.movedIndexInfo) { const { index, rowKey: targetRowKey, appended, moveToLast = false } = this.movedIndexInfo; const gridEvent = new GridEvent({ rowKey, targetRowKey, appended }); /** * Occurs when dropping the row * @event Grid#drop * @property {Grid} instance - Current grid instance * @property {RowKey} rowKey - The rowKey of the dragging row * @property {RowKey} targetRowKey - The rowKey of the row at current dragging position * @property {boolean} appended - Whether the row is appended to other row as the child in tree data. */ this.props.eventBus.trigger('drop', gridEvent); if (!gridEvent.isStopped()) { if (hasTreeColumn) { this.props.dispatch('moveTreeRow', rowKey, index, { appended, moveToLast }); } else { this.props.dispatch('moveRow', rowKey, index); } } } this.props.dispatch('removeRowClassName', rowKey, DRAGGING_CLASS); if (!isNil(this.movedIndexInfo?.rowKey)) { this.props.dispatch('removeRowClassName', this.movedIndexInfo!.rowKey, PARENT_CELL_CLASS); } // clear floating element and draggable info this.clearDraggableInfo(); this.props.dispatch('updateRowSpan'); }; private clearDraggableInfo() { const { row, line } = this.draggableInfo!; row.parentElement!.removeChild(row); if (this.props.hasTreeColumn) { line.parentElement!.removeChild(line); } this.draggableInfo = null; this.movedIndexInfo = null; document.removeEventListener('mousemove', this.dragRow); document.removeEventListener('mouseup', this.dropRow); document.removeEventListener('selectstart', this.handleSelectStart); } private clearDocumentEvents = () => { this.dragStartData = { pageX: null, pageY: null }; this.props.dispatch('dragEnd'); setCursorStyle(''); document.removeEventListener('mousemove', this.handleMouseMove); document.removeEventListener('mouseup', this.clearDocumentEvents); document.removeEventListener('selectstart', this.handleSelectStart); }; shouldComponentUpdate(nextProps: Props) { const currProps = this.props; return some((propName) => nextProps[propName] !== currProps[propName], PROPS_FOR_UPDATE); } componentWillReceiveProps(nextProps: Props) { const { scrollTop, scrollLeft } = nextProps; this.el.scrollTop = scrollTop; this.el.scrollLeft = scrollLeft; } public render({ side, bodyHeight, totalRowHeight, totalColumnWidth, scrollXHeight, offsetTop, offsetLeft, dummyRowCount, scrollX, scrollY, cellBorderWidth, visibleTotalWidth, }: Props) { const areaStyle: AreaStyle = { height: bodyHeight }; if (!scrollX) { areaStyle.overflowX = 'hidden'; } if (!scrollY && side === 'R') { areaStyle.overflowY = 'hidden'; } const tableContainerStyle = { width: visibleTotalWidth, top: offsetTop, left: offsetLeft, height: dummyRowCount ? bodyHeight - scrollXHeight : '', overflow: dummyRowCount ? 'hidden' : 'visible', }; const containerStyle = { width: totalColumnWidth + (side === 'R' ? 0 : cellBorderWidth), height: totalRowHeight ? totalRowHeight + cellBorderWidth : '100%', }; return ( <div class={cls('body-area')} style={areaStyle} onScroll={this.handleScroll} onMouseDown={this.handleMouseDown} ref={(el) => { this.el = el; }} > <div class={cls('body-container')} style={containerStyle}> <div class={cls('table-container')} style={tableContainerStyle}> <table class={cls('table')}> <ColGroup side={side} useViewport={true} /> <BodyRows side={side} /> </table> </div> <FocusLayer side={side} /> <SelectionLayer side={side} /> <EditingLayer side={side} /> </div> </div> ); } } export const BodyArea = connect<StoreProps, OwnProps>((store, { side }) => { const { columnCoords, rowCoords, dimension, viewport, id, column } = store; const { totalRowHeight } = rowCoords; const { totalColumnWidth, widths } = columnCoords; const { bodyHeight, scrollXHeight, scrollX, scrollY, cellBorderWidth } = dimension; const { offsetLeft, offsetTop, scrollTop, scrollLeft, dummyRowCount, colRange, columns, } = viewport; const visibleWidths = side === 'R' ? widths[side].slice(...colRange) : widths[side]; const visibleColumns = side === 'R' ? columns : column.visibleColumnsBySideWithRowHeader[side]; const visibleTotalWidth = visibleColumns.reduce( (acc, _, idx) => acc + visibleWidths[idx] + cellBorderWidth, 0 ); return { bodyHeight, totalRowHeight, offsetTop, scrollTop, totalColumnWidth: totalColumnWidth[side], offsetLeft: side === 'L' ? 0 : offsetLeft, scrollLeft: side === 'L' ? 0 : scrollLeft, scrollXHeight, dummyRowCount, scrollX, scrollY, cellBorderWidth, eventBus: getEventBus(id), hasTreeColumn: !!column.treeColumnName, visibleTotalWidth, }; })(BodyAreaComp);
the_stack
import type { Fn3, FnN2 } from "@thi.ng/api"; import { clamp, clamp01 } from "@thi.ng/math/interval"; import type { Color, ReadonlyColor } from "./api.js"; import { postmultiply, postmultiplyInt, premultiply, premultiplyInt, } from "./premultiply.js"; import { setC4, setN4 } from "./utils.js"; const min = Math.min; export const ZERO: FnN2 = () => 0; export const ONE: FnN2 = () => 1; export const A: FnN2 = (a) => a; export const B: FnN2 = (_, b) => b; export const ONE_MINUS_A: FnN2 = (a) => 1 - a; export const ONE_MINUS_B: FnN2 = (_, b) => 1 - b; /** * General Porter-Duff HOF operator for **pre-multiplied** RGBA. Use * {@link porterDuffP} for applying pre & post multiplication of input * and output colors. The returned function takes 3 arguments: * * - `out` color (if `null` or `undefined` writes to `dest`) * - `src` color (background) * - `dest` color (foreground) * * Unlike the packed int version, here only the alpha channel of the * result color will be clamped. RGB components can potentially go out * of [0..1] range (depending on coefficient functions used). * * Reference: * {@link https://keithp.com/~keithp/porterduff/p253-porter.pdf} * * @param fa - fn for src coeff * @param fb - fn for dest coeff */ export const porterDuff = (fa: FnN2, fb: FnN2) => (out: Color | null, src: ReadonlyColor, dest: ReadonlyColor) => { const sa = src[3]; const sb = dest[3]; const aa = fa(sa, sb); const bb = fb(sa, sb); return setC4( out || dest, src[0] * aa + dest[0] * bb, src[1] * aa + dest[1] * bb, src[2] * aa + dest[2] * bb, clamp01(src[3] * aa + dest[3] * bb) ); }; export const porterDuffInt = (fa: FnN2, fb: FnN2): FnN2 => (a, b) => { const sa = (a >>> 24) / 255; const sb = (b >>> 24) / 255; const aa = fa(sa, sb); const bb = fb(sa, sb); return ( (clamp( ((a >>> 24) & 0xff) * aa + ((b >>> 24) & 0xff) * bb, 0, 255 ) << 24) | (clamp( ((a >>> 16) & 0xff) * aa + ((b >>> 16) & 0xff) * bb, 0, 255 ) << 16) | (clamp(((a >>> 8) & 0xff) * aa + ((b >>> 8) & 0xff) * bb, 0, 255) << 8) | clamp((a & 0xff) * aa + (b & 0xff) * bb, 0, 255) ); }; /** * Higher order function. Takes existing PD operator and returns * function which accepts same args as the operator, but pre-multiplies * alpha for both input colors and then returns post-multiplied alpha * output. * * @param mode - */ export const porterDuffP = (mode: Fn3<Color | null, ReadonlyColor, ReadonlyColor, Color>) => (out: Color, src: ReadonlyColor, dest: ReadonlyColor) => postmultiply( null, mode(null, premultiply([], src), premultiply(out, dest)) ); /** * Like {@link porterDuffP}, but for packed integers. * * @param mode - */ export const porterDuffPInt = (mode: FnN2): FnN2 => (src, dest) => postmultiplyInt(mode(premultiplyInt(src), premultiplyInt(dest))); /** * Porter-Duff operator. None of the terms are used. Always results in * [0, 0, 0, 0]. * * {@link porterDuff} * * @param out - * @param src - * @param dest - */ export const CLEAR_F = (out: Color, _: ReadonlyColor, dest: ReadonlyColor) => setN4(out || dest, 0); /** * Porter-Duff operator. Always results in `src` color, `dest` ignored. * * {@link porterDuff} */ export const SRC_F = porterDuff(ONE, ZERO); /** * Porter-Duff operator. Always results in `dest` color, `src` ignored. * * {@link porterDuff} */ export const DEST_F = porterDuff(ZERO, ONE); /** * Porter-Duff operator. The source color is placed over the destination * color. * * {@link porterDuff} */ export const SRC_OVER_F = porterDuff(ONE, ONE_MINUS_A); /** * Porter-Duff operator. The destination color is placed over the source * color. * * {@link porterDuff} */ export const DEST_OVER_F = porterDuff(ONE_MINUS_B, ONE); /** * Porter-Duff operator. The source that overlaps the destination, * replaces the destination. * * {@link porterDuff} */ export const SRC_IN_F = porterDuff(B, ZERO); /** * Porter-Duff operator. The destination that overlaps the source, * replaces the source. * * {@link porterDuff} */ export const DEST_IN_F = porterDuff(ZERO, A); /** * Porter-Duff operator. The source that does not overlap the * destination replaces the destination. * * {@link porterDuff} */ export const SRC_OUT_F = porterDuff(ONE_MINUS_B, ZERO); /** * Porter-Duff operator. The destination that does not overlap the * source replaces the source. * * {@link porterDuff} */ export const DEST_OUT_F = porterDuff(ZERO, ONE_MINUS_A); /** * Porter-Duff operator. The source that overlaps the destination is * composited with the destination. * * {@link porterDuff} */ export const SRC_ATOP_F = porterDuff(B, ONE_MINUS_A); /** * Porter-Duff operator. The destination that overlaps the source is * composited with the source and replaces the destination. * * {@link porterDuff} */ export const DEST_ATOP_F = porterDuff(ONE_MINUS_B, A); /** * Porter-Duff operator. The non-overlapping regions of source and * destination are combined. * * {@link porterDuff} */ export const XOR_F = porterDuff(ONE_MINUS_B, ONE_MINUS_A); /** * Porter-Duff operator. Source & destination regions are added. */ export const PLUS_F = porterDuff(ONE, ONE); ////////// Packed ARGB / ABGR versions ////////// export const CLEAR_I = ZERO; /** * Porter-Duff operator for packed ints. Always results in `src` color, `dest` ignored. * * {@link porterDuff} */ export const SRC_I = porterDuffInt(ONE, ZERO); /** * Porter-Duff operator for packed ints. Always results in `dest` color, `src` ignored. * * {@link porterDuff} */ export const DEST_I = porterDuffInt(ZERO, ONE); /** * Porter-Duff operator for packed ints. The source color is placed over the destination * color. * * {@link porterDuff} */ export const SRC_OVER_I = porterDuffInt(ONE, ONE_MINUS_A); /** * Porter-Duff operator for packed ints. The destination color is placed over the source * color. * * {@link porterDuff} */ export const DEST_OVER_I = porterDuffInt(ONE_MINUS_B, ONE); /** * Porter-Duff operator for packed ints. The source that overlaps the destination, * replaces the destination. * * {@link porterDuff} */ export const SRC_IN_I = porterDuffInt(B, ZERO); /** * Porter-Duff operator for packed ints. The destination that overlaps the source, * replaces the source. * * {@link porterDuff} */ export const DEST_IN_I = porterDuffInt(ZERO, A); /** * Porter-Duff operator for packed ints. The source that does not overlap the * destination replaces the destination. * * {@link porterDuff} */ export const SRC_OUT_I = porterDuffInt(ONE_MINUS_B, ZERO); /** * Porter-Duff operator for packed ints. The destination that does not overlap the * source replaces the source. * * {@link porterDuff} */ export const DEST_OUT_I = porterDuffInt(ZERO, ONE_MINUS_A); /** * Porter-Duff operator for packed ints. The source that overlaps the destination is * composited with the destination. * * {@link porterDuff} */ export const SRC_ATOP_I = porterDuffInt(B, ONE_MINUS_A); /** * Porter-Duff operator for packed ints. The destination that overlaps the source is * composited with the source and replaces the destination. * * {@link porterDuff} */ export const DEST_ATOP_I = porterDuffInt(ONE_MINUS_B, A); /** * Porter-Duff operator for packed ints. The non-overlapping regions of source and * destination are combined. * * {@link porterDuff} */ export const XOR_I = porterDuffInt(ONE_MINUS_B, ONE_MINUS_A); /** * Porter-Duff operator for packed ints. Source & destination regions * are added. */ export const PLUS_I = porterDuffInt(ONE, ONE); /** * Porter-Duff darken modifier. Multiplies RGB components of `src` with * `t`. Alpha remains unchanged. Writes results to `out`, or if `null` * modifies `src` in-place. * * @param out - * @param src - * @param t - */ export const darken = (out: Color | null, src: ReadonlyColor, t: number) => setC4(out || src, src[0] * t, src[1] * t, src[2] * t, src[3]); /** * Porter-Duff dissolve modifier. Multiplies all components of `src` * with `t`. Clamps alpha to [0..1] range, RGB unclamped. Writes results * to `out`, or if `null` modifies `src` in-place. * * @param out - * @param src - * @param t - */ export const dissolve = (out: Color | null, src: ReadonlyColor, t: number) => setC4(out || src, src[0] * t, src[1] * t, src[2] * t, min(1, src[3] * t)); /** * Porter-Duff opacity modifier. Multiplies alpha component of `src` * with `t`, clamped to [0..1] range. Writes results to `out`, or if * `null` modifies `src` in-place. * * @param out - * @param src - * @param t - */ export const opacity = (out: Color | null, src: ReadonlyColor, t: number) => setC4(out || src, src[0], src[1], src[2], min(1, src[3] * t)); /** * Porter-Duff darken modifier for packed ints. Multiplies RGB * components of `src` with `t` ([0..1] range). * * @param src - * @param t - */ export const darkenInt: FnN2 = (src, t) => (src & 0xff000000) | (min(0xff, ((src >>> 16) & 0xff) * t) << 16) | (min(0xff, ((src >>> 8) & 0xff) * t) << 8) | min(0xff, (src & 0xff) * t); /** * Porter-Duff dissolve modifier for packed ints. Multiplies all * components of `src` with `t` ([0..1] range). * * @param src - * @param t - */ export const dissolveInt: FnN2 = (src, t) => (min(0xff, ((src >>> 24) & 0xff) * t) << 24) | (min(0xff, ((src >>> 16) & 0xff) * t) << 16) | (min(0xff, ((src >>> 8) & 0xff) * t) << 8) | min(0xff, (src & 0xff) * t); /** * Porter-Duff opacity modifier for packed ints. Multiplies alpha * component of `src` with `t` ([0..1] range). * * @param src - * @param t - */ export const opacityInt: FnN2 = (src, t) => (min(0xff, ((src >>> 24) & 0xff) * t) << 24) | (src & 0xffffff);
the_stack
import { connect } from '@tarojs/redux'; import Taro from '@tarojs/taro'; import { View, Text } from '@tarojs/components'; import { AtDivider, AtAvatar, AtMessage, AtLoadMore, AtNavBar } from 'taro-ui'; import dayjs from 'dayjs'; import { IThread, IReply } from '../../interfaces/thread'; import { IThreadRespond } from '../../interfaces/respond'; import { IAccount } from '../../interfaces/account'; import ParserRichText from '../../components/ParserRichText/parserRichText'; import ReplyCard from '../../components/ReplyCard/replyCard'; import contentCleaner from '../../utils/cleaner'; import './thread.scss'; interface Props { auth: boolean; account: IAccount; statusBarHeight: number; } interface State { pageNum: number; loadedPosition: number; thread: IThread; loadMoreVisibility: boolean; loadMoreStatus: 'more' | 'loading' | 'noMore'; } @connect(({ account, system }) => ({ auth: account.auth, account: account.account, statusBarHeight: system.statusBarHeight })) class Thread extends Taro.Component<Props, State> { public config: Taro.Config = { navigationBarTitleText: '主题', onReachBottomDistance: 300 }; public state = { pageNum: 1, loadedPosition: 0, loadMoreVisibility: false, loadMoreStatus: 'loading' as 'more' | 'loading' | 'noMore', thread: { title: '', tid: 0, timestamp: 0, viewed: 0, replied: 0, content: '', maxPosition: 0, author: { username: '', uid: 0, avatar: '' }, replies: [ { user: { username: '', uid: 0, avatar: '' }, content: '', timestamp: 0, position: 0 } ] } }; public componentDidMount(): void { const { pageNum } = this.state; Taro.showLoading({ title: '努力加载中 💦' }); this.fetchThread(parseInt(this.$router.params.tid), pageNum); } public onShareAppMessage(): { title: string; path: string; } { const { thread } = this.state; return { title: `${thread.title} - SteamCN 蒸汽动力`, path: `/pages/thread/thread?tid=${this.$router.params.tid}` }; } public onReachBottom(): void { const { loadedPosition, thread } = this.state; const currentPageNum = this.state.pageNum; if (loadedPosition < thread.maxPosition) { this.setState( { pageNum: currentPageNum + 1, loadMoreVisibility: true, loadMoreStatus: 'loading' }, (): void => { const { pageNum } = this.state; this.fetchThread(parseInt(this.$router.params.tid), pageNum); } ); } else { this.setState({ loadMoreVisibility: true, loadMoreStatus: 'noMore' }); } } private fetchThread(tid: number, pageNum: number): void { const { account } = this.props; Taro.request({ url: `https://vnext.steamcn.com/v1/forum/thread/${tid}?page=${pageNum}`, data: {}, header: { authorization: account.accessToken }, method: 'GET', dataType: 'json', responseType: 'text' }).then( (res): void => { if (res.statusCode === 200) { const threadData = res.data as IThreadRespond; const currentPageNum = this.state.pageNum; if (currentPageNum === 1) { const { loadedPosition } = this.state; const floors = threadData.floors; const title = threadData.thread.subject; const tid = parseInt(threadData.thread.tid); const timestamp = parseInt(threadData.thread.dateline); const viewed = threadData.thread.views; const replied = threadData.thread.replies; const content = contentCleaner(threadData.floors[0].message); const maxPosition = parseInt(threadData.thread.maxposition); const username = threadData.thread.author; const uid = parseInt(threadData.thread.authorid); const avatar = `https://steamcn.com/uc_server/avatar.php?uid=${uid}&size=middle`; // console.log(content) // 打印主贴 HTML 代码 let replies = Array<IReply>(); for (let i = 1; i < floors.length; i++) { const floor = floors[i]; const username = floor.author; const uid = parseInt(floor.authorid); const avatar = `https://steamcn.com/uc_server/avatar.php?uid=${uid}&size=middle`; const content = contentCleaner(floor.message); const timestamp = parseInt(floor.dbdateline); const position = parseInt(floor.position); replies.push({ user: { username, uid, avatar }, content, timestamp, position }); } this.setState({ loadedPosition: loadedPosition + floors.length, thread: { title, tid, timestamp, viewed, replied, content, maxPosition, author: { username, uid, avatar }, replies } }); Taro.hideLoading(); } else { const { loadedPosition, thread } = this.state; const floors = threadData.floors; let replies = Array<IReply>(); for (let i = 0; i < floors.length; i++) { const floor = floors[i]; const username = floor.author; const uid = parseInt(floor.authorid); const avatar = `https://steamcn.com/uc_server/avatar.php?uid=${uid}&size=middle`; const content = contentCleaner(floor.message); const timestamp = parseInt(floor.dbdateline); const position = parseInt(floor.position); replies.push({ user: { username, uid, avatar }, content, timestamp, position }); } this.setState({ loadedPosition: loadedPosition + floors.length, loadMoreVisibility: false, loadMoreStatus: 'more', thread: { ...thread, replies: thread.replies.concat(replies) } }); } } else { const { auth } = this.props; Taro.hideLoading(); if (auth) { Taro.atMessage({ message: `登录凭据过期,请重新登录🥀`, type: 'error', duration: 3000 }); } else { let message = res.data.message as string; message = message.replace('</p></div><div><p>', ''); Taro.atMessage({ message: `无法查看帖子😱,${message}`, type: 'error', duration: 3000 }); } } }, (): void => { Taro.atMessage({ message: '网络连接中断😭', type: 'error', duration: 2000 }); } ); } public render(): JSX.Element { const pageDepth = Taro.getCurrentPages().length; const { thread, loadMoreStatus, loadMoreVisibility } = this.state; const { statusBarHeight } = this.props; const repliesArea = thread.replies.map( (reply): JSX.Element => { return ( <View key={reply.position}> <ReplyCard reply={reply}></ReplyCard> </View> ); } ); return ( // <WxmlifyRichText html={thread.content}></WxmlifyRichText> // 组件报错,不可用 // <WxparseRichText html={thread.content}></WxparseRichText> // 效果挺好 // <RichText nodes={thread.content}></RichText> //最方便,没有任何排版,样式原始,没有表格,图片不自适应 // <wxparse data={thread.content} type="html" padding="15"></wxparse> <View> <AtMessage /> <AtNavBar customStyle={`background-color: #57bae8; padding-top: ${statusBarHeight}px;`} title="主题" color="#FFF" leftIconType={pageDepth === 1 ? 'home' : 'chevron-left'} onClickLeftIcon={ pageDepth === 1 ? (): void => { Taro.switchTab({ url: '/pages/index/index' }); } : (): void => { Taro.navigateBack({ delta: 1 }); } } border={false} /> <View className="header"> <Text decode className="title"> {thread.title} </Text> </View> <View className="author"> <AtAvatar circle image={thread.author.avatar} size="small" className="avatar" ></AtAvatar> <View className="info"> <Text className="name">{thread.author.username}</Text> <View className="others"> <Text className="time"> {dayjs.unix(thread.timestamp as number).fromNow()} </Text> <Text> 阅读 {thread.viewed} · 回复 {thread.replied} </Text> </View> </View> </View> <View className="content"> <ParserRichText html={thread.content} selectable></ParserRichText> </View> <AtDivider> <View className="at-icon at-icon-check-circle"></View> </AtDivider> {repliesArea} {loadMoreVisibility && ( <AtLoadMore status={loadMoreStatus as 'loading' | 'more' | 'noMore' | undefined} loadingText="捕获更多回复中~🤩" noMoreText="下面真的没有啦~😳" /> )} </View> ); } } export default Thread as Taro.ComponentClass;
the_stack
import * as algoliasearch from 'algoliasearch'; import * as algoliasearchHelper from 'algoliasearch-helper'; // tslint:disable-next-line:no-duplicate-imports import { SearchResults, SearchParameters } from 'algoliasearch-helper'; // https://community.algolia.com/algoliasearch-helper-js/reference.html#module:algoliasearchHelper const client = algoliasearch('latency', '6be0576ff61c053d5f9a3225e2a90f76'); const helper = algoliasearchHelper(client, 'bestbuy', { facets: ['shipping'], disjunctiveFacets: ['category'] }); helper.on('result', (result) => { console.log(result); }); helper.toggleRefine('Movies & TV Shows') .toggleRefine('Free shipping') .search(); const updateTheResult = (results: SearchResults, state: SearchParameters) => { console.log(results, state); }; helper.on('result', updateTheResult); helper.once('result', updateTheResult); helper.removeListener('result', updateTheResult); helper.removeAllListeners('result'); () => { // Changing the number of records returned per page to 1 // This example uses the callback API const state = helper.searchOnce({hitsPerPage: 1}, (error, content: SearchResults, state: SearchParameters) => {}); // Changing the number of records returned per page to 1 // This example uses the promise API const state1 = helper.searchOnce({hitsPerPage: 1}) .then(promiseHandler); function promiseHandler(res: {content: SearchResults, state: SearchParameters}) { // res contains // { // content : SearchResults // state : SearchParameters (the one used for this specific search) // } } }; helper.setIndex('highestPrice_products').getIndex(); helper.setPage(0).nextPage().getPage(); helper.setPage(1).previousPage().getPage(); helper.setQueryParameter('hitsPerPage', 20).search(); const hitsPerPage = helper.getQueryParameter('hitsPerPage'); helper.addFacetRefinement('film-genre', 'comedy'); helper.addFacetRefinement('film-genre', 'science-fiction'); () => { const indexName = 'test'; const helper2 = algoliasearchHelper(client, indexName, { facets: ['nameOfTheAttribute'] }); }; // Removing all the refinements helper.clearRefinements().search(); // Removing all the filters on a the category attribute. helper.clearRefinements('category').search(); // Removing only the exclude filters on the category facet. helper.clearRefinements((value, attribute, type) => { return type === 'exclude' && attribute === 'category'; }).search(); // https://community.algolia.com/algoliasearch-helper-js/reference.html#AlgoliaSearchHelper#hasRefinements helper.hasRefinements('price'); // false helper.addNumericRefinement('price', '>', 100); helper.hasRefinements('price'); // true helper.hasRefinements('color'); // false helper.addFacetRefinement('color', 'blue'); helper.hasRefinements('color'); // true helper.hasRefinements('material'); // false helper.addDisjunctiveFacetRefinement('material', 'plastic'); helper.hasRefinements('material'); // true helper.hasRefinements('categories'); // false helper.toggleFacetRefinement('categories', 'kitchen > knife'); helper.hasRefinements('categories'); // true // https://community.algolia.com/algoliasearch-helper-js/reference.html#AlgoliaSearchHelper#getRefinements helper.addNumericRefinement('price', '>', 100); helper.getRefinements('price'); helper.addFacetRefinement('color', 'blue'); helper.addFacetExclusion('color', 'red'); helper.getRefinements('color'); helper.addDisjunctiveFacetRefinement('material', 'plastic'); helper.addDisjunctiveFacetRefinement('tech', 'crt'); helper.addDisjunctiveFacetRefinement('tech', 'led'); helper.addDisjunctiveFacetRefinement('tech', 'plasma'); () => { const helper2 = algoliasearchHelper(client, 'test', { disjunctiveFacets: ['nameOfTheAttribute'] }); }; // https://community.algolia.com/algoliasearch-helper-js/reference.html#AlgoliaSearchHelper#hasRefinements // hasRefinements works with numeric, conjunctive, disjunctive and hierarchical filters helper.hasRefinements('price'); // false helper.addNumericRefinement('price', '>', 100); helper.hasRefinements('price'); // true helper.hasRefinements('color'); // false helper.addFacetRefinement('color', 'blue'); helper.hasRefinements('color'); // true helper.hasRefinements('material'); // false helper.addDisjunctiveFacetRefinement('material', 'plastic'); helper.hasRefinements('material'); // true helper.hasRefinements('categories'); // false helper.toggleFacetRefinement('categories', 'kitchen > knife'); helper.hasRefinements('categories'); // true const params = helper.getState().getQueryParams(); client.search([{ indexName: 'test', query: '', params }]); // https://community.algolia.com/algoliasearch-helper-js/reference.html#SearchResults#getFacetValues helper.on('result', (content) => { // get values ordered only by name ascending using the string predicate content.getFacetValues('city', {sortBy: ['name:asc']}); // get values ordered only by count ascending using a function content.getFacetValues('city', { // this is equivalent to ['count:asc'] sortBy(a: { count: number }, b: { count: number }) { if (a.count === b.count) return 0; if (a.count > b.count) return 1; if (b.count > a.count) return -1; } }); }); // https://community.algolia.com/algoliasearch-helper-js/reference.html#SearchParameters#addTagRefinement const searchparameter = new SearchParameters(); // for price = 50 or 40 searchparameter.addNumericRefinement('price', '=', [50, 40]); // for size = 38 and 40 searchparameter.addNumericRefinement('size', '=', 38); searchparameter.addNumericRefinement('size', '=', 40); let queryParameters = new SearchParameters({}); // everything is optional queryParameters = new SearchParameters({ advancedSyntax: true, allowTyposOnNumericTokens: true, analytics: true, analyticsTags: ['test'], aroundLatLng: 'latitude', aroundLatLngViaIP: true, aroundPrecision: 1, aroundRadius: 1, attributesToHighlight: ['test'], attributesToRetrieve: ['test'], attributesToSnippet: ['test'], disableExactOnAttributes: ['test'], disjunctiveFacets: ['test'], disjunctiveFacetsRefinements: { test: ['test'] }, distinct: 2, enableExactOnSingleWordQuery: true, facets: ['test'], facetsExcludes: { test: ['test'] }, facetsRefinements: { test: ['test'] }, getRankingInfo: true, hierarchicalFacets: ['test'], hierarchicalFacetsRefinements: { test: ['test'] }, highlightPostTag: 'test', highlightPreTag: 'test', hitsPerPage: 1, ignorePlurals: true, index: 'test', insideBoundingBox: [[1, 2, 3, 4]], insidePolygon: [[1, 2, 3, 4]], length: 2, maxValuesPerFacet: 1, minimumAroundRadius: 1, minProximity: 1, minWordSizefor1Typo: 1, minWordSizefor2Typos: 1, numericFilters: ['test'], numericRefinements: { test: { '=': [1], '>': [[2, 3]] } }, offset: 1, optionalFacetFilters: 'test', optionalTagFilters: 'test', optionalWords: ['test'], page: 1, query: 'test', queryType: 'prefixAll', removeWordsIfNoResults: 'none', replaceSynonymsInHighlight: true, restrictSearchableAttributes: ['test'], snippetEllipsisText: '...', synonyms: true, tagFilters: ['test'], tagRefinements: ['test'], typoTolerance: true, }); queryParameters.advancedSyntax; queryParameters.allowTyposOnNumericTokens; queryParameters.analytics; queryParameters.analyticsTags; queryParameters.aroundLatLng; queryParameters.aroundLatLngViaIP; queryParameters.aroundPrecision; queryParameters.aroundRadius; queryParameters.attributesToHighlight; queryParameters.attributesToRetrieve; queryParameters.attributesToSnippet; queryParameters.disableExactOnAttributes; queryParameters.disjunctiveFacets; queryParameters.disjunctiveFacetsRefinements; queryParameters.distinct; queryParameters.enableExactOnSingleWordQuery; queryParameters.facets; queryParameters.facetsExcludes; queryParameters.facetsRefinements; queryParameters.getRankingInfo; queryParameters.hierarchicalFacets; queryParameters.hierarchicalFacetsRefinements; queryParameters.highlightPostTag; queryParameters.highlightPreTag; queryParameters.hitsPerPage; queryParameters.ignorePlurals; queryParameters.index; queryParameters.insideBoundingBox; queryParameters.insidePolygon; queryParameters.length; queryParameters.maxValuesPerFacet; queryParameters.minimumAroundRadius; queryParameters.minProximity; queryParameters.minWordSizefor1Typo; queryParameters.minWordSizefor2Typos; queryParameters.numericFilters; queryParameters.numericRefinements; queryParameters.offset; queryParameters.optionalFacetFilters; queryParameters.optionalTagFilters; queryParameters.optionalWords; queryParameters.page; queryParameters.query; queryParameters.queryType; queryParameters.removeWordsIfNoResults; queryParameters.replaceSynonymsInHighlight; queryParameters.restrictSearchableAttributes; queryParameters.snippetEllipsisText; queryParameters.synonyms; queryParameters.tagFilters; queryParameters.tagRefinements; queryParameters.typoTolerance; queryParameters.addDisjunctiveFacet('test'); queryParameters.addDisjunctiveFacetRefinement('test', 'test'); queryParameters.addExcludeRefinement('test', 'test'); queryParameters.addFacet('test'); queryParameters.addFacetRefinement('test', 'test'); queryParameters.addHierarchicalFacet({}); queryParameters.addHierarchicalFacetRefinement('test', 'test'); queryParameters.addNumericRefinement('test', '>', [7]); queryParameters.addTagRefinement('test'); queryParameters.clearRefinements('test'); queryParameters.clearTags(); queryParameters.filter(['test']); queryParameters.getConjunctiveRefinements('test'); queryParameters.getDisjunctiveRefinements('test'); queryParameters.getExcludeRefinements('test'); queryParameters.getHierarchicalFacetBreadcrumb('test'); queryParameters.getHierarchicalFacetByName('test'); queryParameters.getHierarchicalRefinement('test'); queryParameters.getNumericRefinement('test', '='); queryParameters.getNumericRefinements('test'); queryParameters.getQueryParameter('test'); queryParameters.getRefinedDisjunctiveFacets('test', {}); queryParameters.getRefinedHierarchicalFacets('test', {}); queryParameters.getUnrefinedDisjunctiveFacets(); queryParameters.isConjunctiveFacet('test'); queryParameters.isDisjunctiveFacet('test'); queryParameters.isDisjunctiveFacetRefined('test', 'test'); queryParameters.isExcludeRefined('test', 'test'); queryParameters.isFacetRefined('test', 'test'); queryParameters.isHierarchicalFacet('test'); queryParameters.isHierarchicalFacetRefined('test', 'test'); queryParameters.isNumericRefined('test', '>', 'test'); queryParameters.isTagRefined('test'); queryParameters.removeDisjunctiveFacet('test'); queryParameters.removeDisjunctiveFacetRefinement('test', 'test'); queryParameters.removeExcludeRefinement('test', 'test'); queryParameters.removeFacet('test'); queryParameters.removeFacetRefinement('test', 'test'); queryParameters.removeHierarchicalFacet('test'); queryParameters.removeHierarchicalFacetRefinement('test'); queryParameters.removeTagRefinement('test'); queryParameters.setDisjunctiveFacets(['test']); queryParameters.setFacets(['test']); queryParameters.setHitsPerPage(1); queryParameters.setPage(1); queryParameters.setQuery('test'); queryParameters.setQueryParameter('test', {}); queryParameters.setQueryParameters({ test: {} }); queryParameters.setTypoTolerance('test'); queryParameters.toggleConjunctiveFacetRefinement('test', {}); queryParameters.toggleDisjunctiveFacetRefinement('test', {}); queryParameters.toggleExcludeFacetRefinement('test', {}); queryParameters.toggleFacetRefinement('test', {}); queryParameters.toggleHierarchicalFacetRefinement('test', {}); queryParameters.toggleTagRefinement('test'); // static methods SearchParameters.make(queryParameters); SearchParameters.validate(queryParameters, { queryType: 'prefixAll' });
the_stack
import {Component, ElementRef, Injector, OnDestroy, OnInit, ViewChild} from '@angular/core'; import {Page} from '@domain/common/page'; import {DataconnectionService} from '@common/service/dataconnection.service'; import {Alert} from '@common/util/alert.util'; import {Workbench} from '@domain/workbench/workbench'; import {GridComponent} from '@common/component/grid/grid.component'; import {Header, SlickGridHeader} from '@common/component/grid/grid.header'; import {GridOption} from '@common/component/grid/grid.option'; import {WorkbenchService} from '../../../service/workbench.service'; import {ActivatedRoute} from '@angular/router'; import {Dataconnection} from '@domain/dataconnection/dataconnection'; import {MetadataService} from '../../../../meta-data-management/metadata/service/metadata.service'; import {isNullOrUndefined, isUndefined} from 'util'; import {AbstractWorkbenchComponent} from '../../abstract-workbench.component'; import {StringUtil} from '@common/util/string.util'; import {CommonUtil} from '@common/util/common.util'; import * as _ from 'lodash'; @Component({ selector: 'detail-workbench-schema-browser', templateUrl: './detail-workbench-schema-browser.component.html', }) export class DetailWorkbenchSchemaBrowserComponent extends AbstractWorkbenchComponent implements OnInit, OnDestroy { /*-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-= | Private Variables |-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=*/ @ViewChild('inputSearch') private _inputSearch: ElementRef; // @ViewChild('schemaMain') private gridSchemaComponent: GridComponent; // @ViewChild('schemaColumn') private gridSchemaColumnComponent: GridComponent; // @ViewChild('schemaData') private gridSchemaDataComponent: GridComponent; // private selectedTabNum: number = 0; // private workbench: Workbench; // private workbenchId: string; // private _websocketId: string; // tab list private textList: any[]; // { name: '' + this.tabNum, query: '', selected: true } // request reconnect count private _getColumnListReconnectCount: number = 0; private _getMetaDataReconnectCount: number = 0; private _getSingleQueryReconnectCount: number = 0; private _getTableDetailDataReconnectCount: number = 0; private _getDatabaseListReconnectCount: number = 0; private _getTableListReconnectCount: number = 0; /*-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-= | Protected Variables |-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=*/ /*-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-= | Public Variables |-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=*/ // public dataConnection: Dataconnection = new Dataconnection(); // public databaseList: any[] = []; // public schemaTableList: any[] = []; // public schemaTableColumnList: any[] = []; // public schemaTableMetadataList: any[] = []; // public schemaTableDataList: any[] = []; public schemaTableDataDataList: any[] = []; // . public schemaSelectedTab: string = ''; // public selectedSchemaTable: string = ''; // public searchTableText: string = ''; // public searchColumnText: string = ''; // public searchDataText: string = ''; // public searchDatabaseText: string = ''; // public selectedDatabaseName: string; // public isFull: boolean; // show flag public isShow: boolean; // show flag public connectionInfoShowFl: boolean = false; // show flag public databaseListShowFl: boolean = false; // tab list, no data public isColumListNoData: boolean = false; public isMetadataListNoData: boolean = false; public isDataListNoData: boolean = false; public connTargetImgUrl: string = ''; /*-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-= | Constructor |-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=*/ // constructor(private activatedRoute: ActivatedRoute, private _metaDataService: MetadataService, private connectionService: DataconnectionService, protected workbenchService: WorkbenchService, protected element: ElementRef, protected injector: Injector) { super(workbenchService, element, injector); } /*-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-= | Override Method |-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=*/ // Init public ngOnInit() { // Init super.ngOnInit(); // browser data this._getBrowserData(); } // Destory public ngOnDestroy() { // Destory super.ngOnDestroy(); } /*-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-= | Public Method |-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=*/ /** * init */ public init(param: object): void { // ui this._initView(); // this.isFull = false; // show this.isShow = true; // item this.workbench = param['workbench']; this.workbenchId = param['workbenchId']; this._websocketId = param['websocketId']; this.textList = param['textList']; // this.dataConnection = _.cloneDeep(this.workbench.dataConnection); // this.selectedDatabaseName = this.dataConnection.database; // this.selectedSchemaTable = ''; // this.schemaSelectedTab = ''; // this.databaseList = []; this.schemaTableList = []; this.schemaTableColumnList = []; this.schemaTableMetadataList = []; this.schemaTableDataList = []; this.schemaTableDataDataList = []; // if (isNullOrUndefined(this.dataConnection.authenticationType)) { this.dataConnection.authenticationType = 'MANUAL'; } // this._getDatabaseList(); } /** * */ public close() { this.isShow = false; } /** * */ public changeWindowMode(): void { // close this.close(); // const param = { workbench: this.workbench, workbenchId: this.workbenchId, websocketId: WorkbenchService.websocketId, textList: this.textList }; // sessionStorage.setItem('METATRON_SCHEMA_BROWSER_DATA' + this.workbenchId, JSON.stringify(param)); const popupX = (window.screen.width / 2) - (1200 / 2); const popupY = (window.screen.height / 2) - (900 / 2); const popUrl = `workbench/${this.workbenchId}/schemabrowser`; // window.open(popUrl, '', 'status=no, height=700, width=1200, left=' + popupX + ', top=' + popupY + ', screenX=' + popupX + ', screenY= ' + popupY); // sessionStorage.removeItem('METATRON_SCHEMA_BROWSER_DATA' + this.workbenchId); } /** * * @returns {boolean} */ public isMoreDatabaseList(): boolean { return this.page.page < this.pageResult.totalPages - 1; } /*-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-= | Public Method - getter |-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=*/ /** * */ public getTableList() { // page const page: Page = new Page(); page.page = 0; page.size = 5000; // show this.loadingShow(); // this._getSearchTablesForServer(this.dataConnection, this.selectedDatabaseName, page); } /** * */ public getColumnList() { // if (this.selectedSchemaTable === '') { Alert.warning(this.translateService.instant('msg.comm.alert.table')); return; } // this.searchColumnText = ''; // this.schemaSelectedTab = 'column'; // page const page: Page = new Page(); page.page = 0; page.size = 99999; // this._getColumnListForServer(this.dataConnection.id, this.selectedDatabaseName, this.selectedSchemaTable, this._websocketId, page); } /** * */ public getMetaData() { // if (this.selectedSchemaTable === '') { Alert.warning(this.translateService.instant('msg.comm.alert.table')); return; } // this.schemaSelectedTab = 'metadata'; // page const page: Page = new Page(); page.page = 0; page.size = 99999; // this._getMetaDataForServer(this.dataConnection.id, this.selectedDatabaseName, this.selectedSchemaTable, this._websocketId, page); } /** * */ public getTableDetailData() { // if (this.selectedSchemaTable === '') { Alert.warning(this.translateService.instant('msg.comm.alert.table')); return; } // this.searchDataText = ''; // this._getTableDetailDataForServer(this.textList[this.selectedTabNum]['editorId'], this._websocketId); } /*-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-= | Public Method - event |-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=*/ /** * * @param {string} database */ public onChangeDatabase(database: string): void { // close show list this.databaseListShowFl = false; // this.selectedDatabaseName = database; // this.schemaTableList = []; // this.selectedSchemaTable = ''; // this.getTableList(); } public onSearchDatabaseKeypress(event: KeyboardEvent): void { this.searchDatabaseText = this._inputSearch.nativeElement.value; if (13 === event.keyCode) { this._searchDatabase(); } else if (27 === event.keyCode) { this.onSearchDatabaseClear(); } } public onSearchDatabaseClear(event?: MouseEvent): void { if (event) { event.preventDefault(); event.stopImmediatePropagation(); } this._inputSearch.nativeElement.value = ''; this._searchDatabase(); } /** * * @param {KeyboardEvent} event */ public onSearchTable(event: KeyboardEvent): void { // this.searchTableText = event.target['value']; // this._searchTableEvent(); } /** * */ public onSearchTableInit(): void { // this.searchTableText = ''; // this._searchTableEvent(); } /** * * @param {KeyboardEvent} event */ public onSearchColumn(event: KeyboardEvent): void { // this.searchColumnText = event.target['value']; // this._searchColumnEvent(); } /** * */ public onSearchColumnInit(): void { // this.searchColumnText = ''; // this._searchColumnEvent(); } /** * * @param {KeyboardEvent} event */ public onSearchData(event: KeyboardEvent): void { // this.searchDataText = event.target['value']; // this._searchDataEvent(); } /** * */ public onSearchDataInit(): void { // this.searchDataText = ''; // this._searchDataEvent(); } /** * * @param event */ public onSelectedTable(event) { // this.selectedSchemaTable = event.row.name; // show switch (this.schemaSelectedTab) { case 'column': this.getColumnList(); break; case 'metadata': this.getMetaData(); break; case 'data': this.getTableDetailData(); break; default: this.getColumnList(); break; } } /** * open or cloe data connection info layer */ public connectionInfoShow(event: MouseEvent) { this.connectionInfoShowFl = !this.connectionInfoShowFl; this.safelyDetectChanges(); const target = $(event.target); const infoLeft: number = target.offset().left; const infoTop: number = target.offset().top; const element = document.getElementById(`connectionInfo`); $(element).css({left: infoLeft - 30, top: infoTop + 17}); } // function - dataConnectionInfoShow /** * Default * @returns {boolean} */ public isDefaultType(): boolean { return StringUtil.isEmpty(this.dataConnection.url); } /*-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-= | Protected Method |-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=*/ /*-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-= | Private Method |-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=*/ /** * * @private */ private _initView(): void { // this.databaseList = []; // this.selectedDatabaseName = ''; // this.searchDatabaseText = ''; // connection info flag this.connectionInfoShowFl = false; // database list flag this.databaseListShowFl = false; } /*-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-= | Private Method - event |-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=*/ /** * * @private */ private _searchTableEvent(): void { // if (typeof this.gridSchemaComponent !== 'undefined') { // this._searchGridComponent(this.gridSchemaComponent, this.searchTableText); } } /** * * @private */ private _searchColumnEvent(): void { // if (typeof this.gridSchemaColumnComponent !== 'undefined') { // this._searchGridComponent(this.gridSchemaColumnComponent, this.searchColumnText); } } /** * * @private */ private _searchDataEvent(): void { // if (typeof this.gridSchemaDataComponent !== 'undefined') { // this._searchGridComponent(this.gridSchemaDataComponent, this.searchDataText); } } /** * * @private */ private _searchDatabase(): void { this.searchDatabaseText = this._inputSearch.nativeElement.value; this.page.page = 0; this.databaseList = []; this._getDatabaseList(true); } /*-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-= | Private Method - getter |-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=*/ /** * * @param {boolean} searchFl * @private */ private _getDatabaseList(searchFl: boolean = false): void { this.connTargetImgUrl = this.getConnImplementorImgUrl( this.dataConnection.connectionInformation.implementor, this.dataConnection.connectionInformation.iconResource1 ); this._getDatabaseListReconnectCount++; this.loadingShow(); this.connectionService.getDatabaseListInConnection(this.dataConnection.id, this._getParameterForDatabase(this._websocketId, this.page, this.searchDatabaseText)) .then((data) => { if (data) { this._getDatabaseListReconnectCount = 0; this.databaseList = this.databaseList.concat(data.databases); this.pageResult = data.page; } searchFl ? this.loadingHide() : this.getTableList(); }) .catch((error) => { if (!isUndefined(error.details) && error.code === 'JDC0005' && this._getDatabaseListReconnectCount <= 5) { this.webSocketCheck(() => { this._websocketId = WorkbenchService.websocketId; this._getDatabaseList(searchFl); }); } else { this.commonExceptionHandler(error); } }); } /** * * @param dataConnection * @param {string} databaseName * @param {Page} page * @param {string} tableName * @private */ private _getSearchTablesForServer(dataConnection, databaseName: string, page: Page, tableName: string = ''): void { // this._getTableListReconnectCount++; dataConnection.database = databaseName; // show this.loadingShow(); this.connectionService.getTableListInConnectionQuery(dataConnection, this._getParameterForTable(this._websocketId, page, tableName)) .then((result) => { // this._getTableListReconnectCount = 0; // hide this.loadingHide(); // table if (result['tables']) { // this.schemaTableList = result['tables']; // this._getTableMetaDataList(result['tables']); } }) .catch((error) => { if (!isUndefined(error.details) && error.code === 'JDC0005' && this._getTableListReconnectCount <= 5) { this.webSocketCheck(() => { this._websocketId = WorkbenchService.websocketId; this._getSearchTablesForServer(dataConnection, databaseName, page, tableName); }); } else { this.commonExceptionHandler(error); } }); } /** * * @param {string} connectionId * @param {string} databaseName * @param {string} tableName * @param {string} webSocketId * @param {Page} page * @param {string} columnNamePattern * @private */ private _getColumnListForServer(connectionId: string, databaseName: string, tableName: string, webSocketId: string, page: Page, columnNamePattern: string = ''): void { // this._getColumnListReconnectCount++; // no data this.isColumListNoData = false; // show this.loadingShow(); this.connectionService.getColumnList(connectionId, databaseName, tableName, columnNamePattern, webSocketId, page) .then((result) => { // this._getColumnListReconnectCount = 0; // column list if (result['columns']) { // this.schemaTableColumnList = result['columns']; // this._getTableMetaDataDetail(tableName); } else { // this.schemaTableColumnList = []; this.isColumListNoData = true; Alert.error(this.translateService.instant('msg.comm.alert.del.fail')); // hide this.loadingHide(); } }) .catch((error) => { if (!isUndefined(error.details) && error.code === 'JDC0005' && this._getColumnListReconnectCount <= 5) { this.webSocketCheck(() => { this._websocketId = WorkbenchService.websocketId; this._getColumnListForServer(connectionId, databaseName, tableName, this._websocketId, page, columnNamePattern); }); } else { this.commonExceptionHandler(error); } }); } /** * * @param {string} connectionId * @param {string} databaseName * @param {string} tableName * @param {string} webSocketId * @param {Page} page * @private */ private _getMetaDataForServer(connectionId: string, databaseName: string, tableName: string, webSocketId: string, page: Page): void { // this._getMetaDataReconnectCount++; // no data this.isMetadataListNoData = false; // show this.loadingShow(); this.connectionService.getTableInfomation(connectionId, databaseName, tableName, webSocketId, page) .then((result) => { // this._getMetaDataReconnectCount = 0; // hide this.loadingHide(); // this.schemaTableMetadataList = []; const resultData = []; for (const key in result) { if (key) { const param = { itemKey: key, item: result[key] }; resultData.push(param); } } // let tempLabel = ''; let tempArr: any[] = []; // result Data for (const key in resultData) { if (key) { const tempData = { label: '', data: tempArr }; if (resultData[key]['itemKey'].startsWith('#')) { if (key !== '0') { tempData.label = tempLabel.split('#')[1]; tempData.data = tempArr; this.schemaTableMetadataList.push(tempData); tempLabel = ''; tempArr = []; } // label tempLabel = resultData[key]['itemKey']; } else { // data tempArr.push(resultData[key]); } // if (resultData.length - 1 === Number(key)) { tempData.label = tempLabel.split('#')[1]; tempData.data = tempArr; this.schemaTableMetadataList.push(tempData); } } } // if (this.schemaTableMetadataList.length === 0) { this.isMetadataListNoData = true; } }) .catch((error) => { if (!isUndefined(error.details) && error.code === 'JDC0005' && this._getMetaDataReconnectCount <= 5) { this.webSocketCheck(() => { this._websocketId = WorkbenchService.websocketId; this._getMetaDataForServer(connectionId, databaseName, tableName, this._websocketId, page); }); } else { this.commonExceptionHandler(error); } }); } /** * * @param {string} editorId * @param {string} webSocketId * @private */ private _getTableDetailDataForServer(editorId: string, webSocketId: string): void { // this._getTableDetailDataReconnectCount++; // show this.loadingShow(); this.workbenchService.checkConnectionStatus(editorId, webSocketId) .then((result) => { // this._getTableDetailDataReconnectCount = 0; if (result === 'IDLE') { // this.schemaSelectedTab = 'data'; // this._getSingleQueryForServer(); } else { // hide this.loadingHide(); Alert.error(this.translateService.instant('msg.bench.ui.query.run')); } }) .catch((error) => { if (!isUndefined(error.details) && error.code === 'JDC0005' && this._getTableDetailDataReconnectCount <= 5) { this.webSocketCheck(() => { this._websocketId = WorkbenchService.websocketId; this._getTableDetailDataForServer(editorId, this._websocketId); }); } else { this.commonExceptionHandler(error); } }); } /** * * @private */ private _getSingleQueryForServer(): void { // - init this.dataConnection.database = this.selectedDatabaseName; // no data this.isDataListNoData = false; // this._getSingleQueryReconnectCount++; this.workbenchService.getSchemaInfoTableData(this.selectedSchemaTable, this.dataConnection) .then((result) => { // this._getSingleQueryReconnectCount = 0; if (result.data.length > 0) { this.schemaTableDataList = result; this.schemaTableDataDataList = result.data; // this._drawGridTableDetailData(); } else { this.schemaTableDataList = []; this.schemaTableDataDataList = []; this.isDataListNoData = true; // Alert.error(this.translateService.instant('msg.comm.alert.del.fail')); } // hide this.loadingHide(); }) .catch((error) => { if (!isUndefined(error.details) && error.code === 'JDC0005' && this._getSingleQueryReconnectCount <= 5) { this.webSocketCheck(() => { this._websocketId = WorkbenchService.websocketId; this._getSingleQueryForServer(); }); } else { this.commonExceptionHandler(error); } }); } // /** // * // * @returns {QueryEditor} // * @private // */ // private _getQueryEditor(): QueryEditor { // const queryEditor: QueryEditor = new QueryEditor(); // queryEditor.name = this.textList[this.selectedTabNum]['name']; // queryEditor.workbench = CommonConstant.API_CONSTANT.API_URL + 'workbenchs/' + this.workbenchId; // queryEditor.order = this.selectedTabNum; // // query // queryEditor.query = 'select * from ' + this.selectedDatabaseName + '.' + this.selectedSchemaTable + ';'; // // webSocket id // queryEditor.webSocketId = this._websocketId; // // editor id // queryEditor.editorId = this.textList[this.selectedTabNum]['editorId']; // return queryEditor; // } /** * session storage * @private */ private _getBrowserData(): void { let workbenchId: string; // url id parse this.activatedRoute.params.subscribe((params) => { workbenchId = params['id']; }); const param = JSON.parse(sessionStorage.getItem('METATRON_SCHEMA_BROWSER_DATA' + workbenchId)); // sessionStorage.removeItem('METATRON_SCHEMA_BROWSER_DATA' + workbenchId); // if (param) { // ui this._initView(); // show flag this.isShow = true; this.isFull = true; // workbench this.workbench = param.workbench; this.workbenchId = param.workbenchId; this._websocketId = param.websocketId; this.textList = param.textList; // this.dataConnection = _.cloneDeep(this.workbench.dataConnection); // this.selectedDatabaseName = this.dataConnection.database; // this._getDatabaseList(); } } /** * * @param {any[]} tableList * @private */ private _getTableMetaDataList(tableList: any[]): void { this._metaDataService.getMetadataByConnection(this.dataConnection.id, this.selectedDatabaseName, tableList.map(item => item), 'forItemListView') .then((result) => { // result merge if (result.length > 0) { this.schemaTableList = this.schemaTableList.map((item) => { return _.merge(item, _.find(result.map((column) => { return {table: column.table, metadataName: column.name} }), {table: item})); }); } // this._drawGridTableList(); // hide this.loadingHide(); }) .catch(error => this.commonExceptionHandler(error)); } /** * * @param {string} tableName * @private */ private _getTableMetaDataDetail(tableName: string): void { // table array const tableNameArr: string[] = []; if (tableName !== '') { tableNameArr.push(tableName); } this._metaDataService.getMetadataByConnection(this.dataConnection.id, this.selectedDatabaseName, tableNameArr) .then((result) => { // result merge if (result.length > 0) { this.schemaTableColumnList = this.schemaTableColumnList.map((item) => { return _.merge(item, _.find(result[0].columns, {physicalName: item.columnName})); }); } // this._drawGridColumnList(); // hide this.loadingHide(); }) .catch(error => this.commonExceptionHandler(error)); } /*-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-= | Private Method - grid |-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=*/ /** * * @private */ private _drawGridColumnList(): void { // data const data: any = this.schemaTableColumnList; const enableMetaData: boolean = _.some(this.schemaTableColumnList, column => column.name); // headers const headers: Header[] = []; // Physical name headers.push(this._createSlickGridHeader('physicalName', 'Column Name', 300)); // Logical name enableMetaData && headers.push(this._createSlickGridHeader('LogicalName', 'Logical Column Name', 300)); // Type headers.push(this._createSlickGridHeader('type', 'Type', 200)); // Desc headers.push(this._createSlickGridHeader('description', 'Description', 300)); // rows const rows: any[] = []; for (let idx: number = 0, nMax = data.length; idx < nMax; idx = idx + 1) { const row = {}; // Physical name row['physicalName'] = data[idx]['columnName']; // Logical name enableMetaData && (row['LogicalName'] = data[idx]['name']); // Type // column size if (isUndefined(data[idx]['columnSize'])) { row['type'] = data[idx]['columnType']; } else { row['type'] = data[idx]['columnType'] + '(' + data[idx]['columnSize'] + ')'; } // Desc row['description'] = data[idx]['description']; rows.push(row); } // this._createGridComponent(this.gridSchemaColumnComponent, headers, rows, 32); } /** * * @private */ private _drawGridTableList(): void { // data const data: any = this.schemaTableList; const enableMetaData: boolean = _.some(this.schemaTableList, table => table.metadataName); // headers const headers: Header[] = []; // headers.push(this._createSlickGridHeader('name', 200)); // headers.push(this._createSlickGridHeader('type', 120)); // headers.push(this._createSlickGridHeader('comment', 260)); headers.push(this._createSlickGridHeader('name', 'Table Name', enableMetaData ? 230 : 460)); // MetaData name enableMetaData && headers.push(this._createSlickGridHeader('metadataName', 'Metadata Name', 230)); // rows const rows: any[] = []; for (let idx: number = 0, nMax = data.length; idx < nMax; idx = idx + 1) { const row = {}; row['name'] = data[idx]; enableMetaData && (row['metadataName'] = data[idx]['metadataName'] || ''); rows.push(row); } // this._createTableGridComponent(this.gridSchemaComponent, headers, rows, 32); // if (this.searchTableText !== '') { // this.onSearchTableInit(); } // column if (this.schemaTableList.length > 0) { // this.selectedSchemaTable = this.schemaTableList[0]; this.schemaSelectedTab = 'column'; this.getColumnList(); // this.gridSchemaComponent.selectRowActivate(0); // sort asc this.gridSchemaComponent.setCurrentSortColumns(true); for (let index: number = 0; index < headers.length; index++) { // icon default const gridSchemaHeader = $('.ddp-pop-wrapList .slick-header-columns'); gridSchemaHeader.find('.slick-sort-indicator').eq(index).removeClass('slick-sort-indicator-asc'); } } } /** * * @private */ private _drawGridTableDetailData(): void { // data const data: any = this.schemaTableDataList; // headers const headers: Header[] = []; for (let index: number = 0, nMax = data.fields.length; index < nMax; index = index + 1) { const temp = data.fields[index].name; const columnCnt = temp.length; // const columnWidth = (7 > columnCnt) ? 80 : (columnCnt * 13.5); headers.push(this._createSlickGridHeader(temp, temp, columnWidth, data.fields[index].logicalType.toString())); } // rows const rows: any[] = []; for (let idx1: number = 0, nMax1 = data.data.length; idx1 < nMax1; idx1 = idx1 + 1) { const row = {}; for (let idx2: number = 0, nMax2 = data.fields.length; idx2 < nMax2; idx2 = idx2 + 1) { const temp = data.fields[idx2].name; if (data.fields[idx2].logicalType === 'INTEGER') { try { row[temp] = Number(data.data[idx1][temp]); } catch (e) { row[temp] = 0; } } else { row[temp] = data.data[idx1][temp]; } } rows.push(row); } // this._createGridComponent(this.gridSchemaDataComponent, headers, rows, 32); } /** * slick grid header * @param {string} field * @param {string} name * @param {number} width * @param {string} iconType * @returns {header} * @private */ private _createSlickGridHeader(field: string, name: string, width: number, iconType?: string): Header { return iconType ? new SlickGridHeader() .Id(field) .Name('<span style="padding-left:20px;"><em class="' + this.getFieldTypeIconClass(iconType) + '"></em>' + name + '</span>') .Field(field) .Behavior('select') .CssClass('cell-selection') .Width(width) .CannotTriggerInsert(true) .Resizable(true) .Unselectable(true) .Sortable(true) .build() : new SlickGridHeader() .Id(field) .Name(name) .Field(field) .Behavior('select') .CssClass('cell-selection') .Width(width) .CannotTriggerInsert(true) .Resizable(true) .Unselectable(true) .Sortable(true) .build(); } /** * grid component * @param {GridComponent} gridComponent * @param {header[]} headers * @param {any[]} rows * @param {number} rowHeight * @private */ private _createGridComponent(gridComponent: GridComponent, headers: Header[], rows: any[], rowHeight: number): void { gridComponent.create(headers, rows, new GridOption() .SyncColumnCellResize(true) .MultiColumnSort(true) .RowHeight(rowHeight) .DualSelectionActivate(true) .CellExternalCopyManagerActivate(true) .EnableSeqSort(true) .build() ); } /** * Table grid create * @param {GridComponent} gridComponent * @param {header[]} headers * @param {any[]} rows * @param {number} rowHeight * @private */ private _createTableGridComponent(gridComponent: GridComponent, headers: Header[], rows: any[], rowHeight: number): void { gridComponent.create(headers, rows, new GridOption() .SyncColumnCellResize(true) .MultiColumnSort(true) .RowHeight(rowHeight) .DualSelectionActivate(false) .MultiSelect(false) .build() ); } /** * grid component * @param {GridComponent} gridComponent * @param {string} searchText * @private */ private _searchGridComponent(gridComponent: GridComponent, searchText: string): void { gridComponent.search(searchText); } /** * Get parameters for database list * @param {string} webSocketId * @param {Page} page * @param {string} databaseName * @returns {any} * @private */ private _getParameterForDatabase(webSocketId: string, page?: Page, databaseName?: string): any { const params = { webSocketId: webSocketId, loginUserId: CommonUtil.getLoginUserId() }; if (page) { params['sort'] = page.sort; params['page'] = page.page; params['size'] = page.size; } if (StringUtil.isNotEmpty(databaseName)) { params['databaseName'] = databaseName.trim(); } return params; } /** * Get parameter for table * @param {string} webSocketId * @param {Page} page * @param {string} tableName * @returns {any} * @private */ private _getParameterForTable(webSocketId: string, page?: Page, tableName?: string): any { const params = { webSocketId: webSocketId }; if (page) { params['sort'] = page.sort; params['page'] = page.page; params['size'] = page.size; } if (StringUtil.isNotEmpty(tableName)) { params['tableName'] = tableName.trim(); } return params; } }
the_stack
import omit from 'lodash/omit' import type { ValidationMessages } from '@looker/components' import { DefaultSettings } from '@looker/sdk-rtl' import type { ITabTable } from '@looker/wholly-sheet' import { SheetSDK } from '@looker/wholly-sheet' import { getExtensionSDK } from '@looker/extension-sdk' import { getCore40SDK } from '@looker/extension-sdk-react' import type { SheetData } from '../models/SheetData' import { initActiveSheet } from '../models/SheetData' import { GAuthSession } from '../authToken/gAuthSession' import type { IProjectProps, IHackerProps, IHackathonProps, IJudgingProps, IRegistrationProps, ITechnologyProps, } from '../models' import { Hacker, Project, Projects, Hackers, sheetHeader, Judging, } from '../models' import { ExtensionProxyTransport } from '../authToken/extensionProxyTransport' import type { ProjectsHeadings, HackersHeadings, JudgingsHeadings, } from './types' /** * Client to wholly sheets data. * * Wholly sheets deals with classes of data but has the ability to convert * the classes into and from javascript objects. The redux store only wants to * deal with json objects. The redux sagas use this class to get javascript * objects from wholly sheets classes and to update wholly sheets classes * with javascript object data. * * Important. DO NOT LEAK THE WHOLLY SHEETS CLASSES!!!! * Always convert to or from javascript objects. */ class SheetsClient { private sheetData?: SheetData private hackers?: Hackers private hacker?: IHackerProps async getProjects(refresh = true): Promise<IProjectProps[]> { const projects = await this.getSheetProjects(refresh) return this.decorateProjectObjects(projects.toObject(), projects.rows) } async getProject(projectId: string): Promise<IProjectProps | undefined> { const projects = await this.getProjects(false) return projects.find((project) => project._id === projectId) } async getCurrentProjects(hackathonId?: string): Promise<IProjectProps[]> { const data = await this.getSheetData() await data.projects.refresh() const hackathon = await this.getSheetHackathon(hackathonId) const rows = data.projects.filterBy(hackathon) // Create a projects object from the filtered rows const result = new Projects(data, { header: data.projects.header, rows: rows, } as ITabTable) return this.decorateProjectObjects(result.toObject(), rows) } validateProject({ title, description, project_type, technologies, more_info, }: IProjectProps): ValidationMessages | undefined { const validationMessages: ValidationMessages = {} if (!title || title.trim() === '') { validationMessages.title = { type: 'error', message: 'Title required', } } if (!description || description.trim() === '') { validationMessages.description = { type: 'error', message: 'Description required', } } if (!project_type || project_type.trim() === '') { validationMessages.project_type = { type: 'error', message: 'Project type required', } } if (!technologies || technologies.length === 0) { validationMessages.technologies = { type: 'error', message: 'At least one technology required', } } if ( !( !more_info || // Go figure this but its happening! more_info === '\0' || more_info.trim() === '' || more_info.startsWith('http://') || more_info.startsWith('https://') ) ) { validationMessages.more_info = { type: 'error', message: 'More info must be a URL', } } return Object.keys(validationMessages).length === 0 ? undefined : validationMessages } async createProject( hacker_id: string, projectProps: IProjectProps ): Promise<string> { const hackathon = await this.getSheetHackathon() projectProps._hackathon_id = hackathon!._id projectProps.date_created = new Date() projectProps._user_id = hacker_id const projects = await this.getSheetProjects() let project = new Project() project.fromObject(this.prepareProjectProperties(projectProps)) project = await projects.save(project) return project._id } async updateProject(projectProps: IProjectProps) { const data = await this.getSheetData() const projects = data.projects const project = projects.find(projectProps._id, '_id') if (project) { this.updateJudges(project, projectProps.$judges) const projProps = this.prepareProjectProperties(projectProps) // TODO fromObject messes up $judging which is why judge updates are done first. project.fromObject(projProps) await projects.update(project) // TODO remove this when fromObject is fixed await this.getCurrentProjects() } else { throw new Error(`project not found for ${projectProps._id}`) } } async deleteProject(projectId: string) { const projects = await this.getSheetProjects() const project = projects.find(projectId, '_id') if (project) { await projects.delete(project) } else { throw new Error(`project not found for ${projectId}`) } } async lockProjects( lock: boolean, hackathonId?: string ): Promise<IProjectProps[]> { const projects = await this.getSheetProjects() const hackathon = await this.getSheetHackathon(hackathonId) if (hackathon) { await projects.lock(hackathon, lock) return await this.getCurrentProjects(hackathonId) } else { throw new Error(this.getHackathonErrorMessage(hackathonId)) } } async lockProject(lock: boolean, projectId: string) { const data = await this.getSheetData() const projects = data.projects const project = projects.find(projectId, '_id') if (project) { project.locked = lock await projects.update(project) } else { throw new Error(`project not found for ${projectId}`) } } async getCurrentHackathon(): Promise<IHackathonProps> { const hackathon = await this.getSheetHackathon() if (hackathon) { return hackathon.toObject() } else { throw new Error(this.getHackathonErrorMessage()) } } async getJudgings(hackathonId?: string): Promise<IJudgingProps[]> { const hackathon = await this.getSheetHackathon(hackathonId) if (hackathon) { const data = await this.getSheetData() await data.judgings.refresh() let judgings = data.judgings.filterBy(hackathon).map((j) => j.toObject()) const hacker = await this.getHacker() if (!hacker.canAdmin) { if (hacker.canJudge) { judgings = judgings.filter((j) => j.user_id === hacker.id) } else { judgings = [] } } return judgings } else { throw new Error(this.getHackathonErrorMessage(hackathonId)) } } async saveJudging(judgingProps: IJudgingProps): Promise<IJudgingProps> { const data = await this.getSheetData() const judging = data.judgings.find(judgingProps._id, '_id') if (judging) { judging.fromObject(judgingProps) const updatedJudging = await data.judgings.save(judging) return updatedJudging.toObject() } else { throw new Error(`judging not found for ${judgingProps._id}`) } } async getHacker(): Promise<IHackerProps> { if (!this.hacker) { const lookerSdk = getCore40SDK() const hacker = new Hacker(lookerSdk) await hacker.getMe() try { const data = await this.getSheetData() await this.loadHackers(data) } catch (error) { console.warn( 'Error loading sheets data. Has hackathon application been configured?' ) } this.hacker = this.decorateHacker(hacker.toObject(), hacker) } return this.hacker } async getHackers(): Promise<{ hackers: IHackerProps[] judges: IHackerProps[] admins: IHackerProps[] staff: IHackerProps[] }> { const hackers = this.hackers?.users?.map((hacker) => this.decorateHacker(hacker.toObject(), hacker) ) || [] const judges = this.hackers?.judges?.map((hacker) => this.decorateHacker(hacker.toObject(), hacker) ) || [] const admins = this.hackers?.admins?.map((hacker) => this.decorateHacker(hacker.toObject(), hacker) ) || [] const staff = this.hackers?.staff?.map((hacker) => this.decorateHacker(hacker.toObject(), hacker) ) || [] return { hackers, judges, admins, staff } } async registerUser( user: Hacker, hackathonId?: string ): Promise<IRegistrationProps> { const hackathon = await this.getSheetHackathon(hackathonId) if (hackathon) { const data = await this.getSheetData() const registration = await data.registerUser(hackathon, user) return registration.toObject() } else { throw new Error(this.getHackathonErrorMessage(hackathonId)) } } async getTechnologies(): Promise<ITechnologyProps[]> { const data = await this.getSheetData() if (!data.technologies || data.technologies.rows.length < 1) { await data.technologies.refresh() } return data.technologies.toObject() } async changeMembership( projectId: string, hackerId: string, leave: boolean ): Promise<IProjectProps> { const projects = await this.getSheetProjects() const project = projects.find(projectId, '_id') if (project) { // TODO for some reason hacker id not populated. Verify with JK // TODO originally used users but ended using rows in order to add myself const hacker = this.hackers!.rows.find( (hacker) => String(hacker.user.id) === hackerId ) if (hacker) { if (leave) { await project.leave(hacker) } else { await project.join(hacker) } return (await this.getProject(projectId)) as IProjectProps } else { throw new Error(`hacker not found for ${hackerId}`) } } else { throw new Error(`project not found for ${projectId}`) } } getProjectsHeadings(): ProjectsHeadings { const headers = [ 'locked', 'contestant', 'title', 'description', 'project_type', 'technologies', '$team_count', '$judge_count', ] const template = new Project() return sheetHeader(headers, template) } getHackersHeadings(): HackersHeadings { const template = new Hacker() const lookerSdk = getCore40SDK() const hackersContainer = new Hackers(lookerSdk) const headers = hackersContainer.displayHeaders return sheetHeader(headers, template) } getJudgingsHeadings(): JudgingsHeadings { const headers = [ '$judge_name', '$title', 'execution', 'ambition', 'coolness', 'impact', 'score', 'notes', ] const template = new Judging() return sheetHeader(headers, template) } private async updateJudges(project: Project, judges: string[]) { const addedJudges = judges.filter( (judge) => !project.$judges.includes(judge) ) const deletedJudges = project.$judges.filter( (judge) => !judges.includes(judge) ) const hackerJudges = this.hackers?.judges for (const judge of deletedJudges) { const hackerJudge = hackerJudges?.find((hj) => hj.name === judge) if (hackerJudge) { await project.deleteJudge(hackerJudge) } } for (const judge of addedJudges) { const hackerJudge = hackerJudges?.find((hj) => hj.name === judge) if (hackerJudge) { await project.addJudge(hackerJudge) } } } private prepareProjectProperties(projectProps: IProjectProps): IProjectProps { const props = omit(projectProps, [ '$judges', '$judge_count', '$members', '$team_count', ]) return props as IProjectProps } private async getSheetProjects(refresh = false) { const data = await this.getSheetData() if (refresh) { await data.projects.refresh() } return data.projects } private async getSheetHackathon(hackathonId?: string) { if (hackathonId) { const hackathons = await this.getSheetHackathons() return await hackathons.find(hackathonId, '_id') } else { const data = this.getSheetData() return await ( await data ).currentHackathon } } private async getSheetHackathons() { const data = await this.getSheetData() return data.hackathons } private getHackathonErrorMessage(hackathonId?: string) { return hackathonId ? `hackathon not found for ${hackathonId}` : 'current hackathon not found' } private async getSheetData(): Promise<SheetData> { if (this.sheetData) return this.sheetData // Values required const extSDK = getExtensionSDK() const tokenServerUrl = (await extSDK.userAttributeGetItem('token_server_url')) || '' const sheetId = (await extSDK.userAttributeGetItem('sheet_id')) || '' const options = { ...DefaultSettings(), ...{ base_url: tokenServerUrl }, } const transport = new ExtensionProxyTransport(extSDK, options) const gSession = new GAuthSession(extSDK, options, transport) const sheetSDK = new SheetSDK(gSession, sheetId) const doc = await sheetSDK.index() this.sheetData = initActiveSheet(sheetSDK, doc) return this.sheetData } private async loadHackers(data: SheetData) { if (!this.hackers) { const lookerSdk = getCore40SDK() const foo = new Hackers(lookerSdk) this.hackers = await foo.load(data) } } /** * Temporary method that adds missing data. * @param projectPropsList */ private decorateProjectObjects( projectPropsList: IProjectProps[], projects: Project[] ): IProjectProps[] { return projectPropsList.map((projectProps, index) => { projects[index].load() if (!projectProps.$judges) { projectProps.$judges = projects[index].$judges } if (!projectProps.$judge_count) { projectProps.$judge_count = projects[index].$judge_count } if (!projectProps.$members) { projectProps.$members = projects[index].$members } if (!projectProps.$team_count) { projectProps.$team_count = projectProps.$members.length } projectProps.technologies = projectProps.technologies.filter( (v) => v !== '' ) return projectProps }) } private decorateHacker(hackerProps: IHackerProps, _: Hacker): IHackerProps { if (hackerProps.id === undefined) { hackerProps.id = String(hackerProps.user.id) } if (hackerProps.firstName === undefined) { hackerProps.firstName = hackerProps.user.first_name! } if (hackerProps.firstName === undefined) { hackerProps.lastName = hackerProps.user.last_name! } if (hackerProps.name === undefined) { hackerProps.name = hackerProps.user.display_name! } if (hackerProps.registered === undefined && hackerProps.registration) { hackerProps.registered = hackerProps.registration.date_registered } if (hackerProps.attended === undefined && hackerProps.registration) { hackerProps.attended = hackerProps.registration.attended } return hackerProps } } export const sheetsClient = new SheetsClient()
the_stack
import {BoxrecRole} from "boxrec-requests/dist/boxrec-requests.constants"; import {getHeaderColumnText, trimRemoveLineBreaks} from "../../helpers"; import {BoxrecParseBoutsParseBouts} from "../event/boxrec.parse.bouts.parseBouts"; import {BoxrecProfileRole, BoxrecProfileTable} from "./boxrec.profile.constants"; const profileTableEl: string = ".profileTable"; export abstract class BoxrecPageProfile extends BoxrecParseBoutsParseBouts { /** * The birth name of the person * @returns {string | null} */ get birthName(): string | null { const birthName: string | void = this.parseProfileTableData(BoxrecProfileTable.birthName); if (birthName) { return birthName; } return null; } /** * Returns the place of which the person was born * @returns {string | null} */ get birthPlace(): string | null { const birthPlace: string | void = this.parseProfileTableData(BoxrecProfileTable.birthPlace); if (birthPlace) { return this.$(`<div>${birthPlace}</div>`).text() || ""; } return null; } /** * Returns the date of birth of the person * @example // Gennady Golovkin would return "1982-04-08" * this field is found on all profile types (ex. Lou Duva https://boxrec.com/en/promoter/24678) * @returns {string | null} */ get born(): string | null { const born: string | void = this.parseProfileTableData(BoxrecProfileTable.born); if (born) { // some boxers have dob and age. Match the YYYY-MM-DD const regex: RegExp = /(\d{4}\-\d{2}\-\d{2})/; const bornMatch: RegExpMatchArray | null = born.match(regex); if (bornMatch) { return bornMatch[1]; } } return null; } /** * Returns the date of the death */ get death(): string | null { const death: string | void = this.parseProfileTableData(BoxrecProfileTable.death); // unsure the results if the person has a death date but no date of birth, we'll assume that the `age` part will // not be there if (death) { const splitDeath: string[] = death.split("/"); if (splitDeath.length > 0) { return splitDeath[0].trim(); } } return null; } /** * Returns the profile global id or id * @returns {number | null} */ get globalId(): number | null { const tr: Cheerio = this.$(profileTableEl).find("h2"); const id: RegExpMatchArray | null = tr.text().match(/\d+/); if (id) { const globalId: number = parseInt(id[0] as string, 10); if (!isNaN(globalId)) { return globalId; } } return null; } /** * Returns an object of various metadata * @returns {Object} */ get metadata(): object | null { const metadata: string | null = this.$("script[type='application/ld+json']").html(); if (metadata) { JSON.parse(metadata); } return null; } /** * Returns the full name * @returns {string} */ get name(): string { return this.$(profileTableEl).find("h1").text(); } /** * Additional info that was found on the profile but is unknown what to call it * @returns {string[][]} */ get otherInfo(): string[][] { return this.parseOtherInfo(); } get picture(): string { return this.$(".profileTablePhoto img").attr("src"); } /** * Returns the current residency of the person * @returns {string | null} */ get residence(): string | null { const residence: string | void = this.parseProfileTableData(BoxrecProfileTable.residence); if (residence) { return this.$(`<div>${residence}</div>`).text() || ""; } return null; } /** * Returns the Boxrec Role value because the values in the HTML might change and not the text * ex. proboxer -> Pro Boxing. therefore to keep tests passing, return the `proboxer` role */ get role(): BoxrecProfileRole[] { const rolesWithLinks: BoxrecProfileRole[] = []; const parentEl: Cheerio = this.$(profileTableEl).find("h2").parent(); // if they have one role they have this element, other they don't const profileOneRole: Cheerio = parentEl.find(".profileP"); // current role (might not exist if they have one role const currentRole: Cheerio = parentEl.find(".profileIcon"); if (currentRole.length || profileOneRole.length) { const canonicalLinkMatches: RegExpMatchArray | null = this.$("link[rel='canonical']").attr("href") .match(/\/en\/(\w+)\/\d+/); if (canonicalLinkMatches && canonicalLinkMatches.length) { rolesWithLinks.push({ id: this.globalId, name: canonicalLinkMatches[1] as BoxrecRole, }); } else { throw new Error(`Could not get BoxRec role?: ${this.globalId}`); } } // other roles parentEl.find("a").each((index: number, elem: CheerioElement) => { const hrefMatches: RegExpMatchArray | null = elem.attribs.href.match(/(\d+)$/); const type: string = trimRemoveLineBreaks(this.$(elem).text()); if (hrefMatches && type) { rolesWithLinks.push({ id: parseInt(hrefMatches[1], 10), name: type as BoxrecRole, }); } }).get(); // sort so `name` is in order rolesWithLinks.sort((a: BoxrecProfileRole, b: BoxrecProfileRole) => { if (a.name > b.name) { return 1; } if (a.name < b.name) { return -1; } return 0; }); return rolesWithLinks; } /** * Returns an array of social media links * Due to social media platforms changing, this returns an array and not an object */ get socialMedia(): string[] { // we could check that the "type" is empty but that could change, let's check for links to common social media // since BoxRec lists sites like Facebook and YouTube as string URLs and not links, we're going // to protect ourselves by both checking for the strings as well as check for URLs because this could change const tableColumns: Cheerio = this.$(`.profileTable table`) .find(`td:contains(youtube.com), td a[href*='youtube.com'], td:contains(facebook.com), td a[href*='facebook.com'], td:contains(twitter.com), td a[href*='twitter.com']`); if (tableColumns.length) { return tableColumns.map((index: number, elem: CheerioElement) => { const attr: string | undefined = this.$(elem).attr("href"); // if the element has the href attr we know it's the link otherwise it's a string column return attr ? trimRemoveLineBreaks(attr) : trimRemoveLineBreaks(this.$(elem).text()); }).get(); } return []; } /** * Returns whether the person is active or inactive in boxing * @example // returns "active" * @returns {string | null} */ get status(): string | null { const status: string | void = this.parseProfileTableData(BoxrecProfileTable.status); if (status) { return status; } return null; } private get profileTableBody(): Cheerio { return this.$(profileTableEl).find(`table.rowTable tbody`); } /** * Returns bout information in an array * @param boutsListArr Array of bouts * @param {{new(boxrecBodyBout: string, additionalData: (string | null)): U}} type this variable is a class that is instantiated * a class is passed in and an array of that instantiated class is passed back * https://blog.rsuter.com/how-to-instantiate-a-generic-type-in-typescript/ * @hidden * @returns {U[]} */ protected getBouts<U>(boutsListArr: Array<[string, string | null]>, type: (new (headerColumns: string[], boxrecBodyBout: string, additionalData: string | null) => U)): U[] { const headerColumns: string[] = getHeaderColumnText(this.$(".dataTable")); // todo also heads up that the opponent last6 is labelled firstLast6 because it only shows the opponents return boutsListArr.map((val: [string, string | null]) => new type(headerColumns, val[0], val[1])); } /** * Parses the profile table data found at the top of the profile * @hidden */ protected parseProfileTableData(keyToRetrieve?: BoxrecProfileTable): string | void { const tableRow: Cheerio = this.profileTableBody.find(`tr:contains("${keyToRetrieve}")`); const val: string | null = tableRow.find("td:nth-child(2)").html(); if (keyToRetrieve && val) { return val.trim(); } } private parseOtherInfo(): Array<[string, string]> { const otherInfo: Array<[string, string]> = []; const knownTableColumnKeys: string[] = Object.values(BoxrecProfileTable); this.profileTableBody.find("tr").each((i: number, elem: CheerioElement) => { const val: string | null = this.$(elem).find("td:nth-child(2)").html(); const key: string | null = trimRemoveLineBreaks(this.$(elem).find("td:nth-child(1)").text()); // key.subtr because we don't want to match the `ID #` table row if (key && val && key.substr(0, 2) !== "ID" && !knownTableColumnKeys.includes(key)) { otherInfo.push([key, val]); } }); return otherInfo; } }
the_stack
* --------------------------------------------------------------- * ## THIS FILE WAS GENERATED VIA SWAGGER-TYPESCRIPT-API ## * ## ## * ## AUTHOR: acacode ## * ## SOURCE: https://github.com/acacode/swagger-typescript-api ## * --------------------------------------------------------------- */ export interface ProtobufAny { typeUrl?: string; /** @format byte */ value?: string; } export interface RpcStatus { /** @format int32 */ code?: number; message?: string; details?: ProtobufAny[]; } /** * Coin defines a token with a denomination and an amount. NOTE: The amount field is an Int which implements the custom method signatures required by gogoproto. */ export interface V1Beta1Coin { denom?: string; amount?: string; } /** * DenomUnit represents a struct that describes a given denomination unit of the basic token. */ export interface V1Beta1DenomUnit { /** denom represents the string name of the given denom unit (e.g uatom). */ denom?: string; /** * exponent represents power of 10 exponent that one must * raise the base_denom to in order to equal the given DenomUnit's denom * 1 denom = 1^exponent base_denom * (e.g. with a base_denom of uatom, one can create a DenomUnit of 'atom' with * exponent = 6, thus: 1 atom = 10^6 uatom). * @format int64 */ exponent?: number; aliases?: string[]; } /** * Input models transaction input. */ export interface V1Beta1Input { address?: string; coins?: V1Beta1Coin[]; } /** * Metadata represents a struct that describes a basic token. */ export interface V1Beta1Metadata { description?: string; denomUnits?: V1Beta1DenomUnit[]; /** base represents the base denom (should be the DenomUnit with exponent = 0). */ base?: string; /** * display indicates the suggested denom that should be * displayed in clients. */ display?: string; } /** * MsgMultiSendResponse defines the Msg/MultiSend response type. */ export type V1Beta1MsgMultiSendResponse = object; /** * MsgSendResponse defines the Msg/Send response type. */ export type V1Beta1MsgSendResponse = object; /** * Output models transaction outputs. */ export interface V1Beta1Output { address?: string; coins?: V1Beta1Coin[]; } /** * message SomeRequest { Foo some_parameter = 1; PageRequest pagination = 2; } */ export interface V1Beta1PageRequest { /** * key is a value returned in PageResponse.next_key to begin * querying the next page most efficiently. Only one of offset or key * should be set. * @format byte */ key?: string; /** * offset is a numeric offset that can be used when key is unavailable. * It is less efficient than using key. Only one of offset or key should * be set. * @format uint64 */ offset?: string; /** * limit is the total number of results to be returned in the result page. * If left empty it will default to a value to be set by each app. * @format uint64 */ limit?: string; /** * count_total is set to true to indicate that the result set should include * a count of the total number of items available for pagination in UIs. * count_total is only respected when offset is used. It is ignored when key * is set. */ countTotal?: boolean; } /** * PageResponse is to be embedded in gRPC response messages where the corresponding request message has used PageRequest. message SomeResponse { repeated Bar results = 1; PageResponse page = 2; } */ export interface V1Beta1PageResponse { /** @format byte */ nextKey?: string; /** @format uint64 */ total?: string; } /** * Params defines the parameters for the bank module. */ export interface V1Beta1Params { sendEnabled?: V1Beta1SendEnabled[]; defaultSendEnabled?: boolean; } /** * QueryAllBalancesResponse is the response type for the Query/AllBalances RPC method. */ export interface V1Beta1QueryAllBalancesResponse { /** balances is the balances of all the coins. */ balances?: V1Beta1Coin[]; /** pagination defines the pagination in the response. */ pagination?: V1Beta1PageResponse; } /** * QueryBalanceResponse is the response type for the Query/Balance RPC method. */ export interface V1Beta1QueryBalanceResponse { /** balance is the balance of the coin. */ balance?: V1Beta1Coin; } /** * QueryDenomMetadataResponse is the response type for the Query/DenomMetadata RPC method. */ export interface V1Beta1QueryDenomMetadataResponse { /** metadata describes and provides all the client information for the requested token. */ metadata?: V1Beta1Metadata; } /** * QueryDenomsMetadataResponse is the response type for the Query/DenomsMetadata RPC method. */ export interface V1Beta1QueryDenomsMetadataResponse { /** metadata provides the client information for all the registered tokens. */ metadatas?: V1Beta1Metadata[]; /** pagination defines the pagination in the response. */ pagination?: V1Beta1PageResponse; } /** * QueryParamsResponse defines the response type for querying x/bank parameters. */ export interface V1Beta1QueryParamsResponse { /** Params defines the parameters for the bank module. */ params?: V1Beta1Params; } /** * QuerySupplyOfResponse is the response type for the Query/SupplyOf RPC method. */ export interface V1Beta1QuerySupplyOfResponse { /** amount is the supply of the coin. */ amount?: V1Beta1Coin; } export interface V1Beta1QueryTotalSupplyResponse { supply?: V1Beta1Coin[]; } /** * SendEnabled maps coin denom to a send_enabled status (whether a denom is sendable). */ export interface V1Beta1SendEnabled { denom?: string; enabled?: boolean; } export type QueryParamsType = Record<string | number, any>; export type ResponseFormat = keyof Omit<Body, "body" | "bodyUsed">; export interface FullRequestParams extends Omit<RequestInit, "body"> { /** set parameter to `true` for call `securityWorker` for this request */ secure?: boolean; /** request path */ path: string; /** content type of request body */ type?: ContentType; /** query params */ query?: QueryParamsType; /** format of response (i.e. response.json() -> format: "json") */ format?: keyof Omit<Body, "body" | "bodyUsed">; /** request body */ body?: unknown; /** base url */ baseUrl?: string; /** request cancellation token */ cancelToken?: CancelToken; } export type RequestParams = Omit<FullRequestParams, "body" | "method" | "query" | "path">; export interface ApiConfig<SecurityDataType = unknown> { baseUrl?: string; baseApiParams?: Omit<RequestParams, "baseUrl" | "cancelToken" | "signal">; securityWorker?: (securityData: SecurityDataType) => RequestParams | void; } export interface HttpResponse<D extends unknown, E extends unknown = unknown> extends Response { data: D; error: E; } type CancelToken = Symbol | string | number; export enum ContentType { Json = "application/json", FormData = "multipart/form-data", UrlEncoded = "application/x-www-form-urlencoded", } export class HttpClient<SecurityDataType = unknown> { public baseUrl: string = ""; private securityData: SecurityDataType = null as any; private securityWorker: null | ApiConfig<SecurityDataType>["securityWorker"] = null; private abortControllers = new Map<CancelToken, AbortController>(); private baseApiParams: RequestParams = { credentials: "same-origin", headers: {}, redirect: "follow", referrerPolicy: "no-referrer", }; constructor(apiConfig: ApiConfig<SecurityDataType> = {}) { Object.assign(this, apiConfig); } public setSecurityData = (data: SecurityDataType) => { this.securityData = data; }; private addQueryParam(query: QueryParamsType, key: string) { const value = query[key]; return ( encodeURIComponent(key) + "=" + encodeURIComponent(Array.isArray(value) ? value.join(",") : typeof value === "number" ? value : `${value}`) ); } protected toQueryString(rawQuery?: QueryParamsType): string { const query = rawQuery || {}; const keys = Object.keys(query).filter((key) => "undefined" !== typeof query[key]); return keys .map((key) => typeof query[key] === "object" && !Array.isArray(query[key]) ? this.toQueryString(query[key] as QueryParamsType) : this.addQueryParam(query, key), ) .join("&"); } protected addQueryParams(rawQuery?: QueryParamsType): string { const queryString = this.toQueryString(rawQuery); return queryString ? `?${queryString}` : ""; } private contentFormatters: Record<ContentType, (input: any) => any> = { [ContentType.Json]: (input: any) => input !== null && (typeof input === "object" || typeof input === "string") ? JSON.stringify(input) : input, [ContentType.FormData]: (input: any) => Object.keys(input || {}).reduce((data, key) => { data.append(key, input[key]); return data; }, new FormData()), [ContentType.UrlEncoded]: (input: any) => this.toQueryString(input), }; private mergeRequestParams(params1: RequestParams, params2?: RequestParams): RequestParams { return { ...this.baseApiParams, ...params1, ...(params2 || {}), headers: { ...(this.baseApiParams.headers || {}), ...(params1.headers || {}), ...((params2 && params2.headers) || {}), }, }; } private createAbortSignal = (cancelToken: CancelToken): AbortSignal | undefined => { if (this.abortControllers.has(cancelToken)) { const abortController = this.abortControllers.get(cancelToken); if (abortController) { return abortController.signal; } return void 0; } const abortController = new AbortController(); this.abortControllers.set(cancelToken, abortController); return abortController.signal; }; public abortRequest = (cancelToken: CancelToken) => { const abortController = this.abortControllers.get(cancelToken); if (abortController) { abortController.abort(); this.abortControllers.delete(cancelToken); } }; public request = <T = any, E = any>({ body, secure, path, type, query, format = "json", baseUrl, cancelToken, ...params }: FullRequestParams): Promise<HttpResponse<T, E>> => { const secureParams = (secure && this.securityWorker && this.securityWorker(this.securityData)) || {}; const requestParams = this.mergeRequestParams(params, secureParams); const queryString = query && this.toQueryString(query); const payloadFormatter = this.contentFormatters[type || ContentType.Json]; return fetch(`${baseUrl || this.baseUrl || ""}${path}${queryString ? `?${queryString}` : ""}`, { ...requestParams, headers: { ...(type && type !== ContentType.FormData ? { "Content-Type": type } : {}), ...(requestParams.headers || {}), }, signal: cancelToken ? this.createAbortSignal(cancelToken) : void 0, body: typeof body === "undefined" || body === null ? null : payloadFormatter(body), }).then(async (response) => { const r = response as HttpResponse<T, E>; r.data = (null as unknown) as T; r.error = (null as unknown) as E; const data = await response[format]() .then((data) => { if (r.ok) { r.data = data; } else { r.error = data; } return r; }) .catch((e) => { r.error = e; return r; }); if (cancelToken) { this.abortControllers.delete(cancelToken); } if (!response.ok) throw data; return data; }); }; } /** * @title cosmos/bank/v1beta1/bank.proto * @version version not set */ export class Api<SecurityDataType extends unknown> extends HttpClient<SecurityDataType> { /** * No description * * @tags Query * @name QueryAllBalances * @summary AllBalances queries the balance of all coins for a single account. * @request GET:/cosmos/bank/v1beta1/balances/{address} */ queryAllBalances = ( address: string, query?: { "pagination.key"?: string; "pagination.offset"?: string; "pagination.limit"?: string; "pagination.countTotal"?: boolean; }, params: RequestParams = {}, ) => this.request<V1Beta1QueryAllBalancesResponse, RpcStatus>({ path: `/cosmos/bank/v1beta1/balances/${address}`, method: "GET", query: query, format: "json", ...params, }); /** * No description * * @tags Query * @name QueryBalance * @summary Balance queries the balance of a single coin for a single account. * @request GET:/cosmos/bank/v1beta1/balances/{address}/{denom} */ queryBalance = (address: string, denom: string, params: RequestParams = {}) => this.request<V1Beta1QueryBalanceResponse, RpcStatus>({ path: `/cosmos/bank/v1beta1/balances/${address}/${denom}`, method: "GET", format: "json", ...params, }); /** * No description * * @tags Query * @name QueryDenomsMetadata * @summary DenomsMetadata queries the client metadata for all registered coin denominations. * @request GET:/cosmos/bank/v1beta1/denoms_metadata */ queryDenomsMetadata = ( query?: { "pagination.key"?: string; "pagination.offset"?: string; "pagination.limit"?: string; "pagination.countTotal"?: boolean; }, params: RequestParams = {}, ) => this.request<V1Beta1QueryDenomsMetadataResponse, RpcStatus>({ path: `/cosmos/bank/v1beta1/denoms_metadata`, method: "GET", query: query, format: "json", ...params, }); /** * No description * * @tags Query * @name QueryDenomMetadata * @summary DenomsMetadata queries the client metadata of a given coin denomination. * @request GET:/cosmos/bank/v1beta1/denoms_metadata/{denom} */ queryDenomMetadata = (denom: string, params: RequestParams = {}) => this.request<V1Beta1QueryDenomMetadataResponse, RpcStatus>({ path: `/cosmos/bank/v1beta1/denoms_metadata/${denom}`, method: "GET", format: "json", ...params, }); /** * No description * * @tags Query * @name QueryParams * @summary Params queries the parameters of x/bank module. * @request GET:/cosmos/bank/v1beta1/params */ queryParams = (params: RequestParams = {}) => this.request<V1Beta1QueryParamsResponse, RpcStatus>({ path: `/cosmos/bank/v1beta1/params`, method: "GET", format: "json", ...params, }); /** * No description * * @tags Query * @name QueryTotalSupply * @summary TotalSupply queries the total supply of all coins. * @request GET:/cosmos/bank/v1beta1/supply */ queryTotalSupply = (params: RequestParams = {}) => this.request<V1Beta1QueryTotalSupplyResponse, RpcStatus>({ path: `/cosmos/bank/v1beta1/supply`, method: "GET", format: "json", ...params, }); /** * No description * * @tags Query * @name QuerySupplyOf * @summary SupplyOf queries the supply of a single coin. * @request GET:/cosmos/bank/v1beta1/supply/{denom} */ querySupplyOf = (denom: string, params: RequestParams = {}) => this.request<V1Beta1QuerySupplyOfResponse, RpcStatus>({ path: `/cosmos/bank/v1beta1/supply/${denom}`, method: "GET", format: "json", ...params, }); }
the_stack
declare namespace jBox { interface jBoxOptions { /** Choose a unique id, otherwise jBox will set one for you (jBox1, jBox2, ...) */ id?: string; /** The width of the content area */ width?: 'auto' | number; /** The height of the content area */ height?: 'auto' | number; /** Minimal width of content area */ minWidth?: number; /** Minimal height of content area */ minHeight?: number; /** Maximal width of content area */ maxWidth?: number; /** Maximal height of content area */ maxHeight?: number; /** Adjusts width to fit the viewport */ responsiveWidth?: boolean; /** Adjusts height to fit the viewport */ responsiveHeight?: boolean; /** Don't adjust width below this value (in pixel) */ responsiveMinWidth?: number; /** Don't adjust height below this value (in pixel) */ responsiveMinHeight?: number; /** A jQuery selector to elements that will open and close your jBox, e.g. '.tooltip' */ attach?: JQuery<HTMLElement>; /** Defines with which event the jBox opens or closes when interacting with the attached element */ trigger?: 'click' | 'mouseenter' | 'touchclick'; /** Prevent the default event when opening jBox, e.g. don't follow the href in a link */ preventDefault?: boolean; /** Sets the content of your jBox. You can use jQuery elements to append elements (set CSS style display to none so the elements won't show up on your page) */ content?: string | JQuery<HTMLElement>; /** Get the content from an attribute when jBox opens, e.g. 'data-content'. Use 'html' to get the attached elements HTML as content */ getContent?: string; /** Adds a title to your jBox */ title?: string; /** Get the title from an attribute when jBox opens, e.g. 'data-title' */ getTitle?: string; /** Adds a footer to your jBox */ footer?: string; /** Isolates scrolling to the content container */ isolateScroll?: boolean; /** When you set an URL, jBox makes an AJAX request when it opens. You can add any jQuery ajax option, e.g. beforeSend, complete, success, etc. */ ajax?: jBoxAjaxOptions; /** Cancels the ajax call when you close the jBox and it's not finished yet */ cancelAjaxOnClose?: boolean, /** The jQuery selector to the target element where jBox will be opened. If no element is found, jBox will use the attached element as target */ target?: JQuery<HTMLElement>; /** Set an object with the horizontal position x and the vertical position y, e.g. {x: 'right', y: 'center'}. You can also set numbers for an absolute position */ position?: { x: 'right' | 'left' | 'center' | number; y: 'top' | 'bottom' | 'center' | number }; /** Moves your jBox outside of the target element */ outside?: 'x' | 'y' | 'xy'; /** Offset to final position. You can set different values for x and y with an object, e.g. {x: 15, y: -10} */ offset?: number | { x: number; y: number }; /** Defines which CSS attributes should be used, e.g. {x: 'right', y: 'bottom'}. Note that right and bottom can only be used when your position values are integer, e.g. {x: 300, y: 20} */ attributes?: { x: 'right' | 'left' | 'center'; y: 'top' | 'bottom' | 'center' }; /** Your jBox will stay on position when scrolling */ fixed?: boolean; /** Adjusts your jBoxes position if there is not enough space. The value 'flip' positions the jBox on the opposite outside position, the value 'move' works only with a pointer. * Set to true to use both. This option overrides the reposition options */ adjustPosition?: 'flip' | 'move' | boolean; /** By default jBox adjusts its position when it opens or when the window size changes, set to true to also adjust when scrolling */ adjustTracker?: boolean; /** The minimal distance to the viewport edge while adjusting. Use an object to set different values, e.g. {top: 50, right: 5, bottom: 20, left: 5} */ adjustDistance?: number | { top?: number; right?: number; bottom?: number; left?: number }; /** Calculates new position when the window-size changes */ reposition?: boolean; /** Calculates new position each time jBox opens (rather than only when it opens the first time) */ repositionOnOpen?: boolean; /** Calculates new position when the content changes with .setContent() or .setTitle() */ repositionOnContent?: boolean; /** Keeps current position if space permits. Applies only to 'Modal' type */ holdPosition?: boolean; /** Your pointer will always point towards the target element, so the option outside needs to be 'x' or 'y'. By default the pointer is centered, set a position to move it to any side. You can also add an offset, e.g. 'left:30' or 'center:-20' */ pointer?: boolean | 'left' | 'right' | 'top' | 'bottom' | 'center'; /** Setting something else than 'target' will add a pointer even if there is no target element set or found */ pointTo?: 'target' | 'left' | 'right' | 'top' | 'bottom'; /** Fade duration in ms, set 0 or false to disable */ fade?: number; /** Animation when jBox opens or closes. To use different animations for opening and closing, use an object: {open: 'tada', close: 'flip'}. * You can also set the direction of the move and slide animations: {open: 'move:right', close: 'slide:top'} */ animation?: jBoxAnimations | { open?: jBoxAnimations; close?: jBoxAnimations } | boolean; /** Set a jBox theme class, e.g. 'TooltipDark' */ theme?: string; /** Adds classes to the wrapper */ addClass?: string; /** Adds an overlay to hide page content when jBox opens (adjust color and opacity with CSS) */ overlay?: boolean; /** Add a class name to the overlay */ overlayClass?: null | string; /** Use a high z-index, or set to 'auto' to move the jBox to the very top when it opens */ zIndex?: number | 'auto'; /** Delay opening in ms. Note that the delay will be ignored if your jBox didn't finish closing */ delayOpen?: number; /** Delay closing in ms. Nnote that there is always a closing delay of at least 10ms to ensure jBox won't be closed when opening right away */ delayClose?: number; /** Close jBox when pressing [esc] key */ closeOnEsc?: boolean; /** Close jBox with a mouseclick: true closes when you click anywhere, 'overlay' when clicking on the overlay, 'box' when clicking on the jBox itself and 'body' when you click anywhere but the jBox */ closeOnClick?: boolean | 'body' | 'box' | 'overlay'; /** Close jBox when the mouse leaves the jBox area or the area of the attached element */ closeOnMouseleave?: boolean; /** Adds a close button to your jBox. The value true will add the button to the overlay, title or the jBox itself, in that order if any of those elements can be found */ closeButton?: boolean | 'overlay' | 'title' | 'box'; /** The element your jBox will be appended to. Any other element than $('body') is only useful for fixed positions or when position values are numbers */ appendTo?: JQuery<HTMLElement>; /** Creates jBox and makes it available in DOM when it's being initialized, otherwise it will be created when it opens for the first time */ createOnInit?: boolean; /** Blocks scrolling when jBox is open */ blockScroll?: boolean; /** Adjust page elements to avoid content jumps when scrolling is blocked. See more here: https://github.com/StephanWagner/unscroll */ blockScrollAdjust?: boolean | string | Array<string | Array<string>>; /** Makes your jBox draggable. Use title or provide the selector of any child element of jBox to use as the handle */ draggable?: boolean | 'title' | JQuery<HTMLElement>; /** When you have multiple draggable jBoxes, the one you select will always move over the other ones */ dragOver?: boolean; /** Time in ms when jBox will close automatically after it was opened */ autoClose?: number | boolean; /** Preloads the audio files set in option audio. You can also preload other audio files, e.g. ['src_to_file.mp3', 'src_to_file.ogg'] */ preloadAudio?: boolean | string[]; /** The URL to an audio file to play when jBox opens. Set the URL without file extension, jBox will look for an .mp3 and .ogg file. To play audio when jBox closes, use an object, e.g. {open: 'src_to_audio1', close: 'src_to_audio2'} */ audio?: string | { open?: string; close?: string }; /** The volume of the audio in percent. To have different volumes for opening and closeing, use an object, e.g. {open: 75, close: 100} */ volume?: number | { open?: number; close?: number }; /** Fired when jBox is initialized. Note that you can use this in the event functions, it refers to your jBox object, e.g. onInit: function() { this.open(); } */ onInit?: () => void; /** Fired when jBox attached itself to elements */ onAttach?: () => void; /** Fired when jBox is positioned */ onPosition?: () => void; /** Fired when jBox is created and is availible in DOM */ onCreated?: () => void; /** Fired when jBox opens */ onOpen?: () => void; /** Fired when jBox is completely open (when fading is finished) */ onOpenComplete?: () => void; /** Fired when jBox closes */ onClose?: () => void; /** Fired when jBox is completely closed (when fading finished) */ onCloseComplete?: () => void; /** Fired when dragging starts */ onDragStart?: () => void; /** Fired when dragging finished */ onDragEnd?: () => void; } /** Possible values for the 'animation' option */ type jBoxAnimations = | 'zoomIn' | 'zoomOut' | 'pulse' | 'move' | 'slide' | 'flip' | 'tada' | 'move:right' | 'move:left' | 'move:top' | 'move:bottom' | 'slide:right' | 'slide:left' | 'slide:top' | 'slide:bottom'; /** Options for AJAX calls. */ interface jBoxAjaxOptions { /** The URL to send the AJAX request to */ url?: string | null; /** Data to send with your AJAX request, e.g. {id: 82, limit: 10} */ data?: string | {}; /** Resend the AJAX request when jBox opens. Use true to send the AJAX request call only once for every element or 'strict' to resend every time jBox opens */ reload?: boolean | 'strict'; /** The attribute in the source element where the AJAX request will look for the URL, e.g. 'data-url' */ getURL?: string; /** The attribute in the source element where the AJAX request will look for the data, e.g. 'data-ajax' */ getData?: string; /** Automatically set the response as new content when the AJAX request is finished */ setContent?: boolean; /** Add a class to the wrapper when jBox is loading, set to class name or true to use the default class name 'jBox-loading' */ loadingClass?: boolean | string, /** Hides the current content and adds a spinner while loading. You can pass HTML content to add your own spinner, e.g. spinner: '<div class="mySpinner"></div>' */ spinner?: boolean | string; /** Milliseconds to wait until spinner appears */ spinnerDelay?: number; /** Repositions jBox when the spinner is added or removed */ spinnerReposition?: boolean; } /** Additional options for the Confirm plugin */ interface jBoxConfirmOptions extends jBoxOptions { /** Text for the submit button */ confirmButton?: string; /** Text for the cancel button */ cancelButton?: string; /** Function to execute when clicking the submit button. By default jBox will use the onclick or href attribute in that order if found */ confirm?: () => void; /** Function to execute when clicking the cancel button */ cancel?: () => void; /** Close jBox when the user clicks the confirm button */ closeOnConfirm: boolean; } /** Additional options for the Image plugin */ interface jBoxImageOptions extends jBoxOptions { /** The attribute to get the image source from, e.g. 'href' for a link: <a href="/path/image.jpg"> */ src?: string; /** The attribute to set the galleries, e.g. 'data-jbox-gallery'. When changing this option, make sure you check the option attach, as jBox Image gets attached to [data-jbox-gallery] by default. */ gallery?: string; /** The attribute where jBox gets the image label from, e.g. 'title' */ imageLabel?: string; /** The fade duration for images in ms */ imageFade?: number; /** How to display the images. Use CSS styles of background-position, e.g. 'cover', '50% auto' */ imageSize?: 'cover' | 'contain' | 'auto' | string; /** Set to true to add an image counter, e.g. 4/20 */ imageCounter?: boolean; /** HTML to separate the current image number from all image numbers, e.g. '/' or ' of ' */ imageCounterSeparator: string; /** Adds a download button */ downloadButton?: boolean; /** Text for the download button */ downloadButtonText?: string | null; /** The attribute at the source element where to find the image to download, e.g. data-download="/path_to_image/image.jpg". If none provided, the currently active image will be downloaded */ downloadButtonUrl?: string | null; /** The attribute to look for an mobile version of the image */ mobileImageAttr?: string | null; /** The upper breakpoint to load the mobile image */ mobileImageBreakpoint?: number | null; /** Preload the first image when page is loaded */ preloadFirstImage?: boolean; } /** Additional options for the Notice plugin */ interface jBoxNoticeOptions extends jBoxOptions { /** Add a color to your notices */ color?: 'black' | 'red' | 'green' | 'blue' | 'yellow'; /** Set to false to disable notice-stacking */ stack?: boolean; /** Spacing between notices when they stack */ stackSpacing?: number; /** When hovering the notice it won't close */ delayOnHover?: boolean; /** Adds a progress bar showing the time it will take until the notice closes */ showCountdown?: boolean; } } /** Connects the name of the plugin with the type of its options */ declare interface jBoxOptionsMap { Tooltip: jBox.jBoxOptions; Modal: jBox.jBoxOptions; Mouse: jBox.jBoxOptions; Confirm: jBox.jBoxConfirmOptions; Notice: jBox.jBoxNoticeOptions; Image: jBox.jBoxImageOptions; } interface IgnoreDelay { /** Whether to open or close immediately (true) or respect the original delay settings. */ ignoreDelay?: boolean; } /** The core jBox class. Create instances using 'new' e.g. new jBox('Tooltip', { attach: '.tooltip'. }) */ declare class jBox<T extends keyof jBoxOptionsMap> { constructor(type: T, options: jBoxOptionsMap[T]); /** * Opens the jBox. You can set a new target with the option target, e.g. {target: $('#newTarget')}. * If your jBox has an opening delay, you can force it to open immediately with the option ignoreDelay, * e.g. {ignoreDelay: true}. To set new AJAX content when opening the jBox, you can pass an AJAX object, * e.g. {ajax: {url: 'https://reqres.in/api/users'}} */ open(options?: jBoxOptionsMap[T] & IgnoreDelay): void; /** * Closes the jBox. If your jBox has a closing delay, you can force it to close immediately with the option * ignoreDelay, e.g. {ignoreDelay: true} */ close(options?: jBoxOptionsMap[T] & IgnoreDelay): void; /** * Calls the method open when jBox is closed and close when it is open */ toggle(options?: jBoxOptionsMap[T] & IgnoreDelay): void; /** Sets the CSS width of the content container. * Optional you can set a second argument to disable the automatic repositioning of jBox, e.g. .setWidth(200, true) */ setWidth(value: number, disableAutoPosition?: boolean): void; /** Sets the CSS height of the content container. * Optional you can set a second argument to disable the automatic repositioning of jBox, e.g. .setWidth(200, true) */ setHeight(value: number, disableAutoPosition?: boolean): void; /** * Attaches your jBox to elements. Providing a jQuery selector is optional. * If you don't tell this method which elements to use, it will use the selector defined in the options. * This method should be called when elements, which should open or close a jBox, are being created in runtime */ attach(element: JQuery<HTMLElement>): void; /** * Removes the open and close function from elements. */ detach(element: JQuery<HTMLElement>): void; /** * Sets the title of your jBox. If there is no title yet, it will be created. * jBox will reposition if dimensions change, to disable, pass true as second argument: * @example .setTitle('myTitle', true) */ setTitle(title: string, disableAutoPosition?: boolean): void; /** * Sets the content of your jBox. You can use jQuery elements to append elements * (set CSS style display to none so the elements won't show up on your page). * jBox will reposition if dimensions change, to disable, pass true as second argument: * @example .setContent('myContent', true) */ setContent(content: string, disableAutoPosition?: boolean): void; /** * Reloads the AJAX request. You can pass the options url and data, e.g. {url: '/example.php', data: 'id=82'} or any jQuery ajax Option. */ ajax(options: jBox.jBoxAjaxOptions): void; /** * Abort running ajax call */ cancelAjax(): void; /** * Plays an audio file. Don't add the file extension, jBox will look for an .mp3 and an .ogg file. */ audio(url: string, volume: number): void; /** * Recalculates your jBoxes position. You can set a new target with the option target, e.g. {target: $('#newTarget')} */ position(options: jBoxOptionsMap[T]): void; /** * Animates for your jBox or any other element. The animation method is independent from the option animation. * By default this method will animate the jBox wrapper, to animate another element set the option element, e.g. {element: $('#animateMe')}. * To execute a function when the animation is finished use the option complete, e.g. {complete: function () { $('#animateMe').remove(); }} */ animate( animation: | 'tada' | 'tadaSmall' | 'flash' | 'shake' | 'pulseUp' | 'pulseDown' | 'popIn' | 'popOut' | 'fadeIn' | 'fadeOut' | 'slideUp' | 'slideRight' | 'slideLeft' | 'slideDown', options?: { element?: JQuery<HTMLElement>; complete?: () => void } ): void; /** * Disables your jBox, you won't be able to open or close it until enabled. */ disable(): void; /** * Enables your jBox, so you can close and open it again. */ enable(): void; /** * Disables and hides the jBox. This doesnt affect the overlay. */ hide(): void; /** * Enables and shows your jBox again. */ show(): void; /** * Destroys your jBox and removes it from DOM. */ destroy(): void; } export = jBox; export as namespace jBox;
the_stack
import { AfterViewInit, Component, Directive, ElementRef, HostListener, Input, OnDestroy, OnInit, Optional, Renderer2, TemplateRef, ViewChild, Output, EventEmitter, OnChanges, ContentChildren, forwardRef, QueryList, HostBinding } from '@angular/core'; import { LyOverlay, LyTheme2, OverlayFactory, Placement, Positioning, shadowBuilder, ThemeVariables, XPosition, YPosition, StyleCollection, LyClasses, StyleTemplate, lyl, ThemeRef, LyOverlayPosition, StyleRenderer } from '@alyle/ui'; import { trigger, style, animate, transition, AnimationEvent, group } from '@angular/animations'; import { BooleanInput, coerceBooleanProperty } from '@angular/cdk/coercion'; import { ViewportRuler } from '@angular/cdk/scrolling'; import { Subject, asapScheduler } from 'rxjs'; import { take, delay, debounceTime } from 'rxjs/operators'; export interface LyMenuTheme { /** Styles for Menu Component */ root?: StyleCollection<((classes: LyClasses<typeof STYLES>) => StyleTemplate)> | ((classes: LyClasses<typeof STYLES>) => StyleTemplate); } export interface LyMenuVariables { menu?: LyMenuTheme; } const STYLE_PRIORITY = -1; export const STYLES = (theme: ThemeVariables & LyMenuVariables, ref: ThemeRef) => { const menu = ref.selectorsOf(STYLES); const { after } = theme; return { $name: LyMenu.и, $priority: STYLE_PRIORITY, root: () => ( theme.menu?.root && (theme.menu.root instanceof StyleCollection ? theme.menu.root.setTransformer(fn => fn(menu)).css : theme.menu.root(menu)) ), container: lyl `{ background: ${theme.background.primary.default} border-radius: 2px box-shadow: ${shadowBuilder(4)} display: block padding-top: 8px padding-bottom: 8px transform-origin: inherit pointer-events: all overflow: auto max-height: inherit max-width: inherit box-sizing: border-box }`, item: lyl `{ display: flex min-height: 48px border-radius: 0 width: 100% justify-content: flex-start font-weight: 400 ly-icon { margin-${after}: 16px } }`, itemSubMenuTrigger: () => lyl `{ padding-${after}: 32px &::after { width: 0 height: 0 border-style: solid border-width: 5px 0 5px 5px border-color: transparent transparent transparent currentColor content: "" display: inline-block position: absolute top: 50% ${after}: 16px transform: translateY(-50%) } }` }; }; const ANIMATIONS = [ trigger('transformMenu', [ transition('void => enter', group([ style({ opacity: 0, transform: 'scale(0.8)' }), animate('100ms linear', style({ opacity: 1 })), animate('120ms cubic-bezier(0, 0, 0.2, 1)', style({transform: 'scale(1)'})), ])) ]), trigger('transformMenuLeave', [ transition('* => void', animate('100ms 25ms linear', style({ opacity: 0 }))) ]) ]; /** Menu container */ @Component({ selector: 'ly-menu', animations: [...ANIMATIONS], templateUrl: 'menu.html', exportAs: 'lyMenu', providers: [ StyleRenderer ] }) export class LyMenu implements OnChanges, OnInit, AfterViewInit, OnDestroy { /** Menu Trigger */ @Input() set ref(value: LyMenuTriggerFor) { this._ref = value; this._menuRef = value._menuRef!; } get ref() { return this._ref; } /** Whether the menu has a backdrop. */ @Input() get hasBackdrop(): boolean { return this._hasBackdrop; } set hasBackdrop(value: boolean) { this._hasBackdrop = coerceBooleanProperty(value); } constructor( private _theme: LyTheme2, private _el: ElementRef, private _renderer: Renderer2, private _viewportRuler: ViewportRuler, readonly sRenderer: StyleRenderer ) { } /** @docs-private */ static readonly и = 'LyMenu'; static ngAcceptInputType_hasBackdrop: BooleanInput; /** * styles * @docs-private */ readonly classes = this.sRenderer.renderSheet(STYLES, true); /** Whether the menu is animating. */ _isAnimating: boolean; /** Whether the menu is destroying. */ _isDestroying: boolean; /** Emits whenever an animation on the menu completes. */ _animationDone = new Subject<AnimationEvent>(); private _menuRef: OverlayFactory<any>; /** * Destroy menu * @docs-private */ destroy: () => void; @ViewChild('container') _container?: ElementRef<HTMLDivElement>; @ContentChildren(forwardRef(() => LyMenuItem)) readonly menuItems?: QueryList<LyMenuItem>; private _ref: LyMenuTriggerFor; /** The point in the anchor where the menu `xAxis` will be attached. */ @Input() xAnchor: XPosition; /** The point in the anchor where the menu `yAxis` will be attached. */ @Input() yAnchor: YPosition; /** The x-axis position of the menu. */ @Input() xAxis: XPosition; /** The y-axis position of the menu. */ @Input() yAxis: YPosition; /** * Position where the menu will be placed. * @deprecated Use `xAxis` and` yAxis` together instead. */ @Input() placement: Placement; /** * The x-axis position of the menu. * @deprecated Use `xAxis` instead. */ @Input() xPosition: XPosition; /** * The y-axis position of the menu. * @deprecated Use `yAxis` instead. */ @Input() yPosition: YPosition; private _hasBackdrop: boolean = true; private _mouseenterListen?: () => void; private _mouseleaveListen?: () => void; @HostBinding('@transformMenuLeave') transformMenuLeave: unknown; ngOnChanges() { if (this.ref?._menuRef && this._container) { // Update backdrop this.ref._menuRef.updateBackdrop(this.ref._isItemSubMenuTrigger() ? false : this.hasBackdrop); this._updatePlacement(); this._checkBackdropAndOpenOnHover(); } } ngOnInit() { if (!this.ref) { throw new Error('LyMenu: require @Input() ref'); } } ngAfterViewInit() { if (this.ref._menuRef) { this.ref._menuRef.onResizeScroll = this._updatePlacement.bind(this); this.ref._menuRef.updateBackdrop(this.ref._isItemSubMenuTrigger() ? false : this.hasBackdrop); this._checkBackdropAndOpenOnHover(); } this._updatePlacement(); this.ref.menuOpened.emit(); Promise.resolve(null).then(() => { this.ref._setMenuOpenToTrue(); }); const hostTrigger = this._getHostMenuTrigger(); hostTrigger._menuDetached .pipe(take(1)) .subscribe(() => this._ref.closeMenu()); this._addOpenOnHover(); } ngOnDestroy() { this._removeOpenOnHoverListeners(); } private _checkBackdropAndOpenOnHover() { const hostTrigger = this._getHostMenuTrigger(); if (this.hasBackdrop && hostTrigger._menuOpenOnHoverRef?.openOnHover) { throw new Error(`${LyMenu.и}: Can't use [hasBackdrop] with [openOnHover] at the same time, set [hasBackdrop] to false to use [openOnHover]`); } } private _getHostMenuTrigger() { let menuTrigger = this.ref; while (menuTrigger._menu?.ref) { menuTrigger = menuTrigger._menu.ref; } return menuTrigger; } private _addOpenOnHover() { const hostTrigger = this._getHostMenuTrigger(); if (hostTrigger._menuOpenOnHoverRef?.openOnHover && !this._mouseenterListen && !this._mouseleaveListen) { hostTrigger._menuOpenOnHoverRef!._handleMouseEnterOrLeave(true); this._mouseenterListen = this._renderer .listen( this._el.nativeElement, 'mouseenter', () => hostTrigger._menuOpenOnHoverRef!._handleMouseEnterOrLeave(true) ); this._mouseleaveListen = this._renderer .listen( this._el.nativeElement, 'mouseleave', () => hostTrigger._menuOpenOnHoverRef!._handleMouseEnterOrLeave(false) ); } } /** Remove listeners */ private _removeOpenOnHoverListeners() { if (this._mouseenterListen) { this._mouseenterListen(); } if (this._mouseleaveListen) { this._mouseleaveListen(); } } /** Update Menu Position */ private _updatePlacement() { const el = this.ref._menuRef?.containerElement; const container = this._container?.nativeElement; // Do not update when not available if (!el || !container) { return; } // reset height & width this._renderer.setStyle(container, 'height', 'initial'); this._renderer.setStyle(container, 'width', 'initial'); const position = this.placement ? new Positioning(this.placement, this.xPosition, this.yPosition, this.ref._getHostElement(), el, this._theme.variables) : !this.ref._isItemSubMenuTrigger() ? new LyOverlayPosition(this._theme, this._viewportRuler, this.ref._getHostElement(), el) .setXAnchor(this.xAnchor) .setYAnchor(this.yAnchor) .setXAxis(this.xAxis) .setYAxis(this.yAxis) .setFlip(true) .build() : new LyOverlayPosition(this._theme, this._viewportRuler, this.ref._getHostElement(), el) .setXAnchor(XPosition.after) .setYAnchor(YPosition.above) .setFlip(true) .build(); if (position instanceof Positioning) { // set position deprecated this._renderer.setStyle(el, 'transform', `translate3d(${position.x}px, ${position.y}px, 0)`); this._renderer.setStyle(this._el.nativeElement, 'transform-origin', `${position.ox} ${position.oy} 0`); // set height & width deprecated this._renderer.setStyle(container, 'height', position.height === 'initial' ? '100%' : position.height); this._renderer.setStyle(container, 'width', position.width === 'initial' ? '100%' : position.width); } else { // set position this._renderer.setStyle(el, 'left', `${position.x}px`); this._renderer.setStyle(el, 'top', `${position.y}px`); this._renderer.setStyle(container, 'width', position.width ? `${position.width}px` : '100%'); this._renderer.setStyle(container, 'height', position.height ? `${position.height}px` : '100%'); this._renderer.setStyle(this._el.nativeElement, 'transform-origin', `${position.xo}px ${position.yo}px 0`); } } @HostListener('@transformMenuLeave.start', ['$event']) _onAnimationStart(event: AnimationEvent) { this._isAnimating = true; if (event.triggerName === 'transformMenuLeave' && event.toState === 'void') { this._isDestroying = true; } } @HostListener('@transformMenuLeave.done', ['$event']) _onAnimationDone(event: AnimationEvent) { this._animationDone.next(event); this._isAnimating = false; if (event.toState === 'void' && event.triggerName === 'transformMenuLeave') { this.ref.destroy(this._menuRef); } } } @Directive({ selector: '[ly-menu-item]', host: { '(click)': '_handleClick()', '(mouseenter)': '_handleMouseEnter()' } }) export class LyMenuItem { constructor( @Optional() private _menu: LyMenu, el: ElementRef, renderer: Renderer2 ) { renderer.addClass(el.nativeElement, _menu.classes.item); } private _itemSubMenuTrigger?: LyMenuTriggerFor; _handleClick() { if (this._menu.ref && this._menu.ref._menuRef) { if (!this._getItemSubMenuTrigger()) { let currentTrigger = this._menu.ref; while (currentTrigger) { currentTrigger.closeMenu(); currentTrigger = currentTrigger._menu?.ref; } } } } _handleMouseEnter() { const itemSubMenuTrigger = this._getItemSubMenuTrigger(); if (itemSubMenuTrigger && !this._menu._isDestroying) { if (this._menu._isAnimating) { this._menu._animationDone .pipe(take(1), delay(0, asapScheduler)) .subscribe(() => { itemSubMenuTrigger.openMenu(); this._closeOtherMenus(); }); } else { itemSubMenuTrigger.openMenu(); this._closeOtherMenus(); } } else { this._closeOtherMenus(); } } /** Except for this, close all menus */ private _closeOtherMenus() { this._menu.menuItems!.forEach(menuItem => { if (menuItem !== this) { menuItem._getItemSubMenuTrigger()?.closeMenu(); } }); } _setItemSubMenuTrigger(menuTrigger: LyMenuTriggerFor) { this._itemSubMenuTrigger = menuTrigger; } _getItemSubMenuTrigger() { return this._itemSubMenuTrigger; } } @Directive({ selector: '[lyMenuTriggerFor]', host: { '(click)': '_handleClick()' }, exportAs: 'lyMenuTriggerFor', providers: [ StyleRenderer ] }) export class LyMenuTriggerFor implements OnDestroy { readonly classes = this.sRenderer.renderSheet(STYLES); /** Current menuRef */ _menuRef?: OverlayFactory | null; private _menuOpen = false; private _destroying: boolean; _menuDetached = new Subject<void>(); _menuOpenOnHoverRef?: LyMenuOpenOnHover; /** Whether the menu is open. */ get menuOpen() { return this._menuOpen; } @Input() lyMenuTriggerFor: TemplateRef<any>; /** Data to be passed to the menu. */ @Input('lyMenuTriggerData') menuData: any; @Output() readonly menuOpened = new EventEmitter<void>(); @Output() readonly menuClosed = new EventEmitter<void>(); constructor( private elementRef: ElementRef, private overlay: LyOverlay, @Optional() private _menuItem: LyMenuItem, readonly sRenderer: StyleRenderer, @Optional() public _menu: LyMenu ) { if (this._isItemSubMenuTrigger()) { _menuItem._setItemSubMenuTrigger(this); sRenderer.addClass(this.classes.itemSubMenuTrigger); } } ngOnDestroy() { // Not force destruction if it is already being destroyed if (!this._destroying) { this.closeMenu(); } this._menuDetached.complete(); } _handleClick() { if (!this._isItemSubMenuTrigger()) { this.toggleMenu(); } } /** Opens the menu */ openMenu() { if (!this._menuRef) { this._menuRef = this.overlay.create(this.lyMenuTriggerFor, { $implicit: this, data: this.menuData }, { styles: { top: 0, left: 0, pointerEvents: null }, fnDestroy: this.detach.bind(this), hasBackdrop: false }); } } /** Closes the menu */ closeMenu() { this.detach(); } /** Toggle menu */ toggleMenu() { if (this._menuRef) { this.closeMenu(); } else { this.openMenu(); } } /** @docs-private */ detach() { if (this._menuRef) { this._menuRef.detach(); this._menuRef = null; this._destroying = true; this._menuDetached.next(); } } /** @docs-private */ destroy(menuRef: OverlayFactory<any>) { this.menuClosed.emit(null!); menuRef.remove(); this._destroying = false; Promise.resolve(null).then(() => this._menuOpen = false); } _getHostElement() { return this.elementRef.nativeElement; } _setMenuOpenToTrue() { this._menuOpen = true; } /** * @docs-private */ _isItemSubMenuTrigger() { return !!this._menuItem; } } @Directive({ selector: '[lyMenuTriggerFor][openOnHover]', host: { '(mouseenter)': '_handleMouseEnterOrLeave(true)', '(mouseleave)': '_handleMouseEnterOrLeave(false)' } }) export class LyMenuOpenOnHover implements OnDestroy { private _events = new Subject<boolean>(); /** Whether menu should open on hover. */ @Input() get openOnHover(): boolean { return this._openOnHover; } set openOnHover(value: boolean) { this._openOnHover = coerceBooleanProperty(value); Promise.resolve(null) .then(() => this._openOnHover ? this._trigger._menuOpenOnHoverRef = this : delete this._trigger._menuOpenOnHoverRef); } private _openOnHover: boolean = true; constructor( private _trigger: LyMenuTriggerFor ) { _trigger._menuOpenOnHoverRef = this; this._events .pipe( debounceTime(200) ) .subscribe(enterOrLeave => { if (this.openOnHover) { if (enterOrLeave) { _trigger.openMenu(); } else { _trigger.closeMenu(); } } }); } ngOnDestroy() { this._events.complete(); } /** Handle mouseenter */ _handleMouseEnterOrLeave(enter: true): void; /** Handle mouseleave */ _handleMouseEnterOrLeave(leave: false): void; /** Handle mouseenter or mouseleave */ _handleMouseEnterOrLeave(leaveOrEnter: boolean): void { if (this.openOnHover) { if (leaveOrEnter) { this._trigger.openMenu(); } this._events.next(leaveOrEnter); } } }
the_stack
import { DelimArray } from '@looker/sdk-rtl' import { TestConfig } from './testUtils' import type { IEnumType } from './sdkModels' import { KotlinGen } from './kotlin.gen' const config = TestConfig() const apiTestModel = config.apiTestModel const gen = new KotlinGen(apiTestModel) const indent = '' describe('Kotlin generator', () => { describe('comment header', () => { it('is empty with no comment', () => { expect(gen.commentHeader(indent, '')).toEqual('') }) it('is four lines with a two line comment', () => { const expected = `/** * foo * bar */ ` expect(gen.commentHeader(indent, 'foo\nbar')).toEqual(expected) }) }) describe('types', () => { it('enum type', () => { const type = apiTestModel.types.PermissionType as IEnumType expect(type).toBeDefined() expect(type.values).toEqual(['view', 'edit']) const expected = `/** * Type of permission: "view" or "edit" Valid values are: "view", "edit". */ enum class PermissionType : Serializable { view, edit }` const actual = gen.declareType('', type) expect(actual).toEqual(expected) }) it('noComment enum type', () => { const type = apiTestModel.types.PermissionType as IEnumType expect(type).toBeDefined() expect(type.values).toEqual(['view', 'edit']) const expected = `enum class PermissionType : Serializable { view, edit }` gen.noComment = true const actual = gen.declareType('', type) gen.noComment = false expect(actual).toEqual(expected) }) // TODO a different PR broke this, need to fix it it.skip('special needs', () => { const type = apiTestModel.types.HyphenType const actual = gen.declareType('', type) const expected = `/** * @property project_name A normal variable name (read-only) * @property project_digest A hyphenated property name (read-only) * @property computation_time A spaced out property name (read-only) */ data class HyphenType ( var project_name: String? = null, @SerializedName("project-digest") var project_digest: String? = null, @SerializedName("computation time") var computation_time: Float? = null ) : Serializable` expect(actual).toEqual(expected) }) }) describe('makeTheCall', () => { const fields = 'id,user_id,title,description' it('handles no params', () => { const inputs = {} const method = apiTestModel.methods.look const actual = gen.makeTheCall(method, inputs) const expected = 'val response = await sdk.ok<LookWithQuery>(sdk.look())' expect(actual).toEqual(expected) }) it('assigns single param', () => { const inputs = { look_id: 17 } const method = apiTestModel.methods.look const actual = gen.makeTheCall(method, inputs) const expected = `val response = await sdk.ok<LookWithQuery>(sdk.look(17))` expect(actual).toEqual(expected) }) it('assigns simple params', () => { const inputs = { look_id: 17, fields } const method = apiTestModel.methods.look const actual = gen.makeTheCall(method, inputs) const expected = `val response = await sdk.ok<LookWithQuery>(sdk.look( 17, fields = "${fields}"))` expect(actual).toEqual(expected) }) it('assigns a body param', () => { const body = { title: 'test title', description: 'gen test', query: { model: 'the_look', view: 'users', total: true, }, } const inputs = { look_id: 17, body, fields } const method = apiTestModel.methods.update_look const actual = gen.makeTheCall(method, inputs) const expected = `val response = await sdk.ok<LookWithQuery>(sdk.update_look( 17, WriteLookWithQuery( title = "test title", description = "gen test", query = WriteQuery( model = "the_look", view = "users", total = true ) ), fields = "id,user_id,title,description"))` expect(actual).toEqual(expected) }) it('treats void response type as String', () => { const inputs = { look_id: 17, result_format: 'png', limit: 10 } const method = apiTestModel.methods.run_look const actual = gen.makeTheCall(method, inputs) const expected = `val response = await sdk.ok<String>(sdk.run_look( 17, "png", limit = 10))` expect(actual).toEqual(expected) }) it('assigns an enum', () => { const inputs = { body: { query_id: 1, result_format: 'csv', }, } const method = apiTestModel.methods.create_query_task const actual = gen.makeTheCall(method, inputs) const expected = `val response = await sdk.ok<QueryTask>(sdk.create_query_task( WriteCreateQueryTask( query_id = 1, result_format = ResultFormat.csv )))` expect(actual).toEqual(expected) }) it('assigns a DelimArray', () => { const inputs = { tests: new DelimArray<string>(['1', '2', '3']), } const method = apiTestModel.methods.test_connection const actual = gen.makeTheCall(method, inputs) const expected = `val response = await sdk.ok<Array<DBConnectionTestResult>>(sdk.test_connection( tests = DelimArray<String>( arrayOf( "1", "2", "3" ) )))` expect(actual).toEqual(expected) }) it('assigns simple and complex arrays', () => { const body = { pivots: ['one', 'two', 'three'], sorts: ['a'], source_queries: [ { name: 'first query', query_id: 1, merge_fields: [ { field_name: 'merge_1', source_field_name: 'source_1', }, ], }, { name: 'second query', query_id: 2, merge_fields: [ { field_name: 'merge_2', source_field_name: 'source_2', }, ], }, ], } const inputs = { body, fields } const method = apiTestModel.methods.create_merge_query const actual = gen.makeTheCall(method, inputs) const expected = `val response = await sdk.ok<MergeQuery>(sdk.create_merge_query( body = WriteMergeQuery( pivots = arrayOf( "one", "two", "three" ), sorts = arrayOf("a"), source_queries = arrayOf( MergeQuerySourceQuery( merge_fields = arrayOf( MergeFields( field_name = "merge_1", source_field_name = "source_1" ) ), name = "first query", query_id = 1 ), MergeQuerySourceQuery( merge_fields = arrayOf( MergeFields( field_name = "merge_2", source_field_name = "source_2" ) ), name = "second query", query_id = 2 ) ) ), fields = "id,user_id,title,description"))` expect(actual).toEqual(expected) }) it('assigns dictionaries', () => { const query = { connection_name: 'looker', model_name: 'the_look', vis_config: { first: 1, second: 'two' }, } const inputs = { body: query } const method = apiTestModel.methods.create_sql_query const expected = `val response = await sdk.ok<SqlQuery>(sdk.create_sql_query( SqlQueryCreate( connection_name = "looker", model_name = "the_look", vis_config = mapOf( "first" to 1, "second" to "two" ) )))` const actual = gen.makeTheCall(method, inputs) expect(actual).toEqual(expected) }) describe('hashValue', () => { it('assigns a hash with heterogeneous values', () => { const token = { access_token: 'backstage', token_type: 'test', expires_in: 10, } const oneItem = [1] const threeItems = ['Abe', 'Zeb', token] const inputs = { item: oneItem, items: threeItems, first: 1, second: 'two', third: false, token, } const expected = `mapOf( "item" to arrayOf(1), "items" to arrayOf( "Abe", "Zeb", mapOf( "access_token" to "backstage", "token_type" to "test", "expires_in" to 10 ) ), "first" to 1, "second" to "two", "third" to false, "token" to mapOf( "access_token" to "backstage", "token_type" to "test", "expires_in" to 10 ) )` const actual = gen.hashValue('', inputs) expect(actual).toEqual(expected) }) }) describe('assignType', () => { it('assigns a complex type', () => { const inputs = { name: 'first query', query_id: 1, merge_fields: [ { field_name: 'merge_1', source_field_name: 'source_1', }, ], } const type = apiTestModel.types.MergeQuerySourceQuery expect(type).toBeDefined() const expected = `MergeQuerySourceQuery( merge_fields = arrayOf( MergeFields( field_name = "merge_1", source_field_name = "source_1" ) ), name = "first query", query_id = 1 )` const actual = gen.assignType(gen.indentStr, type, inputs) expect(actual).toEqual(expected) }) }) describe('arrayValue', () => { it('assigns complex arrays', () => { const sourceQueries = [ { name: 'first query', query_id: 1, merge_fields: [ { field_name: 'merge_1', source_field_name: 'source_1', }, ], }, { name: 'second query', query_id: 2, merge_fields: [ { field_name: 'merge_2', source_field_name: 'source_2', }, ], }, ] const props = apiTestModel.types.WriteMergeQuery.properties const type = props.source_queries.type expect(type).toBeDefined() const actual = gen.arrayValue('', type, sourceQueries) const expected = `arrayOf( MergeQuerySourceQuery( merge_fields = arrayOf( MergeFields( field_name = "merge_1", source_field_name = "source_1" ) ), name = "first query", query_id = 1 ), MergeQuerySourceQuery( merge_fields = arrayOf( MergeFields( field_name = "merge_2", source_field_name = "source_2" ) ), name = "second query", query_id = 2 ) )` expect(actual).toEqual(expected) }) }) }) })
the_stack
import DebounceLink from './DebounceLink'; import { ObservableEvent, TestSequenceLink, toResultValue, assertObservableSequence, } from './TestUtils'; import { gql, execute, GraphQLRequest, ApolloLink, } from '@apollo/client'; import { ExecutionResult, } from 'graphql'; describe('DebounceLink', () => { let link: ApolloLink; let testLink: TestSequenceLink; let debounceLink: DebounceLink; const DEBOUNCE_TIMEOUT = 500; function makeSimpleResponse(value: string): ExecutionResult { return { data: { hello: value, }, }; } const testResponse = makeSimpleResponse('world'); function makeSimpleSequence(response: ExecutionResult): ObservableEvent[] { return [ { type: 'next', value: response, }, { type: 'complete', }, ]; } function makeSimpleOp(sequence: ObservableEvent[], debounceKey: string, debounceTimeout: number): GraphQLRequest { return { query: gql`{ hello }`, context: { debounceKey, debounceTimeout, testSequence: sequence, }, }; } function getTestSubscriber(observedSequence: ObservableEvent[]) { return { next(value: ExecutionResult) { observedSequence.push({ type: 'next', value, }); }, error(e: Error) { observedSequence.push({ type: 'error', value: e, }); }, complete() { observedSequence.push({ type: 'complete' }); }, }; } const testSequence = makeSimpleSequence(testResponse); const op = makeSimpleOp( testSequence, 'key1', ); const testError = new Error('Hello darkness my old friend'); const testErrorSequence = [{ type: 'error', value: testError }]; const opWithError: GraphQLRequest = { query: gql`{ hello }`, context: { debounceKey: 'key1', testSequence: testErrorSequence, }, }; beforeEach(() => { jest.useFakeTimers(); testLink = new TestSequenceLink(); debounceLink = new DebounceLink(DEBOUNCE_TIMEOUT); link = ApolloLink.from([debounceLink, testLink]); }); it('forwards the operation', () => { return new Promise((resolve, reject) => { execute(link, op).subscribe({ next: (data) => undefined, error: (error) => reject(error), complete: () => { expect(testLink.operations.length).toBe(1); expect(testLink.operations[0].query).toEqual(op.query); resolve(); }, }); jest.runAllTimers(); }); }); it('forwards the operation if context.debounceKey is not defined', () => { const opWithoutKey: GraphQLRequest = { query: gql`{ hello }`, context: { testSequence: makeSimpleSequence(testResponse), }, }; return new Promise((resolve, reject) => { execute(link, opWithoutKey).subscribe({ next: (data) => undefined, error: (error) => reject(error), complete: () => { expect(testLink.operations.length).toBe(1); expect(testLink.operations[0].query).toEqual(op.query); resolve(); }, }); jest.runAllTimers(); }); }); it('calls next and complete as expected', () => { return Promise.resolve(assertObservableSequence( execute(link, op), [ { type: 'next', value: testResponse }, { type: 'complete' }, ], () => jest.runAllTimers(), )); }); it('passes through errors', () => { return Promise.resolve(assertObservableSequence( execute(link, opWithError), [ { type: 'error', value: testError }, ], () => jest.runAllTimers(), )); }); it('debounces multiple queries within the debounce interval', () => { const observedSequence: ObservableEvent[] = []; const subscriber = getTestSubscriber(observedSequence); const s1 = execute(link, op).subscribe(subscriber); jest.runTimersToTime(DEBOUNCE_TIMEOUT - 1); // check that query did not execute. expect(testLink.operations.length).toBe(0); expect(observedSequence.length).toBe(0); // make another query, different params. const op2 = makeSimpleOp( makeSimpleSequence(makeSimpleResponse('op2')), 'key1', ); const s2 = execute(link, op2).subscribe(subscriber); jest.runTimersToTime(DEBOUNCE_TIMEOUT - 1); // check that query did not execute expect(testLink.operations.length).toBe(0); expect(observedSequence.length).toBe(0); // make another query, different params const op3sequence = makeSimpleSequence(makeSimpleResponse('op3')); const op3 = makeSimpleOp( op3sequence, 'key1', ); op3.operationName = 'op3'; const s3 = execute(link, op3).subscribe(subscriber); jest.runTimersToTime(DEBOUNCE_TIMEOUT + 1); // check that all queries returned the sequence of the last query. const expectedSequence = [ toResultValue(op3sequence[0]), toResultValue(op3sequence[0]), toResultValue(op3sequence[0]), toResultValue(op3sequence[1]), toResultValue(op3sequence[1]), toResultValue(op3sequence[1]), ]; expect(testLink.operations.length).toEqual(1); expect(testLink.operations[0].operationName).toBe(op3.operationName); expect(observedSequence.length).toEqual(6); expect(observedSequence).toEqual(expectedSequence); s1.unsubscribe(); s2.unsubscribe(); s3.unsubscribe(); }); it('debounces multiple queries within the custom debounce interval provided in context', () => { const observedSequence: ObservableEvent[] = []; const subscriber = getTestSubscriber(observedSequence); const customDebounceTimeout = DEBOUNCE_TIMEOUT / 4; const op0 = makeSimpleOp( testSequence, 'key1', customDebounceTimeout, ); const s1 = execute(link, op0).subscribe(subscriber); jest.runTimersToTime(customDebounceTimeout - 1); // check that query did not execute. expect(testLink.operations.length).toBe(0); expect(observedSequence.length).toBe(0); // make another query, different params. const op2 = makeSimpleOp( makeSimpleSequence(makeSimpleResponse('op2')), 'key1', customDebounceTimeout, ); const s2 = execute(link, op2).subscribe(subscriber); jest.runTimersToTime(customDebounceTimeout - 1); // check that query did not execute expect(testLink.operations.length).toBe(0); expect(observedSequence.length).toBe(0); // make another query, different params const op3sequence = makeSimpleSequence(makeSimpleResponse('op3')); const op3 = makeSimpleOp( op3sequence, 'key1', customDebounceTimeout, ); op3.operationName = 'op3'; const s3 = execute(link, op3).subscribe(subscriber); jest.runTimersToTime(customDebounceTimeout + 1); // check that all queries returned the sequence of the last query. const expectedSequence = [ toResultValue(op3sequence[0]), toResultValue(op3sequence[0]), toResultValue(op3sequence[0]), toResultValue(op3sequence[1]), toResultValue(op3sequence[1]), toResultValue(op3sequence[1]), ]; expect(testLink.operations.length).toEqual(1); expect(testLink.operations[0].operationName).toBe(op3.operationName); expect(observedSequence.length).toEqual(6); expect(observedSequence).toEqual(expectedSequence); s1.unsubscribe(); s2.unsubscribe(); s3.unsubscribe(); }); it('does not debounce queries that are not within the interval', () => { // make one query. // run timer for debounce + 1 // check that query executed. // make one query. // run timer for debounce + 1 // check that query executed. const observedSequence: ObservableEvent[] = []; const subscriber = getTestSubscriber(observedSequence); const s1 = execute(link, op).subscribe(subscriber); jest.runTimersToTime(DEBOUNCE_TIMEOUT + 1); // check that query did not execute. expect(testLink.operations.length).toBe(1); expect(observedSequence.length).toBe(2); // make another query, different params. const op2sequence = makeSimpleSequence(testResponse); const op2 = makeSimpleOp( op2sequence, 'key1', ); const s2 = execute(link, op2).subscribe(subscriber); jest.runTimersToTime(DEBOUNCE_TIMEOUT + 1); // check that query executed expect(testLink.operations.length).toBe(2); expect(observedSequence.length).toBe(4); const expectedSequence = [ toResultValue(testSequence[0]), toResultValue(testSequence[1]), toResultValue(op2sequence[0]), toResultValue(op2sequence[1]), ]; expect(observedSequence).toEqual(expectedSequence); s1.unsubscribe(); s2.unsubscribe(); }); it('does not debounce queries with different debounceKey (even within the interval)', () => { // make query // make another query with different debounceKey // run timer for debounce +1. // check that both queries ran and returned different values const observedSequence: ObservableEvent[] = []; const subscriber = getTestSubscriber(observedSequence); const s1 = execute(link, op).subscribe(subscriber); // make another query, different debounceKey. const op2sequence = makeSimpleSequence(testResponse); const op2 = makeSimpleOp( op2sequence, 'key2', ); const observedSequence2: ObservableEvent[] = []; // Using a different subscriber, just for fun. const subscriber2 = getTestSubscriber(observedSequence2); const s2 = execute(link, op2).subscribe(subscriber2); jest.runTimersToTime(DEBOUNCE_TIMEOUT + 1); // check that both queries executed expect(testLink.operations.length).toBe(2); expect(observedSequence.length).toBe(2); expect(observedSequence2.length).toBe(2); const expectedSequence = [ toResultValue(testSequence[0]), toResultValue(testSequence[1]), ]; const expectedSequence2 = [ toResultValue(op2sequence[0]), toResultValue(op2sequence[1]), ]; expect(observedSequence).toEqual(expectedSequence); expect(observedSequence2).toEqual(expectedSequence2); s1.unsubscribe(); s2.unsubscribe(); }); it('does not make any query if you unsubscribe before interval is over', () => { // make query // run timer for debounce -1 // unsubscribe // run timer for debounce +1. // check that nothing ran const observedSequence: ObservableEvent[] = []; const subscriber = getTestSubscriber(observedSequence); const s1 = execute(link, op).subscribe(subscriber); jest.runTimersToTime(DEBOUNCE_TIMEOUT - 1); s1.unsubscribe(); jest.runTimersToTime(DEBOUNCE_TIMEOUT + 1); expect(testLink.operations.length).toBe(0); expect(observedSequence.length).toBe(0); }); it('correctly debounces a query that errors', () => { const observedSequence: ObservableEvent[] = []; const subscriber = getTestSubscriber(observedSequence); const s1 = execute(link, opWithError).subscribe(subscriber); jest.runTimersToTime(DEBOUNCE_TIMEOUT + 1); expect(testLink.operations.length).toBe(1); expect(observedSequence).toEqual(testErrorSequence); s1.unsubscribe(); }); it('runs the second to last query if the last one was unsubscribed from', () => { // make query // make another query // run timer for debounce -1 // unsubscribe from second query // run timer for debounce +1. // check that first query executed and returned value const observedSequence: ObservableEvent[] = []; const subscriber = getTestSubscriber(observedSequence); const s1 = execute(link, op).subscribe(subscriber); // make another query const op2sequence = makeSimpleSequence(testResponse); const op2 = makeSimpleOp( op2sequence, 'key1', ); const observedSequence2: ObservableEvent[] = []; // Using a different subscriber, just for fun. const subscriber2 = getTestSubscriber(observedSequence2); const s2 = execute(link, op2).subscribe(subscriber2); jest.runTimersToTime(DEBOUNCE_TIMEOUT - 1); s2.unsubscribe(); jest.runTimersToTime(DEBOUNCE_TIMEOUT + 1); expect(testLink.operations.length).toBe(1); expect(observedSequence.length).toBe(2); expect(observedSequence2.length).toBe(0); const expectedSequence = [ toResultValue(testSequence[0]), toResultValue(testSequence[1]), ]; expect(observedSequence).toEqual(expectedSequence); s1.unsubscribe(); }); });
the_stack
import cloneDeep from 'lodash/cloneDeep'; import { CollectionNode, CollectionNodeBackendDict, } from 'domain/collection/collection-node.model'; import { CollectionPlaythrough, CollectionPlaythroughBackendDict } from 'domain/collection/collection-playthrough.model'; interface ExplorationIdToNodeIndexMap { [explorationId: string]: number; } export interface CollectionBackendDict { // When creating a new collection, properties below are always // initialized with null values. These are null until populated // from the backend and provided themselves by the user. 'id': string | null; 'title': string | null; 'objective': string | null; 'language_code': string | null; 'tags': string[] | null; 'schema_version': number | null; 'category': string | null; 'version': number | null; 'playthrough_dict': CollectionPlaythroughBackendDict; 'nodes': CollectionNodeBackendDict[]; } export class Collection { id: string | null; title: string | null; objective: string | null; languageCode: string | null; tags: string[] | null; playthrough: CollectionPlaythrough; category: string | null; version: number | null; schemaVersion: number | null; nodes: CollectionNode[]; explorationIdToNodeIndexMap: ExplorationIdToNodeIndexMap = {}; constructor( id: string | null, title: string | null, objective: string | null, languageCode: string | null, tags: string[] | null, playthrough: CollectionPlaythrough, category: string | null, version: number | null, schemaVersion: number | null, nodes: CollectionNode[]) { this.id = id; this.title = title; this.objective = objective; this.languageCode = languageCode; this.tags = tags; this.category = category; this.version = version; this.schemaVersion = schemaVersion; this.playthrough = playthrough; this.nodes = []; // This map acts as a fast way of looking up a collection node for a given // exploration ID. this.explorationIdToNodeIndexMap = {}; for (var i = 0; i < nodes.length; i++) { this.nodes[i] = nodes[i]; var explorationId = this.nodes[i].getExplorationId(); this.explorationIdToNodeIndexMap[explorationId] = i; } } static create(collectionBackendObject: CollectionBackendDict): Collection { let collectionNodes = collectionBackendObject.nodes.map( node => CollectionNode.create(node)); let collectionPlaythrough = ( CollectionPlaythrough.createFromBackendObject( collectionBackendObject.playthrough_dict)); return new Collection( collectionBackendObject.id, collectionBackendObject.title, collectionBackendObject.objective, collectionBackendObject.language_code, collectionBackendObject.tags, collectionPlaythrough, collectionBackendObject.category, collectionBackendObject.version, collectionBackendObject.schema_version, collectionNodes); } // Create a new, empty collection. This is not guaranteed to pass validation // tests. static createEmptyCollection(): Collection { let emptyCollectionPlaythrough = CollectionPlaythrough.create(null, []); return new Collection( null, null, null, null, null, emptyCollectionPlaythrough, null, null, null, []); } getId(): string | null { return this.id; } getTitle(): string | null { return this.title; } setTitle(title: string | null): void { this.title = title; } getCategory(): string | null { return this.category; } getSchemaVersion(): number | null { return this.schemaVersion; } getPlaythrough(): CollectionPlaythrough { return this.playthrough; } setCategory(category: string | null): void { this.category = category; } getObjective(): string | null { return this.objective; } setObjective(objective: string | null): void { this.objective = objective; } getLanguageCode(): string | null { return this.languageCode; } setLanguageCode(languageCode: string | null): void { this.languageCode = languageCode; } getTags(): string[] | null { return this.tags; } setTags(tags: string[] | null): void { this.tags = tags; } getVersion(): number | null { return this.version; } // Adds a new frontend collection node domain object to this collection. // This will return true if the node was successfully added, or false if the // given collection node references an exploration ID already referenced by // another node within this collection. Changes to the provided object will // be reflected in this collection. addCollectionNode(collectionNodeObject: CollectionNode): boolean { var explorationId = collectionNodeObject.getExplorationId(); if (!this.explorationIdToNodeIndexMap.hasOwnProperty(explorationId)) { this.explorationIdToNodeIndexMap[explorationId] = this.nodes.length; this.nodes.push(collectionNodeObject); return true; } return false; } // This will swap 2 nodes of the collection and update the exploration id // to node index map accordingly. swapCollectionNodes(firstIndex: number, secondIndex: number): boolean { if (firstIndex >= this.nodes.length || secondIndex >= this.nodes.length || firstIndex < 0 || secondIndex < 0) { return false; } var firstIndexId = this.nodes[firstIndex].getExplorationId(); var secondIndexId = this.nodes[secondIndex].getExplorationId(); var temp = this.nodes[firstIndex]; this.nodes[firstIndex] = this.nodes[secondIndex]; this.nodes[secondIndex] = temp; this.explorationIdToNodeIndexMap[firstIndexId] = secondIndex; this.explorationIdToNodeIndexMap[secondIndexId] = firstIndex; return true; } // Attempts to remove a collection node from this collection given the // specified exploration ID. Returns whether the collection node was // removed, which depends on whether any collection nodes reference the // given exploration ID. deleteCollectionNode(explorationId: string): boolean { // TODO(bhenning): Consider whether the removed collection node should be // invalidated, leading to errors if its mutated in the future. This might // help prevent bugs where collection nodes are stored and changed after // being removed from a collection. if (this.explorationIdToNodeIndexMap.hasOwnProperty(explorationId)) { var nodeIndex = this.explorationIdToNodeIndexMap[explorationId]; delete this.explorationIdToNodeIndexMap[explorationId]; this.nodes.splice(nodeIndex, 1); // Update all node exploration ID map references past the removed index // to ensure they are still pointing to correct indexes. for (var i = nodeIndex; i < this.nodes.length; i++) { var nodeExpId = this.nodes[i].getExplorationId(); this.explorationIdToNodeIndexMap[nodeExpId] = i; } return true; } return false; } // Deletes all collection nodes within this collection. clearCollectionNodes(): void { // Clears the existing array in-place, since there may be Angular bindings // to this array and they can't be reset to empty arrays.See for context: // http://stackoverflow.com/a/1232046 this.nodes.length = 0; this.explorationIdToNodeIndexMap = {}; } // Returns whether any collection nodes in this collection reference the // provided exploration ID. containsCollectionNode(explorationId: string): boolean { return this.explorationIdToNodeIndexMap.hasOwnProperty(explorationId); } // Returns a collection node given an exploration ID, or undefined if no // collection node within this collection references the provided // exploration ID. getCollectionNodeByExplorationId(expId: string): CollectionNode { return this.nodes[this.explorationIdToNodeIndexMap[expId]]; } // Returns a list of collection node objects for this collection. Changes to // nodes returned by this function will be reflected in the collection. // Changes to the list itself will not be reflected in this collection. getCollectionNodes(): CollectionNode[] { return this.nodes.slice(); } getCollectionNodeCount(): number { return this.nodes.length; } // Returns the reference to the internal nodes array; this function is only // meant to be used for Angular bindings and should never be used in code. // Please use getCollectionNodes() and related functions, instead. Please // also be aware this exposes internal state of the collection domain // object, so changes to the array itself may internally break the domain // object. getBindableCollectionNodes(): CollectionNode[] { return this.nodes; } // Returns the collection node which is initially available to play // by the player. getStartingCollectionNode(): CollectionNode | null { if (this.nodes.length === 0) { return null; } else { return this.nodes[0]; } } // Returns a list of all exploration IDs referenced by this collection. // Changes to the list itself will not be reflected in this collection. getExplorationIds(): string[] { return cloneDeep(Object.keys(this.explorationIdToNodeIndexMap)); } // Reassigns all values within this collection to match the existing // collection. This is performed as a deep copy such that none of the // internal, bindable objects are changed within this collection. Note that // the collection nodes within this collection will be completely redefined // as copies from the specified collection. copyFromCollection(otherCollection: Collection): void { this.id = otherCollection.getId(); this.setTitle(otherCollection.getTitle()); this.setCategory(otherCollection.getCategory()); this.setObjective(otherCollection.getObjective()); this.setLanguageCode(otherCollection.getLanguageCode()); this.setTags(otherCollection.getTags()); this.version = otherCollection.getVersion(); this.playthrough = otherCollection.getPlaythrough(); this.schemaVersion = otherCollection.getSchemaVersion(); this.clearCollectionNodes(); var nodes = otherCollection.getCollectionNodes(); for (var i = 0; i < nodes.length; i++) { this.addCollectionNode(cloneDeep(nodes[i])); } } }
the_stack
import log from "../../log"; import { UploadDirectoryPath, WorkDirectoryPath, DataDirectoryPath, TReturnData, ExportDirectoryPath, } from "../../../types/module/data/data.types"; import { TWorkspaceCreateData, TWorkspaceUpdateData, TWorkspaceData, TReturnWorkspaceData, } from "../../../types/module/data/service/workspace/workspace.type"; import { setJsonData, getJsonData, isExists, removeData, handle, searchWorkspaceFiles } from "../etc/fileManager"; import DataUploadManager from "../etc/uploadManager"; import fs from "fs"; import simpleGit from "simple-git"; import { zip } from "zip-a-folder"; import { TUploadFileLanguageToSize } from "../../../types/module/data/service/etc/file.types"; import path from "path"; import { v4 as uuidv4 } from "uuid"; import { TDockerCreateData, TDockerUpdateData } from "../../../types/module/data/service/workspace/docker.types"; import DataDockerManager from "./dockerManager"; import { ResponseCode } from "../../../constants/response"; import { getTime } from "../../datetime"; import os from "os"; import DataAlarmManager from "../alarm/alarmManager"; const workspaceFileName = "workspaceInfo.json"; export default class DataWorkspaceManager { /** * * @param workspaceId ID that you want to know if workspace's path exists * @param workspacePath function that you want to know if workspace's path exists * @description check if path exists * @returns true if path exists, false if not */ static isExists(workspaceId: string, workspacePath: (workspaceId: string) => string) { return isExists(workspacePath(workspaceId)); } /** * * @description get workspace data path * @returns path that workspace data path */ static getWorkspaceDefaultPath() { return `${DataDirectoryPath}/workspace`; } /** * * @param workspaceId ID that you want to get work path of ID's workspace * @description get ID's workspace work path * @returns ID's workspace work path */ static getWorkspaceWorkPath(workspaceId: string) { return `${WorkDirectoryPath}/workspace/${workspaceId}`; } /** * * @param workspaceId ID that you want to get data path of ID's workspace * @description get ID's workspace data path * @returns ID's workspace data path */ static getWorkspaceDataPath(workspaceId: string) { return `${DataDirectoryPath}/workspace/${workspaceId}`; } /** * * @param workspaceId ID that you want to get workspace infomation of ID's workspace * @description get ID's workspace infomation * @returns ID's workspace infomation */ static getWorkspaceInfo(workspaceId: string) { const defaultPath = this.getWorkspaceDataPath(workspaceId); const workspacePath = `${defaultPath}/${workspaceFileName}`; if (!isExists(workspacePath)) { return undefined; } return getJsonData(workspacePath) as TWorkspaceData; } /** * * @param workspaceId ID that you want to set workspace infomation of ID's workspace * @param data data that you want to set workspace infomation * @description set ID's workspace infomation * @returns true if setting infomation succeed, false if failed */ static setWorkspaceInfo(workspaceId: string, data: TWorkspaceData | TWorkspaceCreateData | TWorkspaceUpdateData) { const defaultPath = this.getWorkspaceDataPath(workspaceId); if (!isExists(defaultPath)) { return false; } const workspacePath = `${defaultPath}/${workspaceFileName}`; return setJsonData(workspacePath, data); } /** * * @param workspaceId ID that you want to compare * @param workspaceName name that you want to compare * @description compare workspace name to ID's workspace name * @returns true if workspaceId's name is same to workspace name, false if different */ static compareWorkspaceName(workspaceId: string, workspaceName?: string) { return (this.getWorkspaceInfo(workspaceId) as TWorkspaceData).name === workspaceName; } /** * * @param userId user ID that you want to know if he is a creator * @param workspaceId workspace ID to compare with userid to see if he is a creator. * @description check if user is a creator of workspace * @returns true if workspace's creator is userId, false if not */ static isWorkspaceCreator(userId: string, workspaceId: string) { return (this.getWorkspaceInfo(workspaceId) as TWorkspaceData)?.creator === userId; } /** * * @param userId user ID that you want to know if he is participant of workspace * @param workspaceId workspace ID to see if userId is a participant of workerspace. * @description check if user is a participant of workspace * @returns true if user ID is a participant of workspace, false if not */ static isWorkspaceParticipants(userId: string, workspaceId: string) { return this.getWorkspaceInfo(workspaceId)?.participants?.includes(userId); } /** * * @param userId user ID that you want to know if he has authority of this workspace * @param workspaceId workspace ID to see if user ID has authority of this workspace * @param participantIncluded check true if you want to allow authority to participant, check false if not * @description check if user has authority of this workspace * @returns true if user ID has authority of this workspace, false if not */ static canEditWorkspace(userId: string, workspaceId: string, participantIncluded: boolean) { return this.isWorkspaceCreator(userId, workspaceId) || participantIncluded ? this.isWorkspaceParticipants(userId, workspaceId) : false; } /** * * @param userId user ID to get workspace ID * @param workspaceName workspace name to get workspace ID * @description get workspace ID from user ID, workspace name * @returns workspace ID that userId has authority and workspace's name is workspaceName */ static getWorkspaceId(userId: string, workspaceName: string) { return fs.readdirSync(this.getWorkspaceDefaultPath()).find((workspaceId) => { const workspaceInfo = this.getWorkspaceInfo(workspaceId); return workspaceInfo ? this.canEditWorkspace(userId, workspaceId, true) && workspaceInfo.name === workspaceName : false; }); } /** * * @param workspaceId workspace ID to be downloaded from git url * @param source object that contains git url * @description git clone from git url * @returns true if succeed, false if not */ static gitCloneFromURL( workspaceId: string, source: { gitUrl?: string; } ) { const clonePath = DataWorkspaceManager.getWorkspaceWorkPath(workspaceId); if (!fs.existsSync(clonePath)) { fs.mkdirSync(clonePath, { recursive: true }); } try { if (source.gitUrl === undefined) { log.error(`invalid git URL`); return false; } simpleGit() .clone(source.gitUrl, clonePath) .then(() => { const fileToSize: TUploadFileLanguageToSize = {}; const workspaceInfo = DataWorkspaceManager.getWorkspaceInfo(workspaceId); if (workspaceInfo === undefined) { throw new Error(`could not find workspaceInfo`); } searchWorkspaceFiles(clonePath, { fileToSize: fileToSize }), DataWorkspaceManager.setWorkspaceInfo(workspaceId, { ...workspaceInfo, workspaceLanguage: fileToSize, } as TWorkspaceUpdateData); log.info(`git clone complete gitUrl: ${source.gitUrl}`); }) .catch((e) => { log.error(e.stack); }); } catch (e: any) { log.error(e.stack); return false; } return true; } /** * * @param workspaceId workspace ID to be downloaded from zip file * @param source object that contains File ID and isExtract * @description move zip file to workspace and if isExtract is true, unzip zip file to workspace * @returns true if succeed to move zip file or unzip zip file, false if not */ static createworkspaceFromFile( workspaceId: string, source: { upload: { uploadFileId: string; isExtract?: boolean; }; } ) { const uploadFileId = source.upload.uploadFileId; const isExtract = source.upload.isExtract; const fileName = DataUploadManager.UploadFileManager[uploadFileId].originalname; const newPath = DataWorkspaceManager.getWorkspaceWorkPath(workspaceId); if (!fs.existsSync(newPath)) { fs.mkdirSync(newPath, { recursive: true }); } return handle(`${UploadDirectoryPath}/${uploadFileId}`, `${newPath}/${fileName}`, { isExtract: isExtract, extractPath: isExtract ? newPath : undefined, extractCallback: (err) => { if (err) { log.error(err.stack); } else { fs.unlinkSync(`${newPath}/${fileName}`); const fileToSize: TUploadFileLanguageToSize = {}; searchWorkspaceFiles(newPath, { fileToSize: fileToSize }); DataWorkspaceManager.setWorkspaceInfo(workspaceId, { ...DataWorkspaceManager.getWorkspaceInfo(workspaceId), workspaceLanguage: fileToSize, } as TWorkspaceUpdateData); DataUploadManager.deleteUploadFileInfo(uploadFileId); } }, }) ? true : false; } /** * * @param workspaceId workspace ID * @param source object that contains type * @description create empty workspace * @returns true if function has no error, false if not */ static createEmptyworkspace(workspaceId: string, source: any) { if (source.type !== "nothing") { return false; } if (!fs.existsSync(DataWorkspaceManager.getWorkspaceWorkPath(workspaceId))) { fs.mkdirSync(DataWorkspaceManager.getWorkspaceWorkPath(workspaceId), { recursive: true, }); } return true; } /** * * @param userId : user ID from session * @param workspaceName : workspace name that you want to get infomation * @description : get workspaceInfo or workspaceInfoList * @returns workspaceInfo if you input workspaceName, or workspaceList * */ static get(userId: string, workspaceId?: string) { DataUploadManager.loadUploadFileInfo(); if (!fs.existsSync(this.getWorkspaceDefaultPath())) { fs.mkdirSync(this.getWorkspaceDefaultPath(), { recursive: true }); } return fs .readdirSync(this.getWorkspaceDefaultPath()) .filter((workspaceUUID) => { return this.canEditWorkspace(userId, workspaceUUID, true) && (workspaceId === undefined || workspaceId === workspaceUUID); }) .map((workspaceUUID) => { return { ...(this.getWorkspaceInfo(workspaceUUID) as TWorkspaceData), ...DataDockerManager.getDockerInfo(workspaceUUID) }; }); } /** * * @param userId : user ID from session * @param { name, description, thumbnail, participants } : infomation that create workspace * @param dockerInfo : information that create container * @param source : Information on how to create a workspace. * @description create workspace with container * @returns {TReturnData } : code based on the result and message if function has error */ static create( userId: string, { name, description, thumbnail, participants }: TWorkspaceCreateData, dockerInfo: TDockerCreateData, source: { type: "gitUrl" | "upload" | "nothing"; gitUrl?: string; upload?: { uploadFileId: string; isExtract?: boolean; }; } ): TReturnWorkspaceData { if (!fs.existsSync(this.getWorkspaceDefaultPath())) { fs.mkdirSync(this.getWorkspaceDefaultPath(), { recursive: true }); } if (this.getWorkspaceId(userId, name) !== undefined) { return { code: ResponseCode.confilct, message: "The same workspace name already exists." }; } const func: Record<string, (workspaceId: string, source: any) => boolean> = { gitUrl: this.gitCloneFromURL, upload: this.createworkspaceFromFile, nothing: this.createEmptyworkspace, }; try { DataUploadManager.loadUploadFileInfo(); const workspaceId = uuidv4(); fs.mkdirSync(this.getWorkspaceDataPath(workspaceId), { recursive: true }); if (thumbnail !== undefined) { if (!fs.existsSync(UploadDirectoryPath)) { fs.mkdirSync(UploadDirectoryPath, { recursive: true, }); } const extension = DataUploadManager.UploadFileManager[thumbnail].originalname.split(".").pop(); if (!handle(`${UploadDirectoryPath}/${thumbnail}`, `${UploadDirectoryPath}/${thumbnail}.${extension}`)) { return { code: ResponseCode.internalError, message: "Failed to handle thumbnail image" }; } thumbnail = `${thumbnail}.${extension}`; DataUploadManager.deleteUploadFileInfo(thumbnail); } const workspaceParticipants = participants ? [...participants, userId] : [userId]; if ( !this.setWorkspaceInfo(workspaceId, { workspaceId: workspaceId, name: name, description: description, thumbnail: thumbnail, creator: userId, participants: workspaceParticipants, creation: getTime(getTime(), "YY-MM-DD"), }) ) { return { code: ResponseCode.internalError, message: `Failed to create workspace` }; } if (func?.[source.type](workspaceId, source) !== true) { return { code: ResponseCode.internalError, message: `Failed to create workspace with ${source.type}` }; } DataDockerManager.create(userId, dockerInfo, { workspaceId, workspaceName: name, workspaceParticipants }); return { code: ResponseCode.ok, workspaceId }; } catch (err: any) { log.error(err.stack); return { code: ResponseCode.internalError, message: "Error occured" }; } } /** * * @param userId user ID to find workspace * @param workspaceId workspace ID to find workspace * @param participantIncluded check true if you want to allow authority to participant, check false if not * @param workspaceInfo workspace infomation to update old workspace infomation * @param dockerInfo container infomation to update old container infomation * @description update workspace infomation * @returns {TReturnData } : code based on the result and message if function has error */ static update( userId: string, workspaceId: string, participantIncluded: boolean, workspaceInfo: TWorkspaceUpdateData, dockerInfo: TDockerUpdateData ): TReturnData { DataUploadManager.loadUploadFileInfo(); const workspaceData = this.getWorkspaceInfo(workspaceId); if (workspaceData === undefined) { return { code: ResponseCode.invaildRequest, message: "Could not find workspace" }; } if (!this.canEditWorkspace(userId, workspaceId, participantIncluded)) { return { code: ResponseCode.forbidden, message: "No authority to modify this workspace" }; } try { if ( workspaceInfo.thumbnail !== undefined && path.parse(workspaceData.thumbnail as string).name !== workspaceInfo.thumbnail && workspaceData.thumbnail !== workspaceInfo.thumbnail ) { const extension = DataUploadManager.UploadFileManager[workspaceInfo.thumbnail].originalname.split(".").pop(); if ( !handle( `${UploadDirectoryPath}/${workspaceInfo.thumbnail}`, `${UploadDirectoryPath}/${workspaceInfo.thumbnail}.${extension}` ) ) { return { code: ResponseCode.internalError, message: "Failed to handle thumbnail image" }; } if (workspaceData.thumbnail !== undefined) { fs.unlinkSync(`${UploadDirectoryPath}/${workspaceData.thumbnail}`); } workspaceData.thumbnail = `${workspaceInfo.thumbnail}.${extension}`; DataUploadManager.deleteUploadFileInfo(workspaceInfo.thumbnail); } if ( !this.setWorkspaceInfo(workspaceId, { workspaceId, name: workspaceInfo.name ?? workspaceData.name, description: workspaceInfo.description ?? workspaceData.description, thumbnail: workspaceInfo.thumbnail ?? workspaceData.thumbnail, language: workspaceData.language, creator: workspaceData.creator, participants: workspaceInfo.participants ?? workspaceData.participants, }) ) { return { code: ResponseCode.internalError, message: "Could not update workspace infomation" }; } DataDockerManager.update(userId, workspaceId, dockerInfo); } catch (e: any) { log.error(e.stack); return { code: ResponseCode.internalError, message: "Error occured" }; } return { code: ResponseCode.ok }; } /** * * @param userId user ID to delete workspace * @param workspaceId workspace ID to delete workspace * @description delete workspace * @returns {TReturnData } : code based on the result and message if function has error */ static delete(userId: string, workspaceId: string): TReturnData { if (!this.canEditWorkspace(userId, workspaceId, false)) { return { code: ResponseCode.forbidden, message: "No authority to delete this workspace" }; } if (!DataDockerManager.delete(userId, workspaceId)) { return { code: ResponseCode.internalError, message: "Error occured from container" }; } if (!this.isExists(workspaceId, this.getWorkspaceWorkPath) || !removeData(this.getWorkspaceWorkPath(workspaceId))) { return { code: ResponseCode.internalError, message: "Failed to remove workspace data" }; } return { code: ResponseCode.ok }; } /** * * @param userId user ID to export workspace * @param workspaceId workspace ID to export workspace * @returns true if you succeed to export workspace, false if not */ static export( userId: string, { dockerOption, workspaceOption }: { dockerOption?: TDockerExportOption; workspaceOption: TWorkspaceExportOption } ) { if (!isExists(ExportDirectoryPath)) { fs.mkdirSync(ExportDirectoryPath, { recursive: true }); } if (dockerOption !== undefined) { if (!DataDockerManager.export(userId, dockerOption)) { return { code: ResponseCode.internalError, message: "Error occurred while exporting workspace" }; } return { code: ResponseCode.ok, message: "Export container request confirmed" }; } const workspaceId = workspaceOption.workspaceId; if (workspaceId === undefined) { return false; } const extensionList = ["zip", "tar", "7z", "tar.gz", "egg"]; const extension = extensionList.includes(workspaceOption.extension) ? workspaceOption.extension : os.platform() === "win32" ? "zip" : "tar"; try { const downloadPath = `${ExportDirectoryPath}/${workspaceId}.${extension}`; if (isExists(downloadPath)) { fs.unlinkSync(downloadPath); } zip(this.getWorkspaceWorkPath(workspaceId), downloadPath).then(() => { DataAlarmManager.create(userId, { type: "workspace", location: `/api/download/${workspaceId}.${extension}`, content: `Export workspace complete`, checkAlarm: { [userId]: true }, }); }); } catch (e: any) { log.error(e.stack); DataAlarmManager.create(userId, { type: "workspace", location: ``, content: `Failed to export workspace`, checkAlarm: { [userId]: true }, }); return { code: ResponseCode.internalError, message: "Error occurred while exporting workspace" }; } return { code: ResponseCode.ok, message: "Export workspace request confirmed" }; } } type TDockerExportOption = { containerId: string; imageName: string; tagName: string; }; type TWorkspaceExportOption = { workspaceId: string; extension: string; };
the_stack
import { isIE } from '@ui5/webcomponents-react-base/dist/Device'; import { useResponsiveContentPadding, useSyncRef } from '@ui5/webcomponents-react-base/dist/hooks'; import { ThemingParameters } from '@ui5/webcomponents-react-base/dist/ThemingParameters'; import { debounce, enrichEventWithDetails } from '@ui5/webcomponents-react-base/dist/Utils'; import { FlexBox } from '@ui5/webcomponents-react/dist/FlexBox'; import { GlobalStyleClasses } from '@ui5/webcomponents-react/dist/GlobalStyleClasses'; import { PageBackgroundDesign } from '@ui5/webcomponents-react/dist/PageBackgroundDesign'; import { CommonProps } from '@ui5/webcomponents-react/interfaces/CommonProps'; import clsx from 'clsx'; import React, { cloneElement, forwardRef, ReactElement, ReactNode, Ref, useEffect, useRef, useState } from 'react'; import { createUseStyles } from 'react-jss'; import { useObserveHeights } from '../../internal/useObserveHeights'; import { DynamicPageAnchorBar } from '../DynamicPageAnchorBar'; import { styles } from './DynamicPage.jss'; export interface DynamicPagePropTypes extends Omit<CommonProps, 'title'> { /** * Determines the background color of DynamicPage. */ backgroundDesign?: PageBackgroundDesign | keyof typeof PageBackgroundDesign; /** * Determines whether the `headerContent` is shown. */ alwaysShowContentHeader?: boolean; /** * Determines whether the expand/collapse `headerContent` button is shown. */ showHideHeaderButton?: boolean; /** * Determines whether the pin button is shown. */ headerContentPinnable?: boolean; /** * Defines the the upper, always static, title section of the `DynamicPage`. * * __Note:__ Although this prop accepts all HTML Elements, it is strongly recommended that you only use `DynamicPageTitle` in order to preserve the intended design. */ headerTitle?: ReactElement; /** * Defines the dynamic header section of the `DynamicPage`. * * __Note:__ Although this prop accepts all HTML Elements, it is strongly recommended that you only use `DynamicPageHeader` in order to preserve the intended design. */ headerContent?: ReactElement; /** * React element which defines the footer content. * * __Note:__ Although this prop accepts all HTML Elements, it is strongly recommended that you only use `Bar` with `design={BarDesign.FloatingFooter}` in order to preserve the intended design. */ footer?: ReactElement; /** * React element or node array which defines the content. */ children?: ReactNode | ReactNode[]; /** * Defines internally used a11y properties. */ a11yConfig?: { dynamicPageAnchorBar?: { role?: string; }; }; } /** * Defines the current state of the component. */ enum HEADER_STATES { AUTO = 'AUTO', VISIBLE_PINNED = 'VISIBLE_PINNED', HIDDEN_PINNED = 'HIDDEN_PINNED', VISIBLE = 'VISIBLE', HIDDEN = 'HIDDEN' } const useStyles = createUseStyles(styles, { name: 'DynamicPage' }); /** * The dynamic page is a generic layout control designed to support various floorplans and use cases. * The content of both the header and the page can differ from floorplan to floorplan. * * The header of the dynamic page is collapsible, which helps users to focus on the actual page content, but still ensures that important header information * and actions are readily available. */ const DynamicPage = forwardRef((props: DynamicPagePropTypes, ref: Ref<HTMLDivElement>) => { const { headerTitle, headerContent, tooltip, style, backgroundDesign, showHideHeaderButton, headerContentPinnable, alwaysShowContentHeader, children, className, footer, a11yConfig, ...rest } = props; const { onScroll: _1, ...propsWithoutOmitted } = rest; const anchorBarRef = useRef<HTMLDivElement>(); const [componentRef, dynamicPageRef] = useSyncRef<HTMLDivElement>(ref); const contentRef = useRef<HTMLDivElement>(); // @ts-ignore const [componentRefTopHeader, topHeaderRef] = useSyncRef(headerTitle?.ref); // @ts-ignore const [componentRefHeaderContent, headerContentRef] = useSyncRef(headerContent?.ref); const [headerState, setHeaderState] = useState<HEADER_STATES>( alwaysShowContentHeader ? HEADER_STATES.VISIBLE_PINNED : isIE() ? HEADER_STATES.VISIBLE : HEADER_STATES.AUTO ); const classes = useStyles(); const dynamicPageClasses = clsx( classes.dynamicPage, GlobalStyleClasses.sapScrollBar, classes[`background${backgroundDesign}`], className, [HEADER_STATES.HIDDEN, HEADER_STATES.HIDDEN_PINNED].includes(headerState) && classes.headerCollapsed ); // observe heights of header parts const { topHeaderHeight, headerContentHeight } = useObserveHeights( dynamicPageRef, topHeaderRef, headerContentRef, anchorBarRef, { noHeader: false } ); const [isOverflowing, setIsOverflowing] = useState(false); useEffect(() => { const observer = new IntersectionObserver( debounce(([element]) => { setIsOverflowing(!element.isIntersecting); }, 250), { root: dynamicPageRef.current, threshold: 0.98, rootMargin: '0px 0px -60px 0px' // negative bottom margin for footer height } ); if (contentRef.current) { observer.observe(contentRef.current); } return () => { observer.disconnect(); }; }, []); useEffect(() => { const oneTimeScrollHandler = () => { if (!isIE()) { setHeaderState(HEADER_STATES.AUTO); } }; if (headerState === HEADER_STATES.VISIBLE || headerState === HEADER_STATES.HIDDEN) { dynamicPageRef.current?.addEventListener('scroll', oneTimeScrollHandler, { once: true }); } return () => { dynamicPageRef.current?.removeEventListener('scroll', oneTimeScrollHandler); }; }, [dynamicPageRef, headerState]); const onToggleHeaderContentVisibility = (e) => { const shouldHideHeader = !e.detail.visible; setHeaderState((oldState) => { if (oldState === HEADER_STATES.VISIBLE_PINNED || oldState === HEADER_STATES.HIDDEN_PINNED) { return shouldHideHeader ? HEADER_STATES.HIDDEN_PINNED : HEADER_STATES.VISIBLE_PINNED; } return shouldHideHeader ? HEADER_STATES.HIDDEN : HEADER_STATES.VISIBLE; }); }; const onHoverToggleButton = (e) => { // TODO background color should be sapObjectHeader_Hover_Background (same color as sapTile_Active_Background) topHeaderRef.current.style.backgroundColor = e?.type === 'mouseover' ? ThemingParameters.sapTile_Active_Background : null; }; const onToggleHeaderContent = (e) => { onToggleHeaderContentVisibility(enrichEventWithDetails(e, { visible: !headerContentHeight })); }; const handleHeaderPinnedChange = (headerWillPin) => { if (headerWillPin) { setHeaderState(HEADER_STATES.VISIBLE_PINNED); } else { setHeaderState(HEADER_STATES.VISIBLE); } }; useEffect(() => { if (alwaysShowContentHeader) { setHeaderState(HEADER_STATES.VISIBLE_PINNED); } else if (!isIE()) { setHeaderState(HEADER_STATES.AUTO); } }, [alwaysShowContentHeader, setHeaderState]); const anchorBarClasses = clsx(classes.anchorBar, isIE() && classes.iEClass); const responsivePaddingClass = useResponsiveContentPadding(dynamicPageRef.current); const onDynamicPageScroll = (e) => { if (typeof props?.onScroll === 'function') { props.onScroll(e); } if (headerState === HEADER_STATES.HIDDEN_PINNED && e.target.scrollTop === 0) { setHeaderState(HEADER_STATES.VISIBLE_PINNED); } }; return ( <div ref={componentRef} title={tooltip} className={dynamicPageClasses} style={style} onScroll={onDynamicPageScroll} {...propsWithoutOmitted} > {headerTitle && cloneElement(headerTitle, { 'data-not-clickable': (alwaysShowContentHeader && !headerContentPinnable) || !headerContent || (!showHideHeaderButton && !headerContentPinnable), ref: componentRefTopHeader, className: headerTitle?.props?.className ? `${responsivePaddingClass} ${headerTitle.props.className}` : responsivePaddingClass, onToggleHeaderContentVisibility: onToggleHeaderContent })} {headerContent && cloneElement(headerContent, { ref: componentRefHeaderContent, className: headerContent.props.className ? `${responsivePaddingClass} ${headerContent.props.className}` : responsivePaddingClass, headerPinned: headerState === HEADER_STATES.VISIBLE_PINNED || headerState === HEADER_STATES.VISIBLE, topHeaderHeight })} <FlexBox data-component-name="DynamicPageAnchorBar" className={anchorBarClasses} ref={anchorBarRef} style={{ top: headerState === HEADER_STATES.VISIBLE_PINNED || headerState === HEADER_STATES.VISIBLE ? (headerContentRef?.current?.offsetHeight ?? 0) + topHeaderHeight : topHeaderHeight }} > <DynamicPageAnchorBar headerContentPinnable={headerContentPinnable} showHideHeaderButton={showHideHeaderButton} headerContentVisible={!!headerContentHeight} onToggleHeaderContentVisibility={onToggleHeaderContentVisibility} setHeaderPinned={handleHeaderPinnedChange} headerPinned={headerState === HEADER_STATES.VISIBLE_PINNED || headerState === HEADER_STATES.HIDDEN_PINNED} onHoverToggleButton={onHoverToggleButton} a11yConfig={a11yConfig} /> </FlexBox> {isIE() && ( <div className={classes.iEBackgroundElement} style={{ height: `${headerContentHeight + topHeaderHeight}px`, width: `calc(100% - ${ dynamicPageRef?.current?.clientHeight < dynamicPageRef?.current?.scrollHeight ? '18px' : '0px' })` }} /> )} <div ref={contentRef} data-component-name="DynamicPageContent" className={`${classes.contentContainer} ${responsivePaddingClass}`} style={{ marginTop: isIE() ? `${headerContentHeight + topHeaderHeight + 34}px` : 0, paddingBottom: footer ? '1rem' : 0 }} > {children} </div> {footer && ( <footer className={classes.footer} style={{ position: isOverflowing ? 'sticky' : 'absolute' }} data-component-name="DynamicPageFooter" > {footer} </footer> )} </div> ); }); DynamicPage.displayName = 'DynamicPage'; DynamicPage.defaultProps = { backgroundDesign: PageBackgroundDesign.Solid, showHideHeaderButton: true, headerContentPinnable: true, alwaysShowContentHeader: false }; export { DynamicPage };
the_stack